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