xref: /freebsd/sys/kern/vfs_vnops.c (revision bc4430dc203ed7b6765fb5df041bf545c50f859b)
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 <kib@FreeBSD.org>
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 
43 #include "opt_hwpmc_hooks.h"
44 #include "opt_hwt_hooks.h"
45 
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/buf.h>
49 #include <sys/disk.h>
50 #include <sys/dirent.h>
51 #include <sys/fail.h>
52 #include <sys/fcntl.h>
53 #include <sys/file.h>
54 #include <sys/filio.h>
55 #include <sys/inotify.h>
56 #include <sys/ktr.h>
57 #include <sys/ktrace.h>
58 #include <sys/limits.h>
59 #include <sys/lock.h>
60 #include <sys/mman.h>
61 #include <sys/mount.h>
62 #include <sys/mutex.h>
63 #include <sys/namei.h>
64 #include <sys/priv.h>
65 #include <sys/prng.h>
66 #include <sys/proc.h>
67 #include <sys/rwlock.h>
68 #include <sys/sleepqueue.h>
69 #include <sys/stat.h>
70 #include <sys/sysctl.h>
71 #include <sys/unistd.h>
72 #include <sys/user.h>
73 #include <sys/vnode.h>
74 
75 #include <security/audit/audit.h>
76 #include <security/mac/mac_framework.h>
77 
78 #include <vm/vm.h>
79 #include <vm/vm_extern.h>
80 #include <vm/pmap.h>
81 #include <vm/vm_map.h>
82 #include <vm/vm_object.h>
83 #include <vm/vm_page.h>
84 #include <vm/vm_pager.h>
85 #include <vm/vnode_pager.h>
86 
87 #ifdef HWPMC_HOOKS
88 #include <sys/pmckern.h>
89 #endif
90 
91 #ifdef HWT_HOOKS
92 #include <dev/hwt/hwt_hook.h>
93 #endif
94 
95 static fo_rdwr_t	vn_read;
96 static fo_rdwr_t	vn_write;
97 static fo_rdwr_t	vn_io_fault;
98 static fo_truncate_t	vn_truncate;
99 static fo_ioctl_t	vn_ioctl;
100 static fo_poll_t	vn_poll;
101 static fo_kqfilter_t	vn_kqfilter;
102 static fo_close_t	vn_closefile;
103 static fo_mmap_t	vn_mmap;
104 static fo_fallocate_t	vn_fallocate;
105 static fo_fspacectl_t	vn_fspacectl;
106 
107 const struct fileops vnops = {
108 	.fo_read = vn_io_fault,
109 	.fo_write = vn_io_fault,
110 	.fo_truncate = vn_truncate,
111 	.fo_ioctl = vn_ioctl,
112 	.fo_poll = vn_poll,
113 	.fo_kqfilter = vn_kqfilter,
114 	.fo_stat = vn_statfile,
115 	.fo_close = vn_closefile,
116 	.fo_chmod = vn_chmod,
117 	.fo_chown = vn_chown,
118 	.fo_sendfile = vn_sendfile,
119 	.fo_seek = vn_seek,
120 	.fo_fill_kinfo = vn_fill_kinfo,
121 	.fo_mmap = vn_mmap,
122 	.fo_fallocate = vn_fallocate,
123 	.fo_fspacectl = vn_fspacectl,
124 	.fo_cmp = vn_cmp,
125 	.fo_flags = DFLAG_PASSABLE | DFLAG_SEEKABLE
126 };
127 
128 const u_int io_hold_cnt = 16;
129 static int vn_io_fault_enable = 1;
130 SYSCTL_INT(_debug, OID_AUTO, vn_io_fault_enable, CTLFLAG_RWTUN,
131     &vn_io_fault_enable, 0, "Enable vn_io_fault lock avoidance");
132 static int vn_io_fault_prefault = 0;
133 SYSCTL_INT(_debug, OID_AUTO, vn_io_fault_prefault, CTLFLAG_RWTUN,
134     &vn_io_fault_prefault, 0, "Enable vn_io_fault prefaulting");
135 static int vn_io_pgcache_read_enable = 1;
136 SYSCTL_INT(_debug, OID_AUTO, vn_io_pgcache_read_enable, CTLFLAG_RWTUN,
137     &vn_io_pgcache_read_enable, 0,
138     "Enable copying from page cache for reads, avoiding fs");
139 static u_long vn_io_faults_cnt;
140 SYSCTL_ULONG(_debug, OID_AUTO, vn_io_faults, CTLFLAG_RD,
141     &vn_io_faults_cnt, 0, "Count of vn_io_fault lock avoidance triggers");
142 
143 static int vfs_allow_read_dir = 0;
144 SYSCTL_INT(_security_bsd, OID_AUTO, allow_read_dir, CTLFLAG_RW,
145     &vfs_allow_read_dir, 0,
146     "Enable read(2) of directory by root for filesystems that support it");
147 
148 /*
149  * Returns true if vn_io_fault mode of handling the i/o request should
150  * be used.
151  */
152 static bool
do_vn_io_fault(struct vnode * vp,struct uio * uio)153 do_vn_io_fault(struct vnode *vp, struct uio *uio)
154 {
155 	struct mount *mp;
156 
157 	return (uio->uio_segflg == UIO_USERSPACE && vp->v_type == VREG &&
158 	    (mp = vp->v_mount) != NULL &&
159 	    (mp->mnt_kern_flag & MNTK_NO_IOPF) != 0 && vn_io_fault_enable);
160 }
161 
162 /*
163  * Structure used to pass arguments to vn_io_fault1(), to do either
164  * file- or vnode-based I/O calls.
165  */
166 struct vn_io_fault_args {
167 	enum {
168 		VN_IO_FAULT_FOP,
169 		VN_IO_FAULT_VOP
170 	} kind;
171 	struct ucred *cred;
172 	int flags;
173 	union {
174 		struct fop_args_tag {
175 			struct file *fp;
176 			fo_rdwr_t *doio;
177 		} fop_args;
178 		struct vop_args_tag {
179 			struct vnode *vp;
180 		} vop_args;
181 	} args;
182 };
183 
184 static int vn_io_fault1(struct vnode *vp, struct uio *uio,
185     struct vn_io_fault_args *args, struct thread *td);
186 
187 int
vn_open(struct nameidata * ndp,int * flagp,int cmode,struct file * fp)188 vn_open(struct nameidata *ndp, int *flagp, int cmode, struct file *fp)
189 {
190 	struct thread *td = curthread;
191 
192 	return (vn_open_cred(ndp, flagp, cmode, 0, td->td_ucred, fp));
193 }
194 
195 static uint64_t
open2nameif(int fmode,u_int vn_open_flags,uint64_t cn_flags)196 open2nameif(int fmode, u_int vn_open_flags, uint64_t cn_flags)
197 {
198 	uint64_t res;
199 
200 	res = ISOPEN | LOCKLEAF | cn_flags;
201 	if ((fmode & O_RESOLVE_BENEATH) != 0)
202 		res |= RBENEATH;
203 	if ((fmode & O_EMPTY_PATH) != 0)
204 		res |= EMPTYPATH;
205 	if ((fmode & FREAD) != 0)
206 		res |= OPENREAD;
207 	if ((fmode & FWRITE) != 0)
208 		res |= OPENWRITE;
209 	if ((fmode & O_NAMEDATTR) != 0)
210 		res |= OPENNAMED | CREATENAMED;
211 	if ((fmode & O_NOFOLLOW) != 0)
212 		res &= ~FOLLOW;
213 	if ((vn_open_flags & VN_OPEN_NOAUDIT) == 0)
214 		res |= AUDITVNODE1;
215 	else
216 		res &= ~AUDITVNODE1;
217 	if ((vn_open_flags & VN_OPEN_NOCAPCHECK) != 0)
218 		res |= NOCAPCHECK;
219 	if ((vn_open_flags & VN_OPEN_WANTIOCTLCAPS) != 0)
220 		res |= WANTIOCTLCAPS;
221 
222 	return (res);
223 }
224 
225 /*
226  * For the O_NAMEDATTR case, check for a valid use of it.
227  */
228 static int
vfs_check_namedattr(struct vnode * vp)229 vfs_check_namedattr(struct vnode *vp)
230 {
231 	int error;
232 	short irflag;
233 
234 	error = 0;
235 	irflag = vn_irflag_read(vp);
236 	if ((vp->v_mount->mnt_flag & MNT_NAMEDATTR) == 0 ||
237 	    ((irflag & VIRF_NAMEDATTR) != 0 && vp->v_type != VREG))
238 		error = EINVAL;
239 	else if ((irflag & (VIRF_NAMEDDIR | VIRF_NAMEDATTR)) == 0)
240 		error = ENOATTR;
241 	return (error);
242 }
243 
244 /*
245  * Common code for vnode open operations via a name lookup.
246  * Lookup the vnode and invoke VOP_CREATE if needed.
247  * Check permissions, and call the VOP_OPEN or VOP_CREATE routine.
248  *
249  * Note that this does NOT free nameidata for the successful case,
250  * due to the NDINIT being done elsewhere.
251  */
252 int
vn_open_cred(struct nameidata * ndp,int * flagp,int cmode,u_int vn_open_flags,struct ucred * cred,struct file * fp)253 vn_open_cred(struct nameidata *ndp, int *flagp, int cmode, u_int vn_open_flags,
254     struct ucred *cred, struct file *fp)
255 {
256 	struct vnode *vp;
257 	struct mount *mp;
258 	struct vattr vat;
259 	struct vattr *vap = &vat;
260 	int fmode, error;
261 	bool first_open;
262 
263 restart:
264 	first_open = false;
265 	fmode = *flagp;
266 	if ((fmode & (O_CREAT | O_EXCL | O_DIRECTORY)) == (O_CREAT |
267 	    O_EXCL | O_DIRECTORY) ||
268 	    (fmode & (O_CREAT | O_EMPTY_PATH)) == (O_CREAT | O_EMPTY_PATH))
269 		return (EINVAL);
270 	else if ((fmode & (O_CREAT | O_DIRECTORY)) == O_CREAT) {
271 		ndp->ni_cnd.cn_nameiop = CREATE;
272 		ndp->ni_cnd.cn_flags = open2nameif(fmode, vn_open_flags,
273 		    ndp->ni_cnd.cn_flags);
274 
275 		/*
276 		 * Set NOCACHE to avoid flushing the cache when
277 		 * rolling in many files at once.
278 		 *
279 		 * Set NC_KEEPPOSENTRY to keep positive entries if they already
280 		 * exist despite NOCACHE.
281 		 */
282 		ndp->ni_cnd.cn_flags |= LOCKPARENT | NOCACHE | NC_KEEPPOSENTRY;
283 		if ((fmode & O_EXCL) != 0)
284 			ndp->ni_cnd.cn_flags &= ~FOLLOW;
285 		if ((vn_open_flags & VN_OPEN_INVFS) == 0)
286 			bwillwrite();
287 		if ((error = namei(ndp)) != 0)
288 			return (error);
289 		if (ndp->ni_vp == NULL) {
290 			if ((fmode & O_NAMEDATTR) != 0 &&
291 			    (ndp->ni_dvp->v_mount->mnt_flag & MNT_NAMEDATTR) ==
292 			    0) {
293 				error = EINVAL;
294 				vp = ndp->ni_dvp;
295 				ndp->ni_dvp = NULL;
296 				goto bad;
297 			}
298 			VATTR_NULL(vap);
299 			vap->va_type = VREG;
300 			vap->va_mode = cmode;
301 			if (fmode & O_EXCL)
302 				vap->va_vaflags |= VA_EXCLUSIVE;
303 			if (vn_start_write(ndp->ni_dvp, &mp, V_NOWAIT) != 0) {
304 				NDFREE_PNBUF(ndp);
305 				vput(ndp->ni_dvp);
306 				if ((error = vn_start_write(NULL, &mp,
307 				    V_XSLEEP | V_PCATCH)) != 0)
308 					return (error);
309 				NDREINIT(ndp);
310 				goto restart;
311 			}
312 			if ((vn_open_flags & VN_OPEN_NAMECACHE) != 0 ||
313 			    (vn_irflag_read(ndp->ni_dvp) & VIRF_INOTIFY) != 0)
314 				ndp->ni_cnd.cn_flags |= MAKEENTRY;
315 #ifdef MAC
316 			error = mac_vnode_check_create(cred, ndp->ni_dvp,
317 			    &ndp->ni_cnd, vap);
318 			if (error == 0)
319 #endif
320 				error = VOP_CREATE(ndp->ni_dvp, &ndp->ni_vp,
321 				    &ndp->ni_cnd, vap);
322 			vp = ndp->ni_vp;
323 			if (error == 0 && (fmode & O_EXCL) != 0 &&
324 			    (fmode & (O_EXLOCK | O_SHLOCK)) != 0) {
325 				VI_LOCK(vp);
326 				vp->v_iflag |= VI_FOPENING;
327 				VI_UNLOCK(vp);
328 				first_open = true;
329 			}
330 			VOP_VPUT_PAIR(ndp->ni_dvp, error == 0 ? &vp : NULL,
331 			    false);
332 			vn_finished_write(mp);
333 			if (error) {
334 				NDFREE_PNBUF(ndp);
335 				if (error == ERELOOKUP) {
336 					NDREINIT(ndp);
337 					goto restart;
338 				}
339 				return (error);
340 			}
341 			fmode &= ~O_TRUNC;
342 		} else {
343 			if (ndp->ni_dvp == ndp->ni_vp)
344 				vrele(ndp->ni_dvp);
345 			else
346 				vput(ndp->ni_dvp);
347 			ndp->ni_dvp = NULL;
348 			vp = ndp->ni_vp;
349 			if (fmode & O_EXCL) {
350 				error = EEXIST;
351 				goto bad;
352 			}
353 			if ((fmode & O_NAMEDATTR) != 0) {
354 				error = vfs_check_namedattr(vp);
355 				if (error != 0)
356 					goto bad;
357 			} else if (vp->v_type == VDIR) {
358 				error = EISDIR;
359 				goto bad;
360 			}
361 			fmode &= ~O_CREAT;
362 		}
363 	} else {
364 		ndp->ni_cnd.cn_nameiop = LOOKUP;
365 		ndp->ni_cnd.cn_flags = open2nameif(fmode, vn_open_flags,
366 		    ndp->ni_cnd.cn_flags);
367 		if ((fmode & FWRITE) == 0)
368 			ndp->ni_cnd.cn_flags |= LOCKSHARED;
369 		if ((error = namei(ndp)) != 0)
370 			return (error);
371 		vp = ndp->ni_vp;
372 		if ((fmode & O_NAMEDATTR) != 0) {
373 			error = vfs_check_namedattr(vp);
374 			if (error != 0)
375 				goto bad;
376 		}
377 	}
378 	error = vn_open_vnode(vp, fmode, cred, curthread, fp);
379 	if (first_open) {
380 		VI_LOCK(vp);
381 		vp->v_iflag &= ~VI_FOPENING;
382 		wakeup(vp);
383 		VI_UNLOCK(vp);
384 	}
385 	if (error)
386 		goto bad;
387 	*flagp = fmode;
388 	return (0);
389 bad:
390 	NDFREE_PNBUF(ndp);
391 	vput(vp);
392 	*flagp = fmode;
393 	ndp->ni_vp = NULL;
394 	return (error);
395 }
396 
397 static int
vn_open_vnode_advlock(struct vnode * vp,int fmode,struct file * fp)398 vn_open_vnode_advlock(struct vnode *vp, int fmode, struct file *fp)
399 {
400 	struct flock lf;
401 	int error, lock_flags, type;
402 
403 	ASSERT_VOP_LOCKED(vp, "vn_open_vnode_advlock");
404 	if ((fmode & (O_EXLOCK | O_SHLOCK)) == 0)
405 		return (0);
406 	KASSERT(fp != NULL, ("open with flock requires fp"));
407 	if (fp->f_type != DTYPE_NONE && fp->f_type != DTYPE_VNODE)
408 		return (EOPNOTSUPP);
409 
410 	lock_flags = VOP_ISLOCKED(vp);
411 	VOP_UNLOCK(vp);
412 
413 	lf.l_whence = SEEK_SET;
414 	lf.l_start = 0;
415 	lf.l_len = 0;
416 	lf.l_type = (fmode & O_EXLOCK) != 0 ? F_WRLCK : F_RDLCK;
417 	type = F_FLOCK;
418 	if ((fmode & FNONBLOCK) == 0)
419 		type |= F_WAIT;
420 	if ((fmode & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))
421 		type |= F_FIRSTOPEN;
422 	error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, type);
423 	if (error == 0)
424 		fp->f_flag |= FHASLOCK;
425 
426 	vn_lock(vp, lock_flags | LK_RETRY);
427 	return (error);
428 }
429 
430 /*
431  * Common code for vnode open operations once a vnode is located.
432  * Check permissions, and call the VOP_OPEN routine.
433  */
434 int
vn_open_vnode(struct vnode * vp,int fmode,struct ucred * cred,struct thread * td,struct file * fp)435 vn_open_vnode(struct vnode *vp, int fmode, struct ucred *cred,
436     struct thread *td, struct file *fp)
437 {
438 	accmode_t accmode;
439 	int error;
440 
441 	KASSERT((fmode & O_PATH) == 0 || (fmode & O_ACCMODE) == 0,
442 	    ("%s: O_PATH and O_ACCMODE are mutually exclusive", __func__));
443 
444 	if (vp->v_type == VLNK) {
445 		if ((fmode & O_PATH) == 0 || (fmode & FEXEC) != 0)
446 			return (EMLINK);
447 	}
448 	if (vp->v_type != VDIR && fmode & O_DIRECTORY)
449 		return (ENOTDIR);
450 
451 	accmode = 0;
452 	if ((fmode & O_PATH) == 0) {
453 		if (vp->v_type == VSOCK)
454 			return (EOPNOTSUPP);
455 		if ((fmode & (FWRITE | O_TRUNC)) != 0) {
456 			if (vp->v_type == VDIR)
457 				return (EISDIR);
458 			accmode |= VWRITE;
459 		}
460 		if ((fmode & FREAD) != 0)
461 			accmode |= VREAD;
462 		if ((fmode & O_APPEND) && (fmode & FWRITE))
463 			accmode |= VAPPEND;
464 #ifdef MAC
465 		if ((fmode & O_CREAT) != 0)
466 			accmode |= VCREAT;
467 #endif
468 	}
469 	if ((fmode & FEXEC) != 0)
470 		accmode |= VEXEC;
471 #ifdef MAC
472 	if ((fmode & O_VERIFY) != 0)
473 		accmode |= VVERIFY;
474 	error = mac_vnode_check_open(cred, vp, accmode);
475 	if (error != 0)
476 		return (error);
477 
478 	accmode &= ~(VCREAT | VVERIFY);
479 #endif
480 	if ((fmode & O_CREAT) == 0 && accmode != 0) {
481 		error = VOP_ACCESS(vp, accmode, cred, td);
482 		if (error != 0)
483 			return (error);
484 	}
485 	if ((fmode & O_PATH) != 0) {
486 		if (vp->v_type != VFIFO && vp->v_type != VSOCK &&
487 		    VOP_ACCESS(vp, VREAD, cred, td) == 0)
488 			fp->f_flag |= FKQALLOWED;
489 		INOTIFY(vp, IN_OPEN);
490 		return (0);
491 	}
492 
493 	if (vp->v_type == VFIFO && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
494 		vn_lock(vp, LK_UPGRADE | LK_RETRY);
495 	error = VOP_OPEN(vp, fmode, cred, td, fp);
496 	if (error != 0)
497 		return (error);
498 
499 	error = vn_open_vnode_advlock(vp, fmode, fp);
500 	if (error == 0 && (fmode & FWRITE) != 0) {
501 		error = VOP_ADD_WRITECOUNT(vp, 1);
502 		if (error == 0) {
503 			CTR3(KTR_VFS, "%s: vp %p v_writecount increased to %d",
504 			     __func__, vp, vp->v_writecount);
505 		}
506 	}
507 
508 	/*
509 	 * Error from advlock or VOP_ADD_WRITECOUNT() still requires
510 	 * calling VOP_CLOSE() to pair with earlier VOP_OPEN().
511 	 */
512 	if (error != 0) {
513 		if (fp != NULL) {
514 			/*
515 			 * Arrange the call by having fdrop() to use
516 			 * vn_closefile().  This is to satisfy
517 			 * filesystems like devfs or tmpfs, which
518 			 * override fo_close().
519 			 */
520 			fp->f_flag |= FOPENFAILED;
521 			fp->f_vnode = vp;
522 			if (fp->f_ops == &badfileops) {
523 				fp->f_type = DTYPE_VNODE;
524 				fp->f_ops = &vnops;
525 			}
526 			vref(vp);
527 		} else {
528 			/*
529 			 * If there is no fp, due to kernel-mode open,
530 			 * we can call VOP_CLOSE() now.
531 			 */
532 			if ((vp->v_type == VFIFO ||
533 			    !MNT_EXTENDED_SHARED(vp->v_mount)) &&
534 			    VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
535 				vn_lock(vp, LK_UPGRADE | LK_RETRY);
536 			(void)VOP_CLOSE(vp, fmode & (FREAD | FWRITE | FEXEC),
537 			    cred, td);
538 		}
539 	}
540 
541 	ASSERT_VOP_LOCKED(vp, "vn_open_vnode");
542 	return (error);
543 
544 }
545 
546 /*
547  * Check for write permissions on the specified vnode.
548  * Prototype text segments cannot be written.
549  * It is racy.
550  */
551 int
vn_writechk(struct vnode * vp)552 vn_writechk(struct vnode *vp)
553 {
554 
555 	ASSERT_VOP_LOCKED(vp, "vn_writechk");
556 	/*
557 	 * If there's shared text associated with
558 	 * the vnode, try to free it up once.  If
559 	 * we fail, we can't allow writing.
560 	 */
561 	if (VOP_IS_TEXT(vp))
562 		return (ETXTBSY);
563 
564 	return (0);
565 }
566 
567 /*
568  * Vnode close call
569  */
570 static int
vn_close1(struct vnode * vp,int flags,struct ucred * file_cred,struct thread * td,bool keep_ref)571 vn_close1(struct vnode *vp, int flags, struct ucred *file_cred,
572     struct thread *td, bool keep_ref)
573 {
574 	struct mount *mp;
575 	int error, lock_flags;
576 
577 	lock_flags = vp->v_type != VFIFO && MNT_EXTENDED_SHARED(vp->v_mount) ?
578 	    LK_SHARED : LK_EXCLUSIVE;
579 
580 	vn_start_write(vp, &mp, V_WAIT);
581 	vn_lock(vp, lock_flags | LK_RETRY);
582 	AUDIT_ARG_VNODE1(vp);
583 	if ((flags & (FWRITE | FOPENFAILED)) == FWRITE) {
584 		VOP_ADD_WRITECOUNT_CHECKED(vp, -1);
585 		CTR3(KTR_VFS, "%s: vp %p v_writecount decreased to %d",
586 		    __func__, vp, vp->v_writecount);
587 	}
588 	error = VOP_CLOSE(vp, flags, file_cred, td);
589 	if (keep_ref)
590 		VOP_UNLOCK(vp);
591 	else
592 		vput(vp);
593 	vn_finished_write(mp);
594 	return (error);
595 }
596 
597 int
vn_close(struct vnode * vp,int flags,struct ucred * file_cred,struct thread * td)598 vn_close(struct vnode *vp, int flags, struct ucred *file_cred,
599     struct thread *td)
600 {
601 
602 	return (vn_close1(vp, flags, file_cred, td, false));
603 }
604 
605 /*
606  * Heuristic to detect sequential operation.
607  */
608 static int
sequential_heuristic(struct uio * uio,struct file * fp)609 sequential_heuristic(struct uio *uio, struct file *fp)
610 {
611 	enum uio_rw rw;
612 
613 	ASSERT_VOP_LOCKED(fp->f_vnode, __func__);
614 
615 	rw = uio->uio_rw;
616 	if (fp->f_flag & FRDAHEAD)
617 		return (fp->f_seqcount[rw] << IO_SEQSHIFT);
618 
619 	/*
620 	 * Offset 0 is handled specially.  open() sets f_seqcount to 1 so
621 	 * that the first I/O is normally considered to be slightly
622 	 * sequential.  Seeking to offset 0 doesn't change sequentiality
623 	 * unless previous seeks have reduced f_seqcount to 0, in which
624 	 * case offset 0 is not special.
625 	 */
626 	if ((uio->uio_offset == 0 && fp->f_seqcount[rw] > 0) ||
627 	    uio->uio_offset == fp->f_nextoff[rw]) {
628 		/*
629 		 * f_seqcount is in units of fixed-size blocks so that it
630 		 * depends mainly on the amount of sequential I/O and not
631 		 * much on the number of sequential I/O's.  The fixed size
632 		 * of 16384 is hard-coded here since it is (not quite) just
633 		 * a magic size that works well here.  This size is more
634 		 * closely related to the best I/O size for real disks than
635 		 * to any block size used by software.
636 		 */
637 		if (uio->uio_resid >= IO_SEQMAX * 16384)
638 			fp->f_seqcount[rw] = IO_SEQMAX;
639 		else {
640 			fp->f_seqcount[rw] += howmany(uio->uio_resid, 16384);
641 			if (fp->f_seqcount[rw] > IO_SEQMAX)
642 				fp->f_seqcount[rw] = IO_SEQMAX;
643 		}
644 		return (fp->f_seqcount[rw] << IO_SEQSHIFT);
645 	}
646 
647 	/* Not sequential.  Quickly draw-down sequentiality. */
648 	if (fp->f_seqcount[rw] > 1)
649 		fp->f_seqcount[rw] = 1;
650 	else
651 		fp->f_seqcount[rw] = 0;
652 	return (0);
653 }
654 
655 /*
656  * Package up an I/O request on a vnode into a uio and do it.
657  */
658 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)659 vn_rdwr(enum uio_rw rw, struct vnode *vp, void *base, int len, off_t offset,
660     enum uio_seg segflg, int ioflg, struct ucred *active_cred,
661     struct ucred *file_cred, ssize_t *aresid, struct thread *td)
662 {
663 	struct uio auio;
664 	struct iovec aiov;
665 	struct mount *mp;
666 	struct ucred *cred;
667 	void *rl_cookie;
668 	struct vn_io_fault_args args;
669 	int error, lock_flags;
670 
671 	if (offset < 0 && vp->v_type != VCHR)
672 		return (EINVAL);
673 	auio.uio_iov = &aiov;
674 	auio.uio_iovcnt = 1;
675 	aiov.iov_base = base;
676 	aiov.iov_len = len;
677 	auio.uio_resid = len;
678 	auio.uio_offset = offset;
679 	auio.uio_segflg = segflg;
680 	auio.uio_rw = rw;
681 	auio.uio_td = td;
682 	error = 0;
683 
684 	if ((ioflg & IO_NODELOCKED) == 0) {
685 		if ((ioflg & IO_RANGELOCKED) == 0) {
686 			if (rw == UIO_READ) {
687 				rl_cookie = vn_rangelock_rlock(vp, offset,
688 				    offset + len);
689 			} else if ((ioflg & IO_APPEND) != 0) {
690 				rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
691 			} else {
692 				rl_cookie = vn_rangelock_wlock(vp, offset,
693 				    offset + len);
694 			}
695 		} else
696 			rl_cookie = NULL;
697 		mp = NULL;
698 		if (rw == UIO_WRITE) {
699 			if (vp->v_type != VCHR &&
700 			    (error = vn_start_write(vp, &mp, V_WAIT | V_PCATCH))
701 			    != 0)
702 				goto out;
703 			lock_flags = vn_lktype_write(mp, vp);
704 		} else
705 			lock_flags = LK_SHARED;
706 		vn_lock(vp, lock_flags | LK_RETRY);
707 	} else
708 		rl_cookie = NULL;
709 
710 	ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
711 #ifdef MAC
712 	if ((ioflg & IO_NOMACCHECK) == 0) {
713 		if (rw == UIO_READ)
714 			error = mac_vnode_check_read(active_cred, file_cred,
715 			    vp);
716 		else
717 			error = mac_vnode_check_write(active_cred, file_cred,
718 			    vp);
719 	}
720 #endif
721 	if (error == 0) {
722 		if (file_cred != NULL)
723 			cred = file_cred;
724 		else
725 			cred = active_cred;
726 		if (do_vn_io_fault(vp, &auio)) {
727 			args.kind = VN_IO_FAULT_VOP;
728 			args.cred = cred;
729 			args.flags = ioflg;
730 			args.args.vop_args.vp = vp;
731 			error = vn_io_fault1(vp, &auio, &args, td);
732 		} else if (rw == UIO_READ) {
733 			error = VOP_READ(vp, &auio, ioflg, cred);
734 		} else /* if (rw == UIO_WRITE) */ {
735 			error = VOP_WRITE(vp, &auio, ioflg, cred);
736 		}
737 	}
738 	if (aresid)
739 		*aresid = auio.uio_resid;
740 	else
741 		if (auio.uio_resid && error == 0)
742 			error = EIO;
743 	if ((ioflg & IO_NODELOCKED) == 0) {
744 		VOP_UNLOCK(vp);
745 		if (mp != NULL)
746 			vn_finished_write(mp);
747 	}
748  out:
749 	if (rl_cookie != NULL)
750 		vn_rangelock_unlock(vp, rl_cookie);
751 	return (error);
752 }
753 
754 /*
755  * Package up an I/O request on a vnode into a uio and do it.  The I/O
756  * request is split up into smaller chunks and we try to avoid saturating
757  * the buffer cache while potentially holding a vnode locked, so we
758  * check bwillwrite() before calling vn_rdwr().  We also call kern_yield()
759  * to give other processes a chance to lock the vnode (either other processes
760  * core'ing the same binary, or unrelated processes scanning the directory).
761  */
762 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)763 vn_rdwr_inchunks(enum uio_rw rw, struct vnode *vp, void *base, size_t len,
764     off_t offset, enum uio_seg segflg, int ioflg, struct ucred *active_cred,
765     struct ucred *file_cred, size_t *aresid, struct thread *td)
766 {
767 	int error = 0;
768 	ssize_t iaresid;
769 
770 	do {
771 		int chunk;
772 
773 		/*
774 		 * Force `offset' to a multiple of MAXBSIZE except possibly
775 		 * for the first chunk, so that filesystems only need to
776 		 * write full blocks except possibly for the first and last
777 		 * chunks.
778 		 */
779 		chunk = MAXBSIZE - (uoff_t)offset % MAXBSIZE;
780 
781 		if (chunk > len)
782 			chunk = len;
783 		if (rw != UIO_READ && vp->v_type == VREG)
784 			bwillwrite();
785 		iaresid = 0;
786 		error = vn_rdwr(rw, vp, base, chunk, offset, segflg,
787 		    ioflg, active_cred, file_cred, &iaresid, td);
788 		len -= chunk;	/* aresid calc already includes length */
789 		if (error)
790 			break;
791 		offset += chunk;
792 		base = (char *)base + chunk;
793 		kern_yield(PRI_USER);
794 	} while (len);
795 	if (aresid)
796 		*aresid = len + iaresid;
797 	return (error);
798 }
799 
800 #if OFF_MAX <= LONG_MAX
801 off_t
foffset_lock(struct file * fp,int flags)802 foffset_lock(struct file *fp, int flags)
803 {
804 	volatile short *flagsp;
805 	off_t res;
806 	short state;
807 
808 	KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
809 
810 	if ((flags & FOF_NOLOCK) != 0)
811 		return (atomic_load_long(&fp->f_offset));
812 
813 	/*
814 	 * According to McKusick the vn lock was protecting f_offset here.
815 	 * It is now protected by the FOFFSET_LOCKED flag.
816 	 */
817 	flagsp = &fp->f_vnread_flags;
818 	if (atomic_cmpset_acq_16(flagsp, 0, FOFFSET_LOCKED))
819 		return (atomic_load_long(&fp->f_offset));
820 
821 	sleepq_lock(&fp->f_vnread_flags);
822 	state = atomic_load_16(flagsp);
823 	for (;;) {
824 		if ((state & FOFFSET_LOCKED) == 0) {
825 			if (!atomic_fcmpset_acq_16(flagsp, &state,
826 			    FOFFSET_LOCKED))
827 				continue;
828 			break;
829 		}
830 		if ((state & FOFFSET_LOCK_WAITING) == 0) {
831 			if (!atomic_fcmpset_acq_16(flagsp, &state,
832 			    state | FOFFSET_LOCK_WAITING))
833 				continue;
834 		}
835 		DROP_GIANT();
836 		sleepq_add(&fp->f_vnread_flags, NULL, "vofflock", 0, 0);
837 		sleepq_wait(&fp->f_vnread_flags, PRI_MAX_KERN);
838 		PICKUP_GIANT();
839 		sleepq_lock(&fp->f_vnread_flags);
840 		state = atomic_load_16(flagsp);
841 	}
842 	res = atomic_load_long(&fp->f_offset);
843 	sleepq_release(&fp->f_vnread_flags);
844 	return (res);
845 }
846 
847 void
foffset_unlock(struct file * fp,off_t val,int flags)848 foffset_unlock(struct file *fp, off_t val, int flags)
849 {
850 	volatile short *flagsp;
851 	short state;
852 
853 	KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
854 
855 	if ((flags & FOF_NOUPDATE) == 0)
856 		atomic_store_long(&fp->f_offset, val);
857 	if ((flags & FOF_NEXTOFF_R) != 0)
858 		fp->f_nextoff[UIO_READ] = val;
859 	if ((flags & FOF_NEXTOFF_W) != 0)
860 		fp->f_nextoff[UIO_WRITE] = val;
861 
862 	if ((flags & FOF_NOLOCK) != 0)
863 		return;
864 
865 	flagsp = &fp->f_vnread_flags;
866 	state = atomic_load_16(flagsp);
867 	if ((state & FOFFSET_LOCK_WAITING) == 0 &&
868 	    atomic_cmpset_rel_16(flagsp, state, 0))
869 		return;
870 
871 	sleepq_lock(&fp->f_vnread_flags);
872 	MPASS((fp->f_vnread_flags & FOFFSET_LOCKED) != 0);
873 	MPASS((fp->f_vnread_flags & FOFFSET_LOCK_WAITING) != 0);
874 	fp->f_vnread_flags = 0;
875 	sleepq_broadcast(&fp->f_vnread_flags, SLEEPQ_SLEEP, 0, 0);
876 	sleepq_release(&fp->f_vnread_flags);
877 }
878 
879 static off_t
foffset_read(struct file * fp)880 foffset_read(struct file *fp)
881 {
882 
883 	return (atomic_load_long(&fp->f_offset));
884 }
885 #else
886 off_t
foffset_lock(struct file * fp,int flags)887 foffset_lock(struct file *fp, int flags)
888 {
889 	struct mtx *mtxp;
890 	off_t res;
891 
892 	KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
893 
894 	mtxp = mtx_pool_find(mtxpool_sleep, fp);
895 	mtx_lock(mtxp);
896 	if ((flags & FOF_NOLOCK) == 0) {
897 		while (fp->f_vnread_flags & FOFFSET_LOCKED) {
898 			fp->f_vnread_flags |= FOFFSET_LOCK_WAITING;
899 			msleep(&fp->f_vnread_flags, mtxp, PRI_MAX_KERN,
900 			    "vofflock", 0);
901 		}
902 		fp->f_vnread_flags |= FOFFSET_LOCKED;
903 	}
904 	res = fp->f_offset;
905 	mtx_unlock(mtxp);
906 	return (res);
907 }
908 
909 void
foffset_unlock(struct file * fp,off_t val,int flags)910 foffset_unlock(struct file *fp, off_t val, int flags)
911 {
912 	struct mtx *mtxp;
913 
914 	KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
915 
916 	mtxp = mtx_pool_find(mtxpool_sleep, fp);
917 	mtx_lock(mtxp);
918 	if ((flags & FOF_NOUPDATE) == 0)
919 		fp->f_offset = val;
920 	if ((flags & FOF_NEXTOFF_R) != 0)
921 		fp->f_nextoff[UIO_READ] = val;
922 	if ((flags & FOF_NEXTOFF_W) != 0)
923 		fp->f_nextoff[UIO_WRITE] = val;
924 	if ((flags & FOF_NOLOCK) == 0) {
925 		KASSERT((fp->f_vnread_flags & FOFFSET_LOCKED) != 0,
926 		    ("Lost FOFFSET_LOCKED"));
927 		if (fp->f_vnread_flags & FOFFSET_LOCK_WAITING)
928 			wakeup(&fp->f_vnread_flags);
929 		fp->f_vnread_flags = 0;
930 	}
931 	mtx_unlock(mtxp);
932 }
933 
934 static off_t
foffset_read(struct file * fp)935 foffset_read(struct file *fp)
936 {
937 
938 	return (foffset_lock(fp, FOF_NOLOCK));
939 }
940 #endif
941 
942 void
foffset_lock_pair(struct file * fp1,off_t * off1p,struct file * fp2,off_t * off2p,int flags)943 foffset_lock_pair(struct file *fp1, off_t *off1p, struct file *fp2, off_t *off2p,
944     int flags)
945 {
946 	KASSERT(fp1 != fp2, ("foffset_lock_pair: fp1 == fp2"));
947 
948 	/* Lock in a consistent order to avoid deadlock. */
949 	if ((uintptr_t)fp1 > (uintptr_t)fp2) {
950 		struct file *tmpfp;
951 		off_t *tmpoffp;
952 
953 		tmpfp = fp1, fp1 = fp2, fp2 = tmpfp;
954 		tmpoffp = off1p, off1p = off2p, off2p = tmpoffp;
955 	}
956 	if (fp1 != NULL)
957 		*off1p = foffset_lock(fp1, flags);
958 	if (fp2 != NULL)
959 		*off2p = foffset_lock(fp2, flags);
960 }
961 
962 void
foffset_lock_uio(struct file * fp,struct uio * uio,int flags)963 foffset_lock_uio(struct file *fp, struct uio *uio, int flags)
964 {
965 
966 	if ((flags & FOF_OFFSET) == 0)
967 		uio->uio_offset = foffset_lock(fp, flags);
968 }
969 
970 void
foffset_unlock_uio(struct file * fp,struct uio * uio,int flags)971 foffset_unlock_uio(struct file *fp, struct uio *uio, int flags)
972 {
973 
974 	if ((flags & FOF_OFFSET) == 0)
975 		foffset_unlock(fp, uio->uio_offset, flags);
976 }
977 
978 static int
get_advice(struct file * fp,struct uio * uio)979 get_advice(struct file *fp, struct uio *uio)
980 {
981 	struct mtx *mtxp;
982 	int ret;
983 
984 	ret = POSIX_FADV_NORMAL;
985 	if (fp->f_advice == NULL || fp->f_vnode->v_type != VREG)
986 		return (ret);
987 
988 	mtxp = mtx_pool_find(mtxpool_sleep, fp);
989 	mtx_lock(mtxp);
990 	if (fp->f_advice != NULL &&
991 	    uio->uio_offset >= fp->f_advice->fa_start &&
992 	    uio->uio_offset + uio->uio_resid <= fp->f_advice->fa_end)
993 		ret = fp->f_advice->fa_advice;
994 	mtx_unlock(mtxp);
995 	return (ret);
996 }
997 
998 static int
get_write_ioflag(struct file * fp)999 get_write_ioflag(struct file *fp)
1000 {
1001 	int ioflag;
1002 	struct mount *mp;
1003 	struct vnode *vp;
1004 
1005 	ioflag = 0;
1006 	vp = fp->f_vnode;
1007 	mp = atomic_load_ptr(&vp->v_mount);
1008 
1009 	if ((fp->f_flag & O_DIRECT) != 0)
1010 		ioflag |= IO_DIRECT;
1011 
1012 	if ((fp->f_flag & O_FSYNC) != 0 ||
1013 	    (mp != NULL && (mp->mnt_flag & MNT_SYNCHRONOUS) != 0))
1014 		ioflag |= IO_SYNC;
1015 
1016 	/*
1017 	 * For O_DSYNC we set both IO_SYNC and IO_DATASYNC, so that VOP_WRITE()
1018 	 * or VOP_DEALLOCATE() implementations that don't understand IO_DATASYNC
1019 	 * fall back to full O_SYNC behavior.
1020 	 */
1021 	if ((fp->f_flag & O_DSYNC) != 0)
1022 		ioflag |= IO_SYNC | IO_DATASYNC;
1023 
1024 	return (ioflag);
1025 }
1026 
1027 int
vn_read_from_obj(struct vnode * vp,struct uio * uio)1028 vn_read_from_obj(struct vnode *vp, struct uio *uio)
1029 {
1030 	vm_object_t obj;
1031 	vm_page_t ma[io_hold_cnt + 2];
1032 	off_t off, vsz;
1033 	ssize_t resid;
1034 	int error, i, j;
1035 
1036 	MPASS(uio->uio_resid <= ptoa(io_hold_cnt + 2));
1037 	obj = atomic_load_ptr(&vp->v_object);
1038 	if (obj == NULL)
1039 		return (EJUSTRETURN);
1040 
1041 	/*
1042 	 * Depends on type stability of vm_objects.
1043 	 */
1044 	vm_object_pip_add(obj, 1);
1045 	if ((obj->flags & OBJ_DEAD) != 0) {
1046 		/*
1047 		 * Note that object might be already reused from the
1048 		 * vnode, and the OBJ_DEAD flag cleared.  This is fine,
1049 		 * we recheck for DOOMED vnode state after all pages
1050 		 * are busied, and retract then.
1051 		 *
1052 		 * But we check for OBJ_DEAD to ensure that we do not
1053 		 * busy pages while vm_object_terminate_pages()
1054 		 * processes the queue.
1055 		 */
1056 		error = EJUSTRETURN;
1057 		goto out_pip;
1058 	}
1059 
1060 	resid = uio->uio_resid;
1061 	off = uio->uio_offset;
1062 	for (i = 0; resid > 0; i++) {
1063 		MPASS(i < io_hold_cnt + 2);
1064 		ma[i] = vm_page_grab_unlocked(obj, atop(off),
1065 		    VM_ALLOC_NOCREAT | VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY |
1066 		    VM_ALLOC_NOWAIT);
1067 		if (ma[i] == NULL)
1068 			break;
1069 
1070 		/*
1071 		 * Skip invalid pages.  Valid mask can be partial only
1072 		 * at EOF, and we clip later.
1073 		 */
1074 		if (vm_page_none_valid(ma[i])) {
1075 			vm_page_sunbusy(ma[i]);
1076 			break;
1077 		}
1078 
1079 		resid -= PAGE_SIZE;
1080 		off += PAGE_SIZE;
1081 	}
1082 	if (i == 0) {
1083 		error = EJUSTRETURN;
1084 		goto out_pip;
1085 	}
1086 
1087 	/*
1088 	 * Check VIRF_DOOMED after we busied our pages.  Since
1089 	 * vgonel() terminates the vnode' vm_object, it cannot
1090 	 * process past pages busied by us.
1091 	 */
1092 	if (VN_IS_DOOMED(vp)) {
1093 		error = EJUSTRETURN;
1094 		goto out;
1095 	}
1096 
1097 	resid = PAGE_SIZE - (uio->uio_offset & PAGE_MASK) + ptoa(i - 1);
1098 	if (resid > uio->uio_resid)
1099 		resid = uio->uio_resid;
1100 
1101 	/*
1102 	 * Unlocked read of vnp_size is safe because truncation cannot
1103 	 * pass busied page.  But we load vnp_size into a local
1104 	 * variable so that possible concurrent extension does not
1105 	 * break calculation.
1106 	 */
1107 #if defined(__powerpc__) && !defined(__powerpc64__)
1108 	vsz = obj->un_pager.vnp.vnp_size;
1109 #else
1110 	vsz = atomic_load_64(&obj->un_pager.vnp.vnp_size);
1111 #endif
1112 	if (uio->uio_offset >= vsz) {
1113 		error = EJUSTRETURN;
1114 		goto out;
1115 	}
1116 	if (uio->uio_offset + resid > vsz)
1117 		resid = vsz - uio->uio_offset;
1118 
1119 	error = vn_io_fault_pgmove(ma, uio->uio_offset & PAGE_MASK, resid, uio);
1120 
1121 out:
1122 	for (j = 0; j < i; j++) {
1123 		if (error == 0)
1124 			vm_page_reference(ma[j]);
1125 		vm_page_sunbusy(ma[j]);
1126 	}
1127 out_pip:
1128 	vm_object_pip_wakeup(obj);
1129 	if (error != 0)
1130 		return (error);
1131 	return (uio->uio_resid == 0 ? 0 : EJUSTRETURN);
1132 }
1133 
1134 /*
1135  * File table vnode read routine.
1136  */
1137 static int
vn_read(struct file * fp,struct uio * uio,struct ucred * active_cred,int flags,struct thread * td)1138 vn_read(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags,
1139     struct thread *td)
1140 {
1141 	struct vnode *vp;
1142 	off_t orig_offset;
1143 	int error, ioflag;
1144 	int advice;
1145 
1146 	KASSERT(uio->uio_td == td, ("uio_td %p is not td %p",
1147 	    uio->uio_td, td));
1148 	KASSERT(flags & FOF_OFFSET, ("No FOF_OFFSET"));
1149 	vp = fp->f_vnode;
1150 	ioflag = 0;
1151 	if (fp->f_flag & FNONBLOCK)
1152 		ioflag |= IO_NDELAY;
1153 	if (fp->f_flag & O_DIRECT)
1154 		ioflag |= IO_DIRECT;
1155 
1156 	/*
1157 	 * Try to read from page cache.  VIRF_DOOMED check is racy but
1158 	 * allows us to avoid unneeded work outright.
1159 	 */
1160 	if (vn_io_pgcache_read_enable && !mac_vnode_check_read_enabled() &&
1161 	    (vn_irflag_read(vp) & (VIRF_DOOMED | VIRF_PGREAD)) == VIRF_PGREAD) {
1162 		error = VOP_READ_PGCACHE(vp, uio, ioflag, fp->f_cred);
1163 		if (error == 0) {
1164 			fp->f_nextoff[UIO_READ] = uio->uio_offset;
1165 			return (0);
1166 		}
1167 		if (error != EJUSTRETURN)
1168 			return (error);
1169 	}
1170 
1171 	advice = get_advice(fp, uio);
1172 	vn_lock(vp, LK_SHARED | LK_RETRY);
1173 
1174 	switch (advice) {
1175 	case POSIX_FADV_NORMAL:
1176 	case POSIX_FADV_SEQUENTIAL:
1177 	case POSIX_FADV_NOREUSE:
1178 		ioflag |= sequential_heuristic(uio, fp);
1179 		break;
1180 	case POSIX_FADV_RANDOM:
1181 		/* Disable read-ahead for random I/O. */
1182 		break;
1183 	}
1184 	orig_offset = uio->uio_offset;
1185 
1186 #ifdef MAC
1187 	error = mac_vnode_check_read(active_cred, fp->f_cred, vp);
1188 	if (error == 0)
1189 #endif
1190 		error = VOP_READ(vp, uio, ioflag, fp->f_cred);
1191 	fp->f_nextoff[UIO_READ] = uio->uio_offset;
1192 	VOP_UNLOCK(vp);
1193 	if (error == 0 && advice == POSIX_FADV_NOREUSE &&
1194 	    orig_offset != uio->uio_offset)
1195 		/*
1196 		 * Use POSIX_FADV_DONTNEED to flush pages and buffers
1197 		 * for the backing file after a POSIX_FADV_NOREUSE
1198 		 * read(2).
1199 		 */
1200 		error = VOP_ADVISE(vp, orig_offset, uio->uio_offset - 1,
1201 		    POSIX_FADV_DONTNEED);
1202 	return (error);
1203 }
1204 
1205 /*
1206  * File table vnode write routine.
1207  */
1208 static int
vn_write(struct file * fp,struct uio * uio,struct ucred * active_cred,int flags,struct thread * td)1209 vn_write(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags,
1210     struct thread *td)
1211 {
1212 	struct vnode *vp;
1213 	struct mount *mp;
1214 	off_t orig_offset;
1215 	int error, ioflag;
1216 	int advice;
1217 	bool need_finished_write;
1218 
1219 	KASSERT(uio->uio_td == td, ("uio_td %p is not td %p",
1220 	    uio->uio_td, td));
1221 	KASSERT(flags & FOF_OFFSET, ("No FOF_OFFSET"));
1222 	vp = fp->f_vnode;
1223 	if (vp->v_type == VREG)
1224 		bwillwrite();
1225 	ioflag = IO_UNIT;
1226 	if (vp->v_type == VREG && (fp->f_flag & O_APPEND) != 0)
1227 		ioflag |= IO_APPEND;
1228 	if ((fp->f_flag & FNONBLOCK) != 0)
1229 		ioflag |= IO_NDELAY;
1230 	ioflag |= get_write_ioflag(fp);
1231 
1232 	mp = NULL;
1233 	need_finished_write = false;
1234 	if (vp->v_type != VCHR) {
1235 		error = vn_start_write(vp, &mp, V_WAIT | V_PCATCH);
1236 		if (error != 0)
1237 			goto unlock;
1238 		need_finished_write = true;
1239 	}
1240 
1241 	advice = get_advice(fp, uio);
1242 
1243 	vn_lock(vp, vn_lktype_write(mp, vp) | LK_RETRY);
1244 	switch (advice) {
1245 	case POSIX_FADV_NORMAL:
1246 	case POSIX_FADV_SEQUENTIAL:
1247 	case POSIX_FADV_NOREUSE:
1248 		ioflag |= sequential_heuristic(uio, fp);
1249 		break;
1250 	case POSIX_FADV_RANDOM:
1251 		/* XXX: Is this correct? */
1252 		break;
1253 	}
1254 	orig_offset = uio->uio_offset;
1255 
1256 #ifdef MAC
1257 	error = mac_vnode_check_write(active_cred, fp->f_cred, vp);
1258 	if (error == 0)
1259 #endif
1260 		error = VOP_WRITE(vp, uio, ioflag, fp->f_cred);
1261 	fp->f_nextoff[UIO_WRITE] = uio->uio_offset;
1262 	VOP_UNLOCK(vp);
1263 	if (need_finished_write)
1264 		vn_finished_write(mp);
1265 	if (error == 0 && advice == POSIX_FADV_NOREUSE &&
1266 	    orig_offset != uio->uio_offset)
1267 		/*
1268 		 * Use POSIX_FADV_DONTNEED to flush pages and buffers
1269 		 * for the backing file after a POSIX_FADV_NOREUSE
1270 		 * write(2).
1271 		 */
1272 		error = VOP_ADVISE(vp, orig_offset, uio->uio_offset - 1,
1273 		    POSIX_FADV_DONTNEED);
1274 unlock:
1275 	return (error);
1276 }
1277 
1278 /*
1279  * The vn_io_fault() is a wrapper around vn_read() and vn_write() to
1280  * prevent the following deadlock:
1281  *
1282  * Assume that the thread A reads from the vnode vp1 into userspace
1283  * buffer buf1 backed by the pages of vnode vp2.  If a page in buf1 is
1284  * currently not resident, then system ends up with the call chain
1285  *   vn_read() -> VOP_READ(vp1) -> uiomove() -> [Page Fault] ->
1286  *     vm_fault(buf1) -> vnode_pager_getpages(vp2) -> VOP_GETPAGES(vp2)
1287  * which establishes lock order vp1->vn_lock, then vp2->vn_lock.
1288  * If, at the same time, thread B reads from vnode vp2 into buffer buf2
1289  * backed by the pages of vnode vp1, and some page in buf2 is not
1290  * resident, we get a reversed order vp2->vn_lock, then vp1->vn_lock.
1291  *
1292  * To prevent the lock order reversal and deadlock, vn_io_fault() does
1293  * not allow page faults to happen during VOP_READ() or VOP_WRITE().
1294  * Instead, it first tries to do the whole range i/o with pagefaults
1295  * disabled. If all pages in the i/o buffer are resident and mapped,
1296  * VOP will succeed (ignoring the genuine filesystem errors).
1297  * Otherwise, we get back EFAULT, and vn_io_fault() falls back to do
1298  * i/o in chunks, with all pages in the chunk prefaulted and held
1299  * using vm_fault_quick_hold_pages().
1300  *
1301  * Filesystems using this deadlock avoidance scheme should use the
1302  * array of the held pages from uio, saved in the curthread->td_ma,
1303  * instead of doing uiomove().  A helper function
1304  * vn_io_fault_uiomove() converts uiomove request into
1305  * uiomove_fromphys() over td_ma array.
1306  *
1307  * Since vnode locks do not cover the whole i/o anymore, rangelocks
1308  * make the current i/o request atomic with respect to other i/os and
1309  * truncations.
1310  */
1311 
1312 /*
1313  * Decode vn_io_fault_args and perform the corresponding i/o.
1314  */
1315 static int
vn_io_fault_doio(struct vn_io_fault_args * args,struct uio * uio,struct thread * td)1316 vn_io_fault_doio(struct vn_io_fault_args *args, struct uio *uio,
1317     struct thread *td)
1318 {
1319 	int error, save;
1320 
1321 	error = 0;
1322 	save = vm_fault_disable_pagefaults();
1323 	switch (args->kind) {
1324 	case VN_IO_FAULT_FOP:
1325 		error = (args->args.fop_args.doio)(args->args.fop_args.fp,
1326 		    uio, args->cred, args->flags, td);
1327 		break;
1328 	case VN_IO_FAULT_VOP:
1329 		switch (uio->uio_rw) {
1330 		case UIO_READ:
1331 			error = VOP_READ(args->args.vop_args.vp, uio,
1332 			    args->flags, args->cred);
1333 			break;
1334 		case UIO_WRITE:
1335 			error = VOP_WRITE(args->args.vop_args.vp, uio,
1336 			    args->flags, args->cred);
1337 			break;
1338 		}
1339 		break;
1340 	default:
1341 		panic("vn_io_fault_doio: unknown kind of io %d %d",
1342 		    args->kind, uio->uio_rw);
1343 	}
1344 	vm_fault_enable_pagefaults(save);
1345 	return (error);
1346 }
1347 
1348 static int
vn_io_fault_touch(char * base,const struct uio * uio)1349 vn_io_fault_touch(char *base, const struct uio *uio)
1350 {
1351 	int r;
1352 
1353 	r = fubyte(base);
1354 	if (r == -1 || (uio->uio_rw == UIO_READ && subyte(base, r) == -1))
1355 		return (EFAULT);
1356 	return (0);
1357 }
1358 
1359 static int
vn_io_fault_prefault_user(const struct uio * uio)1360 vn_io_fault_prefault_user(const struct uio *uio)
1361 {
1362 	char *base;
1363 	const struct iovec *iov;
1364 	size_t len;
1365 	ssize_t resid;
1366 	int error, i;
1367 
1368 	KASSERT(uio->uio_segflg == UIO_USERSPACE,
1369 	    ("vn_io_fault_prefault userspace"));
1370 
1371 	error = i = 0;
1372 	iov = uio->uio_iov;
1373 	resid = uio->uio_resid;
1374 	base = iov->iov_base;
1375 	len = iov->iov_len;
1376 	while (resid > 0) {
1377 		error = vn_io_fault_touch(base, uio);
1378 		if (error != 0)
1379 			break;
1380 		if (len < PAGE_SIZE) {
1381 			if (len != 0) {
1382 				error = vn_io_fault_touch(base + len - 1, uio);
1383 				if (error != 0)
1384 					break;
1385 				resid -= len;
1386 			}
1387 			if (++i >= uio->uio_iovcnt)
1388 				break;
1389 			iov = uio->uio_iov + i;
1390 			base = iov->iov_base;
1391 			len = iov->iov_len;
1392 		} else {
1393 			len -= PAGE_SIZE;
1394 			base += PAGE_SIZE;
1395 			resid -= PAGE_SIZE;
1396 		}
1397 	}
1398 	return (error);
1399 }
1400 
1401 /*
1402  * Common code for vn_io_fault(), agnostic to the kind of i/o request.
1403  * Uses vn_io_fault_doio() to make the call to an actual i/o function.
1404  * Used from vn_rdwr() and vn_io_fault(), which encode the i/o request
1405  * into args and call vn_io_fault1() to handle faults during the user
1406  * mode buffer accesses.
1407  */
1408 static int
vn_io_fault1(struct vnode * vp,struct uio * uio,struct vn_io_fault_args * args,struct thread * td)1409 vn_io_fault1(struct vnode *vp, struct uio *uio, struct vn_io_fault_args *args,
1410     struct thread *td)
1411 {
1412 	vm_page_t ma[io_hold_cnt + 2];
1413 	struct uio *uio_clone, short_uio;
1414 	struct iovec short_iovec[1];
1415 	vm_page_t *prev_td_ma;
1416 	vm_prot_t prot;
1417 	vm_offset_t addr, end;
1418 	size_t len, resid;
1419 	ssize_t adv;
1420 	int error, cnt, saveheld, prev_td_ma_cnt;
1421 
1422 	if (vn_io_fault_prefault) {
1423 		error = vn_io_fault_prefault_user(uio);
1424 		if (error != 0)
1425 			return (error); /* Or ignore ? */
1426 	}
1427 
1428 	prot = uio->uio_rw == UIO_READ ? VM_PROT_WRITE : VM_PROT_READ;
1429 
1430 	/*
1431 	 * The UFS follows IO_UNIT directive and replays back both
1432 	 * uio_offset and uio_resid if an error is encountered during the
1433 	 * operation.  But, since the iovec may be already advanced,
1434 	 * uio is still in an inconsistent state.
1435 	 *
1436 	 * Cache a copy of the original uio, which is advanced to the redo
1437 	 * point using UIO_NOCOPY below.
1438 	 */
1439 	uio_clone = cloneuio(uio);
1440 	resid = uio->uio_resid;
1441 
1442 	short_uio.uio_segflg = UIO_USERSPACE;
1443 	short_uio.uio_rw = uio->uio_rw;
1444 	short_uio.uio_td = uio->uio_td;
1445 
1446 	error = vn_io_fault_doio(args, uio, td);
1447 	if (error != EFAULT)
1448 		goto out;
1449 
1450 	atomic_add_long(&vn_io_faults_cnt, 1);
1451 	uio_clone->uio_segflg = UIO_NOCOPY;
1452 	uiomove(NULL, resid - uio->uio_resid, uio_clone);
1453 	uio_clone->uio_segflg = uio->uio_segflg;
1454 
1455 	saveheld = curthread_pflags_set(TDP_UIOHELD);
1456 	prev_td_ma = td->td_ma;
1457 	prev_td_ma_cnt = td->td_ma_cnt;
1458 
1459 	while (uio_clone->uio_resid != 0) {
1460 		len = uio_clone->uio_iov->iov_len;
1461 		if (len == 0) {
1462 			KASSERT(uio_clone->uio_iovcnt >= 1,
1463 			    ("iovcnt underflow"));
1464 			uio_clone->uio_iov++;
1465 			uio_clone->uio_iovcnt--;
1466 			continue;
1467 		}
1468 		if (len > ptoa(io_hold_cnt))
1469 			len = ptoa(io_hold_cnt);
1470 		addr = (uintptr_t)uio_clone->uio_iov->iov_base;
1471 		end = round_page(addr + len);
1472 		if (end < addr) {
1473 			error = EFAULT;
1474 			break;
1475 		}
1476 		/*
1477 		 * A perfectly misaligned address and length could cause
1478 		 * both the start and the end of the chunk to use partial
1479 		 * page.  +2 accounts for such a situation.
1480 		 */
1481 		cnt = vm_fault_quick_hold_pages(&td->td_proc->p_vmspace->vm_map,
1482 		    addr, len, prot, ma, io_hold_cnt + 2);
1483 		if (cnt == -1) {
1484 			error = EFAULT;
1485 			break;
1486 		}
1487 		short_uio.uio_iov = &short_iovec[0];
1488 		short_iovec[0].iov_base = (void *)addr;
1489 		short_uio.uio_iovcnt = 1;
1490 		short_uio.uio_resid = short_iovec[0].iov_len = len;
1491 		short_uio.uio_offset = uio_clone->uio_offset;
1492 		td->td_ma = ma;
1493 		td->td_ma_cnt = cnt;
1494 
1495 		error = vn_io_fault_doio(args, &short_uio, td);
1496 		vm_page_unhold_pages(ma, cnt);
1497 		adv = len - short_uio.uio_resid;
1498 
1499 		uio_clone->uio_iov->iov_base =
1500 		    (char *)uio_clone->uio_iov->iov_base + adv;
1501 		uio_clone->uio_iov->iov_len -= adv;
1502 		uio_clone->uio_resid -= adv;
1503 		uio_clone->uio_offset += adv;
1504 
1505 		uio->uio_resid -= adv;
1506 		uio->uio_offset += adv;
1507 
1508 		if (error != 0 || adv == 0)
1509 			break;
1510 	}
1511 	td->td_ma = prev_td_ma;
1512 	td->td_ma_cnt = prev_td_ma_cnt;
1513 	curthread_pflags_restore(saveheld);
1514 out:
1515 	freeuio(uio_clone);
1516 	return (error);
1517 }
1518 
1519 static int
vn_io_fault(struct file * fp,struct uio * uio,struct ucred * active_cred,int flags,struct thread * td)1520 vn_io_fault(struct file *fp, struct uio *uio, struct ucred *active_cred,
1521     int flags, struct thread *td)
1522 {
1523 	fo_rdwr_t *doio;
1524 	struct vnode *vp;
1525 	void *rl_cookie;
1526 	struct vn_io_fault_args args;
1527 	int error;
1528 	bool do_io_fault, do_rangelock;
1529 
1530 	doio = uio->uio_rw == UIO_READ ? vn_read : vn_write;
1531 	vp = fp->f_vnode;
1532 
1533 	/*
1534 	 * The ability to read(2) on a directory has historically been
1535 	 * allowed for all users, but this can and has been the source of
1536 	 * at least one security issue in the past.  As such, it is now hidden
1537 	 * away behind a sysctl for those that actually need it to use it, and
1538 	 * restricted to root when it's turned on to make it relatively safe to
1539 	 * leave on for longer sessions of need.
1540 	 */
1541 	if (vp->v_type == VDIR) {
1542 		KASSERT(uio->uio_rw == UIO_READ,
1543 		    ("illegal write attempted on a directory"));
1544 		if (!vfs_allow_read_dir)
1545 			return (EISDIR);
1546 		if ((error = priv_check(td, PRIV_VFS_READ_DIR)) != 0)
1547 			return (EISDIR);
1548 	}
1549 
1550 	do_io_fault = do_vn_io_fault(vp, uio);
1551 	do_rangelock = do_io_fault || (vn_irflag_read(vp) & VIRF_PGREAD) != 0;
1552 	foffset_lock_uio(fp, uio, flags);
1553 	if (do_rangelock) {
1554 		if (uio->uio_rw == UIO_READ) {
1555 			rl_cookie = vn_rangelock_rlock(vp, uio->uio_offset,
1556 			    uio->uio_offset + uio->uio_resid);
1557 		} else if ((fp->f_flag & O_APPEND) != 0 ||
1558 		    (flags & FOF_OFFSET) == 0) {
1559 			/* For appenders, punt and lock the whole range. */
1560 			rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
1561 		} else {
1562 			rl_cookie = vn_rangelock_wlock(vp, uio->uio_offset,
1563 			    uio->uio_offset + uio->uio_resid);
1564 		}
1565 	}
1566 	if (do_io_fault) {
1567 		args.kind = VN_IO_FAULT_FOP;
1568 		args.args.fop_args.fp = fp;
1569 		args.args.fop_args.doio = doio;
1570 		args.cred = active_cred;
1571 		args.flags = flags | FOF_OFFSET;
1572 		error = vn_io_fault1(vp, uio, &args, td);
1573 	} else {
1574 		error = doio(fp, uio, active_cred, flags | FOF_OFFSET, td);
1575 	}
1576 	if (do_rangelock)
1577 		vn_rangelock_unlock(vp, rl_cookie);
1578 	foffset_unlock_uio(fp, uio, flags);
1579 	return (error);
1580 }
1581 
1582 /*
1583  * Helper function to perform the requested uiomove operation using
1584  * the held pages for io->uio_iov[0].iov_base buffer instead of
1585  * copyin/copyout.  Access to the pages with uiomove_fromphys()
1586  * instead of iov_base prevents page faults that could occur due to
1587  * pmap_collect() invalidating the mapping created by
1588  * vm_fault_quick_hold_pages(), or pageout daemon, page laundry or
1589  * object cleanup revoking the write access from page mappings.
1590  *
1591  * Filesystems specified MNTK_NO_IOPF shall use vn_io_fault_uiomove()
1592  * instead of plain uiomove().
1593  */
1594 int
vn_io_fault_uiomove(char * data,int xfersize,struct uio * uio)1595 vn_io_fault_uiomove(char *data, int xfersize, struct uio *uio)
1596 {
1597 	struct uio transp_uio;
1598 	struct iovec transp_iov[1];
1599 	struct thread *td;
1600 	size_t adv;
1601 	int error, pgadv;
1602 
1603 	td = curthread;
1604 	if ((td->td_pflags & TDP_UIOHELD) == 0 ||
1605 	    uio->uio_segflg != UIO_USERSPACE)
1606 		return (uiomove(data, xfersize, uio));
1607 
1608 	KASSERT(uio->uio_iovcnt == 1, ("uio_iovcnt %d", uio->uio_iovcnt));
1609 	transp_iov[0].iov_base = data;
1610 	transp_uio.uio_iov = &transp_iov[0];
1611 	transp_uio.uio_iovcnt = 1;
1612 	if (xfersize > uio->uio_resid)
1613 		xfersize = uio->uio_resid;
1614 	transp_uio.uio_resid = transp_iov[0].iov_len = xfersize;
1615 	transp_uio.uio_offset = 0;
1616 	transp_uio.uio_segflg = UIO_SYSSPACE;
1617 	/*
1618 	 * Since transp_iov points to data, and td_ma page array
1619 	 * corresponds to original uio->uio_iov, we need to invert the
1620 	 * direction of the i/o operation as passed to
1621 	 * uiomove_fromphys().
1622 	 */
1623 	switch (uio->uio_rw) {
1624 	case UIO_WRITE:
1625 		transp_uio.uio_rw = UIO_READ;
1626 		break;
1627 	case UIO_READ:
1628 		transp_uio.uio_rw = UIO_WRITE;
1629 		break;
1630 	}
1631 	transp_uio.uio_td = uio->uio_td;
1632 	error = uiomove_fromphys(td->td_ma,
1633 	    ((vm_offset_t)uio->uio_iov->iov_base) & PAGE_MASK,
1634 	    xfersize, &transp_uio);
1635 	adv = xfersize - transp_uio.uio_resid;
1636 	pgadv =
1637 	    (((vm_offset_t)uio->uio_iov->iov_base + adv) >> PAGE_SHIFT) -
1638 	    (((vm_offset_t)uio->uio_iov->iov_base) >> PAGE_SHIFT);
1639 	td->td_ma += pgadv;
1640 	KASSERT(td->td_ma_cnt >= pgadv, ("consumed pages %d %d", td->td_ma_cnt,
1641 	    pgadv));
1642 	td->td_ma_cnt -= pgadv;
1643 	uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + adv;
1644 	uio->uio_iov->iov_len -= adv;
1645 	uio->uio_resid -= adv;
1646 	uio->uio_offset += adv;
1647 	return (error);
1648 }
1649 
1650 int
vn_io_fault_pgmove(vm_page_t ma[],vm_offset_t offset,int xfersize,struct uio * uio)1651 vn_io_fault_pgmove(vm_page_t ma[], vm_offset_t offset, int xfersize,
1652     struct uio *uio)
1653 {
1654 	struct thread *td;
1655 	vm_offset_t iov_base;
1656 	int cnt, pgadv;
1657 
1658 	td = curthread;
1659 	if ((td->td_pflags & TDP_UIOHELD) == 0 ||
1660 	    uio->uio_segflg != UIO_USERSPACE)
1661 		return (uiomove_fromphys(ma, offset, xfersize, uio));
1662 
1663 	KASSERT(uio->uio_iovcnt == 1, ("uio_iovcnt %d", uio->uio_iovcnt));
1664 	cnt = xfersize > uio->uio_resid ? uio->uio_resid : xfersize;
1665 	iov_base = (vm_offset_t)uio->uio_iov->iov_base;
1666 	switch (uio->uio_rw) {
1667 	case UIO_WRITE:
1668 		pmap_copy_pages(td->td_ma, iov_base & PAGE_MASK, ma,
1669 		    offset, cnt);
1670 		break;
1671 	case UIO_READ:
1672 		pmap_copy_pages(ma, offset, td->td_ma, iov_base & PAGE_MASK,
1673 		    cnt);
1674 		break;
1675 	}
1676 	pgadv = ((iov_base + cnt) >> PAGE_SHIFT) - (iov_base >> PAGE_SHIFT);
1677 	td->td_ma += pgadv;
1678 	KASSERT(td->td_ma_cnt >= pgadv, ("consumed pages %d %d", td->td_ma_cnt,
1679 	    pgadv));
1680 	td->td_ma_cnt -= pgadv;
1681 	uio->uio_iov->iov_base = (char *)(iov_base + cnt);
1682 	uio->uio_iov->iov_len -= cnt;
1683 	uio->uio_resid -= cnt;
1684 	uio->uio_offset += cnt;
1685 	return (0);
1686 }
1687 
1688 /*
1689  * File table truncate routine.
1690  */
1691 static int
vn_truncate(struct file * fp,off_t length,struct ucred * active_cred,struct thread * td)1692 vn_truncate(struct file *fp, off_t length, struct ucred *active_cred,
1693     struct thread *td)
1694 {
1695 	struct mount *mp;
1696 	struct vnode *vp;
1697 	void *rl_cookie;
1698 	int error;
1699 
1700 	vp = fp->f_vnode;
1701 
1702 retry:
1703 	/*
1704 	 * Lock the whole range for truncation.  Otherwise split i/o
1705 	 * might happen partly before and partly after the truncation.
1706 	 */
1707 	rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
1708 	error = vn_start_write(vp, &mp, V_WAIT | V_PCATCH);
1709 	if (error)
1710 		goto out1;
1711 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1712 	AUDIT_ARG_VNODE1(vp);
1713 	if (vp->v_type == VDIR) {
1714 		error = EISDIR;
1715 		goto out;
1716 	}
1717 #ifdef MAC
1718 	error = mac_vnode_check_write(active_cred, fp->f_cred, vp);
1719 	if (error)
1720 		goto out;
1721 #endif
1722 	error = vn_truncate_locked(vp, length, (fp->f_flag & O_FSYNC) != 0,
1723 	    fp->f_cred);
1724 out:
1725 	VOP_UNLOCK(vp);
1726 	vn_finished_write(mp);
1727 out1:
1728 	vn_rangelock_unlock(vp, rl_cookie);
1729 	if (error == ERELOOKUP)
1730 		goto retry;
1731 	return (error);
1732 }
1733 
1734 /*
1735  * Truncate a file that is already locked.
1736  */
1737 int
vn_truncate_locked(struct vnode * vp,off_t length,bool sync,struct ucred * cred)1738 vn_truncate_locked(struct vnode *vp, off_t length, bool sync,
1739     struct ucred *cred)
1740 {
1741 	struct vattr vattr;
1742 	int error;
1743 
1744 	error = VOP_ADD_WRITECOUNT(vp, 1);
1745 	if (error == 0) {
1746 		VATTR_NULL(&vattr);
1747 		vattr.va_size = length;
1748 		if (sync)
1749 			vattr.va_vaflags |= VA_SYNC;
1750 		error = VOP_SETATTR(vp, &vattr, cred);
1751 		VOP_ADD_WRITECOUNT_CHECKED(vp, -1);
1752 		if (error == 0)
1753 			INOTIFY(vp, IN_MODIFY);
1754 	}
1755 	return (error);
1756 }
1757 
1758 /*
1759  * File table vnode stat routine.
1760  */
1761 int
vn_statfile(struct file * fp,struct stat * sb,struct ucred * active_cred)1762 vn_statfile(struct file *fp, struct stat *sb, struct ucred *active_cred)
1763 {
1764 	struct vnode *vp = fp->f_vnode;
1765 	int error;
1766 
1767 	vn_lock(vp, LK_SHARED | LK_RETRY);
1768 	error = VOP_STAT(vp, sb, active_cred, fp->f_cred);
1769 	VOP_UNLOCK(vp);
1770 
1771 	return (error);
1772 }
1773 
1774 /*
1775  * File table vnode ioctl routine.
1776  */
1777 static int
vn_ioctl(struct file * fp,u_long com,void * data,struct ucred * active_cred,struct thread * td)1778 vn_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
1779     struct thread *td)
1780 {
1781 	struct vnode *vp;
1782 	struct fiobmap2_arg *bmarg;
1783 	off_t size;
1784 	int error;
1785 
1786 	vp = fp->f_vnode;
1787 	switch (vp->v_type) {
1788 	case VDIR:
1789 	case VREG:
1790 		switch (com) {
1791 		case FIONREAD:
1792 			error = vn_getsize(vp, &size, active_cred);
1793 			if (error == 0)
1794 				*(int *)data = size - fp->f_offset;
1795 			return (error);
1796 		case FIOBMAP2:
1797 			bmarg = (struct fiobmap2_arg *)data;
1798 			vn_lock(vp, LK_SHARED | LK_RETRY);
1799 #ifdef MAC
1800 			error = mac_vnode_check_read(active_cred, fp->f_cred,
1801 			    vp);
1802 			if (error == 0)
1803 #endif
1804 				error = VOP_BMAP(vp, bmarg->bn, NULL,
1805 				    &bmarg->bn, &bmarg->runp, &bmarg->runb);
1806 			VOP_UNLOCK(vp);
1807 			return (error);
1808 		case FIONBIO:
1809 		case FIOASYNC:
1810 			return (0);
1811 		default:
1812 			return (VOP_IOCTL(vp, com, data, fp->f_flag,
1813 			    active_cred, td));
1814 		}
1815 		break;
1816 	case VCHR:
1817 		return (VOP_IOCTL(vp, com, data, fp->f_flag,
1818 		    active_cred, td));
1819 	default:
1820 		return (ENOTTY);
1821 	}
1822 }
1823 
1824 /*
1825  * File table vnode poll routine.
1826  */
1827 static int
vn_poll(struct file * fp,int events,struct ucred * active_cred,struct thread * td)1828 vn_poll(struct file *fp, int events, struct ucred *active_cred,
1829     struct thread *td)
1830 {
1831 	struct vnode *vp;
1832 	int error;
1833 
1834 	vp = fp->f_vnode;
1835 #if defined(MAC) || defined(AUDIT)
1836 	if (AUDITING_TD(td) || mac_vnode_check_poll_enabled()) {
1837 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1838 		AUDIT_ARG_VNODE1(vp);
1839 		error = mac_vnode_check_poll(active_cred, fp->f_cred, vp);
1840 		VOP_UNLOCK(vp);
1841 		if (error != 0)
1842 			return (error);
1843 	}
1844 #endif
1845 	error = VOP_POLL(vp, events, fp->f_cred, td);
1846 	return (error);
1847 }
1848 
1849 /*
1850  * Acquire the requested lock and then check for validity.  LK_RETRY
1851  * permits vn_lock to return doomed vnodes.
1852  */
1853 static int __noinline
_vn_lock_fallback(struct vnode * vp,int flags,const char * file,int line,int error)1854 _vn_lock_fallback(struct vnode *vp, int flags, const char *file, int line,
1855     int error)
1856 {
1857 
1858 	KASSERT((flags & LK_RETRY) == 0 || error == 0,
1859 	    ("vn_lock: error %d incompatible with flags %#x", error, flags));
1860 
1861 	if (error == 0)
1862 		VNASSERT(VN_IS_DOOMED(vp), vp, ("vnode not doomed"));
1863 
1864 	if ((flags & LK_RETRY) == 0) {
1865 		if (error == 0) {
1866 			VOP_UNLOCK(vp);
1867 			error = ENOENT;
1868 		}
1869 		return (error);
1870 	}
1871 
1872 	/*
1873 	 * LK_RETRY case.
1874 	 *
1875 	 * Nothing to do if we got the lock.
1876 	 */
1877 	if (error == 0)
1878 		return (0);
1879 
1880 	/*
1881 	 * Interlock was dropped by the call in _vn_lock.
1882 	 */
1883 	flags &= ~LK_INTERLOCK;
1884 	do {
1885 		error = VOP_LOCK1(vp, flags, file, line);
1886 	} while (error != 0);
1887 	return (0);
1888 }
1889 
1890 int
_vn_lock(struct vnode * vp,int flags,const char * file,int line)1891 _vn_lock(struct vnode *vp, int flags, const char *file, int line)
1892 {
1893 	int error;
1894 
1895 	VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
1896 	    ("vn_lock: no locktype (%d passed)", flags));
1897 	VNPASS(vp->v_holdcnt > 0, vp);
1898 	error = VOP_LOCK1(vp, flags, file, line);
1899 	if (__predict_false(error != 0 || VN_IS_DOOMED(vp)))
1900 		return (_vn_lock_fallback(vp, flags, file, line, error));
1901 	return (0);
1902 }
1903 
1904 /*
1905  * File table vnode close routine.
1906  */
1907 static int
vn_closefile(struct file * fp,struct thread * td)1908 vn_closefile(struct file *fp, struct thread *td)
1909 {
1910 	struct vnode *vp;
1911 	struct flock lf;
1912 	int error;
1913 	bool ref;
1914 
1915 	vp = fp->f_vnode;
1916 	fp->f_ops = &badfileops;
1917 	ref = (fp->f_flag & FHASLOCK) != 0;
1918 
1919 	error = vn_close1(vp, fp->f_flag, fp->f_cred, td, ref);
1920 
1921 	if (__predict_false(ref)) {
1922 		lf.l_whence = SEEK_SET;
1923 		lf.l_start = 0;
1924 		lf.l_len = 0;
1925 		lf.l_type = F_UNLCK;
1926 		(void) VOP_ADVLOCK(vp, fp, F_UNLCK, &lf, F_FLOCK);
1927 		vrele(vp);
1928 	}
1929 	return (error);
1930 }
1931 
1932 /*
1933  * Preparing to start a filesystem write operation. If the operation is
1934  * permitted, then we bump the count of operations in progress and
1935  * proceed. If a suspend request is in progress, we wait until the
1936  * suspension is over, and then proceed.
1937  */
1938 static int
vn_start_write_refed(struct mount * mp,int flags,bool mplocked)1939 vn_start_write_refed(struct mount *mp, int flags, bool mplocked)
1940 {
1941 	struct mount_pcpu *mpcpu;
1942 	int error, mflags;
1943 
1944 	if (__predict_true(!mplocked) && (flags & V_XSLEEP) == 0 &&
1945 	    vfs_op_thread_enter(mp, mpcpu)) {
1946 		MPASS((mp->mnt_kern_flag & MNTK_SUSPEND) == 0);
1947 		vfs_mp_count_add_pcpu(mpcpu, writeopcount, 1);
1948 		vfs_op_thread_exit(mp, mpcpu);
1949 		return (0);
1950 	}
1951 
1952 	if (mplocked)
1953 		mtx_assert(MNT_MTX(mp), MA_OWNED);
1954 	else
1955 		MNT_ILOCK(mp);
1956 
1957 	error = 0;
1958 
1959 	/*
1960 	 * Check on status of suspension.
1961 	 */
1962 	if ((curthread->td_pflags & TDP_IGNSUSP) == 0 ||
1963 	    mp->mnt_susp_owner != curthread) {
1964 		mflags = 0;
1965 		if ((mp->mnt_vfc->vfc_flags & VFCF_SBDRY) != 0) {
1966 			if (flags & V_PCATCH)
1967 				mflags |= PCATCH;
1968 		}
1969 		mflags |= PRI_MAX_KERN;
1970 		while ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0) {
1971 			if ((flags & V_NOWAIT) != 0) {
1972 				error = EWOULDBLOCK;
1973 				goto unlock;
1974 			}
1975 			error = msleep(&mp->mnt_flag, MNT_MTX(mp), mflags,
1976 			    "suspfs", 0);
1977 			if (error != 0)
1978 				goto unlock;
1979 		}
1980 	}
1981 	if ((flags & V_XSLEEP) != 0)
1982 		goto unlock;
1983 	mp->mnt_writeopcount++;
1984 unlock:
1985 	if (error != 0 || (flags & V_XSLEEP) != 0)
1986 		MNT_REL(mp);
1987 	MNT_IUNLOCK(mp);
1988 	return (error);
1989 }
1990 
1991 int
vn_start_write(struct vnode * vp,struct mount ** mpp,int flags)1992 vn_start_write(struct vnode *vp, struct mount **mpp, int flags)
1993 {
1994 	struct mount *mp;
1995 	int error;
1996 
1997 	KASSERT((flags & ~V_VALID_FLAGS) == 0,
1998 	    ("%s: invalid flags passed %d\n", __func__, flags));
1999 
2000 	error = 0;
2001 	/*
2002 	 * If a vnode is provided, get and return the mount point that
2003 	 * to which it will write.
2004 	 */
2005 	if (vp != NULL) {
2006 		if ((error = VOP_GETWRITEMOUNT(vp, mpp)) != 0) {
2007 			*mpp = NULL;
2008 			if (error != EOPNOTSUPP)
2009 				return (error);
2010 			return (0);
2011 		}
2012 	}
2013 	if ((mp = *mpp) == NULL)
2014 		return (0);
2015 
2016 	/*
2017 	 * VOP_GETWRITEMOUNT() returns with the mp refcount held through
2018 	 * a vfs_ref().
2019 	 * As long as a vnode is not provided we need to acquire a
2020 	 * refcount for the provided mountpoint too, in order to
2021 	 * emulate a vfs_ref().
2022 	 */
2023 	if (vp == NULL)
2024 		vfs_ref(mp);
2025 
2026 	error = vn_start_write_refed(mp, flags, false);
2027 	if (error != 0 && (flags & V_NOWAIT) == 0)
2028 		*mpp = NULL;
2029 	return (error);
2030 }
2031 
2032 /*
2033  * Secondary suspension. Used by operations such as vop_inactive
2034  * routines that are needed by the higher level functions. These
2035  * are allowed to proceed until all the higher level functions have
2036  * completed (indicated by mnt_writeopcount dropping to zero). At that
2037  * time, these operations are halted until the suspension is over.
2038  */
2039 int
vn_start_secondary_write(struct vnode * vp,struct mount ** mpp,int flags)2040 vn_start_secondary_write(struct vnode *vp, struct mount **mpp, int flags)
2041 {
2042 	struct mount *mp;
2043 	int error, mflags;
2044 
2045 	KASSERT((flags & (~V_VALID_FLAGS | V_XSLEEP)) == 0,
2046 	    ("%s: invalid flags passed %d\n", __func__, flags));
2047 
2048  retry:
2049 	if (vp != NULL) {
2050 		if ((error = VOP_GETWRITEMOUNT(vp, mpp)) != 0) {
2051 			*mpp = NULL;
2052 			if (error != EOPNOTSUPP)
2053 				return (error);
2054 			return (0);
2055 		}
2056 	}
2057 	/*
2058 	 * If we are not suspended or have not yet reached suspended
2059 	 * mode, then let the operation proceed.
2060 	 */
2061 	if ((mp = *mpp) == NULL)
2062 		return (0);
2063 
2064 	/*
2065 	 * VOP_GETWRITEMOUNT() returns with the mp refcount held through
2066 	 * a vfs_ref().
2067 	 * As long as a vnode is not provided we need to acquire a
2068 	 * refcount for the provided mountpoint too, in order to
2069 	 * emulate a vfs_ref().
2070 	 */
2071 	MNT_ILOCK(mp);
2072 	if (vp == NULL)
2073 		MNT_REF(mp);
2074 	if ((mp->mnt_kern_flag & (MNTK_SUSPENDED | MNTK_SUSPEND2)) == 0) {
2075 		mp->mnt_secondary_writes++;
2076 		mp->mnt_secondary_accwrites++;
2077 		MNT_IUNLOCK(mp);
2078 		return (0);
2079 	}
2080 	if ((flags & V_NOWAIT) != 0) {
2081 		MNT_REL(mp);
2082 		MNT_IUNLOCK(mp);
2083 		*mpp = NULL;
2084 		return (EWOULDBLOCK);
2085 	}
2086 	/*
2087 	 * Wait for the suspension to finish.
2088 	 */
2089 	mflags = 0;
2090 	if ((mp->mnt_vfc->vfc_flags & VFCF_SBDRY) != 0) {
2091 		if ((flags & V_PCATCH) != 0)
2092 			mflags |= PCATCH;
2093 	}
2094 	mflags |= PRI_MAX_KERN | PDROP;
2095 	error = msleep(&mp->mnt_flag, MNT_MTX(mp), mflags, "suspfs", 0);
2096 	vfs_rel(mp);
2097 	if (error == 0)
2098 		goto retry;
2099 	*mpp = NULL;
2100 	return (error);
2101 }
2102 
2103 /*
2104  * Filesystem write operation has completed. If we are suspending and this
2105  * operation is the last one, notify the suspender that the suspension is
2106  * now in effect.
2107  */
2108 void
vn_finished_write(struct mount * mp)2109 vn_finished_write(struct mount *mp)
2110 {
2111 	struct mount_pcpu *mpcpu;
2112 	int c;
2113 
2114 	if (mp == NULL)
2115 		return;
2116 
2117 	if (vfs_op_thread_enter(mp, mpcpu)) {
2118 		vfs_mp_count_sub_pcpu(mpcpu, writeopcount, 1);
2119 		vfs_mp_count_sub_pcpu(mpcpu, ref, 1);
2120 		vfs_op_thread_exit(mp, mpcpu);
2121 		return;
2122 	}
2123 
2124 	MNT_ILOCK(mp);
2125 	vfs_assert_mount_counters(mp);
2126 	MNT_REL(mp);
2127 	c = --mp->mnt_writeopcount;
2128 	if (mp->mnt_vfs_ops == 0) {
2129 		MPASS((mp->mnt_kern_flag & MNTK_SUSPEND) == 0);
2130 		MNT_IUNLOCK(mp);
2131 		return;
2132 	}
2133 	if (c < 0)
2134 		vfs_dump_mount_counters(mp);
2135 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0 && c == 0)
2136 		wakeup(&mp->mnt_writeopcount);
2137 	MNT_IUNLOCK(mp);
2138 }
2139 
2140 /*
2141  * Filesystem secondary write operation has completed. If we are
2142  * suspending and this operation is the last one, notify the suspender
2143  * that the suspension is now in effect.
2144  */
2145 void
vn_finished_secondary_write(struct mount * mp)2146 vn_finished_secondary_write(struct mount *mp)
2147 {
2148 	if (mp == NULL)
2149 		return;
2150 	MNT_ILOCK(mp);
2151 	MNT_REL(mp);
2152 	mp->mnt_secondary_writes--;
2153 	if (mp->mnt_secondary_writes < 0)
2154 		panic("vn_finished_secondary_write: neg cnt");
2155 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0 &&
2156 	    mp->mnt_secondary_writes <= 0)
2157 		wakeup(&mp->mnt_secondary_writes);
2158 	MNT_IUNLOCK(mp);
2159 }
2160 
2161 /*
2162  * Request a filesystem to suspend write operations.
2163  */
2164 int
vfs_write_suspend(struct mount * mp,int flags)2165 vfs_write_suspend(struct mount *mp, int flags)
2166 {
2167 	int error;
2168 
2169 	vfs_op_enter(mp);
2170 
2171 	MNT_ILOCK(mp);
2172 	vfs_assert_mount_counters(mp);
2173 	if (mp->mnt_susp_owner == curthread) {
2174 		vfs_op_exit_locked(mp);
2175 		MNT_IUNLOCK(mp);
2176 		return (EALREADY);
2177 	}
2178 	while (mp->mnt_kern_flag & MNTK_SUSPEND)
2179 		msleep(&mp->mnt_flag, MNT_MTX(mp), PRI_MAX_KERN, "wsuspfs", 0);
2180 
2181 	/*
2182 	 * Unmount holds a write reference on the mount point.  If we
2183 	 * own busy reference and drain for writers, we deadlock with
2184 	 * the reference draining in the unmount path.  Callers of
2185 	 * vfs_write_suspend() must specify VS_SKIP_UNMOUNT if
2186 	 * vfs_busy() reference is owned and caller is not in the
2187 	 * unmount context.
2188 	 */
2189 	if ((flags & VS_SKIP_UNMOUNT) != 0 &&
2190 	    (mp->mnt_kern_flag & MNTK_UNMOUNT) != 0) {
2191 		vfs_op_exit_locked(mp);
2192 		MNT_IUNLOCK(mp);
2193 		return (EBUSY);
2194 	}
2195 
2196 	mp->mnt_kern_flag |= MNTK_SUSPEND;
2197 	mp->mnt_susp_owner = curthread;
2198 	if (mp->mnt_writeopcount > 0)
2199 		(void) msleep(&mp->mnt_writeopcount,
2200 		    MNT_MTX(mp), PRI_MAX_KERN | PDROP, "suspwt", 0);
2201 	else
2202 		MNT_IUNLOCK(mp);
2203 	if ((error = VFS_SYNC(mp, MNT_SUSPEND)) != 0) {
2204 		vfs_write_resume(mp, 0);
2205 		/* vfs_write_resume does vfs_op_exit() for us */
2206 	}
2207 	return (error);
2208 }
2209 
2210 /*
2211  * Request a filesystem to resume write operations.
2212  */
2213 void
vfs_write_resume(struct mount * mp,int flags)2214 vfs_write_resume(struct mount *mp, int flags)
2215 {
2216 
2217 	MNT_ILOCK(mp);
2218 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0) {
2219 		KASSERT(mp->mnt_susp_owner == curthread, ("mnt_susp_owner"));
2220 		mp->mnt_kern_flag &= ~(MNTK_SUSPEND | MNTK_SUSPEND2 |
2221 				       MNTK_SUSPENDED);
2222 		mp->mnt_susp_owner = NULL;
2223 		wakeup(&mp->mnt_writeopcount);
2224 		wakeup(&mp->mnt_flag);
2225 		curthread->td_pflags &= ~TDP_IGNSUSP;
2226 		if ((flags & VR_START_WRITE) != 0) {
2227 			MNT_REF(mp);
2228 			mp->mnt_writeopcount++;
2229 		}
2230 		MNT_IUNLOCK(mp);
2231 		if ((flags & VR_NO_SUSPCLR) == 0)
2232 			VFS_SUSP_CLEAN(mp);
2233 		vfs_op_exit(mp);
2234 	} else if ((flags & VR_START_WRITE) != 0) {
2235 		MNT_REF(mp);
2236 		vn_start_write_refed(mp, 0, true);
2237 	} else {
2238 		MNT_IUNLOCK(mp);
2239 	}
2240 }
2241 
2242 /*
2243  * Helper loop around vfs_write_suspend() for filesystem unmount VFS
2244  * methods.
2245  */
2246 int
vfs_write_suspend_umnt(struct mount * mp)2247 vfs_write_suspend_umnt(struct mount *mp)
2248 {
2249 	int error;
2250 
2251 	KASSERT((curthread->td_pflags & TDP_IGNSUSP) == 0,
2252 	    ("vfs_write_suspend_umnt: recursed"));
2253 
2254 	/* dounmount() already called vn_start_write(). */
2255 	for (;;) {
2256 		vn_finished_write(mp);
2257 		error = vfs_write_suspend(mp, 0);
2258 		if (error != 0) {
2259 			vn_start_write(NULL, &mp, V_WAIT);
2260 			return (error);
2261 		}
2262 		MNT_ILOCK(mp);
2263 		if ((mp->mnt_kern_flag & MNTK_SUSPENDED) != 0)
2264 			break;
2265 		MNT_IUNLOCK(mp);
2266 		vn_start_write(NULL, &mp, V_WAIT);
2267 	}
2268 	mp->mnt_kern_flag &= ~(MNTK_SUSPENDED | MNTK_SUSPEND2);
2269 	wakeup(&mp->mnt_flag);
2270 	MNT_IUNLOCK(mp);
2271 	curthread->td_pflags |= TDP_IGNSUSP;
2272 	return (0);
2273 }
2274 
2275 /*
2276  * Implement kqueues for files by translating it to vnode operation.
2277  */
2278 static int
vn_kqfilter(struct file * fp,struct knote * kn)2279 vn_kqfilter(struct file *fp, struct knote *kn)
2280 {
2281 
2282 	return (VOP_KQFILTER(fp->f_vnode, kn));
2283 }
2284 
2285 int
vn_kqfilter_opath(struct file * fp,struct knote * kn)2286 vn_kqfilter_opath(struct file *fp, struct knote *kn)
2287 {
2288 	if ((fp->f_flag & FKQALLOWED) == 0)
2289 		return (EBADF);
2290 	return (vn_kqfilter(fp, kn));
2291 }
2292 
2293 /*
2294  * Simplified in-kernel wrapper calls for extended attribute access.
2295  * Both calls pass in a NULL credential, authorizing as "kernel" access.
2296  * Set IO_NODELOCKED in ioflg if the vnode is already locked.
2297  */
2298 int
vn_extattr_get(struct vnode * vp,int ioflg,int attrnamespace,const char * attrname,int * buflen,char * buf,struct thread * td)2299 vn_extattr_get(struct vnode *vp, int ioflg, int attrnamespace,
2300     const char *attrname, int *buflen, char *buf, struct thread *td)
2301 {
2302 	struct uio	auio;
2303 	struct iovec	iov;
2304 	int	error;
2305 
2306 	iov.iov_len = *buflen;
2307 	iov.iov_base = buf;
2308 
2309 	auio.uio_iov = &iov;
2310 	auio.uio_iovcnt = 1;
2311 	auio.uio_rw = UIO_READ;
2312 	auio.uio_segflg = UIO_SYSSPACE;
2313 	auio.uio_td = td;
2314 	auio.uio_offset = 0;
2315 	auio.uio_resid = *buflen;
2316 
2317 	if ((ioflg & IO_NODELOCKED) == 0)
2318 		vn_lock(vp, LK_SHARED | LK_RETRY);
2319 
2320 	ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
2321 
2322 	/* authorize attribute retrieval as kernel */
2323 	error = VOP_GETEXTATTR(vp, attrnamespace, attrname, &auio, NULL, NULL,
2324 	    td);
2325 
2326 	if ((ioflg & IO_NODELOCKED) == 0)
2327 		VOP_UNLOCK(vp);
2328 
2329 	if (error == 0) {
2330 		*buflen = *buflen - auio.uio_resid;
2331 	}
2332 
2333 	return (error);
2334 }
2335 
2336 /*
2337  * XXX failure mode if partially written?
2338  */
2339 int
vn_extattr_set(struct vnode * vp,int ioflg,int attrnamespace,const char * attrname,int buflen,char * buf,struct thread * td)2340 vn_extattr_set(struct vnode *vp, int ioflg, int attrnamespace,
2341     const char *attrname, int buflen, char *buf, struct thread *td)
2342 {
2343 	struct uio	auio;
2344 	struct iovec	iov;
2345 	struct mount	*mp;
2346 	int	error;
2347 
2348 	iov.iov_len = buflen;
2349 	iov.iov_base = buf;
2350 
2351 	auio.uio_iov = &iov;
2352 	auio.uio_iovcnt = 1;
2353 	auio.uio_rw = UIO_WRITE;
2354 	auio.uio_segflg = UIO_SYSSPACE;
2355 	auio.uio_td = td;
2356 	auio.uio_offset = 0;
2357 	auio.uio_resid = buflen;
2358 
2359 	if ((ioflg & IO_NODELOCKED) == 0) {
2360 		if ((error = vn_start_write(vp, &mp, V_WAIT)) != 0)
2361 			return (error);
2362 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2363 	}
2364 
2365 	ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
2366 
2367 	/* authorize attribute setting as kernel */
2368 	error = VOP_SETEXTATTR(vp, attrnamespace, attrname, &auio, NULL, td);
2369 
2370 	if ((ioflg & IO_NODELOCKED) == 0) {
2371 		vn_finished_write(mp);
2372 		VOP_UNLOCK(vp);
2373 	}
2374 
2375 	return (error);
2376 }
2377 
2378 int
vn_extattr_rm(struct vnode * vp,int ioflg,int attrnamespace,const char * attrname,struct thread * td)2379 vn_extattr_rm(struct vnode *vp, int ioflg, int attrnamespace,
2380     const char *attrname, struct thread *td)
2381 {
2382 	struct mount	*mp;
2383 	int	error;
2384 
2385 	if ((ioflg & IO_NODELOCKED) == 0) {
2386 		if ((error = vn_start_write(vp, &mp, V_WAIT)) != 0)
2387 			return (error);
2388 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2389 	}
2390 
2391 	ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
2392 
2393 	/* authorize attribute removal as kernel */
2394 	error = VOP_DELETEEXTATTR(vp, attrnamespace, attrname, NULL, td);
2395 	if (error == EOPNOTSUPP)
2396 		error = VOP_SETEXTATTR(vp, attrnamespace, attrname, NULL,
2397 		    NULL, td);
2398 
2399 	if ((ioflg & IO_NODELOCKED) == 0) {
2400 		vn_finished_write(mp);
2401 		VOP_UNLOCK(vp);
2402 	}
2403 
2404 	return (error);
2405 }
2406 
2407 static int
vn_get_ino_alloc_vget(struct mount * mp,void * arg,int lkflags,struct vnode ** rvp)2408 vn_get_ino_alloc_vget(struct mount *mp, void *arg, int lkflags,
2409     struct vnode **rvp)
2410 {
2411 
2412 	return (VFS_VGET(mp, *(ino_t *)arg, lkflags, rvp));
2413 }
2414 
2415 int
vn_vget_ino(struct vnode * vp,ino_t ino,int lkflags,struct vnode ** rvp)2416 vn_vget_ino(struct vnode *vp, ino_t ino, int lkflags, struct vnode **rvp)
2417 {
2418 
2419 	return (vn_vget_ino_gen(vp, vn_get_ino_alloc_vget, &ino,
2420 	    lkflags, rvp));
2421 }
2422 
2423 int
vn_vget_ino_gen(struct vnode * vp,vn_get_ino_t alloc,void * alloc_arg,int lkflags,struct vnode ** rvp)2424 vn_vget_ino_gen(struct vnode *vp, vn_get_ino_t alloc, void *alloc_arg,
2425     int lkflags, struct vnode **rvp)
2426 {
2427 	struct mount *mp;
2428 	int ltype, error;
2429 
2430 	ASSERT_VOP_LOCKED(vp, "vn_vget_ino_get");
2431 	mp = vp->v_mount;
2432 	ltype = VOP_ISLOCKED(vp);
2433 	KASSERT(ltype == LK_EXCLUSIVE || ltype == LK_SHARED,
2434 	    ("vn_vget_ino: vp not locked"));
2435 	error = vfs_busy(mp, MBF_NOWAIT);
2436 	if (error != 0) {
2437 		vfs_ref(mp);
2438 		VOP_UNLOCK(vp);
2439 		error = vfs_busy(mp, 0);
2440 		vn_lock(vp, ltype | LK_RETRY);
2441 		vfs_rel(mp);
2442 		if (error != 0)
2443 			return (ENOENT);
2444 		if (VN_IS_DOOMED(vp)) {
2445 			vfs_unbusy(mp);
2446 			return (ENOENT);
2447 		}
2448 	}
2449 	VOP_UNLOCK(vp);
2450 	error = alloc(mp, alloc_arg, lkflags, rvp);
2451 	vfs_unbusy(mp);
2452 	if (error != 0 || *rvp != vp)
2453 		vn_lock(vp, ltype | LK_RETRY);
2454 	if (VN_IS_DOOMED(vp)) {
2455 		if (error == 0) {
2456 			if (*rvp == vp)
2457 				vunref(vp);
2458 			else
2459 				vput(*rvp);
2460 		}
2461 		error = ENOENT;
2462 	}
2463 	return (error);
2464 }
2465 
2466 static void
vn_send_sigxfsz(struct proc * p)2467 vn_send_sigxfsz(struct proc *p)
2468 {
2469 	PROC_LOCK(p);
2470 	kern_psignal(p, SIGXFSZ);
2471 	PROC_UNLOCK(p);
2472 }
2473 
2474 int
vn_rlimit_trunc(u_quad_t size,struct thread * td)2475 vn_rlimit_trunc(u_quad_t size, struct thread *td)
2476 {
2477 	if (size <= lim_cur(td, RLIMIT_FSIZE))
2478 		return (0);
2479 	vn_send_sigxfsz(td->td_proc);
2480 	return (EFBIG);
2481 }
2482 
2483 static int
vn_rlimit_fsizex1(const struct vnode * vp,struct uio * uio,off_t maxfsz,bool adj,struct thread * td)2484 vn_rlimit_fsizex1(const struct vnode *vp, struct uio *uio, off_t maxfsz,
2485     bool adj, struct thread *td)
2486 {
2487 	off_t lim;
2488 	bool ktr_write;
2489 
2490 	if (vp->v_type != VREG)
2491 		return (0);
2492 
2493 	/*
2494 	 * Handle file system maximum file size.
2495 	 */
2496 	if (maxfsz != 0 && uio->uio_offset + uio->uio_resid > maxfsz) {
2497 		if (!adj || uio->uio_offset >= maxfsz)
2498 			return (EFBIG);
2499 		uio->uio_resid = maxfsz - uio->uio_offset;
2500 	}
2501 
2502 	/*
2503 	 * This is kernel write (e.g. vnode_pager) or accounting
2504 	 * write, ignore limit.
2505 	 */
2506 	if (td == NULL || (td->td_pflags2 & TDP2_ACCT) != 0)
2507 		return (0);
2508 
2509 	/*
2510 	 * Calculate file size limit.
2511 	 */
2512 	ktr_write = (td->td_pflags & TDP_INKTRACE) != 0;
2513 	lim = __predict_false(ktr_write) ? td->td_ktr_io_lim :
2514 	    lim_cur(td, RLIMIT_FSIZE);
2515 
2516 	/*
2517 	 * Is the limit reached?
2518 	 */
2519 	if (__predict_true((uoff_t)uio->uio_offset + uio->uio_resid <= lim))
2520 		return (0);
2521 
2522 	/*
2523 	 * Prepared filesystems can handle writes truncated to the
2524 	 * file size limit.
2525 	 */
2526 	if (adj && (uoff_t)uio->uio_offset < lim) {
2527 		uio->uio_resid = lim - (uoff_t)uio->uio_offset;
2528 		return (0);
2529 	}
2530 
2531 	if (!ktr_write || ktr_filesize_limit_signal)
2532 		vn_send_sigxfsz(td->td_proc);
2533 	return (EFBIG);
2534 }
2535 
2536 /*
2537  * Helper for VOP_WRITE() implementations, the common code to
2538  * handle maximum supported file size on the filesystem, and
2539  * RLIMIT_FSIZE, except for special writes from accounting subsystem
2540  * and ktrace.
2541  *
2542  * For maximum file size (maxfsz argument):
2543  * - return EFBIG if uio_offset is beyond it
2544  * - otherwise, clamp uio_resid if write would extend file beyond maxfsz.
2545  *
2546  * For RLIMIT_FSIZE:
2547  * - return EFBIG and send SIGXFSZ if uio_offset is beyond the limit
2548  * - otherwise, clamp uio_resid if write would extend file beyond limit.
2549  *
2550  * If clamping occured, the adjustment for uio_resid is stored in
2551  * *resid_adj, to be re-applied by vn_rlimit_fsizex_res() on return
2552  * from the VOP.
2553  */
2554 int
vn_rlimit_fsizex(const struct vnode * vp,struct uio * uio,off_t maxfsz,ssize_t * resid_adj,struct thread * td)2555 vn_rlimit_fsizex(const struct vnode *vp, struct uio *uio, off_t maxfsz,
2556     ssize_t *resid_adj, struct thread *td)
2557 {
2558 	ssize_t resid_orig;
2559 	int error;
2560 	bool adj;
2561 
2562 	resid_orig = uio->uio_resid;
2563 	adj = resid_adj != NULL;
2564 	error = vn_rlimit_fsizex1(vp, uio, maxfsz, adj, td);
2565 	if (adj)
2566 		*resid_adj = resid_orig - uio->uio_resid;
2567 	return (error);
2568 }
2569 
2570 void
vn_rlimit_fsizex_res(struct uio * uio,ssize_t resid_adj)2571 vn_rlimit_fsizex_res(struct uio *uio, ssize_t resid_adj)
2572 {
2573 	uio->uio_resid += resid_adj;
2574 }
2575 
2576 int
vn_rlimit_fsize(const struct vnode * vp,const struct uio * uio,struct thread * td)2577 vn_rlimit_fsize(const struct vnode *vp, const struct uio *uio,
2578     struct thread *td)
2579 {
2580 	return (vn_rlimit_fsizex(vp, __DECONST(struct uio *, uio), 0, NULL,
2581 	    td));
2582 }
2583 
2584 int
vn_chmod(struct file * fp,mode_t mode,struct ucred * active_cred,struct thread * td)2585 vn_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
2586     struct thread *td)
2587 {
2588 	struct vnode *vp;
2589 
2590 	vp = fp->f_vnode;
2591 #ifdef AUDIT
2592 	vn_lock(vp, LK_SHARED | LK_RETRY);
2593 	AUDIT_ARG_VNODE1(vp);
2594 	VOP_UNLOCK(vp);
2595 #endif
2596 	return (setfmode(td, active_cred, vp, mode));
2597 }
2598 
2599 int
vn_chown(struct file * fp,uid_t uid,gid_t gid,struct ucred * active_cred,struct thread * td)2600 vn_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
2601     struct thread *td)
2602 {
2603 	struct vnode *vp;
2604 
2605 	vp = fp->f_vnode;
2606 #ifdef AUDIT
2607 	vn_lock(vp, LK_SHARED | LK_RETRY);
2608 	AUDIT_ARG_VNODE1(vp);
2609 	VOP_UNLOCK(vp);
2610 #endif
2611 	return (setfown(td, active_cred, vp, uid, gid));
2612 }
2613 
2614 /*
2615  * Remove pages in the range ["start", "end") from the vnode's VM object.  If
2616  * "end" is 0, then the range extends to the end of the object.
2617  */
2618 void
vn_pages_remove(struct vnode * vp,vm_pindex_t start,vm_pindex_t end)2619 vn_pages_remove(struct vnode *vp, vm_pindex_t start, vm_pindex_t end)
2620 {
2621 	vm_object_t object;
2622 
2623 	if ((object = vp->v_object) == NULL)
2624 		return;
2625 	VM_OBJECT_WLOCK(object);
2626 	vm_object_page_remove(object, start, end, 0);
2627 	VM_OBJECT_WUNLOCK(object);
2628 }
2629 
2630 /*
2631  * Like vn_pages_remove(), but skips invalid pages, which by definition are not
2632  * mapped into any process' address space.  Filesystems may use this in
2633  * preference to vn_pages_remove() to avoid blocking on pages busied in
2634  * preparation for a VOP_GETPAGES.
2635  */
2636 void
vn_pages_remove_valid(struct vnode * vp,vm_pindex_t start,vm_pindex_t end)2637 vn_pages_remove_valid(struct vnode *vp, vm_pindex_t start, vm_pindex_t end)
2638 {
2639 	vm_object_t object;
2640 
2641 	if ((object = vp->v_object) == NULL)
2642 		return;
2643 	VM_OBJECT_WLOCK(object);
2644 	vm_object_page_remove(object, start, end, OBJPR_VALIDONLY);
2645 	VM_OBJECT_WUNLOCK(object);
2646 }
2647 
2648 int
vn_bmap_seekhole_locked(struct vnode * vp,u_long cmd,off_t * off,struct ucred * cred)2649 vn_bmap_seekhole_locked(struct vnode *vp, u_long cmd, off_t *off,
2650     struct ucred *cred)
2651 {
2652 	off_t size;
2653 	daddr_t bn, bnp;
2654 	uint64_t bsize;
2655 	off_t noff;
2656 	int error;
2657 
2658 	KASSERT(cmd == FIOSEEKHOLE || cmd == FIOSEEKDATA,
2659 	    ("%s: Wrong command %lu", __func__, cmd));
2660 	ASSERT_VOP_ELOCKED(vp, "vn_bmap_seekhole_locked");
2661 
2662 	if (vp->v_type != VREG) {
2663 		error = ENOTTY;
2664 		goto out;
2665 	}
2666 	error = vn_getsize_locked(vp, &size, cred);
2667 	if (error != 0)
2668 		goto out;
2669 	noff = *off;
2670 	if (noff < 0 || noff >= size) {
2671 		error = ENXIO;
2672 		goto out;
2673 	}
2674 
2675 	/* See the comment in ufs_bmap_seekdata(). */
2676 	vnode_pager_clean_sync(vp);
2677 
2678 	bsize = vp->v_mount->mnt_stat.f_iosize;
2679 	for (bn = noff / bsize; noff < size; bn++, noff += bsize -
2680 	    noff % bsize) {
2681 		error = VOP_BMAP(vp, bn, NULL, &bnp, NULL, NULL);
2682 		if (error == EOPNOTSUPP) {
2683 			error = ENOTTY;
2684 			goto out;
2685 		}
2686 		if ((bnp == -1 && cmd == FIOSEEKHOLE) ||
2687 		    (bnp != -1 && cmd == FIOSEEKDATA)) {
2688 			noff = bn * bsize;
2689 			if (noff < *off)
2690 				noff = *off;
2691 			goto out;
2692 		}
2693 	}
2694 	if (noff > size)
2695 		noff = size;
2696 	/* noff == size. There is an implicit hole at the end of file. */
2697 	if (cmd == FIOSEEKDATA)
2698 		error = ENXIO;
2699 out:
2700 	if (error == 0)
2701 		*off = noff;
2702 	return (error);
2703 }
2704 
2705 int
vn_bmap_seekhole(struct vnode * vp,u_long cmd,off_t * off,struct ucred * cred)2706 vn_bmap_seekhole(struct vnode *vp, u_long cmd, off_t *off, struct ucred *cred)
2707 {
2708 	int error;
2709 
2710 	KASSERT(cmd == FIOSEEKHOLE || cmd == FIOSEEKDATA,
2711 	    ("%s: Wrong command %lu", __func__, cmd));
2712 
2713 	if (vn_lock(vp, LK_EXCLUSIVE) != 0)
2714 		return (EBADF);
2715 	error = vn_bmap_seekhole_locked(vp, cmd, off, cred);
2716 	VOP_UNLOCK(vp);
2717 	return (error);
2718 }
2719 
2720 int
vn_seek(struct file * fp,off_t offset,int whence,struct thread * td)2721 vn_seek(struct file *fp, off_t offset, int whence, struct thread *td)
2722 {
2723 	struct ucred *cred;
2724 	struct vnode *vp;
2725 	off_t foffset, fsize, size;
2726 	int error, noneg;
2727 
2728 	cred = td->td_ucred;
2729 	vp = fp->f_vnode;
2730 	noneg = (vp->v_type != VCHR);
2731 	/*
2732 	 * Try to dodge locking for common case of querying the offset.
2733 	 */
2734 	if (whence == L_INCR && offset == 0) {
2735 		foffset = foffset_read(fp);
2736 		if (__predict_false(foffset < 0 && noneg)) {
2737 			return (EOVERFLOW);
2738 		}
2739 		td->td_uretoff.tdu_off = foffset;
2740 		return (0);
2741 	}
2742 	foffset = foffset_lock(fp, 0);
2743 	error = 0;
2744 	switch (whence) {
2745 	case L_INCR:
2746 		if (noneg &&
2747 		    (foffset < 0 ||
2748 		    (offset > 0 && foffset > OFF_MAX - offset))) {
2749 			error = EOVERFLOW;
2750 			break;
2751 		}
2752 		offset += foffset;
2753 		break;
2754 	case L_XTND:
2755 		error = vn_getsize(vp, &fsize, cred);
2756 		if (error != 0)
2757 			break;
2758 
2759 		/*
2760 		 * If the file references a disk device, then fetch
2761 		 * the media size and use that to determine the ending
2762 		 * offset.
2763 		 */
2764 		if (fsize == 0 && vp->v_type == VCHR &&
2765 		    fo_ioctl(fp, DIOCGMEDIASIZE, &size, cred, td) == 0)
2766 			fsize = size;
2767 		if (noneg && offset > 0 && fsize > OFF_MAX - offset) {
2768 			error = EOVERFLOW;
2769 			break;
2770 		}
2771 		offset += fsize;
2772 		break;
2773 	case L_SET:
2774 		break;
2775 	case SEEK_DATA:
2776 		error = fo_ioctl(fp, FIOSEEKDATA, &offset, cred, td);
2777 		if (error == ENOTTY)
2778 			error = EINVAL;
2779 		break;
2780 	case SEEK_HOLE:
2781 		error = fo_ioctl(fp, FIOSEEKHOLE, &offset, cred, td);
2782 		if (error == ENOTTY)
2783 			error = EINVAL;
2784 		break;
2785 	default:
2786 		error = EINVAL;
2787 	}
2788 	if (error == 0 && noneg && offset < 0)
2789 		error = EINVAL;
2790 	if (error != 0)
2791 		goto drop;
2792 	VFS_KNOTE_UNLOCKED(vp, 0);
2793 	td->td_uretoff.tdu_off = offset;
2794 drop:
2795 	foffset_unlock(fp, offset, error != 0 ? FOF_NOUPDATE : 0);
2796 	return (error);
2797 }
2798 
2799 int
vn_utimes_perm(struct vnode * vp,struct vattr * vap,struct ucred * cred,struct thread * td)2800 vn_utimes_perm(struct vnode *vp, struct vattr *vap, struct ucred *cred,
2801     struct thread *td)
2802 {
2803 	int error;
2804 
2805 	/*
2806 	 * Grant permission if the caller is the owner of the file, or
2807 	 * the super-user, or has ACL_WRITE_ATTRIBUTES permission on
2808 	 * on the file.  If the time pointer is null, then write
2809 	 * permission on the file is also sufficient.
2810 	 *
2811 	 * From NFSv4.1, draft 21, 6.2.1.3.1, Discussion of Mask Attributes:
2812 	 * A user having ACL_WRITE_DATA or ACL_WRITE_ATTRIBUTES
2813 	 * will be allowed to set the times [..] to the current
2814 	 * server time.
2815 	 */
2816 	error = VOP_ACCESSX(vp, VWRITE_ATTRIBUTES, cred, td);
2817 	if (error != 0 && (vap->va_vaflags & VA_UTIMES_NULL) != 0)
2818 		error = VOP_ACCESS(vp, VWRITE, cred, td);
2819 	return (error);
2820 }
2821 
2822 int
vn_fill_kinfo(struct file * fp,struct kinfo_file * kif,struct filedesc * fdp)2823 vn_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
2824 {
2825 	struct vnode *vp;
2826 	int error;
2827 
2828 	if (fp->f_type == DTYPE_FIFO)
2829 		kif->kf_type = KF_TYPE_FIFO;
2830 	else
2831 		kif->kf_type = KF_TYPE_VNODE;
2832 	vp = fp->f_vnode;
2833 	vref(vp);
2834 	FILEDESC_SUNLOCK(fdp);
2835 	error = vn_fill_kinfo_vnode(vp, kif);
2836 	vrele(vp);
2837 	FILEDESC_SLOCK(fdp);
2838 	return (error);
2839 }
2840 
2841 static inline void
vn_fill_junk(struct kinfo_file * kif)2842 vn_fill_junk(struct kinfo_file *kif)
2843 {
2844 	size_t len, olen;
2845 
2846 	/*
2847 	 * Simulate vn_fullpath returning changing values for a given
2848 	 * vp during e.g. coredump.
2849 	 */
2850 	len = (arc4random() % (sizeof(kif->kf_path) - 2)) + 1;
2851 	olen = strlen(kif->kf_path);
2852 	if (len < olen)
2853 		strcpy(&kif->kf_path[len - 1], "$");
2854 	else
2855 		for (; olen < len; olen++)
2856 			strcpy(&kif->kf_path[olen], "A");
2857 }
2858 
2859 int
vn_fill_kinfo_vnode(struct vnode * vp,struct kinfo_file * kif)2860 vn_fill_kinfo_vnode(struct vnode *vp, struct kinfo_file *kif)
2861 {
2862 	struct vattr va;
2863 	char *fullpath, *freepath;
2864 	int error;
2865 
2866 	kif->kf_un.kf_file.kf_file_type = vntype_to_kinfo(vp->v_type);
2867 	freepath = NULL;
2868 	fullpath = "-";
2869 	error = vn_fullpath(vp, &fullpath, &freepath);
2870 	if (error == 0) {
2871 		strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2872 	}
2873 	if (freepath != NULL)
2874 		free(freepath, M_TEMP);
2875 
2876 	KFAIL_POINT_CODE(DEBUG_FP, fill_kinfo_vnode__random_path,
2877 		vn_fill_junk(kif);
2878 	);
2879 
2880 	/*
2881 	 * Retrieve vnode attributes.
2882 	 */
2883 	va.va_fsid = VNOVAL;
2884 	va.va_rdev = NODEV;
2885 	vn_lock(vp, LK_SHARED | LK_RETRY);
2886 	error = VOP_GETATTR(vp, &va, curthread->td_ucred);
2887 	VOP_UNLOCK(vp);
2888 	if (error != 0)
2889 		return (error);
2890 	if (va.va_fsid != VNOVAL)
2891 		kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
2892 	else
2893 		kif->kf_un.kf_file.kf_file_fsid =
2894 		    vp->v_mount->mnt_stat.f_fsid.val[0];
2895 	kif->kf_un.kf_file.kf_file_fsid_freebsd11 =
2896 	    kif->kf_un.kf_file.kf_file_fsid; /* truncate */
2897 	kif->kf_un.kf_file.kf_file_fileid = va.va_fileid;
2898 	kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode);
2899 	kif->kf_un.kf_file.kf_file_size = va.va_size;
2900 	kif->kf_un.kf_file.kf_file_rdev = va.va_rdev;
2901 	kif->kf_un.kf_file.kf_file_rdev_freebsd11 =
2902 	    kif->kf_un.kf_file.kf_file_rdev; /* truncate */
2903 	kif->kf_un.kf_file.kf_file_nlink = va.va_nlink;
2904 	return (0);
2905 }
2906 
2907 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)2908 vn_mmap(struct file *fp, vm_map_t map, vm_offset_t *addr, vm_size_t size,
2909     vm_prot_t prot, vm_prot_t cap_maxprot, int flags, vm_ooffset_t foff,
2910     struct thread *td)
2911 {
2912 #ifdef HWPMC_HOOKS
2913 	struct pmckern_map_in pkm;
2914 #endif
2915 	struct mount *mp;
2916 	struct vnode *vp;
2917 	vm_object_t object;
2918 	vm_prot_t maxprot;
2919 	boolean_t writecounted;
2920 	int error;
2921 
2922 #if defined(COMPAT_FREEBSD7) || defined(COMPAT_FREEBSD6) || \
2923     defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4)
2924 	/*
2925 	 * POSIX shared-memory objects are defined to have
2926 	 * kernel persistence, and are not defined to support
2927 	 * read(2)/write(2) -- or even open(2).  Thus, we can
2928 	 * use MAP_ASYNC to trade on-disk coherence for speed.
2929 	 * The shm_open(3) library routine turns on the FPOSIXSHM
2930 	 * flag to request this behavior.
2931 	 */
2932 	if ((fp->f_flag & FPOSIXSHM) != 0)
2933 		flags |= MAP_NOSYNC;
2934 #endif
2935 	vp = fp->f_vnode;
2936 
2937 	/*
2938 	 * Ensure that file and memory protections are
2939 	 * compatible.  Note that we only worry about
2940 	 * writability if mapping is shared; in this case,
2941 	 * current and max prot are dictated by the open file.
2942 	 * XXX use the vnode instead?  Problem is: what
2943 	 * credentials do we use for determination? What if
2944 	 * proc does a setuid?
2945 	 */
2946 	mp = vp->v_mount;
2947 	if (mp != NULL && (mp->mnt_flag & MNT_NOEXEC) != 0) {
2948 		maxprot = VM_PROT_NONE;
2949 		if ((prot & VM_PROT_EXECUTE) != 0)
2950 			return (EACCES);
2951 	} else
2952 		maxprot = VM_PROT_EXECUTE;
2953 	if ((fp->f_flag & FREAD) != 0)
2954 		maxprot |= VM_PROT_READ;
2955 	else if ((prot & VM_PROT_READ) != 0)
2956 		return (EACCES);
2957 
2958 	/*
2959 	 * If we are sharing potential changes via MAP_SHARED and we
2960 	 * are trying to get write permission although we opened it
2961 	 * without asking for it, bail out.
2962 	 */
2963 	if ((flags & MAP_SHARED) != 0) {
2964 		if ((fp->f_flag & FWRITE) != 0)
2965 			maxprot |= VM_PROT_WRITE;
2966 		else if ((prot & VM_PROT_WRITE) != 0)
2967 			return (EACCES);
2968 	} else {
2969 		maxprot |= VM_PROT_WRITE;
2970 		cap_maxprot |= VM_PROT_WRITE;
2971 	}
2972 	maxprot &= cap_maxprot;
2973 
2974 	/*
2975 	 * For regular files and shared memory, POSIX requires that
2976 	 * the value of foff be a legitimate offset within the data
2977 	 * object.  In particular, negative offsets are invalid.
2978 	 * Blocking negative offsets and overflows here avoids
2979 	 * possible wraparound or user-level access into reserved
2980 	 * ranges of the data object later.  In contrast, POSIX does
2981 	 * not dictate how offsets are used by device drivers, so in
2982 	 * the case of a device mapping a negative offset is passed
2983 	 * on.
2984 	 */
2985 	if (
2986 #ifdef _LP64
2987 	    size > OFF_MAX ||
2988 #endif
2989 	    foff > OFF_MAX - size)
2990 		return (EINVAL);
2991 
2992 	writecounted = FALSE;
2993 	error = vm_mmap_vnode(td, size, prot, &maxprot, &flags, vp,
2994 	    &foff, &object, &writecounted);
2995 	if (error != 0)
2996 		return (error);
2997 	error = vm_mmap_object(map, addr, size, prot, maxprot, flags, object,
2998 	    foff, writecounted, td);
2999 	if (error != 0) {
3000 		/*
3001 		 * If this mapping was accounted for in the vnode's
3002 		 * writecount, then undo that now.
3003 		 */
3004 		if (writecounted)
3005 			vm_pager_release_writecount(object, 0, size);
3006 		vm_object_deallocate(object);
3007 	}
3008 #ifdef HWPMC_HOOKS
3009 	/* Inform hwpmc(4) if an executable is being mapped. */
3010 	if (PMC_HOOK_INSTALLED(PMC_FN_MMAP)) {
3011 		if ((prot & VM_PROT_EXECUTE) != 0 && error == 0) {
3012 			pkm.pm_file = vp;
3013 			pkm.pm_address = (uintptr_t) *addr;
3014 			PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_MMAP, (void *) &pkm);
3015 		}
3016 	}
3017 #endif
3018 
3019 #ifdef HWT_HOOKS
3020 	if (HWT_HOOK_INSTALLED && (prot & VM_PROT_EXECUTE) != 0 &&
3021 	    error == 0) {
3022 		struct hwt_record_entry ent;
3023 		char *fullpath;
3024 		char *freepath;
3025 
3026 		if (vn_fullpath(vp, &fullpath, &freepath) == 0) {
3027 			ent.fullpath = fullpath;
3028 			ent.addr = (uintptr_t) *addr;
3029 			ent.record_type = HWT_RECORD_MMAP;
3030 			HWT_CALL_HOOK(td, HWT_MMAP, &ent);
3031 			free(freepath, M_TEMP);
3032 		}
3033 	}
3034 #endif
3035 
3036 	return (error);
3037 }
3038 
3039 void
vn_fsid(struct vnode * vp,struct vattr * va)3040 vn_fsid(struct vnode *vp, struct vattr *va)
3041 {
3042 	fsid_t *f;
3043 
3044 	f = &vp->v_mount->mnt_stat.f_fsid;
3045 	va->va_fsid = (uint32_t)f->val[1];
3046 	va->va_fsid <<= sizeof(f->val[1]) * NBBY;
3047 	va->va_fsid += (uint32_t)f->val[0];
3048 }
3049 
3050 int
vn_fsync_buf(struct vnode * vp,int waitfor)3051 vn_fsync_buf(struct vnode *vp, int waitfor)
3052 {
3053 	struct buf *bp, *nbp;
3054 	struct bufobj *bo;
3055 	struct mount *mp;
3056 	int error, maxretry;
3057 
3058 	error = 0;
3059 	maxretry = 10000;     /* large, arbitrarily chosen */
3060 	mp = NULL;
3061 	if (vp->v_type == VCHR) {
3062 		VI_LOCK(vp);
3063 		mp = vp->v_rdev->si_mountpt;
3064 		VI_UNLOCK(vp);
3065 	}
3066 	bo = &vp->v_bufobj;
3067 	BO_LOCK(bo);
3068 loop1:
3069 	/*
3070 	 * MARK/SCAN initialization to avoid infinite loops.
3071 	 */
3072         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
3073 		bp->b_vflags &= ~BV_SCANNED;
3074 		bp->b_error = 0;
3075 	}
3076 
3077 	/*
3078 	 * Flush all dirty buffers associated with a vnode.
3079 	 */
3080 loop2:
3081 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
3082 		if ((bp->b_vflags & BV_SCANNED) != 0)
3083 			continue;
3084 		bp->b_vflags |= BV_SCANNED;
3085 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL)) {
3086 			if (waitfor != MNT_WAIT)
3087 				continue;
3088 			if (BUF_LOCK(bp,
3089 			    LK_EXCLUSIVE | LK_INTERLOCK | LK_SLEEPFAIL,
3090 			    BO_LOCKPTR(bo)) != 0) {
3091 				BO_LOCK(bo);
3092 				goto loop1;
3093 			}
3094 			BO_LOCK(bo);
3095 		}
3096 		BO_UNLOCK(bo);
3097 		KASSERT(bp->b_bufobj == bo,
3098 		    ("bp %p wrong b_bufobj %p should be %p",
3099 		    bp, bp->b_bufobj, bo));
3100 		if ((bp->b_flags & B_DELWRI) == 0)
3101 			panic("fsync: not dirty");
3102 		if ((vp->v_object != NULL) && (bp->b_flags & B_CLUSTEROK)) {
3103 			vfs_bio_awrite(bp);
3104 		} else {
3105 			bremfree(bp);
3106 			bawrite(bp);
3107 		}
3108 		if (maxretry < 1000)
3109 			pause("dirty", hz < 1000 ? 1 : hz / 1000);
3110 		BO_LOCK(bo);
3111 		goto loop2;
3112 	}
3113 
3114 	/*
3115 	 * If synchronous the caller expects us to completely resolve all
3116 	 * dirty buffers in the system.  Wait for in-progress I/O to
3117 	 * complete (which could include background bitmap writes), then
3118 	 * retry if dirty blocks still exist.
3119 	 */
3120 	if (waitfor == MNT_WAIT) {
3121 		bufobj_wwait(bo, 0, 0);
3122 		if (bo->bo_dirty.bv_cnt > 0) {
3123 			/*
3124 			 * If we are unable to write any of these buffers
3125 			 * then we fail now rather than trying endlessly
3126 			 * to write them out.
3127 			 */
3128 			TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
3129 				if ((error = bp->b_error) != 0)
3130 					break;
3131 			if ((mp != NULL && mp->mnt_secondary_writes > 0) ||
3132 			    (error == 0 && --maxretry >= 0))
3133 				goto loop1;
3134 			if (error == 0)
3135 				error = EAGAIN;
3136 		}
3137 	}
3138 	BO_UNLOCK(bo);
3139 	if (error != 0)
3140 		vn_printf(vp, "fsync: giving up on dirty (error = %d) ", error);
3141 
3142 	return (error);
3143 }
3144 
3145 /*
3146  * Copies a byte range from invp to outvp.  Calls VOP_COPY_FILE_RANGE()
3147  * or vn_generic_copy_file_range() after rangelocking the byte ranges,
3148  * to do the actual copy.
3149  * vn_generic_copy_file_range() is factored out, so it can be called
3150  * from a VOP_COPY_FILE_RANGE() call as well, but handles vnodes from
3151  * different file systems.
3152  */
3153 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)3154 vn_copy_file_range(struct vnode *invp, off_t *inoffp, struct vnode *outvp,
3155     off_t *outoffp, size_t *lenp, unsigned int flags, struct ucred *incred,
3156     struct ucred *outcred, struct thread *fsize_td)
3157 {
3158 	struct mount *inmp, *outmp;
3159 	struct vnode *invpl, *outvpl;
3160 	int error;
3161 	size_t len;
3162 	uint64_t uval;
3163 
3164 	invpl = outvpl = NULL;
3165 	len = *lenp;
3166 	*lenp = 0;		/* For error returns. */
3167 	error = 0;
3168 
3169 	/* Do some sanity checks on the arguments. */
3170 	if (invp->v_type == VDIR || outvp->v_type == VDIR)
3171 		error = EISDIR;
3172 	else if (*inoffp < 0 || *outoffp < 0 ||
3173 	    invp->v_type != VREG || outvp->v_type != VREG)
3174 		error = EINVAL;
3175 	if (error != 0)
3176 		goto out;
3177 
3178 	/* Ensure offset + len does not wrap around. */
3179 	uval = *inoffp;
3180 	uval += len;
3181 	if (uval > INT64_MAX)
3182 		len = INT64_MAX - *inoffp;
3183 	uval = *outoffp;
3184 	uval += len;
3185 	if (uval > INT64_MAX)
3186 		len = INT64_MAX - *outoffp;
3187 	if (len == 0)
3188 		goto out;
3189 
3190 	error = VOP_GETLOWVNODE(invp, &invpl, FREAD);
3191 	if (error != 0)
3192 		goto out;
3193 	error = VOP_GETLOWVNODE(outvp, &outvpl, FWRITE);
3194 	if (error != 0)
3195 		goto out1;
3196 
3197 	inmp = invpl->v_mount;
3198 	outmp = outvpl->v_mount;
3199 	if (inmp == NULL || outmp == NULL)
3200 		goto out2;
3201 
3202 	for (;;) {
3203 		error = vfs_busy(inmp, 0);
3204 		if (error != 0)
3205 			goto out2;
3206 		if (inmp == outmp)
3207 			break;
3208 		error = vfs_busy(outmp, MBF_NOWAIT);
3209 		if (error != 0) {
3210 			vfs_unbusy(inmp);
3211 			error = vfs_busy(outmp, 0);
3212 			if (error == 0) {
3213 				vfs_unbusy(outmp);
3214 				continue;
3215 			}
3216 			goto out2;
3217 		}
3218 		break;
3219 	}
3220 
3221 	/*
3222 	 * If the two vnodes are for the same file system type, call
3223 	 * VOP_COPY_FILE_RANGE(), otherwise call vn_generic_copy_file_range()
3224 	 * which can handle copies across multiple file system types.
3225 	 */
3226 	*lenp = len;
3227 	if (inmp == outmp || inmp->mnt_vfc == outmp->mnt_vfc)
3228 		error = VOP_COPY_FILE_RANGE(invpl, inoffp, outvpl, outoffp,
3229 		    lenp, flags, incred, outcred, fsize_td);
3230 	else
3231 		error = ENOSYS;
3232 	if (error == ENOSYS)
3233 		error = vn_generic_copy_file_range(invpl, inoffp, outvpl,
3234 		    outoffp, lenp, flags, incred, outcred, fsize_td);
3235 	vfs_unbusy(outmp);
3236 	if (inmp != outmp)
3237 		vfs_unbusy(inmp);
3238 out2:
3239 	if (outvpl != NULL)
3240 		vrele(outvpl);
3241 out1:
3242 	if (invpl != NULL)
3243 		vrele(invpl);
3244 out:
3245 	return (error);
3246 }
3247 
3248 /*
3249  * Test len bytes of data starting at dat for all bytes == 0.
3250  * Return true if all bytes are zero, false otherwise.
3251  * Expects dat to be well aligned.
3252  */
3253 static bool
mem_iszero(void * dat,int len)3254 mem_iszero(void *dat, int len)
3255 {
3256 	int i;
3257 	const u_int *p;
3258 	const char *cp;
3259 
3260 	for (p = dat; len > 0; len -= sizeof(*p), p++) {
3261 		if (len >= sizeof(*p)) {
3262 			if (*p != 0)
3263 				return (false);
3264 		} else {
3265 			cp = (const char *)p;
3266 			for (i = 0; i < len; i++, cp++)
3267 				if (*cp != '\0')
3268 					return (false);
3269 		}
3270 	}
3271 	return (true);
3272 }
3273 
3274 /*
3275  * Look for a hole in the output file and, if found, adjust *outoffp
3276  * and *xferp to skip past the hole.
3277  * *xferp is the entire hole length to be written and xfer2 is how many bytes
3278  * to be written as 0's upon return.
3279  */
3280 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)3281 vn_skip_hole(struct vnode *outvp, off_t xfer2, off_t *outoffp, off_t *xferp,
3282     off_t *dataoffp, off_t *holeoffp, struct ucred *cred)
3283 {
3284 	int error;
3285 	off_t delta;
3286 
3287 	if (*holeoffp == 0 || *holeoffp <= *outoffp) {
3288 		*dataoffp = *outoffp;
3289 		error = VOP_IOCTL(outvp, FIOSEEKDATA, dataoffp, 0, cred,
3290 		    curthread);
3291 		if (error == 0) {
3292 			*holeoffp = *dataoffp;
3293 			error = VOP_IOCTL(outvp, FIOSEEKHOLE, holeoffp, 0, cred,
3294 			    curthread);
3295 		}
3296 		if (error != 0 || *holeoffp == *dataoffp) {
3297 			/*
3298 			 * Since outvp is unlocked, it may be possible for
3299 			 * another thread to do a truncate(), lseek(), write()
3300 			 * creating a hole at startoff between the above
3301 			 * VOP_IOCTL() calls, if the other thread does not do
3302 			 * rangelocking.
3303 			 * If that happens, *holeoffp == *dataoffp and finding
3304 			 * the hole has failed, so disable vn_skip_hole().
3305 			 */
3306 			*holeoffp = -1;	/* Disable use of vn_skip_hole(). */
3307 			return (xfer2);
3308 		}
3309 		KASSERT(*dataoffp >= *outoffp,
3310 		    ("vn_skip_hole: dataoff=%jd < outoff=%jd",
3311 		    (intmax_t)*dataoffp, (intmax_t)*outoffp));
3312 		KASSERT(*holeoffp > *dataoffp,
3313 		    ("vn_skip_hole: holeoff=%jd <= dataoff=%jd",
3314 		    (intmax_t)*holeoffp, (intmax_t)*dataoffp));
3315 	}
3316 
3317 	/*
3318 	 * If there is a hole before the data starts, advance *outoffp and
3319 	 * *xferp past the hole.
3320 	 */
3321 	if (*dataoffp > *outoffp) {
3322 		delta = *dataoffp - *outoffp;
3323 		if (delta >= *xferp) {
3324 			/* Entire *xferp is a hole. */
3325 			*outoffp += *xferp;
3326 			*xferp = 0;
3327 			return (0);
3328 		}
3329 		*xferp -= delta;
3330 		*outoffp += delta;
3331 		xfer2 = MIN(xfer2, *xferp);
3332 	}
3333 
3334 	/*
3335 	 * If a hole starts before the end of this xfer2, reduce this xfer2 so
3336 	 * that the write ends at the start of the hole.
3337 	 * *holeoffp should always be greater than *outoffp, but for the
3338 	 * non-INVARIANTS case, check this to make sure xfer2 remains a sane
3339 	 * value.
3340 	 */
3341 	if (*holeoffp > *outoffp && *holeoffp < *outoffp + xfer2)
3342 		xfer2 = *holeoffp - *outoffp;
3343 	return (xfer2);
3344 }
3345 
3346 /*
3347  * Write an xfer sized chunk to outvp in blksize blocks from dat.
3348  * dat is a maximum of blksize in length and can be written repeatedly in
3349  * the chunk.
3350  * If growfile == true, just grow the file via vn_truncate_locked() instead
3351  * of doing actual writes.
3352  * If checkhole == true, a hole is being punched, so skip over any hole
3353  * already in the output file.
3354  */
3355 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)3356 vn_write_outvp(struct vnode *outvp, char *dat, off_t outoff, off_t xfer,
3357     u_long blksize, bool growfile, bool checkhole, struct ucred *cred)
3358 {
3359 	struct mount *mp;
3360 	off_t dataoff, holeoff, xfer2;
3361 	int error;
3362 
3363 	/*
3364 	 * Loop around doing writes of blksize until write has been completed.
3365 	 * Lock/unlock on each loop iteration so that a bwillwrite() can be
3366 	 * done for each iteration, since the xfer argument can be very
3367 	 * large if there is a large hole to punch in the output file.
3368 	 */
3369 	error = 0;
3370 	holeoff = 0;
3371 	do {
3372 		xfer2 = MIN(xfer, blksize);
3373 		if (checkhole) {
3374 			/*
3375 			 * Punching a hole.  Skip writing if there is
3376 			 * already a hole in the output file.
3377 			 */
3378 			xfer2 = vn_skip_hole(outvp, xfer2, &outoff, &xfer,
3379 			    &dataoff, &holeoff, cred);
3380 			if (xfer == 0)
3381 				break;
3382 			if (holeoff < 0)
3383 				checkhole = false;
3384 			KASSERT(xfer2 > 0, ("vn_write_outvp: xfer2=%jd",
3385 			    (intmax_t)xfer2));
3386 		}
3387 		bwillwrite();
3388 		mp = NULL;
3389 		error = vn_start_write(outvp, &mp, V_WAIT);
3390 		if (error != 0)
3391 			break;
3392 		if (growfile) {
3393 			error = vn_lock(outvp, LK_EXCLUSIVE);
3394 			if (error == 0) {
3395 				error = vn_truncate_locked(outvp, outoff + xfer,
3396 				    false, cred);
3397 				VOP_UNLOCK(outvp);
3398 			}
3399 		} else {
3400 			error = vn_lock(outvp, vn_lktype_write(mp, outvp));
3401 			if (error == 0) {
3402 				error = vn_rdwr(UIO_WRITE, outvp, dat, xfer2,
3403 				    outoff, UIO_SYSSPACE, IO_NODELOCKED,
3404 				    curthread->td_ucred, cred, NULL, curthread);
3405 				outoff += xfer2;
3406 				xfer -= xfer2;
3407 				VOP_UNLOCK(outvp);
3408 			}
3409 		}
3410 		if (mp != NULL)
3411 			vn_finished_write(mp);
3412 	} while (!growfile && xfer > 0 && error == 0);
3413 	return (error);
3414 }
3415 
3416 /*
3417  * Copy a byte range of one file to another.  This function can handle the
3418  * case where invp and outvp are on different file systems.
3419  * It can also be called by a VOP_COPY_FILE_RANGE() to do the work, if there
3420  * is no better file system specific way to do it.
3421  */
3422 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)3423 vn_generic_copy_file_range(struct vnode *invp, off_t *inoffp,
3424     struct vnode *outvp, off_t *outoffp, size_t *lenp, unsigned int flags,
3425     struct ucred *incred, struct ucred *outcred, struct thread *fsize_td)
3426 {
3427 	struct vattr inva;
3428 	struct mount *mp;
3429 	off_t startoff, endoff, xfer, xfer2;
3430 	u_long blksize;
3431 	int error, interrupted;
3432 	bool cantseek, readzeros, eof, first, lastblock, holetoeof, sparse;
3433 	ssize_t aresid, r = 0;
3434 	size_t copylen, len, savlen;
3435 	off_t outsize;
3436 	char *dat;
3437 	long holein, holeout;
3438 	struct timespec curts, endts;
3439 
3440 	holein = holeout = 0;
3441 	savlen = len = *lenp;
3442 	error = 0;
3443 	interrupted = 0;
3444 	dat = NULL;
3445 
3446 	error = vn_lock(invp, LK_SHARED);
3447 	if (error != 0)
3448 		goto out;
3449 	if (VOP_PATHCONF(invp, _PC_MIN_HOLE_SIZE, &holein) != 0)
3450 		holein = 0;
3451 	error = VOP_GETATTR(invp, &inva, incred);
3452 	if (error == 0 && inva.va_size > OFF_MAX)
3453 		error = EFBIG;
3454 	VOP_UNLOCK(invp);
3455 	if (error != 0)
3456 		goto out;
3457 
3458 	/*
3459 	 * Use va_bytes >= va_size as a hint that the file does not have
3460 	 * sufficient holes to justify the overhead of doing FIOSEEKHOLE.
3461 	 * This hint does not work well for file systems doing compression
3462 	 * and may fail when allocations for extended attributes increases
3463 	 * the value of va_bytes to >= va_size.
3464 	 */
3465 	sparse = true;
3466 	if (holein != 0 && inva.va_bytes >= inva.va_size) {
3467 		holein = 0;
3468 		sparse = false;
3469 	}
3470 
3471 	mp = NULL;
3472 	error = vn_start_write(outvp, &mp, V_WAIT);
3473 	if (error == 0)
3474 		error = vn_lock(outvp, LK_EXCLUSIVE);
3475 	if (error == 0) {
3476 		/*
3477 		 * If fsize_td != NULL, do a vn_rlimit_fsizex() call,
3478 		 * now that outvp is locked.
3479 		 */
3480 		if (fsize_td != NULL) {
3481 			struct uio io;
3482 
3483 			io.uio_offset = *outoffp;
3484 			io.uio_resid = len;
3485 			error = vn_rlimit_fsizex(outvp, &io, 0, &r, fsize_td);
3486 			len = savlen = io.uio_resid;
3487 			/*
3488 			 * No need to call vn_rlimit_fsizex_res before return,
3489 			 * since the uio is local.
3490 			 */
3491 		}
3492 		if (VOP_PATHCONF(outvp, _PC_MIN_HOLE_SIZE, &holeout) != 0)
3493 			holeout = 0;
3494 		/*
3495 		 * Holes that are past EOF do not need to be written as a block
3496 		 * of zero bytes.  So, truncate the output file as far as
3497 		 * possible and then use size to decide if writing 0
3498 		 * bytes is necessary in the loop below.
3499 		 */
3500 		if (error == 0)
3501 			error = vn_getsize_locked(outvp, &outsize, outcred);
3502 		if (error == 0 && outsize > *outoffp &&
3503 		    *outoffp <= OFF_MAX - len && outsize <= *outoffp + len &&
3504 		    *inoffp < inva.va_size &&
3505 		    *outoffp <= OFF_MAX - (inva.va_size - *inoffp) &&
3506 		    outsize <= *outoffp + (inva.va_size - *inoffp)) {
3507 #ifdef MAC
3508 			error = mac_vnode_check_write(curthread->td_ucred,
3509 			    outcred, outvp);
3510 			if (error == 0)
3511 #endif
3512 				error = vn_truncate_locked(outvp, *outoffp,
3513 				    false, outcred);
3514 			if (error == 0)
3515 				outsize = *outoffp;
3516 		}
3517 		VOP_UNLOCK(outvp);
3518 	}
3519 	if (mp != NULL)
3520 		vn_finished_write(mp);
3521 	if (error != 0)
3522 		goto out;
3523 
3524 	if (sparse && holein == 0 && holeout > 0) {
3525 		/*
3526 		 * For this special case, the input data will be scanned
3527 		 * for blocks of all 0 bytes.  For these blocks, the
3528 		 * write can be skipped for the output file to create
3529 		 * an unallocated region.
3530 		 * Therefore, use the appropriate size for the output file.
3531 		 */
3532 		blksize = holeout;
3533 		if (blksize <= 512) {
3534 			/*
3535 			 * Use f_iosize, since ZFS reports a _PC_MIN_HOLE_SIZE
3536 			 * of 512, although it actually only creates
3537 			 * unallocated regions for blocks >= f_iosize.
3538 			 */
3539 			blksize = outvp->v_mount->mnt_stat.f_iosize;
3540 		}
3541 	} else {
3542 		/*
3543 		 * Use the larger of the two f_iosize values.  If they are
3544 		 * not the same size, one will normally be an exact multiple of
3545 		 * the other, since they are both likely to be a power of 2.
3546 		 */
3547 		blksize = MAX(invp->v_mount->mnt_stat.f_iosize,
3548 		    outvp->v_mount->mnt_stat.f_iosize);
3549 	}
3550 
3551 	/* Clip to sane limits. */
3552 	if (blksize < 4096)
3553 		blksize = 4096;
3554 	else if (blksize > maxphys)
3555 		blksize = maxphys;
3556 	dat = malloc(blksize, M_TEMP, M_WAITOK);
3557 
3558 	/*
3559 	 * If VOP_IOCTL(FIOSEEKHOLE) works for invp, use it and FIOSEEKDATA
3560 	 * to find holes.  Otherwise, just scan the read block for all 0s
3561 	 * in the inner loop where the data copying is done.
3562 	 * Note that some file systems such as NFSv3, NFSv4.0 and NFSv4.1 may
3563 	 * support holes on the server, but do not support FIOSEEKHOLE.
3564 	 * The kernel flag COPY_FILE_RANGE_TIMEO1SEC is used to indicate
3565 	 * that this function should return after 1second with a partial
3566 	 * completion.
3567 	 */
3568 	if ((flags & COPY_FILE_RANGE_TIMEO1SEC) != 0) {
3569 		getnanouptime(&endts);
3570 		endts.tv_sec++;
3571 	} else
3572 		timespecclear(&endts);
3573 	first = true;
3574 	holetoeof = eof = false;
3575 	while (len > 0 && error == 0 && !eof && interrupted == 0) {
3576 		endoff = 0;			/* To shut up compilers. */
3577 		cantseek = true;
3578 		startoff = *inoffp;
3579 		copylen = len;
3580 
3581 		/*
3582 		 * Find the next data area.  If there is just a hole to EOF,
3583 		 * FIOSEEKDATA should fail with ENXIO.
3584 		 * (I do not know if any file system will report a hole to
3585 		 *  EOF via FIOSEEKHOLE, but I am pretty sure FIOSEEKDATA
3586 		 *  will fail for those file systems.)
3587 		 *
3588 		 * For input files that don't support FIOSEEKDATA/FIOSEEKHOLE,
3589 		 * the code just falls through to the inner copy loop.
3590 		 */
3591 		error = EINVAL;
3592 		if (holein > 0) {
3593 			error = VOP_IOCTL(invp, FIOSEEKDATA, &startoff, 0,
3594 			    incred, curthread);
3595 			if (error == ENXIO) {
3596 				startoff = endoff = inva.va_size;
3597 				eof = holetoeof = true;
3598 				error = 0;
3599 			}
3600 		}
3601 		if (error == 0 && !holetoeof) {
3602 			endoff = startoff;
3603 			error = VOP_IOCTL(invp, FIOSEEKHOLE, &endoff, 0,
3604 			    incred, curthread);
3605 			/*
3606 			 * Since invp is unlocked, it may be possible for
3607 			 * another thread to do a truncate(), lseek(), write()
3608 			 * creating a hole at startoff between the above
3609 			 * VOP_IOCTL() calls, if the other thread does not do
3610 			 * rangelocking.
3611 			 * If that happens, startoff == endoff and finding
3612 			 * the hole has failed, so set an error.
3613 			 */
3614 			if (error == 0 && startoff == endoff)
3615 				error = EINVAL; /* Any error. Reset to 0. */
3616 		}
3617 		if (error == 0) {
3618 			if (startoff > *inoffp) {
3619 				/* Found hole before data block. */
3620 				xfer = MIN(startoff - *inoffp, len);
3621 				if (*outoffp < outsize) {
3622 					/* Must write 0s to punch hole. */
3623 					xfer2 = MIN(outsize - *outoffp,
3624 					    xfer);
3625 					memset(dat, 0, MIN(xfer2, blksize));
3626 					error = vn_write_outvp(outvp, dat,
3627 					    *outoffp, xfer2, blksize, false,
3628 					    holeout > 0, outcred);
3629 				}
3630 
3631 				if (error == 0 && *outoffp + xfer >
3632 				    outsize && (xfer == len || holetoeof)) {
3633 					/* Grow output file (hole at end). */
3634 					error = vn_write_outvp(outvp, dat,
3635 					    *outoffp, xfer, blksize, true,
3636 					    false, outcred);
3637 				}
3638 				if (error == 0) {
3639 					*inoffp += xfer;
3640 					*outoffp += xfer;
3641 					len -= xfer;
3642 					if (len < savlen) {
3643 						interrupted = sig_intr();
3644 						if (timespecisset(&endts) &&
3645 						    interrupted == 0) {
3646 							getnanouptime(&curts);
3647 							if (timespeccmp(&curts,
3648 							    &endts, >=))
3649 								interrupted =
3650 								    EINTR;
3651 						}
3652 					}
3653 				}
3654 			}
3655 			copylen = MIN(len, endoff - startoff);
3656 			cantseek = false;
3657 		} else {
3658 			cantseek = true;
3659 			if (!sparse)
3660 				cantseek = false;
3661 			startoff = *inoffp;
3662 			copylen = len;
3663 			error = 0;
3664 		}
3665 
3666 		xfer = blksize;
3667 		if (cantseek) {
3668 			/*
3669 			 * Set first xfer to end at a block boundary, so that
3670 			 * holes are more likely detected in the loop below via
3671 			 * the for all bytes 0 method.
3672 			 */
3673 			xfer -= (*inoffp % blksize);
3674 		}
3675 
3676 		/*
3677 		 * Loop copying the data block.  If this was our first attempt
3678 		 * to copy anything, allow a zero-length block so that the VOPs
3679 		 * get a chance to update metadata, specifically the atime.
3680 		 */
3681 		while (error == 0 && ((copylen > 0 && !eof) || first) &&
3682 		    interrupted == 0) {
3683 			if (copylen < xfer)
3684 				xfer = copylen;
3685 			first = false;
3686 			error = vn_lock(invp, LK_SHARED);
3687 			if (error != 0)
3688 				goto out;
3689 			error = vn_rdwr(UIO_READ, invp, dat, xfer,
3690 			    startoff, UIO_SYSSPACE, IO_NODELOCKED,
3691 			    curthread->td_ucred, incred, &aresid,
3692 			    curthread);
3693 			VOP_UNLOCK(invp);
3694 			lastblock = false;
3695 			if (error == 0 && (xfer == 0 || aresid > 0)) {
3696 				/* Stop the copy at EOF on the input file. */
3697 				xfer -= aresid;
3698 				eof = true;
3699 				lastblock = true;
3700 			}
3701 			if (error == 0) {
3702 				/*
3703 				 * Skip the write for holes past the initial EOF
3704 				 * of the output file, unless this is the last
3705 				 * write of the output file at EOF.
3706 				 */
3707 				readzeros = cantseek ? mem_iszero(dat, xfer) :
3708 				    false;
3709 				if (xfer == len)
3710 					lastblock = true;
3711 				if (!cantseek || *outoffp < outsize ||
3712 				    lastblock || !readzeros)
3713 					error = vn_write_outvp(outvp, dat,
3714 					    *outoffp, xfer, blksize,
3715 					    readzeros && lastblock &&
3716 					    *outoffp >= outsize, false,
3717 					    outcred);
3718 				if (error == 0) {
3719 					*inoffp += xfer;
3720 					startoff += xfer;
3721 					*outoffp += xfer;
3722 					copylen -= xfer;
3723 					len -= xfer;
3724 					if (len < savlen) {
3725 						interrupted = sig_intr();
3726 						if (timespecisset(&endts) &&
3727 						    interrupted == 0) {
3728 							getnanouptime(&curts);
3729 							if (timespeccmp(&curts,
3730 							    &endts, >=))
3731 								interrupted =
3732 								    EINTR;
3733 						}
3734 					}
3735 				}
3736 			}
3737 			xfer = blksize;
3738 		}
3739 	}
3740 out:
3741 	*lenp = savlen - len;
3742 	free(dat, M_TEMP);
3743 	return (error);
3744 }
3745 
3746 static int
vn_fallocate(struct file * fp,off_t offset,off_t len,struct thread * td)3747 vn_fallocate(struct file *fp, off_t offset, off_t len, struct thread *td)
3748 {
3749 	struct mount *mp;
3750 	struct vnode *vp;
3751 	off_t olen, ooffset;
3752 	int error;
3753 #ifdef AUDIT
3754 	int audited_vnode1 = 0;
3755 #endif
3756 
3757 	vp = fp->f_vnode;
3758 	if (vp->v_type != VREG)
3759 		return (ENODEV);
3760 
3761 	/* Allocating blocks may take a long time, so iterate. */
3762 	for (;;) {
3763 		olen = len;
3764 		ooffset = offset;
3765 
3766 		bwillwrite();
3767 		mp = NULL;
3768 		error = vn_start_write(vp, &mp, V_WAIT | V_PCATCH);
3769 		if (error != 0)
3770 			break;
3771 		error = vn_lock(vp, LK_EXCLUSIVE);
3772 		if (error != 0) {
3773 			vn_finished_write(mp);
3774 			break;
3775 		}
3776 #ifdef AUDIT
3777 		if (!audited_vnode1) {
3778 			AUDIT_ARG_VNODE1(vp);
3779 			audited_vnode1 = 1;
3780 		}
3781 #endif
3782 #ifdef MAC
3783 		error = mac_vnode_check_write(td->td_ucred, fp->f_cred, vp);
3784 		if (error == 0)
3785 #endif
3786 			error = VOP_ALLOCATE(vp, &offset, &len, 0,
3787 			    td->td_ucred);
3788 		VOP_UNLOCK(vp);
3789 		vn_finished_write(mp);
3790 
3791 		if (olen + ooffset != offset + len) {
3792 			panic("offset + len changed from %jx/%jx to %jx/%jx",
3793 			    ooffset, olen, offset, len);
3794 		}
3795 		if (error != 0 || len == 0)
3796 			break;
3797 		KASSERT(olen > len, ("Iteration did not make progress?"));
3798 		maybe_yield();
3799 	}
3800 
3801 	return (error);
3802 }
3803 
3804 static int
vn_deallocate_impl(struct vnode * vp,off_t * offset,off_t * length,int flags,int ioflag,struct ucred * cred,struct ucred * active_cred,struct ucred * file_cred)3805 vn_deallocate_impl(struct vnode *vp, off_t *offset, off_t *length, int flags,
3806     int ioflag, struct ucred *cred, struct ucred *active_cred,
3807     struct ucred *file_cred)
3808 {
3809 	struct mount *mp;
3810 	void *rl_cookie;
3811 	off_t off, len;
3812 	int error;
3813 #ifdef AUDIT
3814 	bool audited_vnode1 = false;
3815 #endif
3816 
3817 	rl_cookie = NULL;
3818 	error = 0;
3819 	mp = NULL;
3820 	off = *offset;
3821 	len = *length;
3822 
3823 	if ((ioflag & (IO_NODELOCKED | IO_RANGELOCKED)) == 0)
3824 		rl_cookie = vn_rangelock_wlock(vp, off, off + len);
3825 	while (len > 0 && error == 0) {
3826 		/*
3827 		 * Try to deallocate the longest range in one pass.
3828 		 * In case a pass takes too long to be executed, it returns
3829 		 * partial result. The residue will be proceeded in the next
3830 		 * pass.
3831 		 */
3832 
3833 		if ((ioflag & IO_NODELOCKED) == 0) {
3834 			bwillwrite();
3835 			if ((error = vn_start_write(vp, &mp,
3836 			    V_WAIT | V_PCATCH)) != 0)
3837 				goto out;
3838 			vn_lock(vp, vn_lktype_write(mp, vp) | LK_RETRY);
3839 		}
3840 #ifdef AUDIT
3841 		if (!audited_vnode1) {
3842 			AUDIT_ARG_VNODE1(vp);
3843 			audited_vnode1 = true;
3844 		}
3845 #endif
3846 
3847 #ifdef MAC
3848 		if ((ioflag & IO_NOMACCHECK) == 0)
3849 			error = mac_vnode_check_write(active_cred, file_cred,
3850 			    vp);
3851 #endif
3852 		if (error == 0)
3853 			error = VOP_DEALLOCATE(vp, &off, &len, flags, ioflag,
3854 			    cred);
3855 
3856 		if ((ioflag & IO_NODELOCKED) == 0) {
3857 			VOP_UNLOCK(vp);
3858 			if (mp != NULL) {
3859 				vn_finished_write(mp);
3860 				mp = NULL;
3861 			}
3862 		}
3863 		if (error == 0 && len != 0)
3864 			maybe_yield();
3865 	}
3866 out:
3867 	if (rl_cookie != NULL)
3868 		vn_rangelock_unlock(vp, rl_cookie);
3869 	*offset = off;
3870 	*length = len;
3871 	return (error);
3872 }
3873 
3874 /*
3875  * This function is supposed to be used in the situations where the deallocation
3876  * is not triggered by a user request.
3877  */
3878 int
vn_deallocate(struct vnode * vp,off_t * offset,off_t * length,int flags,int ioflag,struct ucred * active_cred,struct ucred * file_cred)3879 vn_deallocate(struct vnode *vp, off_t *offset, off_t *length, int flags,
3880     int ioflag, struct ucred *active_cred, struct ucred *file_cred)
3881 {
3882 	struct ucred *cred;
3883 
3884 	if (*offset < 0 || *length <= 0 || *length > OFF_MAX - *offset ||
3885 	    flags != 0)
3886 		return (EINVAL);
3887 	if (vp->v_type != VREG)
3888 		return (ENODEV);
3889 
3890 	cred = file_cred != NOCRED ? file_cred : active_cred;
3891 	return (vn_deallocate_impl(vp, offset, length, flags, ioflag, cred,
3892 	    active_cred, file_cred));
3893 }
3894 
3895 static int
vn_fspacectl(struct file * fp,int cmd,off_t * offset,off_t * length,int flags,struct ucred * active_cred,struct thread * td)3896 vn_fspacectl(struct file *fp, int cmd, off_t *offset, off_t *length, int flags,
3897     struct ucred *active_cred, struct thread *td)
3898 {
3899 	int error;
3900 	struct vnode *vp;
3901 	int ioflag;
3902 
3903 	KASSERT(cmd == SPACECTL_DEALLOC, ("vn_fspacectl: Invalid cmd"));
3904 	KASSERT((flags & ~SPACECTL_F_SUPPORTED) == 0,
3905 	    ("vn_fspacectl: non-zero flags"));
3906 	KASSERT(*offset >= 0 && *length > 0 && *length <= OFF_MAX - *offset,
3907 	    ("vn_fspacectl: offset/length overflow or underflow"));
3908 	vp = fp->f_vnode;
3909 
3910 	if (vp->v_type != VREG)
3911 		return (ENODEV);
3912 
3913 	ioflag = get_write_ioflag(fp);
3914 
3915 	switch (cmd) {
3916 	case SPACECTL_DEALLOC:
3917 		error = vn_deallocate_impl(vp, offset, length, flags, ioflag,
3918 		    active_cred, active_cred, fp->f_cred);
3919 		break;
3920 	default:
3921 		panic("vn_fspacectl: unknown cmd %d", cmd);
3922 	}
3923 
3924 	return (error);
3925 }
3926 
3927 /*
3928  * Keep this assert as long as sizeof(struct dirent) is used as the maximum
3929  * entry size.
3930  */
3931 _Static_assert(_GENERIC_MAXDIRSIZ == sizeof(struct dirent),
3932     "'struct dirent' size must be a multiple of its alignment "
3933     "(see _GENERIC_DIRLEN())");
3934 
3935 /*
3936  * Returns successive directory entries through some caller's provided buffer.
3937  *
3938  * This function automatically refills the provided buffer with calls to
3939  * VOP_READDIR() (after MAC permission checks).
3940  *
3941  * 'td' is used for credentials and passed to uiomove().  'dirbuf' is the
3942  * caller's buffer to fill and 'dirbuflen' its allocated size.  'dirbuf' must
3943  * be properly aligned to access 'struct dirent' structures and 'dirbuflen'
3944  * must be greater than GENERIC_MAXDIRSIZ to avoid VOP_READDIR() returning
3945  * EINVAL (the latter is not a strong guarantee (yet); but EINVAL will always
3946  * be returned if this requirement is not verified).  '*dpp' points to the
3947  * current directory entry in the buffer and '*len' contains the remaining
3948  * valid bytes in 'dirbuf' after 'dpp' (including the pointed entry).
3949  *
3950  * At first call (or when restarting the read), '*len' must have been set to 0,
3951  * '*off' to 0 (or any valid start offset) and '*eofflag' to 0.  There are no
3952  * more entries as soon as '*len' is 0 after a call that returned 0.  Calling
3953  * again this function after such a condition is considered an error and EINVAL
3954  * will be returned.  Other possible error codes are those of VOP_READDIR(),
3955  * EINTEGRITY if the returned entries do not pass coherency tests, or EINVAL
3956  * (bad call).  All errors are unrecoverable, i.e., the state ('*len', '*off'
3957  * and '*eofflag') must be re-initialized before a subsequent call.  On error
3958  * or at end of directory, '*dpp' is reset to NULL.
3959  *
3960  * '*len', '*off' and '*eofflag' are internal state the caller should not
3961  * tamper with except as explained above.  '*off' is the next directory offset
3962  * to read from to refill the buffer.  '*eofflag' is set to 0 or 1 by the last
3963  * internal call to VOP_READDIR() that returned without error, indicating
3964  * whether it reached the end of the directory, and to 2 by this function after
3965  * all entries have been read.
3966  */
3967 int
vn_dir_next_dirent(struct vnode * vp,struct thread * td,char * dirbuf,size_t dirbuflen,struct dirent ** dpp,size_t * len,off_t * off,int * eofflag)3968 vn_dir_next_dirent(struct vnode *vp, struct thread *td,
3969     char *dirbuf, size_t dirbuflen,
3970     struct dirent **dpp, size_t *len, off_t *off, int *eofflag)
3971 {
3972 	struct dirent *dp = NULL;
3973 	int reclen;
3974 	int error;
3975 	struct uio uio;
3976 	struct iovec iov;
3977 
3978 	ASSERT_VOP_LOCKED(vp, "vnode not locked");
3979 	VNASSERT(vp->v_type == VDIR, vp, ("vnode is not a directory"));
3980 	MPASS2((uintptr_t)dirbuf < (uintptr_t)dirbuf + dirbuflen,
3981 	    "Address space overflow");
3982 
3983 	if (__predict_false(dirbuflen < GENERIC_MAXDIRSIZ)) {
3984 		/* Don't take any chances in this case */
3985 		error = EINVAL;
3986 		goto out;
3987 	}
3988 
3989 	if (*len != 0) {
3990 		dp = *dpp;
3991 
3992 		/*
3993 		 * The caller continued to call us after an error (we set dp to
3994 		 * NULL in a previous iteration).  Bail out right now.
3995 		 */
3996 		if (__predict_false(dp == NULL))
3997 			return (EINVAL);
3998 
3999 		MPASS(*len <= dirbuflen);
4000 		MPASS2((uintptr_t)dirbuf <= (uintptr_t)dp &&
4001 		    (uintptr_t)dp + *len <= (uintptr_t)dirbuf + dirbuflen,
4002 		    "Filled range not inside buffer");
4003 
4004 		reclen = dp->d_reclen;
4005 		if (reclen >= *len) {
4006 			/* End of buffer reached */
4007 			*len = 0;
4008 		} else {
4009 			dp = (struct dirent *)((char *)dp + reclen);
4010 			*len -= reclen;
4011 		}
4012 	}
4013 
4014 	if (*len == 0) {
4015 		dp = NULL;
4016 
4017 		/* Have to refill. */
4018 		switch (*eofflag) {
4019 		case 0:
4020 			break;
4021 
4022 		case 1:
4023 			/* Nothing more to read. */
4024 			*eofflag = 2; /* Remember the caller reached EOF. */
4025 			goto success;
4026 
4027 		default:
4028 			/* The caller didn't test for EOF. */
4029 			error = EINVAL;
4030 			goto out;
4031 		}
4032 
4033 		iov.iov_base = dirbuf;
4034 		iov.iov_len = dirbuflen;
4035 
4036 		uio.uio_iov = &iov;
4037 		uio.uio_iovcnt = 1;
4038 		uio.uio_offset = *off;
4039 		uio.uio_resid = dirbuflen;
4040 		uio.uio_segflg = UIO_SYSSPACE;
4041 		uio.uio_rw = UIO_READ;
4042 		uio.uio_td = td;
4043 
4044 #ifdef MAC
4045 		error = mac_vnode_check_readdir(td->td_ucred, vp);
4046 		if (error == 0)
4047 #endif
4048 			error = VOP_READDIR(vp, &uio, td->td_ucred, eofflag,
4049 			    NULL, NULL);
4050 		if (error != 0)
4051 			goto out;
4052 
4053 		*len = dirbuflen - uio.uio_resid;
4054 		*off = uio.uio_offset;
4055 
4056 		if (*len == 0) {
4057 			/* Sanity check on INVARIANTS. */
4058 			MPASS(*eofflag != 0);
4059 			*eofflag = 1;
4060 			goto success;
4061 		}
4062 
4063 		/*
4064 		 * Normalize the flag returned by VOP_READDIR(), since we use 2
4065 		 * as a sentinel value.
4066 		 */
4067 		if (*eofflag != 0)
4068 			*eofflag = 1;
4069 
4070 		dp = (struct dirent *)dirbuf;
4071 	}
4072 
4073 	if (__predict_false(*len < GENERIC_MINDIRSIZ ||
4074 	    dp->d_reclen < GENERIC_MINDIRSIZ)) {
4075 		error = EINTEGRITY;
4076 		dp = NULL;
4077 		goto out;
4078 	}
4079 
4080 success:
4081 	error = 0;
4082 out:
4083 	*dpp = dp;
4084 	return (error);
4085 }
4086 
4087 /*
4088  * Checks whether a directory is empty or not.
4089  *
4090  * If the directory is empty, returns 0, and if it is not, ENOTEMPTY.  Other
4091  * values are genuine errors preventing the check.
4092  */
4093 int
vn_dir_check_empty(struct vnode * vp)4094 vn_dir_check_empty(struct vnode *vp)
4095 {
4096 	struct thread *const td = curthread;
4097 	char *dirbuf;
4098 	size_t dirbuflen, len;
4099 	off_t off;
4100 	int eofflag, error;
4101 	struct dirent *dp;
4102 	struct vattr va;
4103 
4104 	ASSERT_VOP_LOCKED(vp, "vfs_emptydir");
4105 	VNPASS(vp->v_type == VDIR, vp);
4106 
4107 	error = VOP_GETATTR(vp, &va, td->td_ucred);
4108 	if (error != 0)
4109 		return (error);
4110 
4111 	dirbuflen = max(DEV_BSIZE, GENERIC_MAXDIRSIZ);
4112 	if (dirbuflen < va.va_blocksize)
4113 		dirbuflen = va.va_blocksize;
4114 	dirbuf = malloc(dirbuflen, M_TEMP, M_WAITOK);
4115 
4116 	len = 0;
4117 	off = 0;
4118 	eofflag = 0;
4119 
4120 	for (;;) {
4121 		error = vn_dir_next_dirent(vp, td, dirbuf, dirbuflen,
4122 		    &dp, &len, &off, &eofflag);
4123 		if (error != 0)
4124 			goto end;
4125 
4126 		if (len == 0) {
4127 			/* EOF */
4128 			error = 0;
4129 			goto end;
4130 		}
4131 
4132 		/*
4133 		 * Skip whiteouts.  Unionfs operates on filesystems only and
4134 		 * not on hierarchies, so these whiteouts would be shadowed on
4135 		 * the system hierarchy but not for a union using the
4136 		 * filesystem of their directories as the upper layer.
4137 		 * Additionally, unionfs currently transparently exposes
4138 		 * union-specific metadata of its upper layer, meaning that
4139 		 * whiteouts can be seen through the union view in empty
4140 		 * directories.  Taking into account these whiteouts would then
4141 		 * prevent mounting another filesystem on such effectively
4142 		 * empty directories.
4143 		 */
4144 		if (dp->d_type == DT_WHT)
4145 			continue;
4146 
4147 		/*
4148 		 * Any file in the directory which is not '.' or '..' indicates
4149 		 * the directory is not empty.
4150 		 */
4151 		switch (dp->d_namlen) {
4152 		case 2:
4153 			if (dp->d_name[1] != '.') {
4154 				/* Can't be '..' (nor '.') */
4155 				error = ENOTEMPTY;
4156 				goto end;
4157 			}
4158 			/* FALLTHROUGH */
4159 		case 1:
4160 			if (dp->d_name[0] != '.') {
4161 				/* Can't be '..' nor '.' */
4162 				error = ENOTEMPTY;
4163 				goto end;
4164 			}
4165 			break;
4166 
4167 		default:
4168 			error = ENOTEMPTY;
4169 			goto end;
4170 		}
4171 	}
4172 
4173 end:
4174 	free(dirbuf, M_TEMP);
4175 	return (error);
4176 }
4177 
4178 
4179 static u_long vn_lock_pair_pause_cnt;
4180 SYSCTL_ULONG(_debug, OID_AUTO, vn_lock_pair_pause, CTLFLAG_RD,
4181     &vn_lock_pair_pause_cnt, 0,
4182     "Count of vn_lock_pair deadlocks");
4183 
4184 u_int vn_lock_pair_pause_max;
4185 SYSCTL_UINT(_debug, OID_AUTO, vn_lock_pair_pause_max, CTLFLAG_RW,
4186     &vn_lock_pair_pause_max, 0,
4187     "Max ticks for vn_lock_pair deadlock avoidance sleep");
4188 
4189 static void
vn_lock_pair_pause(const char * wmesg)4190 vn_lock_pair_pause(const char *wmesg)
4191 {
4192 	atomic_add_long(&vn_lock_pair_pause_cnt, 1);
4193 	pause(wmesg, prng32_bounded(vn_lock_pair_pause_max));
4194 }
4195 
4196 /*
4197  * Lock pair of (possibly same) vnodes vp1, vp2, avoiding lock order
4198  * reversal.  vp1_locked indicates whether vp1 is locked; if not, vp1
4199  * must be unlocked.  Same for vp2 and vp2_locked.  One of the vnodes
4200  * can be NULL.
4201  *
4202  * The function returns with both vnodes exclusively or shared locked,
4203  * according to corresponding lkflags, and guarantees that it does not
4204  * create lock order reversal with other threads during its execution.
4205  * Both vnodes could be unlocked temporary (and reclaimed).
4206  *
4207  * If requesting shared locking, locked vnode lock must not be recursed.
4208  *
4209  * Only one of LK_SHARED and LK_EXCLUSIVE must be specified.
4210  * LK_NODDLKTREAT can be optionally passed.
4211  *
4212  * If vp1 == vp2, only one, most exclusive, lock is obtained on it.
4213  */
4214 void
vn_lock_pair(struct vnode * vp1,bool vp1_locked,int lkflags1,struct vnode * vp2,bool vp2_locked,int lkflags2)4215 vn_lock_pair(struct vnode *vp1, bool vp1_locked, int lkflags1,
4216     struct vnode *vp2, bool vp2_locked, int lkflags2)
4217 {
4218 	int error, locked1;
4219 
4220 	MPASS((((lkflags1 & LK_SHARED) != 0) ^ ((lkflags1 & LK_EXCLUSIVE) != 0)) ||
4221 	    (vp1 == NULL && lkflags1 == 0));
4222 	MPASS((lkflags1 & ~(LK_SHARED | LK_EXCLUSIVE | LK_NODDLKTREAT)) == 0);
4223 	MPASS((((lkflags2 & LK_SHARED) != 0) ^ ((lkflags2 & LK_EXCLUSIVE) != 0)) ||
4224 	    (vp2 == NULL && lkflags2 == 0));
4225 	MPASS((lkflags2 & ~(LK_SHARED | LK_EXCLUSIVE | LK_NODDLKTREAT)) == 0);
4226 
4227 	if (vp1 == NULL && vp2 == NULL)
4228 		return;
4229 
4230 	if (vp1 == vp2) {
4231 		MPASS(vp1_locked == vp2_locked);
4232 
4233 		/* Select the most exclusive mode for lock. */
4234 		if ((lkflags1 & LK_TYPE_MASK) != (lkflags2 & LK_TYPE_MASK))
4235 			lkflags1 = (lkflags1 & ~LK_SHARED) | LK_EXCLUSIVE;
4236 
4237 		if (vp1_locked) {
4238 			ASSERT_VOP_LOCKED(vp1, "vp1");
4239 
4240 			/* No need to relock if any lock is exclusive. */
4241 			if ((vp1->v_vnlock->lock_object.lo_flags &
4242 			    LK_NOSHARE) != 0)
4243 				return;
4244 
4245 			locked1 = VOP_ISLOCKED(vp1);
4246 			if (((lkflags1 & LK_SHARED) != 0 &&
4247 			    locked1 != LK_EXCLUSIVE) ||
4248 			    ((lkflags1 & LK_EXCLUSIVE) != 0 &&
4249 			    locked1 == LK_EXCLUSIVE))
4250 				return;
4251 			VOP_UNLOCK(vp1);
4252 		}
4253 
4254 		ASSERT_VOP_UNLOCKED(vp1, "vp1");
4255 		vn_lock(vp1, lkflags1 | LK_RETRY);
4256 		return;
4257 	}
4258 
4259 	if (vp1 != NULL) {
4260 		if ((lkflags1 & LK_SHARED) != 0 &&
4261 		    (vp1->v_vnlock->lock_object.lo_flags & LK_NOSHARE) != 0)
4262 			lkflags1 = (lkflags1 & ~LK_SHARED) | LK_EXCLUSIVE;
4263 		if (vp1_locked && VOP_ISLOCKED(vp1) != LK_EXCLUSIVE) {
4264 			ASSERT_VOP_LOCKED(vp1, "vp1");
4265 			if ((lkflags1 & LK_EXCLUSIVE) != 0) {
4266 				VOP_UNLOCK(vp1);
4267 				ASSERT_VOP_UNLOCKED(vp1,
4268 				    "vp1 shared recursed");
4269 				vp1_locked = false;
4270 			}
4271 		} else if (!vp1_locked)
4272 			ASSERT_VOP_UNLOCKED(vp1, "vp1");
4273 	} else {
4274 		vp1_locked = true;
4275 	}
4276 
4277 	if (vp2 != NULL) {
4278 		if ((lkflags2 & LK_SHARED) != 0 &&
4279 		    (vp2->v_vnlock->lock_object.lo_flags & LK_NOSHARE) != 0)
4280 			lkflags2 = (lkflags2 & ~LK_SHARED) | LK_EXCLUSIVE;
4281 		if (vp2_locked && VOP_ISLOCKED(vp2) != LK_EXCLUSIVE) {
4282 			ASSERT_VOP_LOCKED(vp2, "vp2");
4283 			if ((lkflags2 & LK_EXCLUSIVE) != 0) {
4284 				VOP_UNLOCK(vp2);
4285 				ASSERT_VOP_UNLOCKED(vp2,
4286 				    "vp2 shared recursed");
4287 				vp2_locked = false;
4288 			}
4289 		} else if (!vp2_locked)
4290 			ASSERT_VOP_UNLOCKED(vp2, "vp2");
4291 	} else {
4292 		vp2_locked = true;
4293 	}
4294 
4295 	if (!vp1_locked && !vp2_locked) {
4296 		vn_lock(vp1, lkflags1 | LK_RETRY);
4297 		vp1_locked = true;
4298 	}
4299 
4300 	while (!vp1_locked || !vp2_locked) {
4301 		if (vp1_locked && vp2 != NULL) {
4302 			if (vp1 != NULL) {
4303 				error = VOP_LOCK1(vp2, lkflags2 | LK_NOWAIT,
4304 				    __FILE__, __LINE__);
4305 				if (error == 0)
4306 					break;
4307 				VOP_UNLOCK(vp1);
4308 				vp1_locked = false;
4309 				vn_lock_pair_pause("vlp1");
4310 			}
4311 			vn_lock(vp2, lkflags2 | LK_RETRY);
4312 			vp2_locked = true;
4313 		}
4314 		if (vp2_locked && vp1 != NULL) {
4315 			if (vp2 != NULL) {
4316 				error = VOP_LOCK1(vp1, lkflags1 | LK_NOWAIT,
4317 				    __FILE__, __LINE__);
4318 				if (error == 0)
4319 					break;
4320 				VOP_UNLOCK(vp2);
4321 				vp2_locked = false;
4322 				vn_lock_pair_pause("vlp2");
4323 			}
4324 			vn_lock(vp1, lkflags1 | LK_RETRY);
4325 			vp1_locked = true;
4326 		}
4327 	}
4328 	if (vp1 != NULL) {
4329 		if (lkflags1 == LK_EXCLUSIVE)
4330 			ASSERT_VOP_ELOCKED(vp1, "vp1 ret");
4331 		else
4332 			ASSERT_VOP_LOCKED(vp1, "vp1 ret");
4333 	}
4334 	if (vp2 != NULL) {
4335 		if (lkflags2 == LK_EXCLUSIVE)
4336 			ASSERT_VOP_ELOCKED(vp2, "vp2 ret");
4337 		else
4338 			ASSERT_VOP_LOCKED(vp2, "vp2 ret");
4339 	}
4340 }
4341 
4342 int
vn_lktype_write(struct mount * mp,struct vnode * vp)4343 vn_lktype_write(struct mount *mp, struct vnode *vp)
4344 {
4345 	if (MNT_SHARED_WRITES(mp) ||
4346 	    (mp == NULL && MNT_SHARED_WRITES(vp->v_mount)))
4347 		return (LK_SHARED);
4348 	return (LK_EXCLUSIVE);
4349 }
4350 
4351 int
vn_cmp(struct file * fp1,struct file * fp2,struct thread * td)4352 vn_cmp(struct file *fp1, struct file *fp2, struct thread *td)
4353 {
4354 	if (fp2->f_type != DTYPE_VNODE)
4355 		return (3);
4356 	return (kcmp_cmp((uintptr_t)fp1->f_vnode, (uintptr_t)fp2->f_vnode));
4357 }
4358