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 static int
vn_lock_delayed_setsize(struct vnode * vp,int flags,const char * file,int line)1963 vn_lock_delayed_setsize(struct vnode *vp, int flags, const char *file, int line)
1964 {
1965 struct vop_lock1_args ap;
1966 int error, lktype;
1967 bool onfault;
1968
1969 ASSERT_VOP_LOCKED(vp, "vn_lock_delayed_setsize");
1970 lktype = flags & LK_TYPE_MASK;
1971 if (vp->v_op == &dead_vnodeops)
1972 return (0);
1973 VI_LOCK(vp);
1974 if ((vp->v_iflag & VI_DELAYED_SETSIZE) == 0 || (lktype != LK_SHARED &&
1975 lktype != LK_EXCLUSIVE && lktype != LK_UPGRADE &&
1976 lktype != LK_TRYUPGRADE)) {
1977 VI_UNLOCK(vp);
1978 return (0);
1979 }
1980 onfault = (flags & LK_EATTR_MASK) == LK_NOWAIT &&
1981 (flags & LK_INIT_MASK) == LK_CANRECURSE &&
1982 (lktype == LK_SHARED || lktype == LK_EXCLUSIVE);
1983 if (onfault && vp->v_vnlock->lk_recurse == 0) {
1984 /*
1985 * Force retry in vm_fault(), to make the lock request
1986 * sleepable, which allows us to piggy-back the
1987 * sleepable call to vnode_pager_setsize().
1988 */
1989 VI_UNLOCK(vp);
1990 VOP_UNLOCK(vp);
1991 return (EBUSY);
1992 }
1993 if ((flags & LK_NOWAIT) != 0 ||
1994 (lktype == LK_SHARED && vp->v_vnlock->lk_recurse > 0)) {
1995 VI_UNLOCK(vp);
1996 return (0);
1997 }
1998 if (lktype == LK_SHARED) {
1999 VOP_UNLOCK(vp);
2000 ap.a_gen.a_desc = &vop_lock1_desc;
2001 ap.a_vp = vp;
2002 ap.a_flags = (flags & ~LK_TYPE_MASK) | LK_EXCLUSIVE |
2003 LK_INTERLOCK;
2004 ap.a_file = file;
2005 ap.a_line = line;
2006 error = VOP_LOCK1_APV(&default_vnodeops, &ap);
2007 if (error != 0 || vp->v_op == &dead_vnodeops)
2008 return (error);
2009 if (vp->v_data == NULL)
2010 goto downgrade;
2011 VI_LOCK(vp);
2012 if ((vp->v_iflag & VI_DELAYED_SETSIZE) == 0) {
2013 VI_UNLOCK(vp);
2014 goto downgrade;
2015 }
2016 }
2017 vn_clear_delayed_setsize_locked(vp);
2018 VI_UNLOCK(vp);
2019 VOP_DELAYED_SETSIZE(vp);
2020 downgrade:
2021 if (lktype == LK_SHARED) {
2022 ap.a_flags &= ~(LK_TYPE_MASK | LK_INTERLOCK);
2023 ap.a_flags |= LK_DOWNGRADE;
2024 (void)VOP_LOCK1_APV(&default_vnodeops, &ap);
2025 }
2026 return (0);
2027 }
2028
2029 int
_vn_lock(struct vnode * vp,int flags,const char * file,int line)2030 _vn_lock(struct vnode *vp, int flags, const char *file, int line)
2031 {
2032 int error;
2033
2034 VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
2035 ("vn_lock: no locktype (%d passed)", flags));
2036 VNPASS(vp->v_holdcnt > 0, vp);
2037 error = VOP_LOCK1(vp, flags, file, line);
2038 if (__predict_false(error != 0 || VN_IS_DOOMED(vp)))
2039 error = _vn_lock_fallback(vp, flags, file, line, error);
2040 if (error != 0 || __predict_true((atomic_load_short(&vp->v_iflag) &
2041 VI_DELAYED_SETSIZE) == 0))
2042 return (error);
2043 return (vn_lock_delayed_setsize(vp, flags, file, line));
2044 }
2045
2046 /*
2047 * File table vnode close routine.
2048 */
2049 static int
vn_closefile(struct file * fp,struct thread * td)2050 vn_closefile(struct file *fp, struct thread *td)
2051 {
2052 struct vnode *vp;
2053 struct flock lf;
2054 int error;
2055 bool ref;
2056
2057 vp = fp->f_vnode;
2058 fp->f_ops = &badfileops;
2059 ref = (fp->f_flag & FHASLOCK) != 0;
2060
2061 error = vn_close1(vp, fp->f_flag, fp->f_cred, td, ref);
2062
2063 if (__predict_false(ref)) {
2064 lf.l_whence = SEEK_SET;
2065 lf.l_start = 0;
2066 lf.l_len = 0;
2067 lf.l_type = F_UNLCK;
2068 (void) VOP_ADVLOCK(vp, fp, F_UNLCK, &lf, F_FLOCK);
2069 vrele(vp);
2070 }
2071 return (error);
2072 }
2073
2074 /*
2075 * Preparing to start a filesystem write operation. If the operation is
2076 * permitted, then we bump the count of operations in progress and
2077 * proceed. If a suspend request is in progress, we wait until the
2078 * suspension is over, and then proceed.
2079 */
2080 static int
vn_start_write_refed(struct mount * mp,int flags)2081 vn_start_write_refed(struct mount *mp, int flags)
2082 {
2083 struct mount_pcpu *mpcpu;
2084 int error, mflags;
2085
2086 if ((flags & V_XSLEEP) == 0 && vfs_op_thread_enter(mp, &mpcpu)) {
2087 MPASS((mp->mnt_kern_flag & MNTK_SUSPEND) == 0);
2088 vfs_mp_count_add_pcpu(mpcpu, writeopcount, 1);
2089 vfs_op_thread_exit(mp, mpcpu);
2090 return (0);
2091 }
2092
2093 error = 0;
2094
2095 MNT_ILOCK(mp);
2096
2097 /*
2098 * Check on status of suspension.
2099 */
2100 if ((curthread->td_pflags & TDP_IGNSUSP) == 0 ||
2101 mp->mnt_susp_owner != curthread) {
2102 mflags = 0;
2103 if ((mp->mnt_vfc->vfc_flags & VFCF_SBDRY) != 0) {
2104 if (flags & V_PCATCH)
2105 mflags |= PCATCH;
2106 }
2107 mflags |= PRI_MAX_KERN;
2108 while ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0) {
2109 if ((flags & V_NOWAIT) != 0) {
2110 error = EWOULDBLOCK;
2111 goto unlock;
2112 }
2113 error = msleep(&mp->mnt_flag, MNT_MTX(mp), mflags,
2114 "suspfs", 0);
2115 if (error != 0)
2116 goto unlock;
2117 }
2118 }
2119 if ((flags & V_XSLEEP) != 0)
2120 goto unlock;
2121 mp->mnt_writeopcount++;
2122 unlock:
2123 if (error != 0 || (flags & V_XSLEEP) != 0)
2124 MNT_REL(mp);
2125 MNT_IUNLOCK(mp);
2126 return (error);
2127 }
2128
2129 int
vn_start_write(struct vnode * vp,struct mount ** mpp,int flags)2130 vn_start_write(struct vnode *vp, struct mount **mpp, int flags)
2131 {
2132 struct mount *mp;
2133 int error;
2134
2135 KASSERT((flags & ~V_VALID_FLAGS) == 0,
2136 ("%s: invalid flags passed %d\n", __func__, flags));
2137
2138 error = 0;
2139 /*
2140 * If a vnode is provided, get and return the mount point that
2141 * to which it will write.
2142 */
2143 if (vp != NULL) {
2144 if ((error = VOP_GETWRITEMOUNT(vp, mpp)) != 0) {
2145 *mpp = NULL;
2146 if (error != EOPNOTSUPP)
2147 return (error);
2148 return (0);
2149 }
2150 }
2151 if ((mp = *mpp) == NULL)
2152 return (0);
2153
2154 /*
2155 * VOP_GETWRITEMOUNT() returns with the mp refcount held through
2156 * a vfs_ref().
2157 * As long as a vnode is not provided we need to acquire a
2158 * refcount for the provided mountpoint too, in order to
2159 * emulate a vfs_ref().
2160 */
2161 if (vp == NULL)
2162 vfs_ref(mp);
2163
2164 error = vn_start_write_refed(mp, flags);
2165 if (error != 0 && (flags & V_NOWAIT) == 0)
2166 *mpp = NULL;
2167 return (error);
2168 }
2169
2170 /*
2171 * Secondary suspension. Used by operations such as vop_inactive
2172 * routines that are needed by the higher level functions. These
2173 * are allowed to proceed until all the higher level functions have
2174 * completed (indicated by mnt_writeopcount dropping to zero). At that
2175 * time, these operations are halted until the suspension is over.
2176 */
2177 int
vn_start_secondary_write(struct vnode * vp,struct mount ** mpp,int flags)2178 vn_start_secondary_write(struct vnode *vp, struct mount **mpp, int flags)
2179 {
2180 struct mount *mp;
2181 int error, mflags;
2182
2183 KASSERT((flags & (~V_VALID_FLAGS | V_XSLEEP)) == 0,
2184 ("%s: invalid flags passed %d\n", __func__, flags));
2185
2186 retry:
2187 if (vp != NULL) {
2188 if ((error = VOP_GETWRITEMOUNT(vp, mpp)) != 0) {
2189 *mpp = NULL;
2190 if (error != EOPNOTSUPP)
2191 return (error);
2192 return (0);
2193 }
2194 }
2195 /*
2196 * If we are not suspended or have not yet reached suspended
2197 * mode, then let the operation proceed.
2198 */
2199 if ((mp = *mpp) == NULL)
2200 return (0);
2201
2202 /*
2203 * VOP_GETWRITEMOUNT() returns with the mp refcount held through
2204 * a vfs_ref().
2205 * As long as a vnode is not provided we need to acquire a
2206 * refcount for the provided mountpoint too, in order to
2207 * emulate a vfs_ref().
2208 */
2209 MNT_ILOCK(mp);
2210 if (vp == NULL)
2211 MNT_REF(mp);
2212 if ((mp->mnt_kern_flag & (MNTK_SUSPENDED | MNTK_SUSPEND2)) == 0) {
2213 mp->mnt_secondary_writes++;
2214 mp->mnt_secondary_accwrites++;
2215 MNT_IUNLOCK(mp);
2216 return (0);
2217 }
2218 if ((flags & V_NOWAIT) != 0) {
2219 MNT_REL(mp);
2220 MNT_IUNLOCK(mp);
2221 *mpp = NULL;
2222 return (EWOULDBLOCK);
2223 }
2224 /*
2225 * Wait for the suspension to finish.
2226 */
2227 mflags = 0;
2228 if ((mp->mnt_vfc->vfc_flags & VFCF_SBDRY) != 0) {
2229 if ((flags & V_PCATCH) != 0)
2230 mflags |= PCATCH;
2231 }
2232 mflags |= PRI_MAX_KERN | PDROP;
2233 error = msleep(&mp->mnt_flag, MNT_MTX(mp), mflags, "suspfs", 0);
2234 vfs_rel(mp);
2235 if (error == 0)
2236 goto retry;
2237 *mpp = NULL;
2238 return (error);
2239 }
2240
2241 /*
2242 * Filesystem write operation has completed. If we are suspending and this
2243 * operation is the last one, notify the suspender that the suspension is
2244 * now in effect.
2245 */
2246 void
vn_finished_write(struct mount * mp)2247 vn_finished_write(struct mount *mp)
2248 {
2249 struct mount_pcpu *mpcpu;
2250 int c;
2251
2252 if (mp == NULL)
2253 return;
2254
2255 if (vfs_op_thread_enter(mp, &mpcpu)) {
2256 vfs_mp_count_sub_pcpu(mpcpu, writeopcount, 1);
2257 vfs_mp_count_sub_pcpu(mpcpu, ref, 1);
2258 vfs_op_thread_exit(mp, mpcpu);
2259 return;
2260 }
2261
2262 MNT_ILOCK(mp);
2263 vfs_assert_mount_counters(mp);
2264 MNT_REL(mp);
2265 c = --mp->mnt_writeopcount;
2266 if (mp->mnt_vfs_ops == 0) {
2267 MPASS((mp->mnt_kern_flag & MNTK_SUSPEND) == 0);
2268 MNT_IUNLOCK(mp);
2269 return;
2270 }
2271 if (c < 0)
2272 vfs_dump_mount_counters(mp);
2273 if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0 && c == 0)
2274 wakeup(&mp->mnt_writeopcount);
2275 MNT_IUNLOCK(mp);
2276 }
2277
2278 /*
2279 * Filesystem secondary write operation has completed. If we are
2280 * suspending and this operation is the last one, notify the suspender
2281 * that the suspension is now in effect.
2282 */
2283 void
vn_finished_secondary_write(struct mount * mp)2284 vn_finished_secondary_write(struct mount *mp)
2285 {
2286 if (mp == NULL)
2287 return;
2288 MNT_ILOCK(mp);
2289 MNT_REL(mp);
2290 mp->mnt_secondary_writes--;
2291 if (mp->mnt_secondary_writes < 0)
2292 panic("vn_finished_secondary_write: neg cnt");
2293 if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0 &&
2294 mp->mnt_secondary_writes <= 0)
2295 wakeup(&mp->mnt_secondary_writes);
2296 MNT_IUNLOCK(mp);
2297 }
2298
2299 /*
2300 * Request a filesystem to suspend write operations.
2301 */
2302 int
vfs_write_suspend(struct mount * mp,int flags)2303 vfs_write_suspend(struct mount *mp, int flags)
2304 {
2305 int error;
2306
2307 vfs_op_enter(mp);
2308
2309 MNT_ILOCK(mp);
2310 vfs_assert_mount_counters(mp);
2311 if (mp->mnt_susp_owner == curthread) {
2312 vfs_op_exit_locked(mp);
2313 MNT_IUNLOCK(mp);
2314 return (EALREADY);
2315 }
2316 while (mp->mnt_kern_flag & MNTK_SUSPEND)
2317 msleep(&mp->mnt_flag, MNT_MTX(mp), PRI_MAX_KERN, "wsuspfs", 0);
2318
2319 /*
2320 * Unmount holds a write reference on the mount point. If we
2321 * own busy reference and drain for writers, we deadlock with
2322 * the reference draining in the unmount path. Callers of
2323 * vfs_write_suspend() must specify VS_SKIP_UNMOUNT if
2324 * vfs_busy() reference is owned and caller is not in the
2325 * unmount context.
2326 */
2327 if ((flags & VS_SKIP_UNMOUNT) != 0 &&
2328 (mp->mnt_kern_flag & MNTK_UNMOUNT) != 0) {
2329 vfs_op_exit_locked(mp);
2330 MNT_IUNLOCK(mp);
2331 return (EBUSY);
2332 }
2333
2334 mp->mnt_kern_flag |= MNTK_SUSPEND;
2335 mp->mnt_susp_owner = curthread;
2336 if (mp->mnt_writeopcount > 0)
2337 (void) msleep(&mp->mnt_writeopcount,
2338 MNT_MTX(mp), PRI_MAX_KERN | PDROP, "suspwt", 0);
2339 else
2340 MNT_IUNLOCK(mp);
2341 if ((error = VFS_SYNC(mp, MNT_SUSPEND)) != 0) {
2342 vfs_write_resume(mp, 0);
2343 /* vfs_write_resume does vfs_op_exit() for us */
2344 }
2345 return (error);
2346 }
2347
2348 /*
2349 * Request a filesystem to resume write operations.
2350 */
2351 void
vfs_write_resume(struct mount * mp,int flags)2352 vfs_write_resume(struct mount *mp, int flags)
2353 {
2354
2355 MNT_ILOCK(mp);
2356 if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0) {
2357 KASSERT(mp->mnt_susp_owner == curthread, ("mnt_susp_owner"));
2358 mp->mnt_kern_flag &= ~(MNTK_SUSPEND | MNTK_SUSPEND2 |
2359 MNTK_SUSPENDED);
2360 mp->mnt_susp_owner = NULL;
2361 wakeup(&mp->mnt_writeopcount);
2362 wakeup(&mp->mnt_flag);
2363 curthread->td_pflags &= ~TDP_IGNSUSP;
2364 if ((flags & VR_START_WRITE) != 0) {
2365 MNT_REF(mp);
2366 mp->mnt_writeopcount++;
2367 }
2368 MNT_IUNLOCK(mp);
2369 if ((flags & VR_NO_SUSPCLR) == 0)
2370 VFS_SUSP_CLEAN(mp);
2371 vfs_op_exit(mp);
2372 } else {
2373 if ((flags & VR_START_WRITE) != 0) {
2374 MNT_REF(mp);
2375 mp->mnt_writeopcount++;
2376 }
2377
2378 MNT_IUNLOCK(mp);
2379 }
2380 }
2381
2382 /*
2383 * Helper loop around vfs_write_suspend() for filesystem unmount VFS
2384 * methods.
2385 */
2386 int
vfs_write_suspend_umnt(struct mount * mp)2387 vfs_write_suspend_umnt(struct mount *mp)
2388 {
2389 int error;
2390
2391 KASSERT((curthread->td_pflags & TDP_IGNSUSP) == 0,
2392 ("vfs_write_suspend_umnt: recursed"));
2393
2394 /* dounmount() already called vn_start_write(). */
2395 for (;;) {
2396 vn_finished_write(mp);
2397 error = vfs_write_suspend(mp, 0);
2398 if (error != 0) {
2399 vn_start_write(NULL, &mp, V_WAIT);
2400 return (error);
2401 }
2402 MNT_ILOCK(mp);
2403 if ((mp->mnt_kern_flag & MNTK_SUSPENDED) != 0)
2404 break;
2405 MNT_IUNLOCK(mp);
2406 vn_start_write(NULL, &mp, V_WAIT);
2407 }
2408 mp->mnt_kern_flag &= ~(MNTK_SUSPENDED | MNTK_SUSPEND2);
2409 wakeup(&mp->mnt_flag);
2410 MNT_IUNLOCK(mp);
2411 curthread->td_pflags |= TDP_IGNSUSP;
2412 return (0);
2413 }
2414
2415 /*
2416 * Implement kqueues for files by translating it to vnode operation.
2417 */
2418 static int
vn_kqfilter(struct file * fp,struct knote * kn)2419 vn_kqfilter(struct file *fp, struct knote *kn)
2420 {
2421
2422 return (VOP_KQFILTER(fp->f_vnode, kn));
2423 }
2424
2425 int
vn_kqfilter_opath(struct file * fp,struct knote * kn)2426 vn_kqfilter_opath(struct file *fp, struct knote *kn)
2427 {
2428 if ((fp->f_flag & FKQALLOWED) == 0)
2429 return (EBADF);
2430 return (vn_kqfilter(fp, kn));
2431 }
2432
2433 /*
2434 * Simplified in-kernel wrapper calls for extended attribute access.
2435 * Both calls pass in a NULL credential, authorizing as "kernel" access.
2436 * Set IO_NODELOCKED in ioflg if the vnode is already locked.
2437 */
2438 int
vn_extattr_get(struct vnode * vp,int ioflg,int attrnamespace,const char * attrname,int * buflen,char * buf,struct thread * td)2439 vn_extattr_get(struct vnode *vp, int ioflg, int attrnamespace,
2440 const char *attrname, int *buflen, char *buf, struct thread *td)
2441 {
2442 struct uio auio;
2443 struct iovec iov;
2444 int error;
2445
2446 iov.iov_len = *buflen;
2447 iov.iov_base = buf;
2448
2449 auio.uio_iov = &iov;
2450 auio.uio_iovcnt = 1;
2451 auio.uio_rw = UIO_READ;
2452 auio.uio_segflg = UIO_SYSSPACE;
2453 auio.uio_td = td;
2454 auio.uio_offset = 0;
2455 auio.uio_resid = *buflen;
2456
2457 if ((ioflg & IO_NODELOCKED) == 0)
2458 vn_lock(vp, LK_SHARED | LK_RETRY);
2459
2460 ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
2461
2462 /* authorize attribute retrieval as kernel */
2463 error = VOP_GETEXTATTR(vp, attrnamespace, attrname, &auio, NULL, NULL,
2464 td);
2465
2466 if ((ioflg & IO_NODELOCKED) == 0)
2467 VOP_UNLOCK(vp);
2468
2469 if (error == 0) {
2470 *buflen = *buflen - auio.uio_resid;
2471 }
2472
2473 return (error);
2474 }
2475
2476 /*
2477 * XXX failure mode if partially written?
2478 */
2479 int
vn_extattr_set(struct vnode * vp,int ioflg,int attrnamespace,const char * attrname,int buflen,char * buf,struct thread * td)2480 vn_extattr_set(struct vnode *vp, int ioflg, int attrnamespace,
2481 const char *attrname, int buflen, char *buf, struct thread *td)
2482 {
2483 struct uio auio;
2484 struct iovec iov;
2485 struct mount *mp;
2486 int error;
2487
2488 iov.iov_len = buflen;
2489 iov.iov_base = buf;
2490
2491 auio.uio_iov = &iov;
2492 auio.uio_iovcnt = 1;
2493 auio.uio_rw = UIO_WRITE;
2494 auio.uio_segflg = UIO_SYSSPACE;
2495 auio.uio_td = td;
2496 auio.uio_offset = 0;
2497 auio.uio_resid = buflen;
2498
2499 if ((ioflg & IO_NODELOCKED) == 0) {
2500 if ((error = vn_start_write(vp, &mp, V_WAIT)) != 0)
2501 return (error);
2502 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2503 }
2504
2505 ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
2506
2507 /* authorize attribute setting as kernel */
2508 error = VOP_SETEXTATTR(vp, attrnamespace, attrname, &auio, NULL, td);
2509
2510 if ((ioflg & IO_NODELOCKED) == 0) {
2511 vn_finished_write(mp);
2512 VOP_UNLOCK(vp);
2513 }
2514
2515 return (error);
2516 }
2517
2518 int
vn_extattr_rm(struct vnode * vp,int ioflg,int attrnamespace,const char * attrname,struct thread * td)2519 vn_extattr_rm(struct vnode *vp, int ioflg, int attrnamespace,
2520 const char *attrname, struct thread *td)
2521 {
2522 struct mount *mp;
2523 int error;
2524
2525 if ((ioflg & IO_NODELOCKED) == 0) {
2526 if ((error = vn_start_write(vp, &mp, V_WAIT)) != 0)
2527 return (error);
2528 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2529 }
2530
2531 ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
2532
2533 /* authorize attribute removal as kernel */
2534 error = VOP_DELETEEXTATTR(vp, attrnamespace, attrname, NULL, td);
2535 if (error == EOPNOTSUPP)
2536 error = VOP_SETEXTATTR(vp, attrnamespace, attrname, NULL,
2537 NULL, td);
2538
2539 if ((ioflg & IO_NODELOCKED) == 0) {
2540 vn_finished_write(mp);
2541 VOP_UNLOCK(vp);
2542 }
2543
2544 return (error);
2545 }
2546
2547 static int
vn_get_ino_alloc_vget(struct mount * mp,void * arg,int lkflags,struct vnode ** rvp)2548 vn_get_ino_alloc_vget(struct mount *mp, void *arg, int lkflags,
2549 struct vnode **rvp)
2550 {
2551
2552 return (VFS_VGET(mp, *(ino_t *)arg, lkflags, rvp));
2553 }
2554
2555 int
vn_vget_ino(struct vnode * vp,ino_t ino,int lkflags,struct vnode ** rvp)2556 vn_vget_ino(struct vnode *vp, ino_t ino, int lkflags, struct vnode **rvp)
2557 {
2558
2559 return (vn_vget_ino_gen(vp, vn_get_ino_alloc_vget, &ino,
2560 lkflags, rvp));
2561 }
2562
2563 int
vn_vget_ino_gen(struct vnode * vp,vn_get_ino_t alloc,void * alloc_arg,int lkflags,struct vnode ** rvp)2564 vn_vget_ino_gen(struct vnode *vp, vn_get_ino_t alloc, void *alloc_arg,
2565 int lkflags, struct vnode **rvp)
2566 {
2567 struct mount *mp;
2568 int ltype, error;
2569
2570 ASSERT_VOP_LOCKED(vp, "vn_vget_ino_get");
2571 mp = vp->v_mount;
2572 ltype = VOP_ISLOCKED(vp);
2573 KASSERT(ltype == LK_EXCLUSIVE || ltype == LK_SHARED,
2574 ("vn_vget_ino: vp not locked"));
2575 error = vfs_busy(mp, MBF_NOWAIT);
2576 if (error != 0) {
2577 vfs_ref(mp);
2578 VOP_UNLOCK(vp);
2579 error = vfs_busy(mp, 0);
2580 vn_lock(vp, ltype | LK_RETRY);
2581 vfs_rel(mp);
2582 if (error != 0)
2583 return (ENOENT);
2584 if (VN_IS_DOOMED(vp)) {
2585 vfs_unbusy(mp);
2586 return (ENOENT);
2587 }
2588 }
2589 VOP_UNLOCK(vp);
2590 error = alloc(mp, alloc_arg, lkflags, rvp);
2591 vfs_unbusy(mp);
2592 if (error != 0 || *rvp != vp)
2593 vn_lock(vp, ltype | LK_RETRY);
2594 if (VN_IS_DOOMED(vp)) {
2595 if (error == 0) {
2596 if (*rvp == vp)
2597 vunref(vp);
2598 else
2599 vput(*rvp);
2600 }
2601 error = ENOENT;
2602 }
2603 return (error);
2604 }
2605
2606 static void
vn_send_sigxfsz(struct proc * p)2607 vn_send_sigxfsz(struct proc *p)
2608 {
2609 PROC_LOCK(p);
2610 kern_psignal(p, SIGXFSZ);
2611 PROC_UNLOCK(p);
2612 }
2613
2614 int
vn_rlimit_trunc(u_quad_t size,struct thread * td)2615 vn_rlimit_trunc(u_quad_t size, struct thread *td)
2616 {
2617 if (size <= lim_cur(td, RLIMIT_FSIZE))
2618 return (0);
2619 vn_send_sigxfsz(td->td_proc);
2620 return (EFBIG);
2621 }
2622
2623 static int
vn_rlimit_fsizex1(const struct vnode * vp,struct uio * uio,off_t maxfsz,bool adj,struct thread * td)2624 vn_rlimit_fsizex1(const struct vnode *vp, struct uio *uio, off_t maxfsz,
2625 bool adj, struct thread *td)
2626 {
2627 off_t lim;
2628 bool ktr_write;
2629
2630 if (vp->v_type != VREG)
2631 return (0);
2632
2633 /*
2634 * Handle file system maximum file size.
2635 */
2636 if (maxfsz != 0 && uio->uio_offset + uio->uio_resid > maxfsz) {
2637 if (!adj || uio->uio_offset >= maxfsz)
2638 return (EFBIG);
2639 uio->uio_resid = maxfsz - uio->uio_offset;
2640 }
2641
2642 /*
2643 * This is kernel write (e.g. vnode_pager) or accounting
2644 * write, ignore limit.
2645 */
2646 if (td == NULL || (td->td_pflags2 & TDP2_ACCT) != 0)
2647 return (0);
2648
2649 /*
2650 * Calculate file size limit.
2651 */
2652 ktr_write = (td->td_pflags & TDP_INKTRACE) != 0;
2653 lim = __predict_false(ktr_write) ? td->td_ktr_io_lim :
2654 lim_cur(td, RLIMIT_FSIZE);
2655
2656 /*
2657 * Is the limit reached?
2658 */
2659 if (__predict_true((uoff_t)uio->uio_offset + uio->uio_resid <= lim))
2660 return (0);
2661
2662 /*
2663 * Prepared filesystems can handle writes truncated to the
2664 * file size limit.
2665 */
2666 if (adj && (uoff_t)uio->uio_offset < lim) {
2667 uio->uio_resid = lim - (uoff_t)uio->uio_offset;
2668 return (0);
2669 }
2670
2671 if (!ktr_write || ktr_filesize_limit_signal)
2672 vn_send_sigxfsz(td->td_proc);
2673 return (EFBIG);
2674 }
2675
2676 /*
2677 * Helper for VOP_WRITE() implementations, the common code to
2678 * handle maximum supported file size on the filesystem, and
2679 * RLIMIT_FSIZE, except for special writes from accounting subsystem
2680 * and ktrace.
2681 *
2682 * For maximum file size (maxfsz argument):
2683 * - return EFBIG if uio_offset is beyond it
2684 * - otherwise, clamp uio_resid if write would extend file beyond maxfsz.
2685 *
2686 * For RLIMIT_FSIZE:
2687 * - return EFBIG and send SIGXFSZ if uio_offset is beyond the limit
2688 * - otherwise, clamp uio_resid if write would extend file beyond limit.
2689 *
2690 * If clamping occured, the adjustment for uio_resid is stored in
2691 * *resid_adj, to be re-applied by vn_rlimit_fsizex_res() on return
2692 * from the VOP.
2693 */
2694 int
vn_rlimit_fsizex(const struct vnode * vp,struct uio * uio,off_t maxfsz,ssize_t * resid_adj,struct thread * td)2695 vn_rlimit_fsizex(const struct vnode *vp, struct uio *uio, off_t maxfsz,
2696 ssize_t *resid_adj, struct thread *td)
2697 {
2698 ssize_t resid_orig;
2699 int error;
2700 bool adj;
2701
2702 resid_orig = uio->uio_resid;
2703 adj = resid_adj != NULL;
2704 error = vn_rlimit_fsizex1(vp, uio, maxfsz, adj, td);
2705 if (adj)
2706 *resid_adj = resid_orig - uio->uio_resid;
2707 return (error);
2708 }
2709
2710 void
vn_rlimit_fsizex_res(struct uio * uio,ssize_t resid_adj)2711 vn_rlimit_fsizex_res(struct uio *uio, ssize_t resid_adj)
2712 {
2713 uio->uio_resid += resid_adj;
2714 }
2715
2716 int
vn_rlimit_fsize(const struct vnode * vp,const struct uio * uio,struct thread * td)2717 vn_rlimit_fsize(const struct vnode *vp, const struct uio *uio,
2718 struct thread *td)
2719 {
2720 return (vn_rlimit_fsizex(vp, __DECONST(struct uio *, uio), 0, NULL,
2721 td));
2722 }
2723
2724 int
vn_chmod(struct file * fp,mode_t mode,struct ucred * active_cred,struct thread * td)2725 vn_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
2726 struct thread *td)
2727 {
2728 struct vnode *vp;
2729
2730 vp = fp->f_vnode;
2731 #ifdef AUDIT
2732 vn_lock(vp, LK_SHARED | LK_RETRY);
2733 AUDIT_ARG_VNODE1(vp);
2734 VOP_UNLOCK(vp);
2735 #endif
2736 return (setfmode(td, active_cred, vp, mode));
2737 }
2738
2739 int
vn_chown(struct file * fp,uid_t uid,gid_t gid,struct ucred * active_cred,struct thread * td)2740 vn_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
2741 struct thread *td)
2742 {
2743 struct vnode *vp;
2744
2745 vp = fp->f_vnode;
2746 #ifdef AUDIT
2747 vn_lock(vp, LK_SHARED | LK_RETRY);
2748 AUDIT_ARG_VNODE1(vp);
2749 VOP_UNLOCK(vp);
2750 #endif
2751 return (setfown(td, active_cred, vp, uid, gid));
2752 }
2753
2754 /*
2755 * Remove pages in the range ["start", "end") from the vnode's VM object. If
2756 * "end" is 0, then the range extends to the end of the object.
2757 */
2758 void
vn_pages_remove(struct vnode * vp,vm_pindex_t start,vm_pindex_t end)2759 vn_pages_remove(struct vnode *vp, vm_pindex_t start, vm_pindex_t end)
2760 {
2761 vm_object_t object;
2762
2763 if ((object = vp->v_object) == NULL)
2764 return;
2765 VM_OBJECT_WLOCK(object);
2766 vm_object_page_remove(object, start, end, 0);
2767 VM_OBJECT_WUNLOCK(object);
2768 }
2769
2770 /*
2771 * Like vn_pages_remove(), but skips invalid pages, which by definition are not
2772 * mapped into any process' address space. Filesystems may use this in
2773 * preference to vn_pages_remove() to avoid blocking on pages busied in
2774 * preparation for a VOP_GETPAGES.
2775 */
2776 void
vn_pages_remove_valid(struct vnode * vp,vm_pindex_t start,vm_pindex_t end)2777 vn_pages_remove_valid(struct vnode *vp, vm_pindex_t start, vm_pindex_t end)
2778 {
2779 vm_object_t object;
2780
2781 if ((object = vp->v_object) == NULL)
2782 return;
2783 VM_OBJECT_WLOCK(object);
2784 vm_object_page_remove(object, start, end, OBJPR_VALIDONLY);
2785 VM_OBJECT_WUNLOCK(object);
2786 }
2787
2788 int
vn_bmap_seekhole_locked(struct vnode * vp,u_long cmd,off_t * off,struct ucred * cred)2789 vn_bmap_seekhole_locked(struct vnode *vp, u_long cmd, off_t *off,
2790 struct ucred *cred)
2791 {
2792 off_t size;
2793 daddr_t bn, bnp;
2794 uint64_t bsize;
2795 off_t noff;
2796 int error;
2797
2798 KASSERT(cmd == FIOSEEKHOLE || cmd == FIOSEEKDATA,
2799 ("%s: Wrong command %lu", __func__, cmd));
2800 ASSERT_VOP_ELOCKED(vp, "vn_bmap_seekhole_locked");
2801
2802 if (vp->v_type != VREG) {
2803 error = ENOTTY;
2804 goto out;
2805 }
2806 error = vn_getsize_locked(vp, &size, cred);
2807 if (error != 0)
2808 goto out;
2809 noff = *off;
2810 if (noff < 0 || noff >= size) {
2811 error = ENXIO;
2812 goto out;
2813 }
2814
2815 /* See the comment in ufs_bmap_seekdata(). */
2816 vnode_pager_clean_sync(vp);
2817
2818 bsize = vp->v_mount->mnt_stat.f_iosize;
2819 for (bn = noff / bsize; noff < size; bn++, noff += bsize -
2820 noff % bsize) {
2821 error = VOP_BMAP(vp, bn, NULL, &bnp, NULL, NULL);
2822 if (error == EOPNOTSUPP) {
2823 error = ENOTTY;
2824 goto out;
2825 }
2826 if ((bnp == -1 && cmd == FIOSEEKHOLE) ||
2827 (bnp != -1 && cmd == FIOSEEKDATA)) {
2828 noff = bn * bsize;
2829 if (noff < *off)
2830 noff = *off;
2831 goto out;
2832 }
2833 }
2834 if (noff > size)
2835 noff = size;
2836 /* noff == size. There is an implicit hole at the end of file. */
2837 if (cmd == FIOSEEKDATA)
2838 error = ENXIO;
2839 out:
2840 if (error == 0)
2841 *off = noff;
2842 return (error);
2843 }
2844
2845 int
vn_bmap_seekhole(struct vnode * vp,u_long cmd,off_t * off,struct ucred * cred)2846 vn_bmap_seekhole(struct vnode *vp, u_long cmd, off_t *off, struct ucred *cred)
2847 {
2848 int error;
2849
2850 KASSERT(cmd == FIOSEEKHOLE || cmd == FIOSEEKDATA,
2851 ("%s: Wrong command %lu", __func__, cmd));
2852
2853 if (vn_lock(vp, LK_EXCLUSIVE) != 0)
2854 return (EBADF);
2855 error = vn_bmap_seekhole_locked(vp, cmd, off, cred);
2856 VOP_UNLOCK(vp);
2857 return (error);
2858 }
2859
2860 int
vn_seek(struct file * fp,off_t offset,int whence,struct thread * td)2861 vn_seek(struct file *fp, off_t offset, int whence, struct thread *td)
2862 {
2863 struct ucred *cred;
2864 struct vnode *vp;
2865 off_t foffset, fsize, size;
2866 int error, noneg;
2867
2868 cred = td->td_ucred;
2869 vp = fp->f_vnode;
2870 noneg = (vp->v_type != VCHR);
2871 /*
2872 * Try to dodge locking for common case of querying the offset.
2873 */
2874 if (whence == L_INCR && offset == 0) {
2875 foffset = foffset_read(fp);
2876 if (__predict_false(foffset < 0 && noneg)) {
2877 return (EOVERFLOW);
2878 }
2879 td->td_uretoff.tdu_off = foffset;
2880 return (0);
2881 }
2882 foffset = foffset_lock(fp, 0);
2883 error = 0;
2884 switch (whence) {
2885 case L_INCR:
2886 if (noneg &&
2887 (foffset < 0 ||
2888 (offset > 0 && foffset > OFF_MAX - offset))) {
2889 error = EOVERFLOW;
2890 break;
2891 }
2892 offset += foffset;
2893 break;
2894 case L_XTND:
2895 error = vn_getsize(vp, &fsize, cred);
2896 if (error != 0)
2897 break;
2898
2899 /*
2900 * If the file references a disk device, then fetch
2901 * the media size and use that to determine the ending
2902 * offset.
2903 */
2904 if (fsize == 0 && vp->v_type == VCHR &&
2905 fo_ioctl(fp, DIOCGMEDIASIZE, &size, cred, td) == 0)
2906 fsize = size;
2907 if (noneg && offset > 0 && fsize > OFF_MAX - offset) {
2908 error = EOVERFLOW;
2909 break;
2910 }
2911 offset += fsize;
2912 break;
2913 case L_SET:
2914 break;
2915 case SEEK_DATA:
2916 error = fo_ioctl(fp, FIOSEEKDATA, &offset, cred, td);
2917 if (error == ENOTTY)
2918 error = EINVAL;
2919 break;
2920 case SEEK_HOLE:
2921 error = fo_ioctl(fp, FIOSEEKHOLE, &offset, cred, td);
2922 if (error == ENOTTY)
2923 error = EINVAL;
2924 break;
2925 default:
2926 error = EINVAL;
2927 }
2928 if (error == 0 && noneg && offset < 0)
2929 error = EINVAL;
2930 if (error != 0)
2931 goto drop;
2932 VFS_KNOTE_UNLOCKED(vp, 0);
2933 td->td_uretoff.tdu_off = offset;
2934 drop:
2935 foffset_unlock(fp, offset, error != 0 ? FOF_NOUPDATE : 0);
2936 return (error);
2937 }
2938
2939 int
vn_utimes_perm(struct vnode * vp,struct vattr * vap,struct ucred * cred,struct thread * td)2940 vn_utimes_perm(struct vnode *vp, struct vattr *vap, struct ucred *cred,
2941 struct thread *td)
2942 {
2943 int error;
2944
2945 /*
2946 * Grant permission if the caller is the owner of the file, or
2947 * the super-user, or has ACL_WRITE_ATTRIBUTES permission on
2948 * on the file. If the time pointer is null, then write
2949 * permission on the file is also sufficient.
2950 *
2951 * From NFSv4.1, draft 21, 6.2.1.3.1, Discussion of Mask Attributes:
2952 * A user having ACL_WRITE_DATA or ACL_WRITE_ATTRIBUTES
2953 * will be allowed to set the times [..] to the current
2954 * server time.
2955 */
2956 error = VOP_ACCESSX(vp, VWRITE_ATTRIBUTES, cred, td);
2957 if (error != 0 && (vap->va_vaflags & VA_UTIMES_NULL) != 0)
2958 error = VOP_ACCESS(vp, VWRITE, cred, td);
2959 return (error);
2960 }
2961
2962 int
vn_fill_kinfo(struct file * fp,struct kinfo_file * kif,struct filedesc * fdp)2963 vn_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
2964 {
2965 struct vnode *vp;
2966 int error;
2967
2968 if (fp->f_type == DTYPE_FIFO)
2969 kif->kf_type = KF_TYPE_FIFO;
2970 else
2971 kif->kf_type = KF_TYPE_VNODE;
2972 vp = fp->f_vnode;
2973 vref(vp);
2974 FILEDESC_SUNLOCK(fdp);
2975 error = vn_fill_kinfo_vnode(vp, kif);
2976 vrele(vp);
2977 FILEDESC_SLOCK(fdp);
2978 return (error);
2979 }
2980
2981 static inline void
vn_fill_junk(struct kinfo_file * kif)2982 vn_fill_junk(struct kinfo_file *kif)
2983 {
2984 size_t len, olen;
2985
2986 /*
2987 * Simulate vn_fullpath returning changing values for a given
2988 * vp during e.g. coredump.
2989 */
2990 len = (arc4random() % (sizeof(kif->kf_path) - 2)) + 1;
2991 olen = strlen(kif->kf_path);
2992 if (len < olen)
2993 strcpy(&kif->kf_path[len - 1], "$");
2994 else
2995 for (; olen < len; olen++)
2996 strcpy(&kif->kf_path[olen], "A");
2997 }
2998
2999 int
vn_fill_kinfo_vnode(struct vnode * vp,struct kinfo_file * kif)3000 vn_fill_kinfo_vnode(struct vnode *vp, struct kinfo_file *kif)
3001 {
3002 struct vattr va;
3003 char *fullpath, *freepath;
3004 int error;
3005
3006 kif->kf_un.kf_file.kf_file_type = vntype_to_kinfo(vp->v_type);
3007 freepath = NULL;
3008 fullpath = "-";
3009 error = vn_fullpath(vp, &fullpath, &freepath);
3010 if (error == 0) {
3011 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
3012 }
3013 if (freepath != NULL)
3014 free(freepath, M_TEMP);
3015
3016 KFAIL_POINT_CODE(DEBUG_FP, fill_kinfo_vnode__random_path,
3017 vn_fill_junk(kif);
3018 );
3019
3020 /*
3021 * Retrieve vnode attributes.
3022 */
3023 va.va_fsid = VNOVAL;
3024 va.va_rdev = NODEV;
3025 vn_lock(vp, LK_SHARED | LK_RETRY);
3026 error = VOP_GETATTR(vp, &va, curthread->td_ucred);
3027 VOP_UNLOCK(vp);
3028 if (error != 0)
3029 return (error);
3030 if (va.va_fsid != VNOVAL)
3031 kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
3032 else
3033 kif->kf_un.kf_file.kf_file_fsid =
3034 vp->v_mount->mnt_stat.f_fsid.val[0];
3035 kif->kf_un.kf_file.kf_file_fsid_freebsd11 =
3036 kif->kf_un.kf_file.kf_file_fsid; /* truncate */
3037 kif->kf_un.kf_file.kf_file_fileid = va.va_fileid;
3038 kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode);
3039 kif->kf_un.kf_file.kf_file_size = va.va_size;
3040 kif->kf_un.kf_file.kf_file_rdev = va.va_rdev;
3041 kif->kf_un.kf_file.kf_file_rdev_freebsd11 =
3042 kif->kf_un.kf_file.kf_file_rdev; /* truncate */
3043 kif->kf_un.kf_file.kf_file_nlink = va.va_nlink;
3044 return (0);
3045 }
3046
3047 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)3048 vn_mmap(struct file *fp, vm_map_t map, vm_offset_t *addr, vm_size_t size,
3049 vm_prot_t prot, vm_prot_t cap_maxprot, int flags, vm_ooffset_t foff,
3050 struct thread *td)
3051 {
3052 #ifdef HWPMC_HOOKS
3053 struct pmckern_map_in pkm;
3054 #endif
3055 struct mount *mp;
3056 struct vnode *vp;
3057 vm_object_t object;
3058 vm_prot_t maxprot;
3059 boolean_t writecounted;
3060 int error;
3061
3062 #if defined(COMPAT_FREEBSD7) || defined(COMPAT_FREEBSD6) || \
3063 defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4)
3064 /*
3065 * POSIX shared-memory objects are defined to have
3066 * kernel persistence, and are not defined to support
3067 * read(2)/write(2) -- or even open(2). Thus, we can
3068 * use MAP_ASYNC to trade on-disk coherence for speed.
3069 * The shm_open(3) library routine turns on the FPOSIXSHM
3070 * flag to request this behavior.
3071 */
3072 if ((fp->f_flag & FPOSIXSHM) != 0)
3073 flags |= MAP_NOSYNC;
3074 #endif
3075 vp = fp->f_vnode;
3076
3077 /*
3078 * Ensure that file and memory protections are
3079 * compatible. Note that we only worry about
3080 * writability if mapping is shared; in this case,
3081 * current and max prot are dictated by the open file.
3082 * XXX use the vnode instead? Problem is: what
3083 * credentials do we use for determination? What if
3084 * proc does a setuid?
3085 */
3086 mp = vp->v_mount;
3087 if (mp != NULL && (mp->mnt_flag & MNT_NOEXEC) != 0) {
3088 maxprot = VM_PROT_NONE;
3089 if ((prot & VM_PROT_EXECUTE) != 0)
3090 return (EACCES);
3091 } else
3092 maxprot = VM_PROT_EXECUTE;
3093 if ((fp->f_flag & FREAD) != 0)
3094 maxprot |= VM_PROT_READ;
3095 else if ((prot & VM_PROT_READ) != 0)
3096 return (EACCES);
3097
3098 /*
3099 * If we are sharing potential changes via MAP_SHARED and we
3100 * are trying to get write permission although we opened it
3101 * without asking for it, bail out.
3102 */
3103 if ((flags & MAP_SHARED) != 0) {
3104 if ((fp->f_flag & FWRITE) != 0)
3105 maxprot |= VM_PROT_WRITE;
3106 else if ((prot & VM_PROT_WRITE) != 0)
3107 return (EACCES);
3108 } else {
3109 maxprot |= VM_PROT_WRITE;
3110 cap_maxprot |= VM_PROT_WRITE;
3111 }
3112 maxprot &= cap_maxprot;
3113
3114 /*
3115 * For regular files and shared memory, POSIX requires that
3116 * the value of foff be a legitimate offset within the data
3117 * object. In particular, negative offsets are invalid.
3118 * Blocking negative offsets and overflows here avoids
3119 * possible wraparound or user-level access into reserved
3120 * ranges of the data object later. In contrast, POSIX does
3121 * not dictate how offsets are used by device drivers, so in
3122 * the case of a device mapping a negative offset is passed
3123 * on.
3124 */
3125 if (
3126 #ifdef _LP64
3127 size > OFF_MAX ||
3128 #endif
3129 foff > OFF_MAX - size)
3130 return (EINVAL);
3131
3132 writecounted = FALSE;
3133 error = vm_mmap_vnode(td, size, prot, &maxprot, &flags, vp,
3134 &foff, &object, &writecounted);
3135 if (error != 0)
3136 return (error);
3137 error = vm_mmap_object(map, addr, size, prot, maxprot, flags, object,
3138 foff, writecounted, td);
3139 if (error != 0) {
3140 /*
3141 * If this mapping was accounted for in the vnode's
3142 * writecount, then undo that now.
3143 */
3144 if (writecounted)
3145 vm_pager_release_writecount(object, 0, size);
3146 vm_object_deallocate(object);
3147 }
3148 #ifdef HWPMC_HOOKS
3149 /* Inform hwpmc(4) if an executable is being mapped. */
3150 if (PMC_HOOK_INSTALLED(PMC_FN_MMAP)) {
3151 if ((prot & VM_PROT_EXECUTE) != 0 && error == 0) {
3152 pkm.pm_file = vp;
3153 pkm.pm_address = (uintptr_t) *addr;
3154 PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_MMAP, (void *) &pkm);
3155 }
3156 }
3157 #endif
3158
3159 #ifdef HWT_HOOKS
3160 if (HWT_HOOK_INSTALLED && (prot & VM_PROT_EXECUTE) != 0 &&
3161 error == 0) {
3162 struct hwt_record_entry ent;
3163 char *fullpath;
3164 char *freepath;
3165
3166 if (vn_fullpath(vp, &fullpath, &freepath) == 0) {
3167 ent.fullpath = fullpath;
3168 ent.addr = (uintptr_t) *addr;
3169 ent.record_type = HWT_RECORD_MMAP;
3170 HWT_CALL_HOOK(td, HWT_MMAP, &ent);
3171 free(freepath, M_TEMP);
3172 }
3173 }
3174 #endif
3175
3176 return (error);
3177 }
3178
3179 void
vn_fsid(struct vnode * vp,struct vattr * va)3180 vn_fsid(struct vnode *vp, struct vattr *va)
3181 {
3182 fsid_t *f;
3183
3184 f = &vp->v_mount->mnt_stat.f_fsid;
3185 va->va_fsid = (uint32_t)f->val[1];
3186 va->va_fsid <<= sizeof(f->val[1]) * NBBY;
3187 va->va_fsid += (uint32_t)f->val[0];
3188 }
3189
3190 int
vn_fsync_buf(struct vnode * vp,int waitfor)3191 vn_fsync_buf(struct vnode *vp, int waitfor)
3192 {
3193 struct buf *bp, *nbp;
3194 struct bufobj *bo;
3195 struct mount *mp;
3196 int error, maxretry;
3197
3198 error = 0;
3199 maxretry = 10000; /* large, arbitrarily chosen */
3200 mp = NULL;
3201 if (vp->v_type == VCHR) {
3202 VI_LOCK(vp);
3203 mp = vp->v_rdev->si_mountpt;
3204 VI_UNLOCK(vp);
3205 }
3206 bo = &vp->v_bufobj;
3207 BO_LOCK(bo);
3208 loop1:
3209 /*
3210 * MARK/SCAN initialization to avoid infinite loops.
3211 */
3212 TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
3213 bp->b_vflags &= ~BV_SCANNED;
3214 bp->b_error = 0;
3215 }
3216
3217 /*
3218 * Flush all dirty buffers associated with a vnode.
3219 */
3220 loop2:
3221 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
3222 if ((bp->b_vflags & BV_SCANNED) != 0)
3223 continue;
3224 bp->b_vflags |= BV_SCANNED;
3225 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL)) {
3226 if (waitfor != MNT_WAIT)
3227 continue;
3228 if (BUF_LOCK(bp,
3229 LK_EXCLUSIVE | LK_INTERLOCK | LK_SLEEPFAIL,
3230 BO_LOCKPTR(bo)) != 0) {
3231 BO_LOCK(bo);
3232 goto loop1;
3233 }
3234 BO_LOCK(bo);
3235 }
3236 BO_UNLOCK(bo);
3237 KASSERT(bp->b_bufobj == bo,
3238 ("bp %p wrong b_bufobj %p should be %p",
3239 bp, bp->b_bufobj, bo));
3240 if ((bp->b_flags & B_DELWRI) == 0)
3241 panic("fsync: not dirty");
3242 if ((vp->v_object != NULL) && (bp->b_flags & B_CLUSTEROK)) {
3243 vfs_bio_awrite(bp);
3244 } else {
3245 bremfree(bp);
3246 bawrite(bp);
3247 }
3248 if (maxretry < 1000)
3249 pause("dirty", hz < 1000 ? 1 : hz / 1000);
3250 BO_LOCK(bo);
3251 goto loop2;
3252 }
3253
3254 /*
3255 * If synchronous the caller expects us to completely resolve all
3256 * dirty buffers in the system. Wait for in-progress I/O to
3257 * complete (which could include background bitmap writes), then
3258 * retry if dirty blocks still exist.
3259 */
3260 if (waitfor == MNT_WAIT) {
3261 bufobj_wwait(bo, 0, 0);
3262 if (bo->bo_dirty.bv_cnt > 0) {
3263 /*
3264 * If we are unable to write any of these buffers
3265 * then we fail now rather than trying endlessly
3266 * to write them out.
3267 */
3268 TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
3269 if ((error = bp->b_error) != 0)
3270 break;
3271 if ((mp != NULL && mp->mnt_secondary_writes > 0) ||
3272 (error == 0 && --maxretry >= 0))
3273 goto loop1;
3274 if (error == 0)
3275 error = EAGAIN;
3276 }
3277 }
3278 BO_UNLOCK(bo);
3279 if (error != 0)
3280 vn_printf(vp, "fsync: giving up on dirty (error = %d) ", error);
3281
3282 return (error);
3283 }
3284
3285 /*
3286 * Copies a byte range from invp to outvp. Calls VOP_COPY_FILE_RANGE()
3287 * or vn_generic_copy_file_range() after rangelocking the byte ranges,
3288 * to do the actual copy.
3289 * vn_generic_copy_file_range() is factored out, so it can be called
3290 * from a VOP_COPY_FILE_RANGE() call as well, but handles vnodes from
3291 * different file systems.
3292 */
3293 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)3294 vn_copy_file_range(struct vnode *invp, off_t *inoffp, struct vnode *outvp,
3295 off_t *outoffp, size_t *lenp, unsigned int flags, struct ucred *incred,
3296 struct ucred *outcred, struct thread *fsize_td)
3297 {
3298 struct mount *inmp, *outmp;
3299 struct vnode *invpl, *outvpl;
3300 int error;
3301 size_t len;
3302 uint64_t uval;
3303
3304 invpl = outvpl = NULL;
3305 len = *lenp;
3306 *lenp = 0; /* For error returns. */
3307 error = 0;
3308
3309 /* Do some sanity checks on the arguments. */
3310 if (invp->v_type == VDIR || outvp->v_type == VDIR)
3311 error = EISDIR;
3312 else if (*inoffp < 0 || *outoffp < 0 ||
3313 invp->v_type != VREG || outvp->v_type != VREG)
3314 error = EINVAL;
3315 if (error != 0)
3316 goto out;
3317
3318 /* Ensure offset + len does not wrap around. */
3319 uval = *inoffp;
3320 uval += len;
3321 if (uval > INT64_MAX)
3322 len = INT64_MAX - *inoffp;
3323 uval = *outoffp;
3324 uval += len;
3325 if (uval > INT64_MAX)
3326 len = INT64_MAX - *outoffp;
3327 if (len == 0)
3328 goto out;
3329
3330 error = VOP_GETLOWVNODE(invp, &invpl, FREAD);
3331 if (error != 0)
3332 goto out;
3333 error = VOP_GETLOWVNODE(outvp, &outvpl, FWRITE);
3334 if (error != 0)
3335 goto out1;
3336
3337 inmp = invpl->v_mount;
3338 outmp = outvpl->v_mount;
3339 if (inmp == NULL || outmp == NULL)
3340 goto out2;
3341
3342 for (;;) {
3343 error = vfs_busy(inmp, 0);
3344 if (error != 0)
3345 goto out2;
3346 if (inmp == outmp)
3347 break;
3348 error = vfs_busy(outmp, MBF_NOWAIT);
3349 if (error != 0) {
3350 vfs_unbusy(inmp);
3351 error = vfs_busy(outmp, 0);
3352 if (error == 0) {
3353 vfs_unbusy(outmp);
3354 continue;
3355 }
3356 goto out2;
3357 }
3358 break;
3359 }
3360
3361 /*
3362 * If the two vnodes are for the same file system type, call
3363 * VOP_COPY_FILE_RANGE(), otherwise call vn_generic_copy_file_range()
3364 * which can handle copies across multiple file system types.
3365 */
3366 *lenp = len;
3367 if (inmp == outmp || inmp->mnt_vfc == outmp->mnt_vfc)
3368 error = VOP_COPY_FILE_RANGE(invpl, inoffp, outvpl, outoffp,
3369 lenp, flags, incred, outcred, fsize_td);
3370 else
3371 error = ENOSYS;
3372 if (error == ENOSYS)
3373 error = vn_generic_copy_file_range(invpl, inoffp, outvpl,
3374 outoffp, lenp, flags, incred, outcred, fsize_td);
3375 vfs_unbusy(outmp);
3376 if (inmp != outmp)
3377 vfs_unbusy(inmp);
3378 out2:
3379 if (outvpl != NULL)
3380 vrele(outvpl);
3381 out1:
3382 if (invpl != NULL)
3383 vrele(invpl);
3384 out:
3385 return (error);
3386 }
3387
3388 /*
3389 * Test len bytes of data starting at dat for all bytes == 0.
3390 * Return true if all bytes are zero, false otherwise.
3391 * Expects dat to be well aligned.
3392 */
3393 static bool
mem_iszero(void * dat,int len)3394 mem_iszero(void *dat, int len)
3395 {
3396 int i;
3397 const u_int *p;
3398 const char *cp;
3399
3400 for (p = dat; len > 0; len -= sizeof(*p), p++) {
3401 if (len >= sizeof(*p)) {
3402 if (*p != 0)
3403 return (false);
3404 } else {
3405 cp = (const char *)p;
3406 for (i = 0; i < len; i++, cp++)
3407 if (*cp != '\0')
3408 return (false);
3409 }
3410 }
3411 return (true);
3412 }
3413
3414 /*
3415 * Look for a hole in the output file and, if found, adjust *outoffp
3416 * and *xferp to skip past the hole.
3417 * *xferp is the entire hole length to be written and xfer2 is how many bytes
3418 * to be written as 0's upon return.
3419 */
3420 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)3421 vn_skip_hole(struct vnode *outvp, off_t xfer2, off_t *outoffp, off_t *xferp,
3422 off_t *dataoffp, off_t *holeoffp, struct ucred *cred)
3423 {
3424 int error;
3425 off_t delta;
3426
3427 if (*holeoffp == 0 || *holeoffp <= *outoffp) {
3428 *dataoffp = *outoffp;
3429 error = VOP_IOCTL(outvp, FIOSEEKDATA, dataoffp, 0, cred,
3430 curthread);
3431 if (error == 0) {
3432 *holeoffp = *dataoffp;
3433 error = VOP_IOCTL(outvp, FIOSEEKHOLE, holeoffp, 0, cred,
3434 curthread);
3435 }
3436 if (error != 0 || *holeoffp == *dataoffp) {
3437 /*
3438 * Since outvp is unlocked, it may be possible for
3439 * another thread to do a truncate(), lseek(), write()
3440 * creating a hole at startoff between the above
3441 * VOP_IOCTL() calls, if the other thread does not do
3442 * rangelocking.
3443 * If that happens, *holeoffp == *dataoffp and finding
3444 * the hole has failed, so disable vn_skip_hole().
3445 */
3446 *holeoffp = -1; /* Disable use of vn_skip_hole(). */
3447 return (xfer2);
3448 }
3449 KASSERT(*dataoffp >= *outoffp,
3450 ("vn_skip_hole: dataoff=%jd < outoff=%jd",
3451 (intmax_t)*dataoffp, (intmax_t)*outoffp));
3452 KASSERT(*holeoffp > *dataoffp,
3453 ("vn_skip_hole: holeoff=%jd <= dataoff=%jd",
3454 (intmax_t)*holeoffp, (intmax_t)*dataoffp));
3455 }
3456
3457 /*
3458 * If there is a hole before the data starts, advance *outoffp and
3459 * *xferp past the hole.
3460 */
3461 if (*dataoffp > *outoffp) {
3462 delta = *dataoffp - *outoffp;
3463 if (delta >= *xferp) {
3464 /* Entire *xferp is a hole. */
3465 *outoffp += *xferp;
3466 *xferp = 0;
3467 return (0);
3468 }
3469 *xferp -= delta;
3470 *outoffp += delta;
3471 xfer2 = MIN(xfer2, *xferp);
3472 }
3473
3474 /*
3475 * If a hole starts before the end of this xfer2, reduce this xfer2 so
3476 * that the write ends at the start of the hole.
3477 * *holeoffp should always be greater than *outoffp, but for the
3478 * non-INVARIANTS case, check this to make sure xfer2 remains a sane
3479 * value.
3480 */
3481 if (*holeoffp > *outoffp && *holeoffp < *outoffp + xfer2)
3482 xfer2 = *holeoffp - *outoffp;
3483 return (xfer2);
3484 }
3485
3486 /*
3487 * Write an xfer sized chunk to outvp in blksize blocks from dat.
3488 * dat is a maximum of blksize in length and can be written repeatedly in
3489 * the chunk.
3490 * If growfile == true, just grow the file via vn_truncate_locked() instead
3491 * of doing actual writes.
3492 * If checkhole == true, a hole is being punched, so skip over any hole
3493 * already in the output file.
3494 */
3495 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)3496 vn_write_outvp(struct vnode *outvp, char *dat, off_t outoff, off_t xfer,
3497 u_long blksize, bool growfile, bool checkhole, struct ucred *cred)
3498 {
3499 struct mount *mp;
3500 off_t dataoff, holeoff, xfer2;
3501 int error;
3502
3503 /*
3504 * Loop around doing writes of blksize until write has been completed.
3505 * Lock/unlock on each loop iteration so that a bwillwrite() can be
3506 * done for each iteration, since the xfer argument can be very
3507 * large if there is a large hole to punch in the output file.
3508 */
3509 error = 0;
3510 holeoff = 0;
3511 do {
3512 xfer2 = MIN(xfer, blksize);
3513 if (checkhole) {
3514 /*
3515 * Punching a hole. Skip writing if there is
3516 * already a hole in the output file.
3517 */
3518 xfer2 = vn_skip_hole(outvp, xfer2, &outoff, &xfer,
3519 &dataoff, &holeoff, cred);
3520 if (xfer == 0)
3521 break;
3522 if (holeoff < 0)
3523 checkhole = false;
3524 KASSERT(xfer2 > 0, ("vn_write_outvp: xfer2=%jd",
3525 (intmax_t)xfer2));
3526 }
3527 bwillwrite();
3528 mp = NULL;
3529 error = vn_start_write(outvp, &mp, V_WAIT);
3530 if (error != 0)
3531 break;
3532 if (growfile) {
3533 error = vn_lock(outvp, LK_EXCLUSIVE);
3534 if (error == 0) {
3535 error = vn_truncate_locked(outvp, outoff + xfer,
3536 false, cred);
3537 VOP_UNLOCK(outvp);
3538 }
3539 } else {
3540 error = vn_lock(outvp, vn_lktype_write(mp, outvp));
3541 if (error == 0) {
3542 error = vn_rdwr(UIO_WRITE, outvp, dat, xfer2,
3543 outoff, UIO_SYSSPACE, IO_NODELOCKED,
3544 curthread->td_ucred, cred, NULL, curthread);
3545 outoff += xfer2;
3546 xfer -= xfer2;
3547 VOP_UNLOCK(outvp);
3548 }
3549 }
3550 if (mp != NULL)
3551 vn_finished_write(mp);
3552 } while (!growfile && xfer > 0 && error == 0);
3553 return (error);
3554 }
3555
3556 /*
3557 * Copy a byte range of one file to another. This function can handle the
3558 * case where invp and outvp are on different file systems.
3559 * It can also be called by a VOP_COPY_FILE_RANGE() to do the work, if there
3560 * is no better file system specific way to do it.
3561 */
3562 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)3563 vn_generic_copy_file_range(struct vnode *invp, off_t *inoffp,
3564 struct vnode *outvp, off_t *outoffp, size_t *lenp, unsigned int flags,
3565 struct ucred *incred, struct ucred *outcred, struct thread *fsize_td)
3566 {
3567 struct vattr inva;
3568 struct mount *mp;
3569 off_t startoff, endoff, xfer, xfer2;
3570 u_long blksize;
3571 int error, interrupted;
3572 bool cantseek, readzeros, eof, first, lastblock, holetoeof, sparse;
3573 ssize_t aresid, r = 0;
3574 size_t copylen, len, savlen;
3575 off_t outsize;
3576 char *dat;
3577 long holein, holeout;
3578 struct timespec curts, endts;
3579
3580 holein = holeout = 0;
3581 savlen = len = *lenp;
3582 error = 0;
3583 interrupted = 0;
3584 dat = NULL;
3585
3586 if ((flags & COPY_FILE_RANGE_CLONE) != 0) {
3587 error = EOPNOTSUPP;
3588 goto out;
3589 }
3590
3591 error = vn_lock(invp, LK_SHARED);
3592 if (error != 0)
3593 goto out;
3594 if (VOP_PATHCONF(invp, _PC_MIN_HOLE_SIZE, &holein) != 0)
3595 holein = 0;
3596 error = VOP_GETATTR(invp, &inva, incred);
3597 if (error == 0 && inva.va_size > OFF_MAX)
3598 error = EFBIG;
3599 VOP_UNLOCK(invp);
3600 if (error != 0)
3601 goto out;
3602
3603 /*
3604 * Use va_bytes >= va_size as a hint that the file does not have
3605 * sufficient holes to justify the overhead of doing FIOSEEKHOLE.
3606 * This hint does not work well for file systems doing compression
3607 * and may fail when allocations for extended attributes increases
3608 * the value of va_bytes to >= va_size.
3609 */
3610 sparse = true;
3611 if (holein != 0 && inva.va_bytes >= inva.va_size) {
3612 holein = 0;
3613 sparse = false;
3614 }
3615
3616 mp = NULL;
3617 error = vn_start_write(outvp, &mp, V_WAIT);
3618 if (error == 0)
3619 error = vn_lock(outvp, LK_EXCLUSIVE);
3620 if (error == 0) {
3621 /*
3622 * If fsize_td != NULL, do a vn_rlimit_fsizex() call,
3623 * now that outvp is locked.
3624 */
3625 if (fsize_td != NULL) {
3626 struct uio io;
3627
3628 io.uio_offset = *outoffp;
3629 io.uio_resid = len;
3630 error = vn_rlimit_fsizex(outvp, &io, 0, &r, fsize_td);
3631 len = savlen = io.uio_resid;
3632 /*
3633 * No need to call vn_rlimit_fsizex_res before return,
3634 * since the uio is local.
3635 */
3636 }
3637 if (VOP_PATHCONF(outvp, _PC_MIN_HOLE_SIZE, &holeout) != 0)
3638 holeout = 0;
3639 /*
3640 * Holes that are past EOF do not need to be written as a block
3641 * of zero bytes. So, truncate the output file as far as
3642 * possible and then use size to decide if writing 0
3643 * bytes is necessary in the loop below.
3644 */
3645 if (error == 0)
3646 error = vn_getsize_locked(outvp, &outsize, outcred);
3647 if (error == 0 && outsize > *outoffp &&
3648 *outoffp <= OFF_MAX - len && outsize <= *outoffp + len &&
3649 *inoffp < inva.va_size &&
3650 *outoffp <= OFF_MAX - (inva.va_size - *inoffp) &&
3651 outsize <= *outoffp + (inva.va_size - *inoffp)) {
3652 #ifdef MAC
3653 error = mac_vnode_check_write(curthread->td_ucred,
3654 outcred, outvp);
3655 if (error == 0)
3656 #endif
3657 error = vn_truncate_locked(outvp, *outoffp,
3658 false, outcred);
3659 if (error == 0)
3660 outsize = *outoffp;
3661 }
3662 VOP_UNLOCK(outvp);
3663 }
3664 if (mp != NULL)
3665 vn_finished_write(mp);
3666 if (error != 0)
3667 goto out;
3668
3669 if (sparse && holein == 0 && holeout > 0) {
3670 /*
3671 * For this special case, the input data will be scanned
3672 * for blocks of all 0 bytes. For these blocks, the
3673 * write can be skipped for the output file to create
3674 * an unallocated region.
3675 * Therefore, use the appropriate size for the output file.
3676 */
3677 blksize = holeout;
3678 if (blksize <= 512) {
3679 /*
3680 * Use f_iosize, since ZFS reports a _PC_MIN_HOLE_SIZE
3681 * of 512, although it actually only creates
3682 * unallocated regions for blocks >= f_iosize.
3683 */
3684 blksize = outvp->v_mount->mnt_stat.f_iosize;
3685 }
3686 } else {
3687 /*
3688 * Use the larger of the two f_iosize values. If they are
3689 * not the same size, one will normally be an exact multiple of
3690 * the other, since they are both likely to be a power of 2.
3691 */
3692 blksize = MAX(invp->v_mount->mnt_stat.f_iosize,
3693 outvp->v_mount->mnt_stat.f_iosize);
3694 }
3695
3696 /* Clip to sane limits. */
3697 if (blksize < 4096)
3698 blksize = 4096;
3699 else if (blksize > maxphys)
3700 blksize = maxphys;
3701 dat = malloc(blksize, M_TEMP, M_WAITOK);
3702
3703 /*
3704 * If VOP_IOCTL(FIOSEEKHOLE) works for invp, use it and FIOSEEKDATA
3705 * to find holes. Otherwise, just scan the read block for all 0s
3706 * in the inner loop where the data copying is done.
3707 * Note that some file systems such as NFSv3, NFSv4.0 and NFSv4.1 may
3708 * support holes on the server, but do not support FIOSEEKHOLE.
3709 * The kernel flag COPY_FILE_RANGE_TIMEO1SEC is used to indicate
3710 * that this function should return after 1second with a partial
3711 * completion.
3712 */
3713 if ((flags & COPY_FILE_RANGE_TIMEO1SEC) != 0) {
3714 getnanouptime(&endts);
3715 endts.tv_sec++;
3716 } else
3717 timespecclear(&endts);
3718 first = true;
3719 holetoeof = eof = false;
3720 while (len > 0 && error == 0 && !eof && interrupted == 0) {
3721 endoff = 0; /* To shut up compilers. */
3722 cantseek = true;
3723 startoff = *inoffp;
3724 copylen = len;
3725
3726 /*
3727 * Find the next data area. If there is just a hole to EOF,
3728 * FIOSEEKDATA should fail with ENXIO.
3729 * (I do not know if any file system will report a hole to
3730 * EOF via FIOSEEKHOLE, but I am pretty sure FIOSEEKDATA
3731 * will fail for those file systems.)
3732 *
3733 * For input files that don't support FIOSEEKDATA/FIOSEEKHOLE,
3734 * the code just falls through to the inner copy loop.
3735 */
3736 error = EINVAL;
3737 if (holein > 0) {
3738 error = VOP_IOCTL(invp, FIOSEEKDATA, &startoff, 0,
3739 incred, curthread);
3740 if (error == ENXIO) {
3741 startoff = endoff = inva.va_size;
3742 eof = holetoeof = true;
3743 error = 0;
3744 }
3745 }
3746 if (error == 0 && !holetoeof) {
3747 endoff = startoff;
3748 error = VOP_IOCTL(invp, FIOSEEKHOLE, &endoff, 0,
3749 incred, curthread);
3750 /*
3751 * Since invp is unlocked, it may be possible for
3752 * another thread to do a truncate(), lseek(), write()
3753 * creating a hole at startoff between the above
3754 * VOP_IOCTL() calls, if the other thread does not do
3755 * rangelocking.
3756 * If that happens, startoff == endoff and finding
3757 * the hole has failed, so set an error.
3758 */
3759 if (error == 0 && startoff == endoff)
3760 error = EINVAL; /* Any error. Reset to 0. */
3761 }
3762 if (error == 0) {
3763 if (startoff > *inoffp) {
3764 /* Found hole before data block. */
3765 xfer = MIN(startoff - *inoffp, len);
3766 if (*outoffp < outsize) {
3767 /* Must write 0s to punch hole. */
3768 xfer2 = MIN(outsize - *outoffp,
3769 xfer);
3770 memset(dat, 0, MIN(xfer2, blksize));
3771 error = vn_write_outvp(outvp, dat,
3772 *outoffp, xfer2, blksize, false,
3773 holeout > 0, outcred);
3774 }
3775
3776 if (error == 0 && *outoffp + xfer >
3777 outsize && (xfer == len || holetoeof)) {
3778 /* Grow output file (hole at end). */
3779 error = vn_write_outvp(outvp, dat,
3780 *outoffp, xfer, blksize, true,
3781 false, outcred);
3782 }
3783 if (error == 0) {
3784 *inoffp += xfer;
3785 *outoffp += xfer;
3786 len -= xfer;
3787 if (len < savlen) {
3788 interrupted = sig_intr();
3789 if (timespecisset(&endts) &&
3790 interrupted == 0) {
3791 getnanouptime(&curts);
3792 if (timespeccmp(&curts,
3793 &endts, >=))
3794 interrupted =
3795 EINTR;
3796 }
3797 }
3798 }
3799 }
3800 copylen = MIN(len, endoff - startoff);
3801 cantseek = false;
3802 } else {
3803 cantseek = true;
3804 if (!sparse)
3805 cantseek = false;
3806 startoff = *inoffp;
3807 copylen = len;
3808 error = 0;
3809 }
3810
3811 xfer = blksize;
3812 if (cantseek) {
3813 /*
3814 * Set first xfer to end at a block boundary, so that
3815 * holes are more likely detected in the loop below via
3816 * the for all bytes 0 method.
3817 */
3818 xfer -= (*inoffp % blksize);
3819 }
3820
3821 /*
3822 * Loop copying the data block. If this was our first attempt
3823 * to copy anything, allow a zero-length block so that the VOPs
3824 * get a chance to update metadata, specifically the atime.
3825 */
3826 while (error == 0 && ((copylen > 0 && !eof) || first) &&
3827 interrupted == 0) {
3828 if (copylen < xfer)
3829 xfer = copylen;
3830 first = false;
3831 error = vn_lock(invp, LK_SHARED);
3832 if (error != 0)
3833 goto out;
3834 error = vn_rdwr(UIO_READ, invp, dat, xfer,
3835 startoff, UIO_SYSSPACE, IO_NODELOCKED,
3836 curthread->td_ucred, incred, &aresid,
3837 curthread);
3838 VOP_UNLOCK(invp);
3839 lastblock = false;
3840 if (error == 0 && (xfer == 0 || aresid > 0)) {
3841 /* Stop the copy at EOF on the input file. */
3842 xfer -= aresid;
3843 eof = true;
3844 lastblock = true;
3845 }
3846 if (error == 0) {
3847 /*
3848 * Skip the write for holes past the initial EOF
3849 * of the output file, unless this is the last
3850 * write of the output file at EOF.
3851 */
3852 readzeros = cantseek ? mem_iszero(dat, xfer) :
3853 false;
3854 if (xfer == len)
3855 lastblock = true;
3856 if (!cantseek || *outoffp < outsize ||
3857 lastblock || !readzeros)
3858 error = vn_write_outvp(outvp, dat,
3859 *outoffp, xfer, blksize,
3860 readzeros && lastblock &&
3861 *outoffp >= outsize, false,
3862 outcred);
3863 if (error == 0) {
3864 *inoffp += xfer;
3865 startoff += xfer;
3866 *outoffp += xfer;
3867 copylen -= xfer;
3868 len -= xfer;
3869 if (len < savlen) {
3870 interrupted = sig_intr();
3871 if (timespecisset(&endts) &&
3872 interrupted == 0) {
3873 getnanouptime(&curts);
3874 if (timespeccmp(&curts,
3875 &endts, >=))
3876 interrupted =
3877 EINTR;
3878 }
3879 }
3880 }
3881 }
3882 xfer = blksize;
3883 }
3884 }
3885 out:
3886 *lenp = savlen - len;
3887 free(dat, M_TEMP);
3888 return (error);
3889 }
3890
3891 static int
vn_fallocate(struct file * fp,off_t offset,off_t len,struct thread * td)3892 vn_fallocate(struct file *fp, off_t offset, off_t len, struct thread *td)
3893 {
3894 struct mount *mp;
3895 struct vnode *vp;
3896 off_t olen, ooffset;
3897 int error;
3898 #ifdef AUDIT
3899 int audited_vnode1 = 0;
3900 #endif
3901
3902 vp = fp->f_vnode;
3903 if (vp->v_type != VREG)
3904 return (ENODEV);
3905
3906 /* Allocating blocks may take a long time, so iterate. */
3907 for (;;) {
3908 olen = len;
3909 ooffset = offset;
3910
3911 bwillwrite();
3912 mp = NULL;
3913 error = vn_start_write(vp, &mp, V_WAIT | V_PCATCH);
3914 if (error != 0)
3915 break;
3916 error = vn_lock(vp, LK_EXCLUSIVE);
3917 if (error != 0) {
3918 vn_finished_write(mp);
3919 break;
3920 }
3921 #ifdef AUDIT
3922 if (!audited_vnode1) {
3923 AUDIT_ARG_VNODE1(vp);
3924 audited_vnode1 = 1;
3925 }
3926 #endif
3927 #ifdef MAC
3928 error = mac_vnode_check_write(td->td_ucred, fp->f_cred, vp);
3929 if (error == 0)
3930 #endif
3931 error = VOP_ALLOCATE(vp, &offset, &len, 0,
3932 td->td_ucred);
3933 VOP_UNLOCK(vp);
3934 vn_finished_write(mp);
3935
3936 if (olen + ooffset != offset + len) {
3937 panic("offset + len changed from %jx/%jx to %jx/%jx",
3938 ooffset, olen, offset, len);
3939 }
3940 if (error != 0 || len == 0)
3941 break;
3942 KASSERT(olen > len, ("Iteration did not make progress?"));
3943 maybe_yield();
3944 }
3945
3946 return (error);
3947 }
3948
3949 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)3950 vn_deallocate_impl(struct vnode *vp, off_t *offset, off_t *length, int flags,
3951 int ioflag, struct ucred *cred, struct ucred *active_cred,
3952 struct ucred *file_cred)
3953 {
3954 struct mount *mp;
3955 void *rl_cookie;
3956 off_t off, len;
3957 int error;
3958 #ifdef AUDIT
3959 bool audited_vnode1 = false;
3960 #endif
3961
3962 rl_cookie = NULL;
3963 error = 0;
3964 mp = NULL;
3965 off = *offset;
3966 len = *length;
3967
3968 if ((ioflag & (IO_NODELOCKED | IO_RANGELOCKED)) == 0)
3969 rl_cookie = vn_rangelock_wlock(vp, off, off + len);
3970 while (len > 0 && error == 0) {
3971 /*
3972 * Try to deallocate the longest range in one pass.
3973 * In case a pass takes too long to be executed, it returns
3974 * partial result. The residue will be proceeded in the next
3975 * pass.
3976 */
3977
3978 if ((ioflag & IO_NODELOCKED) == 0) {
3979 bwillwrite();
3980 if ((error = vn_start_write(vp, &mp,
3981 V_WAIT | V_PCATCH)) != 0)
3982 goto out;
3983 vn_lock(vp, vn_lktype_write(mp, vp) | LK_RETRY);
3984 }
3985 #ifdef AUDIT
3986 if (!audited_vnode1) {
3987 AUDIT_ARG_VNODE1(vp);
3988 audited_vnode1 = true;
3989 }
3990 #endif
3991
3992 #ifdef MAC
3993 if ((ioflag & IO_NOMACCHECK) == 0)
3994 error = mac_vnode_check_write(active_cred, file_cred,
3995 vp);
3996 #endif
3997 if (error == 0)
3998 error = VOP_DEALLOCATE(vp, &off, &len, flags, ioflag,
3999 cred);
4000
4001 if ((ioflag & IO_NODELOCKED) == 0) {
4002 VOP_UNLOCK(vp);
4003 if (mp != NULL) {
4004 vn_finished_write(mp);
4005 mp = NULL;
4006 }
4007 }
4008 if (error == 0 && len != 0)
4009 maybe_yield();
4010 }
4011 out:
4012 if (rl_cookie != NULL)
4013 vn_rangelock_unlock(vp, rl_cookie);
4014 *offset = off;
4015 *length = len;
4016 return (error);
4017 }
4018
4019 /*
4020 * This function is supposed to be used in the situations where the deallocation
4021 * is not triggered by a user request.
4022 */
4023 int
vn_deallocate(struct vnode * vp,off_t * offset,off_t * length,int flags,int ioflag,struct ucred * active_cred,struct ucred * file_cred)4024 vn_deallocate(struct vnode *vp, off_t *offset, off_t *length, int flags,
4025 int ioflag, struct ucred *active_cred, struct ucred *file_cred)
4026 {
4027 struct ucred *cred;
4028
4029 if (*offset < 0 || *length <= 0 || *length > OFF_MAX - *offset ||
4030 flags != 0)
4031 return (EINVAL);
4032 if (vp->v_type != VREG)
4033 return (ENODEV);
4034
4035 cred = file_cred != NOCRED ? file_cred : active_cred;
4036 return (vn_deallocate_impl(vp, offset, length, flags, ioflag, cred,
4037 active_cred, file_cred));
4038 }
4039
4040 static int
vn_fspacectl(struct file * fp,int cmd,off_t * offset,off_t * length,int flags,struct ucred * active_cred,struct thread * td)4041 vn_fspacectl(struct file *fp, int cmd, off_t *offset, off_t *length, int flags,
4042 struct ucred *active_cred, struct thread *td)
4043 {
4044 int error;
4045 struct vnode *vp;
4046 int ioflag;
4047
4048 KASSERT(cmd == SPACECTL_DEALLOC, ("vn_fspacectl: Invalid cmd"));
4049 KASSERT((flags & ~SPACECTL_F_SUPPORTED) == 0,
4050 ("vn_fspacectl: non-zero flags"));
4051 KASSERT(*offset >= 0 && *length > 0 && *length <= OFF_MAX - *offset,
4052 ("vn_fspacectl: offset/length overflow or underflow"));
4053 vp = fp->f_vnode;
4054
4055 if (vp->v_type != VREG)
4056 return (ENODEV);
4057
4058 ioflag = get_write_ioflag(fp);
4059
4060 switch (cmd) {
4061 case SPACECTL_DEALLOC:
4062 error = vn_deallocate_impl(vp, offset, length, flags, ioflag,
4063 active_cred, active_cred, fp->f_cred);
4064 break;
4065 default:
4066 panic("vn_fspacectl: unknown cmd %d", cmd);
4067 }
4068
4069 return (error);
4070 }
4071
4072 /*
4073 * Keep this assert as long as sizeof(struct dirent) is used as the maximum
4074 * entry size.
4075 */
4076 _Static_assert(_GENERIC_MAXDIRSIZ == sizeof(struct dirent),
4077 "'struct dirent' size must be a multiple of its alignment "
4078 "(see _GENERIC_DIRLEN())");
4079
4080 /*
4081 * Returns successive directory entries through some caller's provided buffer.
4082 *
4083 * This function automatically refills the provided buffer with calls to
4084 * VOP_READDIR() (after MAC permission checks).
4085 *
4086 * 'td' is used for credentials and passed to uiomove(). 'dirbuf' is the
4087 * caller's buffer to fill and 'dirbuflen' its allocated size. 'dirbuf' must
4088 * be properly aligned to access 'struct dirent' structures and 'dirbuflen'
4089 * must be greater than GENERIC_MAXDIRSIZ to avoid VOP_READDIR() returning
4090 * EINVAL (the latter is not a strong guarantee (yet); but EINVAL will always
4091 * be returned if this requirement is not verified). '*dpp' points to the
4092 * current directory entry in the buffer and '*len' contains the remaining
4093 * valid bytes in 'dirbuf' after 'dpp' (including the pointed entry).
4094 *
4095 * At first call (or when restarting the read), '*len' must have been set to 0,
4096 * '*off' to 0 (or any valid start offset) and '*eofflag' to 0. There are no
4097 * more entries as soon as '*len' is 0 after a call that returned 0. Calling
4098 * again this function after such a condition is considered an error and EINVAL
4099 * will be returned. Other possible error codes are those of VOP_READDIR(),
4100 * EINTEGRITY if the returned entries do not pass coherency tests, or EINVAL
4101 * (bad call). All errors are unrecoverable, i.e., the state ('*len', '*off'
4102 * and '*eofflag') must be re-initialized before a subsequent call. On error
4103 * or at end of directory, '*dpp' is reset to NULL.
4104 *
4105 * '*len', '*off' and '*eofflag' are internal state the caller should not
4106 * tamper with except as explained above. '*off' is the next directory offset
4107 * to read from to refill the buffer. '*eofflag' is set to 0 or 1 by the last
4108 * internal call to VOP_READDIR() that returned without error, indicating
4109 * whether it reached the end of the directory, and to 2 by this function after
4110 * all entries have been read.
4111 */
4112 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)4113 vn_dir_next_dirent(struct vnode *vp, struct thread *td,
4114 char *dirbuf, size_t dirbuflen,
4115 struct dirent **dpp, size_t *len, off_t *off, int *eofflag)
4116 {
4117 struct dirent *dp = NULL;
4118 int reclen;
4119 int error;
4120 struct uio uio;
4121 struct iovec iov;
4122
4123 ASSERT_VOP_LOCKED(vp, "vnode not locked");
4124 VNASSERT(vp->v_type == VDIR, vp, ("vnode is not a directory"));
4125 MPASS2((uintptr_t)dirbuf < (uintptr_t)dirbuf + dirbuflen,
4126 "Address space overflow");
4127
4128 if (__predict_false(dirbuflen < GENERIC_MAXDIRSIZ)) {
4129 /* Don't take any chances in this case */
4130 error = EINVAL;
4131 goto out;
4132 }
4133
4134 if (*len != 0) {
4135 dp = *dpp;
4136
4137 /*
4138 * The caller continued to call us after an error (we set dp to
4139 * NULL in a previous iteration). Bail out right now.
4140 */
4141 if (__predict_false(dp == NULL))
4142 return (EINVAL);
4143
4144 MPASS(*len <= dirbuflen);
4145 MPASS2((uintptr_t)dirbuf <= (uintptr_t)dp &&
4146 (uintptr_t)dp + *len <= (uintptr_t)dirbuf + dirbuflen,
4147 "Filled range not inside buffer");
4148
4149 reclen = dp->d_reclen;
4150 if (reclen >= *len) {
4151 /* End of buffer reached */
4152 *len = 0;
4153 } else {
4154 dp = (struct dirent *)((char *)dp + reclen);
4155 *len -= reclen;
4156 }
4157 }
4158
4159 if (*len == 0) {
4160 dp = NULL;
4161
4162 /* Have to refill. */
4163 switch (*eofflag) {
4164 case 0:
4165 break;
4166
4167 case 1:
4168 /* Nothing more to read. */
4169 *eofflag = 2; /* Remember the caller reached EOF. */
4170 goto success;
4171
4172 default:
4173 /* The caller didn't test for EOF. */
4174 error = EINVAL;
4175 goto out;
4176 }
4177
4178 iov.iov_base = dirbuf;
4179 iov.iov_len = dirbuflen;
4180
4181 uio.uio_iov = &iov;
4182 uio.uio_iovcnt = 1;
4183 uio.uio_offset = *off;
4184 uio.uio_resid = dirbuflen;
4185 uio.uio_segflg = UIO_SYSSPACE;
4186 uio.uio_rw = UIO_READ;
4187 uio.uio_td = td;
4188
4189 #ifdef MAC
4190 error = mac_vnode_check_readdir(td->td_ucred, vp);
4191 if (error == 0)
4192 #endif
4193 error = VOP_READDIR(vp, &uio, td->td_ucred, eofflag,
4194 NULL, NULL);
4195 if (error != 0)
4196 goto out;
4197
4198 *len = dirbuflen - uio.uio_resid;
4199 *off = uio.uio_offset;
4200
4201 if (*len == 0) {
4202 /* Sanity check on INVARIANTS. */
4203 MPASS(*eofflag != 0);
4204 *eofflag = 1;
4205 goto success;
4206 }
4207
4208 /*
4209 * Normalize the flag returned by VOP_READDIR(), since we use 2
4210 * as a sentinel value.
4211 */
4212 if (*eofflag != 0)
4213 *eofflag = 1;
4214
4215 dp = (struct dirent *)dirbuf;
4216 }
4217
4218 if (__predict_false(*len < GENERIC_MINDIRSIZ ||
4219 dp->d_reclen < GENERIC_MINDIRSIZ)) {
4220 error = EINTEGRITY;
4221 dp = NULL;
4222 goto out;
4223 }
4224
4225 success:
4226 error = 0;
4227 out:
4228 *dpp = dp;
4229 return (error);
4230 }
4231
4232 /*
4233 * Checks whether a directory is empty or not.
4234 *
4235 * If the directory is empty, returns 0, and if it is not, ENOTEMPTY. Other
4236 * values are genuine errors preventing the check.
4237 */
4238 int
vn_dir_check_empty(struct vnode * vp)4239 vn_dir_check_empty(struct vnode *vp)
4240 {
4241 struct thread *const td = curthread;
4242 char *dirbuf;
4243 size_t dirbuflen, len;
4244 off_t off;
4245 int eofflag, error;
4246 struct dirent *dp;
4247 struct vattr va;
4248
4249 ASSERT_VOP_LOCKED(vp, "vfs_emptydir");
4250 VNPASS(vp->v_type == VDIR, vp);
4251
4252 error = VOP_GETATTR(vp, &va, td->td_ucred);
4253 if (error != 0)
4254 return (error);
4255
4256 dirbuflen = max(DEV_BSIZE, GENERIC_MAXDIRSIZ);
4257 if (dirbuflen < va.va_blocksize)
4258 dirbuflen = va.va_blocksize;
4259 dirbuf = malloc(dirbuflen, M_TEMP, M_WAITOK);
4260
4261 len = 0;
4262 off = 0;
4263 eofflag = 0;
4264
4265 for (;;) {
4266 error = vn_dir_next_dirent(vp, td, dirbuf, dirbuflen,
4267 &dp, &len, &off, &eofflag);
4268 if (error != 0)
4269 goto end;
4270
4271 if (len == 0) {
4272 /* EOF */
4273 error = 0;
4274 goto end;
4275 }
4276
4277 /*
4278 * Skip whiteouts. Unionfs operates on filesystems only and
4279 * not on hierarchies, so these whiteouts would be shadowed on
4280 * the system hierarchy but not for a union using the
4281 * filesystem of their directories as the upper layer.
4282 * Additionally, unionfs currently transparently exposes
4283 * union-specific metadata of its upper layer, meaning that
4284 * whiteouts can be seen through the union view in empty
4285 * directories. Taking into account these whiteouts would then
4286 * prevent mounting another filesystem on such effectively
4287 * empty directories.
4288 */
4289 if (dp->d_type == DT_WHT)
4290 continue;
4291
4292 /*
4293 * Any file in the directory which is not '.' or '..' indicates
4294 * the directory is not empty.
4295 */
4296 switch (dp->d_namlen) {
4297 case 2:
4298 if (dp->d_name[1] != '.') {
4299 /* Can't be '..' (nor '.') */
4300 error = ENOTEMPTY;
4301 goto end;
4302 }
4303 /* FALLTHROUGH */
4304 case 1:
4305 if (dp->d_name[0] != '.') {
4306 /* Can't be '..' nor '.' */
4307 error = ENOTEMPTY;
4308 goto end;
4309 }
4310 break;
4311
4312 default:
4313 error = ENOTEMPTY;
4314 goto end;
4315 }
4316 }
4317
4318 end:
4319 free(dirbuf, M_TEMP);
4320 return (error);
4321 }
4322
4323
4324 static u_long vn_lock_pair_pause_cnt;
4325 SYSCTL_ULONG(_debug, OID_AUTO, vn_lock_pair_pause, CTLFLAG_RD,
4326 &vn_lock_pair_pause_cnt, 0,
4327 "Count of vn_lock_pair deadlocks");
4328
4329 u_int vn_lock_pair_pause_max;
4330 SYSCTL_UINT(_debug, OID_AUTO, vn_lock_pair_pause_max, CTLFLAG_RW,
4331 &vn_lock_pair_pause_max, 0,
4332 "Max ticks for vn_lock_pair deadlock avoidance sleep");
4333
4334 static void
vn_lock_pair_pause(const char * wmesg)4335 vn_lock_pair_pause(const char *wmesg)
4336 {
4337 atomic_add_long(&vn_lock_pair_pause_cnt, 1);
4338 pause(wmesg, prng32_bounded(vn_lock_pair_pause_max));
4339 }
4340
4341 /*
4342 * Lock pair of (possibly same) vnodes vp1, vp2, avoiding lock order
4343 * reversal. vp1_locked indicates whether vp1 is locked; if not, vp1
4344 * must be unlocked. Same for vp2 and vp2_locked. One of the vnodes
4345 * can be NULL.
4346 *
4347 * The function returns with both vnodes exclusively or shared locked,
4348 * according to corresponding lkflags, and guarantees that it does not
4349 * create lock order reversal with other threads during its execution.
4350 * Both vnodes could be unlocked temporary (and reclaimed).
4351 *
4352 * If requesting shared locking, locked vnode lock must not be recursed.
4353 *
4354 * Only one of LK_SHARED and LK_EXCLUSIVE must be specified.
4355 * LK_NODDLKTREAT can be optionally passed.
4356 *
4357 * If vp1 == vp2, only one, most exclusive, lock is obtained on it.
4358 */
4359 void
vn_lock_pair(struct vnode * vp1,bool vp1_locked,int lkflags1,struct vnode * vp2,bool vp2_locked,int lkflags2)4360 vn_lock_pair(struct vnode *vp1, bool vp1_locked, int lkflags1,
4361 struct vnode *vp2, bool vp2_locked, int lkflags2)
4362 {
4363 int error, locked1;
4364
4365 MPASS((((lkflags1 & LK_SHARED) != 0) ^ ((lkflags1 & LK_EXCLUSIVE) != 0)) ||
4366 (vp1 == NULL && lkflags1 == 0));
4367 MPASS((lkflags1 & ~(LK_SHARED | LK_EXCLUSIVE | LK_NODDLKTREAT)) == 0);
4368 MPASS((((lkflags2 & LK_SHARED) != 0) ^ ((lkflags2 & LK_EXCLUSIVE) != 0)) ||
4369 (vp2 == NULL && lkflags2 == 0));
4370 MPASS((lkflags2 & ~(LK_SHARED | LK_EXCLUSIVE | LK_NODDLKTREAT)) == 0);
4371
4372 if (vp1 == NULL && vp2 == NULL)
4373 return;
4374
4375 if (vp1 == vp2) {
4376 MPASS(vp1_locked == vp2_locked);
4377
4378 /* Select the most exclusive mode for lock. */
4379 if ((lkflags1 & LK_TYPE_MASK) != (lkflags2 & LK_TYPE_MASK))
4380 lkflags1 = (lkflags1 & ~LK_SHARED) | LK_EXCLUSIVE;
4381
4382 if (vp1_locked) {
4383 ASSERT_VOP_LOCKED(vp1, "vp1");
4384
4385 /* No need to relock if any lock is exclusive. */
4386 if ((vp1->v_vnlock->lock_object.lo_flags &
4387 LK_NOSHARE) != 0)
4388 return;
4389
4390 locked1 = VOP_ISLOCKED(vp1);
4391 if (((lkflags1 & LK_SHARED) != 0 &&
4392 locked1 != LK_EXCLUSIVE) ||
4393 ((lkflags1 & LK_EXCLUSIVE) != 0 &&
4394 locked1 == LK_EXCLUSIVE))
4395 return;
4396 VOP_UNLOCK(vp1);
4397 }
4398
4399 ASSERT_VOP_UNLOCKED(vp1, "vp1");
4400 vn_lock(vp1, lkflags1 | LK_RETRY);
4401 return;
4402 }
4403
4404 if (vp1 != NULL) {
4405 if ((lkflags1 & LK_SHARED) != 0 &&
4406 (vp1->v_vnlock->lock_object.lo_flags & LK_NOSHARE) != 0)
4407 lkflags1 = (lkflags1 & ~LK_SHARED) | LK_EXCLUSIVE;
4408 if (vp1_locked && VOP_ISLOCKED(vp1) != LK_EXCLUSIVE) {
4409 ASSERT_VOP_LOCKED(vp1, "vp1");
4410 if ((lkflags1 & LK_EXCLUSIVE) != 0) {
4411 VOP_UNLOCK(vp1);
4412 ASSERT_VOP_UNLOCKED(vp1,
4413 "vp1 shared recursed");
4414 vp1_locked = false;
4415 }
4416 } else if (!vp1_locked)
4417 ASSERT_VOP_UNLOCKED(vp1, "vp1");
4418 } else {
4419 vp1_locked = true;
4420 }
4421
4422 if (vp2 != NULL) {
4423 if ((lkflags2 & LK_SHARED) != 0 &&
4424 (vp2->v_vnlock->lock_object.lo_flags & LK_NOSHARE) != 0)
4425 lkflags2 = (lkflags2 & ~LK_SHARED) | LK_EXCLUSIVE;
4426 if (vp2_locked && VOP_ISLOCKED(vp2) != LK_EXCLUSIVE) {
4427 ASSERT_VOP_LOCKED(vp2, "vp2");
4428 if ((lkflags2 & LK_EXCLUSIVE) != 0) {
4429 VOP_UNLOCK(vp2);
4430 ASSERT_VOP_UNLOCKED(vp2,
4431 "vp2 shared recursed");
4432 vp2_locked = false;
4433 }
4434 } else if (!vp2_locked)
4435 ASSERT_VOP_UNLOCKED(vp2, "vp2");
4436 } else {
4437 vp2_locked = true;
4438 }
4439
4440 if (!vp1_locked && !vp2_locked) {
4441 vn_lock(vp1, lkflags1 | LK_RETRY);
4442 vp1_locked = true;
4443 }
4444
4445 while (!vp1_locked || !vp2_locked) {
4446 if (vp1_locked && vp2 != NULL) {
4447 if (vp1 != NULL) {
4448 error = VOP_LOCK1(vp2, lkflags2 | LK_NOWAIT,
4449 __FILE__, __LINE__);
4450 if (error == 0)
4451 break;
4452 VOP_UNLOCK(vp1);
4453 vp1_locked = false;
4454 vn_lock_pair_pause("vlp1");
4455 }
4456 vn_lock(vp2, lkflags2 | LK_RETRY);
4457 vp2_locked = true;
4458 }
4459 if (vp2_locked && vp1 != NULL) {
4460 if (vp2 != NULL) {
4461 error = VOP_LOCK1(vp1, lkflags1 | LK_NOWAIT,
4462 __FILE__, __LINE__);
4463 if (error == 0)
4464 break;
4465 VOP_UNLOCK(vp2);
4466 vp2_locked = false;
4467 vn_lock_pair_pause("vlp2");
4468 }
4469 vn_lock(vp1, lkflags1 | LK_RETRY);
4470 vp1_locked = true;
4471 }
4472 }
4473 if (vp1 != NULL) {
4474 if (lkflags1 == LK_EXCLUSIVE)
4475 ASSERT_VOP_ELOCKED(vp1, "vp1 ret");
4476 else
4477 ASSERT_VOP_LOCKED(vp1, "vp1 ret");
4478 }
4479 if (vp2 != NULL) {
4480 if (lkflags2 == LK_EXCLUSIVE)
4481 ASSERT_VOP_ELOCKED(vp2, "vp2 ret");
4482 else
4483 ASSERT_VOP_LOCKED(vp2, "vp2 ret");
4484 }
4485 }
4486
4487 int
vn_lktype_write(struct mount * mp,struct vnode * vp)4488 vn_lktype_write(struct mount *mp, struct vnode *vp)
4489 {
4490 if (MNT_SHARED_WRITES(mp) ||
4491 (mp == NULL && MNT_SHARED_WRITES(vp->v_mount)))
4492 return (LK_SHARED);
4493 return (LK_EXCLUSIVE);
4494 }
4495
4496 int
vn_cmp(struct file * fp1,struct file * fp2,struct thread * td)4497 vn_cmp(struct file *fp1, struct file *fp2, struct thread *td)
4498 {
4499 if (fp2->f_type != DTYPE_VNODE)
4500 return (3);
4501 return (kcmp_cmp((uintptr_t)fp1->f_vnode, (uintptr_t)fp2->f_vnode));
4502 }
4503