hammer2 - Flush asynchronization, bug fixes, stabilization
[dragonfly.git] / sys / vfs / hammer2 / hammer2_vnops.c
1 /*
2  * Copyright (c) 2011-2015 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  * by Daniel Flores (GSOC 2013 - mentored by Matthew Dillon, compression)
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  * 3. Neither the name of The DragonFly Project nor the names of its
20  *    contributors may be used to endorse or promote products derived
21  *    from this software without specific, prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
27  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
29  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
31  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
32  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
33  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 /*
37  * Kernel Filesystem interface
38  *
39  * NOTE! local ipdata pointers must be reloaded on any modifying operation
40  *       to the inode as its underlying chain may have changed.
41  */
42
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/kernel.h>
46 #include <sys/fcntl.h>
47 #include <sys/buf.h>
48 #include <sys/proc.h>
49 #include <sys/namei.h>
50 #include <sys/mount.h>
51 #include <sys/vnode.h>
52 #include <sys/mountctl.h>
53 #include <sys/dirent.h>
54 #include <sys/uio.h>
55 #include <sys/objcache.h>
56 #include <sys/event.h>
57 #include <sys/file.h>
58 #include <vfs/fifofs/fifo.h>
59
60 #include "hammer2.h"
61
62 static int hammer2_read_file(hammer2_inode_t *ip, struct uio *uio,
63                                 int seqcount);
64 static int hammer2_write_file(hammer2_inode_t *ip, struct uio *uio,
65                                 int ioflag, int seqcount);
66 static void hammer2_extend_file(hammer2_inode_t *ip, hammer2_key_t nsize);
67 static void hammer2_truncate_file(hammer2_inode_t *ip, hammer2_key_t nsize);
68
69 struct objcache *cache_xops;
70
71 static __inline
72 void
73 hammer2_knote(struct vnode *vp, int flags)
74 {
75         if (flags)
76                 KNOTE(&vp->v_pollinfo.vpi_kqinfo.ki_note, flags);
77 }
78
79 /*
80  * Last reference to a vnode is going away but it is still cached.
81  */
82 static
83 int
84 hammer2_vop_inactive(struct vop_inactive_args *ap)
85 {
86         hammer2_inode_t *ip;
87         struct vnode *vp;
88
89         vp = ap->a_vp;
90         ip = VTOI(vp);
91
92         /*
93          * Degenerate case
94          */
95         if (ip == NULL) {
96                 vrecycle(vp);
97                 return (0);
98         }
99
100         /*
101          * Check for deleted inodes and recycle immediately on the last
102          * release.  Be sure to destroy any left-over buffer cache buffers
103          * so we do not waste time trying to flush them.
104          *
105          * Note that deleting the file block chains under the inode chain
106          * would just be a waste of energy, so don't do it.
107          *
108          * WARNING: nvtruncbuf() can only be safely called without the inode
109          *          lock held due to the way our write thread works.
110          */
111         if (ip->flags & HAMMER2_INODE_ISUNLINKED) {
112                 hammer2_key_t lbase;
113                 int nblksize;
114
115                 /*
116                  * Detect updates to the embedded data which may be
117                  * synchronized by the strategy code.  Simply mark the
118                  * inode modified so it gets picked up by our normal flush.
119                  */
120                 nblksize = hammer2_calc_logical(ip, 0, &lbase, NULL);
121                 nvtruncbuf(vp, 0, nblksize, 0, 0);
122                 vrecycle(vp);
123         }
124         return (0);
125 }
126
127 /*
128  * Reclaim a vnode so that it can be reused; after the inode is
129  * disassociated, the filesystem must manage it alone.
130  */
131 static
132 int
133 hammer2_vop_reclaim(struct vop_reclaim_args *ap)
134 {
135         hammer2_inode_t *ip;
136         hammer2_pfs_t *pmp;
137         struct vnode *vp;
138
139         vp = ap->a_vp;
140         ip = VTOI(vp);
141         if (ip == NULL) {
142                 return(0);
143         }
144         pmp = ip->pmp;
145
146         /*
147          * The final close of a deleted file or directory marks it for
148          * destruction.  The DELETED flag allows the flusher to shortcut
149          * any modified blocks still unflushed (that is, just ignore them).
150          *
151          * HAMMER2 usually does not try to optimize the freemap by returning
152          * deleted blocks to it as it does not usually know how many snapshots
153          * might be referencing portions of the file/dir.
154          */
155         vp->v_data = NULL;
156         ip->vp = NULL;
157
158         /*
159          * NOTE! We do not attempt to flush chains here, flushing is
160          *       really fragile and could also deadlock.
161          */
162         vclrisdirty(vp);
163
164         /*
165          * A modified inode may require chain synchronization.  This
166          * synchronization is usually handled by VOP_SYNC / VOP_FSYNC
167          * when vfsync() is called.  However, that requires a vnode.
168          *
169          * When the vnode is disassociated we must keep track of any modified
170          * inode via the sideq so that it is properly flushed.  We cannot
171          * safely synchronize the inode from inside the reclaim due to
172          * potentially deep locks held as-of when the reclaim occurs.
173          * Interactions and potential deadlocks abound.
174          */
175         if ((ip->flags & (HAMMER2_INODE_ISUNLINKED |
176                           HAMMER2_INODE_MODIFIED |
177                           HAMMER2_INODE_RESIZED)) &&
178             (ip->flags & HAMMER2_INODE_ISDELETED) == 0) {
179                 hammer2_inode_sideq_t *ipul;
180
181                 ipul = kmalloc(sizeof(*ipul), pmp->minode, M_WAITOK | M_ZERO);
182                 ipul->ip = ip;
183
184                 hammer2_spin_ex(&pmp->list_spin);
185                 if ((ip->flags & HAMMER2_INODE_ONSIDEQ) == 0) {
186                         /* ref -> sideq */
187                         atomic_set_int(&ip->flags, HAMMER2_INODE_ONSIDEQ);
188                         TAILQ_INSERT_TAIL(&pmp->sideq, ipul, entry);
189                         ++pmp->sideq_count;
190                         hammer2_spin_unex(&pmp->list_spin);
191                 } else {
192                         hammer2_spin_unex(&pmp->list_spin);
193                         kfree(ipul, pmp->minode);
194                         hammer2_inode_drop(ip);         /* vp ref */
195                 }
196                 /* retain ref from vp for ipul */
197         } else {
198                 hammer2_inode_drop(ip);                 /* vp ref */
199         }
200
201         /*
202          * XXX handle background sync when ip dirty, kernel will no longer
203          * notify us regarding this inode because there is no longer a
204          * vnode attached to it.
205          */
206
207         return (0);
208 }
209
210 /*
211  * Currently this function synchronizes the front-end inode state to the
212  * backend chain topology, then flushes the inode's chain and sub-topology
213  * to backend media.  This function does not flush the root topology down to
214  * the inode.
215  */
216 static
217 int
218 hammer2_vop_fsync(struct vop_fsync_args *ap)
219 {
220         hammer2_inode_t *ip;
221         struct vnode *vp;
222         int error1;
223         int error2;
224
225         vp = ap->a_vp;
226         ip = VTOI(vp);
227         error1 = 0;
228
229         hammer2_trans_init(ip->pmp, 0);
230
231         /*
232          * Clean out buffer cache, wait for I/O's to complete.
233          */
234         vfsync(vp, ap->a_waitfor, 1, NULL, NULL);
235         bio_track_wait(&vp->v_track_write, 0, 0);
236
237         /*
238          * Flush any inode changes
239          */
240         hammer2_inode_lock(ip, 0);
241         if (ip->flags & (HAMMER2_INODE_RESIZED|HAMMER2_INODE_MODIFIED))
242                 error1 = hammer2_inode_chain_sync(ip);
243
244         /*
245          * Flush dirty chains related to the inode.
246          *
247          * NOTE! XXX We do not currently flush to the volume root, ultimately
248          *       we will want to have a shortcut for the flushed inode stored
249          *       in the volume root for recovery purposes.
250          */
251         error2 = hammer2_inode_chain_flush(ip);
252         if (error2)
253                 error1 = error2;
254         hammer2_inode_unlock(ip);
255         hammer2_trans_done(ip->pmp);
256
257         return (error1);
258 }
259
260 static
261 int
262 hammer2_vop_access(struct vop_access_args *ap)
263 {
264         hammer2_inode_t *ip = VTOI(ap->a_vp);
265         uid_t uid;
266         gid_t gid;
267         int error;
268
269         hammer2_inode_lock(ip, HAMMER2_RESOLVE_SHARED);
270         uid = hammer2_to_unix_xid(&ip->meta.uid);
271         gid = hammer2_to_unix_xid(&ip->meta.gid);
272         error = vop_helper_access(ap, uid, gid, ip->meta.mode, ip->meta.uflags);
273         hammer2_inode_unlock(ip);
274
275         return (error);
276 }
277
278 static
279 int
280 hammer2_vop_getattr(struct vop_getattr_args *ap)
281 {
282         hammer2_pfs_t *pmp;
283         hammer2_inode_t *ip;
284         struct vnode *vp;
285         struct vattr *vap;
286         hammer2_chain_t *chain;
287         int i;
288
289         vp = ap->a_vp;
290         vap = ap->a_vap;
291
292         ip = VTOI(vp);
293         pmp = ip->pmp;
294
295         hammer2_inode_lock(ip, HAMMER2_RESOLVE_SHARED);
296
297         vap->va_fsid = pmp->mp->mnt_stat.f_fsid.val[0];
298         vap->va_fileid = ip->meta.inum;
299         vap->va_mode = ip->meta.mode;
300         vap->va_nlink = ip->meta.nlinks;
301         vap->va_uid = hammer2_to_unix_xid(&ip->meta.uid);
302         vap->va_gid = hammer2_to_unix_xid(&ip->meta.gid);
303         vap->va_rmajor = 0;
304         vap->va_rminor = 0;
305         vap->va_size = ip->meta.size;   /* protected by shared lock */
306         vap->va_blocksize = HAMMER2_PBUFSIZE;
307         vap->va_flags = ip->meta.uflags;
308         hammer2_time_to_timespec(ip->meta.ctime, &vap->va_ctime);
309         hammer2_time_to_timespec(ip->meta.mtime, &vap->va_mtime);
310         hammer2_time_to_timespec(ip->meta.mtime, &vap->va_atime);
311         vap->va_gen = 1;
312         vap->va_bytes = 0;
313         if (ip->meta.type == HAMMER2_OBJTYPE_DIRECTORY) {
314                 /*
315                  * Can't really calculate directory use sans the files under
316                  * it, just assume one block for now.
317                  */
318                 vap->va_bytes += HAMMER2_INODE_BYTES;
319         } else {
320                 for (i = 0; i < ip->cluster.nchains; ++i) {
321                         if ((chain = ip->cluster.array[i].chain) != NULL) {
322                                 if (vap->va_bytes <
323                                     chain->bref.embed.stats.data_count) {
324                                         vap->va_bytes =
325                                             chain->bref.embed.stats.data_count;
326                                 }
327                         }
328                 }
329         }
330         vap->va_type = hammer2_get_vtype(ip->meta.type);
331         vap->va_filerev = 0;
332         vap->va_uid_uuid = ip->meta.uid;
333         vap->va_gid_uuid = ip->meta.gid;
334         vap->va_vaflags = VA_UID_UUID_VALID | VA_GID_UUID_VALID |
335                           VA_FSID_UUID_VALID;
336
337         hammer2_inode_unlock(ip);
338
339         return (0);
340 }
341
342 static
343 int
344 hammer2_vop_setattr(struct vop_setattr_args *ap)
345 {
346         hammer2_inode_t *ip;
347         struct vnode *vp;
348         struct vattr *vap;
349         int error;
350         int kflags = 0;
351         uint64_t ctime;
352
353         vp = ap->a_vp;
354         vap = ap->a_vap;
355         hammer2_update_time(&ctime);
356
357         ip = VTOI(vp);
358
359         if (ip->pmp->ronly)
360                 return (EROFS);
361         if (hammer2_vfs_enospace(ip, 0, ap->a_cred) > 1)
362                 return (ENOSPC);
363
364         hammer2_pfs_memory_wait(ip->pmp);
365         hammer2_trans_init(ip->pmp, 0);
366         hammer2_inode_lock(ip, 0);
367         error = 0;
368
369         if (vap->va_flags != VNOVAL) {
370                 uint32_t flags;
371
372                 flags = ip->meta.uflags;
373                 error = vop_helper_setattr_flags(&flags, vap->va_flags,
374                                      hammer2_to_unix_xid(&ip->meta.uid),
375                                      ap->a_cred);
376                 if (error == 0) {
377                         if (ip->meta.uflags != flags) {
378                                 hammer2_inode_modify(ip);
379                                 ip->meta.uflags = flags;
380                                 ip->meta.ctime = ctime;
381                                 kflags |= NOTE_ATTRIB;
382                         }
383                         if (ip->meta.uflags & (IMMUTABLE | APPEND)) {
384                                 error = 0;
385                                 goto done;
386                         }
387                 }
388                 goto done;
389         }
390         if (ip->meta.uflags & (IMMUTABLE | APPEND)) {
391                 error = EPERM;
392                 goto done;
393         }
394         if (vap->va_uid != (uid_t)VNOVAL || vap->va_gid != (gid_t)VNOVAL) {
395                 mode_t cur_mode = ip->meta.mode;
396                 uid_t cur_uid = hammer2_to_unix_xid(&ip->meta.uid);
397                 gid_t cur_gid = hammer2_to_unix_xid(&ip->meta.gid);
398                 uuid_t uuid_uid;
399                 uuid_t uuid_gid;
400
401                 error = vop_helper_chown(ap->a_vp, vap->va_uid, vap->va_gid,
402                                          ap->a_cred,
403                                          &cur_uid, &cur_gid, &cur_mode);
404                 if (error == 0) {
405                         hammer2_guid_to_uuid(&uuid_uid, cur_uid);
406                         hammer2_guid_to_uuid(&uuid_gid, cur_gid);
407                         if (bcmp(&uuid_uid, &ip->meta.uid, sizeof(uuid_uid)) ||
408                             bcmp(&uuid_gid, &ip->meta.gid, sizeof(uuid_gid)) ||
409                             ip->meta.mode != cur_mode
410                         ) {
411                                 hammer2_inode_modify(ip);
412                                 ip->meta.uid = uuid_uid;
413                                 ip->meta.gid = uuid_gid;
414                                 ip->meta.mode = cur_mode;
415                                 ip->meta.ctime = ctime;
416                         }
417                         kflags |= NOTE_ATTRIB;
418                 }
419         }
420
421         /*
422          * Resize the file
423          */
424         if (vap->va_size != VNOVAL && ip->meta.size != vap->va_size) {
425                 switch(vp->v_type) {
426                 case VREG:
427                         if (vap->va_size == ip->meta.size)
428                                 break;
429                         if (vap->va_size < ip->meta.size) {
430                                 hammer2_mtx_ex(&ip->truncate_lock);
431                                 hammer2_truncate_file(ip, vap->va_size);
432                                 hammer2_mtx_unlock(&ip->truncate_lock);
433                                 kflags |= NOTE_WRITE;
434                         } else {
435                                 hammer2_extend_file(ip, vap->va_size);
436                                 kflags |= NOTE_WRITE | NOTE_EXTEND;
437                         }
438                         hammer2_inode_modify(ip);
439                         ip->meta.mtime = ctime;
440                         vclrflags(vp, VLASTWRITETS);
441                         break;
442                 default:
443                         error = EINVAL;
444                         goto done;
445                 }
446         }
447 #if 0
448         /* atime not supported */
449         if (vap->va_atime.tv_sec != VNOVAL) {
450                 hammer2_inode_modify(ip);
451                 ip->meta.atime = hammer2_timespec_to_time(&vap->va_atime);
452                 kflags |= NOTE_ATTRIB;
453         }
454 #endif
455         if (vap->va_mode != (mode_t)VNOVAL) {
456                 mode_t cur_mode = ip->meta.mode;
457                 uid_t cur_uid = hammer2_to_unix_xid(&ip->meta.uid);
458                 gid_t cur_gid = hammer2_to_unix_xid(&ip->meta.gid);
459
460                 error = vop_helper_chmod(ap->a_vp, vap->va_mode, ap->a_cred,
461                                          cur_uid, cur_gid, &cur_mode);
462                 if (error == 0 && ip->meta.mode != cur_mode) {
463                         hammer2_inode_modify(ip);
464                         ip->meta.mode = cur_mode;
465                         ip->meta.ctime = ctime;
466                         kflags |= NOTE_ATTRIB;
467                 }
468         }
469
470         if (vap->va_mtime.tv_sec != VNOVAL) {
471                 hammer2_inode_modify(ip);
472                 ip->meta.mtime = hammer2_timespec_to_time(&vap->va_mtime);
473                 kflags |= NOTE_ATTRIB;
474                 vclrflags(vp, VLASTWRITETS);
475         }
476
477 done:
478         /*
479          * If a truncation occurred we must call chain_sync() now in order
480          * to trim the related data chains, otherwise a later expansion can
481          * cause havoc.
482          *
483          * If an extend occured that changed the DIRECTDATA state, we must
484          * call inode_fsync now in order to prepare the inode's indirect
485          * block table.
486          *
487          * WARNING! This means we are making an adjustment to the inode's
488          * chain outside of sync/fsync, and not just to inode->meta, which
489          * may result in some consistency issues if a crash were to occur
490          * at just the wrong time.
491          */
492         if (ip->flags & HAMMER2_INODE_RESIZED)
493                 hammer2_inode_chain_sync(ip);
494
495         /*
496          * Cleanup.
497          */
498         hammer2_inode_unlock(ip);
499         hammer2_trans_done(ip->pmp);
500         hammer2_knote(ip->vp, kflags);
501
502         return (error);
503 }
504
505 static
506 int
507 hammer2_vop_readdir(struct vop_readdir_args *ap)
508 {
509         hammer2_xop_readdir_t *xop;
510         hammer2_blockref_t bref;
511         hammer2_inode_t *ip;
512         hammer2_tid_t inum;
513         hammer2_key_t lkey;
514         struct uio *uio;
515         off_t *cookies;
516         off_t saveoff;
517         int cookie_index;
518         int ncookies;
519         int error;
520         int eofflag;
521         int r;
522
523         ip = VTOI(ap->a_vp);
524         uio = ap->a_uio;
525         saveoff = uio->uio_offset;
526         eofflag = 0;
527         error = 0;
528
529         /*
530          * Setup cookies directory entry cookies if requested
531          */
532         if (ap->a_ncookies) {
533                 ncookies = uio->uio_resid / 16 + 1;
534                 if (ncookies > 1024)
535                         ncookies = 1024;
536                 cookies = kmalloc(ncookies * sizeof(off_t), M_TEMP, M_WAITOK);
537         } else {
538                 ncookies = -1;
539                 cookies = NULL;
540         }
541         cookie_index = 0;
542
543         hammer2_inode_lock(ip, HAMMER2_RESOLVE_SHARED);
544
545         /*
546          * Handle artificial entries.  To ensure that only positive 64 bit
547          * quantities are returned to userland we always strip off bit 63.
548          * The hash code is designed such that codes 0x0000-0x7FFF are not
549          * used, allowing us to use these codes for articial entries.
550          *
551          * Entry 0 is used for '.' and entry 1 is used for '..'.  Do not
552          * allow '..' to cross the mount point into (e.g.) the super-root.
553          */
554         if (saveoff == 0) {
555                 inum = ip->meta.inum & HAMMER2_DIRHASH_USERMSK;
556                 r = vop_write_dirent(&error, uio, inum, DT_DIR, 1, ".");
557                 if (r)
558                         goto done;
559                 if (cookies)
560                         cookies[cookie_index] = saveoff;
561                 ++saveoff;
562                 ++cookie_index;
563                 if (cookie_index == ncookies)
564                         goto done;
565         }
566
567         if (saveoff == 1) {
568                 /*
569                  * Be careful with lockorder when accessing ".."
570                  *
571                  * (ip is the current dir. xip is the parent dir).
572                  */
573                 inum = ip->meta.inum & HAMMER2_DIRHASH_USERMSK;
574                 if (ip != ip->pmp->iroot)
575                         inum = ip->meta.iparent & HAMMER2_DIRHASH_USERMSK;
576                 r = vop_write_dirent(&error, uio, inum, DT_DIR, 2, "..");
577                 if (r)
578                         goto done;
579                 if (cookies)
580                         cookies[cookie_index] = saveoff;
581                 ++saveoff;
582                 ++cookie_index;
583                 if (cookie_index == ncookies)
584                         goto done;
585         }
586
587         lkey = saveoff | HAMMER2_DIRHASH_VISIBLE;
588         if (hammer2_debug & 0x0020)
589                 kprintf("readdir: lkey %016jx\n", lkey);
590         if (error)
591                 goto done;
592
593         /*
594          * Use XOP for cluster scan.
595          *
596          * parent is the inode cluster, already locked for us.  Don't
597          * double lock shared locks as this will screw up upgrades.
598          */
599         xop = hammer2_xop_alloc(ip, 0);
600         xop->lkey = lkey;
601         hammer2_xop_start(&xop->head, hammer2_xop_readdir);
602
603         for (;;) {
604                 const hammer2_inode_data_t *ripdata;
605                 const char *dname;
606                 int dtype;
607
608                 error = hammer2_xop_collect(&xop->head, 0);
609                 error = hammer2_error_to_errno(error);
610                 if (error) {
611                         break;
612                 }
613                 if (cookie_index == ncookies)
614                         break;
615                 if (hammer2_debug & 0x0020)
616                 kprintf("cluster chain %p %p\n",
617                         xop->head.cluster.focus,
618                         (xop->head.cluster.focus ?
619                          xop->head.cluster.focus->data : (void *)-1));
620                 hammer2_cluster_bref(&xop->head.cluster, &bref);
621
622                 if (bref.type == HAMMER2_BREF_TYPE_INODE) {
623                         ripdata =
624                             &hammer2_cluster_rdata(&xop->head.cluster)->ipdata;
625                         dtype = hammer2_get_dtype(ripdata->meta.type);
626                         saveoff = bref.key & HAMMER2_DIRHASH_USERMSK;
627                         r = vop_write_dirent(&error, uio,
628                                              ripdata->meta.inum &
629                                               HAMMER2_DIRHASH_USERMSK,
630                                              dtype,
631                                              ripdata->meta.name_len,
632                                              ripdata->filename);
633                         if (r)
634                                 break;
635                         if (cookies)
636                                 cookies[cookie_index] = saveoff;
637                         ++cookie_index;
638                 } else if (bref.type == HAMMER2_BREF_TYPE_DIRENT) {
639                         dtype = hammer2_get_dtype(bref.embed.dirent.type);
640                         saveoff = bref.key & HAMMER2_DIRHASH_USERMSK;
641                         if (bref.embed.dirent.namlen <=
642                             sizeof(bref.check.buf)) {
643                                 dname = bref.check.buf;
644                         } else {
645                                 dname =
646                                  hammer2_cluster_rdata(&xop->head.cluster)->buf;
647                         }
648                         r = vop_write_dirent(&error, uio,
649                                              bref.embed.dirent.inum,
650                                              dtype,
651                                              bref.embed.dirent.namlen,
652                                              dname);
653                         if (r)
654                                 break;
655                         if (cookies)
656                                 cookies[cookie_index] = saveoff;
657                         ++cookie_index;
658                 } else {
659                         /* XXX chain error */
660                         kprintf("bad chain type readdir %d\n", bref.type);
661                 }
662         }
663         hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
664         if (error == ENOENT) {
665                 error = 0;
666                 eofflag = 1;
667                 saveoff = (hammer2_key_t)-1;
668         } else {
669                 saveoff = bref.key & HAMMER2_DIRHASH_USERMSK;
670         }
671 done:
672         hammer2_inode_unlock(ip);
673         if (ap->a_eofflag)
674                 *ap->a_eofflag = eofflag;
675         if (hammer2_debug & 0x0020)
676                 kprintf("readdir: done at %016jx\n", saveoff);
677         uio->uio_offset = saveoff & ~HAMMER2_DIRHASH_VISIBLE;
678         if (error && cookie_index == 0) {
679                 if (cookies) {
680                         kfree(cookies, M_TEMP);
681                         *ap->a_ncookies = 0;
682                         *ap->a_cookies = NULL;
683                 }
684         } else {
685                 if (cookies) {
686                         *ap->a_ncookies = cookie_index;
687                         *ap->a_cookies = cookies;
688                 }
689         }
690         return (error);
691 }
692
693 /*
694  * hammer2_vop_readlink { vp, uio, cred }
695  */
696 static
697 int
698 hammer2_vop_readlink(struct vop_readlink_args *ap)
699 {
700         struct vnode *vp;
701         hammer2_inode_t *ip;
702         int error;
703
704         vp = ap->a_vp;
705         if (vp->v_type != VLNK)
706                 return (EINVAL);
707         ip = VTOI(vp);
708
709         error = hammer2_read_file(ip, ap->a_uio, 0);
710         return (error);
711 }
712
713 static
714 int
715 hammer2_vop_read(struct vop_read_args *ap)
716 {
717         struct vnode *vp;
718         hammer2_inode_t *ip;
719         struct uio *uio;
720         int error;
721         int seqcount;
722         int bigread;
723
724         /*
725          * Read operations supported on this vnode?
726          */
727         vp = ap->a_vp;
728         if (vp->v_type != VREG)
729                 return (EINVAL);
730
731         /*
732          * Misc
733          */
734         ip = VTOI(vp);
735         uio = ap->a_uio;
736         error = 0;
737
738         seqcount = ap->a_ioflag >> 16;
739         bigread = (uio->uio_resid > 100 * 1024 * 1024);
740
741         error = hammer2_read_file(ip, uio, seqcount);
742         return (error);
743 }
744
745 static
746 int
747 hammer2_vop_write(struct vop_write_args *ap)
748 {
749         hammer2_inode_t *ip;
750         thread_t td;
751         struct vnode *vp;
752         struct uio *uio;
753         int error;
754         int seqcount;
755         int ioflag;
756
757         /*
758          * Read operations supported on this vnode?
759          */
760         vp = ap->a_vp;
761         if (vp->v_type != VREG)
762                 return (EINVAL);
763
764         /*
765          * Misc
766          */
767         ip = VTOI(vp);
768         ioflag = ap->a_ioflag;
769         uio = ap->a_uio;
770         error = 0;
771         if (ip->pmp->ronly)
772                 return (EROFS);
773         switch (hammer2_vfs_enospace(ip, uio->uio_resid, ap->a_cred)) {
774         case 2:
775                 return (ENOSPC);
776         case 1:
777                 ioflag |= IO_DIRECT;    /* semi-synchronous */
778                 /* fall through */
779         default:
780                 break;
781         }
782
783         seqcount = ioflag >> 16;
784
785         /*
786          * Check resource limit
787          */
788         if (uio->uio_resid > 0 && (td = uio->uio_td) != NULL && td->td_proc &&
789             uio->uio_offset + uio->uio_resid >
790              td->td_proc->p_rlimit[RLIMIT_FSIZE].rlim_cur) {
791                 lwpsignal(td->td_proc, td->td_lwp, SIGXFSZ);
792                 return (EFBIG);
793         }
794
795         /*
796          * The transaction interlocks against flush initiations
797          * (note: but will run concurrently with the actual flush).
798          *
799          * To avoid deadlocking against the VM system, we must flag any
800          * transaction related to the buffer cache or other direct
801          * VM page manipulation.
802          */
803         if (uio->uio_segflg == UIO_NOCOPY)
804                 hammer2_trans_init(ip->pmp, HAMMER2_TRANS_BUFCACHE);
805         else
806                 hammer2_trans_init(ip->pmp, 0);
807         error = hammer2_write_file(ip, uio, ioflag, seqcount);
808         hammer2_trans_done(ip->pmp);
809
810         return (error);
811 }
812
813 /*
814  * Perform read operations on a file or symlink given an UNLOCKED
815  * inode and uio.
816  *
817  * The passed ip is not locked.
818  */
819 static
820 int
821 hammer2_read_file(hammer2_inode_t *ip, struct uio *uio, int seqcount)
822 {
823         hammer2_off_t size;
824         struct buf *bp;
825         int error;
826
827         error = 0;
828
829         /*
830          * UIO read loop.
831          *
832          * WARNING! Assumes that the kernel interlocks size changes at the
833          *          vnode level.
834          */
835         hammer2_mtx_sh(&ip->lock);
836         hammer2_mtx_sh(&ip->truncate_lock);
837         size = ip->meta.size;
838         hammer2_mtx_unlock(&ip->lock);
839
840         while (uio->uio_resid > 0 && uio->uio_offset < size) {
841                 hammer2_key_t lbase;
842                 hammer2_key_t leof;
843                 int lblksize;
844                 int loff;
845                 int n;
846
847                 lblksize = hammer2_calc_logical(ip, uio->uio_offset,
848                                                 &lbase, &leof);
849
850 #if 1
851                 bp = NULL;
852                 error = cluster_readx(ip->vp, leof, lbase, lblksize,
853                                       B_NOTMETA | B_KVABIO,
854                                       uio->uio_resid,
855                                       seqcount * MAXBSIZE,
856                                       &bp);
857 #else
858                 if (uio->uio_segflg == UIO_NOCOPY) {
859                         bp = getblk(ip->vp, lbase, lblksize,
860                                     GETBLK_BHEAVY | GETBLK_KVABIO, 0);
861                         if (bp->b_flags & B_CACHE) {
862                                 int i;
863                                 int j = 0;
864                                 if (bp->b_xio.xio_npages != 16)
865                                         kprintf("NPAGES BAD\n");
866                                 for (i = 0; i < bp->b_xio.xio_npages; ++i) {
867                                         vm_page_t m;
868                                         m = bp->b_xio.xio_pages[i];
869                                         if (m == NULL || m->valid == 0) {
870                                                 kprintf("bp %016jx %016jx pg %d inv",
871                                                         lbase, leof, i);
872                                                 if (m)
873                                                         kprintf("m->object %p/%p", m->object, ip->vp->v_object);
874                                                 kprintf("\n");
875                                                 j = 1;
876                                         }
877                                 }
878                                 if (j)
879                                         kprintf("b_flags %08x, b_error %d\n", bp->b_flags, bp->b_error);
880                         }
881                         bqrelse(bp);
882                 }
883                 error = bread_kvabio(ip->vp, lbase, lblksize, &bp);
884 #endif
885                 if (error) {
886                         brelse(bp);
887                         break;
888                 }
889                 bkvasync(bp);
890                 loff = (int)(uio->uio_offset - lbase);
891                 n = lblksize - loff;
892                 if (n > uio->uio_resid)
893                         n = uio->uio_resid;
894                 if (n > size - uio->uio_offset)
895                         n = (int)(size - uio->uio_offset);
896                 bp->b_flags |= B_AGE;
897                 uiomovebp(bp, (char *)bp->b_data + loff, n, uio);
898                 bqrelse(bp);
899         }
900         hammer2_mtx_unlock(&ip->truncate_lock);
901
902         return (error);
903 }
904
905 /*
906  * Write to the file represented by the inode via the logical buffer cache.
907  * The inode may represent a regular file or a symlink.
908  *
909  * The inode must not be locked.
910  */
911 static
912 int
913 hammer2_write_file(hammer2_inode_t *ip, struct uio *uio,
914                    int ioflag, int seqcount)
915 {
916         hammer2_key_t old_eof;
917         hammer2_key_t new_eof;
918         struct buf *bp;
919         int kflags;
920         int error;
921         int modified;
922
923         /*
924          * Setup if append
925          *
926          * WARNING! Assumes that the kernel interlocks size changes at the
927          *          vnode level.
928          */
929         hammer2_mtx_ex(&ip->lock);
930         hammer2_mtx_sh(&ip->truncate_lock);
931         if (ioflag & IO_APPEND)
932                 uio->uio_offset = ip->meta.size;
933         old_eof = ip->meta.size;
934
935         /*
936          * Extend the file if necessary.  If the write fails at some point
937          * we will truncate it back down to cover as much as we were able
938          * to write.
939          *
940          * Doing this now makes it easier to calculate buffer sizes in
941          * the loop.
942          */
943         kflags = 0;
944         error = 0;
945         modified = 0;
946
947         if (uio->uio_offset + uio->uio_resid > old_eof) {
948                 new_eof = uio->uio_offset + uio->uio_resid;
949                 modified = 1;
950                 hammer2_extend_file(ip, new_eof);
951                 kflags |= NOTE_EXTEND;
952         } else {
953                 new_eof = old_eof;
954         }
955         hammer2_mtx_unlock(&ip->lock);
956
957         /*
958          * UIO write loop
959          */
960         while (uio->uio_resid > 0) {
961                 hammer2_key_t lbase;
962                 int trivial;
963                 int endofblk;
964                 int lblksize;
965                 int loff;
966                 int n;
967
968                 /*
969                  * Don't allow the buffer build to blow out the buffer
970                  * cache.
971                  */
972                 if ((ioflag & IO_RECURSE) == 0)
973                         bwillwrite(HAMMER2_PBUFSIZE);
974
975                 /*
976                  * This nominally tells us how much we can cluster and
977                  * what the logical buffer size needs to be.  Currently
978                  * we don't try to cluster the write and just handle one
979                  * block at a time.
980                  */
981                 lblksize = hammer2_calc_logical(ip, uio->uio_offset,
982                                                 &lbase, NULL);
983                 loff = (int)(uio->uio_offset - lbase);
984
985                 KKASSERT(lblksize <= 65536);
986
987                 /*
988                  * Calculate bytes to copy this transfer and whether the
989                  * copy completely covers the buffer or not.
990                  */
991                 trivial = 0;
992                 n = lblksize - loff;
993                 if (n > uio->uio_resid) {
994                         n = uio->uio_resid;
995                         if (loff == lbase && uio->uio_offset + n == new_eof)
996                                 trivial = 1;
997                         endofblk = 0;
998                 } else {
999                         if (loff == 0)
1000                                 trivial = 1;
1001                         endofblk = 1;
1002                 }
1003                 if (lbase >= new_eof)
1004                         trivial = 1;
1005
1006                 /*
1007                  * Get the buffer
1008                  */
1009                 if (uio->uio_segflg == UIO_NOCOPY) {
1010                         /*
1011                          * Issuing a write with the same data backing the
1012                          * buffer.  Instantiate the buffer to collect the
1013                          * backing vm pages, then read-in any missing bits.
1014                          *
1015                          * This case is used by vop_stdputpages().
1016                          */
1017                         bp = getblk(ip->vp, lbase, lblksize,
1018                                     GETBLK_BHEAVY | GETBLK_KVABIO, 0);
1019                         if ((bp->b_flags & B_CACHE) == 0) {
1020                                 bqrelse(bp);
1021                                 error = bread_kvabio(ip->vp, lbase,
1022                                                      lblksize, &bp);
1023                         }
1024                 } else if (trivial) {
1025                         /*
1026                          * Even though we are entirely overwriting the buffer
1027                          * we may still have to zero it out to avoid a
1028                          * mmap/write visibility issue.
1029                          */
1030                         bp = getblk(ip->vp, lbase, lblksize,
1031                                     GETBLK_BHEAVY | GETBLK_KVABIO, 0);
1032                         if ((bp->b_flags & B_CACHE) == 0)
1033                                 vfs_bio_clrbuf(bp);
1034                 } else {
1035                         /*
1036                          * Partial overwrite, read in any missing bits then
1037                          * replace the portion being written.
1038                          *
1039                          * (The strategy code will detect zero-fill physical
1040                          * blocks for this case).
1041                          */
1042                         error = bread_kvabio(ip->vp, lbase, lblksize, &bp);
1043                         if (error == 0)
1044                                 bheavy(bp);
1045                 }
1046
1047                 if (error) {
1048                         brelse(bp);
1049                         break;
1050                 }
1051
1052                 /*
1053                  * Ok, copy the data in
1054                  */
1055                 bkvasync(bp);
1056                 error = uiomovebp(bp, bp->b_data + loff, n, uio);
1057                 kflags |= NOTE_WRITE;
1058                 modified = 1;
1059                 if (error) {
1060                         brelse(bp);
1061                         break;
1062                 }
1063
1064                 /*
1065                  * WARNING: Pageout daemon will issue UIO_NOCOPY writes
1066                  *          with IO_SYNC or IO_ASYNC set.  These writes
1067                  *          must be handled as the pageout daemon expects.
1068                  *
1069                  * NOTE!    H2 relies on cluster_write() here because it
1070                  *          cannot preallocate disk blocks at the logical
1071                  *          level due to not knowing what the compression
1072                  *          size will be at this time.
1073                  *
1074                  *          We must use cluster_write() here and we depend
1075                  *          on the write-behind feature to flush buffers
1076                  *          appropriately.  If we let the buffer daemons do
1077                  *          it the block allocations will be all over the
1078                  *          map.
1079                  */
1080                 if (ioflag & IO_SYNC) {
1081                         bwrite(bp);
1082                 } else if ((ioflag & IO_DIRECT) && endofblk) {
1083                         bawrite(bp);
1084                 } else if (ioflag & IO_ASYNC) {
1085                         bawrite(bp);
1086                 } else if (ip->vp->v_mount->mnt_flag & MNT_NOCLUSTERW) {
1087                         bdwrite(bp);
1088                 } else {
1089 #if 1
1090                         bp->b_flags |= B_CLUSTEROK;
1091                         cluster_write(bp, new_eof, lblksize, seqcount);
1092 #else
1093                         bp->b_flags |= B_CLUSTEROK;
1094                         bdwrite(bp);
1095 #endif
1096                 }
1097         }
1098
1099         /*
1100          * Cleanup.  If we extended the file EOF but failed to write through
1101          * the entire write is a failure and we have to back-up.
1102          */
1103         if (error && new_eof != old_eof) {
1104                 hammer2_mtx_unlock(&ip->truncate_lock);
1105                 hammer2_mtx_ex(&ip->lock);
1106                 hammer2_mtx_ex(&ip->truncate_lock);
1107                 hammer2_truncate_file(ip, old_eof);
1108                 if (ip->flags & HAMMER2_INODE_MODIFIED)
1109                         hammer2_inode_chain_sync(ip);
1110                 hammer2_mtx_unlock(&ip->lock);
1111         } else if (modified) {
1112                 struct vnode *vp = ip->vp;
1113
1114                 hammer2_mtx_ex(&ip->lock);
1115                 hammer2_inode_modify(ip);
1116                 if (uio->uio_segflg == UIO_NOCOPY) {
1117                         if (vp->v_flag & VLASTWRITETS) {
1118                                 ip->meta.mtime =
1119                                     (unsigned long)vp->v_lastwrite_ts.tv_sec *
1120                                     1000000 +
1121                                     vp->v_lastwrite_ts.tv_nsec / 1000;
1122                         }
1123                 } else {
1124                         hammer2_update_time(&ip->meta.mtime);
1125                         vclrflags(vp, VLASTWRITETS);
1126                 }
1127
1128 #if 0
1129                 /*
1130                  * REMOVED - handled by hammer2_extend_file().  Do not issue
1131                  * a chain_sync() outside of a sync/fsync except for DIRECTDATA
1132                  * state changes.
1133                  *
1134                  * Under normal conditions we only issue a chain_sync if
1135                  * the inode's DIRECTDATA state changed.
1136                  */
1137                 if (ip->flags & HAMMER2_INODE_RESIZED)
1138                         hammer2_inode_chain_sync(ip);
1139 #endif
1140                 hammer2_mtx_unlock(&ip->lock);
1141                 hammer2_knote(ip->vp, kflags);
1142         }
1143         hammer2_trans_assert_strategy(ip->pmp);
1144         hammer2_mtx_unlock(&ip->truncate_lock);
1145
1146         return error;
1147 }
1148
1149 /*
1150  * Truncate the size of a file.  The inode must not be locked.
1151  *
1152  * We must unconditionally set HAMMER2_INODE_RESIZED to properly
1153  * ensure that any on-media data beyond the new file EOF has been destroyed.
1154  *
1155  * WARNING: nvtruncbuf() can only be safely called without the inode lock
1156  *          held due to the way our write thread works.  If the truncation
1157  *          occurs in the middle of a buffer, nvtruncbuf() is responsible
1158  *          for dirtying that buffer and zeroing out trailing bytes.
1159  *
1160  * WARNING! Assumes that the kernel interlocks size changes at the
1161  *          vnode level.
1162  *
1163  * WARNING! Caller assumes responsibility for removing dead blocks
1164  *          if INODE_RESIZED is set.
1165  */
1166 static
1167 void
1168 hammer2_truncate_file(hammer2_inode_t *ip, hammer2_key_t nsize)
1169 {
1170         hammer2_key_t lbase;
1171         int nblksize;
1172
1173         hammer2_mtx_unlock(&ip->lock);
1174         if (ip->vp) {
1175                 nblksize = hammer2_calc_logical(ip, nsize, &lbase, NULL);
1176                 nvtruncbuf(ip->vp, nsize,
1177                            nblksize, (int)nsize & (nblksize - 1),
1178                            0);
1179         }
1180         hammer2_mtx_ex(&ip->lock);
1181         KKASSERT((ip->flags & HAMMER2_INODE_RESIZED) == 0);
1182         ip->osize = ip->meta.size;
1183         ip->meta.size = nsize;
1184         atomic_set_int(&ip->flags, HAMMER2_INODE_RESIZED);
1185         hammer2_inode_modify(ip);
1186 }
1187
1188 /*
1189  * Extend the size of a file.  The inode must not be locked.
1190  *
1191  * Even though the file size is changing, we do not have to set the
1192  * INODE_RESIZED bit unless the file size crosses the EMBEDDED_BYTES
1193  * boundary.  When this occurs a hammer2_inode_chain_sync() is required
1194  * to prepare the inode cluster's indirect block table, otherwise
1195  * async execution of the strategy code will implode on us.
1196  *
1197  * WARNING! Assumes that the kernel interlocks size changes at the
1198  *          vnode level.
1199  *
1200  * WARNING! Caller assumes responsibility for transitioning out
1201  *          of the inode DIRECTDATA mode if INODE_RESIZED is set.
1202  */
1203 static
1204 void
1205 hammer2_extend_file(hammer2_inode_t *ip, hammer2_key_t nsize)
1206 {
1207         hammer2_key_t lbase;
1208         hammer2_key_t osize;
1209         int oblksize;
1210         int nblksize;
1211
1212         KKASSERT((ip->flags & HAMMER2_INODE_RESIZED) == 0);
1213         hammer2_inode_modify(ip);
1214         osize = ip->meta.size;
1215         ip->osize = osize;
1216         ip->meta.size = nsize;
1217
1218         /*
1219          * We must issue a chain_sync() when the DIRECTDATA state changes
1220          * to prevent confusion between the flush code and the in-memory
1221          * state.  This is not perfect because we are doing it outside of
1222          * a sync/fsync operation, so it might not be fully synchronized
1223          * with the meta-data topology flush.
1224          */
1225         if (osize <= HAMMER2_EMBEDDED_BYTES && nsize > HAMMER2_EMBEDDED_BYTES) {
1226                 atomic_set_int(&ip->flags, HAMMER2_INODE_RESIZED);
1227                 hammer2_inode_chain_sync(ip);
1228         }
1229
1230         hammer2_mtx_unlock(&ip->lock);
1231         if (ip->vp) {
1232                 oblksize = hammer2_calc_logical(ip, osize, &lbase, NULL);
1233                 nblksize = hammer2_calc_logical(ip, nsize, &lbase, NULL);
1234                 nvextendbuf(ip->vp,
1235                             osize, nsize,
1236                             oblksize, nblksize,
1237                             -1, -1, 0);
1238         }
1239         hammer2_mtx_ex(&ip->lock);
1240 }
1241
1242 static
1243 int
1244 hammer2_vop_nresolve(struct vop_nresolve_args *ap)
1245 {
1246         hammer2_xop_nresolve_t *xop;
1247         hammer2_inode_t *ip;
1248         hammer2_inode_t *dip;
1249         struct namecache *ncp;
1250         struct vnode *vp;
1251         int error;
1252
1253         dip = VTOI(ap->a_dvp);
1254         xop = hammer2_xop_alloc(dip, 0);
1255
1256         ncp = ap->a_nch->ncp;
1257         hammer2_xop_setname(&xop->head, ncp->nc_name, ncp->nc_nlen);
1258
1259         /*
1260          * Note: In DragonFly the kernel handles '.' and '..'.
1261          */
1262         hammer2_inode_lock(dip, HAMMER2_RESOLVE_SHARED);
1263         hammer2_xop_start(&xop->head, hammer2_xop_nresolve);
1264
1265         error = hammer2_xop_collect(&xop->head, 0);
1266         error = hammer2_error_to_errno(error);
1267         if (error) {
1268                 ip = NULL;
1269         } else {
1270                 ip = hammer2_inode_get(dip->pmp, dip, &xop->head.cluster, -1);
1271         }
1272         hammer2_inode_unlock(dip);
1273
1274         /*
1275          * Acquire the related vnode
1276          *
1277          * NOTE: For error processing, only ENOENT resolves the namecache
1278          *       entry to NULL, otherwise we just return the error and
1279          *       leave the namecache unresolved.
1280          *
1281          * NOTE: multiple hammer2_inode structures can be aliased to the
1282          *       same chain element, for example for hardlinks.  This
1283          *       use case does not 'reattach' inode associations that
1284          *       might already exist, but always allocates a new one.
1285          *
1286          * WARNING: inode structure is locked exclusively via inode_get
1287          *          but chain was locked shared.  inode_unlock()
1288          *          will handle it properly.
1289          */
1290         if (ip) {
1291                 vp = hammer2_igetv(ip, &error); /* error set to UNIX error */
1292                 if (error == 0) {
1293                         vn_unlock(vp);
1294                         cache_setvp(ap->a_nch, vp);
1295                 } else if (error == ENOENT) {
1296                         cache_setvp(ap->a_nch, NULL);
1297                 }
1298                 hammer2_inode_unlock(ip);
1299
1300                 /*
1301                  * The vp should not be released until after we've disposed
1302                  * of our locks, because it might cause vop_inactive() to
1303                  * be called.
1304                  */
1305                 if (vp)
1306                         vrele(vp);
1307         } else {
1308                 error = ENOENT;
1309                 cache_setvp(ap->a_nch, NULL);
1310         }
1311         hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
1312         KASSERT(error || ap->a_nch->ncp->nc_vp != NULL,
1313                 ("resolve error %d/%p ap %p\n",
1314                  error, ap->a_nch->ncp->nc_vp, ap));
1315
1316         return error;
1317 }
1318
1319 static
1320 int
1321 hammer2_vop_nlookupdotdot(struct vop_nlookupdotdot_args *ap)
1322 {
1323         hammer2_inode_t *dip;
1324         hammer2_tid_t inum;
1325         int error;
1326
1327         dip = VTOI(ap->a_dvp);
1328         inum = dip->meta.iparent;
1329         *ap->a_vpp = NULL;
1330
1331         if (inum) {
1332                 error = hammer2_vfs_vget(ap->a_dvp->v_mount, NULL,
1333                                          inum, ap->a_vpp);
1334         } else {
1335                 error = ENOENT;
1336         }
1337         return error;
1338 }
1339
1340 static
1341 int
1342 hammer2_vop_nmkdir(struct vop_nmkdir_args *ap)
1343 {
1344         hammer2_inode_t *dip;
1345         hammer2_inode_t *nip;
1346         struct namecache *ncp;
1347         const uint8_t *name;
1348         size_t name_len;
1349         hammer2_tid_t inum;
1350         int error;
1351
1352         dip = VTOI(ap->a_dvp);
1353         if (dip->pmp->ronly)
1354                 return (EROFS);
1355         if (hammer2_vfs_enospace(dip, 0, ap->a_cred) > 1)
1356                 return (ENOSPC);
1357
1358         ncp = ap->a_nch->ncp;
1359         name = ncp->nc_name;
1360         name_len = ncp->nc_nlen;
1361
1362         hammer2_pfs_memory_wait(dip->pmp);
1363         hammer2_trans_init(dip->pmp, 0);
1364
1365         inum = hammer2_trans_newinum(dip->pmp);
1366
1367         /*
1368          * Create the actual inode as a hidden file in the iroot, then
1369          * create the directory entry.  The creation of the actual inode
1370          * sets its nlinks to 1 which is the value we desire.
1371          */
1372         nip = hammer2_inode_create(dip->pmp->iroot, dip, ap->a_vap, ap->a_cred,
1373                                    NULL, 0, inum,
1374                                    inum, 0, 0,
1375                                    0, &error);
1376         if (error) {
1377                 error = hammer2_error_to_errno(error);
1378         } else {
1379                 error = hammer2_dirent_create(dip, name, name_len,
1380                                               nip->meta.inum, nip->meta.type);
1381                 /* returns UNIX error code */
1382         }
1383         if (error) {
1384                 if (nip) {
1385                         hammer2_inode_unlink_finisher(nip, 0);
1386                         hammer2_inode_unlock(nip);
1387                         nip = NULL;
1388                 }
1389                 *ap->a_vpp = NULL;
1390         } else {
1391                 *ap->a_vpp = hammer2_igetv(nip, &error);
1392                 hammer2_inode_unlock(nip);
1393         }
1394
1395         /*
1396          * Update dip's mtime
1397          *
1398          * We can use a shared inode lock and allow the meta.mtime update
1399          * SMP race.  hammer2_inode_modify() is MPSAFE w/a shared lock.
1400          */
1401         if (error == 0) {
1402                 uint64_t mtime;
1403
1404                 hammer2_inode_lock(dip, HAMMER2_RESOLVE_SHARED);
1405                 hammer2_update_time(&mtime);
1406                 hammer2_inode_modify(dip);
1407                 dip->meta.mtime = mtime;
1408                 hammer2_inode_unlock(dip);
1409         }
1410
1411         hammer2_trans_done(dip->pmp);
1412
1413         if (error == 0) {
1414                 cache_setunresolved(ap->a_nch);
1415                 cache_setvp(ap->a_nch, *ap->a_vpp);
1416                 hammer2_knote(ap->a_dvp, NOTE_WRITE | NOTE_LINK);
1417         }
1418         return error;
1419 }
1420
1421 static
1422 int
1423 hammer2_vop_open(struct vop_open_args *ap)
1424 {
1425         return vop_stdopen(ap);
1426 }
1427
1428 /*
1429  * hammer2_vop_advlock { vp, id, op, fl, flags }
1430  */
1431 static
1432 int
1433 hammer2_vop_advlock(struct vop_advlock_args *ap)
1434 {
1435         hammer2_inode_t *ip = VTOI(ap->a_vp);
1436         hammer2_off_t size;
1437
1438         size = ip->meta.size;
1439         return (lf_advlock(ap, &ip->advlock, size));
1440 }
1441
1442 static
1443 int
1444 hammer2_vop_close(struct vop_close_args *ap)
1445 {
1446         return vop_stdclose(ap);
1447 }
1448
1449 /*
1450  * hammer2_vop_nlink { nch, dvp, vp, cred }
1451  *
1452  * Create a hardlink from (vp) to {dvp, nch}.
1453  */
1454 static
1455 int
1456 hammer2_vop_nlink(struct vop_nlink_args *ap)
1457 {
1458         hammer2_inode_t *tdip;  /* target directory to create link in */
1459         hammer2_inode_t *ip;    /* inode we are hardlinking to */
1460         struct namecache *ncp;
1461         const uint8_t *name;
1462         size_t name_len;
1463         int error;
1464
1465         if (ap->a_dvp->v_mount != ap->a_vp->v_mount)
1466                 return(EXDEV);
1467
1468         tdip = VTOI(ap->a_dvp);
1469         if (tdip->pmp->ronly)
1470                 return (EROFS);
1471         if (hammer2_vfs_enospace(tdip, 0, ap->a_cred) > 1)
1472                 return (ENOSPC);
1473
1474         ncp = ap->a_nch->ncp;
1475         name = ncp->nc_name;
1476         name_len = ncp->nc_nlen;
1477
1478         /*
1479          * ip represents the file being hardlinked.  The file could be a
1480          * normal file or a hardlink target if it has already been hardlinked.
1481          * (with the new semantics, it will almost always be a hardlink
1482          * target).
1483          *
1484          * Bump nlinks and potentially also create or move the hardlink
1485          * target in the parent directory common to (ip) and (tdip).  The
1486          * consolidation code can modify ip->cluster.  The returned cluster
1487          * is locked.
1488          */
1489         ip = VTOI(ap->a_vp);
1490         KASSERT(ip->pmp, ("ip->pmp is NULL %p %p", ip, ip->pmp));
1491         hammer2_pfs_memory_wait(ip->pmp);
1492         hammer2_trans_init(ip->pmp, 0);
1493
1494         /*
1495          * Target should be an indexed inode or there's no way we will ever
1496          * be able to find it!
1497          */
1498         KKASSERT((ip->meta.name_key & HAMMER2_DIRHASH_VISIBLE) == 0);
1499
1500         error = 0;
1501
1502         /*
1503          * Can return NULL and error == EXDEV if the common parent
1504          * crosses a directory with the xlink flag set.
1505          */
1506         hammer2_inode_lock(tdip, 0);
1507         hammer2_inode_lock(ip, 0);
1508
1509         /*
1510          * Create the directory entry and bump nlinks.
1511          */
1512         if (error == 0) {
1513                 error = hammer2_dirent_create(tdip, name, name_len,
1514                                               ip->meta.inum, ip->meta.type);
1515                 hammer2_inode_modify(ip);
1516                 ++ip->meta.nlinks;
1517         }
1518         if (error == 0) {
1519                 /*
1520                  * Update dip's mtime
1521                  */
1522                 uint64_t mtime;
1523
1524                 hammer2_update_time(&mtime);
1525                 hammer2_inode_modify(tdip);
1526                 tdip->meta.mtime = mtime;
1527
1528                 cache_setunresolved(ap->a_nch);
1529                 cache_setvp(ap->a_nch, ap->a_vp);
1530         }
1531         hammer2_inode_unlock(ip);
1532         hammer2_inode_unlock(tdip);
1533
1534         hammer2_trans_done(ip->pmp);
1535         hammer2_knote(ap->a_vp, NOTE_LINK);
1536         hammer2_knote(ap->a_dvp, NOTE_WRITE);
1537
1538         return error;
1539 }
1540
1541 /*
1542  * hammer2_vop_ncreate { nch, dvp, vpp, cred, vap }
1543  *
1544  * The operating system has already ensured that the directory entry
1545  * does not exist and done all appropriate namespace locking.
1546  */
1547 static
1548 int
1549 hammer2_vop_ncreate(struct vop_ncreate_args *ap)
1550 {
1551         hammer2_inode_t *dip;
1552         hammer2_inode_t *nip;
1553         struct namecache *ncp;
1554         const uint8_t *name;
1555         size_t name_len;
1556         hammer2_tid_t inum;
1557         int error;
1558
1559         dip = VTOI(ap->a_dvp);
1560         if (dip->pmp->ronly)
1561                 return (EROFS);
1562         if (hammer2_vfs_enospace(dip, 0, ap->a_cred) > 1)
1563                 return (ENOSPC);
1564
1565         ncp = ap->a_nch->ncp;
1566         name = ncp->nc_name;
1567         name_len = ncp->nc_nlen;
1568         hammer2_pfs_memory_wait(dip->pmp);
1569         hammer2_trans_init(dip->pmp, 0);
1570
1571         inum = hammer2_trans_newinum(dip->pmp);
1572
1573         /*
1574          * Create the actual inode as a hidden file in the iroot, then
1575          * create the directory entry.  The creation of the actual inode
1576          * sets its nlinks to 1 which is the value we desire.
1577          */
1578         nip = hammer2_inode_create(dip->pmp->iroot, dip, ap->a_vap, ap->a_cred,
1579                                    NULL, 0, inum,
1580                                    inum, 0, 0,
1581                                    0, &error);
1582
1583         if (error) {
1584                 error = hammer2_error_to_errno(error);
1585         } else {
1586                 error = hammer2_dirent_create(dip, name, name_len,
1587                                               nip->meta.inum, nip->meta.type);
1588         }
1589         if (error) {
1590                 if (nip) {
1591                         hammer2_inode_unlink_finisher(nip, 0);
1592                         hammer2_inode_unlock(nip);
1593                         nip = NULL;
1594                 }
1595                 *ap->a_vpp = NULL;
1596         } else {
1597                 *ap->a_vpp = hammer2_igetv(nip, &error);
1598                 hammer2_inode_unlock(nip);
1599         }
1600
1601         /*
1602          * Update dip's mtime
1603          */
1604         if (error == 0) {
1605                 uint64_t mtime;
1606
1607                 hammer2_inode_lock(dip, HAMMER2_RESOLVE_SHARED);
1608                 hammer2_update_time(&mtime);
1609                 hammer2_inode_modify(dip);
1610                 dip->meta.mtime = mtime;
1611                 hammer2_inode_unlock(dip);
1612         }
1613
1614         hammer2_trans_done(dip->pmp);
1615
1616         if (error == 0) {
1617                 cache_setunresolved(ap->a_nch);
1618                 cache_setvp(ap->a_nch, *ap->a_vpp);
1619                 hammer2_knote(ap->a_dvp, NOTE_WRITE);
1620         }
1621         return error;
1622 }
1623
1624 /*
1625  * Make a device node (typically a fifo)
1626  */
1627 static
1628 int
1629 hammer2_vop_nmknod(struct vop_nmknod_args *ap)
1630 {
1631         hammer2_inode_t *dip;
1632         hammer2_inode_t *nip;
1633         struct namecache *ncp;
1634         const uint8_t *name;
1635         size_t name_len;
1636         hammer2_tid_t inum;
1637         int error;
1638
1639         dip = VTOI(ap->a_dvp);
1640         if (dip->pmp->ronly)
1641                 return (EROFS);
1642         if (hammer2_vfs_enospace(dip, 0, ap->a_cred) > 1)
1643                 return (ENOSPC);
1644
1645         ncp = ap->a_nch->ncp;
1646         name = ncp->nc_name;
1647         name_len = ncp->nc_nlen;
1648         hammer2_pfs_memory_wait(dip->pmp);
1649         hammer2_trans_init(dip->pmp, 0);
1650
1651         /*
1652          * Create the device inode and then create the directory entry.
1653          */
1654         inum = hammer2_trans_newinum(dip->pmp);
1655         nip = hammer2_inode_create(dip->pmp->iroot, dip, ap->a_vap, ap->a_cred,
1656                                    NULL, 0, inum,
1657                                    inum, 0, 0,
1658                                    0, &error);
1659         if (error == 0) {
1660                 error = hammer2_dirent_create(dip, name, name_len,
1661                                               nip->meta.inum, nip->meta.type);
1662         }
1663         if (error) {
1664                 if (nip) {
1665                         hammer2_inode_unlink_finisher(nip, 0);
1666                         hammer2_inode_unlock(nip);
1667                         nip = NULL;
1668                 }
1669                 *ap->a_vpp = NULL;
1670         } else {
1671                 *ap->a_vpp = hammer2_igetv(nip, &error);
1672                 hammer2_inode_unlock(nip);
1673         }
1674
1675         /*
1676          * Update dip's mtime
1677          */
1678         if (error == 0) {
1679                 uint64_t mtime;
1680
1681                 hammer2_inode_lock(dip, HAMMER2_RESOLVE_SHARED);
1682                 hammer2_update_time(&mtime);
1683                 hammer2_inode_modify(dip);
1684                 dip->meta.mtime = mtime;
1685                 hammer2_inode_unlock(dip);
1686         }
1687
1688         hammer2_trans_done(dip->pmp);
1689
1690         if (error == 0) {
1691                 cache_setunresolved(ap->a_nch);
1692                 cache_setvp(ap->a_nch, *ap->a_vpp);
1693                 hammer2_knote(ap->a_dvp, NOTE_WRITE);
1694         }
1695         return error;
1696 }
1697
1698 /*
1699  * hammer2_vop_nsymlink { nch, dvp, vpp, cred, vap, target }
1700  */
1701 static
1702 int
1703 hammer2_vop_nsymlink(struct vop_nsymlink_args *ap)
1704 {
1705         hammer2_inode_t *dip;
1706         hammer2_inode_t *nip;
1707         struct namecache *ncp;
1708         const uint8_t *name;
1709         size_t name_len;
1710         hammer2_tid_t inum;
1711         int error;
1712
1713         dip = VTOI(ap->a_dvp);
1714         if (dip->pmp->ronly)
1715                 return (EROFS);
1716         if (hammer2_vfs_enospace(dip, 0, ap->a_cred) > 1)
1717                 return (ENOSPC);
1718
1719         ncp = ap->a_nch->ncp;
1720         name = ncp->nc_name;
1721         name_len = ncp->nc_nlen;
1722         hammer2_pfs_memory_wait(dip->pmp);
1723         hammer2_trans_init(dip->pmp, 0);
1724
1725         ap->a_vap->va_type = VLNK;      /* enforce type */
1726
1727         /*
1728          * Create the softlink as an inode and then create the directory
1729          * entry.
1730          */
1731         inum = hammer2_trans_newinum(dip->pmp);
1732
1733         nip = hammer2_inode_create(dip->pmp->iroot, dip, ap->a_vap, ap->a_cred,
1734                                    NULL, 0, inum,
1735                                    inum, 0, 0,
1736                                    0, &error);
1737         if (error == 0) {
1738                 error = hammer2_dirent_create(dip, name, name_len,
1739                                               nip->meta.inum, nip->meta.type);
1740         }
1741         if (error) {
1742                 if (nip) {
1743                         hammer2_inode_unlink_finisher(nip, 0);
1744                         hammer2_inode_unlock(nip);
1745                         nip = NULL;
1746                 }
1747                 *ap->a_vpp = NULL;
1748                 hammer2_trans_done(dip->pmp);
1749                 return error;
1750         }
1751         *ap->a_vpp = hammer2_igetv(nip, &error);
1752
1753         /*
1754          * Build the softlink (~like file data) and finalize the namecache.
1755          */
1756         if (error == 0) {
1757                 size_t bytes;
1758                 struct uio auio;
1759                 struct iovec aiov;
1760
1761                 bytes = strlen(ap->a_target);
1762
1763                 hammer2_inode_unlock(nip);
1764                 bzero(&auio, sizeof(auio));
1765                 bzero(&aiov, sizeof(aiov));
1766                 auio.uio_iov = &aiov;
1767                 auio.uio_segflg = UIO_SYSSPACE;
1768                 auio.uio_rw = UIO_WRITE;
1769                 auio.uio_resid = bytes;
1770                 auio.uio_iovcnt = 1;
1771                 auio.uio_td = curthread;
1772                 aiov.iov_base = ap->a_target;
1773                 aiov.iov_len = bytes;
1774                 error = hammer2_write_file(nip, &auio, IO_APPEND, 0);
1775                 /* XXX handle error */
1776                 error = 0;
1777         } else {
1778                 hammer2_inode_unlock(nip);
1779         }
1780
1781         /*
1782          * Update dip's mtime
1783          */
1784         if (error == 0) {
1785                 uint64_t mtime;
1786
1787                 hammer2_inode_lock(dip, HAMMER2_RESOLVE_SHARED);
1788                 hammer2_update_time(&mtime);
1789                 hammer2_inode_modify(dip);
1790                 dip->meta.mtime = mtime;
1791                 hammer2_inode_unlock(dip);
1792         }
1793
1794         hammer2_trans_done(dip->pmp);
1795
1796         /*
1797          * Finalize namecache
1798          */
1799         if (error == 0) {
1800                 cache_setunresolved(ap->a_nch);
1801                 cache_setvp(ap->a_nch, *ap->a_vpp);
1802                 hammer2_knote(ap->a_dvp, NOTE_WRITE);
1803         }
1804         return error;
1805 }
1806
1807 /*
1808  * hammer2_vop_nremove { nch, dvp, cred }
1809  */
1810 static
1811 int
1812 hammer2_vop_nremove(struct vop_nremove_args *ap)
1813 {
1814         hammer2_xop_unlink_t *xop;
1815         hammer2_inode_t *dip;
1816         hammer2_inode_t *ip;
1817         struct namecache *ncp;
1818         int error;
1819         int isopen;
1820
1821         dip = VTOI(ap->a_dvp);
1822         if (dip->pmp->ronly)
1823                 return (EROFS);
1824 #if 0
1825         /* allow removals, except user to also bulkfree */
1826         if (hammer2_vfs_enospace(dip, 0, ap->a_cred) > 1)
1827                 return (ENOSPC);
1828 #endif
1829
1830         ncp = ap->a_nch->ncp;
1831
1832         hammer2_pfs_memory_wait(dip->pmp);
1833         hammer2_trans_init(dip->pmp, 0);
1834         hammer2_inode_lock(dip, 0);
1835
1836         /*
1837          * The unlink XOP unlinks the path from the directory and
1838          * locates and returns the cluster associated with the real inode.
1839          * We have to handle nlinks here on the frontend.
1840          */
1841         xop = hammer2_xop_alloc(dip, HAMMER2_XOP_MODIFYING);
1842         hammer2_xop_setname(&xop->head, ncp->nc_name, ncp->nc_nlen);
1843
1844         /*
1845          * The namecache entry is locked so nobody can use this namespace.
1846          * Calculate isopen to determine if this namespace has an open vp
1847          * associated with it and resolve the vp only if it does.
1848          *
1849          * We try to avoid resolving the vnode if nobody has it open, but
1850          * note that the test is via this namespace only.
1851          */
1852         isopen = cache_isopen(ap->a_nch);
1853         xop->isdir = 0;
1854         xop->dopermanent = 0;
1855         hammer2_xop_start(&xop->head, hammer2_xop_unlink);
1856
1857         /*
1858          * Collect the real inode and adjust nlinks, destroy the real
1859          * inode if nlinks transitions to 0 and it was the real inode
1860          * (else it has already been removed).
1861          */
1862         error = hammer2_xop_collect(&xop->head, 0);
1863         error = hammer2_error_to_errno(error);
1864         hammer2_inode_unlock(dip);
1865
1866         if (error == 0) {
1867                 ip = hammer2_inode_get(dip->pmp, dip, &xop->head.cluster, -1);
1868                 hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
1869                 if (ip) {
1870                         hammer2_inode_unlink_finisher(ip, isopen);
1871                         hammer2_inode_unlock(ip);
1872                 }
1873         } else {
1874                 hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
1875         }
1876
1877         /*
1878          * Update dip's mtime
1879          */
1880         if (error == 0) {
1881                 uint64_t mtime;
1882
1883                 hammer2_inode_lock(dip, HAMMER2_RESOLVE_SHARED);
1884                 hammer2_update_time(&mtime);
1885                 hammer2_inode_modify(dip);
1886                 dip->meta.mtime = mtime;
1887                 hammer2_inode_unlock(dip);
1888         }
1889
1890         hammer2_inode_run_sideq(dip->pmp, 0);
1891         hammer2_trans_done(dip->pmp);
1892         if (error == 0) {
1893                 cache_unlink(ap->a_nch);
1894                 hammer2_knote(ap->a_dvp, NOTE_WRITE);
1895         }
1896         return (error);
1897 }
1898
1899 /*
1900  * hammer2_vop_nrmdir { nch, dvp, cred }
1901  */
1902 static
1903 int
1904 hammer2_vop_nrmdir(struct vop_nrmdir_args *ap)
1905 {
1906         hammer2_xop_unlink_t *xop;
1907         hammer2_inode_t *dip;
1908         hammer2_inode_t *ip;
1909         struct namecache *ncp;
1910         int isopen;
1911         int error;
1912
1913         dip = VTOI(ap->a_dvp);
1914         if (dip->pmp->ronly)
1915                 return (EROFS);
1916 #if 0
1917         /* allow removals, except user to also bulkfree */
1918         if (hammer2_vfs_enospace(dip, 0, ap->a_cred) > 1)
1919                 return (ENOSPC);
1920 #endif
1921
1922         hammer2_pfs_memory_wait(dip->pmp);
1923         hammer2_trans_init(dip->pmp, 0);
1924         hammer2_inode_lock(dip, 0);
1925
1926         xop = hammer2_xop_alloc(dip, HAMMER2_XOP_MODIFYING);
1927
1928         ncp = ap->a_nch->ncp;
1929         hammer2_xop_setname(&xop->head, ncp->nc_name, ncp->nc_nlen);
1930         isopen = cache_isopen(ap->a_nch);
1931         xop->isdir = 1;
1932         xop->dopermanent = 0;
1933         hammer2_xop_start(&xop->head, hammer2_xop_unlink);
1934
1935         /*
1936          * Collect the real inode and adjust nlinks, destroy the real
1937          * inode if nlinks transitions to 0 and it was the real inode
1938          * (else it has already been removed).
1939          */
1940         error = hammer2_xop_collect(&xop->head, 0);
1941         error = hammer2_error_to_errno(error);
1942         hammer2_inode_unlock(dip);
1943
1944         if (error == 0) {
1945                 ip = hammer2_inode_get(dip->pmp, dip, &xop->head.cluster, -1);
1946                 hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
1947                 if (ip) {
1948                         hammer2_inode_unlink_finisher(ip, isopen);
1949                         hammer2_inode_unlock(ip);
1950                 }
1951         } else {
1952                 hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
1953         }
1954
1955         /*
1956          * Update dip's mtime
1957          */
1958         if (error == 0) {
1959                 uint64_t mtime;
1960
1961                 hammer2_inode_lock(dip, HAMMER2_RESOLVE_SHARED);
1962                 hammer2_update_time(&mtime);
1963                 hammer2_inode_modify(dip);
1964                 dip->meta.mtime = mtime;
1965                 hammer2_inode_unlock(dip);
1966         }
1967
1968         hammer2_inode_run_sideq(dip->pmp, 0);
1969         hammer2_trans_done(dip->pmp);
1970         if (error == 0) {
1971                 cache_unlink(ap->a_nch);
1972                 hammer2_knote(ap->a_dvp, NOTE_WRITE | NOTE_LINK);
1973         }
1974         return (error);
1975 }
1976
1977 /*
1978  * hammer2_vop_nrename { fnch, tnch, fdvp, tdvp, cred }
1979  */
1980 static
1981 int
1982 hammer2_vop_nrename(struct vop_nrename_args *ap)
1983 {
1984         struct namecache *fncp;
1985         struct namecache *tncp;
1986         hammer2_inode_t *fdip;  /* source directory */
1987         hammer2_inode_t *tdip;  /* target directory */
1988         hammer2_inode_t *ip;    /* file being renamed */
1989         hammer2_inode_t *tip;   /* replaced target during rename or NULL */
1990         const uint8_t *fname;
1991         size_t fname_len;
1992         const uint8_t *tname;
1993         size_t tname_len;
1994         int error;
1995         int update_tdip;
1996         int update_fdip;
1997         hammer2_key_t tlhc;
1998
1999         if (ap->a_fdvp->v_mount != ap->a_tdvp->v_mount)
2000                 return(EXDEV);
2001         if (ap->a_fdvp->v_mount != ap->a_fnch->ncp->nc_vp->v_mount)
2002                 return(EXDEV);
2003
2004         fdip = VTOI(ap->a_fdvp);        /* source directory */
2005         tdip = VTOI(ap->a_tdvp);        /* target directory */
2006
2007         if (fdip->pmp->ronly)
2008                 return (EROFS);
2009         if (hammer2_vfs_enospace(fdip, 0, ap->a_cred) > 1)
2010                 return (ENOSPC);
2011
2012         fncp = ap->a_fnch->ncp;         /* entry name in source */
2013         fname = fncp->nc_name;
2014         fname_len = fncp->nc_nlen;
2015
2016         tncp = ap->a_tnch->ncp;         /* entry name in target */
2017         tname = tncp->nc_name;
2018         tname_len = tncp->nc_nlen;
2019
2020         hammer2_pfs_memory_wait(tdip->pmp);
2021         hammer2_trans_init(tdip->pmp, 0);
2022
2023         update_tdip = 0;
2024         update_fdip = 0;
2025
2026         ip = VTOI(fncp->nc_vp);
2027         hammer2_inode_ref(ip);          /* extra ref */
2028
2029         /*
2030          * Lookup the target name to determine if a directory entry
2031          * is being overwritten.  We only hold related inode locks
2032          * temporarily, the operating system is expected to protect
2033          * against rename races.
2034          */
2035         tip = tncp->nc_vp ? VTOI(tncp->nc_vp) : NULL;
2036         if (tip)
2037                 hammer2_inode_ref(tip); /* extra ref */
2038
2039         /*
2040          * Can return NULL and error == EXDEV if the common parent
2041          * crosses a directory with the xlink flag set.
2042          *
2043          * For now try to avoid deadlocks with a simple pointer address
2044          * test.  (tip) can be NULL.
2045          */
2046         error = 0;
2047         if (fdip <= tdip) {
2048                 hammer2_inode_lock(fdip, 0);
2049                 hammer2_inode_lock(tdip, 0);
2050         } else {
2051                 hammer2_inode_lock(tdip, 0);
2052                 hammer2_inode_lock(fdip, 0);
2053         }
2054         if (tip) {
2055                 if (ip <= tip) {
2056                         hammer2_inode_lock(ip, 0);
2057                         hammer2_inode_lock(tip, 0);
2058                 } else {
2059                         hammer2_inode_lock(tip, 0);
2060                         hammer2_inode_lock(ip, 0);
2061                 }
2062         } else {
2063                 hammer2_inode_lock(ip, 0);
2064         }
2065
2066 #if 0
2067         /*
2068          * Delete the target namespace.
2069          *
2070          * REMOVED - NOW FOLDED INTO XOP_NRENAME OPERATION
2071          */
2072         {
2073                 hammer2_xop_unlink_t *xop2;
2074                 hammer2_inode_t *tip;
2075                 int isopen;
2076
2077                 /*
2078                  * The unlink XOP unlinks the path from the directory and
2079                  * locates and returns the cluster associated with the real
2080                  * inode.  We have to handle nlinks here on the frontend.
2081                  */
2082                 xop2 = hammer2_xop_alloc(tdip, HAMMER2_XOP_MODIFYING);
2083                 hammer2_xop_setname(&xop2->head, tname, tname_len);
2084                 isopen = cache_isopen(ap->a_tnch);
2085                 xop2->isdir = -1;
2086                 xop2->dopermanent = 0;
2087                 hammer2_xop_start(&xop2->head, hammer2_xop_unlink);
2088
2089                 /*
2090                  * Collect the real inode and adjust nlinks, destroy the real
2091                  * inode if nlinks transitions to 0 and it was the real inode
2092                  * (else it has already been removed).
2093                  */
2094                 tnch_error = hammer2_xop_collect(&xop2->head, 0);
2095                 tnch_error = hammer2_error_to_errno(tnch_error);
2096                 /* hammer2_inode_unlock(tdip); */
2097
2098                 if (tnch_error == 0) {
2099                         tip = hammer2_inode_get(tdip->pmp, NULL,
2100                                                 &xop2->head.cluster, -1);
2101                         hammer2_xop_retire(&xop2->head, HAMMER2_XOPMASK_VOP);
2102                         if (tip) {
2103                                 hammer2_inode_unlink_finisher(tip, isopen);
2104                                 hammer2_inode_unlock(tip);
2105                         }
2106                 } else {
2107                         hammer2_xop_retire(&xop2->head, HAMMER2_XOPMASK_VOP);
2108                 }
2109                 /* hammer2_inode_lock(tdip, 0); */
2110
2111                 if (tnch_error && tnch_error != ENOENT) {
2112                         error = tnch_error;
2113                         goto done2;
2114                 }
2115                 update_tdip = 1;
2116         }
2117 #endif
2118
2119         /*
2120          * Resolve the collision space for (tdip, tname, tname_len)
2121          *
2122          * tdip must be held exclusively locked to prevent races since
2123          * multiple filenames can end up in the same collision space.
2124          */
2125         {
2126                 hammer2_xop_scanlhc_t *sxop;
2127                 hammer2_tid_t lhcbase;
2128
2129                 tlhc = hammer2_dirhash(tname, tname_len);
2130                 lhcbase = tlhc;
2131                 sxop = hammer2_xop_alloc(tdip, HAMMER2_XOP_MODIFYING);
2132                 sxop->lhc = tlhc;
2133                 hammer2_xop_start(&sxop->head, hammer2_xop_scanlhc);
2134                 while ((error = hammer2_xop_collect(&sxop->head, 0)) == 0) {
2135                         if (tlhc != sxop->head.cluster.focus->bref.key)
2136                                 break;
2137                         ++tlhc;
2138                 }
2139                 error = hammer2_error_to_errno(error);
2140                 hammer2_xop_retire(&sxop->head, HAMMER2_XOPMASK_VOP);
2141
2142                 if (error) {
2143                         if (error != ENOENT)
2144                                 goto done2;
2145                         ++tlhc;
2146                         error = 0;
2147                 }
2148                 if ((lhcbase ^ tlhc) & ~HAMMER2_DIRHASH_LOMASK) {
2149                         error = ENOSPC;
2150                         goto done2;
2151                 }
2152         }
2153
2154         /*
2155          * Ready to go, issue the rename to the backend.  Note that meta-data
2156          * updates to the related inodes occur separately from the rename
2157          * operation.
2158          *
2159          * NOTE: While it is not necessary to update ip->meta.name*, doing
2160          *       so aids catastrophic recovery and debugging.
2161          */
2162         if (error == 0) {
2163                 hammer2_xop_nrename_t *xop4;
2164
2165                 xop4 = hammer2_xop_alloc(fdip, HAMMER2_XOP_MODIFYING);
2166                 xop4->lhc = tlhc;
2167                 xop4->ip_key = ip->meta.name_key;
2168                 hammer2_xop_setip2(&xop4->head, ip);
2169                 hammer2_xop_setip3(&xop4->head, tdip);
2170                 hammer2_xop_setname(&xop4->head, fname, fname_len);
2171                 hammer2_xop_setname2(&xop4->head, tname, tname_len);
2172                 hammer2_xop_start(&xop4->head, hammer2_xop_nrename);
2173
2174                 error = hammer2_xop_collect(&xop4->head, 0);
2175                 error = hammer2_error_to_errno(error);
2176                 hammer2_xop_retire(&xop4->head, HAMMER2_XOPMASK_VOP);
2177
2178                 if (error == ENOENT)
2179                         error = 0;
2180
2181                 /*
2182                  * Update inode meta-data.
2183                  *
2184                  * WARNING!  The in-memory inode (ip) structure does not
2185                  *           maintain a copy of the inode's filename buffer.
2186                  */
2187                 if (error == 0 &&
2188                     (ip->meta.name_key & HAMMER2_DIRHASH_VISIBLE)) {
2189                         hammer2_inode_modify(ip);
2190                         ip->meta.name_len = tname_len;
2191                         ip->meta.name_key = tlhc;
2192                 }
2193                 if (error == 0) {
2194                         hammer2_inode_modify(ip);
2195                         ip->meta.iparent = tdip->meta.inum;
2196                 }
2197                 update_fdip = 1;
2198                 update_tdip = 1;
2199         }
2200
2201 done2:
2202         /*
2203          * If no error, the backend has replaced the target directory entry.
2204          * We must adjust nlinks on the original replace target if it exists.
2205          */
2206         if (error == 0 && tip) {
2207                 int isopen;
2208
2209                 isopen = cache_isopen(ap->a_tnch);
2210                 hammer2_inode_unlink_finisher(tip, isopen);
2211         }
2212
2213         /*
2214          * Update directory mtimes to represent the something changed.
2215          */
2216         if (update_fdip || update_tdip) {
2217                 uint64_t mtime;
2218
2219                 hammer2_update_time(&mtime);
2220                 if (update_fdip) {
2221                         hammer2_inode_modify(fdip);
2222                         fdip->meta.mtime = mtime;
2223                 }
2224                 if (update_tdip) {
2225                         hammer2_inode_modify(tdip);
2226                         tdip->meta.mtime = mtime;
2227                 }
2228         }
2229         if (tip) {
2230                 hammer2_inode_unlock(tip);
2231                 hammer2_inode_drop(tip);
2232         }
2233         hammer2_inode_unlock(ip);
2234         hammer2_inode_unlock(tdip);
2235         hammer2_inode_unlock(fdip);
2236         hammer2_inode_drop(ip);
2237         hammer2_inode_run_sideq(fdip->pmp, 0);
2238
2239         hammer2_trans_done(tdip->pmp);
2240
2241         /*
2242          * Issue the namecache update after unlocking all the internal
2243          * hammer2 structures, otherwise we might deadlock.
2244          *
2245          * WARNING! The target namespace must be updated atomically,
2246          *          and we depend on cache_rename() to handle that for
2247          *          us.  Do not do a separate cache_unlink() because
2248          *          that leaves a small window of opportunity for other
2249          *          threads to allocate the target namespace before we
2250          *          manage to complete our rename.
2251          *
2252          * WARNING! cache_rename() (and cache_unlink()) will properly
2253          *          set VREF_FINALIZE on any attached vnode.  Do not
2254          *          call cache_setunresolved() manually before-hand as
2255          *          this will prevent the flag from being set later via
2256          *          cache_rename().  If VREF_FINALIZE is not properly set
2257          *          and the inode is no longer in the topology, related
2258          *          chains can remain dirty indefinitely.
2259          */
2260         if (error == 0 && tip) {
2261                 /*cache_unlink(ap->a_tnch); see above */
2262                 /*cache_setunresolved(ap->a_tnch); see above */
2263         }
2264         if (error == 0) {
2265                 cache_rename(ap->a_fnch, ap->a_tnch);
2266                 hammer2_knote(ap->a_fdvp, NOTE_WRITE);
2267                 hammer2_knote(ap->a_tdvp, NOTE_WRITE);
2268                 hammer2_knote(fncp->nc_vp, NOTE_RENAME);
2269         }
2270
2271         return (error);
2272 }
2273
2274 /*
2275  * hammer2_vop_ioctl { vp, command, data, fflag, cred }
2276  */
2277 static
2278 int
2279 hammer2_vop_ioctl(struct vop_ioctl_args *ap)
2280 {
2281         hammer2_inode_t *ip;
2282         int error;
2283
2284         ip = VTOI(ap->a_vp);
2285
2286         error = hammer2_ioctl(ip, ap->a_command, (void *)ap->a_data,
2287                               ap->a_fflag, ap->a_cred);
2288         return (error);
2289 }
2290
2291 static
2292 int
2293 hammer2_vop_mountctl(struct vop_mountctl_args *ap)
2294 {
2295         struct mount *mp;
2296         hammer2_pfs_t *pmp;
2297         int rc;
2298
2299         switch (ap->a_op) {
2300         case (MOUNTCTL_SET_EXPORT):
2301                 mp = ap->a_head.a_ops->head.vv_mount;
2302                 pmp = MPTOPMP(mp);
2303
2304                 if (ap->a_ctllen != sizeof(struct export_args))
2305                         rc = (EINVAL);
2306                 else
2307                         rc = vfs_export(mp, &pmp->export,
2308                                         (const struct export_args *)ap->a_ctl);
2309                 break;
2310         default:
2311                 rc = vop_stdmountctl(ap);
2312                 break;
2313         }
2314         return (rc);
2315 }
2316
2317 /*
2318  * KQFILTER
2319  */
2320 static void filt_hammer2detach(struct knote *kn);
2321 static int filt_hammer2read(struct knote *kn, long hint);
2322 static int filt_hammer2write(struct knote *kn, long hint);
2323 static int filt_hammer2vnode(struct knote *kn, long hint);
2324
2325 static struct filterops hammer2read_filtops =
2326         { FILTEROP_ISFD | FILTEROP_MPSAFE,
2327           NULL, filt_hammer2detach, filt_hammer2read };
2328 static struct filterops hammer2write_filtops =
2329         { FILTEROP_ISFD | FILTEROP_MPSAFE,
2330           NULL, filt_hammer2detach, filt_hammer2write };
2331 static struct filterops hammer2vnode_filtops =
2332         { FILTEROP_ISFD | FILTEROP_MPSAFE,
2333           NULL, filt_hammer2detach, filt_hammer2vnode };
2334
2335 static
2336 int
2337 hammer2_vop_kqfilter(struct vop_kqfilter_args *ap)
2338 {
2339         struct vnode *vp = ap->a_vp;
2340         struct knote *kn = ap->a_kn;
2341
2342         switch (kn->kn_filter) {
2343         case EVFILT_READ:
2344                 kn->kn_fop = &hammer2read_filtops;
2345                 break;
2346         case EVFILT_WRITE:
2347                 kn->kn_fop = &hammer2write_filtops;
2348                 break;
2349         case EVFILT_VNODE:
2350                 kn->kn_fop = &hammer2vnode_filtops;
2351                 break;
2352         default:
2353                 return (EOPNOTSUPP);
2354         }
2355
2356         kn->kn_hook = (caddr_t)vp;
2357
2358         knote_insert(&vp->v_pollinfo.vpi_kqinfo.ki_note, kn);
2359
2360         return(0);
2361 }
2362
2363 static void
2364 filt_hammer2detach(struct knote *kn)
2365 {
2366         struct vnode *vp = (void *)kn->kn_hook;
2367
2368         knote_remove(&vp->v_pollinfo.vpi_kqinfo.ki_note, kn);
2369 }
2370
2371 static int
2372 filt_hammer2read(struct knote *kn, long hint)
2373 {
2374         struct vnode *vp = (void *)kn->kn_hook;
2375         hammer2_inode_t *ip = VTOI(vp);
2376         off_t off;
2377
2378         if (hint == NOTE_REVOKE) {
2379                 kn->kn_flags |= (EV_EOF | EV_NODATA | EV_ONESHOT);
2380                 return(1);
2381         }
2382         off = ip->meta.size - kn->kn_fp->f_offset;
2383         kn->kn_data = (off < INTPTR_MAX) ? off : INTPTR_MAX;
2384         if (kn->kn_sfflags & NOTE_OLDAPI)
2385                 return(1);
2386         return (kn->kn_data != 0);
2387 }
2388
2389
2390 static int
2391 filt_hammer2write(struct knote *kn, long hint)
2392 {
2393         if (hint == NOTE_REVOKE)
2394                 kn->kn_flags |= (EV_EOF | EV_NODATA | EV_ONESHOT);
2395         kn->kn_data = 0;
2396         return (1);
2397 }
2398
2399 static int
2400 filt_hammer2vnode(struct knote *kn, long hint)
2401 {
2402         if (kn->kn_sfflags & hint)
2403                 kn->kn_fflags |= hint;
2404         if (hint == NOTE_REVOKE) {
2405                 kn->kn_flags |= (EV_EOF | EV_NODATA);
2406                 return (1);
2407         }
2408         return (kn->kn_fflags != 0);
2409 }
2410
2411 /*
2412  * FIFO VOPS
2413  */
2414 static
2415 int
2416 hammer2_vop_markatime(struct vop_markatime_args *ap)
2417 {
2418         hammer2_inode_t *ip;
2419         struct vnode *vp;
2420
2421         vp = ap->a_vp;
2422         ip = VTOI(vp);
2423
2424         if (ip->pmp->ronly)
2425                 return (EROFS);
2426         return(0);
2427 }
2428
2429 static
2430 int
2431 hammer2_vop_fifokqfilter(struct vop_kqfilter_args *ap)
2432 {
2433         int error;
2434
2435         error = VOCALL(&fifo_vnode_vops, &ap->a_head);
2436         if (error)
2437                 error = hammer2_vop_kqfilter(ap);
2438         return(error);
2439 }
2440
2441 /*
2442  * VOPS vector
2443  */
2444 struct vop_ops hammer2_vnode_vops = {
2445         .vop_default    = vop_defaultop,
2446         .vop_fsync      = hammer2_vop_fsync,
2447         .vop_getpages   = vop_stdgetpages,
2448         .vop_putpages   = vop_stdputpages,
2449         .vop_access     = hammer2_vop_access,
2450         .vop_advlock    = hammer2_vop_advlock,
2451         .vop_close      = hammer2_vop_close,
2452         .vop_nlink      = hammer2_vop_nlink,
2453         .vop_ncreate    = hammer2_vop_ncreate,
2454         .vop_nsymlink   = hammer2_vop_nsymlink,
2455         .vop_nremove    = hammer2_vop_nremove,
2456         .vop_nrmdir     = hammer2_vop_nrmdir,
2457         .vop_nrename    = hammer2_vop_nrename,
2458         .vop_getattr    = hammer2_vop_getattr,
2459         .vop_setattr    = hammer2_vop_setattr,
2460         .vop_readdir    = hammer2_vop_readdir,
2461         .vop_readlink   = hammer2_vop_readlink,
2462         .vop_read       = hammer2_vop_read,
2463         .vop_write      = hammer2_vop_write,
2464         .vop_open       = hammer2_vop_open,
2465         .vop_inactive   = hammer2_vop_inactive,
2466         .vop_reclaim    = hammer2_vop_reclaim,
2467         .vop_nresolve   = hammer2_vop_nresolve,
2468         .vop_nlookupdotdot = hammer2_vop_nlookupdotdot,
2469         .vop_nmkdir     = hammer2_vop_nmkdir,
2470         .vop_nmknod     = hammer2_vop_nmknod,
2471         .vop_ioctl      = hammer2_vop_ioctl,
2472         .vop_mountctl   = hammer2_vop_mountctl,
2473         .vop_bmap       = hammer2_vop_bmap,
2474         .vop_strategy   = hammer2_vop_strategy,
2475         .vop_kqfilter   = hammer2_vop_kqfilter
2476 };
2477
2478 struct vop_ops hammer2_spec_vops = {
2479         .vop_default =          vop_defaultop,
2480         .vop_fsync =            hammer2_vop_fsync,
2481         .vop_read =             vop_stdnoread,
2482         .vop_write =            vop_stdnowrite,
2483         .vop_access =           hammer2_vop_access,
2484         .vop_close =            hammer2_vop_close,
2485         .vop_markatime =        hammer2_vop_markatime,
2486         .vop_getattr =          hammer2_vop_getattr,
2487         .vop_inactive =         hammer2_vop_inactive,
2488         .vop_reclaim =          hammer2_vop_reclaim,
2489         .vop_setattr =          hammer2_vop_setattr
2490 };
2491
2492 struct vop_ops hammer2_fifo_vops = {
2493         .vop_default =          fifo_vnoperate,
2494         .vop_fsync =            hammer2_vop_fsync,
2495 #if 0
2496         .vop_read =             hammer2_vop_fiforead,
2497         .vop_write =            hammer2_vop_fifowrite,
2498 #endif
2499         .vop_access =           hammer2_vop_access,
2500 #if 0
2501         .vop_close =            hammer2_vop_fifoclose,
2502 #endif
2503         .vop_markatime =        hammer2_vop_markatime,
2504         .vop_getattr =          hammer2_vop_getattr,
2505         .vop_inactive =         hammer2_vop_inactive,
2506         .vop_reclaim =          hammer2_vop_reclaim,
2507         .vop_setattr =          hammer2_vop_setattr,
2508         .vop_kqfilter =         hammer2_vop_fifokqfilter
2509 };
2510