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