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