xref: /freebsd/sys/kern/vfs_vnops.c (revision c243e4902be8df1e643c76b5f18b68bb77cc5268)
1 /*-
2  * Copyright (c) 1982, 1986, 1989, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
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 the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	@(#)vfs_vnops.c	8.2 (Berkeley) 1/21/94
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/fcntl.h>
43 #include <sys/file.h>
44 #include <sys/kdb.h>
45 #include <sys/stat.h>
46 #include <sys/priv.h>
47 #include <sys/proc.h>
48 #include <sys/limits.h>
49 #include <sys/lock.h>
50 #include <sys/mount.h>
51 #include <sys/mutex.h>
52 #include <sys/namei.h>
53 #include <sys/vnode.h>
54 #include <sys/bio.h>
55 #include <sys/buf.h>
56 #include <sys/filio.h>
57 #include <sys/resourcevar.h>
58 #include <sys/sx.h>
59 #include <sys/sysctl.h>
60 #include <sys/ttycom.h>
61 #include <sys/conf.h>
62 #include <sys/syslog.h>
63 #include <sys/unistd.h>
64 
65 #include <security/audit/audit.h>
66 #include <security/mac/mac_framework.h>
67 
68 #include <vm/vm.h>
69 #include <vm/vm_extern.h>
70 #include <vm/pmap.h>
71 #include <vm/vm_map.h>
72 #include <vm/vm_object.h>
73 #include <vm/vm_page.h>
74 
75 static fo_rdwr_t	vn_read;
76 static fo_rdwr_t	vn_write;
77 static fo_rdwr_t	vn_io_fault;
78 static fo_truncate_t	vn_truncate;
79 static fo_ioctl_t	vn_ioctl;
80 static fo_poll_t	vn_poll;
81 static fo_kqfilter_t	vn_kqfilter;
82 static fo_stat_t	vn_statfile;
83 static fo_close_t	vn_closefile;
84 
85 struct 	fileops vnops = {
86 	.fo_read = vn_io_fault,
87 	.fo_write = vn_io_fault,
88 	.fo_truncate = vn_truncate,
89 	.fo_ioctl = vn_ioctl,
90 	.fo_poll = vn_poll,
91 	.fo_kqfilter = vn_kqfilter,
92 	.fo_stat = vn_statfile,
93 	.fo_close = vn_closefile,
94 	.fo_chmod = vn_chmod,
95 	.fo_chown = vn_chown,
96 	.fo_flags = DFLAG_PASSABLE | DFLAG_SEEKABLE
97 };
98 
99 int
100 vn_open(ndp, flagp, cmode, fp)
101 	struct nameidata *ndp;
102 	int *flagp, cmode;
103 	struct file *fp;
104 {
105 	struct thread *td = ndp->ni_cnd.cn_thread;
106 
107 	return (vn_open_cred(ndp, flagp, cmode, 0, td->td_ucred, fp));
108 }
109 
110 /*
111  * Common code for vnode open operations via a name lookup.
112  * Lookup the vnode and invoke VOP_CREATE if needed.
113  * Check permissions, and call the VOP_OPEN or VOP_CREATE routine.
114  *
115  * Note that this does NOT free nameidata for the successful case,
116  * due to the NDINIT being done elsewhere.
117  */
118 int
119 vn_open_cred(struct nameidata *ndp, int *flagp, int cmode, u_int vn_open_flags,
120     struct ucred *cred, struct file *fp)
121 {
122 	struct vnode *vp;
123 	struct mount *mp;
124 	struct thread *td = ndp->ni_cnd.cn_thread;
125 	struct vattr vat;
126 	struct vattr *vap = &vat;
127 	int fmode, error;
128 	int vfslocked, mpsafe;
129 
130 	mpsafe = ndp->ni_cnd.cn_flags & MPSAFE;
131 restart:
132 	vfslocked = 0;
133 	fmode = *flagp;
134 	if (fmode & O_CREAT) {
135 		ndp->ni_cnd.cn_nameiop = CREATE;
136 		ndp->ni_cnd.cn_flags = ISOPEN | LOCKPARENT | LOCKLEAF |
137 		    MPSAFE;
138 		if ((fmode & O_EXCL) == 0 && (fmode & O_NOFOLLOW) == 0)
139 			ndp->ni_cnd.cn_flags |= FOLLOW;
140 		if (!(vn_open_flags & VN_OPEN_NOAUDIT))
141 			ndp->ni_cnd.cn_flags |= AUDITVNODE1;
142 		bwillwrite();
143 		if ((error = namei(ndp)) != 0)
144 			return (error);
145 		vfslocked = NDHASGIANT(ndp);
146 		if (!mpsafe)
147 			ndp->ni_cnd.cn_flags &= ~MPSAFE;
148 		if (ndp->ni_vp == NULL) {
149 			VATTR_NULL(vap);
150 			vap->va_type = VREG;
151 			vap->va_mode = cmode;
152 			if (fmode & O_EXCL)
153 				vap->va_vaflags |= VA_EXCLUSIVE;
154 			if (vn_start_write(ndp->ni_dvp, &mp, V_NOWAIT) != 0) {
155 				NDFREE(ndp, NDF_ONLY_PNBUF);
156 				vput(ndp->ni_dvp);
157 				VFS_UNLOCK_GIANT(vfslocked);
158 				if ((error = vn_start_write(NULL, &mp,
159 				    V_XSLEEP | PCATCH)) != 0)
160 					return (error);
161 				goto restart;
162 			}
163 #ifdef MAC
164 			error = mac_vnode_check_create(cred, ndp->ni_dvp,
165 			    &ndp->ni_cnd, vap);
166 			if (error == 0)
167 #endif
168 				error = VOP_CREATE(ndp->ni_dvp, &ndp->ni_vp,
169 						   &ndp->ni_cnd, vap);
170 			vput(ndp->ni_dvp);
171 			vn_finished_write(mp);
172 			if (error) {
173 				VFS_UNLOCK_GIANT(vfslocked);
174 				NDFREE(ndp, NDF_ONLY_PNBUF);
175 				return (error);
176 			}
177 			fmode &= ~O_TRUNC;
178 			vp = ndp->ni_vp;
179 		} else {
180 			if (ndp->ni_dvp == ndp->ni_vp)
181 				vrele(ndp->ni_dvp);
182 			else
183 				vput(ndp->ni_dvp);
184 			ndp->ni_dvp = NULL;
185 			vp = ndp->ni_vp;
186 			if (fmode & O_EXCL) {
187 				error = EEXIST;
188 				goto bad;
189 			}
190 			fmode &= ~O_CREAT;
191 		}
192 	} else {
193 		ndp->ni_cnd.cn_nameiop = LOOKUP;
194 		ndp->ni_cnd.cn_flags = ISOPEN |
195 		    ((fmode & O_NOFOLLOW) ? NOFOLLOW : FOLLOW) |
196 		    LOCKLEAF | MPSAFE;
197 		if (!(fmode & FWRITE))
198 			ndp->ni_cnd.cn_flags |= LOCKSHARED;
199 		if (!(vn_open_flags & VN_OPEN_NOAUDIT))
200 			ndp->ni_cnd.cn_flags |= AUDITVNODE1;
201 		if ((error = namei(ndp)) != 0)
202 			return (error);
203 		if (!mpsafe)
204 			ndp->ni_cnd.cn_flags &= ~MPSAFE;
205 		vfslocked = NDHASGIANT(ndp);
206 		vp = ndp->ni_vp;
207 	}
208 	error = vn_open_vnode(vp, fmode, cred, td, fp);
209 	if (error)
210 		goto bad;
211 	*flagp = fmode;
212 	if (!mpsafe)
213 		VFS_UNLOCK_GIANT(vfslocked);
214 	return (0);
215 bad:
216 	NDFREE(ndp, NDF_ONLY_PNBUF);
217 	vput(vp);
218 	VFS_UNLOCK_GIANT(vfslocked);
219 	*flagp = fmode;
220 	ndp->ni_vp = NULL;
221 	return (error);
222 }
223 
224 /*
225  * Common code for vnode open operations once a vnode is located.
226  * Check permissions, and call the VOP_OPEN routine.
227  */
228 int
229 vn_open_vnode(struct vnode *vp, int fmode, struct ucred *cred,
230     struct thread *td, struct file *fp)
231 {
232 	struct mount *mp;
233 	accmode_t accmode;
234 	struct flock lf;
235 	int error, have_flock, lock_flags, type;
236 
237 	VFS_ASSERT_GIANT(vp->v_mount);
238 	if (vp->v_type == VLNK)
239 		return (EMLINK);
240 	if (vp->v_type == VSOCK)
241 		return (EOPNOTSUPP);
242 	if (vp->v_type != VDIR && fmode & O_DIRECTORY)
243 		return (ENOTDIR);
244 	accmode = 0;
245 	if (fmode & (FWRITE | O_TRUNC)) {
246 		if (vp->v_type == VDIR)
247 			return (EISDIR);
248 		accmode |= VWRITE;
249 	}
250 	if (fmode & FREAD)
251 		accmode |= VREAD;
252 	if (fmode & FEXEC)
253 		accmode |= VEXEC;
254 	if ((fmode & O_APPEND) && (fmode & FWRITE))
255 		accmode |= VAPPEND;
256 #ifdef MAC
257 	error = mac_vnode_check_open(cred, vp, accmode);
258 	if (error)
259 		return (error);
260 #endif
261 	if ((fmode & O_CREAT) == 0) {
262 		if (accmode & VWRITE) {
263 			error = vn_writechk(vp);
264 			if (error)
265 				return (error);
266 		}
267 		if (accmode) {
268 		        error = VOP_ACCESS(vp, accmode, cred, td);
269 			if (error)
270 				return (error);
271 		}
272 	}
273 	if ((error = VOP_OPEN(vp, fmode, cred, td, fp)) != 0)
274 		return (error);
275 
276 	if (fmode & (O_EXLOCK | O_SHLOCK)) {
277 		KASSERT(fp != NULL, ("open with flock requires fp"));
278 		lock_flags = VOP_ISLOCKED(vp);
279 		VOP_UNLOCK(vp, 0);
280 		lf.l_whence = SEEK_SET;
281 		lf.l_start = 0;
282 		lf.l_len = 0;
283 		if (fmode & O_EXLOCK)
284 			lf.l_type = F_WRLCK;
285 		else
286 			lf.l_type = F_RDLCK;
287 		type = F_FLOCK;
288 		if ((fmode & FNONBLOCK) == 0)
289 			type |= F_WAIT;
290 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, type);
291 		have_flock = (error == 0);
292 		vn_lock(vp, lock_flags | LK_RETRY);
293 		if (error == 0 && vp->v_iflag & VI_DOOMED)
294 			error = ENOENT;
295 		/*
296 		 * Another thread might have used this vnode as an
297 		 * executable while the vnode lock was dropped.
298 		 * Ensure the vnode is still able to be opened for
299 		 * writing after the lock has been obtained.
300 		 */
301 		if (error == 0 && accmode & VWRITE)
302 			error = vn_writechk(vp);
303 		if (error) {
304 			VOP_UNLOCK(vp, 0);
305 			if (have_flock) {
306 				lf.l_whence = SEEK_SET;
307 				lf.l_start = 0;
308 				lf.l_len = 0;
309 				lf.l_type = F_UNLCK;
310 				(void) VOP_ADVLOCK(vp, fp, F_UNLCK, &lf,
311 				    F_FLOCK);
312 			}
313 			vn_start_write(vp, &mp, V_WAIT);
314 			vn_lock(vp, lock_flags | LK_RETRY);
315 			(void)VOP_CLOSE(vp, fmode, cred, td);
316 			vn_finished_write(mp);
317 			return (error);
318 		}
319 		fp->f_flag |= FHASLOCK;
320 	}
321 	if (fmode & FWRITE) {
322 		vp->v_writecount++;
323 		CTR3(KTR_VFS, "%s: vp %p v_writecount increased to %d",
324 		    __func__, vp, vp->v_writecount);
325 	}
326 	ASSERT_VOP_LOCKED(vp, "vn_open_vnode");
327 	return (0);
328 }
329 
330 /*
331  * Check for write permissions on the specified vnode.
332  * Prototype text segments cannot be written.
333  */
334 int
335 vn_writechk(vp)
336 	register struct vnode *vp;
337 {
338 
339 	ASSERT_VOP_LOCKED(vp, "vn_writechk");
340 	/*
341 	 * If there's shared text associated with
342 	 * the vnode, try to free it up once.  If
343 	 * we fail, we can't allow writing.
344 	 */
345 	if (vp->v_vflag & VV_TEXT)
346 		return (ETXTBSY);
347 
348 	return (0);
349 }
350 
351 /*
352  * Vnode close call
353  */
354 int
355 vn_close(vp, flags, file_cred, td)
356 	register struct vnode *vp;
357 	int flags;
358 	struct ucred *file_cred;
359 	struct thread *td;
360 {
361 	struct mount *mp;
362 	int error, lock_flags;
363 
364 	if (!(flags & FWRITE) && vp->v_mount != NULL &&
365 	    vp->v_mount->mnt_kern_flag & MNTK_EXTENDED_SHARED)
366 		lock_flags = LK_SHARED;
367 	else
368 		lock_flags = LK_EXCLUSIVE;
369 
370 	VFS_ASSERT_GIANT(vp->v_mount);
371 
372 	vn_start_write(vp, &mp, V_WAIT);
373 	vn_lock(vp, lock_flags | LK_RETRY);
374 	if (flags & FWRITE) {
375 		VNASSERT(vp->v_writecount > 0, vp,
376 		    ("vn_close: negative writecount"));
377 		vp->v_writecount--;
378 		CTR3(KTR_VFS, "%s: vp %p v_writecount decreased to %d",
379 		    __func__, vp, vp->v_writecount);
380 	}
381 	error = VOP_CLOSE(vp, flags, file_cred, td);
382 	vput(vp);
383 	vn_finished_write(mp);
384 	return (error);
385 }
386 
387 /*
388  * Heuristic to detect sequential operation.
389  */
390 static int
391 sequential_heuristic(struct uio *uio, struct file *fp)
392 {
393 
394 	if (atomic_load_acq_int(&(fp->f_flag)) & FRDAHEAD)
395 		return (fp->f_seqcount << IO_SEQSHIFT);
396 
397 	/*
398 	 * Offset 0 is handled specially.  open() sets f_seqcount to 1 so
399 	 * that the first I/O is normally considered to be slightly
400 	 * sequential.  Seeking to offset 0 doesn't change sequentiality
401 	 * unless previous seeks have reduced f_seqcount to 0, in which
402 	 * case offset 0 is not special.
403 	 */
404 	if ((uio->uio_offset == 0 && fp->f_seqcount > 0) ||
405 	    uio->uio_offset == fp->f_nextoff) {
406 		/*
407 		 * f_seqcount is in units of fixed-size blocks so that it
408 		 * depends mainly on the amount of sequential I/O and not
409 		 * much on the number of sequential I/O's.  The fixed size
410 		 * of 16384 is hard-coded here since it is (not quite) just
411 		 * a magic size that works well here.  This size is more
412 		 * closely related to the best I/O size for real disks than
413 		 * to any block size used by software.
414 		 */
415 		fp->f_seqcount += howmany(uio->uio_resid, 16384);
416 		if (fp->f_seqcount > IO_SEQMAX)
417 			fp->f_seqcount = IO_SEQMAX;
418 		return (fp->f_seqcount << IO_SEQSHIFT);
419 	}
420 
421 	/* Not sequential.  Quickly draw-down sequentiality. */
422 	if (fp->f_seqcount > 1)
423 		fp->f_seqcount = 1;
424 	else
425 		fp->f_seqcount = 0;
426 	return (0);
427 }
428 
429 /*
430  * Package up an I/O request on a vnode into a uio and do it.
431  */
432 int
433 vn_rdwr(enum uio_rw rw, struct vnode *vp, void *base, int len, off_t offset,
434     enum uio_seg segflg, int ioflg, struct ucred *active_cred,
435     struct ucred *file_cred, ssize_t *aresid, struct thread *td)
436 {
437 	struct uio auio;
438 	struct iovec aiov;
439 	struct mount *mp;
440 	struct ucred *cred;
441 	void *rl_cookie;
442 	int error, lock_flags;
443 
444 	VFS_ASSERT_GIANT(vp->v_mount);
445 
446 	auio.uio_iov = &aiov;
447 	auio.uio_iovcnt = 1;
448 	aiov.iov_base = base;
449 	aiov.iov_len = len;
450 	auio.uio_resid = len;
451 	auio.uio_offset = offset;
452 	auio.uio_segflg = segflg;
453 	auio.uio_rw = rw;
454 	auio.uio_td = td;
455 	error = 0;
456 
457 	if ((ioflg & IO_NODELOCKED) == 0) {
458 		if (rw == UIO_READ) {
459 			rl_cookie = vn_rangelock_rlock(vp, offset,
460 			    offset + len);
461 		} else {
462 			rl_cookie = vn_rangelock_wlock(vp, offset,
463 			    offset + len);
464 		}
465 		mp = NULL;
466 		if (rw == UIO_WRITE) {
467 			if (vp->v_type != VCHR &&
468 			    (error = vn_start_write(vp, &mp, V_WAIT | PCATCH))
469 			    != 0)
470 				goto out;
471 			if (MNT_SHARED_WRITES(mp) ||
472 			    ((mp == NULL) && MNT_SHARED_WRITES(vp->v_mount)))
473 				lock_flags = LK_SHARED;
474 			else
475 				lock_flags = LK_EXCLUSIVE;
476 		} else
477 			lock_flags = LK_SHARED;
478 		vn_lock(vp, lock_flags | LK_RETRY);
479 	} else
480 		rl_cookie = NULL;
481 
482 	ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
483 #ifdef MAC
484 	if ((ioflg & IO_NOMACCHECK) == 0) {
485 		if (rw == UIO_READ)
486 			error = mac_vnode_check_read(active_cred, file_cred,
487 			    vp);
488 		else
489 			error = mac_vnode_check_write(active_cred, file_cred,
490 			    vp);
491 	}
492 #endif
493 	if (error == 0) {
494 		if (file_cred != NULL)
495 			cred = file_cred;
496 		else
497 			cred = active_cred;
498 		if (rw == UIO_READ)
499 			error = VOP_READ(vp, &auio, ioflg, cred);
500 		else
501 			error = VOP_WRITE(vp, &auio, ioflg, cred);
502 	}
503 	if (aresid)
504 		*aresid = auio.uio_resid;
505 	else
506 		if (auio.uio_resid && error == 0)
507 			error = EIO;
508 	if ((ioflg & IO_NODELOCKED) == 0) {
509 		VOP_UNLOCK(vp, 0);
510 		if (mp != NULL)
511 			vn_finished_write(mp);
512 	}
513  out:
514 	if (rl_cookie != NULL)
515 		vn_rangelock_unlock(vp, rl_cookie);
516 	return (error);
517 }
518 
519 /*
520  * Package up an I/O request on a vnode into a uio and do it.  The I/O
521  * request is split up into smaller chunks and we try to avoid saturating
522  * the buffer cache while potentially holding a vnode locked, so we
523  * check bwillwrite() before calling vn_rdwr().  We also call kern_yield()
524  * to give other processes a chance to lock the vnode (either other processes
525  * core'ing the same binary, or unrelated processes scanning the directory).
526  */
527 int
528 vn_rdwr_inchunks(rw, vp, base, len, offset, segflg, ioflg, active_cred,
529     file_cred, aresid, td)
530 	enum uio_rw rw;
531 	struct vnode *vp;
532 	void *base;
533 	size_t len;
534 	off_t offset;
535 	enum uio_seg segflg;
536 	int ioflg;
537 	struct ucred *active_cred;
538 	struct ucred *file_cred;
539 	size_t *aresid;
540 	struct thread *td;
541 {
542 	int error = 0;
543 	ssize_t iaresid;
544 
545 	VFS_ASSERT_GIANT(vp->v_mount);
546 
547 	do {
548 		int chunk;
549 
550 		/*
551 		 * Force `offset' to a multiple of MAXBSIZE except possibly
552 		 * for the first chunk, so that filesystems only need to
553 		 * write full blocks except possibly for the first and last
554 		 * chunks.
555 		 */
556 		chunk = MAXBSIZE - (uoff_t)offset % MAXBSIZE;
557 
558 		if (chunk > len)
559 			chunk = len;
560 		if (rw != UIO_READ && vp->v_type == VREG)
561 			bwillwrite();
562 		iaresid = 0;
563 		error = vn_rdwr(rw, vp, base, chunk, offset, segflg,
564 		    ioflg, active_cred, file_cred, &iaresid, td);
565 		len -= chunk;	/* aresid calc already includes length */
566 		if (error)
567 			break;
568 		offset += chunk;
569 		base = (char *)base + chunk;
570 		kern_yield(PRI_USER);
571 	} while (len);
572 	if (aresid)
573 		*aresid = len + iaresid;
574 	return (error);
575 }
576 
577 off_t
578 foffset_lock(struct file *fp, int flags)
579 {
580 	struct mtx *mtxp;
581 	off_t res;
582 
583 	KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
584 
585 #if OFF_MAX <= LONG_MAX
586 	/*
587 	 * Caller only wants the current f_offset value.  Assume that
588 	 * the long and shorter integer types reads are atomic.
589 	 */
590 	if ((flags & FOF_NOLOCK) != 0)
591 		return (fp->f_offset);
592 #endif
593 
594 	/*
595 	 * According to McKusick the vn lock was protecting f_offset here.
596 	 * It is now protected by the FOFFSET_LOCKED flag.
597 	 */
598 	mtxp = mtx_pool_find(mtxpool_sleep, fp);
599 	mtx_lock(mtxp);
600 	if ((flags & FOF_NOLOCK) == 0) {
601 		while (fp->f_vnread_flags & FOFFSET_LOCKED) {
602 			fp->f_vnread_flags |= FOFFSET_LOCK_WAITING;
603 			msleep(&fp->f_vnread_flags, mtxp, PUSER -1,
604 			    "vofflock", 0);
605 		}
606 		fp->f_vnread_flags |= FOFFSET_LOCKED;
607 	}
608 	res = fp->f_offset;
609 	mtx_unlock(mtxp);
610 	return (res);
611 }
612 
613 void
614 foffset_unlock(struct file *fp, off_t val, int flags)
615 {
616 	struct mtx *mtxp;
617 
618 	KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
619 
620 #if OFF_MAX <= LONG_MAX
621 	if ((flags & FOF_NOLOCK) != 0) {
622 		if ((flags & FOF_NOUPDATE) == 0)
623 			fp->f_offset = val;
624 		if ((flags & FOF_NEXTOFF) != 0)
625 			fp->f_nextoff = val;
626 		return;
627 	}
628 #endif
629 
630 	mtxp = mtx_pool_find(mtxpool_sleep, fp);
631 	mtx_lock(mtxp);
632 	if ((flags & FOF_NOUPDATE) == 0)
633 		fp->f_offset = val;
634 	if ((flags & FOF_NEXTOFF) != 0)
635 		fp->f_nextoff = val;
636 	if ((flags & FOF_NOLOCK) == 0) {
637 		KASSERT((fp->f_vnread_flags & FOFFSET_LOCKED) != 0,
638 		    ("Lost FOFFSET_LOCKED"));
639 		if (fp->f_vnread_flags & FOFFSET_LOCK_WAITING)
640 			wakeup(&fp->f_vnread_flags);
641 		fp->f_vnread_flags = 0;
642 	}
643 	mtx_unlock(mtxp);
644 }
645 
646 void
647 foffset_lock_uio(struct file *fp, struct uio *uio, int flags)
648 {
649 
650 	if ((flags & FOF_OFFSET) == 0)
651 		uio->uio_offset = foffset_lock(fp, flags);
652 }
653 
654 void
655 foffset_unlock_uio(struct file *fp, struct uio *uio, int flags)
656 {
657 
658 	if ((flags & FOF_OFFSET) == 0)
659 		foffset_unlock(fp, uio->uio_offset, flags);
660 }
661 
662 static int
663 get_advice(struct file *fp, struct uio *uio)
664 {
665 	struct mtx *mtxp;
666 	int ret;
667 
668 	ret = POSIX_FADV_NORMAL;
669 	if (fp->f_advice == NULL)
670 		return (ret);
671 
672 	mtxp = mtx_pool_find(mtxpool_sleep, fp);
673 	mtx_lock(mtxp);
674 	if (uio->uio_offset >= fp->f_advice->fa_start &&
675 	    uio->uio_offset + uio->uio_resid <= fp->f_advice->fa_end)
676 		ret = fp->f_advice->fa_advice;
677 	mtx_unlock(mtxp);
678 	return (ret);
679 }
680 
681 /*
682  * File table vnode read routine.
683  */
684 static int
685 vn_read(fp, uio, active_cred, flags, td)
686 	struct file *fp;
687 	struct uio *uio;
688 	struct ucred *active_cred;
689 	int flags;
690 	struct thread *td;
691 {
692 	struct vnode *vp;
693 	struct mtx *mtxp;
694 	int error, ioflag;
695 	int advice, vfslocked;
696 	off_t offset, start, end;
697 
698 	KASSERT(uio->uio_td == td, ("uio_td %p is not td %p",
699 	    uio->uio_td, td));
700 	KASSERT(flags & FOF_OFFSET, ("No FOF_OFFSET"));
701 	vp = fp->f_vnode;
702 	ioflag = 0;
703 	if (fp->f_flag & FNONBLOCK)
704 		ioflag |= IO_NDELAY;
705 	if (fp->f_flag & O_DIRECT)
706 		ioflag |= IO_DIRECT;
707 	advice = get_advice(fp, uio);
708 	vfslocked = VFS_LOCK_GIANT(vp->v_mount);
709 	vn_lock(vp, LK_SHARED | LK_RETRY);
710 
711 	switch (advice) {
712 	case POSIX_FADV_NORMAL:
713 	case POSIX_FADV_SEQUENTIAL:
714 	case POSIX_FADV_NOREUSE:
715 		ioflag |= sequential_heuristic(uio, fp);
716 		break;
717 	case POSIX_FADV_RANDOM:
718 		/* Disable read-ahead for random I/O. */
719 		break;
720 	}
721 	offset = uio->uio_offset;
722 
723 #ifdef MAC
724 	error = mac_vnode_check_read(active_cred, fp->f_cred, vp);
725 	if (error == 0)
726 #endif
727 		error = VOP_READ(vp, uio, ioflag, fp->f_cred);
728 	fp->f_nextoff = uio->uio_offset;
729 	VOP_UNLOCK(vp, 0);
730 	if (error == 0 && advice == POSIX_FADV_NOREUSE &&
731 	    offset != uio->uio_offset) {
732 		/*
733 		 * Use POSIX_FADV_DONTNEED to flush clean pages and
734 		 * buffers for the backing file after a
735 		 * POSIX_FADV_NOREUSE read(2).  To optimize the common
736 		 * case of using POSIX_FADV_NOREUSE with sequential
737 		 * access, track the previous implicit DONTNEED
738 		 * request and grow this request to include the
739 		 * current read(2) in addition to the previous
740 		 * DONTNEED.  With purely sequential access this will
741 		 * cause the DONTNEED requests to continously grow to
742 		 * cover all of the previously read regions of the
743 		 * file.  This allows filesystem blocks that are
744 		 * accessed by multiple calls to read(2) to be flushed
745 		 * once the last read(2) finishes.
746 		 */
747 		start = offset;
748 		end = uio->uio_offset - 1;
749 		mtxp = mtx_pool_find(mtxpool_sleep, fp);
750 		mtx_lock(mtxp);
751 		if (fp->f_advice != NULL &&
752 		    fp->f_advice->fa_advice == POSIX_FADV_NOREUSE) {
753 			if (start != 0 && fp->f_advice->fa_prevend + 1 == start)
754 				start = fp->f_advice->fa_prevstart;
755 			else if (fp->f_advice->fa_prevstart != 0 &&
756 			    fp->f_advice->fa_prevstart == end + 1)
757 				end = fp->f_advice->fa_prevend;
758 			fp->f_advice->fa_prevstart = start;
759 			fp->f_advice->fa_prevend = end;
760 		}
761 		mtx_unlock(mtxp);
762 		error = VOP_ADVISE(vp, start, end, POSIX_FADV_DONTNEED);
763 	}
764 	VFS_UNLOCK_GIANT(vfslocked);
765 	return (error);
766 }
767 
768 /*
769  * File table vnode write routine.
770  */
771 static int
772 vn_write(fp, uio, active_cred, flags, td)
773 	struct file *fp;
774 	struct uio *uio;
775 	struct ucred *active_cred;
776 	int flags;
777 	struct thread *td;
778 {
779 	struct vnode *vp;
780 	struct mount *mp;
781 	struct mtx *mtxp;
782 	int error, ioflag, lock_flags;
783 	int advice, vfslocked;
784 	off_t offset, start, end;
785 
786 	KASSERT(uio->uio_td == td, ("uio_td %p is not td %p",
787 	    uio->uio_td, td));
788 	KASSERT(flags & FOF_OFFSET, ("No FOF_OFFSET"));
789 	vp = fp->f_vnode;
790 	vfslocked = VFS_LOCK_GIANT(vp->v_mount);
791 	if (vp->v_type == VREG)
792 		bwillwrite();
793 	ioflag = IO_UNIT;
794 	if (vp->v_type == VREG && (fp->f_flag & O_APPEND))
795 		ioflag |= IO_APPEND;
796 	if (fp->f_flag & FNONBLOCK)
797 		ioflag |= IO_NDELAY;
798 	if (fp->f_flag & O_DIRECT)
799 		ioflag |= IO_DIRECT;
800 	if ((fp->f_flag & O_FSYNC) ||
801 	    (vp->v_mount && (vp->v_mount->mnt_flag & MNT_SYNCHRONOUS)))
802 		ioflag |= IO_SYNC;
803 	mp = NULL;
804 	if (vp->v_type != VCHR &&
805 	    (error = vn_start_write(vp, &mp, V_WAIT | PCATCH)) != 0)
806 		goto unlock;
807 
808 	advice = get_advice(fp, uio);
809 
810 	if ((MNT_SHARED_WRITES(mp) ||
811 	    ((mp == NULL) && MNT_SHARED_WRITES(vp->v_mount))) &&
812 	    (flags & FOF_OFFSET) != 0) {
813 		lock_flags = LK_SHARED;
814 	} else {
815 		lock_flags = LK_EXCLUSIVE;
816 	}
817 
818 	vn_lock(vp, lock_flags | LK_RETRY);
819 	switch (advice) {
820 	case POSIX_FADV_NORMAL:
821 	case POSIX_FADV_SEQUENTIAL:
822 	case POSIX_FADV_NOREUSE:
823 		ioflag |= sequential_heuristic(uio, fp);
824 		break;
825 	case POSIX_FADV_RANDOM:
826 		/* XXX: Is this correct? */
827 		break;
828 	}
829 	offset = uio->uio_offset;
830 
831 #ifdef MAC
832 	error = mac_vnode_check_write(active_cred, fp->f_cred, vp);
833 	if (error == 0)
834 #endif
835 		error = VOP_WRITE(vp, uio, ioflag, fp->f_cred);
836 	fp->f_nextoff = uio->uio_offset;
837 	VOP_UNLOCK(vp, 0);
838 	if (vp->v_type != VCHR)
839 		vn_finished_write(mp);
840 	if (error == 0 && advice == POSIX_FADV_NOREUSE &&
841 	    offset != uio->uio_offset) {
842 		/*
843 		 * Use POSIX_FADV_DONTNEED to flush clean pages and
844 		 * buffers for the backing file after a
845 		 * POSIX_FADV_NOREUSE write(2).  To optimize the
846 		 * common case of using POSIX_FADV_NOREUSE with
847 		 * sequential access, track the previous implicit
848 		 * DONTNEED request and grow this request to include
849 		 * the current write(2) in addition to the previous
850 		 * DONTNEED.  With purely sequential access this will
851 		 * cause the DONTNEED requests to continously grow to
852 		 * cover all of the previously written regions of the
853 		 * file.
854 		 *
855 		 * Note that the blocks just written are almost
856 		 * certainly still dirty, so this only works when
857 		 * VOP_ADVISE() calls from subsequent writes push out
858 		 * the data written by this write(2) once the backing
859 		 * buffers are clean.  However, as compared to forcing
860 		 * IO_DIRECT, this gives much saner behavior.  Write
861 		 * clustering is still allowed, and clean pages are
862 		 * merely moved to the cache page queue rather than
863 		 * outright thrown away.  This means a subsequent
864 		 * read(2) can still avoid hitting the disk if the
865 		 * pages have not been reclaimed.
866 		 *
867 		 * This does make POSIX_FADV_NOREUSE largely useless
868 		 * with non-sequential access.  However, sequential
869 		 * access is the more common use case and the flag is
870 		 * merely advisory.
871 		 */
872 		start = offset;
873 		end = uio->uio_offset - 1;
874 		mtxp = mtx_pool_find(mtxpool_sleep, fp);
875 		mtx_lock(mtxp);
876 		if (fp->f_advice != NULL &&
877 		    fp->f_advice->fa_advice == POSIX_FADV_NOREUSE) {
878 			if (start != 0 && fp->f_advice->fa_prevend + 1 == start)
879 				start = fp->f_advice->fa_prevstart;
880 			else if (fp->f_advice->fa_prevstart != 0 &&
881 			    fp->f_advice->fa_prevstart == end + 1)
882 				end = fp->f_advice->fa_prevend;
883 			fp->f_advice->fa_prevstart = start;
884 			fp->f_advice->fa_prevend = end;
885 		}
886 		mtx_unlock(mtxp);
887 		error = VOP_ADVISE(vp, start, end, POSIX_FADV_DONTNEED);
888 	}
889 
890 unlock:
891 	VFS_UNLOCK_GIANT(vfslocked);
892 	return (error);
893 }
894 
895 static const int io_hold_cnt = 16;
896 static int vn_io_fault_enable = 1;
897 SYSCTL_INT(_debug, OID_AUTO, vn_io_fault_enable, CTLFLAG_RW,
898     &vn_io_fault_enable, 0, "Enable vn_io_fault lock avoidance");
899 static unsigned long vn_io_faults_cnt;
900 SYSCTL_LONG(_debug, OID_AUTO, vn_io_faults, CTLFLAG_RD,
901     &vn_io_faults_cnt, 0, "Count of vn_io_fault lock avoidance triggers");
902 
903 /*
904  * The vn_io_fault() is a wrapper around vn_read() and vn_write() to
905  * prevent the following deadlock:
906  *
907  * Assume that the thread A reads from the vnode vp1 into userspace
908  * buffer buf1 backed by the pages of vnode vp2.  If a page in buf1 is
909  * currently not resident, then system ends up with the call chain
910  *   vn_read() -> VOP_READ(vp1) -> uiomove() -> [Page Fault] ->
911  *     vm_fault(buf1) -> vnode_pager_getpages(vp2) -> VOP_GETPAGES(vp2)
912  * which establishes lock order vp1->vn_lock, then vp2->vn_lock.
913  * If, at the same time, thread B reads from vnode vp2 into buffer buf2
914  * backed by the pages of vnode vp1, and some page in buf2 is not
915  * resident, we get a reversed order vp2->vn_lock, then vp1->vn_lock.
916  *
917  * To prevent the lock order reversal and deadlock, vn_io_fault() does
918  * not allow page faults to happen during VOP_READ() or VOP_WRITE().
919  * Instead, it first tries to do the whole range i/o with pagefaults
920  * disabled. If all pages in the i/o buffer are resident and mapped,
921  * VOP will succeed (ignoring the genuine filesystem errors).
922  * Otherwise, we get back EFAULT, and vn_io_fault() falls back to do
923  * i/o in chunks, with all pages in the chunk prefaulted and held
924  * using vm_fault_quick_hold_pages().
925  *
926  * Filesystems using this deadlock avoidance scheme should use the
927  * array of the held pages from uio, saved in the curthread->td_ma,
928  * instead of doing uiomove().  A helper function
929  * vn_io_fault_uiomove() converts uiomove request into
930  * uiomove_fromphys() over td_ma array.
931  *
932  * Since vnode locks do not cover the whole i/o anymore, rangelocks
933  * make the current i/o request atomic with respect to other i/os and
934  * truncations.
935  */
936 static int
937 vn_io_fault(struct file *fp, struct uio *uio, struct ucred *active_cred,
938     int flags, struct thread *td)
939 {
940 	vm_page_t ma[io_hold_cnt + 2];
941 	struct uio *uio_clone, short_uio;
942 	struct iovec short_iovec[1];
943 	fo_rdwr_t *doio;
944 	struct vnode *vp;
945 	void *rl_cookie;
946 	struct mount *mp;
947 	vm_page_t *prev_td_ma;
948 	int cnt, error, save, saveheld, prev_td_ma_cnt;
949 	vm_offset_t addr, end;
950 	vm_prot_t prot;
951 	size_t len, resid;
952 	ssize_t adv;
953 
954 	if (uio->uio_rw == UIO_READ)
955 		doio = vn_read;
956 	else
957 		doio = vn_write;
958 	vp = fp->f_vnode;
959 	foffset_lock_uio(fp, uio, flags);
960 
961 	if (uio->uio_segflg != UIO_USERSPACE || vp->v_type != VREG ||
962 	    ((mp = vp->v_mount) != NULL &&
963 	    (mp->mnt_kern_flag & MNTK_NO_IOPF) == 0) ||
964 	    !vn_io_fault_enable) {
965 		error = doio(fp, uio, active_cred, flags | FOF_OFFSET, td);
966 		goto out_last;
967 	}
968 
969 	/*
970 	 * The UFS follows IO_UNIT directive and replays back both
971 	 * uio_offset and uio_resid if an error is encountered during the
972 	 * operation.  But, since the iovec may be already advanced,
973 	 * uio is still in an inconsistent state.
974 	 *
975 	 * Cache a copy of the original uio, which is advanced to the redo
976 	 * point using UIO_NOCOPY below.
977 	 */
978 	uio_clone = cloneuio(uio);
979 	resid = uio->uio_resid;
980 
981 	short_uio.uio_segflg = UIO_USERSPACE;
982 	short_uio.uio_rw = uio->uio_rw;
983 	short_uio.uio_td = uio->uio_td;
984 
985 	if (uio->uio_rw == UIO_READ) {
986 		prot = VM_PROT_WRITE;
987 		rl_cookie = vn_rangelock_rlock(vp, uio->uio_offset,
988 		    uio->uio_offset + uio->uio_resid);
989 	} else {
990 		prot = VM_PROT_READ;
991 		if ((fp->f_flag & O_APPEND) != 0 || (flags & FOF_OFFSET) == 0)
992 			/* For appenders, punt and lock the whole range. */
993 			rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
994 		else
995 			rl_cookie = vn_rangelock_wlock(vp, uio->uio_offset,
996 			    uio->uio_offset + uio->uio_resid);
997 	}
998 
999 	save = vm_fault_disable_pagefaults();
1000 	error = doio(fp, uio, active_cred, flags | FOF_OFFSET, td);
1001 	if (error != EFAULT)
1002 		goto out;
1003 
1004 	atomic_add_long(&vn_io_faults_cnt, 1);
1005 	uio_clone->uio_segflg = UIO_NOCOPY;
1006 	uiomove(NULL, resid - uio->uio_resid, uio_clone);
1007 	uio_clone->uio_segflg = uio->uio_segflg;
1008 
1009 	saveheld = curthread_pflags_set(TDP_UIOHELD);
1010 	prev_td_ma = td->td_ma;
1011 	prev_td_ma_cnt = td->td_ma_cnt;
1012 
1013 	while (uio_clone->uio_resid != 0) {
1014 		len = uio_clone->uio_iov->iov_len;
1015 		if (len == 0) {
1016 			KASSERT(uio_clone->uio_iovcnt >= 1,
1017 			    ("iovcnt underflow"));
1018 			uio_clone->uio_iov++;
1019 			uio_clone->uio_iovcnt--;
1020 			continue;
1021 		}
1022 
1023 		addr = (vm_offset_t)uio_clone->uio_iov->iov_base;
1024 		end = round_page(addr + len);
1025 		cnt = howmany(end - trunc_page(addr), PAGE_SIZE);
1026 		/*
1027 		 * A perfectly misaligned address and length could cause
1028 		 * both the start and the end of the chunk to use partial
1029 		 * page.  +2 accounts for such a situation.
1030 		 */
1031 		if (cnt > io_hold_cnt + 2) {
1032 			len = io_hold_cnt * PAGE_SIZE;
1033 			KASSERT(howmany(round_page(addr + len) -
1034 			    trunc_page(addr), PAGE_SIZE) <= io_hold_cnt + 2,
1035 			    ("cnt overflow"));
1036 		}
1037 		cnt = vm_fault_quick_hold_pages(&td->td_proc->p_vmspace->vm_map,
1038 		    addr, len, prot, ma, io_hold_cnt + 2);
1039 		if (cnt == -1) {
1040 			error = EFAULT;
1041 			break;
1042 		}
1043 		short_uio.uio_iov = &short_iovec[0];
1044 		short_iovec[0].iov_base = (void *)addr;
1045 		short_uio.uio_iovcnt = 1;
1046 		short_uio.uio_resid = short_iovec[0].iov_len = len;
1047 		short_uio.uio_offset = uio_clone->uio_offset;
1048 		td->td_ma = ma;
1049 		td->td_ma_cnt = cnt;
1050 
1051 		error = doio(fp, &short_uio, active_cred, flags | FOF_OFFSET,
1052 		    td);
1053 		vm_page_unhold_pages(ma, cnt);
1054 		adv = len - short_uio.uio_resid;
1055 
1056 		uio_clone->uio_iov->iov_base =
1057 		    (char *)uio_clone->uio_iov->iov_base + adv;
1058 		uio_clone->uio_iov->iov_len -= adv;
1059 		uio_clone->uio_resid -= adv;
1060 		uio_clone->uio_offset += adv;
1061 
1062 		uio->uio_resid -= adv;
1063 		uio->uio_offset += adv;
1064 
1065 		if (error != 0 || adv == 0)
1066 			break;
1067 	}
1068 	td->td_ma = prev_td_ma;
1069 	td->td_ma_cnt = prev_td_ma_cnt;
1070 	curthread_pflags_restore(saveheld);
1071 out:
1072 	vm_fault_enable_pagefaults(save);
1073 	vn_rangelock_unlock(vp, rl_cookie);
1074 	free(uio_clone, M_IOV);
1075 out_last:
1076 	foffset_unlock_uio(fp, uio, flags);
1077 	return (error);
1078 }
1079 
1080 /*
1081  * Helper function to perform the requested uiomove operation using
1082  * the held pages for io->uio_iov[0].iov_base buffer instead of
1083  * copyin/copyout.  Access to the pages with uiomove_fromphys()
1084  * instead of iov_base prevents page faults that could occur due to
1085  * pmap_collect() invalidating the mapping created by
1086  * vm_fault_quick_hold_pages(), or pageout daemon, page laundry or
1087  * object cleanup revoking the write access from page mappings.
1088  *
1089  * Filesystems specified MNTK_NO_IOPF shall use vn_io_fault_uiomove()
1090  * instead of plain uiomove().
1091  */
1092 int
1093 vn_io_fault_uiomove(char *data, int xfersize, struct uio *uio)
1094 {
1095 	struct uio transp_uio;
1096 	struct iovec transp_iov[1];
1097 	struct thread *td;
1098 	size_t adv;
1099 	int error, pgadv;
1100 
1101 	td = curthread;
1102 	if ((td->td_pflags & TDP_UIOHELD) == 0 ||
1103 	    uio->uio_segflg != UIO_USERSPACE)
1104 		return (uiomove(data, xfersize, uio));
1105 
1106 	KASSERT(uio->uio_iovcnt == 1, ("uio_iovcnt %d", uio->uio_iovcnt));
1107 	transp_iov[0].iov_base = data;
1108 	transp_uio.uio_iov = &transp_iov[0];
1109 	transp_uio.uio_iovcnt = 1;
1110 	if (xfersize > uio->uio_resid)
1111 		xfersize = uio->uio_resid;
1112 	transp_uio.uio_resid = transp_iov[0].iov_len = xfersize;
1113 	transp_uio.uio_offset = 0;
1114 	transp_uio.uio_segflg = UIO_SYSSPACE;
1115 	/*
1116 	 * Since transp_iov points to data, and td_ma page array
1117 	 * corresponds to original uio->uio_iov, we need to invert the
1118 	 * direction of the i/o operation as passed to
1119 	 * uiomove_fromphys().
1120 	 */
1121 	switch (uio->uio_rw) {
1122 	case UIO_WRITE:
1123 		transp_uio.uio_rw = UIO_READ;
1124 		break;
1125 	case UIO_READ:
1126 		transp_uio.uio_rw = UIO_WRITE;
1127 		break;
1128 	}
1129 	transp_uio.uio_td = uio->uio_td;
1130 	error = uiomove_fromphys(td->td_ma,
1131 	    ((vm_offset_t)uio->uio_iov->iov_base) & PAGE_MASK,
1132 	    xfersize, &transp_uio);
1133 	adv = xfersize - transp_uio.uio_resid;
1134 	pgadv =
1135 	    (((vm_offset_t)uio->uio_iov->iov_base + adv) >> PAGE_SHIFT) -
1136 	    (((vm_offset_t)uio->uio_iov->iov_base) >> PAGE_SHIFT);
1137 	td->td_ma += pgadv;
1138 	KASSERT(td->td_ma_cnt >= pgadv, ("consumed pages %d %d", td->td_ma_cnt,
1139 	    pgadv));
1140 	td->td_ma_cnt -= pgadv;
1141 	uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + adv;
1142 	uio->uio_iov->iov_len -= adv;
1143 	uio->uio_resid -= adv;
1144 	uio->uio_offset += adv;
1145 	return (error);
1146 }
1147 
1148 /*
1149  * File table truncate routine.
1150  */
1151 static int
1152 vn_truncate(struct file *fp, off_t length, struct ucred *active_cred,
1153     struct thread *td)
1154 {
1155 	struct vattr vattr;
1156 	struct mount *mp;
1157 	struct vnode *vp;
1158 	void *rl_cookie;
1159 	int vfslocked;
1160 	int error;
1161 
1162 	vp = fp->f_vnode;
1163 
1164 	/*
1165 	 * Lock the whole range for truncation.  Otherwise split i/o
1166 	 * might happen partly before and partly after the truncation.
1167 	 */
1168 	rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
1169 	vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1170 	error = vn_start_write(vp, &mp, V_WAIT | PCATCH);
1171 	if (error)
1172 		goto out1;
1173 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1174 	if (vp->v_type == VDIR) {
1175 		error = EISDIR;
1176 		goto out;
1177 	}
1178 #ifdef MAC
1179 	error = mac_vnode_check_write(active_cred, fp->f_cred, vp);
1180 	if (error)
1181 		goto out;
1182 #endif
1183 	error = vn_writechk(vp);
1184 	if (error == 0) {
1185 		VATTR_NULL(&vattr);
1186 		vattr.va_size = length;
1187 		error = VOP_SETATTR(vp, &vattr, fp->f_cred);
1188 	}
1189 out:
1190 	VOP_UNLOCK(vp, 0);
1191 	vn_finished_write(mp);
1192 out1:
1193 	VFS_UNLOCK_GIANT(vfslocked);
1194 	vn_rangelock_unlock(vp, rl_cookie);
1195 	return (error);
1196 }
1197 
1198 /*
1199  * File table vnode stat routine.
1200  */
1201 static int
1202 vn_statfile(fp, sb, active_cred, td)
1203 	struct file *fp;
1204 	struct stat *sb;
1205 	struct ucred *active_cred;
1206 	struct thread *td;
1207 {
1208 	struct vnode *vp = fp->f_vnode;
1209 	int vfslocked;
1210 	int error;
1211 
1212 	vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1213 	vn_lock(vp, LK_SHARED | LK_RETRY);
1214 	error = vn_stat(vp, sb, active_cred, fp->f_cred, td);
1215 	VOP_UNLOCK(vp, 0);
1216 	VFS_UNLOCK_GIANT(vfslocked);
1217 
1218 	return (error);
1219 }
1220 
1221 /*
1222  * Stat a vnode; implementation for the stat syscall
1223  */
1224 int
1225 vn_stat(vp, sb, active_cred, file_cred, td)
1226 	struct vnode *vp;
1227 	register struct stat *sb;
1228 	struct ucred *active_cred;
1229 	struct ucred *file_cred;
1230 	struct thread *td;
1231 {
1232 	struct vattr vattr;
1233 	register struct vattr *vap;
1234 	int error;
1235 	u_short mode;
1236 
1237 #ifdef MAC
1238 	error = mac_vnode_check_stat(active_cred, file_cred, vp);
1239 	if (error)
1240 		return (error);
1241 #endif
1242 
1243 	vap = &vattr;
1244 
1245 	/*
1246 	 * Initialize defaults for new and unusual fields, so that file
1247 	 * systems which don't support these fields don't need to know
1248 	 * about them.
1249 	 */
1250 	vap->va_birthtime.tv_sec = -1;
1251 	vap->va_birthtime.tv_nsec = 0;
1252 	vap->va_fsid = VNOVAL;
1253 	vap->va_rdev = NODEV;
1254 
1255 	error = VOP_GETATTR(vp, vap, active_cred);
1256 	if (error)
1257 		return (error);
1258 
1259 	/*
1260 	 * Zero the spare stat fields
1261 	 */
1262 	bzero(sb, sizeof *sb);
1263 
1264 	/*
1265 	 * Copy from vattr table
1266 	 */
1267 	if (vap->va_fsid != VNOVAL)
1268 		sb->st_dev = vap->va_fsid;
1269 	else
1270 		sb->st_dev = vp->v_mount->mnt_stat.f_fsid.val[0];
1271 	sb->st_ino = vap->va_fileid;
1272 	mode = vap->va_mode;
1273 	switch (vap->va_type) {
1274 	case VREG:
1275 		mode |= S_IFREG;
1276 		break;
1277 	case VDIR:
1278 		mode |= S_IFDIR;
1279 		break;
1280 	case VBLK:
1281 		mode |= S_IFBLK;
1282 		break;
1283 	case VCHR:
1284 		mode |= S_IFCHR;
1285 		break;
1286 	case VLNK:
1287 		mode |= S_IFLNK;
1288 		break;
1289 	case VSOCK:
1290 		mode |= S_IFSOCK;
1291 		break;
1292 	case VFIFO:
1293 		mode |= S_IFIFO;
1294 		break;
1295 	default:
1296 		return (EBADF);
1297 	};
1298 	sb->st_mode = mode;
1299 	sb->st_nlink = vap->va_nlink;
1300 	sb->st_uid = vap->va_uid;
1301 	sb->st_gid = vap->va_gid;
1302 	sb->st_rdev = vap->va_rdev;
1303 	if (vap->va_size > OFF_MAX)
1304 		return (EOVERFLOW);
1305 	sb->st_size = vap->va_size;
1306 	sb->st_atim = vap->va_atime;
1307 	sb->st_mtim = vap->va_mtime;
1308 	sb->st_ctim = vap->va_ctime;
1309 	sb->st_birthtim = vap->va_birthtime;
1310 
1311         /*
1312 	 * According to www.opengroup.org, the meaning of st_blksize is
1313 	 *   "a filesystem-specific preferred I/O block size for this
1314 	 *    object.  In some filesystem types, this may vary from file
1315 	 *    to file"
1316 	 * Use miminum/default of PAGE_SIZE (e.g. for VCHR).
1317 	 */
1318 
1319 	sb->st_blksize = max(PAGE_SIZE, vap->va_blocksize);
1320 
1321 	sb->st_flags = vap->va_flags;
1322 	if (priv_check(td, PRIV_VFS_GENERATION))
1323 		sb->st_gen = 0;
1324 	else
1325 		sb->st_gen = vap->va_gen;
1326 
1327 	sb->st_blocks = vap->va_bytes / S_BLKSIZE;
1328 	return (0);
1329 }
1330 
1331 /*
1332  * File table vnode ioctl routine.
1333  */
1334 static int
1335 vn_ioctl(fp, com, data, active_cred, td)
1336 	struct file *fp;
1337 	u_long com;
1338 	void *data;
1339 	struct ucred *active_cred;
1340 	struct thread *td;
1341 {
1342 	struct vnode *vp = fp->f_vnode;
1343 	struct vattr vattr;
1344 	int vfslocked;
1345 	int error;
1346 
1347 	vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1348 	error = ENOTTY;
1349 	switch (vp->v_type) {
1350 	case VREG:
1351 	case VDIR:
1352 		if (com == FIONREAD) {
1353 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1354 			error = VOP_GETATTR(vp, &vattr, active_cred);
1355 			VOP_UNLOCK(vp, 0);
1356 			if (!error)
1357 				*(int *)data = vattr.va_size - fp->f_offset;
1358 		}
1359 		if (com == FIONBIO || com == FIOASYNC)	/* XXX */
1360 			error = 0;
1361 		else
1362 			error = VOP_IOCTL(vp, com, data, fp->f_flag,
1363 			    active_cred, td);
1364 		break;
1365 
1366 	default:
1367 		break;
1368 	}
1369 	VFS_UNLOCK_GIANT(vfslocked);
1370 	return (error);
1371 }
1372 
1373 /*
1374  * File table vnode poll routine.
1375  */
1376 static int
1377 vn_poll(fp, events, active_cred, td)
1378 	struct file *fp;
1379 	int events;
1380 	struct ucred *active_cred;
1381 	struct thread *td;
1382 {
1383 	struct vnode *vp;
1384 	int vfslocked;
1385 	int error;
1386 
1387 	vp = fp->f_vnode;
1388 	vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1389 #ifdef MAC
1390 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1391 	error = mac_vnode_check_poll(active_cred, fp->f_cred, vp);
1392 	VOP_UNLOCK(vp, 0);
1393 	if (!error)
1394 #endif
1395 
1396 	error = VOP_POLL(vp, events, fp->f_cred, td);
1397 	VFS_UNLOCK_GIANT(vfslocked);
1398 	return (error);
1399 }
1400 
1401 /*
1402  * Acquire the requested lock and then check for validity.  LK_RETRY
1403  * permits vn_lock to return doomed vnodes.
1404  */
1405 int
1406 _vn_lock(struct vnode *vp, int flags, char *file, int line)
1407 {
1408 	int error;
1409 
1410 	VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
1411 	    ("vn_lock called with no locktype."));
1412 	do {
1413 #ifdef DEBUG_VFS_LOCKS
1414 		KASSERT(vp->v_holdcnt != 0,
1415 		    ("vn_lock %p: zero hold count", vp));
1416 #endif
1417 		error = VOP_LOCK1(vp, flags, file, line);
1418 		flags &= ~LK_INTERLOCK;	/* Interlock is always dropped. */
1419 		KASSERT((flags & LK_RETRY) == 0 || error == 0,
1420 		    ("LK_RETRY set with incompatible flags (0x%x) or an error occured (%d)",
1421 		    flags, error));
1422 		/*
1423 		 * Callers specify LK_RETRY if they wish to get dead vnodes.
1424 		 * If RETRY is not set, we return ENOENT instead.
1425 		 */
1426 		if (error == 0 && vp->v_iflag & VI_DOOMED &&
1427 		    (flags & LK_RETRY) == 0) {
1428 			VOP_UNLOCK(vp, 0);
1429 			error = ENOENT;
1430 			break;
1431 		}
1432 	} while (flags & LK_RETRY && error != 0);
1433 	return (error);
1434 }
1435 
1436 /*
1437  * File table vnode close routine.
1438  */
1439 static int
1440 vn_closefile(fp, td)
1441 	struct file *fp;
1442 	struct thread *td;
1443 {
1444 	struct vnode *vp;
1445 	struct flock lf;
1446 	int vfslocked;
1447 	int error;
1448 
1449 	vp = fp->f_vnode;
1450 	fp->f_ops = &badfileops;
1451 
1452 	vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1453 	if (fp->f_type == DTYPE_VNODE && fp->f_flag & FHASLOCK)
1454 		vref(vp);
1455 
1456 	error = vn_close(vp, fp->f_flag, fp->f_cred, td);
1457 
1458 	if (fp->f_type == DTYPE_VNODE && fp->f_flag & FHASLOCK) {
1459 		lf.l_whence = SEEK_SET;
1460 		lf.l_start = 0;
1461 		lf.l_len = 0;
1462 		lf.l_type = F_UNLCK;
1463 		(void) VOP_ADVLOCK(vp, fp, F_UNLCK, &lf, F_FLOCK);
1464 		vrele(vp);
1465 	}
1466 	VFS_UNLOCK_GIANT(vfslocked);
1467 	return (error);
1468 }
1469 
1470 /*
1471  * Preparing to start a filesystem write operation. If the operation is
1472  * permitted, then we bump the count of operations in progress and
1473  * proceed. If a suspend request is in progress, we wait until the
1474  * suspension is over, and then proceed.
1475  */
1476 int
1477 vn_start_write(vp, mpp, flags)
1478 	struct vnode *vp;
1479 	struct mount **mpp;
1480 	int flags;
1481 {
1482 	struct mount *mp;
1483 	int error;
1484 
1485 	error = 0;
1486 	/*
1487 	 * If a vnode is provided, get and return the mount point that
1488 	 * to which it will write.
1489 	 */
1490 	if (vp != NULL) {
1491 		if ((error = VOP_GETWRITEMOUNT(vp, mpp)) != 0) {
1492 			*mpp = NULL;
1493 			if (error != EOPNOTSUPP)
1494 				return (error);
1495 			return (0);
1496 		}
1497 	}
1498 	if ((mp = *mpp) == NULL)
1499 		return (0);
1500 
1501 	/*
1502 	 * VOP_GETWRITEMOUNT() returns with the mp refcount held through
1503 	 * a vfs_ref().
1504 	 * As long as a vnode is not provided we need to acquire a
1505 	 * refcount for the provided mountpoint too, in order to
1506 	 * emulate a vfs_ref().
1507 	 */
1508 	MNT_ILOCK(mp);
1509 	if (vp == NULL)
1510 		MNT_REF(mp);
1511 
1512 	/*
1513 	 * Check on status of suspension.
1514 	 */
1515 	if ((curthread->td_pflags & TDP_IGNSUSP) == 0 ||
1516 	    mp->mnt_susp_owner != curthread) {
1517 		while ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0) {
1518 			if (flags & V_NOWAIT) {
1519 				error = EWOULDBLOCK;
1520 				goto unlock;
1521 			}
1522 			error = msleep(&mp->mnt_flag, MNT_MTX(mp),
1523 			    (PUSER - 1) | (flags & PCATCH), "suspfs", 0);
1524 			if (error)
1525 				goto unlock;
1526 		}
1527 	}
1528 	if (flags & V_XSLEEP)
1529 		goto unlock;
1530 	mp->mnt_writeopcount++;
1531 unlock:
1532 	if (error != 0 || (flags & V_XSLEEP) != 0)
1533 		MNT_REL(mp);
1534 	MNT_IUNLOCK(mp);
1535 	return (error);
1536 }
1537 
1538 /*
1539  * Secondary suspension. Used by operations such as vop_inactive
1540  * routines that are needed by the higher level functions. These
1541  * are allowed to proceed until all the higher level functions have
1542  * completed (indicated by mnt_writeopcount dropping to zero). At that
1543  * time, these operations are halted until the suspension is over.
1544  */
1545 int
1546 vn_start_secondary_write(vp, mpp, flags)
1547 	struct vnode *vp;
1548 	struct mount **mpp;
1549 	int flags;
1550 {
1551 	struct mount *mp;
1552 	int error;
1553 
1554  retry:
1555 	if (vp != NULL) {
1556 		if ((error = VOP_GETWRITEMOUNT(vp, mpp)) != 0) {
1557 			*mpp = NULL;
1558 			if (error != EOPNOTSUPP)
1559 				return (error);
1560 			return (0);
1561 		}
1562 	}
1563 	/*
1564 	 * If we are not suspended or have not yet reached suspended
1565 	 * mode, then let the operation proceed.
1566 	 */
1567 	if ((mp = *mpp) == NULL)
1568 		return (0);
1569 
1570 	/*
1571 	 * VOP_GETWRITEMOUNT() returns with the mp refcount held through
1572 	 * a vfs_ref().
1573 	 * As long as a vnode is not provided we need to acquire a
1574 	 * refcount for the provided mountpoint too, in order to
1575 	 * emulate a vfs_ref().
1576 	 */
1577 	MNT_ILOCK(mp);
1578 	if (vp == NULL)
1579 		MNT_REF(mp);
1580 	if ((mp->mnt_kern_flag & (MNTK_SUSPENDED | MNTK_SUSPEND2)) == 0) {
1581 		mp->mnt_secondary_writes++;
1582 		mp->mnt_secondary_accwrites++;
1583 		MNT_IUNLOCK(mp);
1584 		return (0);
1585 	}
1586 	if (flags & V_NOWAIT) {
1587 		MNT_REL(mp);
1588 		MNT_IUNLOCK(mp);
1589 		return (EWOULDBLOCK);
1590 	}
1591 	/*
1592 	 * Wait for the suspension to finish.
1593 	 */
1594 	error = msleep(&mp->mnt_flag, MNT_MTX(mp),
1595 		       (PUSER - 1) | (flags & PCATCH) | PDROP, "suspfs", 0);
1596 	vfs_rel(mp);
1597 	if (error == 0)
1598 		goto retry;
1599 	return (error);
1600 }
1601 
1602 /*
1603  * Filesystem write operation has completed. If we are suspending and this
1604  * operation is the last one, notify the suspender that the suspension is
1605  * now in effect.
1606  */
1607 void
1608 vn_finished_write(mp)
1609 	struct mount *mp;
1610 {
1611 	if (mp == NULL)
1612 		return;
1613 	MNT_ILOCK(mp);
1614 	MNT_REL(mp);
1615 	mp->mnt_writeopcount--;
1616 	if (mp->mnt_writeopcount < 0)
1617 		panic("vn_finished_write: neg cnt");
1618 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0 &&
1619 	    mp->mnt_writeopcount <= 0)
1620 		wakeup(&mp->mnt_writeopcount);
1621 	MNT_IUNLOCK(mp);
1622 }
1623 
1624 
1625 /*
1626  * Filesystem secondary write operation has completed. If we are
1627  * suspending and this operation is the last one, notify the suspender
1628  * that the suspension is now in effect.
1629  */
1630 void
1631 vn_finished_secondary_write(mp)
1632 	struct mount *mp;
1633 {
1634 	if (mp == NULL)
1635 		return;
1636 	MNT_ILOCK(mp);
1637 	MNT_REL(mp);
1638 	mp->mnt_secondary_writes--;
1639 	if (mp->mnt_secondary_writes < 0)
1640 		panic("vn_finished_secondary_write: neg cnt");
1641 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0 &&
1642 	    mp->mnt_secondary_writes <= 0)
1643 		wakeup(&mp->mnt_secondary_writes);
1644 	MNT_IUNLOCK(mp);
1645 }
1646 
1647 
1648 
1649 /*
1650  * Request a filesystem to suspend write operations.
1651  */
1652 int
1653 vfs_write_suspend(mp)
1654 	struct mount *mp;
1655 {
1656 	int error;
1657 
1658 	MNT_ILOCK(mp);
1659 	if (mp->mnt_susp_owner == curthread) {
1660 		MNT_IUNLOCK(mp);
1661 		return (EALREADY);
1662 	}
1663 	while (mp->mnt_kern_flag & MNTK_SUSPEND)
1664 		msleep(&mp->mnt_flag, MNT_MTX(mp), PUSER - 1, "wsuspfs", 0);
1665 	mp->mnt_kern_flag |= MNTK_SUSPEND;
1666 	mp->mnt_susp_owner = curthread;
1667 	if (mp->mnt_writeopcount > 0)
1668 		(void) msleep(&mp->mnt_writeopcount,
1669 		    MNT_MTX(mp), (PUSER - 1)|PDROP, "suspwt", 0);
1670 	else
1671 		MNT_IUNLOCK(mp);
1672 	if ((error = VFS_SYNC(mp, MNT_SUSPEND)) != 0)
1673 		vfs_write_resume(mp);
1674 	return (error);
1675 }
1676 
1677 /*
1678  * Request a filesystem to resume write operations.
1679  */
1680 void
1681 vfs_write_resume(mp)
1682 	struct mount *mp;
1683 {
1684 
1685 	MNT_ILOCK(mp);
1686 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0) {
1687 		KASSERT(mp->mnt_susp_owner == curthread, ("mnt_susp_owner"));
1688 		mp->mnt_kern_flag &= ~(MNTK_SUSPEND | MNTK_SUSPEND2 |
1689 				       MNTK_SUSPENDED);
1690 		mp->mnt_susp_owner = NULL;
1691 		wakeup(&mp->mnt_writeopcount);
1692 		wakeup(&mp->mnt_flag);
1693 		curthread->td_pflags &= ~TDP_IGNSUSP;
1694 		MNT_IUNLOCK(mp);
1695 		VFS_SUSP_CLEAN(mp);
1696 	} else
1697 		MNT_IUNLOCK(mp);
1698 }
1699 
1700 /*
1701  * Implement kqueues for files by translating it to vnode operation.
1702  */
1703 static int
1704 vn_kqfilter(struct file *fp, struct knote *kn)
1705 {
1706 	int vfslocked;
1707 	int error;
1708 
1709 	vfslocked = VFS_LOCK_GIANT(fp->f_vnode->v_mount);
1710 	error = VOP_KQFILTER(fp->f_vnode, kn);
1711 	VFS_UNLOCK_GIANT(vfslocked);
1712 
1713 	return error;
1714 }
1715 
1716 /*
1717  * Simplified in-kernel wrapper calls for extended attribute access.
1718  * Both calls pass in a NULL credential, authorizing as "kernel" access.
1719  * Set IO_NODELOCKED in ioflg if the vnode is already locked.
1720  */
1721 int
1722 vn_extattr_get(struct vnode *vp, int ioflg, int attrnamespace,
1723     const char *attrname, int *buflen, char *buf, struct thread *td)
1724 {
1725 	struct uio	auio;
1726 	struct iovec	iov;
1727 	int	error;
1728 
1729 	iov.iov_len = *buflen;
1730 	iov.iov_base = buf;
1731 
1732 	auio.uio_iov = &iov;
1733 	auio.uio_iovcnt = 1;
1734 	auio.uio_rw = UIO_READ;
1735 	auio.uio_segflg = UIO_SYSSPACE;
1736 	auio.uio_td = td;
1737 	auio.uio_offset = 0;
1738 	auio.uio_resid = *buflen;
1739 
1740 	if ((ioflg & IO_NODELOCKED) == 0)
1741 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1742 
1743 	ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
1744 
1745 	/* authorize attribute retrieval as kernel */
1746 	error = VOP_GETEXTATTR(vp, attrnamespace, attrname, &auio, NULL, NULL,
1747 	    td);
1748 
1749 	if ((ioflg & IO_NODELOCKED) == 0)
1750 		VOP_UNLOCK(vp, 0);
1751 
1752 	if (error == 0) {
1753 		*buflen = *buflen - auio.uio_resid;
1754 	}
1755 
1756 	return (error);
1757 }
1758 
1759 /*
1760  * XXX failure mode if partially written?
1761  */
1762 int
1763 vn_extattr_set(struct vnode *vp, int ioflg, int attrnamespace,
1764     const char *attrname, int buflen, char *buf, struct thread *td)
1765 {
1766 	struct uio	auio;
1767 	struct iovec	iov;
1768 	struct mount	*mp;
1769 	int	error;
1770 
1771 	iov.iov_len = buflen;
1772 	iov.iov_base = buf;
1773 
1774 	auio.uio_iov = &iov;
1775 	auio.uio_iovcnt = 1;
1776 	auio.uio_rw = UIO_WRITE;
1777 	auio.uio_segflg = UIO_SYSSPACE;
1778 	auio.uio_td = td;
1779 	auio.uio_offset = 0;
1780 	auio.uio_resid = buflen;
1781 
1782 	if ((ioflg & IO_NODELOCKED) == 0) {
1783 		if ((error = vn_start_write(vp, &mp, V_WAIT)) != 0)
1784 			return (error);
1785 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1786 	}
1787 
1788 	ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
1789 
1790 	/* authorize attribute setting as kernel */
1791 	error = VOP_SETEXTATTR(vp, attrnamespace, attrname, &auio, NULL, td);
1792 
1793 	if ((ioflg & IO_NODELOCKED) == 0) {
1794 		vn_finished_write(mp);
1795 		VOP_UNLOCK(vp, 0);
1796 	}
1797 
1798 	return (error);
1799 }
1800 
1801 int
1802 vn_extattr_rm(struct vnode *vp, int ioflg, int attrnamespace,
1803     const char *attrname, struct thread *td)
1804 {
1805 	struct mount	*mp;
1806 	int	error;
1807 
1808 	if ((ioflg & IO_NODELOCKED) == 0) {
1809 		if ((error = vn_start_write(vp, &mp, V_WAIT)) != 0)
1810 			return (error);
1811 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1812 	}
1813 
1814 	ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
1815 
1816 	/* authorize attribute removal as kernel */
1817 	error = VOP_DELETEEXTATTR(vp, attrnamespace, attrname, NULL, td);
1818 	if (error == EOPNOTSUPP)
1819 		error = VOP_SETEXTATTR(vp, attrnamespace, attrname, NULL,
1820 		    NULL, td);
1821 
1822 	if ((ioflg & IO_NODELOCKED) == 0) {
1823 		vn_finished_write(mp);
1824 		VOP_UNLOCK(vp, 0);
1825 	}
1826 
1827 	return (error);
1828 }
1829 
1830 int
1831 vn_vget_ino(struct vnode *vp, ino_t ino, int lkflags, struct vnode **rvp)
1832 {
1833 	struct mount *mp;
1834 	int ltype, error;
1835 
1836 	mp = vp->v_mount;
1837 	ltype = VOP_ISLOCKED(vp);
1838 	KASSERT(ltype == LK_EXCLUSIVE || ltype == LK_SHARED,
1839 	    ("vn_vget_ino: vp not locked"));
1840 	error = vfs_busy(mp, MBF_NOWAIT);
1841 	if (error != 0) {
1842 		vfs_ref(mp);
1843 		VOP_UNLOCK(vp, 0);
1844 		error = vfs_busy(mp, 0);
1845 		vn_lock(vp, ltype | LK_RETRY);
1846 		vfs_rel(mp);
1847 		if (error != 0)
1848 			return (ENOENT);
1849 		if (vp->v_iflag & VI_DOOMED) {
1850 			vfs_unbusy(mp);
1851 			return (ENOENT);
1852 		}
1853 	}
1854 	VOP_UNLOCK(vp, 0);
1855 	error = VFS_VGET(mp, ino, lkflags, rvp);
1856 	vfs_unbusy(mp);
1857 	vn_lock(vp, ltype | LK_RETRY);
1858 	if (vp->v_iflag & VI_DOOMED) {
1859 		if (error == 0)
1860 			vput(*rvp);
1861 		error = ENOENT;
1862 	}
1863 	return (error);
1864 }
1865 
1866 int
1867 vn_rlimit_fsize(const struct vnode *vp, const struct uio *uio,
1868     const struct thread *td)
1869 {
1870 
1871 	if (vp->v_type != VREG || td == NULL)
1872 		return (0);
1873 	PROC_LOCK(td->td_proc);
1874 	if ((uoff_t)uio->uio_offset + uio->uio_resid >
1875 	    lim_cur(td->td_proc, RLIMIT_FSIZE)) {
1876 		kern_psignal(td->td_proc, SIGXFSZ);
1877 		PROC_UNLOCK(td->td_proc);
1878 		return (EFBIG);
1879 	}
1880 	PROC_UNLOCK(td->td_proc);
1881 	return (0);
1882 }
1883 
1884 int
1885 vn_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
1886     struct thread *td)
1887 {
1888 	struct vnode *vp;
1889 	int error, vfslocked;
1890 
1891 	vp = fp->f_vnode;
1892 	vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1893 #ifdef AUDIT
1894 	vn_lock(vp, LK_SHARED | LK_RETRY);
1895 	AUDIT_ARG_VNODE1(vp);
1896 	VOP_UNLOCK(vp, 0);
1897 #endif
1898 	error = setfmode(td, active_cred, vp, mode);
1899 	VFS_UNLOCK_GIANT(vfslocked);
1900 	return (error);
1901 }
1902 
1903 int
1904 vn_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
1905     struct thread *td)
1906 {
1907 	struct vnode *vp;
1908 	int error, vfslocked;
1909 
1910 	vp = fp->f_vnode;
1911 	vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1912 #ifdef AUDIT
1913 	vn_lock(vp, LK_SHARED | LK_RETRY);
1914 	AUDIT_ARG_VNODE1(vp);
1915 	VOP_UNLOCK(vp, 0);
1916 #endif
1917 	error = setfown(td, active_cred, vp, uid, gid);
1918 	VFS_UNLOCK_GIANT(vfslocked);
1919 	return (error);
1920 }
1921 
1922 void
1923 vn_pages_remove(struct vnode *vp, vm_pindex_t start, vm_pindex_t end)
1924 {
1925 	vm_object_t object;
1926 
1927 	if ((object = vp->v_object) == NULL)
1928 		return;
1929 	VM_OBJECT_LOCK(object);
1930 	vm_object_page_remove(object, start, end, 0);
1931 	VM_OBJECT_UNLOCK(object);
1932 }
1933 
1934 int
1935 vn_bmap_seekhole(struct vnode *vp, u_long cmd, off_t *off, struct ucred *cred)
1936 {
1937 	struct vattr va;
1938 	daddr_t bn, bnp;
1939 	uint64_t bsize;
1940 	off_t noff;
1941 	int error;
1942 
1943 	KASSERT(cmd == FIOSEEKHOLE || cmd == FIOSEEKDATA,
1944 	    ("Wrong command %lu", cmd));
1945 
1946 	if (vn_lock(vp, LK_SHARED) != 0)
1947 		return (EBADF);
1948 	if (vp->v_type != VREG) {
1949 		error = ENOTTY;
1950 		goto unlock;
1951 	}
1952 	error = VOP_GETATTR(vp, &va, cred);
1953 	if (error != 0)
1954 		goto unlock;
1955 	noff = *off;
1956 	if (noff >= va.va_size) {
1957 		error = ENXIO;
1958 		goto unlock;
1959 	}
1960 	bsize = vp->v_mount->mnt_stat.f_iosize;
1961 	for (bn = noff / bsize; noff < va.va_size; bn++, noff += bsize) {
1962 		error = VOP_BMAP(vp, bn, NULL, &bnp, NULL, NULL);
1963 		if (error == EOPNOTSUPP) {
1964 			error = ENOTTY;
1965 			goto unlock;
1966 		}
1967 		if ((bnp == -1 && cmd == FIOSEEKHOLE) ||
1968 		    (bnp != -1 && cmd == FIOSEEKDATA)) {
1969 			noff = bn * bsize;
1970 			if (noff < *off)
1971 				noff = *off;
1972 			goto unlock;
1973 		}
1974 	}
1975 	if (noff > va.va_size)
1976 		noff = va.va_size;
1977 	/* noff == va.va_size. There is an implicit hole at the end of file. */
1978 	if (cmd == FIOSEEKDATA)
1979 		error = ENXIO;
1980 unlock:
1981 	VOP_UNLOCK(vp, 0);
1982 	if (error == 0)
1983 		*off = noff;
1984 	return (error);
1985 }
1986