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