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