xref: /f-stack/freebsd/kern/vfs_vnops.c (revision 22ce4aff)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Copyright (c) 2012 Konstantin Belousov <[email protected]>
13  * Copyright (c) 2013, 2014 The FreeBSD Foundation
14  *
15  * Portions of this software were developed by Konstantin Belousov
16  * under sponsorship from the FreeBSD Foundation.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  * 1. Redistributions of source code must retain the above copyright
22  *    notice, this list of conditions and the following disclaimer.
23  * 2. Redistributions in binary form must reproduce the above copyright
24  *    notice, this list of conditions and the following disclaimer in the
25  *    documentation and/or other materials provided with the distribution.
26  * 3. Neither the name of the University nor the names of its contributors
27  *    may be used to endorse or promote products derived from this software
28  *    without specific prior written permission.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40  * SUCH DAMAGE.
41  *
42  *	@(#)vfs_vnops.c	8.2 (Berkeley) 1/21/94
43  */
44 
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
47 
48 #include "opt_hwpmc_hooks.h"
49 
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/disk.h>
53 #include <sys/fail.h>
54 #include <sys/fcntl.h>
55 #include <sys/file.h>
56 #include <sys/kdb.h>
57 #include <sys/ktr.h>
58 #include <sys/stat.h>
59 #include <sys/priv.h>
60 #include <sys/proc.h>
61 #include <sys/limits.h>
62 #include <sys/lock.h>
63 #include <sys/mman.h>
64 #include <sys/mount.h>
65 #include <sys/mutex.h>
66 #include <sys/namei.h>
67 #include <sys/vnode.h>
68 #include <sys/bio.h>
69 #include <sys/buf.h>
70 #include <sys/filio.h>
71 #include <sys/resourcevar.h>
72 #include <sys/rwlock.h>
73 #include <sys/prng.h>
74 #include <sys/sx.h>
75 #include <sys/sleepqueue.h>
76 #include <sys/sysctl.h>
77 #include <sys/ttycom.h>
78 #include <sys/conf.h>
79 #include <sys/syslog.h>
80 #include <sys/unistd.h>
81 #include <sys/user.h>
82 
83 #include <security/audit/audit.h>
84 #include <security/mac/mac_framework.h>
85 
86 #include <vm/vm.h>
87 #include <vm/vm_extern.h>
88 #include <vm/pmap.h>
89 #include <vm/vm_map.h>
90 #include <vm/vm_object.h>
91 #include <vm/vm_page.h>
92 #include <vm/vm_pager.h>
93 
94 #ifdef HWPMC_HOOKS
95 #include <sys/pmckern.h>
96 #endif
97 
98 static fo_rdwr_t	vn_read;
99 static fo_rdwr_t	vn_write;
100 static fo_rdwr_t	vn_io_fault;
101 static fo_truncate_t	vn_truncate;
102 static fo_ioctl_t	vn_ioctl;
103 static fo_poll_t	vn_poll;
104 static fo_kqfilter_t	vn_kqfilter;
105 static fo_stat_t	vn_statfile;
106 static fo_close_t	vn_closefile;
107 static fo_mmap_t	vn_mmap;
108 static fo_fallocate_t	vn_fallocate;
109 
110 struct 	fileops vnops = {
111 	.fo_read = vn_io_fault,
112 	.fo_write = vn_io_fault,
113 	.fo_truncate = vn_truncate,
114 	.fo_ioctl = vn_ioctl,
115 	.fo_poll = vn_poll,
116 	.fo_kqfilter = vn_kqfilter,
117 	.fo_stat = vn_statfile,
118 	.fo_close = vn_closefile,
119 	.fo_chmod = vn_chmod,
120 	.fo_chown = vn_chown,
121 	.fo_sendfile = vn_sendfile,
122 	.fo_seek = vn_seek,
123 	.fo_fill_kinfo = vn_fill_kinfo,
124 	.fo_mmap = vn_mmap,
125 	.fo_fallocate = vn_fallocate,
126 	.fo_flags = DFLAG_PASSABLE | DFLAG_SEEKABLE
127 };
128 
129 const u_int io_hold_cnt = 16;
130 static int vn_io_fault_enable = 1;
131 SYSCTL_INT(_debug, OID_AUTO, vn_io_fault_enable, CTLFLAG_RWTUN,
132     &vn_io_fault_enable, 0, "Enable vn_io_fault lock avoidance");
133 static int vn_io_fault_prefault = 0;
134 SYSCTL_INT(_debug, OID_AUTO, vn_io_fault_prefault, CTLFLAG_RWTUN,
135     &vn_io_fault_prefault, 0, "Enable vn_io_fault prefaulting");
136 static int vn_io_pgcache_read_enable = 1;
137 SYSCTL_INT(_debug, OID_AUTO, vn_io_pgcache_read_enable, CTLFLAG_RWTUN,
138     &vn_io_pgcache_read_enable, 0,
139     "Enable copying from page cache for reads, avoiding fs");
140 static u_long vn_io_faults_cnt;
141 SYSCTL_ULONG(_debug, OID_AUTO, vn_io_faults, CTLFLAG_RD,
142     &vn_io_faults_cnt, 0, "Count of vn_io_fault lock avoidance triggers");
143 
144 static int vfs_allow_read_dir = 0;
145 SYSCTL_INT(_security_bsd, OID_AUTO, allow_read_dir, CTLFLAG_RW,
146     &vfs_allow_read_dir, 0,
147     "Enable read(2) of directory by root for filesystems that support it");
148 
149 /*
150  * Returns true if vn_io_fault mode of handling the i/o request should
151  * be used.
152  */
153 static bool
do_vn_io_fault(struct vnode * vp,struct uio * uio)154 do_vn_io_fault(struct vnode *vp, struct uio *uio)
155 {
156 	struct mount *mp;
157 
158 	return (uio->uio_segflg == UIO_USERSPACE && vp->v_type == VREG &&
159 	    (mp = vp->v_mount) != NULL &&
160 	    (mp->mnt_kern_flag & MNTK_NO_IOPF) != 0 && vn_io_fault_enable);
161 }
162 
163 /*
164  * Structure used to pass arguments to vn_io_fault1(), to do either
165  * file- or vnode-based I/O calls.
166  */
167 struct vn_io_fault_args {
168 	enum {
169 		VN_IO_FAULT_FOP,
170 		VN_IO_FAULT_VOP
171 	} kind;
172 	struct ucred *cred;
173 	int flags;
174 	union {
175 		struct fop_args_tag {
176 			struct file *fp;
177 			fo_rdwr_t *doio;
178 		} fop_args;
179 		struct vop_args_tag {
180 			struct vnode *vp;
181 		} vop_args;
182 	} args;
183 };
184 
185 static int vn_io_fault1(struct vnode *vp, struct uio *uio,
186     struct vn_io_fault_args *args, struct thread *td);
187 
188 int
vn_open(struct nameidata * ndp,int * flagp,int cmode,struct file * fp)189 vn_open(struct nameidata *ndp, int *flagp, int cmode, struct file *fp)
190 {
191 	struct thread *td = ndp->ni_cnd.cn_thread;
192 
193 	return (vn_open_cred(ndp, flagp, cmode, 0, td->td_ucred, fp));
194 }
195 
196 static uint64_t
open2nameif(int fmode,u_int vn_open_flags)197 open2nameif(int fmode, u_int vn_open_flags)
198 {
199 	uint64_t res;
200 
201 	res = ISOPEN | LOCKLEAF;
202 	if ((fmode & O_RESOLVE_BENEATH) != 0)
203 		res |= RBENEATH;
204 	if ((vn_open_flags & VN_OPEN_NOAUDIT) == 0)
205 		res |= AUDITVNODE1;
206 	if ((vn_open_flags & VN_OPEN_NOCAPCHECK) != 0)
207 		res |= NOCAPCHECK;
208 	return (res);
209 }
210 
211 /*
212  * Common code for vnode open operations via a name lookup.
213  * Lookup the vnode and invoke VOP_CREATE if needed.
214  * Check permissions, and call the VOP_OPEN or VOP_CREATE routine.
215  *
216  * Note that this does NOT free nameidata for the successful case,
217  * due to the NDINIT being done elsewhere.
218  */
219 int
vn_open_cred(struct nameidata * ndp,int * flagp,int cmode,u_int vn_open_flags,struct ucred * cred,struct file * fp)220 vn_open_cred(struct nameidata *ndp, int *flagp, int cmode, u_int vn_open_flags,
221     struct ucred *cred, struct file *fp)
222 {
223 	struct vnode *vp;
224 	struct mount *mp;
225 	struct thread *td = ndp->ni_cnd.cn_thread;
226 	struct vattr vat;
227 	struct vattr *vap = &vat;
228 	int fmode, error;
229 
230 restart:
231 	fmode = *flagp;
232 	if ((fmode & (O_CREAT | O_EXCL | O_DIRECTORY)) == (O_CREAT |
233 	    O_EXCL | O_DIRECTORY))
234 		return (EINVAL);
235 	else if ((fmode & (O_CREAT | O_DIRECTORY)) == O_CREAT) {
236 		ndp->ni_cnd.cn_nameiop = CREATE;
237 		ndp->ni_cnd.cn_flags = open2nameif(fmode, vn_open_flags);
238 		/*
239 		 * Set NOCACHE to avoid flushing the cache when
240 		 * rolling in many files at once.
241 		 *
242 		 * Set NC_KEEPPOSENTRY to keep positive entries if they already
243 		 * exist despite NOCACHE.
244 		 */
245 		ndp->ni_cnd.cn_flags |= LOCKPARENT | NOCACHE | NC_KEEPPOSENTRY;
246 		if ((fmode & O_EXCL) == 0 && (fmode & O_NOFOLLOW) == 0)
247 			ndp->ni_cnd.cn_flags |= FOLLOW;
248 		if ((vn_open_flags & VN_OPEN_INVFS) == 0)
249 			bwillwrite();
250 		if ((error = namei(ndp)) != 0)
251 			return (error);
252 		if (ndp->ni_vp == NULL) {
253 			VATTR_NULL(vap);
254 			vap->va_type = VREG;
255 			vap->va_mode = cmode;
256 			if (fmode & O_EXCL)
257 				vap->va_vaflags |= VA_EXCLUSIVE;
258 			if (vn_start_write(ndp->ni_dvp, &mp, V_NOWAIT) != 0) {
259 				NDFREE(ndp, NDF_ONLY_PNBUF);
260 				vput(ndp->ni_dvp);
261 				if ((error = vn_start_write(NULL, &mp,
262 				    V_XSLEEP | PCATCH)) != 0)
263 					return (error);
264 				NDREINIT(ndp);
265 				goto restart;
266 			}
267 			if ((vn_open_flags & VN_OPEN_NAMECACHE) != 0)
268 				ndp->ni_cnd.cn_flags |= MAKEENTRY;
269 #ifdef MAC
270 			error = mac_vnode_check_create(cred, ndp->ni_dvp,
271 			    &ndp->ni_cnd, vap);
272 			if (error == 0)
273 #endif
274 				error = VOP_CREATE(ndp->ni_dvp, &ndp->ni_vp,
275 				    &ndp->ni_cnd, vap);
276 			VOP_VPUT_PAIR(ndp->ni_dvp, error == 0 ? &ndp->ni_vp :
277 			    NULL, false);
278 			vn_finished_write(mp);
279 			if (error) {
280 				NDFREE(ndp, NDF_ONLY_PNBUF);
281 				if (error == ERELOOKUP) {
282 					NDREINIT(ndp);
283 					goto restart;
284 				}
285 				return (error);
286 			}
287 			fmode &= ~O_TRUNC;
288 			vp = ndp->ni_vp;
289 		} else {
290 			if (ndp->ni_dvp == ndp->ni_vp)
291 				vrele(ndp->ni_dvp);
292 			else
293 				vput(ndp->ni_dvp);
294 			ndp->ni_dvp = NULL;
295 			vp = ndp->ni_vp;
296 			if (fmode & O_EXCL) {
297 				error = EEXIST;
298 				goto bad;
299 			}
300 			if (vp->v_type == VDIR) {
301 				error = EISDIR;
302 				goto bad;
303 			}
304 			fmode &= ~O_CREAT;
305 		}
306 	} else {
307 		ndp->ni_cnd.cn_nameiop = LOOKUP;
308 		ndp->ni_cnd.cn_flags = open2nameif(fmode, vn_open_flags);
309 		ndp->ni_cnd.cn_flags |= (fmode & O_NOFOLLOW) != 0 ? NOFOLLOW :
310 		    FOLLOW;
311 		if ((fmode & FWRITE) == 0)
312 			ndp->ni_cnd.cn_flags |= LOCKSHARED;
313 		if ((error = namei(ndp)) != 0)
314 			return (error);
315 		vp = ndp->ni_vp;
316 	}
317 	error = vn_open_vnode(vp, fmode, cred, td, fp);
318 	if (error)
319 		goto bad;
320 	*flagp = fmode;
321 	return (0);
322 bad:
323 	NDFREE(ndp, NDF_ONLY_PNBUF);
324 	vput(vp);
325 	*flagp = fmode;
326 	ndp->ni_vp = NULL;
327 	return (error);
328 }
329 
330 static int
vn_open_vnode_advlock(struct vnode * vp,int fmode,struct file * fp)331 vn_open_vnode_advlock(struct vnode *vp, int fmode, struct file *fp)
332 {
333 	struct flock lf;
334 	int error, lock_flags, type;
335 
336 	ASSERT_VOP_LOCKED(vp, "vn_open_vnode_advlock");
337 	if ((fmode & (O_EXLOCK | O_SHLOCK)) == 0)
338 		return (0);
339 	KASSERT(fp != NULL, ("open with flock requires fp"));
340 	if (fp->f_type != DTYPE_NONE && fp->f_type != DTYPE_VNODE)
341 		return (EOPNOTSUPP);
342 
343 	lock_flags = VOP_ISLOCKED(vp);
344 	VOP_UNLOCK(vp);
345 
346 	lf.l_whence = SEEK_SET;
347 	lf.l_start = 0;
348 	lf.l_len = 0;
349 	lf.l_type = (fmode & O_EXLOCK) != 0 ? F_WRLCK : F_RDLCK;
350 	type = F_FLOCK;
351 	if ((fmode & FNONBLOCK) == 0)
352 		type |= F_WAIT;
353 	error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, type);
354 	if (error == 0)
355 		fp->f_flag |= FHASLOCK;
356 
357 	vn_lock(vp, lock_flags | LK_RETRY);
358 	return (error);
359 }
360 
361 /*
362  * Common code for vnode open operations once a vnode is located.
363  * Check permissions, and call the VOP_OPEN routine.
364  */
365 int
vn_open_vnode(struct vnode * vp,int fmode,struct ucred * cred,struct thread * td,struct file * fp)366 vn_open_vnode(struct vnode *vp, int fmode, struct ucred *cred,
367     struct thread *td, struct file *fp)
368 {
369 	accmode_t accmode;
370 	int error;
371 
372 	if (vp->v_type == VLNK)
373 		return (EMLINK);
374 	if (vp->v_type == VSOCK)
375 		return (EOPNOTSUPP);
376 	if (vp->v_type != VDIR && fmode & O_DIRECTORY)
377 		return (ENOTDIR);
378 	accmode = 0;
379 	if (fmode & (FWRITE | O_TRUNC)) {
380 		if (vp->v_type == VDIR)
381 			return (EISDIR);
382 		accmode |= VWRITE;
383 	}
384 	if (fmode & FREAD)
385 		accmode |= VREAD;
386 	if (fmode & FEXEC)
387 		accmode |= VEXEC;
388 	if ((fmode & O_APPEND) && (fmode & FWRITE))
389 		accmode |= VAPPEND;
390 #ifdef MAC
391 	if (fmode & O_CREAT)
392 		accmode |= VCREAT;
393 	if (fmode & O_VERIFY)
394 		accmode |= VVERIFY;
395 	error = mac_vnode_check_open(cred, vp, accmode);
396 	if (error)
397 		return (error);
398 
399 	accmode &= ~(VCREAT | VVERIFY);
400 #endif
401 	if ((fmode & O_CREAT) == 0 && accmode != 0) {
402 		error = VOP_ACCESS(vp, accmode, cred, td);
403 		if (error != 0)
404 			return (error);
405 	}
406 	if (vp->v_type == VFIFO && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
407 		vn_lock(vp, LK_UPGRADE | LK_RETRY);
408 	error = VOP_OPEN(vp, fmode, cred, td, fp);
409 	if (error != 0)
410 		return (error);
411 
412 	error = vn_open_vnode_advlock(vp, fmode, fp);
413 	if (error == 0 && (fmode & FWRITE) != 0) {
414 		error = VOP_ADD_WRITECOUNT(vp, 1);
415 		if (error == 0) {
416 			CTR3(KTR_VFS, "%s: vp %p v_writecount increased to %d",
417 			     __func__, vp, vp->v_writecount);
418 		}
419 	}
420 
421 	/*
422 	 * Error from advlock or VOP_ADD_WRITECOUNT() still requires
423 	 * calling VOP_CLOSE() to pair with earlier VOP_OPEN().
424 	 * Arrange for that by having fdrop() to use vn_closefile().
425 	 */
426 	if (error != 0) {
427 		fp->f_flag |= FOPENFAILED;
428 		fp->f_vnode = vp;
429 		if (fp->f_ops == &badfileops) {
430 			fp->f_type = DTYPE_VNODE;
431 			fp->f_ops = &vnops;
432 		}
433 		vref(vp);
434 	}
435 
436 	ASSERT_VOP_LOCKED(vp, "vn_open_vnode");
437 	return (error);
438 
439 }
440 
441 /*
442  * Check for write permissions on the specified vnode.
443  * Prototype text segments cannot be written.
444  * It is racy.
445  */
446 int
vn_writechk(struct vnode * vp)447 vn_writechk(struct vnode *vp)
448 {
449 
450 	ASSERT_VOP_LOCKED(vp, "vn_writechk");
451 	/*
452 	 * If there's shared text associated with
453 	 * the vnode, try to free it up once.  If
454 	 * we fail, we can't allow writing.
455 	 */
456 	if (VOP_IS_TEXT(vp))
457 		return (ETXTBSY);
458 
459 	return (0);
460 }
461 
462 /*
463  * Vnode close call
464  */
465 static int
vn_close1(struct vnode * vp,int flags,struct ucred * file_cred,struct thread * td,bool keep_ref)466 vn_close1(struct vnode *vp, int flags, struct ucred *file_cred,
467     struct thread *td, bool keep_ref)
468 {
469 	struct mount *mp;
470 	int error, lock_flags;
471 
472 	if (vp->v_type != VFIFO && (flags & FWRITE) == 0 &&
473 	    MNT_EXTENDED_SHARED(vp->v_mount))
474 		lock_flags = LK_SHARED;
475 	else
476 		lock_flags = LK_EXCLUSIVE;
477 
478 	vn_start_write(vp, &mp, V_WAIT);
479 	vn_lock(vp, lock_flags | LK_RETRY);
480 	AUDIT_ARG_VNODE1(vp);
481 	if ((flags & (FWRITE | FOPENFAILED)) == FWRITE) {
482 		VOP_ADD_WRITECOUNT_CHECKED(vp, -1);
483 		CTR3(KTR_VFS, "%s: vp %p v_writecount decreased to %d",
484 		    __func__, vp, vp->v_writecount);
485 	}
486 	error = VOP_CLOSE(vp, flags, file_cred, td);
487 	if (keep_ref)
488 		VOP_UNLOCK(vp);
489 	else
490 		vput(vp);
491 	vn_finished_write(mp);
492 	return (error);
493 }
494 
495 int
vn_close(struct vnode * vp,int flags,struct ucred * file_cred,struct thread * td)496 vn_close(struct vnode *vp, int flags, struct ucred *file_cred,
497     struct thread *td)
498 {
499 
500 	return (vn_close1(vp, flags, file_cred, td, false));
501 }
502 
503 /*
504  * Heuristic to detect sequential operation.
505  */
506 static int
sequential_heuristic(struct uio * uio,struct file * fp)507 sequential_heuristic(struct uio *uio, struct file *fp)
508 {
509 	enum uio_rw rw;
510 
511 	ASSERT_VOP_LOCKED(fp->f_vnode, __func__);
512 
513 	rw = uio->uio_rw;
514 	if (fp->f_flag & FRDAHEAD)
515 		return (fp->f_seqcount[rw] << IO_SEQSHIFT);
516 
517 	/*
518 	 * Offset 0 is handled specially.  open() sets f_seqcount to 1 so
519 	 * that the first I/O is normally considered to be slightly
520 	 * sequential.  Seeking to offset 0 doesn't change sequentiality
521 	 * unless previous seeks have reduced f_seqcount to 0, in which
522 	 * case offset 0 is not special.
523 	 */
524 	if ((uio->uio_offset == 0 && fp->f_seqcount[rw] > 0) ||
525 	    uio->uio_offset == fp->f_nextoff[rw]) {
526 		/*
527 		 * f_seqcount is in units of fixed-size blocks so that it
528 		 * depends mainly on the amount of sequential I/O and not
529 		 * much on the number of sequential I/O's.  The fixed size
530 		 * of 16384 is hard-coded here since it is (not quite) just
531 		 * a magic size that works well here.  This size is more
532 		 * closely related to the best I/O size for real disks than
533 		 * to any block size used by software.
534 		 */
535 		if (uio->uio_resid >= IO_SEQMAX * 16384)
536 			fp->f_seqcount[rw] = IO_SEQMAX;
537 		else {
538 			fp->f_seqcount[rw] += howmany(uio->uio_resid, 16384);
539 			if (fp->f_seqcount[rw] > IO_SEQMAX)
540 				fp->f_seqcount[rw] = IO_SEQMAX;
541 		}
542 		return (fp->f_seqcount[rw] << IO_SEQSHIFT);
543 	}
544 
545 	/* Not sequential.  Quickly draw-down sequentiality. */
546 	if (fp->f_seqcount[rw] > 1)
547 		fp->f_seqcount[rw] = 1;
548 	else
549 		fp->f_seqcount[rw] = 0;
550 	return (0);
551 }
552 
553 /*
554  * Package up an I/O request on a vnode into a uio and do it.
555  */
556 int
vn_rdwr(enum uio_rw rw,struct vnode * vp,void * base,int len,off_t offset,enum uio_seg segflg,int ioflg,struct ucred * active_cred,struct ucred * file_cred,ssize_t * aresid,struct thread * td)557 vn_rdwr(enum uio_rw rw, struct vnode *vp, void *base, int len, off_t offset,
558     enum uio_seg segflg, int ioflg, struct ucred *active_cred,
559     struct ucred *file_cred, ssize_t *aresid, struct thread *td)
560 {
561 	struct uio auio;
562 	struct iovec aiov;
563 	struct mount *mp;
564 	struct ucred *cred;
565 	void *rl_cookie;
566 	struct vn_io_fault_args args;
567 	int error, lock_flags;
568 
569 	if (offset < 0 && vp->v_type != VCHR)
570 		return (EINVAL);
571 	auio.uio_iov = &aiov;
572 	auio.uio_iovcnt = 1;
573 	aiov.iov_base = base;
574 	aiov.iov_len = len;
575 	auio.uio_resid = len;
576 	auio.uio_offset = offset;
577 	auio.uio_segflg = segflg;
578 	auio.uio_rw = rw;
579 	auio.uio_td = td;
580 	error = 0;
581 
582 	if ((ioflg & IO_NODELOCKED) == 0) {
583 		if ((ioflg & IO_RANGELOCKED) == 0) {
584 			if (rw == UIO_READ) {
585 				rl_cookie = vn_rangelock_rlock(vp, offset,
586 				    offset + len);
587 			} else if ((ioflg & IO_APPEND) != 0) {
588 				rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
589 			} else {
590 				rl_cookie = vn_rangelock_wlock(vp, offset,
591 				    offset + len);
592 			}
593 		} else
594 			rl_cookie = NULL;
595 		mp = NULL;
596 		if (rw == UIO_WRITE) {
597 			if (vp->v_type != VCHR &&
598 			    (error = vn_start_write(vp, &mp, V_WAIT | PCATCH))
599 			    != 0)
600 				goto out;
601 			if (MNT_SHARED_WRITES(mp) ||
602 			    ((mp == NULL) && MNT_SHARED_WRITES(vp->v_mount)))
603 				lock_flags = LK_SHARED;
604 			else
605 				lock_flags = LK_EXCLUSIVE;
606 		} else
607 			lock_flags = LK_SHARED;
608 		vn_lock(vp, lock_flags | LK_RETRY);
609 	} else
610 		rl_cookie = NULL;
611 
612 	ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
613 #ifdef MAC
614 	if ((ioflg & IO_NOMACCHECK) == 0) {
615 		if (rw == UIO_READ)
616 			error = mac_vnode_check_read(active_cred, file_cred,
617 			    vp);
618 		else
619 			error = mac_vnode_check_write(active_cred, file_cred,
620 			    vp);
621 	}
622 #endif
623 	if (error == 0) {
624 		if (file_cred != NULL)
625 			cred = file_cred;
626 		else
627 			cred = active_cred;
628 		if (do_vn_io_fault(vp, &auio)) {
629 			args.kind = VN_IO_FAULT_VOP;
630 			args.cred = cred;
631 			args.flags = ioflg;
632 			args.args.vop_args.vp = vp;
633 			error = vn_io_fault1(vp, &auio, &args, td);
634 		} else if (rw == UIO_READ) {
635 			error = VOP_READ(vp, &auio, ioflg, cred);
636 		} else /* if (rw == UIO_WRITE) */ {
637 			error = VOP_WRITE(vp, &auio, ioflg, cred);
638 		}
639 	}
640 	if (aresid)
641 		*aresid = auio.uio_resid;
642 	else
643 		if (auio.uio_resid && error == 0)
644 			error = EIO;
645 	if ((ioflg & IO_NODELOCKED) == 0) {
646 		VOP_UNLOCK(vp);
647 		if (mp != NULL)
648 			vn_finished_write(mp);
649 	}
650  out:
651 	if (rl_cookie != NULL)
652 		vn_rangelock_unlock(vp, rl_cookie);
653 	return (error);
654 }
655 
656 /*
657  * Package up an I/O request on a vnode into a uio and do it.  The I/O
658  * request is split up into smaller chunks and we try to avoid saturating
659  * the buffer cache while potentially holding a vnode locked, so we
660  * check bwillwrite() before calling vn_rdwr().  We also call kern_yield()
661  * to give other processes a chance to lock the vnode (either other processes
662  * core'ing the same binary, or unrelated processes scanning the directory).
663  */
664 int
vn_rdwr_inchunks(enum uio_rw rw,struct vnode * vp,void * base,size_t len,off_t offset,enum uio_seg segflg,int ioflg,struct ucred * active_cred,struct ucred * file_cred,size_t * aresid,struct thread * td)665 vn_rdwr_inchunks(enum uio_rw rw, struct vnode *vp, void *base, size_t len,
666     off_t offset, enum uio_seg segflg, int ioflg, struct ucred *active_cred,
667     struct ucred *file_cred, size_t *aresid, struct thread *td)
668 {
669 	int error = 0;
670 	ssize_t iaresid;
671 
672 	do {
673 		int chunk;
674 
675 		/*
676 		 * Force `offset' to a multiple of MAXBSIZE except possibly
677 		 * for the first chunk, so that filesystems only need to
678 		 * write full blocks except possibly for the first and last
679 		 * chunks.
680 		 */
681 		chunk = MAXBSIZE - (uoff_t)offset % MAXBSIZE;
682 
683 		if (chunk > len)
684 			chunk = len;
685 		if (rw != UIO_READ && vp->v_type == VREG)
686 			bwillwrite();
687 		iaresid = 0;
688 		error = vn_rdwr(rw, vp, base, chunk, offset, segflg,
689 		    ioflg, active_cred, file_cred, &iaresid, td);
690 		len -= chunk;	/* aresid calc already includes length */
691 		if (error)
692 			break;
693 		offset += chunk;
694 		base = (char *)base + chunk;
695 		kern_yield(PRI_USER);
696 	} while (len);
697 	if (aresid)
698 		*aresid = len + iaresid;
699 	return (error);
700 }
701 
702 #if OFF_MAX <= LONG_MAX
703 off_t
foffset_lock(struct file * fp,int flags)704 foffset_lock(struct file *fp, int flags)
705 {
706 	volatile short *flagsp;
707 	off_t res;
708 	short state;
709 
710 	KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
711 
712 	if ((flags & FOF_NOLOCK) != 0)
713 		return (atomic_load_long(&fp->f_offset));
714 
715 	/*
716 	 * According to McKusick the vn lock was protecting f_offset here.
717 	 * It is now protected by the FOFFSET_LOCKED flag.
718 	 */
719 	flagsp = &fp->f_vnread_flags;
720 	if (atomic_cmpset_acq_16(flagsp, 0, FOFFSET_LOCKED))
721 		return (atomic_load_long(&fp->f_offset));
722 
723 	sleepq_lock(&fp->f_vnread_flags);
724 	state = atomic_load_16(flagsp);
725 	for (;;) {
726 		if ((state & FOFFSET_LOCKED) == 0) {
727 			if (!atomic_fcmpset_acq_16(flagsp, &state,
728 			    FOFFSET_LOCKED))
729 				continue;
730 			break;
731 		}
732 		if ((state & FOFFSET_LOCK_WAITING) == 0) {
733 			if (!atomic_fcmpset_acq_16(flagsp, &state,
734 			    state | FOFFSET_LOCK_WAITING))
735 				continue;
736 		}
737 		DROP_GIANT();
738 		sleepq_add(&fp->f_vnread_flags, NULL, "vofflock", 0, 0);
739 		sleepq_wait(&fp->f_vnread_flags, PUSER -1);
740 		PICKUP_GIANT();
741 		sleepq_lock(&fp->f_vnread_flags);
742 		state = atomic_load_16(flagsp);
743 	}
744 	res = atomic_load_long(&fp->f_offset);
745 	sleepq_release(&fp->f_vnread_flags);
746 	return (res);
747 }
748 
749 void
foffset_unlock(struct file * fp,off_t val,int flags)750 foffset_unlock(struct file *fp, off_t val, int flags)
751 {
752 	volatile short *flagsp;
753 	short state;
754 
755 	KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
756 
757 	if ((flags & FOF_NOUPDATE) == 0)
758 		atomic_store_long(&fp->f_offset, val);
759 	if ((flags & FOF_NEXTOFF_R) != 0)
760 		fp->f_nextoff[UIO_READ] = val;
761 	if ((flags & FOF_NEXTOFF_W) != 0)
762 		fp->f_nextoff[UIO_WRITE] = val;
763 
764 	if ((flags & FOF_NOLOCK) != 0)
765 		return;
766 
767 	flagsp = &fp->f_vnread_flags;
768 	state = atomic_load_16(flagsp);
769 	if ((state & FOFFSET_LOCK_WAITING) == 0 &&
770 	    atomic_cmpset_rel_16(flagsp, state, 0))
771 		return;
772 
773 	sleepq_lock(&fp->f_vnread_flags);
774 	MPASS((fp->f_vnread_flags & FOFFSET_LOCKED) != 0);
775 	MPASS((fp->f_vnread_flags & FOFFSET_LOCK_WAITING) != 0);
776 	fp->f_vnread_flags = 0;
777 	sleepq_broadcast(&fp->f_vnread_flags, SLEEPQ_SLEEP, 0, 0);
778 	sleepq_release(&fp->f_vnread_flags);
779 }
780 #else
781 off_t
foffset_lock(struct file * fp,int flags)782 foffset_lock(struct file *fp, int flags)
783 {
784 	struct mtx *mtxp;
785 	off_t res;
786 
787 	KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
788 
789 	mtxp = mtx_pool_find(mtxpool_sleep, fp);
790 	mtx_lock(mtxp);
791 	if ((flags & FOF_NOLOCK) == 0) {
792 		while (fp->f_vnread_flags & FOFFSET_LOCKED) {
793 			fp->f_vnread_flags |= FOFFSET_LOCK_WAITING;
794 			msleep(&fp->f_vnread_flags, mtxp, PUSER -1,
795 			    "vofflock", 0);
796 		}
797 		fp->f_vnread_flags |= FOFFSET_LOCKED;
798 	}
799 	res = fp->f_offset;
800 	mtx_unlock(mtxp);
801 	return (res);
802 }
803 
804 void
foffset_unlock(struct file * fp,off_t val,int flags)805 foffset_unlock(struct file *fp, off_t val, int flags)
806 {
807 	struct mtx *mtxp;
808 
809 	KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
810 
811 	mtxp = mtx_pool_find(mtxpool_sleep, fp);
812 	mtx_lock(mtxp);
813 	if ((flags & FOF_NOUPDATE) == 0)
814 		fp->f_offset = val;
815 	if ((flags & FOF_NEXTOFF_R) != 0)
816 		fp->f_nextoff[UIO_READ] = val;
817 	if ((flags & FOF_NEXTOFF_W) != 0)
818 		fp->f_nextoff[UIO_WRITE] = val;
819 	if ((flags & FOF_NOLOCK) == 0) {
820 		KASSERT((fp->f_vnread_flags & FOFFSET_LOCKED) != 0,
821 		    ("Lost FOFFSET_LOCKED"));
822 		if (fp->f_vnread_flags & FOFFSET_LOCK_WAITING)
823 			wakeup(&fp->f_vnread_flags);
824 		fp->f_vnread_flags = 0;
825 	}
826 	mtx_unlock(mtxp);
827 }
828 #endif
829 
830 void
foffset_lock_uio(struct file * fp,struct uio * uio,int flags)831 foffset_lock_uio(struct file *fp, struct uio *uio, int flags)
832 {
833 
834 	if ((flags & FOF_OFFSET) == 0)
835 		uio->uio_offset = foffset_lock(fp, flags);
836 }
837 
838 void
foffset_unlock_uio(struct file * fp,struct uio * uio,int flags)839 foffset_unlock_uio(struct file *fp, struct uio *uio, int flags)
840 {
841 
842 	if ((flags & FOF_OFFSET) == 0)
843 		foffset_unlock(fp, uio->uio_offset, flags);
844 }
845 
846 static int
get_advice(struct file * fp,struct uio * uio)847 get_advice(struct file *fp, struct uio *uio)
848 {
849 	struct mtx *mtxp;
850 	int ret;
851 
852 	ret = POSIX_FADV_NORMAL;
853 	if (fp->f_advice == NULL || fp->f_vnode->v_type != VREG)
854 		return (ret);
855 
856 	mtxp = mtx_pool_find(mtxpool_sleep, fp);
857 	mtx_lock(mtxp);
858 	if (fp->f_advice != NULL &&
859 	    uio->uio_offset >= fp->f_advice->fa_start &&
860 	    uio->uio_offset + uio->uio_resid <= fp->f_advice->fa_end)
861 		ret = fp->f_advice->fa_advice;
862 	mtx_unlock(mtxp);
863 	return (ret);
864 }
865 
866 int
vn_read_from_obj(struct vnode * vp,struct uio * uio)867 vn_read_from_obj(struct vnode *vp, struct uio *uio)
868 {
869 	vm_object_t obj;
870 	vm_page_t ma[io_hold_cnt + 2];
871 	off_t off, vsz;
872 	ssize_t resid;
873 	int error, i, j;
874 
875 	MPASS(uio->uio_resid <= ptoa(io_hold_cnt + 2));
876 	obj = atomic_load_ptr(&vp->v_object);
877 	if (obj == NULL)
878 		return (EJUSTRETURN);
879 
880 	/*
881 	 * Depends on type stability of vm_objects.
882 	 */
883 	vm_object_pip_add(obj, 1);
884 	if ((obj->flags & OBJ_DEAD) != 0) {
885 		/*
886 		 * Note that object might be already reused from the
887 		 * vnode, and the OBJ_DEAD flag cleared.  This is fine,
888 		 * we recheck for DOOMED vnode state after all pages
889 		 * are busied, and retract then.
890 		 *
891 		 * But we check for OBJ_DEAD to ensure that we do not
892 		 * busy pages while vm_object_terminate_pages()
893 		 * processes the queue.
894 		 */
895 		error = EJUSTRETURN;
896 		goto out_pip;
897 	}
898 
899 	resid = uio->uio_resid;
900 	off = uio->uio_offset;
901 	for (i = 0; resid > 0; i++) {
902 		MPASS(i < io_hold_cnt + 2);
903 		ma[i] = vm_page_grab_unlocked(obj, atop(off),
904 		    VM_ALLOC_NOCREAT | VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY |
905 		    VM_ALLOC_NOWAIT);
906 		if (ma[i] == NULL)
907 			break;
908 
909 		/*
910 		 * Skip invalid pages.  Valid mask can be partial only
911 		 * at EOF, and we clip later.
912 		 */
913 		if (vm_page_none_valid(ma[i])) {
914 			vm_page_sunbusy(ma[i]);
915 			break;
916 		}
917 
918 		resid -= PAGE_SIZE;
919 		off += PAGE_SIZE;
920 	}
921 	if (i == 0) {
922 		error = EJUSTRETURN;
923 		goto out_pip;
924 	}
925 
926 	/*
927 	 * Check VIRF_DOOMED after we busied our pages.  Since
928 	 * vgonel() terminates the vnode' vm_object, it cannot
929 	 * process past pages busied by us.
930 	 */
931 	if (VN_IS_DOOMED(vp)) {
932 		error = EJUSTRETURN;
933 		goto out;
934 	}
935 
936 	resid = PAGE_SIZE - (uio->uio_offset & PAGE_MASK) + ptoa(i - 1);
937 	if (resid > uio->uio_resid)
938 		resid = uio->uio_resid;
939 
940 	/*
941 	 * Unlocked read of vnp_size is safe because truncation cannot
942 	 * pass busied page.  But we load vnp_size into a local
943 	 * variable so that possible concurrent extension does not
944 	 * break calculation.
945 	 */
946 #if defined(__powerpc__) && !defined(__powerpc64__)
947 	vsz = obj->un_pager.vnp.vnp_size;
948 #else
949 	vsz = atomic_load_64(&obj->un_pager.vnp.vnp_size);
950 #endif
951 	if (uio->uio_offset >= vsz) {
952 		error = EJUSTRETURN;
953 		goto out;
954 	}
955 	if (uio->uio_offset + resid > vsz)
956 		resid = vsz - uio->uio_offset;
957 
958 	error = vn_io_fault_pgmove(ma, uio->uio_offset & PAGE_MASK, resid, uio);
959 
960 out:
961 	for (j = 0; j < i; j++) {
962 		if (error == 0)
963 			vm_page_reference(ma[j]);
964 		vm_page_sunbusy(ma[j]);
965 	}
966 out_pip:
967 	vm_object_pip_wakeup(obj);
968 	if (error != 0)
969 		return (error);
970 	return (uio->uio_resid == 0 ? 0 : EJUSTRETURN);
971 }
972 
973 /*
974  * File table vnode read routine.
975  */
976 static int
vn_read(struct file * fp,struct uio * uio,struct ucred * active_cred,int flags,struct thread * td)977 vn_read(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags,
978     struct thread *td)
979 {
980 	struct vnode *vp;
981 	off_t orig_offset;
982 	int error, ioflag;
983 	int advice;
984 
985 	KASSERT(uio->uio_td == td, ("uio_td %p is not td %p",
986 	    uio->uio_td, td));
987 	KASSERT(flags & FOF_OFFSET, ("No FOF_OFFSET"));
988 	vp = fp->f_vnode;
989 	ioflag = 0;
990 	if (fp->f_flag & FNONBLOCK)
991 		ioflag |= IO_NDELAY;
992 	if (fp->f_flag & O_DIRECT)
993 		ioflag |= IO_DIRECT;
994 
995 	/*
996 	 * Try to read from page cache.  VIRF_DOOMED check is racy but
997 	 * allows us to avoid unneeded work outright.
998 	 */
999 	if (vn_io_pgcache_read_enable && !mac_vnode_check_read_enabled() &&
1000 	    (vn_irflag_read(vp) & (VIRF_DOOMED | VIRF_PGREAD)) == VIRF_PGREAD) {
1001 		error = VOP_READ_PGCACHE(vp, uio, ioflag, fp->f_cred);
1002 		if (error == 0) {
1003 			fp->f_nextoff[UIO_READ] = uio->uio_offset;
1004 			return (0);
1005 		}
1006 		if (error != EJUSTRETURN)
1007 			return (error);
1008 	}
1009 
1010 	advice = get_advice(fp, uio);
1011 	vn_lock(vp, LK_SHARED | LK_RETRY);
1012 
1013 	switch (advice) {
1014 	case POSIX_FADV_NORMAL:
1015 	case POSIX_FADV_SEQUENTIAL:
1016 	case POSIX_FADV_NOREUSE:
1017 		ioflag |= sequential_heuristic(uio, fp);
1018 		break;
1019 	case POSIX_FADV_RANDOM:
1020 		/* Disable read-ahead for random I/O. */
1021 		break;
1022 	}
1023 	orig_offset = uio->uio_offset;
1024 
1025 #ifdef MAC
1026 	error = mac_vnode_check_read(active_cred, fp->f_cred, vp);
1027 	if (error == 0)
1028 #endif
1029 		error = VOP_READ(vp, uio, ioflag, fp->f_cred);
1030 	fp->f_nextoff[UIO_READ] = uio->uio_offset;
1031 	VOP_UNLOCK(vp);
1032 	if (error == 0 && advice == POSIX_FADV_NOREUSE &&
1033 	    orig_offset != uio->uio_offset)
1034 		/*
1035 		 * Use POSIX_FADV_DONTNEED to flush pages and buffers
1036 		 * for the backing file after a POSIX_FADV_NOREUSE
1037 		 * read(2).
1038 		 */
1039 		error = VOP_ADVISE(vp, orig_offset, uio->uio_offset - 1,
1040 		    POSIX_FADV_DONTNEED);
1041 	return (error);
1042 }
1043 
1044 /*
1045  * File table vnode write routine.
1046  */
1047 static int
vn_write(struct file * fp,struct uio * uio,struct ucred * active_cred,int flags,struct thread * td)1048 vn_write(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags,
1049     struct thread *td)
1050 {
1051 	struct vnode *vp;
1052 	struct mount *mp;
1053 	off_t orig_offset;
1054 	int error, ioflag, lock_flags;
1055 	int advice;
1056 
1057 	KASSERT(uio->uio_td == td, ("uio_td %p is not td %p",
1058 	    uio->uio_td, td));
1059 	KASSERT(flags & FOF_OFFSET, ("No FOF_OFFSET"));
1060 	vp = fp->f_vnode;
1061 	if (vp->v_type == VREG)
1062 		bwillwrite();
1063 	ioflag = IO_UNIT;
1064 	if (vp->v_type == VREG && (fp->f_flag & O_APPEND))
1065 		ioflag |= IO_APPEND;
1066 	if (fp->f_flag & FNONBLOCK)
1067 		ioflag |= IO_NDELAY;
1068 	if (fp->f_flag & O_DIRECT)
1069 		ioflag |= IO_DIRECT;
1070 	if ((fp->f_flag & O_FSYNC) ||
1071 	    (vp->v_mount && (vp->v_mount->mnt_flag & MNT_SYNCHRONOUS)))
1072 		ioflag |= IO_SYNC;
1073 	/*
1074 	 * For O_DSYNC we set both IO_SYNC and IO_DATASYNC, so that VOP_WRITE()
1075 	 * implementations that don't understand IO_DATASYNC fall back to full
1076 	 * O_SYNC behavior.
1077 	 */
1078 	if (fp->f_flag & O_DSYNC)
1079 		ioflag |= IO_SYNC | IO_DATASYNC;
1080 	mp = NULL;
1081 	if (vp->v_type != VCHR &&
1082 	    (error = vn_start_write(vp, &mp, V_WAIT | PCATCH)) != 0)
1083 		goto unlock;
1084 
1085 	advice = get_advice(fp, uio);
1086 
1087 	if (MNT_SHARED_WRITES(mp) ||
1088 	    (mp == NULL && MNT_SHARED_WRITES(vp->v_mount))) {
1089 		lock_flags = LK_SHARED;
1090 	} else {
1091 		lock_flags = LK_EXCLUSIVE;
1092 	}
1093 
1094 	vn_lock(vp, lock_flags | LK_RETRY);
1095 	switch (advice) {
1096 	case POSIX_FADV_NORMAL:
1097 	case POSIX_FADV_SEQUENTIAL:
1098 	case POSIX_FADV_NOREUSE:
1099 		ioflag |= sequential_heuristic(uio, fp);
1100 		break;
1101 	case POSIX_FADV_RANDOM:
1102 		/* XXX: Is this correct? */
1103 		break;
1104 	}
1105 	orig_offset = uio->uio_offset;
1106 
1107 #ifdef MAC
1108 	error = mac_vnode_check_write(active_cred, fp->f_cred, vp);
1109 	if (error == 0)
1110 #endif
1111 		error = VOP_WRITE(vp, uio, ioflag, fp->f_cred);
1112 	fp->f_nextoff[UIO_WRITE] = uio->uio_offset;
1113 	VOP_UNLOCK(vp);
1114 	if (vp->v_type != VCHR)
1115 		vn_finished_write(mp);
1116 	if (error == 0 && advice == POSIX_FADV_NOREUSE &&
1117 	    orig_offset != uio->uio_offset)
1118 		/*
1119 		 * Use POSIX_FADV_DONTNEED to flush pages and buffers
1120 		 * for the backing file after a POSIX_FADV_NOREUSE
1121 		 * write(2).
1122 		 */
1123 		error = VOP_ADVISE(vp, orig_offset, uio->uio_offset - 1,
1124 		    POSIX_FADV_DONTNEED);
1125 unlock:
1126 	return (error);
1127 }
1128 
1129 /*
1130  * The vn_io_fault() is a wrapper around vn_read() and vn_write() to
1131  * prevent the following deadlock:
1132  *
1133  * Assume that the thread A reads from the vnode vp1 into userspace
1134  * buffer buf1 backed by the pages of vnode vp2.  If a page in buf1 is
1135  * currently not resident, then system ends up with the call chain
1136  *   vn_read() -> VOP_READ(vp1) -> uiomove() -> [Page Fault] ->
1137  *     vm_fault(buf1) -> vnode_pager_getpages(vp2) -> VOP_GETPAGES(vp2)
1138  * which establishes lock order vp1->vn_lock, then vp2->vn_lock.
1139  * If, at the same time, thread B reads from vnode vp2 into buffer buf2
1140  * backed by the pages of vnode vp1, and some page in buf2 is not
1141  * resident, we get a reversed order vp2->vn_lock, then vp1->vn_lock.
1142  *
1143  * To prevent the lock order reversal and deadlock, vn_io_fault() does
1144  * not allow page faults to happen during VOP_READ() or VOP_WRITE().
1145  * Instead, it first tries to do the whole range i/o with pagefaults
1146  * disabled. If all pages in the i/o buffer are resident and mapped,
1147  * VOP will succeed (ignoring the genuine filesystem errors).
1148  * Otherwise, we get back EFAULT, and vn_io_fault() falls back to do
1149  * i/o in chunks, with all pages in the chunk prefaulted and held
1150  * using vm_fault_quick_hold_pages().
1151  *
1152  * Filesystems using this deadlock avoidance scheme should use the
1153  * array of the held pages from uio, saved in the curthread->td_ma,
1154  * instead of doing uiomove().  A helper function
1155  * vn_io_fault_uiomove() converts uiomove request into
1156  * uiomove_fromphys() over td_ma array.
1157  *
1158  * Since vnode locks do not cover the whole i/o anymore, rangelocks
1159  * make the current i/o request atomic with respect to other i/os and
1160  * truncations.
1161  */
1162 
1163 /*
1164  * Decode vn_io_fault_args and perform the corresponding i/o.
1165  */
1166 static int
vn_io_fault_doio(struct vn_io_fault_args * args,struct uio * uio,struct thread * td)1167 vn_io_fault_doio(struct vn_io_fault_args *args, struct uio *uio,
1168     struct thread *td)
1169 {
1170 	int error, save;
1171 
1172 	error = 0;
1173 	save = vm_fault_disable_pagefaults();
1174 	switch (args->kind) {
1175 	case VN_IO_FAULT_FOP:
1176 		error = (args->args.fop_args.doio)(args->args.fop_args.fp,
1177 		    uio, args->cred, args->flags, td);
1178 		break;
1179 	case VN_IO_FAULT_VOP:
1180 		if (uio->uio_rw == UIO_READ) {
1181 			error = VOP_READ(args->args.vop_args.vp, uio,
1182 			    args->flags, args->cred);
1183 		} else if (uio->uio_rw == UIO_WRITE) {
1184 			error = VOP_WRITE(args->args.vop_args.vp, uio,
1185 			    args->flags, args->cred);
1186 		}
1187 		break;
1188 	default:
1189 		panic("vn_io_fault_doio: unknown kind of io %d %d",
1190 		    args->kind, uio->uio_rw);
1191 	}
1192 	vm_fault_enable_pagefaults(save);
1193 	return (error);
1194 }
1195 
1196 static int
vn_io_fault_touch(char * base,const struct uio * uio)1197 vn_io_fault_touch(char *base, const struct uio *uio)
1198 {
1199 	int r;
1200 
1201 	r = fubyte(base);
1202 	if (r == -1 || (uio->uio_rw == UIO_READ && subyte(base, r) == -1))
1203 		return (EFAULT);
1204 	return (0);
1205 }
1206 
1207 static int
vn_io_fault_prefault_user(const struct uio * uio)1208 vn_io_fault_prefault_user(const struct uio *uio)
1209 {
1210 	char *base;
1211 	const struct iovec *iov;
1212 	size_t len;
1213 	ssize_t resid;
1214 	int error, i;
1215 
1216 	KASSERT(uio->uio_segflg == UIO_USERSPACE,
1217 	    ("vn_io_fault_prefault userspace"));
1218 
1219 	error = i = 0;
1220 	iov = uio->uio_iov;
1221 	resid = uio->uio_resid;
1222 	base = iov->iov_base;
1223 	len = iov->iov_len;
1224 	while (resid > 0) {
1225 		error = vn_io_fault_touch(base, uio);
1226 		if (error != 0)
1227 			break;
1228 		if (len < PAGE_SIZE) {
1229 			if (len != 0) {
1230 				error = vn_io_fault_touch(base + len - 1, uio);
1231 				if (error != 0)
1232 					break;
1233 				resid -= len;
1234 			}
1235 			if (++i >= uio->uio_iovcnt)
1236 				break;
1237 			iov = uio->uio_iov + i;
1238 			base = iov->iov_base;
1239 			len = iov->iov_len;
1240 		} else {
1241 			len -= PAGE_SIZE;
1242 			base += PAGE_SIZE;
1243 			resid -= PAGE_SIZE;
1244 		}
1245 	}
1246 	return (error);
1247 }
1248 
1249 /*
1250  * Common code for vn_io_fault(), agnostic to the kind of i/o request.
1251  * Uses vn_io_fault_doio() to make the call to an actual i/o function.
1252  * Used from vn_rdwr() and vn_io_fault(), which encode the i/o request
1253  * into args and call vn_io_fault1() to handle faults during the user
1254  * mode buffer accesses.
1255  */
1256 static int
vn_io_fault1(struct vnode * vp,struct uio * uio,struct vn_io_fault_args * args,struct thread * td)1257 vn_io_fault1(struct vnode *vp, struct uio *uio, struct vn_io_fault_args *args,
1258     struct thread *td)
1259 {
1260 	vm_page_t ma[io_hold_cnt + 2];
1261 	struct uio *uio_clone, short_uio;
1262 	struct iovec short_iovec[1];
1263 	vm_page_t *prev_td_ma;
1264 	vm_prot_t prot;
1265 	vm_offset_t addr, end;
1266 	size_t len, resid;
1267 	ssize_t adv;
1268 	int error, cnt, saveheld, prev_td_ma_cnt;
1269 
1270 	if (vn_io_fault_prefault) {
1271 		error = vn_io_fault_prefault_user(uio);
1272 		if (error != 0)
1273 			return (error); /* Or ignore ? */
1274 	}
1275 
1276 	prot = uio->uio_rw == UIO_READ ? VM_PROT_WRITE : VM_PROT_READ;
1277 
1278 	/*
1279 	 * The UFS follows IO_UNIT directive and replays back both
1280 	 * uio_offset and uio_resid if an error is encountered during the
1281 	 * operation.  But, since the iovec may be already advanced,
1282 	 * uio is still in an inconsistent state.
1283 	 *
1284 	 * Cache a copy of the original uio, which is advanced to the redo
1285 	 * point using UIO_NOCOPY below.
1286 	 */
1287 	uio_clone = cloneuio(uio);
1288 	resid = uio->uio_resid;
1289 
1290 	short_uio.uio_segflg = UIO_USERSPACE;
1291 	short_uio.uio_rw = uio->uio_rw;
1292 	short_uio.uio_td = uio->uio_td;
1293 
1294 	error = vn_io_fault_doio(args, uio, td);
1295 	if (error != EFAULT)
1296 		goto out;
1297 
1298 	atomic_add_long(&vn_io_faults_cnt, 1);
1299 	uio_clone->uio_segflg = UIO_NOCOPY;
1300 	uiomove(NULL, resid - uio->uio_resid, uio_clone);
1301 	uio_clone->uio_segflg = uio->uio_segflg;
1302 
1303 	saveheld = curthread_pflags_set(TDP_UIOHELD);
1304 	prev_td_ma = td->td_ma;
1305 	prev_td_ma_cnt = td->td_ma_cnt;
1306 
1307 	while (uio_clone->uio_resid != 0) {
1308 		len = uio_clone->uio_iov->iov_len;
1309 		if (len == 0) {
1310 			KASSERT(uio_clone->uio_iovcnt >= 1,
1311 			    ("iovcnt underflow"));
1312 			uio_clone->uio_iov++;
1313 			uio_clone->uio_iovcnt--;
1314 			continue;
1315 		}
1316 		if (len > ptoa(io_hold_cnt))
1317 			len = ptoa(io_hold_cnt);
1318 		addr = (uintptr_t)uio_clone->uio_iov->iov_base;
1319 		end = round_page(addr + len);
1320 		if (end < addr) {
1321 			error = EFAULT;
1322 			break;
1323 		}
1324 		cnt = atop(end - trunc_page(addr));
1325 		/*
1326 		 * A perfectly misaligned address and length could cause
1327 		 * both the start and the end of the chunk to use partial
1328 		 * page.  +2 accounts for such a situation.
1329 		 */
1330 		cnt = vm_fault_quick_hold_pages(&td->td_proc->p_vmspace->vm_map,
1331 		    addr, len, prot, ma, io_hold_cnt + 2);
1332 		if (cnt == -1) {
1333 			error = EFAULT;
1334 			break;
1335 		}
1336 		short_uio.uio_iov = &short_iovec[0];
1337 		short_iovec[0].iov_base = (void *)addr;
1338 		short_uio.uio_iovcnt = 1;
1339 		short_uio.uio_resid = short_iovec[0].iov_len = len;
1340 		short_uio.uio_offset = uio_clone->uio_offset;
1341 		td->td_ma = ma;
1342 		td->td_ma_cnt = cnt;
1343 
1344 		error = vn_io_fault_doio(args, &short_uio, td);
1345 		vm_page_unhold_pages(ma, cnt);
1346 		adv = len - short_uio.uio_resid;
1347 
1348 		uio_clone->uio_iov->iov_base =
1349 		    (char *)uio_clone->uio_iov->iov_base + adv;
1350 		uio_clone->uio_iov->iov_len -= adv;
1351 		uio_clone->uio_resid -= adv;
1352 		uio_clone->uio_offset += adv;
1353 
1354 		uio->uio_resid -= adv;
1355 		uio->uio_offset += adv;
1356 
1357 		if (error != 0 || adv == 0)
1358 			break;
1359 	}
1360 	td->td_ma = prev_td_ma;
1361 	td->td_ma_cnt = prev_td_ma_cnt;
1362 	curthread_pflags_restore(saveheld);
1363 out:
1364 	free(uio_clone, M_IOV);
1365 	return (error);
1366 }
1367 
1368 static int
vn_io_fault(struct file * fp,struct uio * uio,struct ucred * active_cred,int flags,struct thread * td)1369 vn_io_fault(struct file *fp, struct uio *uio, struct ucred *active_cred,
1370     int flags, struct thread *td)
1371 {
1372 	fo_rdwr_t *doio;
1373 	struct vnode *vp;
1374 	void *rl_cookie;
1375 	struct vn_io_fault_args args;
1376 	int error;
1377 
1378 	doio = uio->uio_rw == UIO_READ ? vn_read : vn_write;
1379 	vp = fp->f_vnode;
1380 
1381 	/*
1382 	 * The ability to read(2) on a directory has historically been
1383 	 * allowed for all users, but this can and has been the source of
1384 	 * at least one security issue in the past.  As such, it is now hidden
1385 	 * away behind a sysctl for those that actually need it to use it, and
1386 	 * restricted to root when it's turned on to make it relatively safe to
1387 	 * leave on for longer sessions of need.
1388 	 */
1389 	if (vp->v_type == VDIR) {
1390 		KASSERT(uio->uio_rw == UIO_READ,
1391 		    ("illegal write attempted on a directory"));
1392 		if (!vfs_allow_read_dir)
1393 			return (EISDIR);
1394 		if ((error = priv_check(td, PRIV_VFS_READ_DIR)) != 0)
1395 			return (EISDIR);
1396 	}
1397 
1398 	foffset_lock_uio(fp, uio, flags);
1399 	if (do_vn_io_fault(vp, uio)) {
1400 		args.kind = VN_IO_FAULT_FOP;
1401 		args.args.fop_args.fp = fp;
1402 		args.args.fop_args.doio = doio;
1403 		args.cred = active_cred;
1404 		args.flags = flags | FOF_OFFSET;
1405 		if (uio->uio_rw == UIO_READ) {
1406 			rl_cookie = vn_rangelock_rlock(vp, uio->uio_offset,
1407 			    uio->uio_offset + uio->uio_resid);
1408 		} else if ((fp->f_flag & O_APPEND) != 0 ||
1409 		    (flags & FOF_OFFSET) == 0) {
1410 			/* For appenders, punt and lock the whole range. */
1411 			rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
1412 		} else {
1413 			rl_cookie = vn_rangelock_wlock(vp, uio->uio_offset,
1414 			    uio->uio_offset + uio->uio_resid);
1415 		}
1416 		error = vn_io_fault1(vp, uio, &args, td);
1417 		vn_rangelock_unlock(vp, rl_cookie);
1418 	} else {
1419 		error = doio(fp, uio, active_cred, flags | FOF_OFFSET, td);
1420 	}
1421 	foffset_unlock_uio(fp, uio, flags);
1422 	return (error);
1423 }
1424 
1425 /*
1426  * Helper function to perform the requested uiomove operation using
1427  * the held pages for io->uio_iov[0].iov_base buffer instead of
1428  * copyin/copyout.  Access to the pages with uiomove_fromphys()
1429  * instead of iov_base prevents page faults that could occur due to
1430  * pmap_collect() invalidating the mapping created by
1431  * vm_fault_quick_hold_pages(), or pageout daemon, page laundry or
1432  * object cleanup revoking the write access from page mappings.
1433  *
1434  * Filesystems specified MNTK_NO_IOPF shall use vn_io_fault_uiomove()
1435  * instead of plain uiomove().
1436  */
1437 int
vn_io_fault_uiomove(char * data,int xfersize,struct uio * uio)1438 vn_io_fault_uiomove(char *data, int xfersize, struct uio *uio)
1439 {
1440 	struct uio transp_uio;
1441 	struct iovec transp_iov[1];
1442 	struct thread *td;
1443 	size_t adv;
1444 	int error, pgadv;
1445 
1446 	td = curthread;
1447 	if ((td->td_pflags & TDP_UIOHELD) == 0 ||
1448 	    uio->uio_segflg != UIO_USERSPACE)
1449 		return (uiomove(data, xfersize, uio));
1450 
1451 	KASSERT(uio->uio_iovcnt == 1, ("uio_iovcnt %d", uio->uio_iovcnt));
1452 	transp_iov[0].iov_base = data;
1453 	transp_uio.uio_iov = &transp_iov[0];
1454 	transp_uio.uio_iovcnt = 1;
1455 	if (xfersize > uio->uio_resid)
1456 		xfersize = uio->uio_resid;
1457 	transp_uio.uio_resid = transp_iov[0].iov_len = xfersize;
1458 	transp_uio.uio_offset = 0;
1459 	transp_uio.uio_segflg = UIO_SYSSPACE;
1460 	/*
1461 	 * Since transp_iov points to data, and td_ma page array
1462 	 * corresponds to original uio->uio_iov, we need to invert the
1463 	 * direction of the i/o operation as passed to
1464 	 * uiomove_fromphys().
1465 	 */
1466 	switch (uio->uio_rw) {
1467 	case UIO_WRITE:
1468 		transp_uio.uio_rw = UIO_READ;
1469 		break;
1470 	case UIO_READ:
1471 		transp_uio.uio_rw = UIO_WRITE;
1472 		break;
1473 	}
1474 	transp_uio.uio_td = uio->uio_td;
1475 	error = uiomove_fromphys(td->td_ma,
1476 	    ((vm_offset_t)uio->uio_iov->iov_base) & PAGE_MASK,
1477 	    xfersize, &transp_uio);
1478 	adv = xfersize - transp_uio.uio_resid;
1479 	pgadv =
1480 	    (((vm_offset_t)uio->uio_iov->iov_base + adv) >> PAGE_SHIFT) -
1481 	    (((vm_offset_t)uio->uio_iov->iov_base) >> PAGE_SHIFT);
1482 	td->td_ma += pgadv;
1483 	KASSERT(td->td_ma_cnt >= pgadv, ("consumed pages %d %d", td->td_ma_cnt,
1484 	    pgadv));
1485 	td->td_ma_cnt -= pgadv;
1486 	uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + adv;
1487 	uio->uio_iov->iov_len -= adv;
1488 	uio->uio_resid -= adv;
1489 	uio->uio_offset += adv;
1490 	return (error);
1491 }
1492 
1493 int
vn_io_fault_pgmove(vm_page_t ma[],vm_offset_t offset,int xfersize,struct uio * uio)1494 vn_io_fault_pgmove(vm_page_t ma[], vm_offset_t offset, int xfersize,
1495     struct uio *uio)
1496 {
1497 	struct thread *td;
1498 	vm_offset_t iov_base;
1499 	int cnt, pgadv;
1500 
1501 	td = curthread;
1502 	if ((td->td_pflags & TDP_UIOHELD) == 0 ||
1503 	    uio->uio_segflg != UIO_USERSPACE)
1504 		return (uiomove_fromphys(ma, offset, xfersize, uio));
1505 
1506 	KASSERT(uio->uio_iovcnt == 1, ("uio_iovcnt %d", uio->uio_iovcnt));
1507 	cnt = xfersize > uio->uio_resid ? uio->uio_resid : xfersize;
1508 	iov_base = (vm_offset_t)uio->uio_iov->iov_base;
1509 	switch (uio->uio_rw) {
1510 	case UIO_WRITE:
1511 		pmap_copy_pages(td->td_ma, iov_base & PAGE_MASK, ma,
1512 		    offset, cnt);
1513 		break;
1514 	case UIO_READ:
1515 		pmap_copy_pages(ma, offset, td->td_ma, iov_base & PAGE_MASK,
1516 		    cnt);
1517 		break;
1518 	}
1519 	pgadv = ((iov_base + cnt) >> PAGE_SHIFT) - (iov_base >> PAGE_SHIFT);
1520 	td->td_ma += pgadv;
1521 	KASSERT(td->td_ma_cnt >= pgadv, ("consumed pages %d %d", td->td_ma_cnt,
1522 	    pgadv));
1523 	td->td_ma_cnt -= pgadv;
1524 	uio->uio_iov->iov_base = (char *)(iov_base + cnt);
1525 	uio->uio_iov->iov_len -= cnt;
1526 	uio->uio_resid -= cnt;
1527 	uio->uio_offset += cnt;
1528 	return (0);
1529 }
1530 
1531 /*
1532  * File table truncate routine.
1533  */
1534 static int
vn_truncate(struct file * fp,off_t length,struct ucred * active_cred,struct thread * td)1535 vn_truncate(struct file *fp, off_t length, struct ucred *active_cred,
1536     struct thread *td)
1537 {
1538 	struct mount *mp;
1539 	struct vnode *vp;
1540 	void *rl_cookie;
1541 	int error;
1542 
1543 	vp = fp->f_vnode;
1544 
1545 retry:
1546 	/*
1547 	 * Lock the whole range for truncation.  Otherwise split i/o
1548 	 * might happen partly before and partly after the truncation.
1549 	 */
1550 	rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
1551 	error = vn_start_write(vp, &mp, V_WAIT | PCATCH);
1552 	if (error)
1553 		goto out1;
1554 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1555 	AUDIT_ARG_VNODE1(vp);
1556 	if (vp->v_type == VDIR) {
1557 		error = EISDIR;
1558 		goto out;
1559 	}
1560 #ifdef MAC
1561 	error = mac_vnode_check_write(active_cred, fp->f_cred, vp);
1562 	if (error)
1563 		goto out;
1564 #endif
1565 	error = vn_truncate_locked(vp, length, (fp->f_flag & O_FSYNC) != 0,
1566 	    fp->f_cred);
1567 out:
1568 	VOP_UNLOCK(vp);
1569 	vn_finished_write(mp);
1570 out1:
1571 	vn_rangelock_unlock(vp, rl_cookie);
1572 	if (error == ERELOOKUP)
1573 		goto retry;
1574 	return (error);
1575 }
1576 
1577 /*
1578  * Truncate a file that is already locked.
1579  */
1580 int
vn_truncate_locked(struct vnode * vp,off_t length,bool sync,struct ucred * cred)1581 vn_truncate_locked(struct vnode *vp, off_t length, bool sync,
1582     struct ucred *cred)
1583 {
1584 	struct vattr vattr;
1585 	int error;
1586 
1587 	error = VOP_ADD_WRITECOUNT(vp, 1);
1588 	if (error == 0) {
1589 		VATTR_NULL(&vattr);
1590 		vattr.va_size = length;
1591 		if (sync)
1592 			vattr.va_vaflags |= VA_SYNC;
1593 		error = VOP_SETATTR(vp, &vattr, cred);
1594 		VOP_ADD_WRITECOUNT_CHECKED(vp, -1);
1595 	}
1596 	return (error);
1597 }
1598 
1599 /*
1600  * File table vnode stat routine.
1601  */
1602 static int
vn_statfile(struct file * fp,struct stat * sb,struct ucred * active_cred,struct thread * td)1603 vn_statfile(struct file *fp, struct stat *sb, struct ucred *active_cred,
1604     struct thread *td)
1605 {
1606 	struct vnode *vp = fp->f_vnode;
1607 	int error;
1608 
1609 	vn_lock(vp, LK_SHARED | LK_RETRY);
1610 	error = VOP_STAT(vp, sb, active_cred, fp->f_cred, td);
1611 	VOP_UNLOCK(vp);
1612 
1613 	return (error);
1614 }
1615 
1616 /*
1617  * File table vnode ioctl routine.
1618  */
1619 static int
vn_ioctl(struct file * fp,u_long com,void * data,struct ucred * active_cred,struct thread * td)1620 vn_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
1621     struct thread *td)
1622 {
1623 	struct vattr vattr;
1624 	struct vnode *vp;
1625 	struct fiobmap2_arg *bmarg;
1626 	int error;
1627 
1628 	vp = fp->f_vnode;
1629 	switch (vp->v_type) {
1630 	case VDIR:
1631 	case VREG:
1632 		switch (com) {
1633 		case FIONREAD:
1634 			vn_lock(vp, LK_SHARED | LK_RETRY);
1635 			error = VOP_GETATTR(vp, &vattr, active_cred);
1636 			VOP_UNLOCK(vp);
1637 			if (error == 0)
1638 				*(int *)data = vattr.va_size - fp->f_offset;
1639 			return (error);
1640 		case FIOBMAP2:
1641 			bmarg = (struct fiobmap2_arg *)data;
1642 			vn_lock(vp, LK_SHARED | LK_RETRY);
1643 #ifdef MAC
1644 			error = mac_vnode_check_read(active_cred, fp->f_cred,
1645 			    vp);
1646 			if (error == 0)
1647 #endif
1648 				error = VOP_BMAP(vp, bmarg->bn, NULL,
1649 				    &bmarg->bn, &bmarg->runp, &bmarg->runb);
1650 			VOP_UNLOCK(vp);
1651 			return (error);
1652 		case FIONBIO:
1653 		case FIOASYNC:
1654 			return (0);
1655 		default:
1656 			return (VOP_IOCTL(vp, com, data, fp->f_flag,
1657 			    active_cred, td));
1658 		}
1659 		break;
1660 	case VCHR:
1661 		return (VOP_IOCTL(vp, com, data, fp->f_flag,
1662 		    active_cred, td));
1663 	default:
1664 		return (ENOTTY);
1665 	}
1666 }
1667 
1668 /*
1669  * File table vnode poll routine.
1670  */
1671 static int
vn_poll(struct file * fp,int events,struct ucred * active_cred,struct thread * td)1672 vn_poll(struct file *fp, int events, struct ucred *active_cred,
1673     struct thread *td)
1674 {
1675 	struct vnode *vp;
1676 	int error;
1677 
1678 	vp = fp->f_vnode;
1679 #if defined(MAC) || defined(AUDIT)
1680 	if (AUDITING_TD(td) || mac_vnode_check_poll_enabled()) {
1681 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1682 		AUDIT_ARG_VNODE1(vp);
1683 		error = mac_vnode_check_poll(active_cred, fp->f_cred, vp);
1684 		VOP_UNLOCK(vp);
1685 		if (error != 0)
1686 			return (error);
1687 	}
1688 #endif
1689 	error = VOP_POLL(vp, events, fp->f_cred, td);
1690 	return (error);
1691 }
1692 
1693 /*
1694  * Acquire the requested lock and then check for validity.  LK_RETRY
1695  * permits vn_lock to return doomed vnodes.
1696  */
1697 static int __noinline
_vn_lock_fallback(struct vnode * vp,int flags,const char * file,int line,int error)1698 _vn_lock_fallback(struct vnode *vp, int flags, const char *file, int line,
1699     int error)
1700 {
1701 
1702 	KASSERT((flags & LK_RETRY) == 0 || error == 0,
1703 	    ("vn_lock: error %d incompatible with flags %#x", error, flags));
1704 
1705 	if (error == 0)
1706 		VNASSERT(VN_IS_DOOMED(vp), vp, ("vnode not doomed"));
1707 
1708 	if ((flags & LK_RETRY) == 0) {
1709 		if (error == 0) {
1710 			VOP_UNLOCK(vp);
1711 			error = ENOENT;
1712 		}
1713 		return (error);
1714 	}
1715 
1716 	/*
1717 	 * LK_RETRY case.
1718 	 *
1719 	 * Nothing to do if we got the lock.
1720 	 */
1721 	if (error == 0)
1722 		return (0);
1723 
1724 	/*
1725 	 * Interlock was dropped by the call in _vn_lock.
1726 	 */
1727 	flags &= ~LK_INTERLOCK;
1728 	do {
1729 		error = VOP_LOCK1(vp, flags, file, line);
1730 	} while (error != 0);
1731 	return (0);
1732 }
1733 
1734 int
_vn_lock(struct vnode * vp,int flags,const char * file,int line)1735 _vn_lock(struct vnode *vp, int flags, const char *file, int line)
1736 {
1737 	int error;
1738 
1739 	VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
1740 	    ("vn_lock: no locktype (%d passed)", flags));
1741 	VNPASS(vp->v_holdcnt > 0, vp);
1742 	error = VOP_LOCK1(vp, flags, file, line);
1743 	if (__predict_false(error != 0 || VN_IS_DOOMED(vp)))
1744 		return (_vn_lock_fallback(vp, flags, file, line, error));
1745 	return (0);
1746 }
1747 
1748 /*
1749  * File table vnode close routine.
1750  */
1751 static int
vn_closefile(struct file * fp,struct thread * td)1752 vn_closefile(struct file *fp, struct thread *td)
1753 {
1754 	struct vnode *vp;
1755 	struct flock lf;
1756 	int error;
1757 	bool ref;
1758 
1759 	vp = fp->f_vnode;
1760 	fp->f_ops = &badfileops;
1761 	ref= (fp->f_flag & FHASLOCK) != 0 && fp->f_type == DTYPE_VNODE;
1762 
1763 	error = vn_close1(vp, fp->f_flag, fp->f_cred, td, ref);
1764 
1765 	if (__predict_false(ref)) {
1766 		lf.l_whence = SEEK_SET;
1767 		lf.l_start = 0;
1768 		lf.l_len = 0;
1769 		lf.l_type = F_UNLCK;
1770 		(void) VOP_ADVLOCK(vp, fp, F_UNLCK, &lf, F_FLOCK);
1771 		vrele(vp);
1772 	}
1773 	return (error);
1774 }
1775 
1776 /*
1777  * Preparing to start a filesystem write operation. If the operation is
1778  * permitted, then we bump the count of operations in progress and
1779  * proceed. If a suspend request is in progress, we wait until the
1780  * suspension is over, and then proceed.
1781  */
1782 static int
vn_start_write_refed(struct mount * mp,int flags,bool mplocked)1783 vn_start_write_refed(struct mount *mp, int flags, bool mplocked)
1784 {
1785 	struct mount_pcpu *mpcpu;
1786 	int error, mflags;
1787 
1788 	if (__predict_true(!mplocked) && (flags & V_XSLEEP) == 0 &&
1789 	    vfs_op_thread_enter(mp, mpcpu)) {
1790 		MPASS((mp->mnt_kern_flag & MNTK_SUSPEND) == 0);
1791 		vfs_mp_count_add_pcpu(mpcpu, writeopcount, 1);
1792 		vfs_op_thread_exit(mp, mpcpu);
1793 		return (0);
1794 	}
1795 
1796 	if (mplocked)
1797 		mtx_assert(MNT_MTX(mp), MA_OWNED);
1798 	else
1799 		MNT_ILOCK(mp);
1800 
1801 	error = 0;
1802 
1803 	/*
1804 	 * Check on status of suspension.
1805 	 */
1806 	if ((curthread->td_pflags & TDP_IGNSUSP) == 0 ||
1807 	    mp->mnt_susp_owner != curthread) {
1808 		mflags = ((mp->mnt_vfc->vfc_flags & VFCF_SBDRY) != 0 ?
1809 		    (flags & PCATCH) : 0) | (PUSER - 1);
1810 		while ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0) {
1811 			if (flags & V_NOWAIT) {
1812 				error = EWOULDBLOCK;
1813 				goto unlock;
1814 			}
1815 			error = msleep(&mp->mnt_flag, MNT_MTX(mp), mflags,
1816 			    "suspfs", 0);
1817 			if (error)
1818 				goto unlock;
1819 		}
1820 	}
1821 	if (flags & V_XSLEEP)
1822 		goto unlock;
1823 	mp->mnt_writeopcount++;
1824 unlock:
1825 	if (error != 0 || (flags & V_XSLEEP) != 0)
1826 		MNT_REL(mp);
1827 	MNT_IUNLOCK(mp);
1828 	return (error);
1829 }
1830 
1831 int
vn_start_write(struct vnode * vp,struct mount ** mpp,int flags)1832 vn_start_write(struct vnode *vp, struct mount **mpp, int flags)
1833 {
1834 	struct mount *mp;
1835 	int error;
1836 
1837 	KASSERT((flags & V_MNTREF) == 0 || (*mpp != NULL && vp == NULL),
1838 	    ("V_MNTREF requires mp"));
1839 
1840 	error = 0;
1841 	/*
1842 	 * If a vnode is provided, get and return the mount point that
1843 	 * to which it will write.
1844 	 */
1845 	if (vp != NULL) {
1846 		if ((error = VOP_GETWRITEMOUNT(vp, mpp)) != 0) {
1847 			*mpp = NULL;
1848 			if (error != EOPNOTSUPP)
1849 				return (error);
1850 			return (0);
1851 		}
1852 	}
1853 	if ((mp = *mpp) == NULL)
1854 		return (0);
1855 
1856 	/*
1857 	 * VOP_GETWRITEMOUNT() returns with the mp refcount held through
1858 	 * a vfs_ref().
1859 	 * As long as a vnode is not provided we need to acquire a
1860 	 * refcount for the provided mountpoint too, in order to
1861 	 * emulate a vfs_ref().
1862 	 */
1863 	if (vp == NULL && (flags & V_MNTREF) == 0)
1864 		vfs_ref(mp);
1865 
1866 	return (vn_start_write_refed(mp, flags, false));
1867 }
1868 
1869 /*
1870  * Secondary suspension. Used by operations such as vop_inactive
1871  * routines that are needed by the higher level functions. These
1872  * are allowed to proceed until all the higher level functions have
1873  * completed (indicated by mnt_writeopcount dropping to zero). At that
1874  * time, these operations are halted until the suspension is over.
1875  */
1876 int
vn_start_secondary_write(struct vnode * vp,struct mount ** mpp,int flags)1877 vn_start_secondary_write(struct vnode *vp, struct mount **mpp, int flags)
1878 {
1879 	struct mount *mp;
1880 	int error;
1881 
1882 	KASSERT((flags & V_MNTREF) == 0 || (*mpp != NULL && vp == NULL),
1883 	    ("V_MNTREF requires mp"));
1884 
1885  retry:
1886 	if (vp != NULL) {
1887 		if ((error = VOP_GETWRITEMOUNT(vp, mpp)) != 0) {
1888 			*mpp = NULL;
1889 			if (error != EOPNOTSUPP)
1890 				return (error);
1891 			return (0);
1892 		}
1893 	}
1894 	/*
1895 	 * If we are not suspended or have not yet reached suspended
1896 	 * mode, then let the operation proceed.
1897 	 */
1898 	if ((mp = *mpp) == NULL)
1899 		return (0);
1900 
1901 	/*
1902 	 * VOP_GETWRITEMOUNT() returns with the mp refcount held through
1903 	 * a vfs_ref().
1904 	 * As long as a vnode is not provided we need to acquire a
1905 	 * refcount for the provided mountpoint too, in order to
1906 	 * emulate a vfs_ref().
1907 	 */
1908 	MNT_ILOCK(mp);
1909 	if (vp == NULL && (flags & V_MNTREF) == 0)
1910 		MNT_REF(mp);
1911 	if ((mp->mnt_kern_flag & (MNTK_SUSPENDED | MNTK_SUSPEND2)) == 0) {
1912 		mp->mnt_secondary_writes++;
1913 		mp->mnt_secondary_accwrites++;
1914 		MNT_IUNLOCK(mp);
1915 		return (0);
1916 	}
1917 	if (flags & V_NOWAIT) {
1918 		MNT_REL(mp);
1919 		MNT_IUNLOCK(mp);
1920 		return (EWOULDBLOCK);
1921 	}
1922 	/*
1923 	 * Wait for the suspension to finish.
1924 	 */
1925 	error = msleep(&mp->mnt_flag, MNT_MTX(mp), (PUSER - 1) | PDROP |
1926 	    ((mp->mnt_vfc->vfc_flags & VFCF_SBDRY) != 0 ? (flags & PCATCH) : 0),
1927 	    "suspfs", 0);
1928 	vfs_rel(mp);
1929 	if (error == 0)
1930 		goto retry;
1931 	return (error);
1932 }
1933 
1934 /*
1935  * Filesystem write operation has completed. If we are suspending and this
1936  * operation is the last one, notify the suspender that the suspension is
1937  * now in effect.
1938  */
1939 void
vn_finished_write(struct mount * mp)1940 vn_finished_write(struct mount *mp)
1941 {
1942 	struct mount_pcpu *mpcpu;
1943 	int c;
1944 
1945 	if (mp == NULL)
1946 		return;
1947 
1948 	if (vfs_op_thread_enter(mp, mpcpu)) {
1949 		vfs_mp_count_sub_pcpu(mpcpu, writeopcount, 1);
1950 		vfs_mp_count_sub_pcpu(mpcpu, ref, 1);
1951 		vfs_op_thread_exit(mp, mpcpu);
1952 		return;
1953 	}
1954 
1955 	MNT_ILOCK(mp);
1956 	vfs_assert_mount_counters(mp);
1957 	MNT_REL(mp);
1958 	c = --mp->mnt_writeopcount;
1959 	if (mp->mnt_vfs_ops == 0) {
1960 		MPASS((mp->mnt_kern_flag & MNTK_SUSPEND) == 0);
1961 		MNT_IUNLOCK(mp);
1962 		return;
1963 	}
1964 	if (c < 0)
1965 		vfs_dump_mount_counters(mp);
1966 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0 && c == 0)
1967 		wakeup(&mp->mnt_writeopcount);
1968 	MNT_IUNLOCK(mp);
1969 }
1970 
1971 /*
1972  * Filesystem secondary write operation has completed. If we are
1973  * suspending and this operation is the last one, notify the suspender
1974  * that the suspension is now in effect.
1975  */
1976 void
vn_finished_secondary_write(struct mount * mp)1977 vn_finished_secondary_write(struct mount *mp)
1978 {
1979 	if (mp == NULL)
1980 		return;
1981 	MNT_ILOCK(mp);
1982 	MNT_REL(mp);
1983 	mp->mnt_secondary_writes--;
1984 	if (mp->mnt_secondary_writes < 0)
1985 		panic("vn_finished_secondary_write: neg cnt");
1986 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0 &&
1987 	    mp->mnt_secondary_writes <= 0)
1988 		wakeup(&mp->mnt_secondary_writes);
1989 	MNT_IUNLOCK(mp);
1990 }
1991 
1992 /*
1993  * Request a filesystem to suspend write operations.
1994  */
1995 int
vfs_write_suspend(struct mount * mp,int flags)1996 vfs_write_suspend(struct mount *mp, int flags)
1997 {
1998 	int error;
1999 
2000 	vfs_op_enter(mp);
2001 
2002 	MNT_ILOCK(mp);
2003 	vfs_assert_mount_counters(mp);
2004 	if (mp->mnt_susp_owner == curthread) {
2005 		vfs_op_exit_locked(mp);
2006 		MNT_IUNLOCK(mp);
2007 		return (EALREADY);
2008 	}
2009 	while (mp->mnt_kern_flag & MNTK_SUSPEND)
2010 		msleep(&mp->mnt_flag, MNT_MTX(mp), PUSER - 1, "wsuspfs", 0);
2011 
2012 	/*
2013 	 * Unmount holds a write reference on the mount point.  If we
2014 	 * own busy reference and drain for writers, we deadlock with
2015 	 * the reference draining in the unmount path.  Callers of
2016 	 * vfs_write_suspend() must specify VS_SKIP_UNMOUNT if
2017 	 * vfs_busy() reference is owned and caller is not in the
2018 	 * unmount context.
2019 	 */
2020 	if ((flags & VS_SKIP_UNMOUNT) != 0 &&
2021 	    (mp->mnt_kern_flag & MNTK_UNMOUNT) != 0) {
2022 		vfs_op_exit_locked(mp);
2023 		MNT_IUNLOCK(mp);
2024 		return (EBUSY);
2025 	}
2026 
2027 	mp->mnt_kern_flag |= MNTK_SUSPEND;
2028 	mp->mnt_susp_owner = curthread;
2029 	if (mp->mnt_writeopcount > 0)
2030 		(void) msleep(&mp->mnt_writeopcount,
2031 		    MNT_MTX(mp), (PUSER - 1)|PDROP, "suspwt", 0);
2032 	else
2033 		MNT_IUNLOCK(mp);
2034 	if ((error = VFS_SYNC(mp, MNT_SUSPEND)) != 0) {
2035 		vfs_write_resume(mp, 0);
2036 		/* vfs_write_resume does vfs_op_exit() for us */
2037 	}
2038 	return (error);
2039 }
2040 
2041 /*
2042  * Request a filesystem to resume write operations.
2043  */
2044 void
vfs_write_resume(struct mount * mp,int flags)2045 vfs_write_resume(struct mount *mp, int flags)
2046 {
2047 
2048 	MNT_ILOCK(mp);
2049 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0) {
2050 		KASSERT(mp->mnt_susp_owner == curthread, ("mnt_susp_owner"));
2051 		mp->mnt_kern_flag &= ~(MNTK_SUSPEND | MNTK_SUSPEND2 |
2052 				       MNTK_SUSPENDED);
2053 		mp->mnt_susp_owner = NULL;
2054 		wakeup(&mp->mnt_writeopcount);
2055 		wakeup(&mp->mnt_flag);
2056 		curthread->td_pflags &= ~TDP_IGNSUSP;
2057 		if ((flags & VR_START_WRITE) != 0) {
2058 			MNT_REF(mp);
2059 			mp->mnt_writeopcount++;
2060 		}
2061 		MNT_IUNLOCK(mp);
2062 		if ((flags & VR_NO_SUSPCLR) == 0)
2063 			VFS_SUSP_CLEAN(mp);
2064 		vfs_op_exit(mp);
2065 	} else if ((flags & VR_START_WRITE) != 0) {
2066 		MNT_REF(mp);
2067 		vn_start_write_refed(mp, 0, true);
2068 	} else {
2069 		MNT_IUNLOCK(mp);
2070 	}
2071 }
2072 
2073 /*
2074  * Helper loop around vfs_write_suspend() for filesystem unmount VFS
2075  * methods.
2076  */
2077 int
vfs_write_suspend_umnt(struct mount * mp)2078 vfs_write_suspend_umnt(struct mount *mp)
2079 {
2080 	int error;
2081 
2082 	KASSERT((curthread->td_pflags & TDP_IGNSUSP) == 0,
2083 	    ("vfs_write_suspend_umnt: recursed"));
2084 
2085 	/* dounmount() already called vn_start_write(). */
2086 	for (;;) {
2087 		vn_finished_write(mp);
2088 		error = vfs_write_suspend(mp, 0);
2089 		if (error != 0) {
2090 			vn_start_write(NULL, &mp, V_WAIT);
2091 			return (error);
2092 		}
2093 		MNT_ILOCK(mp);
2094 		if ((mp->mnt_kern_flag & MNTK_SUSPENDED) != 0)
2095 			break;
2096 		MNT_IUNLOCK(mp);
2097 		vn_start_write(NULL, &mp, V_WAIT);
2098 	}
2099 	mp->mnt_kern_flag &= ~(MNTK_SUSPENDED | MNTK_SUSPEND2);
2100 	wakeup(&mp->mnt_flag);
2101 	MNT_IUNLOCK(mp);
2102 	curthread->td_pflags |= TDP_IGNSUSP;
2103 	return (0);
2104 }
2105 
2106 /*
2107  * Implement kqueues for files by translating it to vnode operation.
2108  */
2109 static int
vn_kqfilter(struct file * fp,struct knote * kn)2110 vn_kqfilter(struct file *fp, struct knote *kn)
2111 {
2112 
2113 	return (VOP_KQFILTER(fp->f_vnode, kn));
2114 }
2115 
2116 /*
2117  * Simplified in-kernel wrapper calls for extended attribute access.
2118  * Both calls pass in a NULL credential, authorizing as "kernel" access.
2119  * Set IO_NODELOCKED in ioflg if the vnode is already locked.
2120  */
2121 int
vn_extattr_get(struct vnode * vp,int ioflg,int attrnamespace,const char * attrname,int * buflen,char * buf,struct thread * td)2122 vn_extattr_get(struct vnode *vp, int ioflg, int attrnamespace,
2123     const char *attrname, int *buflen, char *buf, struct thread *td)
2124 {
2125 	struct uio	auio;
2126 	struct iovec	iov;
2127 	int	error;
2128 
2129 	iov.iov_len = *buflen;
2130 	iov.iov_base = buf;
2131 
2132 	auio.uio_iov = &iov;
2133 	auio.uio_iovcnt = 1;
2134 	auio.uio_rw = UIO_READ;
2135 	auio.uio_segflg = UIO_SYSSPACE;
2136 	auio.uio_td = td;
2137 	auio.uio_offset = 0;
2138 	auio.uio_resid = *buflen;
2139 
2140 	if ((ioflg & IO_NODELOCKED) == 0)
2141 		vn_lock(vp, LK_SHARED | LK_RETRY);
2142 
2143 	ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
2144 
2145 	/* authorize attribute retrieval as kernel */
2146 	error = VOP_GETEXTATTR(vp, attrnamespace, attrname, &auio, NULL, NULL,
2147 	    td);
2148 
2149 	if ((ioflg & IO_NODELOCKED) == 0)
2150 		VOP_UNLOCK(vp);
2151 
2152 	if (error == 0) {
2153 		*buflen = *buflen - auio.uio_resid;
2154 	}
2155 
2156 	return (error);
2157 }
2158 
2159 /*
2160  * XXX failure mode if partially written?
2161  */
2162 int
vn_extattr_set(struct vnode * vp,int ioflg,int attrnamespace,const char * attrname,int buflen,char * buf,struct thread * td)2163 vn_extattr_set(struct vnode *vp, int ioflg, int attrnamespace,
2164     const char *attrname, int buflen, char *buf, struct thread *td)
2165 {
2166 	struct uio	auio;
2167 	struct iovec	iov;
2168 	struct mount	*mp;
2169 	int	error;
2170 
2171 	iov.iov_len = buflen;
2172 	iov.iov_base = buf;
2173 
2174 	auio.uio_iov = &iov;
2175 	auio.uio_iovcnt = 1;
2176 	auio.uio_rw = UIO_WRITE;
2177 	auio.uio_segflg = UIO_SYSSPACE;
2178 	auio.uio_td = td;
2179 	auio.uio_offset = 0;
2180 	auio.uio_resid = buflen;
2181 
2182 	if ((ioflg & IO_NODELOCKED) == 0) {
2183 		if ((error = vn_start_write(vp, &mp, V_WAIT)) != 0)
2184 			return (error);
2185 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2186 	}
2187 
2188 	ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
2189 
2190 	/* authorize attribute setting as kernel */
2191 	error = VOP_SETEXTATTR(vp, attrnamespace, attrname, &auio, NULL, td);
2192 
2193 	if ((ioflg & IO_NODELOCKED) == 0) {
2194 		vn_finished_write(mp);
2195 		VOP_UNLOCK(vp);
2196 	}
2197 
2198 	return (error);
2199 }
2200 
2201 int
vn_extattr_rm(struct vnode * vp,int ioflg,int attrnamespace,const char * attrname,struct thread * td)2202 vn_extattr_rm(struct vnode *vp, int ioflg, int attrnamespace,
2203     const char *attrname, struct thread *td)
2204 {
2205 	struct mount	*mp;
2206 	int	error;
2207 
2208 	if ((ioflg & IO_NODELOCKED) == 0) {
2209 		if ((error = vn_start_write(vp, &mp, V_WAIT)) != 0)
2210 			return (error);
2211 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2212 	}
2213 
2214 	ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
2215 
2216 	/* authorize attribute removal as kernel */
2217 	error = VOP_DELETEEXTATTR(vp, attrnamespace, attrname, NULL, td);
2218 	if (error == EOPNOTSUPP)
2219 		error = VOP_SETEXTATTR(vp, attrnamespace, attrname, NULL,
2220 		    NULL, td);
2221 
2222 	if ((ioflg & IO_NODELOCKED) == 0) {
2223 		vn_finished_write(mp);
2224 		VOP_UNLOCK(vp);
2225 	}
2226 
2227 	return (error);
2228 }
2229 
2230 static int
vn_get_ino_alloc_vget(struct mount * mp,void * arg,int lkflags,struct vnode ** rvp)2231 vn_get_ino_alloc_vget(struct mount *mp, void *arg, int lkflags,
2232     struct vnode **rvp)
2233 {
2234 
2235 	return (VFS_VGET(mp, *(ino_t *)arg, lkflags, rvp));
2236 }
2237 
2238 int
vn_vget_ino(struct vnode * vp,ino_t ino,int lkflags,struct vnode ** rvp)2239 vn_vget_ino(struct vnode *vp, ino_t ino, int lkflags, struct vnode **rvp)
2240 {
2241 
2242 	return (vn_vget_ino_gen(vp, vn_get_ino_alloc_vget, &ino,
2243 	    lkflags, rvp));
2244 }
2245 
2246 int
vn_vget_ino_gen(struct vnode * vp,vn_get_ino_t alloc,void * alloc_arg,int lkflags,struct vnode ** rvp)2247 vn_vget_ino_gen(struct vnode *vp, vn_get_ino_t alloc, void *alloc_arg,
2248     int lkflags, struct vnode **rvp)
2249 {
2250 	struct mount *mp;
2251 	int ltype, error;
2252 
2253 	ASSERT_VOP_LOCKED(vp, "vn_vget_ino_get");
2254 	mp = vp->v_mount;
2255 	ltype = VOP_ISLOCKED(vp);
2256 	KASSERT(ltype == LK_EXCLUSIVE || ltype == LK_SHARED,
2257 	    ("vn_vget_ino: vp not locked"));
2258 	error = vfs_busy(mp, MBF_NOWAIT);
2259 	if (error != 0) {
2260 		vfs_ref(mp);
2261 		VOP_UNLOCK(vp);
2262 		error = vfs_busy(mp, 0);
2263 		vn_lock(vp, ltype | LK_RETRY);
2264 		vfs_rel(mp);
2265 		if (error != 0)
2266 			return (ENOENT);
2267 		if (VN_IS_DOOMED(vp)) {
2268 			vfs_unbusy(mp);
2269 			return (ENOENT);
2270 		}
2271 	}
2272 	VOP_UNLOCK(vp);
2273 	error = alloc(mp, alloc_arg, lkflags, rvp);
2274 	vfs_unbusy(mp);
2275 	if (error != 0 || *rvp != vp)
2276 		vn_lock(vp, ltype | LK_RETRY);
2277 	if (VN_IS_DOOMED(vp)) {
2278 		if (error == 0) {
2279 			if (*rvp == vp)
2280 				vunref(vp);
2281 			else
2282 				vput(*rvp);
2283 		}
2284 		error = ENOENT;
2285 	}
2286 	return (error);
2287 }
2288 
2289 int
vn_rlimit_fsize(const struct vnode * vp,const struct uio * uio,struct thread * td)2290 vn_rlimit_fsize(const struct vnode *vp, const struct uio *uio,
2291     struct thread *td)
2292 {
2293 
2294 	if (vp->v_type != VREG || td == NULL)
2295 		return (0);
2296 	if ((uoff_t)uio->uio_offset + uio->uio_resid >
2297 	    lim_cur(td, RLIMIT_FSIZE)) {
2298 		PROC_LOCK(td->td_proc);
2299 		kern_psignal(td->td_proc, SIGXFSZ);
2300 		PROC_UNLOCK(td->td_proc);
2301 		return (EFBIG);
2302 	}
2303 	return (0);
2304 }
2305 
2306 int
vn_chmod(struct file * fp,mode_t mode,struct ucred * active_cred,struct thread * td)2307 vn_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
2308     struct thread *td)
2309 {
2310 	struct vnode *vp;
2311 
2312 	vp = fp->f_vnode;
2313 #ifdef AUDIT
2314 	vn_lock(vp, LK_SHARED | LK_RETRY);
2315 	AUDIT_ARG_VNODE1(vp);
2316 	VOP_UNLOCK(vp);
2317 #endif
2318 	return (setfmode(td, active_cred, vp, mode));
2319 }
2320 
2321 int
vn_chown(struct file * fp,uid_t uid,gid_t gid,struct ucred * active_cred,struct thread * td)2322 vn_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
2323     struct thread *td)
2324 {
2325 	struct vnode *vp;
2326 
2327 	vp = fp->f_vnode;
2328 #ifdef AUDIT
2329 	vn_lock(vp, LK_SHARED | LK_RETRY);
2330 	AUDIT_ARG_VNODE1(vp);
2331 	VOP_UNLOCK(vp);
2332 #endif
2333 	return (setfown(td, active_cred, vp, uid, gid));
2334 }
2335 
2336 void
vn_pages_remove(struct vnode * vp,vm_pindex_t start,vm_pindex_t end)2337 vn_pages_remove(struct vnode *vp, vm_pindex_t start, vm_pindex_t end)
2338 {
2339 	vm_object_t object;
2340 
2341 	if ((object = vp->v_object) == NULL)
2342 		return;
2343 	VM_OBJECT_WLOCK(object);
2344 	vm_object_page_remove(object, start, end, 0);
2345 	VM_OBJECT_WUNLOCK(object);
2346 }
2347 
2348 int
vn_bmap_seekhole(struct vnode * vp,u_long cmd,off_t * off,struct ucred * cred)2349 vn_bmap_seekhole(struct vnode *vp, u_long cmd, off_t *off, struct ucred *cred)
2350 {
2351 	struct vattr va;
2352 	daddr_t bn, bnp;
2353 	uint64_t bsize;
2354 	off_t noff;
2355 	int error;
2356 
2357 	KASSERT(cmd == FIOSEEKHOLE || cmd == FIOSEEKDATA,
2358 	    ("Wrong command %lu", cmd));
2359 
2360 	if (vn_lock(vp, LK_SHARED) != 0)
2361 		return (EBADF);
2362 	if (vp->v_type != VREG) {
2363 		error = ENOTTY;
2364 		goto unlock;
2365 	}
2366 	error = VOP_GETATTR(vp, &va, cred);
2367 	if (error != 0)
2368 		goto unlock;
2369 	noff = *off;
2370 	if (noff >= va.va_size) {
2371 		error = ENXIO;
2372 		goto unlock;
2373 	}
2374 	bsize = vp->v_mount->mnt_stat.f_iosize;
2375 	for (bn = noff / bsize; noff < va.va_size; bn++, noff += bsize -
2376 	    noff % bsize) {
2377 		error = VOP_BMAP(vp, bn, NULL, &bnp, NULL, NULL);
2378 		if (error == EOPNOTSUPP) {
2379 			error = ENOTTY;
2380 			goto unlock;
2381 		}
2382 		if ((bnp == -1 && cmd == FIOSEEKHOLE) ||
2383 		    (bnp != -1 && cmd == FIOSEEKDATA)) {
2384 			noff = bn * bsize;
2385 			if (noff < *off)
2386 				noff = *off;
2387 			goto unlock;
2388 		}
2389 	}
2390 	if (noff > va.va_size)
2391 		noff = va.va_size;
2392 	/* noff == va.va_size. There is an implicit hole at the end of file. */
2393 	if (cmd == FIOSEEKDATA)
2394 		error = ENXIO;
2395 unlock:
2396 	VOP_UNLOCK(vp);
2397 	if (error == 0)
2398 		*off = noff;
2399 	return (error);
2400 }
2401 
2402 int
vn_seek(struct file * fp,off_t offset,int whence,struct thread * td)2403 vn_seek(struct file *fp, off_t offset, int whence, struct thread *td)
2404 {
2405 	struct ucred *cred;
2406 	struct vnode *vp;
2407 	struct vattr vattr;
2408 	off_t foffset, size;
2409 	int error, noneg;
2410 
2411 	cred = td->td_ucred;
2412 	vp = fp->f_vnode;
2413 	foffset = foffset_lock(fp, 0);
2414 	noneg = (vp->v_type != VCHR);
2415 	error = 0;
2416 	switch (whence) {
2417 	case L_INCR:
2418 		if (noneg &&
2419 		    (foffset < 0 ||
2420 		    (offset > 0 && foffset > OFF_MAX - offset))) {
2421 			error = EOVERFLOW;
2422 			break;
2423 		}
2424 		offset += foffset;
2425 		break;
2426 	case L_XTND:
2427 		vn_lock(vp, LK_SHARED | LK_RETRY);
2428 		error = VOP_GETATTR(vp, &vattr, cred);
2429 		VOP_UNLOCK(vp);
2430 		if (error)
2431 			break;
2432 
2433 		/*
2434 		 * If the file references a disk device, then fetch
2435 		 * the media size and use that to determine the ending
2436 		 * offset.
2437 		 */
2438 		if (vattr.va_size == 0 && vp->v_type == VCHR &&
2439 		    fo_ioctl(fp, DIOCGMEDIASIZE, &size, cred, td) == 0)
2440 			vattr.va_size = size;
2441 		if (noneg &&
2442 		    (vattr.va_size > OFF_MAX ||
2443 		    (offset > 0 && vattr.va_size > OFF_MAX - offset))) {
2444 			error = EOVERFLOW;
2445 			break;
2446 		}
2447 		offset += vattr.va_size;
2448 		break;
2449 	case L_SET:
2450 		break;
2451 	case SEEK_DATA:
2452 		error = fo_ioctl(fp, FIOSEEKDATA, &offset, cred, td);
2453 		if (error == ENOTTY)
2454 			error = EINVAL;
2455 		break;
2456 	case SEEK_HOLE:
2457 		error = fo_ioctl(fp, FIOSEEKHOLE, &offset, cred, td);
2458 		if (error == ENOTTY)
2459 			error = EINVAL;
2460 		break;
2461 	default:
2462 		error = EINVAL;
2463 	}
2464 	if (error == 0 && noneg && offset < 0)
2465 		error = EINVAL;
2466 	if (error != 0)
2467 		goto drop;
2468 	VFS_KNOTE_UNLOCKED(vp, 0);
2469 	td->td_uretoff.tdu_off = offset;
2470 drop:
2471 	foffset_unlock(fp, offset, error != 0 ? FOF_NOUPDATE : 0);
2472 	return (error);
2473 }
2474 
2475 int
vn_utimes_perm(struct vnode * vp,struct vattr * vap,struct ucred * cred,struct thread * td)2476 vn_utimes_perm(struct vnode *vp, struct vattr *vap, struct ucred *cred,
2477     struct thread *td)
2478 {
2479 	int error;
2480 
2481 	/*
2482 	 * Grant permission if the caller is the owner of the file, or
2483 	 * the super-user, or has ACL_WRITE_ATTRIBUTES permission on
2484 	 * on the file.  If the time pointer is null, then write
2485 	 * permission on the file is also sufficient.
2486 	 *
2487 	 * From NFSv4.1, draft 21, 6.2.1.3.1, Discussion of Mask Attributes:
2488 	 * A user having ACL_WRITE_DATA or ACL_WRITE_ATTRIBUTES
2489 	 * will be allowed to set the times [..] to the current
2490 	 * server time.
2491 	 */
2492 	error = VOP_ACCESSX(vp, VWRITE_ATTRIBUTES, cred, td);
2493 	if (error != 0 && (vap->va_vaflags & VA_UTIMES_NULL) != 0)
2494 		error = VOP_ACCESS(vp, VWRITE, cred, td);
2495 	return (error);
2496 }
2497 
2498 int
vn_fill_kinfo(struct file * fp,struct kinfo_file * kif,struct filedesc * fdp)2499 vn_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
2500 {
2501 	struct vnode *vp;
2502 	int error;
2503 
2504 	if (fp->f_type == DTYPE_FIFO)
2505 		kif->kf_type = KF_TYPE_FIFO;
2506 	else
2507 		kif->kf_type = KF_TYPE_VNODE;
2508 	vp = fp->f_vnode;
2509 	vref(vp);
2510 	FILEDESC_SUNLOCK(fdp);
2511 	error = vn_fill_kinfo_vnode(vp, kif);
2512 	vrele(vp);
2513 	FILEDESC_SLOCK(fdp);
2514 	return (error);
2515 }
2516 
2517 static inline void
vn_fill_junk(struct kinfo_file * kif)2518 vn_fill_junk(struct kinfo_file *kif)
2519 {
2520 	size_t len, olen;
2521 
2522 	/*
2523 	 * Simulate vn_fullpath returning changing values for a given
2524 	 * vp during e.g. coredump.
2525 	 */
2526 	len = (arc4random() % (sizeof(kif->kf_path) - 2)) + 1;
2527 	olen = strlen(kif->kf_path);
2528 	if (len < olen)
2529 		strcpy(&kif->kf_path[len - 1], "$");
2530 	else
2531 		for (; olen < len; olen++)
2532 			strcpy(&kif->kf_path[olen], "A");
2533 }
2534 
2535 int
vn_fill_kinfo_vnode(struct vnode * vp,struct kinfo_file * kif)2536 vn_fill_kinfo_vnode(struct vnode *vp, struct kinfo_file *kif)
2537 {
2538 	struct vattr va;
2539 	char *fullpath, *freepath;
2540 	int error;
2541 
2542 	kif->kf_un.kf_file.kf_file_type = vntype_to_kinfo(vp->v_type);
2543 	freepath = NULL;
2544 	fullpath = "-";
2545 	error = vn_fullpath(vp, &fullpath, &freepath);
2546 	if (error == 0) {
2547 		strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2548 	}
2549 	if (freepath != NULL)
2550 		free(freepath, M_TEMP);
2551 
2552 	KFAIL_POINT_CODE(DEBUG_FP, fill_kinfo_vnode__random_path,
2553 		vn_fill_junk(kif);
2554 	);
2555 
2556 	/*
2557 	 * Retrieve vnode attributes.
2558 	 */
2559 	va.va_fsid = VNOVAL;
2560 	va.va_rdev = NODEV;
2561 	vn_lock(vp, LK_SHARED | LK_RETRY);
2562 	error = VOP_GETATTR(vp, &va, curthread->td_ucred);
2563 	VOP_UNLOCK(vp);
2564 	if (error != 0)
2565 		return (error);
2566 	if (va.va_fsid != VNOVAL)
2567 		kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
2568 	else
2569 		kif->kf_un.kf_file.kf_file_fsid =
2570 		    vp->v_mount->mnt_stat.f_fsid.val[0];
2571 	kif->kf_un.kf_file.kf_file_fsid_freebsd11 =
2572 	    kif->kf_un.kf_file.kf_file_fsid; /* truncate */
2573 	kif->kf_un.kf_file.kf_file_fileid = va.va_fileid;
2574 	kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode);
2575 	kif->kf_un.kf_file.kf_file_size = va.va_size;
2576 	kif->kf_un.kf_file.kf_file_rdev = va.va_rdev;
2577 	kif->kf_un.kf_file.kf_file_rdev_freebsd11 =
2578 	    kif->kf_un.kf_file.kf_file_rdev; /* truncate */
2579 	return (0);
2580 }
2581 
2582 int
vn_mmap(struct file * fp,vm_map_t map,vm_offset_t * addr,vm_size_t size,vm_prot_t prot,vm_prot_t cap_maxprot,int flags,vm_ooffset_t foff,struct thread * td)2583 vn_mmap(struct file *fp, vm_map_t map, vm_offset_t *addr, vm_size_t size,
2584     vm_prot_t prot, vm_prot_t cap_maxprot, int flags, vm_ooffset_t foff,
2585     struct thread *td)
2586 {
2587 #ifdef HWPMC_HOOKS
2588 	struct pmckern_map_in pkm;
2589 #endif
2590 	struct mount *mp;
2591 	struct vnode *vp;
2592 	vm_object_t object;
2593 	vm_prot_t maxprot;
2594 	boolean_t writecounted;
2595 	int error;
2596 
2597 #if defined(COMPAT_FREEBSD7) || defined(COMPAT_FREEBSD6) || \
2598     defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4)
2599 	/*
2600 	 * POSIX shared-memory objects are defined to have
2601 	 * kernel persistence, and are not defined to support
2602 	 * read(2)/write(2) -- or even open(2).  Thus, we can
2603 	 * use MAP_ASYNC to trade on-disk coherence for speed.
2604 	 * The shm_open(3) library routine turns on the FPOSIXSHM
2605 	 * flag to request this behavior.
2606 	 */
2607 	if ((fp->f_flag & FPOSIXSHM) != 0)
2608 		flags |= MAP_NOSYNC;
2609 #endif
2610 	vp = fp->f_vnode;
2611 
2612 	/*
2613 	 * Ensure that file and memory protections are
2614 	 * compatible.  Note that we only worry about
2615 	 * writability if mapping is shared; in this case,
2616 	 * current and max prot are dictated by the open file.
2617 	 * XXX use the vnode instead?  Problem is: what
2618 	 * credentials do we use for determination? What if
2619 	 * proc does a setuid?
2620 	 */
2621 	mp = vp->v_mount;
2622 	if (mp != NULL && (mp->mnt_flag & MNT_NOEXEC) != 0) {
2623 		maxprot = VM_PROT_NONE;
2624 		if ((prot & VM_PROT_EXECUTE) != 0)
2625 			return (EACCES);
2626 	} else
2627 		maxprot = VM_PROT_EXECUTE;
2628 	if ((fp->f_flag & FREAD) != 0)
2629 		maxprot |= VM_PROT_READ;
2630 	else if ((prot & VM_PROT_READ) != 0)
2631 		return (EACCES);
2632 
2633 	/*
2634 	 * If we are sharing potential changes via MAP_SHARED and we
2635 	 * are trying to get write permission although we opened it
2636 	 * without asking for it, bail out.
2637 	 */
2638 	if ((flags & MAP_SHARED) != 0) {
2639 		if ((fp->f_flag & FWRITE) != 0)
2640 			maxprot |= VM_PROT_WRITE;
2641 		else if ((prot & VM_PROT_WRITE) != 0)
2642 			return (EACCES);
2643 	} else {
2644 		maxprot |= VM_PROT_WRITE;
2645 		cap_maxprot |= VM_PROT_WRITE;
2646 	}
2647 	maxprot &= cap_maxprot;
2648 
2649 	/*
2650 	 * For regular files and shared memory, POSIX requires that
2651 	 * the value of foff be a legitimate offset within the data
2652 	 * object.  In particular, negative offsets are invalid.
2653 	 * Blocking negative offsets and overflows here avoids
2654 	 * possible wraparound or user-level access into reserved
2655 	 * ranges of the data object later.  In contrast, POSIX does
2656 	 * not dictate how offsets are used by device drivers, so in
2657 	 * the case of a device mapping a negative offset is passed
2658 	 * on.
2659 	 */
2660 	if (
2661 #ifdef _LP64
2662 	    size > OFF_MAX ||
2663 #endif
2664 	    foff > OFF_MAX - size)
2665 		return (EINVAL);
2666 
2667 	writecounted = FALSE;
2668 	error = vm_mmap_vnode(td, size, prot, &maxprot, &flags, vp,
2669 	    &foff, &object, &writecounted);
2670 	if (error != 0)
2671 		return (error);
2672 	error = vm_mmap_object(map, addr, size, prot, maxprot, flags, object,
2673 	    foff, writecounted, td);
2674 	if (error != 0) {
2675 		/*
2676 		 * If this mapping was accounted for in the vnode's
2677 		 * writecount, then undo that now.
2678 		 */
2679 		if (writecounted)
2680 			vm_pager_release_writecount(object, 0, size);
2681 		vm_object_deallocate(object);
2682 	}
2683 #ifdef HWPMC_HOOKS
2684 	/* Inform hwpmc(4) if an executable is being mapped. */
2685 	if (PMC_HOOK_INSTALLED(PMC_FN_MMAP)) {
2686 		if ((prot & VM_PROT_EXECUTE) != 0 && error == 0) {
2687 			pkm.pm_file = vp;
2688 			pkm.pm_address = (uintptr_t) *addr;
2689 			PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_MMAP, (void *) &pkm);
2690 		}
2691 	}
2692 #endif
2693 	return (error);
2694 }
2695 
2696 void
vn_fsid(struct vnode * vp,struct vattr * va)2697 vn_fsid(struct vnode *vp, struct vattr *va)
2698 {
2699 	fsid_t *f;
2700 
2701 	f = &vp->v_mount->mnt_stat.f_fsid;
2702 	va->va_fsid = (uint32_t)f->val[1];
2703 	va->va_fsid <<= sizeof(f->val[1]) * NBBY;
2704 	va->va_fsid += (uint32_t)f->val[0];
2705 }
2706 
2707 int
vn_fsync_buf(struct vnode * vp,int waitfor)2708 vn_fsync_buf(struct vnode *vp, int waitfor)
2709 {
2710 	struct buf *bp, *nbp;
2711 	struct bufobj *bo;
2712 	struct mount *mp;
2713 	int error, maxretry;
2714 
2715 	error = 0;
2716 	maxretry = 10000;     /* large, arbitrarily chosen */
2717 	mp = NULL;
2718 	if (vp->v_type == VCHR) {
2719 		VI_LOCK(vp);
2720 		mp = vp->v_rdev->si_mountpt;
2721 		VI_UNLOCK(vp);
2722 	}
2723 	bo = &vp->v_bufobj;
2724 	BO_LOCK(bo);
2725 loop1:
2726 	/*
2727 	 * MARK/SCAN initialization to avoid infinite loops.
2728 	 */
2729         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
2730 		bp->b_vflags &= ~BV_SCANNED;
2731 		bp->b_error = 0;
2732 	}
2733 
2734 	/*
2735 	 * Flush all dirty buffers associated with a vnode.
2736 	 */
2737 loop2:
2738 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2739 		if ((bp->b_vflags & BV_SCANNED) != 0)
2740 			continue;
2741 		bp->b_vflags |= BV_SCANNED;
2742 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL)) {
2743 			if (waitfor != MNT_WAIT)
2744 				continue;
2745 			if (BUF_LOCK(bp,
2746 			    LK_EXCLUSIVE | LK_INTERLOCK | LK_SLEEPFAIL,
2747 			    BO_LOCKPTR(bo)) != 0) {
2748 				BO_LOCK(bo);
2749 				goto loop1;
2750 			}
2751 			BO_LOCK(bo);
2752 		}
2753 		BO_UNLOCK(bo);
2754 		KASSERT(bp->b_bufobj == bo,
2755 		    ("bp %p wrong b_bufobj %p should be %p",
2756 		    bp, bp->b_bufobj, bo));
2757 		if ((bp->b_flags & B_DELWRI) == 0)
2758 			panic("fsync: not dirty");
2759 		if ((vp->v_object != NULL) && (bp->b_flags & B_CLUSTEROK)) {
2760 			vfs_bio_awrite(bp);
2761 		} else {
2762 			bremfree(bp);
2763 			bawrite(bp);
2764 		}
2765 		if (maxretry < 1000)
2766 			pause("dirty", hz < 1000 ? 1 : hz / 1000);
2767 		BO_LOCK(bo);
2768 		goto loop2;
2769 	}
2770 
2771 	/*
2772 	 * If synchronous the caller expects us to completely resolve all
2773 	 * dirty buffers in the system.  Wait for in-progress I/O to
2774 	 * complete (which could include background bitmap writes), then
2775 	 * retry if dirty blocks still exist.
2776 	 */
2777 	if (waitfor == MNT_WAIT) {
2778 		bufobj_wwait(bo, 0, 0);
2779 		if (bo->bo_dirty.bv_cnt > 0) {
2780 			/*
2781 			 * If we are unable to write any of these buffers
2782 			 * then we fail now rather than trying endlessly
2783 			 * to write them out.
2784 			 */
2785 			TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
2786 				if ((error = bp->b_error) != 0)
2787 					break;
2788 			if ((mp != NULL && mp->mnt_secondary_writes > 0) ||
2789 			    (error == 0 && --maxretry >= 0))
2790 				goto loop1;
2791 			if (error == 0)
2792 				error = EAGAIN;
2793 		}
2794 	}
2795 	BO_UNLOCK(bo);
2796 	if (error != 0)
2797 		vn_printf(vp, "fsync: giving up on dirty (error = %d) ", error);
2798 
2799 	return (error);
2800 }
2801 
2802 /*
2803  * Copies a byte range from invp to outvp.  Calls VOP_COPY_FILE_RANGE()
2804  * or vn_generic_copy_file_range() after rangelocking the byte ranges,
2805  * to do the actual copy.
2806  * vn_generic_copy_file_range() is factored out, so it can be called
2807  * from a VOP_COPY_FILE_RANGE() call as well, but handles vnodes from
2808  * different file systems.
2809  */
2810 int
vn_copy_file_range(struct vnode * invp,off_t * inoffp,struct vnode * outvp,off_t * outoffp,size_t * lenp,unsigned int flags,struct ucred * incred,struct ucred * outcred,struct thread * fsize_td)2811 vn_copy_file_range(struct vnode *invp, off_t *inoffp, struct vnode *outvp,
2812     off_t *outoffp, size_t *lenp, unsigned int flags, struct ucred *incred,
2813     struct ucred *outcred, struct thread *fsize_td)
2814 {
2815 	int error;
2816 	size_t len;
2817 	uint64_t uval;
2818 
2819 	len = *lenp;
2820 	*lenp = 0;		/* For error returns. */
2821 	error = 0;
2822 
2823 	/* Do some sanity checks on the arguments. */
2824 	if (invp->v_type == VDIR || outvp->v_type == VDIR)
2825 		error = EISDIR;
2826 	else if (*inoffp < 0 || *outoffp < 0 ||
2827 	    invp->v_type != VREG || outvp->v_type != VREG)
2828 		error = EINVAL;
2829 	if (error != 0)
2830 		goto out;
2831 
2832 	/* Ensure offset + len does not wrap around. */
2833 	uval = *inoffp;
2834 	uval += len;
2835 	if (uval > INT64_MAX)
2836 		len = INT64_MAX - *inoffp;
2837 	uval = *outoffp;
2838 	uval += len;
2839 	if (uval > INT64_MAX)
2840 		len = INT64_MAX - *outoffp;
2841 	if (len == 0)
2842 		goto out;
2843 
2844 	/*
2845 	 * If the two vnode are for the same file system, call
2846 	 * VOP_COPY_FILE_RANGE(), otherwise call vn_generic_copy_file_range()
2847 	 * which can handle copies across multiple file systems.
2848 	 */
2849 	*lenp = len;
2850 	if (invp->v_mount == outvp->v_mount)
2851 		error = VOP_COPY_FILE_RANGE(invp, inoffp, outvp, outoffp,
2852 		    lenp, flags, incred, outcred, fsize_td);
2853 	else
2854 		error = vn_generic_copy_file_range(invp, inoffp, outvp,
2855 		    outoffp, lenp, flags, incred, outcred, fsize_td);
2856 out:
2857 	return (error);
2858 }
2859 
2860 /*
2861  * Test len bytes of data starting at dat for all bytes == 0.
2862  * Return true if all bytes are zero, false otherwise.
2863  * Expects dat to be well aligned.
2864  */
2865 static bool
mem_iszero(void * dat,int len)2866 mem_iszero(void *dat, int len)
2867 {
2868 	int i;
2869 	const u_int *p;
2870 	const char *cp;
2871 
2872 	for (p = dat; len > 0; len -= sizeof(*p), p++) {
2873 		if (len >= sizeof(*p)) {
2874 			if (*p != 0)
2875 				return (false);
2876 		} else {
2877 			cp = (const char *)p;
2878 			for (i = 0; i < len; i++, cp++)
2879 				if (*cp != '\0')
2880 					return (false);
2881 		}
2882 	}
2883 	return (true);
2884 }
2885 
2886 /*
2887  * Look for a hole in the output file and, if found, adjust *outoffp
2888  * and *xferp to skip past the hole.
2889  * *xferp is the entire hole length to be written and xfer2 is how many bytes
2890  * to be written as 0's upon return.
2891  */
2892 static off_t
vn_skip_hole(struct vnode * outvp,off_t xfer2,off_t * outoffp,off_t * xferp,off_t * dataoffp,off_t * holeoffp,struct ucred * cred)2893 vn_skip_hole(struct vnode *outvp, off_t xfer2, off_t *outoffp, off_t *xferp,
2894     off_t *dataoffp, off_t *holeoffp, struct ucred *cred)
2895 {
2896 	int error;
2897 	off_t delta;
2898 
2899 	if (*holeoffp == 0 || *holeoffp <= *outoffp) {
2900 		*dataoffp = *outoffp;
2901 		error = VOP_IOCTL(outvp, FIOSEEKDATA, dataoffp, 0, cred,
2902 		    curthread);
2903 		if (error == 0) {
2904 			*holeoffp = *dataoffp;
2905 			error = VOP_IOCTL(outvp, FIOSEEKHOLE, holeoffp, 0, cred,
2906 			    curthread);
2907 		}
2908 		if (error != 0 || *holeoffp == *dataoffp) {
2909 			/*
2910 			 * Since outvp is unlocked, it may be possible for
2911 			 * another thread to do a truncate(), lseek(), write()
2912 			 * creating a hole at startoff between the above
2913 			 * VOP_IOCTL() calls, if the other thread does not do
2914 			 * rangelocking.
2915 			 * If that happens, *holeoffp == *dataoffp and finding
2916 			 * the hole has failed, so disable vn_skip_hole().
2917 			 */
2918 			*holeoffp = -1;	/* Disable use of vn_skip_hole(). */
2919 			return (xfer2);
2920 		}
2921 		KASSERT(*dataoffp >= *outoffp,
2922 		    ("vn_skip_hole: dataoff=%jd < outoff=%jd",
2923 		    (intmax_t)*dataoffp, (intmax_t)*outoffp));
2924 		KASSERT(*holeoffp > *dataoffp,
2925 		    ("vn_skip_hole: holeoff=%jd <= dataoff=%jd",
2926 		    (intmax_t)*holeoffp, (intmax_t)*dataoffp));
2927 	}
2928 
2929 	/*
2930 	 * If there is a hole before the data starts, advance *outoffp and
2931 	 * *xferp past the hole.
2932 	 */
2933 	if (*dataoffp > *outoffp) {
2934 		delta = *dataoffp - *outoffp;
2935 		if (delta >= *xferp) {
2936 			/* Entire *xferp is a hole. */
2937 			*outoffp += *xferp;
2938 			*xferp = 0;
2939 			return (0);
2940 		}
2941 		*xferp -= delta;
2942 		*outoffp += delta;
2943 		xfer2 = MIN(xfer2, *xferp);
2944 	}
2945 
2946 	/*
2947 	 * If a hole starts before the end of this xfer2, reduce this xfer2 so
2948 	 * that the write ends at the start of the hole.
2949 	 * *holeoffp should always be greater than *outoffp, but for the
2950 	 * non-INVARIANTS case, check this to make sure xfer2 remains a sane
2951 	 * value.
2952 	 */
2953 	if (*holeoffp > *outoffp && *holeoffp < *outoffp + xfer2)
2954 		xfer2 = *holeoffp - *outoffp;
2955 	return (xfer2);
2956 }
2957 
2958 /*
2959  * Write an xfer sized chunk to outvp in blksize blocks from dat.
2960  * dat is a maximum of blksize in length and can be written repeatedly in
2961  * the chunk.
2962  * If growfile == true, just grow the file via vn_truncate_locked() instead
2963  * of doing actual writes.
2964  * If checkhole == true, a hole is being punched, so skip over any hole
2965  * already in the output file.
2966  */
2967 static int
vn_write_outvp(struct vnode * outvp,char * dat,off_t outoff,off_t xfer,u_long blksize,bool growfile,bool checkhole,struct ucred * cred)2968 vn_write_outvp(struct vnode *outvp, char *dat, off_t outoff, off_t xfer,
2969     u_long blksize, bool growfile, bool checkhole, struct ucred *cred)
2970 {
2971 	struct mount *mp;
2972 	off_t dataoff, holeoff, xfer2;
2973 	int error, lckf;
2974 
2975 	/*
2976 	 * Loop around doing writes of blksize until write has been completed.
2977 	 * Lock/unlock on each loop iteration so that a bwillwrite() can be
2978 	 * done for each iteration, since the xfer argument can be very
2979 	 * large if there is a large hole to punch in the output file.
2980 	 */
2981 	error = 0;
2982 	holeoff = 0;
2983 	do {
2984 		xfer2 = MIN(xfer, blksize);
2985 		if (checkhole) {
2986 			/*
2987 			 * Punching a hole.  Skip writing if there is
2988 			 * already a hole in the output file.
2989 			 */
2990 			xfer2 = vn_skip_hole(outvp, xfer2, &outoff, &xfer,
2991 			    &dataoff, &holeoff, cred);
2992 			if (xfer == 0)
2993 				break;
2994 			if (holeoff < 0)
2995 				checkhole = false;
2996 			KASSERT(xfer2 > 0, ("vn_write_outvp: xfer2=%jd",
2997 			    (intmax_t)xfer2));
2998 		}
2999 		bwillwrite();
3000 		mp = NULL;
3001 		error = vn_start_write(outvp, &mp, V_WAIT);
3002 		if (error != 0)
3003 			break;
3004 		if (growfile) {
3005 			error = vn_lock(outvp, LK_EXCLUSIVE);
3006 			if (error == 0) {
3007 				error = vn_truncate_locked(outvp, outoff + xfer,
3008 				    false, cred);
3009 				VOP_UNLOCK(outvp);
3010 			}
3011 		} else {
3012 			if (MNT_SHARED_WRITES(mp))
3013 				lckf = LK_SHARED;
3014 			else
3015 				lckf = LK_EXCLUSIVE;
3016 			error = vn_lock(outvp, lckf);
3017 			if (error == 0) {
3018 				error = vn_rdwr(UIO_WRITE, outvp, dat, xfer2,
3019 				    outoff, UIO_SYSSPACE, IO_NODELOCKED,
3020 				    curthread->td_ucred, cred, NULL, curthread);
3021 				outoff += xfer2;
3022 				xfer -= xfer2;
3023 				VOP_UNLOCK(outvp);
3024 			}
3025 		}
3026 		if (mp != NULL)
3027 			vn_finished_write(mp);
3028 	} while (!growfile && xfer > 0 && error == 0);
3029 	return (error);
3030 }
3031 
3032 /*
3033  * Copy a byte range of one file to another.  This function can handle the
3034  * case where invp and outvp are on different file systems.
3035  * It can also be called by a VOP_COPY_FILE_RANGE() to do the work, if there
3036  * is no better file system specific way to do it.
3037  */
3038 int
vn_generic_copy_file_range(struct vnode * invp,off_t * inoffp,struct vnode * outvp,off_t * outoffp,size_t * lenp,unsigned int flags,struct ucred * incred,struct ucred * outcred,struct thread * fsize_td)3039 vn_generic_copy_file_range(struct vnode *invp, off_t *inoffp,
3040     struct vnode *outvp, off_t *outoffp, size_t *lenp, unsigned int flags,
3041     struct ucred *incred, struct ucred *outcred, struct thread *fsize_td)
3042 {
3043 	struct vattr va;
3044 	struct mount *mp;
3045 	struct uio io;
3046 	off_t startoff, endoff, xfer, xfer2;
3047 	u_long blksize;
3048 	int error, interrupted;
3049 	bool cantseek, readzeros, eof, lastblock;
3050 	ssize_t aresid;
3051 	size_t copylen, len, rem, savlen;
3052 	char *dat;
3053 	long holein, holeout;
3054 
3055 	holein = holeout = 0;
3056 	savlen = len = *lenp;
3057 	error = 0;
3058 	interrupted = 0;
3059 	dat = NULL;
3060 
3061 	error = vn_lock(invp, LK_SHARED);
3062 	if (error != 0)
3063 		goto out;
3064 	if (VOP_PATHCONF(invp, _PC_MIN_HOLE_SIZE, &holein) != 0)
3065 		holein = 0;
3066 	VOP_UNLOCK(invp);
3067 
3068 	mp = NULL;
3069 	error = vn_start_write(outvp, &mp, V_WAIT);
3070 	if (error == 0)
3071 		error = vn_lock(outvp, LK_EXCLUSIVE);
3072 	if (error == 0) {
3073 		/*
3074 		 * If fsize_td != NULL, do a vn_rlimit_fsize() call,
3075 		 * now that outvp is locked.
3076 		 */
3077 		if (fsize_td != NULL) {
3078 			io.uio_offset = *outoffp;
3079 			io.uio_resid = len;
3080 			error = vn_rlimit_fsize(outvp, &io, fsize_td);
3081 			if (error != 0)
3082 				error = EFBIG;
3083 		}
3084 		if (VOP_PATHCONF(outvp, _PC_MIN_HOLE_SIZE, &holeout) != 0)
3085 			holeout = 0;
3086 		/*
3087 		 * Holes that are past EOF do not need to be written as a block
3088 		 * of zero bytes.  So, truncate the output file as far as
3089 		 * possible and then use va.va_size to decide if writing 0
3090 		 * bytes is necessary in the loop below.
3091 		 */
3092 		if (error == 0)
3093 			error = VOP_GETATTR(outvp, &va, outcred);
3094 		if (error == 0 && va.va_size > *outoffp && va.va_size <=
3095 		    *outoffp + len) {
3096 #ifdef MAC
3097 			error = mac_vnode_check_write(curthread->td_ucred,
3098 			    outcred, outvp);
3099 			if (error == 0)
3100 #endif
3101 				error = vn_truncate_locked(outvp, *outoffp,
3102 				    false, outcred);
3103 			if (error == 0)
3104 				va.va_size = *outoffp;
3105 		}
3106 		VOP_UNLOCK(outvp);
3107 	}
3108 	if (mp != NULL)
3109 		vn_finished_write(mp);
3110 	if (error != 0)
3111 		goto out;
3112 
3113 	/*
3114 	 * Set the blksize to the larger of the hole sizes for invp and outvp.
3115 	 * If hole sizes aren't available, set the blksize to the larger
3116 	 * f_iosize of invp and outvp.
3117 	 * This code expects the hole sizes and f_iosizes to be powers of 2.
3118 	 * This value is clipped at 4Kbytes and 1Mbyte.
3119 	 */
3120 	blksize = MAX(holein, holeout);
3121 
3122 	/* Clip len to end at an exact multiple of hole size. */
3123 	if (blksize > 1) {
3124 		rem = *inoffp % blksize;
3125 		if (rem > 0)
3126 			rem = blksize - rem;
3127 		if (len > rem && len - rem > blksize)
3128 			len = savlen = rounddown(len - rem, blksize) + rem;
3129 	}
3130 
3131 	if (blksize <= 1)
3132 		blksize = MAX(invp->v_mount->mnt_stat.f_iosize,
3133 		    outvp->v_mount->mnt_stat.f_iosize);
3134 	if (blksize < 4096)
3135 		blksize = 4096;
3136 	else if (blksize > 1024 * 1024)
3137 		blksize = 1024 * 1024;
3138 	dat = malloc(blksize, M_TEMP, M_WAITOK);
3139 
3140 	/*
3141 	 * If VOP_IOCTL(FIOSEEKHOLE) works for invp, use it and FIOSEEKDATA
3142 	 * to find holes.  Otherwise, just scan the read block for all 0s
3143 	 * in the inner loop where the data copying is done.
3144 	 * Note that some file systems such as NFSv3, NFSv4.0 and NFSv4.1 may
3145 	 * support holes on the server, but do not support FIOSEEKHOLE.
3146 	 */
3147 	eof = false;
3148 	while (len > 0 && error == 0 && !eof && interrupted == 0) {
3149 		endoff = 0;			/* To shut up compilers. */
3150 		cantseek = true;
3151 		startoff = *inoffp;
3152 		copylen = len;
3153 
3154 		/*
3155 		 * Find the next data area.  If there is just a hole to EOF,
3156 		 * FIOSEEKDATA should fail and then we drop down into the
3157 		 * inner loop and create the hole on the outvp file.
3158 		 * (I do not know if any file system will report a hole to
3159 		 *  EOF via FIOSEEKHOLE, but I am pretty sure FIOSEEKDATA
3160 		 *  will fail for those file systems.)
3161 		 *
3162 		 * For input files that don't support FIOSEEKDATA/FIOSEEKHOLE,
3163 		 * the code just falls through to the inner copy loop.
3164 		 */
3165 		error = EINVAL;
3166 		if (holein > 0)
3167 			error = VOP_IOCTL(invp, FIOSEEKDATA, &startoff, 0,
3168 			    incred, curthread);
3169 		if (error == 0) {
3170 			endoff = startoff;
3171 			error = VOP_IOCTL(invp, FIOSEEKHOLE, &endoff, 0,
3172 			    incred, curthread);
3173 			/*
3174 			 * Since invp is unlocked, it may be possible for
3175 			 * another thread to do a truncate(), lseek(), write()
3176 			 * creating a hole at startoff between the above
3177 			 * VOP_IOCTL() calls, if the other thread does not do
3178 			 * rangelocking.
3179 			 * If that happens, startoff == endoff and finding
3180 			 * the hole has failed, so set an error.
3181 			 */
3182 			if (error == 0 && startoff == endoff)
3183 				error = EINVAL; /* Any error. Reset to 0. */
3184 		}
3185 		if (error == 0) {
3186 			if (startoff > *inoffp) {
3187 				/* Found hole before data block. */
3188 				xfer = MIN(startoff - *inoffp, len);
3189 				if (*outoffp < va.va_size) {
3190 					/* Must write 0s to punch hole. */
3191 					xfer2 = MIN(va.va_size - *outoffp,
3192 					    xfer);
3193 					memset(dat, 0, MIN(xfer2, blksize));
3194 					error = vn_write_outvp(outvp, dat,
3195 					    *outoffp, xfer2, blksize, false,
3196 					    holeout > 0, outcred);
3197 				}
3198 
3199 				if (error == 0 && *outoffp + xfer >
3200 				    va.va_size && xfer == len)
3201 					/* Grow last block. */
3202 					error = vn_write_outvp(outvp, dat,
3203 					    *outoffp, xfer, blksize, true,
3204 					    false, outcred);
3205 				if (error == 0) {
3206 					*inoffp += xfer;
3207 					*outoffp += xfer;
3208 					len -= xfer;
3209 					if (len < savlen)
3210 						interrupted = sig_intr();
3211 				}
3212 			}
3213 			copylen = MIN(len, endoff - startoff);
3214 			cantseek = false;
3215 		} else {
3216 			cantseek = true;
3217 			startoff = *inoffp;
3218 			copylen = len;
3219 			error = 0;
3220 		}
3221 
3222 		xfer = blksize;
3223 		if (cantseek) {
3224 			/*
3225 			 * Set first xfer to end at a block boundary, so that
3226 			 * holes are more likely detected in the loop below via
3227 			 * the for all bytes 0 method.
3228 			 */
3229 			xfer -= (*inoffp % blksize);
3230 		}
3231 		/* Loop copying the data block. */
3232 		while (copylen > 0 && error == 0 && !eof && interrupted == 0) {
3233 			if (copylen < xfer)
3234 				xfer = copylen;
3235 			error = vn_lock(invp, LK_SHARED);
3236 			if (error != 0)
3237 				goto out;
3238 			error = vn_rdwr(UIO_READ, invp, dat, xfer,
3239 			    startoff, UIO_SYSSPACE, IO_NODELOCKED,
3240 			    curthread->td_ucred, incred, &aresid,
3241 			    curthread);
3242 			VOP_UNLOCK(invp);
3243 			lastblock = false;
3244 			if (error == 0 && aresid > 0) {
3245 				/* Stop the copy at EOF on the input file. */
3246 				xfer -= aresid;
3247 				eof = true;
3248 				lastblock = true;
3249 			}
3250 			if (error == 0) {
3251 				/*
3252 				 * Skip the write for holes past the initial EOF
3253 				 * of the output file, unless this is the last
3254 				 * write of the output file at EOF.
3255 				 */
3256 				readzeros = cantseek ? mem_iszero(dat, xfer) :
3257 				    false;
3258 				if (xfer == len)
3259 					lastblock = true;
3260 				if (!cantseek || *outoffp < va.va_size ||
3261 				    lastblock || !readzeros)
3262 					error = vn_write_outvp(outvp, dat,
3263 					    *outoffp, xfer, blksize,
3264 					    readzeros && lastblock &&
3265 					    *outoffp >= va.va_size, false,
3266 					    outcred);
3267 				if (error == 0) {
3268 					*inoffp += xfer;
3269 					startoff += xfer;
3270 					*outoffp += xfer;
3271 					copylen -= xfer;
3272 					len -= xfer;
3273 					if (len < savlen)
3274 						interrupted = sig_intr();
3275 				}
3276 			}
3277 			xfer = blksize;
3278 		}
3279 	}
3280 out:
3281 	*lenp = savlen - len;
3282 	free(dat, M_TEMP);
3283 	return (error);
3284 }
3285 
3286 static int
vn_fallocate(struct file * fp,off_t offset,off_t len,struct thread * td)3287 vn_fallocate(struct file *fp, off_t offset, off_t len, struct thread *td)
3288 {
3289 	struct mount *mp;
3290 	struct vnode *vp;
3291 	off_t olen, ooffset;
3292 	int error;
3293 #ifdef AUDIT
3294 	int audited_vnode1 = 0;
3295 #endif
3296 
3297 	vp = fp->f_vnode;
3298 	if (vp->v_type != VREG)
3299 		return (ENODEV);
3300 
3301 	/* Allocating blocks may take a long time, so iterate. */
3302 	for (;;) {
3303 		olen = len;
3304 		ooffset = offset;
3305 
3306 		bwillwrite();
3307 		mp = NULL;
3308 		error = vn_start_write(vp, &mp, V_WAIT | PCATCH);
3309 		if (error != 0)
3310 			break;
3311 		error = vn_lock(vp, LK_EXCLUSIVE);
3312 		if (error != 0) {
3313 			vn_finished_write(mp);
3314 			break;
3315 		}
3316 #ifdef AUDIT
3317 		if (!audited_vnode1) {
3318 			AUDIT_ARG_VNODE1(vp);
3319 			audited_vnode1 = 1;
3320 		}
3321 #endif
3322 #ifdef MAC
3323 		error = mac_vnode_check_write(td->td_ucred, fp->f_cred, vp);
3324 		if (error == 0)
3325 #endif
3326 			error = VOP_ALLOCATE(vp, &offset, &len);
3327 		VOP_UNLOCK(vp);
3328 		vn_finished_write(mp);
3329 
3330 		if (olen + ooffset != offset + len) {
3331 			panic("offset + len changed from %jx/%jx to %jx/%jx",
3332 			    ooffset, olen, offset, len);
3333 		}
3334 		if (error != 0 || len == 0)
3335 			break;
3336 		KASSERT(olen > len, ("Iteration did not make progress?"));
3337 		maybe_yield();
3338 	}
3339 
3340 	return (error);
3341 }
3342 
3343 static u_long vn_lock_pair_pause_cnt;
3344 SYSCTL_ULONG(_debug, OID_AUTO, vn_lock_pair_pause, CTLFLAG_RD,
3345     &vn_lock_pair_pause_cnt, 0,
3346     "Count of vn_lock_pair deadlocks");
3347 
3348 u_int vn_lock_pair_pause_max;
3349 SYSCTL_UINT(_debug, OID_AUTO, vn_lock_pair_pause_max, CTLFLAG_RW,
3350     &vn_lock_pair_pause_max, 0,
3351     "Max ticks for vn_lock_pair deadlock avoidance sleep");
3352 
3353 static void
vn_lock_pair_pause(const char * wmesg)3354 vn_lock_pair_pause(const char *wmesg)
3355 {
3356 	atomic_add_long(&vn_lock_pair_pause_cnt, 1);
3357 	pause(wmesg, prng32_bounded(vn_lock_pair_pause_max));
3358 }
3359 
3360 /*
3361  * Lock pair of vnodes vp1, vp2, avoiding lock order reversal.
3362  * vp1_locked indicates whether vp1 is exclusively locked; if not, vp1
3363  * must be unlocked.  Same for vp2 and vp2_locked.  One of the vnodes
3364  * can be NULL.
3365  *
3366  * The function returns with both vnodes exclusively locked, and
3367  * guarantees that it does not create lock order reversal with other
3368  * threads during its execution.  Both vnodes could be unlocked
3369  * temporary (and reclaimed).
3370  */
3371 void
vn_lock_pair(struct vnode * vp1,bool vp1_locked,struct vnode * vp2,bool vp2_locked)3372 vn_lock_pair(struct vnode *vp1, bool vp1_locked, struct vnode *vp2,
3373     bool vp2_locked)
3374 {
3375 	int error;
3376 
3377 	if (vp1 == NULL && vp2 == NULL)
3378 		return;
3379 	if (vp1 != NULL) {
3380 		if (vp1_locked)
3381 			ASSERT_VOP_ELOCKED(vp1, "vp1");
3382 		else
3383 			ASSERT_VOP_UNLOCKED(vp1, "vp1");
3384 	} else {
3385 		vp1_locked = true;
3386 	}
3387 	if (vp2 != NULL) {
3388 		if (vp2_locked)
3389 			ASSERT_VOP_ELOCKED(vp2, "vp2");
3390 		else
3391 			ASSERT_VOP_UNLOCKED(vp2, "vp2");
3392 	} else {
3393 		vp2_locked = true;
3394 	}
3395 	if (!vp1_locked && !vp2_locked) {
3396 		vn_lock(vp1, LK_EXCLUSIVE | LK_RETRY);
3397 		vp1_locked = true;
3398 	}
3399 
3400 	for (;;) {
3401 		if (vp1_locked && vp2_locked)
3402 			break;
3403 		if (vp1_locked && vp2 != NULL) {
3404 			if (vp1 != NULL) {
3405 				error = VOP_LOCK1(vp2, LK_EXCLUSIVE | LK_NOWAIT,
3406 				    __FILE__, __LINE__);
3407 				if (error == 0)
3408 					break;
3409 				VOP_UNLOCK(vp1);
3410 				vp1_locked = false;
3411 				vn_lock_pair_pause("vlp1");
3412 			}
3413 			vn_lock(vp2, LK_EXCLUSIVE | LK_RETRY);
3414 			vp2_locked = true;
3415 		}
3416 		if (vp2_locked && vp1 != NULL) {
3417 			if (vp2 != NULL) {
3418 				error = VOP_LOCK1(vp1, LK_EXCLUSIVE | LK_NOWAIT,
3419 				    __FILE__, __LINE__);
3420 				if (error == 0)
3421 					break;
3422 				VOP_UNLOCK(vp2);
3423 				vp2_locked = false;
3424 				vn_lock_pair_pause("vlp2");
3425 			}
3426 			vn_lock(vp1, LK_EXCLUSIVE | LK_RETRY);
3427 			vp1_locked = true;
3428 		}
3429 	}
3430 	if (vp1 != NULL)
3431 		ASSERT_VOP_ELOCKED(vp1, "vp1 ret");
3432 	if (vp2 != NULL)
3433 		ASSERT_VOP_ELOCKED(vp2, "vp2 ret");
3434 }
3435