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