xref: /freebsd/sys/kern/vfs_syscalls.c (revision eb24e1491f9900e922c78e53af588f22a3e9535f)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 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  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	@(#)vfs_syscalls.c	8.13 (Berkeley) 4/15/94
37  */
38 
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
41 
42 #include "opt_capsicum.h"
43 #include "opt_ktrace.h"
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/bio.h>
48 #include <sys/buf.h>
49 #include <sys/capsicum.h>
50 #include <sys/disk.h>
51 #include <sys/sysent.h>
52 #include <sys/malloc.h>
53 #include <sys/mount.h>
54 #include <sys/mutex.h>
55 #include <sys/sysproto.h>
56 #include <sys/namei.h>
57 #include <sys/filedesc.h>
58 #include <sys/kernel.h>
59 #include <sys/fcntl.h>
60 #include <sys/file.h>
61 #include <sys/filio.h>
62 #include <sys/limits.h>
63 #include <sys/linker.h>
64 #include <sys/rwlock.h>
65 #include <sys/sdt.h>
66 #include <sys/stat.h>
67 #include <sys/sx.h>
68 #include <sys/unistd.h>
69 #include <sys/vnode.h>
70 #include <sys/priv.h>
71 #include <sys/proc.h>
72 #include <sys/dirent.h>
73 #include <sys/jail.h>
74 #include <sys/syscallsubr.h>
75 #include <sys/sysctl.h>
76 #ifdef KTRACE
77 #include <sys/ktrace.h>
78 #endif
79 
80 #include <machine/stdarg.h>
81 
82 #include <security/audit/audit.h>
83 #include <security/mac/mac_framework.h>
84 
85 #include <vm/vm.h>
86 #include <vm/vm_object.h>
87 #include <vm/vm_page.h>
88 #include <vm/uma.h>
89 
90 #include <ufs/ufs/quota.h>
91 
92 MALLOC_DEFINE(M_FADVISE, "fadvise", "posix_fadvise(2) information");
93 
94 SDT_PROVIDER_DEFINE(vfs);
95 SDT_PROBE_DEFINE2(vfs, , stat, mode, "char *", "int");
96 SDT_PROBE_DEFINE2(vfs, , stat, reg, "char *", "int");
97 
98 static int kern_chflagsat(struct thread *td, int fd, const char *path,
99     enum uio_seg pathseg, u_long flags, int atflag);
100 static int setfflags(struct thread *td, struct vnode *, u_long);
101 static int getutimes(const struct timeval *, enum uio_seg, struct timespec *);
102 static int getutimens(const struct timespec *, enum uio_seg,
103     struct timespec *, int *);
104 static int setutimes(struct thread *td, struct vnode *,
105     const struct timespec *, int, int);
106 static int vn_access(struct vnode *vp, int user_flags, struct ucred *cred,
107     struct thread *td);
108 static int kern_fhlinkat(struct thread *td, int fd, const char *path,
109     enum uio_seg pathseg, fhandle_t *fhp);
110 static int kern_getfhat(struct thread *td, int flags, int fd,
111     const char *path, enum uio_seg pathseg, fhandle_t *fhp);
112 static int kern_readlink_vp(struct vnode *vp, char *buf, enum uio_seg bufseg,
113     size_t count, struct thread *td);
114 static int kern_linkat_vp(struct thread *td, struct vnode *vp, int fd,
115     const char *path, enum uio_seg segflag);
116 
117 int
118 kern_sync(struct thread *td)
119 {
120 	struct mount *mp, *nmp;
121 	int save;
122 
123 	mtx_lock(&mountlist_mtx);
124 	for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
125 		if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK)) {
126 			nmp = TAILQ_NEXT(mp, mnt_list);
127 			continue;
128 		}
129 		if ((mp->mnt_flag & MNT_RDONLY) == 0 &&
130 		    vn_start_write(NULL, &mp, V_NOWAIT) == 0) {
131 			save = curthread_pflags_set(TDP_SYNCIO);
132 			vfs_periodic(mp, MNT_NOWAIT);
133 			VFS_SYNC(mp, MNT_NOWAIT);
134 			curthread_pflags_restore(save);
135 			vn_finished_write(mp);
136 		}
137 		mtx_lock(&mountlist_mtx);
138 		nmp = TAILQ_NEXT(mp, mnt_list);
139 		vfs_unbusy(mp);
140 	}
141 	mtx_unlock(&mountlist_mtx);
142 	return (0);
143 }
144 
145 /*
146  * Sync each mounted filesystem.
147  */
148 #ifndef _SYS_SYSPROTO_H_
149 struct sync_args {
150 	int     dummy;
151 };
152 #endif
153 /* ARGSUSED */
154 int
155 sys_sync(struct thread *td, struct sync_args *uap)
156 {
157 
158 	return (kern_sync(td));
159 }
160 
161 /*
162  * Change filesystem quotas.
163  */
164 #ifndef _SYS_SYSPROTO_H_
165 struct quotactl_args {
166 	char *path;
167 	int cmd;
168 	int uid;
169 	caddr_t arg;
170 };
171 #endif
172 int
173 sys_quotactl(struct thread *td, struct quotactl_args *uap)
174 {
175 	struct mount *mp;
176 	struct nameidata nd;
177 	int error;
178 
179 	AUDIT_ARG_CMD(uap->cmd);
180 	AUDIT_ARG_UID(uap->uid);
181 	if (!prison_allow(td->td_ucred, PR_ALLOW_QUOTAS))
182 		return (EPERM);
183 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1, UIO_USERSPACE,
184 	    uap->path, td);
185 	if ((error = namei(&nd)) != 0)
186 		return (error);
187 	NDFREE(&nd, NDF_ONLY_PNBUF);
188 	mp = nd.ni_vp->v_mount;
189 	vfs_ref(mp);
190 	vput(nd.ni_vp);
191 	error = vfs_busy(mp, 0);
192 	if (error != 0) {
193 		vfs_rel(mp);
194 		return (error);
195 	}
196 	error = VFS_QUOTACTL(mp, uap->cmd, uap->uid, uap->arg);
197 
198 	/*
199 	 * Since quota on operation typically needs to open quota
200 	 * file, the Q_QUOTAON handler needs to unbusy the mount point
201 	 * before calling into namei.  Otherwise, unmount might be
202 	 * started between two vfs_busy() invocations (first is our,
203 	 * second is from mount point cross-walk code in lookup()),
204 	 * causing deadlock.
205 	 *
206 	 * Require that Q_QUOTAON handles the vfs_busy() reference on
207 	 * its own, always returning with ubusied mount point.
208 	 */
209 	if ((uap->cmd >> SUBCMDSHIFT) != Q_QUOTAON &&
210 	    (uap->cmd >> SUBCMDSHIFT) != Q_QUOTAOFF)
211 		vfs_unbusy(mp);
212 	vfs_rel(mp);
213 	return (error);
214 }
215 
216 /*
217  * Used by statfs conversion routines to scale the block size up if
218  * necessary so that all of the block counts are <= 'max_size'.  Note
219  * that 'max_size' should be a bitmask, i.e. 2^n - 1 for some non-zero
220  * value of 'n'.
221  */
222 void
223 statfs_scale_blocks(struct statfs *sf, long max_size)
224 {
225 	uint64_t count;
226 	int shift;
227 
228 	KASSERT(powerof2(max_size + 1), ("%s: invalid max_size", __func__));
229 
230 	/*
231 	 * Attempt to scale the block counts to give a more accurate
232 	 * overview to userland of the ratio of free space to used
233 	 * space.  To do this, find the largest block count and compute
234 	 * a divisor that lets it fit into a signed integer <= max_size.
235 	 */
236 	if (sf->f_bavail < 0)
237 		count = -sf->f_bavail;
238 	else
239 		count = sf->f_bavail;
240 	count = MAX(sf->f_blocks, MAX(sf->f_bfree, count));
241 	if (count <= max_size)
242 		return;
243 
244 	count >>= flsl(max_size);
245 	shift = 0;
246 	while (count > 0) {
247 		shift++;
248 		count >>=1;
249 	}
250 
251 	sf->f_bsize <<= shift;
252 	sf->f_blocks >>= shift;
253 	sf->f_bfree >>= shift;
254 	sf->f_bavail >>= shift;
255 }
256 
257 static int
258 kern_do_statfs(struct thread *td, struct mount *mp, struct statfs *buf)
259 {
260 	int error;
261 
262 	if (mp == NULL)
263 		return (EBADF);
264 	error = vfs_busy(mp, 0);
265 	vfs_rel(mp);
266 	if (error != 0)
267 		return (error);
268 #ifdef MAC
269 	error = mac_mount_check_stat(td->td_ucred, mp);
270 	if (error != 0)
271 		goto out;
272 #endif
273 	error = VFS_STATFS(mp, buf);
274 	if (error != 0)
275 		goto out;
276 	if (priv_check(td, PRIV_VFS_GENERATION)) {
277 		buf->f_fsid.val[0] = buf->f_fsid.val[1] = 0;
278 		prison_enforce_statfs(td->td_ucred, mp, buf);
279 	}
280 out:
281 	vfs_unbusy(mp);
282 	return (error);
283 }
284 
285 /*
286  * Get filesystem statistics.
287  */
288 #ifndef _SYS_SYSPROTO_H_
289 struct statfs_args {
290 	char *path;
291 	struct statfs *buf;
292 };
293 #endif
294 int
295 sys_statfs(struct thread *td, struct statfs_args *uap)
296 {
297 	struct statfs *sfp;
298 	int error;
299 
300 	sfp = malloc(sizeof(struct statfs), M_STATFS, M_WAITOK);
301 	error = kern_statfs(td, uap->path, UIO_USERSPACE, sfp);
302 	if (error == 0)
303 		error = copyout(sfp, uap->buf, sizeof(struct statfs));
304 	free(sfp, M_STATFS);
305 	return (error);
306 }
307 
308 int
309 kern_statfs(struct thread *td, const char *path, enum uio_seg pathseg,
310     struct statfs *buf)
311 {
312 	struct mount *mp;
313 	struct nameidata nd;
314 	int error;
315 
316 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF | AUDITVNODE1,
317 	    pathseg, path, td);
318 	error = namei(&nd);
319 	if (error != 0)
320 		return (error);
321 	mp = nd.ni_vp->v_mount;
322 	vfs_ref(mp);
323 	NDFREE(&nd, NDF_ONLY_PNBUF);
324 	vput(nd.ni_vp);
325 	return (kern_do_statfs(td, mp, buf));
326 }
327 
328 /*
329  * Get filesystem statistics.
330  */
331 #ifndef _SYS_SYSPROTO_H_
332 struct fstatfs_args {
333 	int fd;
334 	struct statfs *buf;
335 };
336 #endif
337 int
338 sys_fstatfs(struct thread *td, struct fstatfs_args *uap)
339 {
340 	struct statfs *sfp;
341 	int error;
342 
343 	sfp = malloc(sizeof(struct statfs), M_STATFS, M_WAITOK);
344 	error = kern_fstatfs(td, uap->fd, sfp);
345 	if (error == 0)
346 		error = copyout(sfp, uap->buf, sizeof(struct statfs));
347 	free(sfp, M_STATFS);
348 	return (error);
349 }
350 
351 int
352 kern_fstatfs(struct thread *td, int fd, struct statfs *buf)
353 {
354 	struct file *fp;
355 	struct mount *mp;
356 	struct vnode *vp;
357 	int error;
358 
359 	AUDIT_ARG_FD(fd);
360 	error = getvnode(td, fd, &cap_fstatfs_rights, &fp);
361 	if (error != 0)
362 		return (error);
363 	vp = fp->f_vnode;
364 	vn_lock(vp, LK_SHARED | LK_RETRY);
365 #ifdef AUDIT
366 	AUDIT_ARG_VNODE1(vp);
367 #endif
368 	mp = vp->v_mount;
369 	if (mp != NULL)
370 		vfs_ref(mp);
371 	VOP_UNLOCK(vp);
372 	fdrop(fp, td);
373 	return (kern_do_statfs(td, mp, buf));
374 }
375 
376 /*
377  * Get statistics on all filesystems.
378  */
379 #ifndef _SYS_SYSPROTO_H_
380 struct getfsstat_args {
381 	struct statfs *buf;
382 	long bufsize;
383 	int mode;
384 };
385 #endif
386 int
387 sys_getfsstat(struct thread *td, struct getfsstat_args *uap)
388 {
389 	size_t count;
390 	int error;
391 
392 	if (uap->bufsize < 0 || uap->bufsize > SIZE_MAX)
393 		return (EINVAL);
394 	error = kern_getfsstat(td, &uap->buf, uap->bufsize, &count,
395 	    UIO_USERSPACE, uap->mode);
396 	if (error == 0)
397 		td->td_retval[0] = count;
398 	return (error);
399 }
400 
401 /*
402  * If (bufsize > 0 && bufseg == UIO_SYSSPACE)
403  *	The caller is responsible for freeing memory which will be allocated
404  *	in '*buf'.
405  */
406 int
407 kern_getfsstat(struct thread *td, struct statfs **buf, size_t bufsize,
408     size_t *countp, enum uio_seg bufseg, int mode)
409 {
410 	struct mount *mp, *nmp;
411 	struct statfs *sfsp, *sp, *sptmp, *tofree;
412 	size_t count, maxcount;
413 	int error;
414 
415 	switch (mode) {
416 	case MNT_WAIT:
417 	case MNT_NOWAIT:
418 		break;
419 	default:
420 		if (bufseg == UIO_SYSSPACE)
421 			*buf = NULL;
422 		return (EINVAL);
423 	}
424 restart:
425 	maxcount = bufsize / sizeof(struct statfs);
426 	if (bufsize == 0) {
427 		sfsp = NULL;
428 		tofree = NULL;
429 	} else if (bufseg == UIO_USERSPACE) {
430 		sfsp = *buf;
431 		tofree = NULL;
432 	} else /* if (bufseg == UIO_SYSSPACE) */ {
433 		count = 0;
434 		mtx_lock(&mountlist_mtx);
435 		TAILQ_FOREACH(mp, &mountlist, mnt_list) {
436 			count++;
437 		}
438 		mtx_unlock(&mountlist_mtx);
439 		if (maxcount > count)
440 			maxcount = count;
441 		tofree = sfsp = *buf = malloc(maxcount * sizeof(struct statfs),
442 		    M_STATFS, M_WAITOK);
443 	}
444 	count = 0;
445 	mtx_lock(&mountlist_mtx);
446 	for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
447 		if (prison_canseemount(td->td_ucred, mp) != 0) {
448 			nmp = TAILQ_NEXT(mp, mnt_list);
449 			continue;
450 		}
451 #ifdef MAC
452 		if (mac_mount_check_stat(td->td_ucred, mp) != 0) {
453 			nmp = TAILQ_NEXT(mp, mnt_list);
454 			continue;
455 		}
456 #endif
457 		if (mode == MNT_WAIT) {
458 			if (vfs_busy(mp, MBF_MNTLSTLOCK) != 0) {
459 				/*
460 				 * If vfs_busy() failed, and MBF_NOWAIT
461 				 * wasn't passed, then the mp is gone.
462 				 * Furthermore, because of MBF_MNTLSTLOCK,
463 				 * the mountlist_mtx was dropped.  We have
464 				 * no other choice than to start over.
465 				 */
466 				mtx_unlock(&mountlist_mtx);
467 				free(tofree, M_STATFS);
468 				goto restart;
469 			}
470 		} else {
471 			if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK) != 0) {
472 				nmp = TAILQ_NEXT(mp, mnt_list);
473 				continue;
474 			}
475 		}
476 		if (sfsp != NULL && count < maxcount) {
477 			sp = &mp->mnt_stat;
478 			/*
479 			 * If MNT_NOWAIT is specified, do not refresh
480 			 * the fsstat cache.
481 			 */
482 			if (mode != MNT_NOWAIT) {
483 				error = VFS_STATFS(mp, sp);
484 				if (error != 0) {
485 					mtx_lock(&mountlist_mtx);
486 					nmp = TAILQ_NEXT(mp, mnt_list);
487 					vfs_unbusy(mp);
488 					continue;
489 				}
490 			}
491 			if (priv_check(td, PRIV_VFS_GENERATION)) {
492 				sptmp = malloc(sizeof(struct statfs), M_STATFS,
493 				    M_WAITOK);
494 				*sptmp = *sp;
495 				sptmp->f_fsid.val[0] = sptmp->f_fsid.val[1] = 0;
496 				prison_enforce_statfs(td->td_ucred, mp, sptmp);
497 				sp = sptmp;
498 			} else
499 				sptmp = NULL;
500 			if (bufseg == UIO_SYSSPACE) {
501 				bcopy(sp, sfsp, sizeof(*sp));
502 				free(sptmp, M_STATFS);
503 			} else /* if (bufseg == UIO_USERSPACE) */ {
504 				error = copyout(sp, sfsp, sizeof(*sp));
505 				free(sptmp, M_STATFS);
506 				if (error != 0) {
507 					vfs_unbusy(mp);
508 					return (error);
509 				}
510 			}
511 			sfsp++;
512 		}
513 		count++;
514 		mtx_lock(&mountlist_mtx);
515 		nmp = TAILQ_NEXT(mp, mnt_list);
516 		vfs_unbusy(mp);
517 	}
518 	mtx_unlock(&mountlist_mtx);
519 	if (sfsp != NULL && count > maxcount)
520 		*countp = maxcount;
521 	else
522 		*countp = count;
523 	return (0);
524 }
525 
526 #ifdef COMPAT_FREEBSD4
527 /*
528  * Get old format filesystem statistics.
529  */
530 static void freebsd4_cvtstatfs(struct statfs *, struct ostatfs *);
531 
532 #ifndef _SYS_SYSPROTO_H_
533 struct freebsd4_statfs_args {
534 	char *path;
535 	struct ostatfs *buf;
536 };
537 #endif
538 int
539 freebsd4_statfs(struct thread *td, struct freebsd4_statfs_args *uap)
540 {
541 	struct ostatfs osb;
542 	struct statfs *sfp;
543 	int error;
544 
545 	sfp = malloc(sizeof(struct statfs), M_STATFS, M_WAITOK);
546 	error = kern_statfs(td, uap->path, UIO_USERSPACE, sfp);
547 	if (error == 0) {
548 		freebsd4_cvtstatfs(sfp, &osb);
549 		error = copyout(&osb, uap->buf, sizeof(osb));
550 	}
551 	free(sfp, M_STATFS);
552 	return (error);
553 }
554 
555 /*
556  * Get filesystem statistics.
557  */
558 #ifndef _SYS_SYSPROTO_H_
559 struct freebsd4_fstatfs_args {
560 	int fd;
561 	struct ostatfs *buf;
562 };
563 #endif
564 int
565 freebsd4_fstatfs(struct thread *td, struct freebsd4_fstatfs_args *uap)
566 {
567 	struct ostatfs osb;
568 	struct statfs *sfp;
569 	int error;
570 
571 	sfp = malloc(sizeof(struct statfs), M_STATFS, M_WAITOK);
572 	error = kern_fstatfs(td, uap->fd, sfp);
573 	if (error == 0) {
574 		freebsd4_cvtstatfs(sfp, &osb);
575 		error = copyout(&osb, uap->buf, sizeof(osb));
576 	}
577 	free(sfp, M_STATFS);
578 	return (error);
579 }
580 
581 /*
582  * Get statistics on all filesystems.
583  */
584 #ifndef _SYS_SYSPROTO_H_
585 struct freebsd4_getfsstat_args {
586 	struct ostatfs *buf;
587 	long bufsize;
588 	int mode;
589 };
590 #endif
591 int
592 freebsd4_getfsstat(struct thread *td, struct freebsd4_getfsstat_args *uap)
593 {
594 	struct statfs *buf, *sp;
595 	struct ostatfs osb;
596 	size_t count, size;
597 	int error;
598 
599 	if (uap->bufsize < 0)
600 		return (EINVAL);
601 	count = uap->bufsize / sizeof(struct ostatfs);
602 	if (count > SIZE_MAX / sizeof(struct statfs))
603 		return (EINVAL);
604 	size = count * sizeof(struct statfs);
605 	error = kern_getfsstat(td, &buf, size, &count, UIO_SYSSPACE,
606 	    uap->mode);
607 	if (error == 0)
608 		td->td_retval[0] = count;
609 	if (size != 0) {
610 		sp = buf;
611 		while (count != 0 && error == 0) {
612 			freebsd4_cvtstatfs(sp, &osb);
613 			error = copyout(&osb, uap->buf, sizeof(osb));
614 			sp++;
615 			uap->buf++;
616 			count--;
617 		}
618 		free(buf, M_STATFS);
619 	}
620 	return (error);
621 }
622 
623 /*
624  * Implement fstatfs() for (NFS) file handles.
625  */
626 #ifndef _SYS_SYSPROTO_H_
627 struct freebsd4_fhstatfs_args {
628 	struct fhandle *u_fhp;
629 	struct ostatfs *buf;
630 };
631 #endif
632 int
633 freebsd4_fhstatfs(struct thread *td, struct freebsd4_fhstatfs_args *uap)
634 {
635 	struct ostatfs osb;
636 	struct statfs *sfp;
637 	fhandle_t fh;
638 	int error;
639 
640 	error = copyin(uap->u_fhp, &fh, sizeof(fhandle_t));
641 	if (error != 0)
642 		return (error);
643 	sfp = malloc(sizeof(struct statfs), M_STATFS, M_WAITOK);
644 	error = kern_fhstatfs(td, fh, sfp);
645 	if (error == 0) {
646 		freebsd4_cvtstatfs(sfp, &osb);
647 		error = copyout(&osb, uap->buf, sizeof(osb));
648 	}
649 	free(sfp, M_STATFS);
650 	return (error);
651 }
652 
653 /*
654  * Convert a new format statfs structure to an old format statfs structure.
655  */
656 static void
657 freebsd4_cvtstatfs(struct statfs *nsp, struct ostatfs *osp)
658 {
659 
660 	statfs_scale_blocks(nsp, LONG_MAX);
661 	bzero(osp, sizeof(*osp));
662 	osp->f_bsize = nsp->f_bsize;
663 	osp->f_iosize = MIN(nsp->f_iosize, LONG_MAX);
664 	osp->f_blocks = nsp->f_blocks;
665 	osp->f_bfree = nsp->f_bfree;
666 	osp->f_bavail = nsp->f_bavail;
667 	osp->f_files = MIN(nsp->f_files, LONG_MAX);
668 	osp->f_ffree = MIN(nsp->f_ffree, LONG_MAX);
669 	osp->f_owner = nsp->f_owner;
670 	osp->f_type = nsp->f_type;
671 	osp->f_flags = nsp->f_flags;
672 	osp->f_syncwrites = MIN(nsp->f_syncwrites, LONG_MAX);
673 	osp->f_asyncwrites = MIN(nsp->f_asyncwrites, LONG_MAX);
674 	osp->f_syncreads = MIN(nsp->f_syncreads, LONG_MAX);
675 	osp->f_asyncreads = MIN(nsp->f_asyncreads, LONG_MAX);
676 	strlcpy(osp->f_fstypename, nsp->f_fstypename,
677 	    MIN(MFSNAMELEN, OMFSNAMELEN));
678 	strlcpy(osp->f_mntonname, nsp->f_mntonname,
679 	    MIN(MNAMELEN, OMNAMELEN));
680 	strlcpy(osp->f_mntfromname, nsp->f_mntfromname,
681 	    MIN(MNAMELEN, OMNAMELEN));
682 	osp->f_fsid = nsp->f_fsid;
683 }
684 #endif /* COMPAT_FREEBSD4 */
685 
686 #if defined(COMPAT_FREEBSD11)
687 /*
688  * Get old format filesystem statistics.
689  */
690 static void freebsd11_cvtstatfs(struct statfs *, struct freebsd11_statfs *);
691 
692 int
693 freebsd11_statfs(struct thread *td, struct freebsd11_statfs_args *uap)
694 {
695 	struct freebsd11_statfs osb;
696 	struct statfs *sfp;
697 	int error;
698 
699 	sfp = malloc(sizeof(struct statfs), M_STATFS, M_WAITOK);
700 	error = kern_statfs(td, uap->path, UIO_USERSPACE, sfp);
701 	if (error == 0) {
702 		freebsd11_cvtstatfs(sfp, &osb);
703 		error = copyout(&osb, uap->buf, sizeof(osb));
704 	}
705 	free(sfp, M_STATFS);
706 	return (error);
707 }
708 
709 /*
710  * Get filesystem statistics.
711  */
712 int
713 freebsd11_fstatfs(struct thread *td, struct freebsd11_fstatfs_args *uap)
714 {
715 	struct freebsd11_statfs osb;
716 	struct statfs *sfp;
717 	int error;
718 
719 	sfp = malloc(sizeof(struct statfs), M_STATFS, M_WAITOK);
720 	error = kern_fstatfs(td, uap->fd, sfp);
721 	if (error == 0) {
722 		freebsd11_cvtstatfs(sfp, &osb);
723 		error = copyout(&osb, uap->buf, sizeof(osb));
724 	}
725 	free(sfp, M_STATFS);
726 	return (error);
727 }
728 
729 /*
730  * Get statistics on all filesystems.
731  */
732 int
733 freebsd11_getfsstat(struct thread *td, struct freebsd11_getfsstat_args *uap)
734 {
735 	struct freebsd11_statfs osb;
736 	struct statfs *buf, *sp;
737 	size_t count, size;
738 	int error;
739 
740 	count = uap->bufsize / sizeof(struct ostatfs);
741 	size = count * sizeof(struct statfs);
742 	error = kern_getfsstat(td, &buf, size, &count, UIO_SYSSPACE,
743 	    uap->mode);
744 	if (error == 0)
745 		td->td_retval[0] = count;
746 	if (size > 0) {
747 		sp = buf;
748 		while (count > 0 && error == 0) {
749 			freebsd11_cvtstatfs(sp, &osb);
750 			error = copyout(&osb, uap->buf, sizeof(osb));
751 			sp++;
752 			uap->buf++;
753 			count--;
754 		}
755 		free(buf, M_STATFS);
756 	}
757 	return (error);
758 }
759 
760 /*
761  * Implement fstatfs() for (NFS) file handles.
762  */
763 int
764 freebsd11_fhstatfs(struct thread *td, struct freebsd11_fhstatfs_args *uap)
765 {
766 	struct freebsd11_statfs osb;
767 	struct statfs *sfp;
768 	fhandle_t fh;
769 	int error;
770 
771 	error = copyin(uap->u_fhp, &fh, sizeof(fhandle_t));
772 	if (error)
773 		return (error);
774 	sfp = malloc(sizeof(struct statfs), M_STATFS, M_WAITOK);
775 	error = kern_fhstatfs(td, fh, sfp);
776 	if (error == 0) {
777 		freebsd11_cvtstatfs(sfp, &osb);
778 		error = copyout(&osb, uap->buf, sizeof(osb));
779 	}
780 	free(sfp, M_STATFS);
781 	return (error);
782 }
783 
784 /*
785  * Convert a new format statfs structure to an old format statfs structure.
786  */
787 static void
788 freebsd11_cvtstatfs(struct statfs *nsp, struct freebsd11_statfs *osp)
789 {
790 
791 	bzero(osp, sizeof(*osp));
792 	osp->f_version = FREEBSD11_STATFS_VERSION;
793 	osp->f_type = nsp->f_type;
794 	osp->f_flags = nsp->f_flags;
795 	osp->f_bsize = nsp->f_bsize;
796 	osp->f_iosize = nsp->f_iosize;
797 	osp->f_blocks = nsp->f_blocks;
798 	osp->f_bfree = nsp->f_bfree;
799 	osp->f_bavail = nsp->f_bavail;
800 	osp->f_files = nsp->f_files;
801 	osp->f_ffree = nsp->f_ffree;
802 	osp->f_syncwrites = nsp->f_syncwrites;
803 	osp->f_asyncwrites = nsp->f_asyncwrites;
804 	osp->f_syncreads = nsp->f_syncreads;
805 	osp->f_asyncreads = nsp->f_asyncreads;
806 	osp->f_namemax = nsp->f_namemax;
807 	osp->f_owner = nsp->f_owner;
808 	osp->f_fsid = nsp->f_fsid;
809 	strlcpy(osp->f_fstypename, nsp->f_fstypename,
810 	    MIN(MFSNAMELEN, sizeof(osp->f_fstypename)));
811 	strlcpy(osp->f_mntonname, nsp->f_mntonname,
812 	    MIN(MNAMELEN, sizeof(osp->f_mntonname)));
813 	strlcpy(osp->f_mntfromname, nsp->f_mntfromname,
814 	    MIN(MNAMELEN, sizeof(osp->f_mntfromname)));
815 }
816 #endif /* COMPAT_FREEBSD11 */
817 
818 /*
819  * Change current working directory to a given file descriptor.
820  */
821 #ifndef _SYS_SYSPROTO_H_
822 struct fchdir_args {
823 	int	fd;
824 };
825 #endif
826 int
827 sys_fchdir(struct thread *td, struct fchdir_args *uap)
828 {
829 	struct vnode *vp, *tdp;
830 	struct mount *mp;
831 	struct file *fp;
832 	int error;
833 
834 	AUDIT_ARG_FD(uap->fd);
835 	error = getvnode(td, uap->fd, &cap_fchdir_rights,
836 	    &fp);
837 	if (error != 0)
838 		return (error);
839 	vp = fp->f_vnode;
840 	vrefact(vp);
841 	fdrop(fp, td);
842 	vn_lock(vp, LK_SHARED | LK_RETRY);
843 	AUDIT_ARG_VNODE1(vp);
844 	error = change_dir(vp, td);
845 	while (!error && (mp = vp->v_mountedhere) != NULL) {
846 		if (vfs_busy(mp, 0))
847 			continue;
848 		error = VFS_ROOT(mp, LK_SHARED, &tdp);
849 		vfs_unbusy(mp);
850 		if (error != 0)
851 			break;
852 		vput(vp);
853 		vp = tdp;
854 	}
855 	if (error != 0) {
856 		vput(vp);
857 		return (error);
858 	}
859 	VOP_UNLOCK(vp);
860 	pwd_chdir(td, vp);
861 	return (0);
862 }
863 
864 /*
865  * Change current working directory (``.'').
866  */
867 #ifndef _SYS_SYSPROTO_H_
868 struct chdir_args {
869 	char	*path;
870 };
871 #endif
872 int
873 sys_chdir(struct thread *td, struct chdir_args *uap)
874 {
875 
876 	return (kern_chdir(td, uap->path, UIO_USERSPACE));
877 }
878 
879 int
880 kern_chdir(struct thread *td, const char *path, enum uio_seg pathseg)
881 {
882 	struct nameidata nd;
883 	int error;
884 
885 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF | AUDITVNODE1,
886 	    pathseg, path, td);
887 	if ((error = namei(&nd)) != 0)
888 		return (error);
889 	if ((error = change_dir(nd.ni_vp, td)) != 0) {
890 		vput(nd.ni_vp);
891 		NDFREE(&nd, NDF_ONLY_PNBUF);
892 		return (error);
893 	}
894 	VOP_UNLOCK(nd.ni_vp);
895 	NDFREE(&nd, NDF_ONLY_PNBUF);
896 	pwd_chdir(td, nd.ni_vp);
897 	return (0);
898 }
899 
900 /*
901  * Change notion of root (``/'') directory.
902  */
903 #ifndef _SYS_SYSPROTO_H_
904 struct chroot_args {
905 	char	*path;
906 };
907 #endif
908 int
909 sys_chroot(struct thread *td, struct chroot_args *uap)
910 {
911 	struct nameidata nd;
912 	int error;
913 
914 	error = priv_check(td, PRIV_VFS_CHROOT);
915 	if (error != 0)
916 		return (error);
917 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF | AUDITVNODE1,
918 	    UIO_USERSPACE, uap->path, td);
919 	error = namei(&nd);
920 	if (error != 0)
921 		goto error;
922 	error = change_dir(nd.ni_vp, td);
923 	if (error != 0)
924 		goto e_vunlock;
925 #ifdef MAC
926 	error = mac_vnode_check_chroot(td->td_ucred, nd.ni_vp);
927 	if (error != 0)
928 		goto e_vunlock;
929 #endif
930 	VOP_UNLOCK(nd.ni_vp);
931 	error = pwd_chroot(td, nd.ni_vp);
932 	vrele(nd.ni_vp);
933 	NDFREE(&nd, NDF_ONLY_PNBUF);
934 	return (error);
935 e_vunlock:
936 	vput(nd.ni_vp);
937 error:
938 	NDFREE(&nd, NDF_ONLY_PNBUF);
939 	return (error);
940 }
941 
942 /*
943  * Common routine for chroot and chdir.  Callers must provide a locked vnode
944  * instance.
945  */
946 int
947 change_dir(struct vnode *vp, struct thread *td)
948 {
949 #ifdef MAC
950 	int error;
951 #endif
952 
953 	ASSERT_VOP_LOCKED(vp, "change_dir(): vp not locked");
954 	if (vp->v_type != VDIR)
955 		return (ENOTDIR);
956 #ifdef MAC
957 	error = mac_vnode_check_chdir(td->td_ucred, vp);
958 	if (error != 0)
959 		return (error);
960 #endif
961 	return (VOP_ACCESS(vp, VEXEC, td->td_ucred, td));
962 }
963 
964 static __inline void
965 flags_to_rights(int flags, cap_rights_t *rightsp)
966 {
967 
968 	if (flags & O_EXEC) {
969 		cap_rights_set(rightsp, CAP_FEXECVE);
970 	} else {
971 		switch ((flags & O_ACCMODE)) {
972 		case O_RDONLY:
973 			cap_rights_set(rightsp, CAP_READ);
974 			break;
975 		case O_RDWR:
976 			cap_rights_set(rightsp, CAP_READ);
977 			/* FALLTHROUGH */
978 		case O_WRONLY:
979 			cap_rights_set(rightsp, CAP_WRITE);
980 			if (!(flags & (O_APPEND | O_TRUNC)))
981 				cap_rights_set(rightsp, CAP_SEEK);
982 			break;
983 		}
984 	}
985 
986 	if (flags & O_CREAT)
987 		cap_rights_set(rightsp, CAP_CREATE);
988 
989 	if (flags & O_TRUNC)
990 		cap_rights_set(rightsp, CAP_FTRUNCATE);
991 
992 	if (flags & (O_SYNC | O_FSYNC))
993 		cap_rights_set(rightsp, CAP_FSYNC);
994 
995 	if (flags & (O_EXLOCK | O_SHLOCK))
996 		cap_rights_set(rightsp, CAP_FLOCK);
997 }
998 
999 /*
1000  * Check permissions, allocate an open file structure, and call the device
1001  * open routine if any.
1002  */
1003 #ifndef _SYS_SYSPROTO_H_
1004 struct open_args {
1005 	char	*path;
1006 	int	flags;
1007 	int	mode;
1008 };
1009 #endif
1010 int
1011 sys_open(struct thread *td, struct open_args *uap)
1012 {
1013 
1014 	return (kern_openat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
1015 	    uap->flags, uap->mode));
1016 }
1017 
1018 #ifndef _SYS_SYSPROTO_H_
1019 struct openat_args {
1020 	int	fd;
1021 	char	*path;
1022 	int	flag;
1023 	int	mode;
1024 };
1025 #endif
1026 int
1027 sys_openat(struct thread *td, struct openat_args *uap)
1028 {
1029 
1030 	AUDIT_ARG_FD(uap->fd);
1031 	return (kern_openat(td, uap->fd, uap->path, UIO_USERSPACE, uap->flag,
1032 	    uap->mode));
1033 }
1034 
1035 int
1036 kern_openat(struct thread *td, int fd, const char *path, enum uio_seg pathseg,
1037     int flags, int mode)
1038 {
1039 	struct proc *p = td->td_proc;
1040 	struct filedesc *fdp = p->p_fd;
1041 	struct file *fp;
1042 	struct vnode *vp;
1043 	struct nameidata nd;
1044 	cap_rights_t rights;
1045 	int cmode, error, indx;
1046 
1047 	indx = -1;
1048 
1049 	AUDIT_ARG_FFLAGS(flags);
1050 	AUDIT_ARG_MODE(mode);
1051 	cap_rights_init(&rights, CAP_LOOKUP);
1052 	flags_to_rights(flags, &rights);
1053 	/*
1054 	 * Only one of the O_EXEC, O_RDONLY, O_WRONLY and O_RDWR flags
1055 	 * may be specified.
1056 	 */
1057 	if (flags & O_EXEC) {
1058 		if (flags & O_ACCMODE)
1059 			return (EINVAL);
1060 	} else if ((flags & O_ACCMODE) == O_ACCMODE) {
1061 		return (EINVAL);
1062 	} else {
1063 		flags = FFLAGS(flags);
1064 	}
1065 
1066 	/*
1067 	 * Allocate a file structure. The descriptor to reference it
1068 	 * is allocated and set by finstall() below.
1069 	 */
1070 	error = falloc_noinstall(td, &fp);
1071 	if (error != 0)
1072 		return (error);
1073 	/*
1074 	 * An extra reference on `fp' has been held for us by
1075 	 * falloc_noinstall().
1076 	 */
1077 	/* Set the flags early so the finit in devfs can pick them up. */
1078 	fp->f_flag = flags & FMASK;
1079 	cmode = ((mode & ~fdp->fd_cmask) & ALLPERMS) & ~S_ISTXT;
1080 	NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | AUDITVNODE1, pathseg, path, fd,
1081 	    &rights, td);
1082 	td->td_dupfd = -1;		/* XXX check for fdopen */
1083 	error = vn_open(&nd, &flags, cmode, fp);
1084 	if (error != 0) {
1085 		/*
1086 		 * If the vn_open replaced the method vector, something
1087 		 * wonderous happened deep below and we just pass it up
1088 		 * pretending we know what we do.
1089 		 */
1090 		if (error == ENXIO && fp->f_ops != &badfileops)
1091 			goto success;
1092 
1093 		/*
1094 		 * Handle special fdopen() case. bleh.
1095 		 *
1096 		 * Don't do this for relative (capability) lookups; we don't
1097 		 * understand exactly what would happen, and we don't think
1098 		 * that it ever should.
1099 		 */
1100 		if ((nd.ni_lcf & NI_LCF_STRICTRELATIVE) == 0 &&
1101 		    (error == ENODEV || error == ENXIO) &&
1102 		    td->td_dupfd >= 0) {
1103 			error = dupfdopen(td, fdp, td->td_dupfd, flags, error,
1104 			    &indx);
1105 			if (error == 0)
1106 				goto success;
1107 		}
1108 
1109 		goto bad;
1110 	}
1111 	td->td_dupfd = 0;
1112 	NDFREE(&nd, NDF_ONLY_PNBUF);
1113 	vp = nd.ni_vp;
1114 
1115 	/*
1116 	 * Store the vnode, for any f_type. Typically, the vnode use
1117 	 * count is decremented by direct call to vn_closefile() for
1118 	 * files that switched type in the cdevsw fdopen() method.
1119 	 */
1120 	fp->f_vnode = vp;
1121 	/*
1122 	 * If the file wasn't claimed by devfs bind it to the normal
1123 	 * vnode operations here.
1124 	 */
1125 	if (fp->f_ops == &badfileops) {
1126 		KASSERT(vp->v_type != VFIFO, ("Unexpected fifo."));
1127 		fp->f_seqcount = 1;
1128 		finit(fp, (flags & FMASK) | (fp->f_flag & FHASLOCK),
1129 		    DTYPE_VNODE, vp, &vnops);
1130 	}
1131 
1132 	VOP_UNLOCK(vp);
1133 	if (flags & O_TRUNC) {
1134 		error = fo_truncate(fp, 0, td->td_ucred, td);
1135 		if (error != 0)
1136 			goto bad;
1137 	}
1138 success:
1139 	/*
1140 	 * If we haven't already installed the FD (for dupfdopen), do so now.
1141 	 */
1142 	if (indx == -1) {
1143 		struct filecaps *fcaps;
1144 
1145 #ifdef CAPABILITIES
1146 		if ((nd.ni_lcf & NI_LCF_STRICTRELATIVE) != 0)
1147 			fcaps = &nd.ni_filecaps;
1148 		else
1149 #endif
1150 			fcaps = NULL;
1151 		error = finstall(td, fp, &indx, flags, fcaps);
1152 		/* On success finstall() consumes fcaps. */
1153 		if (error != 0) {
1154 			filecaps_free(&nd.ni_filecaps);
1155 			goto bad;
1156 		}
1157 	} else {
1158 		filecaps_free(&nd.ni_filecaps);
1159 	}
1160 
1161 	/*
1162 	 * Release our private reference, leaving the one associated with
1163 	 * the descriptor table intact.
1164 	 */
1165 	fdrop(fp, td);
1166 	td->td_retval[0] = indx;
1167 	return (0);
1168 bad:
1169 	KASSERT(indx == -1, ("indx=%d, should be -1", indx));
1170 	fdrop(fp, td);
1171 	return (error);
1172 }
1173 
1174 #ifdef COMPAT_43
1175 /*
1176  * Create a file.
1177  */
1178 #ifndef _SYS_SYSPROTO_H_
1179 struct ocreat_args {
1180 	char	*path;
1181 	int	mode;
1182 };
1183 #endif
1184 int
1185 ocreat(struct thread *td, struct ocreat_args *uap)
1186 {
1187 
1188 	return (kern_openat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
1189 	    O_WRONLY | O_CREAT | O_TRUNC, uap->mode));
1190 }
1191 #endif /* COMPAT_43 */
1192 
1193 /*
1194  * Create a special file.
1195  */
1196 #ifndef _SYS_SYSPROTO_H_
1197 struct mknodat_args {
1198 	int	fd;
1199 	char	*path;
1200 	mode_t	mode;
1201 	dev_t	dev;
1202 };
1203 #endif
1204 int
1205 sys_mknodat(struct thread *td, struct mknodat_args *uap)
1206 {
1207 
1208 	return (kern_mknodat(td, uap->fd, uap->path, UIO_USERSPACE, uap->mode,
1209 	    uap->dev));
1210 }
1211 
1212 #if defined(COMPAT_FREEBSD11)
1213 int
1214 freebsd11_mknod(struct thread *td,
1215     struct freebsd11_mknod_args *uap)
1216 {
1217 
1218 	return (kern_mknodat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
1219 	    uap->mode, uap->dev));
1220 }
1221 
1222 int
1223 freebsd11_mknodat(struct thread *td,
1224     struct freebsd11_mknodat_args *uap)
1225 {
1226 
1227 	return (kern_mknodat(td, uap->fd, uap->path, UIO_USERSPACE, uap->mode,
1228 	    uap->dev));
1229 }
1230 #endif /* COMPAT_FREEBSD11 */
1231 
1232 int
1233 kern_mknodat(struct thread *td, int fd, const char *path, enum uio_seg pathseg,
1234     int mode, dev_t dev)
1235 {
1236 	struct vnode *vp;
1237 	struct mount *mp;
1238 	struct vattr vattr;
1239 	struct nameidata nd;
1240 	int error, whiteout = 0;
1241 
1242 	AUDIT_ARG_MODE(mode);
1243 	AUDIT_ARG_DEV(dev);
1244 	switch (mode & S_IFMT) {
1245 	case S_IFCHR:
1246 	case S_IFBLK:
1247 		error = priv_check(td, PRIV_VFS_MKNOD_DEV);
1248 		if (error == 0 && dev == VNOVAL)
1249 			error = EINVAL;
1250 		break;
1251 	case S_IFWHT:
1252 		error = priv_check(td, PRIV_VFS_MKNOD_WHT);
1253 		break;
1254 	case S_IFIFO:
1255 		if (dev == 0)
1256 			return (kern_mkfifoat(td, fd, path, pathseg, mode));
1257 		/* FALLTHROUGH */
1258 	default:
1259 		error = EINVAL;
1260 		break;
1261 	}
1262 	if (error != 0)
1263 		return (error);
1264 restart:
1265 	bwillwrite();
1266 	NDINIT_ATRIGHTS(&nd, CREATE, LOCKPARENT | SAVENAME | AUDITVNODE1 |
1267 	    NOCACHE, pathseg, path, fd, &cap_mknodat_rights,
1268 	    td);
1269 	if ((error = namei(&nd)) != 0)
1270 		return (error);
1271 	vp = nd.ni_vp;
1272 	if (vp != NULL) {
1273 		NDFREE(&nd, NDF_ONLY_PNBUF);
1274 		if (vp == nd.ni_dvp)
1275 			vrele(nd.ni_dvp);
1276 		else
1277 			vput(nd.ni_dvp);
1278 		vrele(vp);
1279 		return (EEXIST);
1280 	} else {
1281 		VATTR_NULL(&vattr);
1282 		vattr.va_mode = (mode & ALLPERMS) &
1283 		    ~td->td_proc->p_fd->fd_cmask;
1284 		vattr.va_rdev = dev;
1285 		whiteout = 0;
1286 
1287 		switch (mode & S_IFMT) {
1288 		case S_IFCHR:
1289 			vattr.va_type = VCHR;
1290 			break;
1291 		case S_IFBLK:
1292 			vattr.va_type = VBLK;
1293 			break;
1294 		case S_IFWHT:
1295 			whiteout = 1;
1296 			break;
1297 		default:
1298 			panic("kern_mknod: invalid mode");
1299 		}
1300 	}
1301 	if (vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
1302 		NDFREE(&nd, NDF_ONLY_PNBUF);
1303 		vput(nd.ni_dvp);
1304 		if ((error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH)) != 0)
1305 			return (error);
1306 		goto restart;
1307 	}
1308 #ifdef MAC
1309 	if (error == 0 && !whiteout)
1310 		error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp,
1311 		    &nd.ni_cnd, &vattr);
1312 #endif
1313 	if (error == 0) {
1314 		if (whiteout)
1315 			error = VOP_WHITEOUT(nd.ni_dvp, &nd.ni_cnd, CREATE);
1316 		else {
1317 			error = VOP_MKNOD(nd.ni_dvp, &nd.ni_vp,
1318 						&nd.ni_cnd, &vattr);
1319 			if (error == 0)
1320 				vput(nd.ni_vp);
1321 		}
1322 	}
1323 	NDFREE(&nd, NDF_ONLY_PNBUF);
1324 	vput(nd.ni_dvp);
1325 	vn_finished_write(mp);
1326 	return (error);
1327 }
1328 
1329 /*
1330  * Create a named pipe.
1331  */
1332 #ifndef _SYS_SYSPROTO_H_
1333 struct mkfifo_args {
1334 	char	*path;
1335 	int	mode;
1336 };
1337 #endif
1338 int
1339 sys_mkfifo(struct thread *td, struct mkfifo_args *uap)
1340 {
1341 
1342 	return (kern_mkfifoat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
1343 	    uap->mode));
1344 }
1345 
1346 #ifndef _SYS_SYSPROTO_H_
1347 struct mkfifoat_args {
1348 	int	fd;
1349 	char	*path;
1350 	mode_t	mode;
1351 };
1352 #endif
1353 int
1354 sys_mkfifoat(struct thread *td, struct mkfifoat_args *uap)
1355 {
1356 
1357 	return (kern_mkfifoat(td, uap->fd, uap->path, UIO_USERSPACE,
1358 	    uap->mode));
1359 }
1360 
1361 int
1362 kern_mkfifoat(struct thread *td, int fd, const char *path,
1363     enum uio_seg pathseg, int mode)
1364 {
1365 	struct mount *mp;
1366 	struct vattr vattr;
1367 	struct nameidata nd;
1368 	int error;
1369 
1370 	AUDIT_ARG_MODE(mode);
1371 restart:
1372 	bwillwrite();
1373 	NDINIT_ATRIGHTS(&nd, CREATE, LOCKPARENT | SAVENAME | AUDITVNODE1 |
1374 	    NOCACHE, pathseg, path, fd, &cap_mkfifoat_rights,
1375 	    td);
1376 	if ((error = namei(&nd)) != 0)
1377 		return (error);
1378 	if (nd.ni_vp != NULL) {
1379 		NDFREE(&nd, NDF_ONLY_PNBUF);
1380 		if (nd.ni_vp == nd.ni_dvp)
1381 			vrele(nd.ni_dvp);
1382 		else
1383 			vput(nd.ni_dvp);
1384 		vrele(nd.ni_vp);
1385 		return (EEXIST);
1386 	}
1387 	if (vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
1388 		NDFREE(&nd, NDF_ONLY_PNBUF);
1389 		vput(nd.ni_dvp);
1390 		if ((error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH)) != 0)
1391 			return (error);
1392 		goto restart;
1393 	}
1394 	VATTR_NULL(&vattr);
1395 	vattr.va_type = VFIFO;
1396 	vattr.va_mode = (mode & ALLPERMS) & ~td->td_proc->p_fd->fd_cmask;
1397 #ifdef MAC
1398 	error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
1399 	    &vattr);
1400 	if (error != 0)
1401 		goto out;
1402 #endif
1403 	error = VOP_MKNOD(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
1404 	if (error == 0)
1405 		vput(nd.ni_vp);
1406 #ifdef MAC
1407 out:
1408 #endif
1409 	vput(nd.ni_dvp);
1410 	vn_finished_write(mp);
1411 	NDFREE(&nd, NDF_ONLY_PNBUF);
1412 	return (error);
1413 }
1414 
1415 /*
1416  * Make a hard file link.
1417  */
1418 #ifndef _SYS_SYSPROTO_H_
1419 struct link_args {
1420 	char	*path;
1421 	char	*link;
1422 };
1423 #endif
1424 int
1425 sys_link(struct thread *td, struct link_args *uap)
1426 {
1427 
1428 	return (kern_linkat(td, AT_FDCWD, AT_FDCWD, uap->path, uap->link,
1429 	    UIO_USERSPACE, FOLLOW));
1430 }
1431 
1432 #ifndef _SYS_SYSPROTO_H_
1433 struct linkat_args {
1434 	int	fd1;
1435 	char	*path1;
1436 	int	fd2;
1437 	char	*path2;
1438 	int	flag;
1439 };
1440 #endif
1441 int
1442 sys_linkat(struct thread *td, struct linkat_args *uap)
1443 {
1444 	int flag;
1445 
1446 	flag = uap->flag;
1447 	if ((flag & ~(AT_SYMLINK_FOLLOW | AT_BENEATH)) != 0)
1448 		return (EINVAL);
1449 
1450 	return (kern_linkat(td, uap->fd1, uap->fd2, uap->path1, uap->path2,
1451 	    UIO_USERSPACE, ((flag & AT_SYMLINK_FOLLOW) != 0 ? FOLLOW :
1452 	    NOFOLLOW) | ((flag & AT_BENEATH) != 0 ? BENEATH : 0)));
1453 }
1454 
1455 int hardlink_check_uid = 0;
1456 SYSCTL_INT(_security_bsd, OID_AUTO, hardlink_check_uid, CTLFLAG_RW,
1457     &hardlink_check_uid, 0,
1458     "Unprivileged processes cannot create hard links to files owned by other "
1459     "users");
1460 static int hardlink_check_gid = 0;
1461 SYSCTL_INT(_security_bsd, OID_AUTO, hardlink_check_gid, CTLFLAG_RW,
1462     &hardlink_check_gid, 0,
1463     "Unprivileged processes cannot create hard links to files owned by other "
1464     "groups");
1465 
1466 static int
1467 can_hardlink(struct vnode *vp, struct ucred *cred)
1468 {
1469 	struct vattr va;
1470 	int error;
1471 
1472 	if (!hardlink_check_uid && !hardlink_check_gid)
1473 		return (0);
1474 
1475 	error = VOP_GETATTR(vp, &va, cred);
1476 	if (error != 0)
1477 		return (error);
1478 
1479 	if (hardlink_check_uid && cred->cr_uid != va.va_uid) {
1480 		error = priv_check_cred(cred, PRIV_VFS_LINK);
1481 		if (error != 0)
1482 			return (error);
1483 	}
1484 
1485 	if (hardlink_check_gid && !groupmember(va.va_gid, cred)) {
1486 		error = priv_check_cred(cred, PRIV_VFS_LINK);
1487 		if (error != 0)
1488 			return (error);
1489 	}
1490 
1491 	return (0);
1492 }
1493 
1494 int
1495 kern_linkat(struct thread *td, int fd1, int fd2, const char *path1,
1496     const char *path2, enum uio_seg segflag, int follow)
1497 {
1498 	struct nameidata nd;
1499 	int error;
1500 
1501 	do {
1502 		bwillwrite();
1503 		NDINIT_ATRIGHTS(&nd, LOOKUP, follow | AUDITVNODE1, segflag,
1504 		    path1, fd1, &cap_linkat_source_rights, td);
1505 		if ((error = namei(&nd)) != 0)
1506 			return (error);
1507 		NDFREE(&nd, NDF_ONLY_PNBUF);
1508 		error = kern_linkat_vp(td, nd.ni_vp, fd2, path2, segflag);
1509 	} while (error ==  EAGAIN);
1510 	return (error);
1511 }
1512 
1513 static int
1514 kern_linkat_vp(struct thread *td, struct vnode *vp, int fd, const char *path,
1515     enum uio_seg segflag)
1516 {
1517 	struct nameidata nd;
1518 	struct mount *mp;
1519 	int error;
1520 
1521 	if (vp->v_type == VDIR) {
1522 		vrele(vp);
1523 		return (EPERM);		/* POSIX */
1524 	}
1525 	NDINIT_ATRIGHTS(&nd, CREATE,
1526 	    LOCKPARENT | SAVENAME | AUDITVNODE2 | NOCACHE, segflag, path, fd,
1527 	    &cap_linkat_target_rights, td);
1528 	if ((error = namei(&nd)) == 0) {
1529 		if (nd.ni_vp != NULL) {
1530 			NDFREE(&nd, NDF_ONLY_PNBUF);
1531 			if (nd.ni_dvp == nd.ni_vp)
1532 				vrele(nd.ni_dvp);
1533 			else
1534 				vput(nd.ni_dvp);
1535 			vrele(nd.ni_vp);
1536 			vrele(vp);
1537 			return (EEXIST);
1538 		} else if (nd.ni_dvp->v_mount != vp->v_mount) {
1539 			/*
1540 			 * Cross-device link.  No need to recheck
1541 			 * vp->v_type, since it cannot change, except
1542 			 * to VBAD.
1543 			 */
1544 			NDFREE(&nd, NDF_ONLY_PNBUF);
1545 			vput(nd.ni_dvp);
1546 			vrele(vp);
1547 			return (EXDEV);
1548 		} else if ((error = vn_lock(vp, LK_EXCLUSIVE)) == 0) {
1549 			error = can_hardlink(vp, td->td_ucred);
1550 #ifdef MAC
1551 			if (error == 0)
1552 				error = mac_vnode_check_link(td->td_ucred,
1553 				    nd.ni_dvp, vp, &nd.ni_cnd);
1554 #endif
1555 			if (error != 0) {
1556 				vput(vp);
1557 				vput(nd.ni_dvp);
1558 				NDFREE(&nd, NDF_ONLY_PNBUF);
1559 				return (error);
1560 			}
1561 			error = vn_start_write(vp, &mp, V_NOWAIT);
1562 			if (error != 0) {
1563 				vput(vp);
1564 				vput(nd.ni_dvp);
1565 				NDFREE(&nd, NDF_ONLY_PNBUF);
1566 				error = vn_start_write(NULL, &mp,
1567 				    V_XSLEEP | PCATCH);
1568 				if (error != 0)
1569 					return (error);
1570 				return (EAGAIN);
1571 			}
1572 			error = VOP_LINK(nd.ni_dvp, vp, &nd.ni_cnd);
1573 			VOP_UNLOCK(vp);
1574 			vput(nd.ni_dvp);
1575 			vn_finished_write(mp);
1576 			NDFREE(&nd, NDF_ONLY_PNBUF);
1577 		} else {
1578 			vput(nd.ni_dvp);
1579 			NDFREE(&nd, NDF_ONLY_PNBUF);
1580 			vrele(vp);
1581 			return (EAGAIN);
1582 		}
1583 	}
1584 	vrele(vp);
1585 	return (error);
1586 }
1587 
1588 /*
1589  * Make a symbolic link.
1590  */
1591 #ifndef _SYS_SYSPROTO_H_
1592 struct symlink_args {
1593 	char	*path;
1594 	char	*link;
1595 };
1596 #endif
1597 int
1598 sys_symlink(struct thread *td, struct symlink_args *uap)
1599 {
1600 
1601 	return (kern_symlinkat(td, uap->path, AT_FDCWD, uap->link,
1602 	    UIO_USERSPACE));
1603 }
1604 
1605 #ifndef _SYS_SYSPROTO_H_
1606 struct symlinkat_args {
1607 	char	*path;
1608 	int	fd;
1609 	char	*path2;
1610 };
1611 #endif
1612 int
1613 sys_symlinkat(struct thread *td, struct symlinkat_args *uap)
1614 {
1615 
1616 	return (kern_symlinkat(td, uap->path1, uap->fd, uap->path2,
1617 	    UIO_USERSPACE));
1618 }
1619 
1620 int
1621 kern_symlinkat(struct thread *td, const char *path1, int fd, const char *path2,
1622     enum uio_seg segflg)
1623 {
1624 	struct mount *mp;
1625 	struct vattr vattr;
1626 	const char *syspath;
1627 	char *tmppath;
1628 	struct nameidata nd;
1629 	int error;
1630 
1631 	if (segflg == UIO_SYSSPACE) {
1632 		syspath = path1;
1633 	} else {
1634 		tmppath = uma_zalloc(namei_zone, M_WAITOK);
1635 		if ((error = copyinstr(path1, tmppath, MAXPATHLEN, NULL)) != 0)
1636 			goto out;
1637 		syspath = tmppath;
1638 	}
1639 	AUDIT_ARG_TEXT(syspath);
1640 restart:
1641 	bwillwrite();
1642 	NDINIT_ATRIGHTS(&nd, CREATE, LOCKPARENT | SAVENAME | AUDITVNODE1 |
1643 	    NOCACHE, segflg, path2, fd, &cap_symlinkat_rights,
1644 	    td);
1645 	if ((error = namei(&nd)) != 0)
1646 		goto out;
1647 	if (nd.ni_vp) {
1648 		NDFREE(&nd, NDF_ONLY_PNBUF);
1649 		if (nd.ni_vp == nd.ni_dvp)
1650 			vrele(nd.ni_dvp);
1651 		else
1652 			vput(nd.ni_dvp);
1653 		vrele(nd.ni_vp);
1654 		error = EEXIST;
1655 		goto out;
1656 	}
1657 	if (vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
1658 		NDFREE(&nd, NDF_ONLY_PNBUF);
1659 		vput(nd.ni_dvp);
1660 		if ((error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH)) != 0)
1661 			goto out;
1662 		goto restart;
1663 	}
1664 	VATTR_NULL(&vattr);
1665 	vattr.va_mode = ACCESSPERMS &~ td->td_proc->p_fd->fd_cmask;
1666 #ifdef MAC
1667 	vattr.va_type = VLNK;
1668 	error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
1669 	    &vattr);
1670 	if (error != 0)
1671 		goto out2;
1672 #endif
1673 	error = VOP_SYMLINK(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr, syspath);
1674 	if (error == 0)
1675 		vput(nd.ni_vp);
1676 #ifdef MAC
1677 out2:
1678 #endif
1679 	NDFREE(&nd, NDF_ONLY_PNBUF);
1680 	vput(nd.ni_dvp);
1681 	vn_finished_write(mp);
1682 out:
1683 	if (segflg != UIO_SYSSPACE)
1684 		uma_zfree(namei_zone, tmppath);
1685 	return (error);
1686 }
1687 
1688 /*
1689  * Delete a whiteout from the filesystem.
1690  */
1691 #ifndef _SYS_SYSPROTO_H_
1692 struct undelete_args {
1693 	char *path;
1694 };
1695 #endif
1696 int
1697 sys_undelete(struct thread *td, struct undelete_args *uap)
1698 {
1699 	struct mount *mp;
1700 	struct nameidata nd;
1701 	int error;
1702 
1703 restart:
1704 	bwillwrite();
1705 	NDINIT(&nd, DELETE, LOCKPARENT | DOWHITEOUT | AUDITVNODE1,
1706 	    UIO_USERSPACE, uap->path, td);
1707 	error = namei(&nd);
1708 	if (error != 0)
1709 		return (error);
1710 
1711 	if (nd.ni_vp != NULLVP || !(nd.ni_cnd.cn_flags & ISWHITEOUT)) {
1712 		NDFREE(&nd, NDF_ONLY_PNBUF);
1713 		if (nd.ni_vp == nd.ni_dvp)
1714 			vrele(nd.ni_dvp);
1715 		else
1716 			vput(nd.ni_dvp);
1717 		if (nd.ni_vp)
1718 			vrele(nd.ni_vp);
1719 		return (EEXIST);
1720 	}
1721 	if (vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
1722 		NDFREE(&nd, NDF_ONLY_PNBUF);
1723 		vput(nd.ni_dvp);
1724 		if ((error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH)) != 0)
1725 			return (error);
1726 		goto restart;
1727 	}
1728 	error = VOP_WHITEOUT(nd.ni_dvp, &nd.ni_cnd, DELETE);
1729 	NDFREE(&nd, NDF_ONLY_PNBUF);
1730 	vput(nd.ni_dvp);
1731 	vn_finished_write(mp);
1732 	return (error);
1733 }
1734 
1735 /*
1736  * Delete a name from the filesystem.
1737  */
1738 #ifndef _SYS_SYSPROTO_H_
1739 struct unlink_args {
1740 	char	*path;
1741 };
1742 #endif
1743 int
1744 sys_unlink(struct thread *td, struct unlink_args *uap)
1745 {
1746 
1747 	return (kern_funlinkat(td, AT_FDCWD, uap->path, FD_NONE, UIO_USERSPACE,
1748 	    0, 0));
1749 }
1750 
1751 static int
1752 kern_funlinkat_ex(struct thread *td, int dfd, const char *path, int fd,
1753     int flag, enum uio_seg pathseg, ino_t oldinum)
1754 {
1755 
1756 	if ((flag & ~AT_REMOVEDIR) != 0)
1757 		return (EINVAL);
1758 
1759 	if ((flag & AT_REMOVEDIR) != 0)
1760 		return (kern_frmdirat(td, dfd, path, fd, UIO_USERSPACE, 0));
1761 
1762 	return (kern_funlinkat(td, dfd, path, fd, UIO_USERSPACE, 0, 0));
1763 }
1764 
1765 #ifndef _SYS_SYSPROTO_H_
1766 struct unlinkat_args {
1767 	int	fd;
1768 	char	*path;
1769 	int	flag;
1770 };
1771 #endif
1772 int
1773 sys_unlinkat(struct thread *td, struct unlinkat_args *uap)
1774 {
1775 
1776 	return (kern_funlinkat_ex(td, uap->fd, uap->path, FD_NONE, uap->flag,
1777 	    UIO_USERSPACE, 0));
1778 }
1779 
1780 #ifndef _SYS_SYSPROTO_H_
1781 struct funlinkat_args {
1782 	int		dfd;
1783 	const char	*path;
1784 	int		fd;
1785 	int		flag;
1786 };
1787 #endif
1788 int
1789 sys_funlinkat(struct thread *td, struct funlinkat_args *uap)
1790 {
1791 
1792 	return (kern_funlinkat_ex(td, uap->dfd, uap->path, uap->fd, uap->flag,
1793 	    UIO_USERSPACE, 0));
1794 }
1795 
1796 int
1797 kern_funlinkat(struct thread *td, int dfd, const char *path, int fd,
1798     enum uio_seg pathseg, int flag, ino_t oldinum)
1799 {
1800 	struct mount *mp;
1801 	struct file *fp;
1802 	struct vnode *vp;
1803 	struct nameidata nd;
1804 	struct stat sb;
1805 	int error;
1806 
1807 	fp = NULL;
1808 	if (fd != FD_NONE) {
1809 		error = getvnode(td, fd, &cap_no_rights, &fp);
1810 		if (error != 0)
1811 			return (error);
1812 	}
1813 
1814 restart:
1815 	bwillwrite();
1816 	NDINIT_ATRIGHTS(&nd, DELETE, LOCKPARENT | LOCKLEAF | AUDITVNODE1 |
1817 	    ((flag & AT_BENEATH) != 0 ? BENEATH : 0),
1818 	    pathseg, path, dfd, &cap_unlinkat_rights, td);
1819 	if ((error = namei(&nd)) != 0) {
1820 		if (error == EINVAL)
1821 			error = EPERM;
1822 		goto fdout;
1823 	}
1824 	vp = nd.ni_vp;
1825 	if (vp->v_type == VDIR && oldinum == 0) {
1826 		error = EPERM;		/* POSIX */
1827 	} else if (oldinum != 0 &&
1828 		  ((error = vn_stat(vp, &sb, td->td_ucred, NOCRED, td)) == 0) &&
1829 		  sb.st_ino != oldinum) {
1830 		error = EIDRM;	/* Identifier removed */
1831 	} else if (fp != NULL && fp->f_vnode != vp) {
1832 		if (VN_IS_DOOMED(fp->f_vnode))
1833 			error = EBADF;
1834 		else
1835 			error = EDEADLK;
1836 	} else {
1837 		/*
1838 		 * The root of a mounted filesystem cannot be deleted.
1839 		 *
1840 		 * XXX: can this only be a VDIR case?
1841 		 */
1842 		if (vp->v_vflag & VV_ROOT)
1843 			error = EBUSY;
1844 	}
1845 	if (error == 0) {
1846 		if (vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
1847 			NDFREE(&nd, NDF_ONLY_PNBUF);
1848 			vput(nd.ni_dvp);
1849 			if (vp == nd.ni_dvp)
1850 				vrele(vp);
1851 			else
1852 				vput(vp);
1853 			if ((error = vn_start_write(NULL, &mp,
1854 			    V_XSLEEP | PCATCH)) != 0) {
1855 				goto fdout;
1856 			}
1857 			goto restart;
1858 		}
1859 #ifdef MAC
1860 		error = mac_vnode_check_unlink(td->td_ucred, nd.ni_dvp, vp,
1861 		    &nd.ni_cnd);
1862 		if (error != 0)
1863 			goto out;
1864 #endif
1865 		vfs_notify_upper(vp, VFS_NOTIFY_UPPER_UNLINK);
1866 		error = VOP_REMOVE(nd.ni_dvp, vp, &nd.ni_cnd);
1867 #ifdef MAC
1868 out:
1869 #endif
1870 		vn_finished_write(mp);
1871 	}
1872 	NDFREE(&nd, NDF_ONLY_PNBUF);
1873 	vput(nd.ni_dvp);
1874 	if (vp == nd.ni_dvp)
1875 		vrele(vp);
1876 	else
1877 		vput(vp);
1878 fdout:
1879 	if (fp != NULL)
1880 		fdrop(fp, td);
1881 	return (error);
1882 }
1883 
1884 /*
1885  * Reposition read/write file offset.
1886  */
1887 #ifndef _SYS_SYSPROTO_H_
1888 struct lseek_args {
1889 	int	fd;
1890 	int	pad;
1891 	off_t	offset;
1892 	int	whence;
1893 };
1894 #endif
1895 int
1896 sys_lseek(struct thread *td, struct lseek_args *uap)
1897 {
1898 
1899 	return (kern_lseek(td, uap->fd, uap->offset, uap->whence));
1900 }
1901 
1902 int
1903 kern_lseek(struct thread *td, int fd, off_t offset, int whence)
1904 {
1905 	struct file *fp;
1906 	int error;
1907 
1908 	AUDIT_ARG_FD(fd);
1909 	error = fget(td, fd, &cap_seek_rights, &fp);
1910 	if (error != 0)
1911 		return (error);
1912 	error = (fp->f_ops->fo_flags & DFLAG_SEEKABLE) != 0 ?
1913 	    fo_seek(fp, offset, whence, td) : ESPIPE;
1914 	fdrop(fp, td);
1915 	return (error);
1916 }
1917 
1918 #if defined(COMPAT_43)
1919 /*
1920  * Reposition read/write file offset.
1921  */
1922 #ifndef _SYS_SYSPROTO_H_
1923 struct olseek_args {
1924 	int	fd;
1925 	long	offset;
1926 	int	whence;
1927 };
1928 #endif
1929 int
1930 olseek(struct thread *td, struct olseek_args *uap)
1931 {
1932 
1933 	return (kern_lseek(td, uap->fd, uap->offset, uap->whence));
1934 }
1935 #endif /* COMPAT_43 */
1936 
1937 #if defined(COMPAT_FREEBSD6)
1938 /* Version with the 'pad' argument */
1939 int
1940 freebsd6_lseek(struct thread *td, struct freebsd6_lseek_args *uap)
1941 {
1942 
1943 	return (kern_lseek(td, uap->fd, uap->offset, uap->whence));
1944 }
1945 #endif
1946 
1947 /*
1948  * Check access permissions using passed credentials.
1949  */
1950 static int
1951 vn_access(struct vnode *vp, int user_flags, struct ucred *cred,
1952      struct thread *td)
1953 {
1954 	accmode_t accmode;
1955 	int error;
1956 
1957 	/* Flags == 0 means only check for existence. */
1958 	if (user_flags == 0)
1959 		return (0);
1960 
1961 	accmode = 0;
1962 	if (user_flags & R_OK)
1963 		accmode |= VREAD;
1964 	if (user_flags & W_OK)
1965 		accmode |= VWRITE;
1966 	if (user_flags & X_OK)
1967 		accmode |= VEXEC;
1968 #ifdef MAC
1969 	error = mac_vnode_check_access(cred, vp, accmode);
1970 	if (error != 0)
1971 		return (error);
1972 #endif
1973 	if ((accmode & VWRITE) == 0 || (error = vn_writechk(vp)) == 0)
1974 		error = VOP_ACCESS(vp, accmode, cred, td);
1975 	return (error);
1976 }
1977 
1978 /*
1979  * Check access permissions using "real" credentials.
1980  */
1981 #ifndef _SYS_SYSPROTO_H_
1982 struct access_args {
1983 	char	*path;
1984 	int	amode;
1985 };
1986 #endif
1987 int
1988 sys_access(struct thread *td, struct access_args *uap)
1989 {
1990 
1991 	return (kern_accessat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
1992 	    0, uap->amode));
1993 }
1994 
1995 #ifndef _SYS_SYSPROTO_H_
1996 struct faccessat_args {
1997 	int	dirfd;
1998 	char	*path;
1999 	int	amode;
2000 	int	flag;
2001 }
2002 #endif
2003 int
2004 sys_faccessat(struct thread *td, struct faccessat_args *uap)
2005 {
2006 
2007 	return (kern_accessat(td, uap->fd, uap->path, UIO_USERSPACE, uap->flag,
2008 	    uap->amode));
2009 }
2010 
2011 int
2012 kern_accessat(struct thread *td, int fd, const char *path,
2013     enum uio_seg pathseg, int flag, int amode)
2014 {
2015 	struct ucred *cred, *usecred;
2016 	struct vnode *vp;
2017 	struct nameidata nd;
2018 	int error;
2019 
2020 	if ((flag & ~(AT_EACCESS | AT_BENEATH)) != 0)
2021 		return (EINVAL);
2022 	if (amode != F_OK && (amode & ~(R_OK | W_OK | X_OK)) != 0)
2023 		return (EINVAL);
2024 
2025 	/*
2026 	 * Create and modify a temporary credential instead of one that
2027 	 * is potentially shared (if we need one).
2028 	 */
2029 	cred = td->td_ucred;
2030 	if ((flag & AT_EACCESS) == 0 &&
2031 	    ((cred->cr_uid != cred->cr_ruid ||
2032 	    cred->cr_rgid != cred->cr_groups[0]))) {
2033 		usecred = crdup(cred);
2034 		usecred->cr_uid = cred->cr_ruid;
2035 		usecred->cr_groups[0] = cred->cr_rgid;
2036 		td->td_ucred = usecred;
2037 	} else
2038 		usecred = cred;
2039 	AUDIT_ARG_VALUE(amode);
2040 	NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF |
2041 	    AUDITVNODE1 | ((flag & AT_BENEATH) != 0 ? BENEATH : 0),
2042 	    pathseg, path, fd, &cap_fstat_rights, td);
2043 	if ((error = namei(&nd)) != 0)
2044 		goto out;
2045 	vp = nd.ni_vp;
2046 
2047 	error = vn_access(vp, amode, usecred, td);
2048 	NDFREE(&nd, NDF_ONLY_PNBUF);
2049 	vput(vp);
2050 out:
2051 	if (usecred != cred) {
2052 		td->td_ucred = cred;
2053 		crfree(usecred);
2054 	}
2055 	return (error);
2056 }
2057 
2058 /*
2059  * Check access permissions using "effective" credentials.
2060  */
2061 #ifndef _SYS_SYSPROTO_H_
2062 struct eaccess_args {
2063 	char	*path;
2064 	int	amode;
2065 };
2066 #endif
2067 int
2068 sys_eaccess(struct thread *td, struct eaccess_args *uap)
2069 {
2070 
2071 	return (kern_accessat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
2072 	    AT_EACCESS, uap->amode));
2073 }
2074 
2075 #if defined(COMPAT_43)
2076 /*
2077  * Get file status; this version follows links.
2078  */
2079 #ifndef _SYS_SYSPROTO_H_
2080 struct ostat_args {
2081 	char	*path;
2082 	struct ostat *ub;
2083 };
2084 #endif
2085 int
2086 ostat(struct thread *td, struct ostat_args *uap)
2087 {
2088 	struct stat sb;
2089 	struct ostat osb;
2090 	int error;
2091 
2092 	error = kern_statat(td, 0, AT_FDCWD, uap->path, UIO_USERSPACE,
2093 	    &sb, NULL);
2094 	if (error != 0)
2095 		return (error);
2096 	cvtstat(&sb, &osb);
2097 	return (copyout(&osb, uap->ub, sizeof (osb)));
2098 }
2099 
2100 /*
2101  * Get file status; this version does not follow links.
2102  */
2103 #ifndef _SYS_SYSPROTO_H_
2104 struct olstat_args {
2105 	char	*path;
2106 	struct ostat *ub;
2107 };
2108 #endif
2109 int
2110 olstat(struct thread *td, struct olstat_args *uap)
2111 {
2112 	struct stat sb;
2113 	struct ostat osb;
2114 	int error;
2115 
2116 	error = kern_statat(td, AT_SYMLINK_NOFOLLOW, AT_FDCWD, uap->path,
2117 	    UIO_USERSPACE, &sb, NULL);
2118 	if (error != 0)
2119 		return (error);
2120 	cvtstat(&sb, &osb);
2121 	return (copyout(&osb, uap->ub, sizeof (osb)));
2122 }
2123 
2124 /*
2125  * Convert from an old to a new stat structure.
2126  * XXX: many values are blindly truncated.
2127  */
2128 void
2129 cvtstat(struct stat *st, struct ostat *ost)
2130 {
2131 
2132 	bzero(ost, sizeof(*ost));
2133 	ost->st_dev = st->st_dev;
2134 	ost->st_ino = st->st_ino;
2135 	ost->st_mode = st->st_mode;
2136 	ost->st_nlink = st->st_nlink;
2137 	ost->st_uid = st->st_uid;
2138 	ost->st_gid = st->st_gid;
2139 	ost->st_rdev = st->st_rdev;
2140 	ost->st_size = MIN(st->st_size, INT32_MAX);
2141 	ost->st_atim = st->st_atim;
2142 	ost->st_mtim = st->st_mtim;
2143 	ost->st_ctim = st->st_ctim;
2144 	ost->st_blksize = st->st_blksize;
2145 	ost->st_blocks = st->st_blocks;
2146 	ost->st_flags = st->st_flags;
2147 	ost->st_gen = st->st_gen;
2148 }
2149 #endif /* COMPAT_43 */
2150 
2151 #if defined(COMPAT_43) || defined(COMPAT_FREEBSD11)
2152 int ino64_trunc_error;
2153 SYSCTL_INT(_vfs, OID_AUTO, ino64_trunc_error, CTLFLAG_RW,
2154     &ino64_trunc_error, 0,
2155     "Error on truncation of device, file or inode number, or link count");
2156 
2157 int
2158 freebsd11_cvtstat(struct stat *st, struct freebsd11_stat *ost)
2159 {
2160 
2161 	ost->st_dev = st->st_dev;
2162 	if (ost->st_dev != st->st_dev) {
2163 		switch (ino64_trunc_error) {
2164 		default:
2165 			/*
2166 			 * Since dev_t is almost raw, don't clamp to the
2167 			 * maximum for case 2, but ignore the error.
2168 			 */
2169 			break;
2170 		case 1:
2171 			return (EOVERFLOW);
2172 		}
2173 	}
2174 	ost->st_ino = st->st_ino;
2175 	if (ost->st_ino != st->st_ino) {
2176 		switch (ino64_trunc_error) {
2177 		default:
2178 		case 0:
2179 			break;
2180 		case 1:
2181 			return (EOVERFLOW);
2182 		case 2:
2183 			ost->st_ino = UINT32_MAX;
2184 			break;
2185 		}
2186 	}
2187 	ost->st_mode = st->st_mode;
2188 	ost->st_nlink = st->st_nlink;
2189 	if (ost->st_nlink != st->st_nlink) {
2190 		switch (ino64_trunc_error) {
2191 		default:
2192 		case 0:
2193 			break;
2194 		case 1:
2195 			return (EOVERFLOW);
2196 		case 2:
2197 			ost->st_nlink = UINT16_MAX;
2198 			break;
2199 		}
2200 	}
2201 	ost->st_uid = st->st_uid;
2202 	ost->st_gid = st->st_gid;
2203 	ost->st_rdev = st->st_rdev;
2204 	if (ost->st_rdev != st->st_rdev) {
2205 		switch (ino64_trunc_error) {
2206 		default:
2207 			break;
2208 		case 1:
2209 			return (EOVERFLOW);
2210 		}
2211 	}
2212 	ost->st_atim = st->st_atim;
2213 	ost->st_mtim = st->st_mtim;
2214 	ost->st_ctim = st->st_ctim;
2215 	ost->st_size = st->st_size;
2216 	ost->st_blocks = st->st_blocks;
2217 	ost->st_blksize = st->st_blksize;
2218 	ost->st_flags = st->st_flags;
2219 	ost->st_gen = st->st_gen;
2220 	ost->st_lspare = 0;
2221 	ost->st_birthtim = st->st_birthtim;
2222 	bzero((char *)&ost->st_birthtim + sizeof(ost->st_birthtim),
2223 	    sizeof(*ost) - offsetof(struct freebsd11_stat,
2224 	    st_birthtim) - sizeof(ost->st_birthtim));
2225 	return (0);
2226 }
2227 
2228 int
2229 freebsd11_stat(struct thread *td, struct freebsd11_stat_args* uap)
2230 {
2231 	struct stat sb;
2232 	struct freebsd11_stat osb;
2233 	int error;
2234 
2235 	error = kern_statat(td, 0, AT_FDCWD, uap->path, UIO_USERSPACE,
2236 	    &sb, NULL);
2237 	if (error != 0)
2238 		return (error);
2239 	error = freebsd11_cvtstat(&sb, &osb);
2240 	if (error == 0)
2241 		error = copyout(&osb, uap->ub, sizeof(osb));
2242 	return (error);
2243 }
2244 
2245 int
2246 freebsd11_lstat(struct thread *td, struct freebsd11_lstat_args* uap)
2247 {
2248 	struct stat sb;
2249 	struct freebsd11_stat osb;
2250 	int error;
2251 
2252 	error = kern_statat(td, AT_SYMLINK_NOFOLLOW, AT_FDCWD, uap->path,
2253 	    UIO_USERSPACE, &sb, NULL);
2254 	if (error != 0)
2255 		return (error);
2256 	error = freebsd11_cvtstat(&sb, &osb);
2257 	if (error == 0)
2258 		error = copyout(&osb, uap->ub, sizeof(osb));
2259 	return (error);
2260 }
2261 
2262 int
2263 freebsd11_fhstat(struct thread *td, struct freebsd11_fhstat_args* uap)
2264 {
2265 	struct fhandle fh;
2266 	struct stat sb;
2267 	struct freebsd11_stat osb;
2268 	int error;
2269 
2270 	error = copyin(uap->u_fhp, &fh, sizeof(fhandle_t));
2271 	if (error != 0)
2272 		return (error);
2273 	error = kern_fhstat(td, fh, &sb);
2274 	if (error != 0)
2275 		return (error);
2276 	error = freebsd11_cvtstat(&sb, &osb);
2277 	if (error == 0)
2278 		error = copyout(&osb, uap->sb, sizeof(osb));
2279 	return (error);
2280 }
2281 
2282 int
2283 freebsd11_fstatat(struct thread *td, struct freebsd11_fstatat_args* uap)
2284 {
2285 	struct stat sb;
2286 	struct freebsd11_stat osb;
2287 	int error;
2288 
2289 	error = kern_statat(td, uap->flag, uap->fd, uap->path,
2290 	    UIO_USERSPACE, &sb, NULL);
2291 	if (error != 0)
2292 		return (error);
2293 	error = freebsd11_cvtstat(&sb, &osb);
2294 	if (error == 0)
2295 		error = copyout(&osb, uap->buf, sizeof(osb));
2296 	return (error);
2297 }
2298 #endif	/* COMPAT_FREEBSD11 */
2299 
2300 /*
2301  * Get file status
2302  */
2303 #ifndef _SYS_SYSPROTO_H_
2304 struct fstatat_args {
2305 	int	fd;
2306 	char	*path;
2307 	struct stat	*buf;
2308 	int	flag;
2309 }
2310 #endif
2311 int
2312 sys_fstatat(struct thread *td, struct fstatat_args *uap)
2313 {
2314 	struct stat sb;
2315 	int error;
2316 
2317 	error = kern_statat(td, uap->flag, uap->fd, uap->path,
2318 	    UIO_USERSPACE, &sb, NULL);
2319 	if (error == 0)
2320 		error = copyout(&sb, uap->buf, sizeof (sb));
2321 	return (error);
2322 }
2323 
2324 int
2325 kern_statat(struct thread *td, int flag, int fd, const char *path,
2326     enum uio_seg pathseg, struct stat *sbp,
2327     void (*hook)(struct vnode *vp, struct stat *sbp))
2328 {
2329 	struct nameidata nd;
2330 	int error;
2331 
2332 	if ((flag & ~(AT_SYMLINK_NOFOLLOW | AT_BENEATH)) != 0)
2333 		return (EINVAL);
2334 
2335 	NDINIT_ATRIGHTS(&nd, LOOKUP, ((flag & AT_SYMLINK_NOFOLLOW) != 0 ?
2336 	    NOFOLLOW : FOLLOW) | ((flag & AT_BENEATH) != 0 ? BENEATH : 0) |
2337 	    LOCKSHARED | LOCKLEAF | AUDITVNODE1, pathseg, path, fd,
2338 	    &cap_fstat_rights, td);
2339 
2340 	if ((error = namei(&nd)) != 0)
2341 		return (error);
2342 	error = vn_stat(nd.ni_vp, sbp, td->td_ucred, NOCRED, td);
2343 	if (error == 0) {
2344 		SDT_PROBE2(vfs, , stat, mode, path, sbp->st_mode);
2345 		if (S_ISREG(sbp->st_mode))
2346 			SDT_PROBE2(vfs, , stat, reg, path, pathseg);
2347 		if (__predict_false(hook != NULL))
2348 			hook(nd.ni_vp, sbp);
2349 	}
2350 	NDFREE(&nd, NDF_ONLY_PNBUF);
2351 	vput(nd.ni_vp);
2352 	if (error != 0)
2353 		return (error);
2354 #ifdef __STAT_TIME_T_EXT
2355 	sbp->st_atim_ext = 0;
2356 	sbp->st_mtim_ext = 0;
2357 	sbp->st_ctim_ext = 0;
2358 	sbp->st_btim_ext = 0;
2359 #endif
2360 #ifdef KTRACE
2361 	if (KTRPOINT(td, KTR_STRUCT))
2362 		ktrstat(sbp);
2363 #endif
2364 	return (0);
2365 }
2366 
2367 #if defined(COMPAT_FREEBSD11)
2368 /*
2369  * Implementation of the NetBSD [l]stat() functions.
2370  */
2371 void
2372 freebsd11_cvtnstat(struct stat *sb, struct nstat *nsb)
2373 {
2374 
2375 	bzero(nsb, sizeof(*nsb));
2376 	nsb->st_dev = sb->st_dev;
2377 	nsb->st_ino = sb->st_ino;
2378 	nsb->st_mode = sb->st_mode;
2379 	nsb->st_nlink = sb->st_nlink;
2380 	nsb->st_uid = sb->st_uid;
2381 	nsb->st_gid = sb->st_gid;
2382 	nsb->st_rdev = sb->st_rdev;
2383 	nsb->st_atim = sb->st_atim;
2384 	nsb->st_mtim = sb->st_mtim;
2385 	nsb->st_ctim = sb->st_ctim;
2386 	nsb->st_size = sb->st_size;
2387 	nsb->st_blocks = sb->st_blocks;
2388 	nsb->st_blksize = sb->st_blksize;
2389 	nsb->st_flags = sb->st_flags;
2390 	nsb->st_gen = sb->st_gen;
2391 	nsb->st_birthtim = sb->st_birthtim;
2392 }
2393 
2394 #ifndef _SYS_SYSPROTO_H_
2395 struct freebsd11_nstat_args {
2396 	char	*path;
2397 	struct nstat *ub;
2398 };
2399 #endif
2400 int
2401 freebsd11_nstat(struct thread *td, struct freebsd11_nstat_args *uap)
2402 {
2403 	struct stat sb;
2404 	struct nstat nsb;
2405 	int error;
2406 
2407 	error = kern_statat(td, 0, AT_FDCWD, uap->path, UIO_USERSPACE,
2408 	    &sb, NULL);
2409 	if (error != 0)
2410 		return (error);
2411 	freebsd11_cvtnstat(&sb, &nsb);
2412 	return (copyout(&nsb, uap->ub, sizeof (nsb)));
2413 }
2414 
2415 /*
2416  * NetBSD lstat.  Get file status; this version does not follow links.
2417  */
2418 #ifndef _SYS_SYSPROTO_H_
2419 struct freebsd11_nlstat_args {
2420 	char	*path;
2421 	struct nstat *ub;
2422 };
2423 #endif
2424 int
2425 freebsd11_nlstat(struct thread *td, struct freebsd11_nlstat_args *uap)
2426 {
2427 	struct stat sb;
2428 	struct nstat nsb;
2429 	int error;
2430 
2431 	error = kern_statat(td, AT_SYMLINK_NOFOLLOW, AT_FDCWD, uap->path,
2432 	    UIO_USERSPACE, &sb, NULL);
2433 	if (error != 0)
2434 		return (error);
2435 	freebsd11_cvtnstat(&sb, &nsb);
2436 	return (copyout(&nsb, uap->ub, sizeof (nsb)));
2437 }
2438 #endif /* COMPAT_FREEBSD11 */
2439 
2440 /*
2441  * Get configurable pathname variables.
2442  */
2443 #ifndef _SYS_SYSPROTO_H_
2444 struct pathconf_args {
2445 	char	*path;
2446 	int	name;
2447 };
2448 #endif
2449 int
2450 sys_pathconf(struct thread *td, struct pathconf_args *uap)
2451 {
2452 	long value;
2453 	int error;
2454 
2455 	error = kern_pathconf(td, uap->path, UIO_USERSPACE, uap->name, FOLLOW,
2456 	    &value);
2457 	if (error == 0)
2458 		td->td_retval[0] = value;
2459 	return (error);
2460 }
2461 
2462 #ifndef _SYS_SYSPROTO_H_
2463 struct lpathconf_args {
2464 	char	*path;
2465 	int	name;
2466 };
2467 #endif
2468 int
2469 sys_lpathconf(struct thread *td, struct lpathconf_args *uap)
2470 {
2471 	long value;
2472 	int error;
2473 
2474 	error = kern_pathconf(td, uap->path, UIO_USERSPACE, uap->name,
2475 	    NOFOLLOW, &value);
2476 	if (error == 0)
2477 		td->td_retval[0] = value;
2478 	return (error);
2479 }
2480 
2481 int
2482 kern_pathconf(struct thread *td, const char *path, enum uio_seg pathseg,
2483     int name, u_long flags, long *valuep)
2484 {
2485 	struct nameidata nd;
2486 	int error;
2487 
2488 	NDINIT(&nd, LOOKUP, LOCKSHARED | LOCKLEAF | AUDITVNODE1 | flags,
2489 	    pathseg, path, td);
2490 	if ((error = namei(&nd)) != 0)
2491 		return (error);
2492 	NDFREE(&nd, NDF_ONLY_PNBUF);
2493 
2494 	error = VOP_PATHCONF(nd.ni_vp, name, valuep);
2495 	vput(nd.ni_vp);
2496 	return (error);
2497 }
2498 
2499 /*
2500  * Return target name of a symbolic link.
2501  */
2502 #ifndef _SYS_SYSPROTO_H_
2503 struct readlink_args {
2504 	char	*path;
2505 	char	*buf;
2506 	size_t	count;
2507 };
2508 #endif
2509 int
2510 sys_readlink(struct thread *td, struct readlink_args *uap)
2511 {
2512 
2513 	return (kern_readlinkat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
2514 	    uap->buf, UIO_USERSPACE, uap->count));
2515 }
2516 #ifndef _SYS_SYSPROTO_H_
2517 struct readlinkat_args {
2518 	int	fd;
2519 	char	*path;
2520 	char	*buf;
2521 	size_t	bufsize;
2522 };
2523 #endif
2524 int
2525 sys_readlinkat(struct thread *td, struct readlinkat_args *uap)
2526 {
2527 
2528 	return (kern_readlinkat(td, uap->fd, uap->path, UIO_USERSPACE,
2529 	    uap->buf, UIO_USERSPACE, uap->bufsize));
2530 }
2531 
2532 int
2533 kern_readlinkat(struct thread *td, int fd, const char *path,
2534     enum uio_seg pathseg, char *buf, enum uio_seg bufseg, size_t count)
2535 {
2536 	struct vnode *vp;
2537 	struct nameidata nd;
2538 	int error;
2539 
2540 	if (count > IOSIZE_MAX)
2541 		return (EINVAL);
2542 
2543 	NDINIT_AT(&nd, LOOKUP, NOFOLLOW | LOCKSHARED | LOCKLEAF | AUDITVNODE1,
2544 	    pathseg, path, fd, td);
2545 
2546 	if ((error = namei(&nd)) != 0)
2547 		return (error);
2548 	NDFREE(&nd, NDF_ONLY_PNBUF);
2549 	vp = nd.ni_vp;
2550 
2551 	error = kern_readlink_vp(vp, buf, bufseg, count, td);
2552 	vput(vp);
2553 
2554 	return (error);
2555 }
2556 
2557 /*
2558  * Helper function to readlink from a vnode
2559  */
2560 static int
2561 kern_readlink_vp(struct vnode *vp, char *buf, enum uio_seg bufseg, size_t count,
2562     struct thread *td)
2563 {
2564 	struct iovec aiov;
2565 	struct uio auio;
2566 	int error;
2567 
2568 	ASSERT_VOP_LOCKED(vp, "kern_readlink_vp(): vp not locked");
2569 #ifdef MAC
2570 	error = mac_vnode_check_readlink(td->td_ucred, vp);
2571 	if (error != 0)
2572 		return (error);
2573 #endif
2574 	if (vp->v_type != VLNK && (vp->v_vflag & VV_READLINK) == 0)
2575 		return (EINVAL);
2576 
2577 	aiov.iov_base = buf;
2578 	aiov.iov_len = count;
2579 	auio.uio_iov = &aiov;
2580 	auio.uio_iovcnt = 1;
2581 	auio.uio_offset = 0;
2582 	auio.uio_rw = UIO_READ;
2583 	auio.uio_segflg = bufseg;
2584 	auio.uio_td = td;
2585 	auio.uio_resid = count;
2586 	error = VOP_READLINK(vp, &auio, td->td_ucred);
2587 	td->td_retval[0] = count - auio.uio_resid;
2588 	return (error);
2589 }
2590 
2591 /*
2592  * Common implementation code for chflags() and fchflags().
2593  */
2594 static int
2595 setfflags(struct thread *td, struct vnode *vp, u_long flags)
2596 {
2597 	struct mount *mp;
2598 	struct vattr vattr;
2599 	int error;
2600 
2601 	/* We can't support the value matching VNOVAL. */
2602 	if (flags == VNOVAL)
2603 		return (EOPNOTSUPP);
2604 
2605 	/*
2606 	 * Prevent non-root users from setting flags on devices.  When
2607 	 * a device is reused, users can retain ownership of the device
2608 	 * if they are allowed to set flags and programs assume that
2609 	 * chown can't fail when done as root.
2610 	 */
2611 	if (vp->v_type == VCHR || vp->v_type == VBLK) {
2612 		error = priv_check(td, PRIV_VFS_CHFLAGS_DEV);
2613 		if (error != 0)
2614 			return (error);
2615 	}
2616 
2617 	if ((error = vn_start_write(vp, &mp, V_WAIT | PCATCH)) != 0)
2618 		return (error);
2619 	VATTR_NULL(&vattr);
2620 	vattr.va_flags = flags;
2621 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2622 #ifdef MAC
2623 	error = mac_vnode_check_setflags(td->td_ucred, vp, vattr.va_flags);
2624 	if (error == 0)
2625 #endif
2626 		error = VOP_SETATTR(vp, &vattr, td->td_ucred);
2627 	VOP_UNLOCK(vp);
2628 	vn_finished_write(mp);
2629 	return (error);
2630 }
2631 
2632 /*
2633  * Change flags of a file given a path name.
2634  */
2635 #ifndef _SYS_SYSPROTO_H_
2636 struct chflags_args {
2637 	const char *path;
2638 	u_long	flags;
2639 };
2640 #endif
2641 int
2642 sys_chflags(struct thread *td, struct chflags_args *uap)
2643 {
2644 
2645 	return (kern_chflagsat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
2646 	    uap->flags, 0));
2647 }
2648 
2649 #ifndef _SYS_SYSPROTO_H_
2650 struct chflagsat_args {
2651 	int	fd;
2652 	const char *path;
2653 	u_long	flags;
2654 	int	atflag;
2655 }
2656 #endif
2657 int
2658 sys_chflagsat(struct thread *td, struct chflagsat_args *uap)
2659 {
2660 
2661 	if ((uap->atflag & ~(AT_SYMLINK_NOFOLLOW | AT_BENEATH)) != 0)
2662 		return (EINVAL);
2663 
2664 	return (kern_chflagsat(td, uap->fd, uap->path, UIO_USERSPACE,
2665 	    uap->flags, uap->atflag));
2666 }
2667 
2668 /*
2669  * Same as chflags() but doesn't follow symlinks.
2670  */
2671 #ifndef _SYS_SYSPROTO_H_
2672 struct lchflags_args {
2673 	const char *path;
2674 	u_long flags;
2675 };
2676 #endif
2677 int
2678 sys_lchflags(struct thread *td, struct lchflags_args *uap)
2679 {
2680 
2681 	return (kern_chflagsat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
2682 	    uap->flags, AT_SYMLINK_NOFOLLOW));
2683 }
2684 
2685 static int
2686 kern_chflagsat(struct thread *td, int fd, const char *path,
2687     enum uio_seg pathseg, u_long flags, int atflag)
2688 {
2689 	struct nameidata nd;
2690 	int error, follow;
2691 
2692 	AUDIT_ARG_FFLAGS(flags);
2693 	follow = (atflag & AT_SYMLINK_NOFOLLOW) ? NOFOLLOW : FOLLOW;
2694 	follow |= (atflag & AT_BENEATH) != 0 ? BENEATH : 0;
2695 	NDINIT_ATRIGHTS(&nd, LOOKUP, follow | AUDITVNODE1, pathseg, path, fd,
2696 	    &cap_fchflags_rights, td);
2697 	if ((error = namei(&nd)) != 0)
2698 		return (error);
2699 	NDFREE(&nd, NDF_ONLY_PNBUF);
2700 	error = setfflags(td, nd.ni_vp, flags);
2701 	vrele(nd.ni_vp);
2702 	return (error);
2703 }
2704 
2705 /*
2706  * Change flags of a file given a file descriptor.
2707  */
2708 #ifndef _SYS_SYSPROTO_H_
2709 struct fchflags_args {
2710 	int	fd;
2711 	u_long	flags;
2712 };
2713 #endif
2714 int
2715 sys_fchflags(struct thread *td, struct fchflags_args *uap)
2716 {
2717 	struct file *fp;
2718 	int error;
2719 
2720 	AUDIT_ARG_FD(uap->fd);
2721 	AUDIT_ARG_FFLAGS(uap->flags);
2722 	error = getvnode(td, uap->fd, &cap_fchflags_rights,
2723 	    &fp);
2724 	if (error != 0)
2725 		return (error);
2726 #ifdef AUDIT
2727 	vn_lock(fp->f_vnode, LK_SHARED | LK_RETRY);
2728 	AUDIT_ARG_VNODE1(fp->f_vnode);
2729 	VOP_UNLOCK(fp->f_vnode);
2730 #endif
2731 	error = setfflags(td, fp->f_vnode, uap->flags);
2732 	fdrop(fp, td);
2733 	return (error);
2734 }
2735 
2736 /*
2737  * Common implementation code for chmod(), lchmod() and fchmod().
2738  */
2739 int
2740 setfmode(struct thread *td, struct ucred *cred, struct vnode *vp, int mode)
2741 {
2742 	struct mount *mp;
2743 	struct vattr vattr;
2744 	int error;
2745 
2746 	if ((error = vn_start_write(vp, &mp, V_WAIT | PCATCH)) != 0)
2747 		return (error);
2748 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2749 	VATTR_NULL(&vattr);
2750 	vattr.va_mode = mode & ALLPERMS;
2751 #ifdef MAC
2752 	error = mac_vnode_check_setmode(cred, vp, vattr.va_mode);
2753 	if (error == 0)
2754 #endif
2755 		error = VOP_SETATTR(vp, &vattr, cred);
2756 	VOP_UNLOCK(vp);
2757 	vn_finished_write(mp);
2758 	return (error);
2759 }
2760 
2761 /*
2762  * Change mode of a file given path name.
2763  */
2764 #ifndef _SYS_SYSPROTO_H_
2765 struct chmod_args {
2766 	char	*path;
2767 	int	mode;
2768 };
2769 #endif
2770 int
2771 sys_chmod(struct thread *td, struct chmod_args *uap)
2772 {
2773 
2774 	return (kern_fchmodat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
2775 	    uap->mode, 0));
2776 }
2777 
2778 #ifndef _SYS_SYSPROTO_H_
2779 struct fchmodat_args {
2780 	int	dirfd;
2781 	char	*path;
2782 	mode_t	mode;
2783 	int	flag;
2784 }
2785 #endif
2786 int
2787 sys_fchmodat(struct thread *td, struct fchmodat_args *uap)
2788 {
2789 
2790 	if ((uap->flag & ~(AT_SYMLINK_NOFOLLOW | AT_BENEATH)) != 0)
2791 		return (EINVAL);
2792 
2793 	return (kern_fchmodat(td, uap->fd, uap->path, UIO_USERSPACE,
2794 	    uap->mode, uap->flag));
2795 }
2796 
2797 /*
2798  * Change mode of a file given path name (don't follow links.)
2799  */
2800 #ifndef _SYS_SYSPROTO_H_
2801 struct lchmod_args {
2802 	char	*path;
2803 	int	mode;
2804 };
2805 #endif
2806 int
2807 sys_lchmod(struct thread *td, struct lchmod_args *uap)
2808 {
2809 
2810 	return (kern_fchmodat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
2811 	    uap->mode, AT_SYMLINK_NOFOLLOW));
2812 }
2813 
2814 int
2815 kern_fchmodat(struct thread *td, int fd, const char *path,
2816     enum uio_seg pathseg, mode_t mode, int flag)
2817 {
2818 	struct nameidata nd;
2819 	int error, follow;
2820 
2821 	AUDIT_ARG_MODE(mode);
2822 	follow = (flag & AT_SYMLINK_NOFOLLOW) != 0 ? NOFOLLOW : FOLLOW;
2823 	follow |= (flag & AT_BENEATH) != 0 ? BENEATH : 0;
2824 	NDINIT_ATRIGHTS(&nd, LOOKUP, follow | AUDITVNODE1, pathseg, path, fd,
2825 	    &cap_fchmod_rights, td);
2826 	if ((error = namei(&nd)) != 0)
2827 		return (error);
2828 	NDFREE(&nd, NDF_ONLY_PNBUF);
2829 	error = setfmode(td, td->td_ucred, nd.ni_vp, mode);
2830 	vrele(nd.ni_vp);
2831 	return (error);
2832 }
2833 
2834 /*
2835  * Change mode of a file given a file descriptor.
2836  */
2837 #ifndef _SYS_SYSPROTO_H_
2838 struct fchmod_args {
2839 	int	fd;
2840 	int	mode;
2841 };
2842 #endif
2843 int
2844 sys_fchmod(struct thread *td, struct fchmod_args *uap)
2845 {
2846 	struct file *fp;
2847 	int error;
2848 
2849 	AUDIT_ARG_FD(uap->fd);
2850 	AUDIT_ARG_MODE(uap->mode);
2851 
2852 	error = fget(td, uap->fd, &cap_fchmod_rights, &fp);
2853 	if (error != 0)
2854 		return (error);
2855 	error = fo_chmod(fp, uap->mode, td->td_ucred, td);
2856 	fdrop(fp, td);
2857 	return (error);
2858 }
2859 
2860 /*
2861  * Common implementation for chown(), lchown(), and fchown()
2862  */
2863 int
2864 setfown(struct thread *td, struct ucred *cred, struct vnode *vp, uid_t uid,
2865     gid_t gid)
2866 {
2867 	struct mount *mp;
2868 	struct vattr vattr;
2869 	int error;
2870 
2871 	if ((error = vn_start_write(vp, &mp, V_WAIT | PCATCH)) != 0)
2872 		return (error);
2873 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2874 	VATTR_NULL(&vattr);
2875 	vattr.va_uid = uid;
2876 	vattr.va_gid = gid;
2877 #ifdef MAC
2878 	error = mac_vnode_check_setowner(cred, vp, vattr.va_uid,
2879 	    vattr.va_gid);
2880 	if (error == 0)
2881 #endif
2882 		error = VOP_SETATTR(vp, &vattr, cred);
2883 	VOP_UNLOCK(vp);
2884 	vn_finished_write(mp);
2885 	return (error);
2886 }
2887 
2888 /*
2889  * Set ownership given a path name.
2890  */
2891 #ifndef _SYS_SYSPROTO_H_
2892 struct chown_args {
2893 	char	*path;
2894 	int	uid;
2895 	int	gid;
2896 };
2897 #endif
2898 int
2899 sys_chown(struct thread *td, struct chown_args *uap)
2900 {
2901 
2902 	return (kern_fchownat(td, AT_FDCWD, uap->path, UIO_USERSPACE, uap->uid,
2903 	    uap->gid, 0));
2904 }
2905 
2906 #ifndef _SYS_SYSPROTO_H_
2907 struct fchownat_args {
2908 	int fd;
2909 	const char * path;
2910 	uid_t uid;
2911 	gid_t gid;
2912 	int flag;
2913 };
2914 #endif
2915 int
2916 sys_fchownat(struct thread *td, struct fchownat_args *uap)
2917 {
2918 
2919 	if ((uap->flag & ~(AT_SYMLINK_NOFOLLOW | AT_BENEATH)) != 0)
2920 		return (EINVAL);
2921 
2922 	return (kern_fchownat(td, uap->fd, uap->path, UIO_USERSPACE, uap->uid,
2923 	    uap->gid, uap->flag));
2924 }
2925 
2926 int
2927 kern_fchownat(struct thread *td, int fd, const char *path,
2928     enum uio_seg pathseg, int uid, int gid, int flag)
2929 {
2930 	struct nameidata nd;
2931 	int error, follow;
2932 
2933 	AUDIT_ARG_OWNER(uid, gid);
2934 	follow = (flag & AT_SYMLINK_NOFOLLOW) ? NOFOLLOW : FOLLOW;
2935 	follow |= (flag & AT_BENEATH) != 0 ? BENEATH : 0;
2936 	NDINIT_ATRIGHTS(&nd, LOOKUP, follow | AUDITVNODE1, pathseg, path, fd,
2937 	    &cap_fchown_rights, td);
2938 
2939 	if ((error = namei(&nd)) != 0)
2940 		return (error);
2941 	NDFREE(&nd, NDF_ONLY_PNBUF);
2942 	error = setfown(td, td->td_ucred, nd.ni_vp, uid, gid);
2943 	vrele(nd.ni_vp);
2944 	return (error);
2945 }
2946 
2947 /*
2948  * Set ownership given a path name, do not cross symlinks.
2949  */
2950 #ifndef _SYS_SYSPROTO_H_
2951 struct lchown_args {
2952 	char	*path;
2953 	int	uid;
2954 	int	gid;
2955 };
2956 #endif
2957 int
2958 sys_lchown(struct thread *td, struct lchown_args *uap)
2959 {
2960 
2961 	return (kern_fchownat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
2962 	    uap->uid, uap->gid, AT_SYMLINK_NOFOLLOW));
2963 }
2964 
2965 /*
2966  * Set ownership given a file descriptor.
2967  */
2968 #ifndef _SYS_SYSPROTO_H_
2969 struct fchown_args {
2970 	int	fd;
2971 	int	uid;
2972 	int	gid;
2973 };
2974 #endif
2975 int
2976 sys_fchown(struct thread *td, struct fchown_args *uap)
2977 {
2978 	struct file *fp;
2979 	int error;
2980 
2981 	AUDIT_ARG_FD(uap->fd);
2982 	AUDIT_ARG_OWNER(uap->uid, uap->gid);
2983 	error = fget(td, uap->fd, &cap_fchown_rights, &fp);
2984 	if (error != 0)
2985 		return (error);
2986 	error = fo_chown(fp, uap->uid, uap->gid, td->td_ucred, td);
2987 	fdrop(fp, td);
2988 	return (error);
2989 }
2990 
2991 /*
2992  * Common implementation code for utimes(), lutimes(), and futimes().
2993  */
2994 static int
2995 getutimes(const struct timeval *usrtvp, enum uio_seg tvpseg,
2996     struct timespec *tsp)
2997 {
2998 	struct timeval tv[2];
2999 	const struct timeval *tvp;
3000 	int error;
3001 
3002 	if (usrtvp == NULL) {
3003 		vfs_timestamp(&tsp[0]);
3004 		tsp[1] = tsp[0];
3005 	} else {
3006 		if (tvpseg == UIO_SYSSPACE) {
3007 			tvp = usrtvp;
3008 		} else {
3009 			if ((error = copyin(usrtvp, tv, sizeof(tv))) != 0)
3010 				return (error);
3011 			tvp = tv;
3012 		}
3013 
3014 		if (tvp[0].tv_usec < 0 || tvp[0].tv_usec >= 1000000 ||
3015 		    tvp[1].tv_usec < 0 || tvp[1].tv_usec >= 1000000)
3016 			return (EINVAL);
3017 		TIMEVAL_TO_TIMESPEC(&tvp[0], &tsp[0]);
3018 		TIMEVAL_TO_TIMESPEC(&tvp[1], &tsp[1]);
3019 	}
3020 	return (0);
3021 }
3022 
3023 /*
3024  * Common implementation code for futimens(), utimensat().
3025  */
3026 #define	UTIMENS_NULL	0x1
3027 #define	UTIMENS_EXIT	0x2
3028 static int
3029 getutimens(const struct timespec *usrtsp, enum uio_seg tspseg,
3030     struct timespec *tsp, int *retflags)
3031 {
3032 	struct timespec tsnow;
3033 	int error;
3034 
3035 	vfs_timestamp(&tsnow);
3036 	*retflags = 0;
3037 	if (usrtsp == NULL) {
3038 		tsp[0] = tsnow;
3039 		tsp[1] = tsnow;
3040 		*retflags |= UTIMENS_NULL;
3041 		return (0);
3042 	}
3043 	if (tspseg == UIO_SYSSPACE) {
3044 		tsp[0] = usrtsp[0];
3045 		tsp[1] = usrtsp[1];
3046 	} else if ((error = copyin(usrtsp, tsp, sizeof(*tsp) * 2)) != 0)
3047 		return (error);
3048 	if (tsp[0].tv_nsec == UTIME_OMIT && tsp[1].tv_nsec == UTIME_OMIT)
3049 		*retflags |= UTIMENS_EXIT;
3050 	if (tsp[0].tv_nsec == UTIME_NOW && tsp[1].tv_nsec == UTIME_NOW)
3051 		*retflags |= UTIMENS_NULL;
3052 	if (tsp[0].tv_nsec == UTIME_OMIT)
3053 		tsp[0].tv_sec = VNOVAL;
3054 	else if (tsp[0].tv_nsec == UTIME_NOW)
3055 		tsp[0] = tsnow;
3056 	else if (tsp[0].tv_nsec < 0 || tsp[0].tv_nsec >= 1000000000L)
3057 		return (EINVAL);
3058 	if (tsp[1].tv_nsec == UTIME_OMIT)
3059 		tsp[1].tv_sec = VNOVAL;
3060 	else if (tsp[1].tv_nsec == UTIME_NOW)
3061 		tsp[1] = tsnow;
3062 	else if (tsp[1].tv_nsec < 0 || tsp[1].tv_nsec >= 1000000000L)
3063 		return (EINVAL);
3064 
3065 	return (0);
3066 }
3067 
3068 /*
3069  * Common implementation code for utimes(), lutimes(), futimes(), futimens(),
3070  * and utimensat().
3071  */
3072 static int
3073 setutimes(struct thread *td, struct vnode *vp, const struct timespec *ts,
3074     int numtimes, int nullflag)
3075 {
3076 	struct mount *mp;
3077 	struct vattr vattr;
3078 	int error, setbirthtime;
3079 
3080 	if ((error = vn_start_write(vp, &mp, V_WAIT | PCATCH)) != 0)
3081 		return (error);
3082 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3083 	setbirthtime = 0;
3084 	if (numtimes < 3 && !VOP_GETATTR(vp, &vattr, td->td_ucred) &&
3085 	    timespeccmp(&ts[1], &vattr.va_birthtime, < ))
3086 		setbirthtime = 1;
3087 	VATTR_NULL(&vattr);
3088 	vattr.va_atime = ts[0];
3089 	vattr.va_mtime = ts[1];
3090 	if (setbirthtime)
3091 		vattr.va_birthtime = ts[1];
3092 	if (numtimes > 2)
3093 		vattr.va_birthtime = ts[2];
3094 	if (nullflag)
3095 		vattr.va_vaflags |= VA_UTIMES_NULL;
3096 #ifdef MAC
3097 	error = mac_vnode_check_setutimes(td->td_ucred, vp, vattr.va_atime,
3098 	    vattr.va_mtime);
3099 #endif
3100 	if (error == 0)
3101 		error = VOP_SETATTR(vp, &vattr, td->td_ucred);
3102 	VOP_UNLOCK(vp);
3103 	vn_finished_write(mp);
3104 	return (error);
3105 }
3106 
3107 /*
3108  * Set the access and modification times of a file.
3109  */
3110 #ifndef _SYS_SYSPROTO_H_
3111 struct utimes_args {
3112 	char	*path;
3113 	struct	timeval *tptr;
3114 };
3115 #endif
3116 int
3117 sys_utimes(struct thread *td, struct utimes_args *uap)
3118 {
3119 
3120 	return (kern_utimesat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
3121 	    uap->tptr, UIO_USERSPACE));
3122 }
3123 
3124 #ifndef _SYS_SYSPROTO_H_
3125 struct futimesat_args {
3126 	int fd;
3127 	const char * path;
3128 	const struct timeval * times;
3129 };
3130 #endif
3131 int
3132 sys_futimesat(struct thread *td, struct futimesat_args *uap)
3133 {
3134 
3135 	return (kern_utimesat(td, uap->fd, uap->path, UIO_USERSPACE,
3136 	    uap->times, UIO_USERSPACE));
3137 }
3138 
3139 int
3140 kern_utimesat(struct thread *td, int fd, const char *path,
3141     enum uio_seg pathseg, struct timeval *tptr, enum uio_seg tptrseg)
3142 {
3143 	struct nameidata nd;
3144 	struct timespec ts[2];
3145 	int error;
3146 
3147 	if ((error = getutimes(tptr, tptrseg, ts)) != 0)
3148 		return (error);
3149 	NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | AUDITVNODE1, pathseg, path, fd,
3150 	    &cap_futimes_rights, td);
3151 
3152 	if ((error = namei(&nd)) != 0)
3153 		return (error);
3154 	NDFREE(&nd, NDF_ONLY_PNBUF);
3155 	error = setutimes(td, nd.ni_vp, ts, 2, tptr == NULL);
3156 	vrele(nd.ni_vp);
3157 	return (error);
3158 }
3159 
3160 /*
3161  * Set the access and modification times of a file.
3162  */
3163 #ifndef _SYS_SYSPROTO_H_
3164 struct lutimes_args {
3165 	char	*path;
3166 	struct	timeval *tptr;
3167 };
3168 #endif
3169 int
3170 sys_lutimes(struct thread *td, struct lutimes_args *uap)
3171 {
3172 
3173 	return (kern_lutimes(td, uap->path, UIO_USERSPACE, uap->tptr,
3174 	    UIO_USERSPACE));
3175 }
3176 
3177 int
3178 kern_lutimes(struct thread *td, const char *path, enum uio_seg pathseg,
3179     struct timeval *tptr, enum uio_seg tptrseg)
3180 {
3181 	struct timespec ts[2];
3182 	struct nameidata nd;
3183 	int error;
3184 
3185 	if ((error = getutimes(tptr, tptrseg, ts)) != 0)
3186 		return (error);
3187 	NDINIT(&nd, LOOKUP, NOFOLLOW | AUDITVNODE1, pathseg, path, td);
3188 	if ((error = namei(&nd)) != 0)
3189 		return (error);
3190 	NDFREE(&nd, NDF_ONLY_PNBUF);
3191 	error = setutimes(td, nd.ni_vp, ts, 2, tptr == NULL);
3192 	vrele(nd.ni_vp);
3193 	return (error);
3194 }
3195 
3196 /*
3197  * Set the access and modification times of a file.
3198  */
3199 #ifndef _SYS_SYSPROTO_H_
3200 struct futimes_args {
3201 	int	fd;
3202 	struct	timeval *tptr;
3203 };
3204 #endif
3205 int
3206 sys_futimes(struct thread *td, struct futimes_args *uap)
3207 {
3208 
3209 	return (kern_futimes(td, uap->fd, uap->tptr, UIO_USERSPACE));
3210 }
3211 
3212 int
3213 kern_futimes(struct thread *td, int fd, struct timeval *tptr,
3214     enum uio_seg tptrseg)
3215 {
3216 	struct timespec ts[2];
3217 	struct file *fp;
3218 	int error;
3219 
3220 	AUDIT_ARG_FD(fd);
3221 	error = getutimes(tptr, tptrseg, ts);
3222 	if (error != 0)
3223 		return (error);
3224 	error = getvnode(td, fd, &cap_futimes_rights, &fp);
3225 	if (error != 0)
3226 		return (error);
3227 #ifdef AUDIT
3228 	vn_lock(fp->f_vnode, LK_SHARED | LK_RETRY);
3229 	AUDIT_ARG_VNODE1(fp->f_vnode);
3230 	VOP_UNLOCK(fp->f_vnode);
3231 #endif
3232 	error = setutimes(td, fp->f_vnode, ts, 2, tptr == NULL);
3233 	fdrop(fp, td);
3234 	return (error);
3235 }
3236 
3237 int
3238 sys_futimens(struct thread *td, struct futimens_args *uap)
3239 {
3240 
3241 	return (kern_futimens(td, uap->fd, uap->times, UIO_USERSPACE));
3242 }
3243 
3244 int
3245 kern_futimens(struct thread *td, int fd, struct timespec *tptr,
3246     enum uio_seg tptrseg)
3247 {
3248 	struct timespec ts[2];
3249 	struct file *fp;
3250 	int error, flags;
3251 
3252 	AUDIT_ARG_FD(fd);
3253 	error = getutimens(tptr, tptrseg, ts, &flags);
3254 	if (error != 0)
3255 		return (error);
3256 	if (flags & UTIMENS_EXIT)
3257 		return (0);
3258 	error = getvnode(td, fd, &cap_futimes_rights, &fp);
3259 	if (error != 0)
3260 		return (error);
3261 #ifdef AUDIT
3262 	vn_lock(fp->f_vnode, LK_SHARED | LK_RETRY);
3263 	AUDIT_ARG_VNODE1(fp->f_vnode);
3264 	VOP_UNLOCK(fp->f_vnode);
3265 #endif
3266 	error = setutimes(td, fp->f_vnode, ts, 2, flags & UTIMENS_NULL);
3267 	fdrop(fp, td);
3268 	return (error);
3269 }
3270 
3271 int
3272 sys_utimensat(struct thread *td, struct utimensat_args *uap)
3273 {
3274 
3275 	return (kern_utimensat(td, uap->fd, uap->path, UIO_USERSPACE,
3276 	    uap->times, UIO_USERSPACE, uap->flag));
3277 }
3278 
3279 int
3280 kern_utimensat(struct thread *td, int fd, const char *path,
3281     enum uio_seg pathseg, struct timespec *tptr, enum uio_seg tptrseg,
3282     int flag)
3283 {
3284 	struct nameidata nd;
3285 	struct timespec ts[2];
3286 	int error, flags;
3287 
3288 	if ((flag & ~(AT_SYMLINK_NOFOLLOW | AT_BENEATH)) != 0)
3289 		return (EINVAL);
3290 
3291 	if ((error = getutimens(tptr, tptrseg, ts, &flags)) != 0)
3292 		return (error);
3293 	NDINIT_ATRIGHTS(&nd, LOOKUP, ((flag & AT_SYMLINK_NOFOLLOW) ? NOFOLLOW :
3294 	    FOLLOW) |  ((flag & AT_BENEATH) != 0 ? BENEATH : 0) | AUDITVNODE1,
3295 	    pathseg, path, fd, &cap_futimes_rights, td);
3296 	if ((error = namei(&nd)) != 0)
3297 		return (error);
3298 	/*
3299 	 * We are allowed to call namei() regardless of 2xUTIME_OMIT.
3300 	 * POSIX states:
3301 	 * "If both tv_nsec fields are UTIME_OMIT... EACCESS may be detected."
3302 	 * "Search permission is denied by a component of the path prefix."
3303 	 */
3304 	NDFREE(&nd, NDF_ONLY_PNBUF);
3305 	if ((flags & UTIMENS_EXIT) == 0)
3306 		error = setutimes(td, nd.ni_vp, ts, 2, flags & UTIMENS_NULL);
3307 	vrele(nd.ni_vp);
3308 	return (error);
3309 }
3310 
3311 /*
3312  * Truncate a file given its path name.
3313  */
3314 #ifndef _SYS_SYSPROTO_H_
3315 struct truncate_args {
3316 	char	*path;
3317 	int	pad;
3318 	off_t	length;
3319 };
3320 #endif
3321 int
3322 sys_truncate(struct thread *td, struct truncate_args *uap)
3323 {
3324 
3325 	return (kern_truncate(td, uap->path, UIO_USERSPACE, uap->length));
3326 }
3327 
3328 int
3329 kern_truncate(struct thread *td, const char *path, enum uio_seg pathseg,
3330     off_t length)
3331 {
3332 	struct mount *mp;
3333 	struct vnode *vp;
3334 	void *rl_cookie;
3335 	struct vattr vattr;
3336 	struct nameidata nd;
3337 	int error;
3338 
3339 	if (length < 0)
3340 		return(EINVAL);
3341 	NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, pathseg, path, td);
3342 	if ((error = namei(&nd)) != 0)
3343 		return (error);
3344 	vp = nd.ni_vp;
3345 	rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
3346 	if ((error = vn_start_write(vp, &mp, V_WAIT | PCATCH)) != 0) {
3347 		vn_rangelock_unlock(vp, rl_cookie);
3348 		vrele(vp);
3349 		return (error);
3350 	}
3351 	NDFREE(&nd, NDF_ONLY_PNBUF);
3352 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3353 	if (vp->v_type == VDIR)
3354 		error = EISDIR;
3355 #ifdef MAC
3356 	else if ((error = mac_vnode_check_write(td->td_ucred, NOCRED, vp))) {
3357 	}
3358 #endif
3359 	else if ((error = vn_writechk(vp)) == 0 &&
3360 	    (error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td)) == 0) {
3361 		VATTR_NULL(&vattr);
3362 		vattr.va_size = length;
3363 		error = VOP_SETATTR(vp, &vattr, td->td_ucred);
3364 	}
3365 	VOP_UNLOCK(vp);
3366 	vn_finished_write(mp);
3367 	vn_rangelock_unlock(vp, rl_cookie);
3368 	vrele(vp);
3369 	return (error);
3370 }
3371 
3372 #if defined(COMPAT_43)
3373 /*
3374  * Truncate a file given its path name.
3375  */
3376 #ifndef _SYS_SYSPROTO_H_
3377 struct otruncate_args {
3378 	char	*path;
3379 	long	length;
3380 };
3381 #endif
3382 int
3383 otruncate(struct thread *td, struct otruncate_args *uap)
3384 {
3385 
3386 	return (kern_truncate(td, uap->path, UIO_USERSPACE, uap->length));
3387 }
3388 #endif /* COMPAT_43 */
3389 
3390 #if defined(COMPAT_FREEBSD6)
3391 /* Versions with the pad argument */
3392 int
3393 freebsd6_truncate(struct thread *td, struct freebsd6_truncate_args *uap)
3394 {
3395 
3396 	return (kern_truncate(td, uap->path, UIO_USERSPACE, uap->length));
3397 }
3398 
3399 int
3400 freebsd6_ftruncate(struct thread *td, struct freebsd6_ftruncate_args *uap)
3401 {
3402 
3403 	return (kern_ftruncate(td, uap->fd, uap->length));
3404 }
3405 #endif
3406 
3407 int
3408 kern_fsync(struct thread *td, int fd, bool fullsync)
3409 {
3410 	struct vnode *vp;
3411 	struct mount *mp;
3412 	struct file *fp;
3413 	int error, lock_flags;
3414 
3415 	AUDIT_ARG_FD(fd);
3416 	error = getvnode(td, fd, &cap_fsync_rights, &fp);
3417 	if (error != 0)
3418 		return (error);
3419 	vp = fp->f_vnode;
3420 #if 0
3421 	if (!fullsync)
3422 		/* XXXKIB: compete outstanding aio writes */;
3423 #endif
3424 	error = vn_start_write(vp, &mp, V_WAIT | PCATCH);
3425 	if (error != 0)
3426 		goto drop;
3427 	if (MNT_SHARED_WRITES(mp) ||
3428 	    ((mp == NULL) && MNT_SHARED_WRITES(vp->v_mount))) {
3429 		lock_flags = LK_SHARED;
3430 	} else {
3431 		lock_flags = LK_EXCLUSIVE;
3432 	}
3433 	vn_lock(vp, lock_flags | LK_RETRY);
3434 	AUDIT_ARG_VNODE1(vp);
3435 	if (vp->v_object != NULL) {
3436 		VM_OBJECT_WLOCK(vp->v_object);
3437 		vm_object_page_clean(vp->v_object, 0, 0, 0);
3438 		VM_OBJECT_WUNLOCK(vp->v_object);
3439 	}
3440 	error = fullsync ? VOP_FSYNC(vp, MNT_WAIT, td) : VOP_FDATASYNC(vp, td);
3441 	VOP_UNLOCK(vp);
3442 	vn_finished_write(mp);
3443 drop:
3444 	fdrop(fp, td);
3445 	return (error);
3446 }
3447 
3448 /*
3449  * Sync an open file.
3450  */
3451 #ifndef _SYS_SYSPROTO_H_
3452 struct fsync_args {
3453 	int	fd;
3454 };
3455 #endif
3456 int
3457 sys_fsync(struct thread *td, struct fsync_args *uap)
3458 {
3459 
3460 	return (kern_fsync(td, uap->fd, true));
3461 }
3462 
3463 int
3464 sys_fdatasync(struct thread *td, struct fdatasync_args *uap)
3465 {
3466 
3467 	return (kern_fsync(td, uap->fd, false));
3468 }
3469 
3470 /*
3471  * Rename files.  Source and destination must either both be directories, or
3472  * both not be directories.  If target is a directory, it must be empty.
3473  */
3474 #ifndef _SYS_SYSPROTO_H_
3475 struct rename_args {
3476 	char	*from;
3477 	char	*to;
3478 };
3479 #endif
3480 int
3481 sys_rename(struct thread *td, struct rename_args *uap)
3482 {
3483 
3484 	return (kern_renameat(td, AT_FDCWD, uap->from, AT_FDCWD,
3485 	    uap->to, UIO_USERSPACE));
3486 }
3487 
3488 #ifndef _SYS_SYSPROTO_H_
3489 struct renameat_args {
3490 	int	oldfd;
3491 	char	*old;
3492 	int	newfd;
3493 	char	*new;
3494 };
3495 #endif
3496 int
3497 sys_renameat(struct thread *td, struct renameat_args *uap)
3498 {
3499 
3500 	return (kern_renameat(td, uap->oldfd, uap->old, uap->newfd, uap->new,
3501 	    UIO_USERSPACE));
3502 }
3503 
3504 int
3505 kern_renameat(struct thread *td, int oldfd, const char *old, int newfd,
3506     const char *new, enum uio_seg pathseg)
3507 {
3508 	struct mount *mp = NULL;
3509 	struct vnode *tvp, *fvp, *tdvp;
3510 	struct nameidata fromnd, tond;
3511 	int error;
3512 
3513 again:
3514 	bwillwrite();
3515 #ifdef MAC
3516 	NDINIT_ATRIGHTS(&fromnd, DELETE, LOCKPARENT | LOCKLEAF | SAVESTART |
3517 	    AUDITVNODE1, pathseg, old, oldfd,
3518 	    &cap_renameat_source_rights, td);
3519 #else
3520 	NDINIT_ATRIGHTS(&fromnd, DELETE, WANTPARENT | SAVESTART | AUDITVNODE1,
3521 	    pathseg, old, oldfd,
3522 	    &cap_renameat_source_rights, td);
3523 #endif
3524 
3525 	if ((error = namei(&fromnd)) != 0)
3526 		return (error);
3527 #ifdef MAC
3528 	error = mac_vnode_check_rename_from(td->td_ucred, fromnd.ni_dvp,
3529 	    fromnd.ni_vp, &fromnd.ni_cnd);
3530 	VOP_UNLOCK(fromnd.ni_dvp);
3531 	if (fromnd.ni_dvp != fromnd.ni_vp)
3532 		VOP_UNLOCK(fromnd.ni_vp);
3533 #endif
3534 	fvp = fromnd.ni_vp;
3535 	NDINIT_ATRIGHTS(&tond, RENAME, LOCKPARENT | LOCKLEAF | NOCACHE |
3536 	    SAVESTART | AUDITVNODE2, pathseg, new, newfd,
3537 	    &cap_renameat_target_rights, td);
3538 	if (fromnd.ni_vp->v_type == VDIR)
3539 		tond.ni_cnd.cn_flags |= WILLBEDIR;
3540 	if ((error = namei(&tond)) != 0) {
3541 		/* Translate error code for rename("dir1", "dir2/."). */
3542 		if (error == EISDIR && fvp->v_type == VDIR)
3543 			error = EINVAL;
3544 		NDFREE(&fromnd, NDF_ONLY_PNBUF);
3545 		vrele(fromnd.ni_dvp);
3546 		vrele(fvp);
3547 		goto out1;
3548 	}
3549 	tdvp = tond.ni_dvp;
3550 	tvp = tond.ni_vp;
3551 	error = vn_start_write(fvp, &mp, V_NOWAIT);
3552 	if (error != 0) {
3553 		NDFREE(&fromnd, NDF_ONLY_PNBUF);
3554 		NDFREE(&tond, NDF_ONLY_PNBUF);
3555 		if (tvp != NULL)
3556 			vput(tvp);
3557 		if (tdvp == tvp)
3558 			vrele(tdvp);
3559 		else
3560 			vput(tdvp);
3561 		vrele(fromnd.ni_dvp);
3562 		vrele(fvp);
3563 		vrele(tond.ni_startdir);
3564 		if (fromnd.ni_startdir != NULL)
3565 			vrele(fromnd.ni_startdir);
3566 		error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
3567 		if (error != 0)
3568 			return (error);
3569 		goto again;
3570 	}
3571 	if (tvp != NULL) {
3572 		if (fvp->v_type == VDIR && tvp->v_type != VDIR) {
3573 			error = ENOTDIR;
3574 			goto out;
3575 		} else if (fvp->v_type != VDIR && tvp->v_type == VDIR) {
3576 			error = EISDIR;
3577 			goto out;
3578 		}
3579 #ifdef CAPABILITIES
3580 		if (newfd != AT_FDCWD && (tond.ni_resflags & NIRES_ABS) == 0) {
3581 			/*
3582 			 * If the target already exists we require CAP_UNLINKAT
3583 			 * from 'newfd', when newfd was used for the lookup.
3584 			 */
3585 			error = cap_check(&tond.ni_filecaps.fc_rights,
3586 			    &cap_unlinkat_rights);
3587 			if (error != 0)
3588 				goto out;
3589 		}
3590 #endif
3591 	}
3592 	if (fvp == tdvp) {
3593 		error = EINVAL;
3594 		goto out;
3595 	}
3596 	/*
3597 	 * If the source is the same as the destination (that is, if they
3598 	 * are links to the same vnode), then there is nothing to do.
3599 	 */
3600 	if (fvp == tvp)
3601 		error = -1;
3602 #ifdef MAC
3603 	else
3604 		error = mac_vnode_check_rename_to(td->td_ucred, tdvp,
3605 		    tond.ni_vp, fromnd.ni_dvp == tdvp, &tond.ni_cnd);
3606 #endif
3607 out:
3608 	if (error == 0) {
3609 		error = VOP_RENAME(fromnd.ni_dvp, fromnd.ni_vp, &fromnd.ni_cnd,
3610 		    tond.ni_dvp, tond.ni_vp, &tond.ni_cnd);
3611 		NDFREE(&fromnd, NDF_ONLY_PNBUF);
3612 		NDFREE(&tond, NDF_ONLY_PNBUF);
3613 	} else {
3614 		NDFREE(&fromnd, NDF_ONLY_PNBUF);
3615 		NDFREE(&tond, NDF_ONLY_PNBUF);
3616 		if (tvp != NULL)
3617 			vput(tvp);
3618 		if (tdvp == tvp)
3619 			vrele(tdvp);
3620 		else
3621 			vput(tdvp);
3622 		vrele(fromnd.ni_dvp);
3623 		vrele(fvp);
3624 	}
3625 	vrele(tond.ni_startdir);
3626 	vn_finished_write(mp);
3627 out1:
3628 	if (fromnd.ni_startdir)
3629 		vrele(fromnd.ni_startdir);
3630 	if (error == -1)
3631 		return (0);
3632 	return (error);
3633 }
3634 
3635 /*
3636  * Make a directory file.
3637  */
3638 #ifndef _SYS_SYSPROTO_H_
3639 struct mkdir_args {
3640 	char	*path;
3641 	int	mode;
3642 };
3643 #endif
3644 int
3645 sys_mkdir(struct thread *td, struct mkdir_args *uap)
3646 {
3647 
3648 	return (kern_mkdirat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
3649 	    uap->mode));
3650 }
3651 
3652 #ifndef _SYS_SYSPROTO_H_
3653 struct mkdirat_args {
3654 	int	fd;
3655 	char	*path;
3656 	mode_t	mode;
3657 };
3658 #endif
3659 int
3660 sys_mkdirat(struct thread *td, struct mkdirat_args *uap)
3661 {
3662 
3663 	return (kern_mkdirat(td, uap->fd, uap->path, UIO_USERSPACE, uap->mode));
3664 }
3665 
3666 int
3667 kern_mkdirat(struct thread *td, int fd, const char *path, enum uio_seg segflg,
3668     int mode)
3669 {
3670 	struct mount *mp;
3671 	struct vnode *vp;
3672 	struct vattr vattr;
3673 	struct nameidata nd;
3674 	int error;
3675 
3676 	AUDIT_ARG_MODE(mode);
3677 restart:
3678 	bwillwrite();
3679 	NDINIT_ATRIGHTS(&nd, CREATE, LOCKPARENT | SAVENAME | AUDITVNODE1 |
3680 	    NOCACHE, segflg, path, fd, &cap_mkdirat_rights,
3681 	    td);
3682 	nd.ni_cnd.cn_flags |= WILLBEDIR;
3683 	if ((error = namei(&nd)) != 0)
3684 		return (error);
3685 	vp = nd.ni_vp;
3686 	if (vp != NULL) {
3687 		NDFREE(&nd, NDF_ONLY_PNBUF);
3688 		/*
3689 		 * XXX namei called with LOCKPARENT but not LOCKLEAF has
3690 		 * the strange behaviour of leaving the vnode unlocked
3691 		 * if the target is the same vnode as the parent.
3692 		 */
3693 		if (vp == nd.ni_dvp)
3694 			vrele(nd.ni_dvp);
3695 		else
3696 			vput(nd.ni_dvp);
3697 		vrele(vp);
3698 		return (EEXIST);
3699 	}
3700 	if (vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
3701 		NDFREE(&nd, NDF_ONLY_PNBUF);
3702 		vput(nd.ni_dvp);
3703 		if ((error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH)) != 0)
3704 			return (error);
3705 		goto restart;
3706 	}
3707 	VATTR_NULL(&vattr);
3708 	vattr.va_type = VDIR;
3709 	vattr.va_mode = (mode & ACCESSPERMS) &~ td->td_proc->p_fd->fd_cmask;
3710 #ifdef MAC
3711 	error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
3712 	    &vattr);
3713 	if (error != 0)
3714 		goto out;
3715 #endif
3716 	error = VOP_MKDIR(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
3717 #ifdef MAC
3718 out:
3719 #endif
3720 	NDFREE(&nd, NDF_ONLY_PNBUF);
3721 	vput(nd.ni_dvp);
3722 	if (error == 0)
3723 		vput(nd.ni_vp);
3724 	vn_finished_write(mp);
3725 	return (error);
3726 }
3727 
3728 /*
3729  * Remove a directory file.
3730  */
3731 #ifndef _SYS_SYSPROTO_H_
3732 struct rmdir_args {
3733 	char	*path;
3734 };
3735 #endif
3736 int
3737 sys_rmdir(struct thread *td, struct rmdir_args *uap)
3738 {
3739 
3740 	return (kern_frmdirat(td, AT_FDCWD, uap->path, FD_NONE, UIO_USERSPACE,
3741 	    0));
3742 }
3743 
3744 int
3745 kern_frmdirat(struct thread *td, int dfd, const char *path, int fd,
3746     enum uio_seg pathseg, int flag)
3747 {
3748 	struct mount *mp;
3749 	struct vnode *vp;
3750 	struct file *fp;
3751 	struct nameidata nd;
3752 	cap_rights_t rights;
3753 	int error;
3754 
3755 	fp = NULL;
3756 	if (fd != FD_NONE) {
3757 		error = getvnode(td, fd, cap_rights_init(&rights, CAP_LOOKUP),
3758 		    &fp);
3759 		if (error != 0)
3760 			return (error);
3761 	}
3762 
3763 restart:
3764 	bwillwrite();
3765 	NDINIT_ATRIGHTS(&nd, DELETE, LOCKPARENT | LOCKLEAF | AUDITVNODE1 |
3766 	    ((flag & AT_BENEATH) != 0 ? BENEATH : 0),
3767 	    pathseg, path, dfd, &cap_unlinkat_rights, td);
3768 	if ((error = namei(&nd)) != 0)
3769 		goto fdout;
3770 	vp = nd.ni_vp;
3771 	if (vp->v_type != VDIR) {
3772 		error = ENOTDIR;
3773 		goto out;
3774 	}
3775 	/*
3776 	 * No rmdir "." please.
3777 	 */
3778 	if (nd.ni_dvp == vp) {
3779 		error = EINVAL;
3780 		goto out;
3781 	}
3782 	/*
3783 	 * The root of a mounted filesystem cannot be deleted.
3784 	 */
3785 	if (vp->v_vflag & VV_ROOT) {
3786 		error = EBUSY;
3787 		goto out;
3788 	}
3789 
3790 	if (fp != NULL && fp->f_vnode != vp) {
3791 		if (VN_IS_DOOMED(fp->f_vnode))
3792 			error = EBADF;
3793 		else
3794 			error = EDEADLK;
3795 		goto out;
3796 	}
3797 
3798 #ifdef MAC
3799 	error = mac_vnode_check_unlink(td->td_ucred, nd.ni_dvp, vp,
3800 	    &nd.ni_cnd);
3801 	if (error != 0)
3802 		goto out;
3803 #endif
3804 	if (vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
3805 		NDFREE(&nd, NDF_ONLY_PNBUF);
3806 		vput(vp);
3807 		if (nd.ni_dvp == vp)
3808 			vrele(nd.ni_dvp);
3809 		else
3810 			vput(nd.ni_dvp);
3811 		if ((error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH)) != 0)
3812 			goto fdout;
3813 		goto restart;
3814 	}
3815 	vfs_notify_upper(vp, VFS_NOTIFY_UPPER_UNLINK);
3816 	error = VOP_RMDIR(nd.ni_dvp, nd.ni_vp, &nd.ni_cnd);
3817 	vn_finished_write(mp);
3818 out:
3819 	NDFREE(&nd, NDF_ONLY_PNBUF);
3820 	vput(vp);
3821 	if (nd.ni_dvp == vp)
3822 		vrele(nd.ni_dvp);
3823 	else
3824 		vput(nd.ni_dvp);
3825 fdout:
3826 	if (fp != NULL)
3827 		fdrop(fp, td);
3828 	return (error);
3829 }
3830 
3831 #if defined(COMPAT_43) || defined(COMPAT_FREEBSD11)
3832 int
3833 freebsd11_kern_getdirentries(struct thread *td, int fd, char *ubuf, u_int count,
3834     long *basep, void (*func)(struct freebsd11_dirent *))
3835 {
3836 	struct freebsd11_dirent dstdp;
3837 	struct dirent *dp, *edp;
3838 	char *dirbuf;
3839 	off_t base;
3840 	ssize_t resid, ucount;
3841 	int error;
3842 
3843 	/* XXX arbitrary sanity limit on `count'. */
3844 	count = min(count, 64 * 1024);
3845 
3846 	dirbuf = malloc(count, M_TEMP, M_WAITOK);
3847 
3848 	error = kern_getdirentries(td, fd, dirbuf, count, &base, &resid,
3849 	    UIO_SYSSPACE);
3850 	if (error != 0)
3851 		goto done;
3852 	if (basep != NULL)
3853 		*basep = base;
3854 
3855 	ucount = 0;
3856 	for (dp = (struct dirent *)dirbuf,
3857 	    edp = (struct dirent *)&dirbuf[count - resid];
3858 	    ucount < count && dp < edp; ) {
3859 		if (dp->d_reclen == 0)
3860 			break;
3861 		MPASS(dp->d_reclen >= _GENERIC_DIRLEN(0));
3862 		if (dp->d_namlen >= sizeof(dstdp.d_name))
3863 			continue;
3864 		dstdp.d_type = dp->d_type;
3865 		dstdp.d_namlen = dp->d_namlen;
3866 		dstdp.d_fileno = dp->d_fileno;		/* truncate */
3867 		if (dstdp.d_fileno != dp->d_fileno) {
3868 			switch (ino64_trunc_error) {
3869 			default:
3870 			case 0:
3871 				break;
3872 			case 1:
3873 				error = EOVERFLOW;
3874 				goto done;
3875 			case 2:
3876 				dstdp.d_fileno = UINT32_MAX;
3877 				break;
3878 			}
3879 		}
3880 		dstdp.d_reclen = sizeof(dstdp) - sizeof(dstdp.d_name) +
3881 		    ((dp->d_namlen + 1 + 3) &~ 3);
3882 		bcopy(dp->d_name, dstdp.d_name, dstdp.d_namlen);
3883 		bzero(dstdp.d_name + dstdp.d_namlen,
3884 		    dstdp.d_reclen - offsetof(struct freebsd11_dirent, d_name) -
3885 		    dstdp.d_namlen);
3886 		MPASS(dstdp.d_reclen <= dp->d_reclen);
3887 		MPASS(ucount + dstdp.d_reclen <= count);
3888 		if (func != NULL)
3889 			func(&dstdp);
3890 		error = copyout(&dstdp, ubuf + ucount, dstdp.d_reclen);
3891 		if (error != 0)
3892 			break;
3893 		dp = (struct dirent *)((char *)dp + dp->d_reclen);
3894 		ucount += dstdp.d_reclen;
3895 	}
3896 
3897 done:
3898 	free(dirbuf, M_TEMP);
3899 	if (error == 0)
3900 		td->td_retval[0] = ucount;
3901 	return (error);
3902 }
3903 #endif /* COMPAT */
3904 
3905 #ifdef COMPAT_43
3906 static void
3907 ogetdirentries_cvt(struct freebsd11_dirent *dp)
3908 {
3909 #if (BYTE_ORDER == LITTLE_ENDIAN)
3910 	/*
3911 	 * The expected low byte of dp->d_namlen is our dp->d_type.
3912 	 * The high MBZ byte of dp->d_namlen is our dp->d_namlen.
3913 	 */
3914 	dp->d_type = dp->d_namlen;
3915 	dp->d_namlen = 0;
3916 #else
3917 	/*
3918 	 * The dp->d_type is the high byte of the expected dp->d_namlen,
3919 	 * so must be zero'ed.
3920 	 */
3921 	dp->d_type = 0;
3922 #endif
3923 }
3924 
3925 /*
3926  * Read a block of directory entries in a filesystem independent format.
3927  */
3928 #ifndef _SYS_SYSPROTO_H_
3929 struct ogetdirentries_args {
3930 	int	fd;
3931 	char	*buf;
3932 	u_int	count;
3933 	long	*basep;
3934 };
3935 #endif
3936 int
3937 ogetdirentries(struct thread *td, struct ogetdirentries_args *uap)
3938 {
3939 	long loff;
3940 	int error;
3941 
3942 	error = kern_ogetdirentries(td, uap, &loff);
3943 	if (error == 0)
3944 		error = copyout(&loff, uap->basep, sizeof(long));
3945 	return (error);
3946 }
3947 
3948 int
3949 kern_ogetdirentries(struct thread *td, struct ogetdirentries_args *uap,
3950     long *ploff)
3951 {
3952 	long base;
3953 	int error;
3954 
3955 	/* XXX arbitrary sanity limit on `count'. */
3956 	if (uap->count > 64 * 1024)
3957 		return (EINVAL);
3958 
3959 	error = freebsd11_kern_getdirentries(td, uap->fd, uap->buf, uap->count,
3960 	    &base, ogetdirentries_cvt);
3961 
3962 	if (error == 0 && uap->basep != NULL)
3963 		error = copyout(&base, uap->basep, sizeof(long));
3964 
3965 	return (error);
3966 }
3967 #endif /* COMPAT_43 */
3968 
3969 #if defined(COMPAT_FREEBSD11)
3970 #ifndef _SYS_SYSPROTO_H_
3971 struct freebsd11_getdirentries_args {
3972 	int	fd;
3973 	char	*buf;
3974 	u_int	count;
3975 	long	*basep;
3976 };
3977 #endif
3978 int
3979 freebsd11_getdirentries(struct thread *td,
3980     struct freebsd11_getdirentries_args *uap)
3981 {
3982 	long base;
3983 	int error;
3984 
3985 	error = freebsd11_kern_getdirentries(td, uap->fd, uap->buf, uap->count,
3986 	    &base, NULL);
3987 
3988 	if (error == 0 && uap->basep != NULL)
3989 		error = copyout(&base, uap->basep, sizeof(long));
3990 	return (error);
3991 }
3992 
3993 int
3994 freebsd11_getdents(struct thread *td, struct freebsd11_getdents_args *uap)
3995 {
3996 	struct freebsd11_getdirentries_args ap;
3997 
3998 	ap.fd = uap->fd;
3999 	ap.buf = uap->buf;
4000 	ap.count = uap->count;
4001 	ap.basep = NULL;
4002 	return (freebsd11_getdirentries(td, &ap));
4003 }
4004 #endif /* COMPAT_FREEBSD11 */
4005 
4006 /*
4007  * Read a block of directory entries in a filesystem independent format.
4008  */
4009 int
4010 sys_getdirentries(struct thread *td, struct getdirentries_args *uap)
4011 {
4012 	off_t base;
4013 	int error;
4014 
4015 	error = kern_getdirentries(td, uap->fd, uap->buf, uap->count, &base,
4016 	    NULL, UIO_USERSPACE);
4017 	if (error != 0)
4018 		return (error);
4019 	if (uap->basep != NULL)
4020 		error = copyout(&base, uap->basep, sizeof(off_t));
4021 	return (error);
4022 }
4023 
4024 int
4025 kern_getdirentries(struct thread *td, int fd, char *buf, size_t count,
4026     off_t *basep, ssize_t *residp, enum uio_seg bufseg)
4027 {
4028 	struct vnode *vp;
4029 	struct file *fp;
4030 	struct uio auio;
4031 	struct iovec aiov;
4032 	off_t loff;
4033 	int error, eofflag;
4034 	off_t foffset;
4035 
4036 	AUDIT_ARG_FD(fd);
4037 	if (count > IOSIZE_MAX)
4038 		return (EINVAL);
4039 	auio.uio_resid = count;
4040 	error = getvnode(td, fd, &cap_read_rights, &fp);
4041 	if (error != 0)
4042 		return (error);
4043 	if ((fp->f_flag & FREAD) == 0) {
4044 		fdrop(fp, td);
4045 		return (EBADF);
4046 	}
4047 	vp = fp->f_vnode;
4048 	foffset = foffset_lock(fp, 0);
4049 unionread:
4050 	if (vp->v_type != VDIR) {
4051 		error = EINVAL;
4052 		goto fail;
4053 	}
4054 	aiov.iov_base = buf;
4055 	aiov.iov_len = count;
4056 	auio.uio_iov = &aiov;
4057 	auio.uio_iovcnt = 1;
4058 	auio.uio_rw = UIO_READ;
4059 	auio.uio_segflg = bufseg;
4060 	auio.uio_td = td;
4061 	vn_lock(vp, LK_SHARED | LK_RETRY);
4062 	AUDIT_ARG_VNODE1(vp);
4063 	loff = auio.uio_offset = foffset;
4064 #ifdef MAC
4065 	error = mac_vnode_check_readdir(td->td_ucred, vp);
4066 	if (error == 0)
4067 #endif
4068 		error = VOP_READDIR(vp, &auio, fp->f_cred, &eofflag, NULL,
4069 		    NULL);
4070 	foffset = auio.uio_offset;
4071 	if (error != 0) {
4072 		VOP_UNLOCK(vp);
4073 		goto fail;
4074 	}
4075 	if (count == auio.uio_resid &&
4076 	    (vp->v_vflag & VV_ROOT) &&
4077 	    (vp->v_mount->mnt_flag & MNT_UNION)) {
4078 		struct vnode *tvp = vp;
4079 
4080 		vp = vp->v_mount->mnt_vnodecovered;
4081 		VREF(vp);
4082 		fp->f_vnode = vp;
4083 		fp->f_data = vp;
4084 		foffset = 0;
4085 		vput(tvp);
4086 		goto unionread;
4087 	}
4088 	VOP_UNLOCK(vp);
4089 	*basep = loff;
4090 	if (residp != NULL)
4091 		*residp = auio.uio_resid;
4092 	td->td_retval[0] = count - auio.uio_resid;
4093 fail:
4094 	foffset_unlock(fp, foffset, 0);
4095 	fdrop(fp, td);
4096 	return (error);
4097 }
4098 
4099 /*
4100  * Set the mode mask for creation of filesystem nodes.
4101  */
4102 #ifndef _SYS_SYSPROTO_H_
4103 struct umask_args {
4104 	int	newmask;
4105 };
4106 #endif
4107 int
4108 sys_umask(struct thread *td, struct umask_args *uap)
4109 {
4110 	struct filedesc *fdp;
4111 
4112 	fdp = td->td_proc->p_fd;
4113 	FILEDESC_XLOCK(fdp);
4114 	td->td_retval[0] = fdp->fd_cmask;
4115 	fdp->fd_cmask = uap->newmask & ALLPERMS;
4116 	FILEDESC_XUNLOCK(fdp);
4117 	return (0);
4118 }
4119 
4120 /*
4121  * Void all references to file by ripping underlying filesystem away from
4122  * vnode.
4123  */
4124 #ifndef _SYS_SYSPROTO_H_
4125 struct revoke_args {
4126 	char	*path;
4127 };
4128 #endif
4129 int
4130 sys_revoke(struct thread *td, struct revoke_args *uap)
4131 {
4132 	struct vnode *vp;
4133 	struct vattr vattr;
4134 	struct nameidata nd;
4135 	int error;
4136 
4137 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1, UIO_USERSPACE,
4138 	    uap->path, td);
4139 	if ((error = namei(&nd)) != 0)
4140 		return (error);
4141 	vp = nd.ni_vp;
4142 	NDFREE(&nd, NDF_ONLY_PNBUF);
4143 	if (vp->v_type != VCHR || vp->v_rdev == NULL) {
4144 		error = EINVAL;
4145 		goto out;
4146 	}
4147 #ifdef MAC
4148 	error = mac_vnode_check_revoke(td->td_ucred, vp);
4149 	if (error != 0)
4150 		goto out;
4151 #endif
4152 	error = VOP_GETATTR(vp, &vattr, td->td_ucred);
4153 	if (error != 0)
4154 		goto out;
4155 	if (td->td_ucred->cr_uid != vattr.va_uid) {
4156 		error = priv_check(td, PRIV_VFS_ADMIN);
4157 		if (error != 0)
4158 			goto out;
4159 	}
4160 	if (vp->v_usecount > 1 || vcount(vp) > 1)
4161 		VOP_REVOKE(vp, REVOKEALL);
4162 out:
4163 	vput(vp);
4164 	return (error);
4165 }
4166 
4167 /*
4168  * Convert a user file descriptor to a kernel file entry and check that, if it
4169  * is a capability, the correct rights are present. A reference on the file
4170  * entry is held upon returning.
4171  */
4172 int
4173 getvnode(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
4174 {
4175 	struct file *fp;
4176 	int error;
4177 
4178 	error = fget_unlocked(td->td_proc->p_fd, fd, rightsp, &fp, NULL);
4179 	if (error != 0)
4180 		return (error);
4181 
4182 	/*
4183 	 * The file could be not of the vnode type, or it may be not
4184 	 * yet fully initialized, in which case the f_vnode pointer
4185 	 * may be set, but f_ops is still badfileops.  E.g.,
4186 	 * devfs_open() transiently create such situation to
4187 	 * facilitate csw d_fdopen().
4188 	 *
4189 	 * Dupfdopen() handling in kern_openat() installs the
4190 	 * half-baked file into the process descriptor table, allowing
4191 	 * other thread to dereference it. Guard against the race by
4192 	 * checking f_ops.
4193 	 */
4194 	if (fp->f_vnode == NULL || fp->f_ops == &badfileops) {
4195 		fdrop(fp, td);
4196 		return (EINVAL);
4197 	}
4198 	*fpp = fp;
4199 	return (0);
4200 }
4201 
4202 /*
4203  * Get an (NFS) file handle.
4204  */
4205 #ifndef _SYS_SYSPROTO_H_
4206 struct lgetfh_args {
4207 	char *fname;
4208 	fhandle_t *fhp;
4209 };
4210 #endif
4211 int
4212 sys_lgetfh(struct thread *td, struct lgetfh_args *uap)
4213 {
4214 
4215 	return (kern_getfhat(td, AT_SYMLINK_NOFOLLOW, AT_FDCWD, uap->fname,
4216 	    UIO_USERSPACE, uap->fhp));
4217 }
4218 
4219 #ifndef _SYS_SYSPROTO_H_
4220 struct getfh_args {
4221 	char *fname;
4222 	fhandle_t *fhp;
4223 };
4224 #endif
4225 int
4226 sys_getfh(struct thread *td, struct getfh_args *uap)
4227 {
4228 
4229 	return (kern_getfhat(td, 0, AT_FDCWD, uap->fname, UIO_USERSPACE,
4230 	    uap->fhp));
4231 }
4232 
4233 /*
4234  * syscall for the rpc.lockd to use to translate an open descriptor into
4235  * a NFS file handle.
4236  *
4237  * warning: do not remove the priv_check() call or this becomes one giant
4238  * security hole.
4239  */
4240 #ifndef _SYS_SYSPROTO_H_
4241 struct getfhat_args {
4242 	int fd;
4243 	char *path;
4244 	fhandle_t *fhp;
4245 	int flags;
4246 };
4247 #endif
4248 int
4249 sys_getfhat(struct thread *td, struct getfhat_args *uap)
4250 {
4251 
4252 	if ((uap->flags & ~(AT_SYMLINK_NOFOLLOW | AT_BENEATH)) != 0)
4253 		return (EINVAL);
4254 	return (kern_getfhat(td, uap->flags, uap->fd, uap->path, UIO_USERSPACE,
4255 	    uap->fhp));
4256 }
4257 
4258 static int
4259 kern_getfhat(struct thread *td, int flags, int fd, const char *path,
4260     enum uio_seg pathseg, fhandle_t *fhp)
4261 {
4262 	struct nameidata nd;
4263 	fhandle_t fh;
4264 	struct vnode *vp;
4265 	int error;
4266 
4267 	error = priv_check(td, PRIV_VFS_GETFH);
4268 	if (error != 0)
4269 		return (error);
4270 	NDINIT_AT(&nd, LOOKUP, ((flags & AT_SYMLINK_NOFOLLOW) != 0 ? NOFOLLOW :
4271 	    FOLLOW) | ((flags & AT_BENEATH) != 0 ? BENEATH : 0) | LOCKLEAF |
4272 	    AUDITVNODE1, pathseg, path, fd, td);
4273 	error = namei(&nd);
4274 	if (error != 0)
4275 		return (error);
4276 	NDFREE(&nd, NDF_ONLY_PNBUF);
4277 	vp = nd.ni_vp;
4278 	bzero(&fh, sizeof(fh));
4279 	fh.fh_fsid = vp->v_mount->mnt_stat.f_fsid;
4280 	error = VOP_VPTOFH(vp, &fh.fh_fid);
4281 	vput(vp);
4282 	if (error == 0)
4283 		error = copyout(&fh, fhp, sizeof (fh));
4284 	return (error);
4285 }
4286 
4287 #ifndef _SYS_SYSPROTO_H_
4288 struct fhlink_args {
4289 	fhandle_t *fhp;
4290 	const char *to;
4291 };
4292 #endif
4293 int
4294 sys_fhlink(struct thread *td, struct fhlink_args *uap)
4295 {
4296 
4297 	return (kern_fhlinkat(td, AT_FDCWD, uap->to, UIO_USERSPACE, uap->fhp));
4298 }
4299 
4300 #ifndef _SYS_SYSPROTO_H_
4301 struct fhlinkat_args {
4302 	fhandle_t *fhp;
4303 	int tofd;
4304 	const char *to;
4305 };
4306 #endif
4307 int
4308 sys_fhlinkat(struct thread *td, struct fhlinkat_args *uap)
4309 {
4310 
4311 	return (kern_fhlinkat(td, uap->tofd, uap->to, UIO_USERSPACE, uap->fhp));
4312 }
4313 
4314 static int
4315 kern_fhlinkat(struct thread *td, int fd, const char *path,
4316     enum uio_seg pathseg, fhandle_t *fhp)
4317 {
4318 	fhandle_t fh;
4319 	struct mount *mp;
4320 	struct vnode *vp;
4321 	int error;
4322 
4323 	error = priv_check(td, PRIV_VFS_GETFH);
4324 	if (error != 0)
4325 		return (error);
4326 	error = copyin(fhp, &fh, sizeof(fh));
4327 	if (error != 0)
4328 		return (error);
4329 	do {
4330 		bwillwrite();
4331 		if ((mp = vfs_busyfs(&fh.fh_fsid)) == NULL)
4332 			return (ESTALE);
4333 		error = VFS_FHTOVP(mp, &fh.fh_fid, LK_SHARED, &vp);
4334 		vfs_unbusy(mp);
4335 		if (error != 0)
4336 			return (error);
4337 		VOP_UNLOCK(vp);
4338 	} while ((error = kern_linkat_vp(td, vp, fd, path, pathseg)) == EAGAIN);
4339 	return (error);
4340 }
4341 
4342 #ifndef _SYS_SYSPROTO_H_
4343 struct fhreadlink_args {
4344 	fhandle_t *fhp;
4345 	char *buf;
4346 	size_t bufsize;
4347 };
4348 #endif
4349 int
4350 sys_fhreadlink(struct thread *td, struct fhreadlink_args *uap)
4351 {
4352 	fhandle_t fh;
4353 	struct mount *mp;
4354 	struct vnode *vp;
4355 	int error;
4356 
4357 	error = priv_check(td, PRIV_VFS_GETFH);
4358 	if (error != 0)
4359 		return (error);
4360 	if (uap->bufsize > IOSIZE_MAX)
4361 		return (EINVAL);
4362 	error = copyin(uap->fhp, &fh, sizeof(fh));
4363 	if (error != 0)
4364 		return (error);
4365 	if ((mp = vfs_busyfs(&fh.fh_fsid)) == NULL)
4366 		return (ESTALE);
4367 	error = VFS_FHTOVP(mp, &fh.fh_fid, LK_SHARED, &vp);
4368 	vfs_unbusy(mp);
4369 	if (error != 0)
4370 		return (error);
4371 	error = kern_readlink_vp(vp, uap->buf, UIO_USERSPACE, uap->bufsize, td);
4372 	vput(vp);
4373 	return (error);
4374 }
4375 
4376 /*
4377  * syscall for the rpc.lockd to use to translate a NFS file handle into an
4378  * open descriptor.
4379  *
4380  * warning: do not remove the priv_check() call or this becomes one giant
4381  * security hole.
4382  */
4383 #ifndef _SYS_SYSPROTO_H_
4384 struct fhopen_args {
4385 	const struct fhandle *u_fhp;
4386 	int flags;
4387 };
4388 #endif
4389 int
4390 sys_fhopen(struct thread *td, struct fhopen_args *uap)
4391 {
4392 	struct mount *mp;
4393 	struct vnode *vp;
4394 	struct fhandle fhp;
4395 	struct file *fp;
4396 	int fmode, error;
4397 	int indx;
4398 
4399 	error = priv_check(td, PRIV_VFS_FHOPEN);
4400 	if (error != 0)
4401 		return (error);
4402 	indx = -1;
4403 	fmode = FFLAGS(uap->flags);
4404 	/* why not allow a non-read/write open for our lockd? */
4405 	if (((fmode & (FREAD | FWRITE)) == 0) || (fmode & O_CREAT))
4406 		return (EINVAL);
4407 	error = copyin(uap->u_fhp, &fhp, sizeof(fhp));
4408 	if (error != 0)
4409 		return(error);
4410 	/* find the mount point */
4411 	mp = vfs_busyfs(&fhp.fh_fsid);
4412 	if (mp == NULL)
4413 		return (ESTALE);
4414 	/* now give me my vnode, it gets returned to me locked */
4415 	error = VFS_FHTOVP(mp, &fhp.fh_fid, LK_EXCLUSIVE, &vp);
4416 	vfs_unbusy(mp);
4417 	if (error != 0)
4418 		return (error);
4419 
4420 	error = falloc_noinstall(td, &fp);
4421 	if (error != 0) {
4422 		vput(vp);
4423 		return (error);
4424 	}
4425 	/*
4426 	 * An extra reference on `fp' has been held for us by
4427 	 * falloc_noinstall().
4428 	 */
4429 
4430 #ifdef INVARIANTS
4431 	td->td_dupfd = -1;
4432 #endif
4433 	error = vn_open_vnode(vp, fmode, td->td_ucred, td, fp);
4434 	if (error != 0) {
4435 		KASSERT(fp->f_ops == &badfileops,
4436 		    ("VOP_OPEN in fhopen() set f_ops"));
4437 		KASSERT(td->td_dupfd < 0,
4438 		    ("fhopen() encountered fdopen()"));
4439 
4440 		vput(vp);
4441 		goto bad;
4442 	}
4443 #ifdef INVARIANTS
4444 	td->td_dupfd = 0;
4445 #endif
4446 	fp->f_vnode = vp;
4447 	fp->f_seqcount = 1;
4448 	finit(fp, (fmode & FMASK) | (fp->f_flag & FHASLOCK), DTYPE_VNODE, vp,
4449 	    &vnops);
4450 	VOP_UNLOCK(vp);
4451 	if ((fmode & O_TRUNC) != 0) {
4452 		error = fo_truncate(fp, 0, td->td_ucred, td);
4453 		if (error != 0)
4454 			goto bad;
4455 	}
4456 
4457 	error = finstall(td, fp, &indx, fmode, NULL);
4458 bad:
4459 	fdrop(fp, td);
4460 	td->td_retval[0] = indx;
4461 	return (error);
4462 }
4463 
4464 /*
4465  * Stat an (NFS) file handle.
4466  */
4467 #ifndef _SYS_SYSPROTO_H_
4468 struct fhstat_args {
4469 	struct fhandle *u_fhp;
4470 	struct stat *sb;
4471 };
4472 #endif
4473 int
4474 sys_fhstat(struct thread *td, struct fhstat_args *uap)
4475 {
4476 	struct stat sb;
4477 	struct fhandle fh;
4478 	int error;
4479 
4480 	error = copyin(uap->u_fhp, &fh, sizeof(fh));
4481 	if (error != 0)
4482 		return (error);
4483 	error = kern_fhstat(td, fh, &sb);
4484 	if (error == 0)
4485 		error = copyout(&sb, uap->sb, sizeof(sb));
4486 	return (error);
4487 }
4488 
4489 int
4490 kern_fhstat(struct thread *td, struct fhandle fh, struct stat *sb)
4491 {
4492 	struct mount *mp;
4493 	struct vnode *vp;
4494 	int error;
4495 
4496 	error = priv_check(td, PRIV_VFS_FHSTAT);
4497 	if (error != 0)
4498 		return (error);
4499 	if ((mp = vfs_busyfs(&fh.fh_fsid)) == NULL)
4500 		return (ESTALE);
4501 	error = VFS_FHTOVP(mp, &fh.fh_fid, LK_EXCLUSIVE, &vp);
4502 	vfs_unbusy(mp);
4503 	if (error != 0)
4504 		return (error);
4505 	error = vn_stat(vp, sb, td->td_ucred, NOCRED, td);
4506 	vput(vp);
4507 	return (error);
4508 }
4509 
4510 /*
4511  * Implement fstatfs() for (NFS) file handles.
4512  */
4513 #ifndef _SYS_SYSPROTO_H_
4514 struct fhstatfs_args {
4515 	struct fhandle *u_fhp;
4516 	struct statfs *buf;
4517 };
4518 #endif
4519 int
4520 sys_fhstatfs(struct thread *td, struct fhstatfs_args *uap)
4521 {
4522 	struct statfs *sfp;
4523 	fhandle_t fh;
4524 	int error;
4525 
4526 	error = copyin(uap->u_fhp, &fh, sizeof(fhandle_t));
4527 	if (error != 0)
4528 		return (error);
4529 	sfp = malloc(sizeof(struct statfs), M_STATFS, M_WAITOK);
4530 	error = kern_fhstatfs(td, fh, sfp);
4531 	if (error == 0)
4532 		error = copyout(sfp, uap->buf, sizeof(*sfp));
4533 	free(sfp, M_STATFS);
4534 	return (error);
4535 }
4536 
4537 int
4538 kern_fhstatfs(struct thread *td, fhandle_t fh, struct statfs *buf)
4539 {
4540 	struct mount *mp;
4541 	struct vnode *vp;
4542 	int error;
4543 
4544 	error = priv_check(td, PRIV_VFS_FHSTATFS);
4545 	if (error != 0)
4546 		return (error);
4547 	if ((mp = vfs_busyfs(&fh.fh_fsid)) == NULL)
4548 		return (ESTALE);
4549 	error = VFS_FHTOVP(mp, &fh.fh_fid, LK_EXCLUSIVE, &vp);
4550 	if (error != 0) {
4551 		vfs_unbusy(mp);
4552 		return (error);
4553 	}
4554 	vput(vp);
4555 	error = prison_canseemount(td->td_ucred, mp);
4556 	if (error != 0)
4557 		goto out;
4558 #ifdef MAC
4559 	error = mac_mount_check_stat(td->td_ucred, mp);
4560 	if (error != 0)
4561 		goto out;
4562 #endif
4563 	error = VFS_STATFS(mp, buf);
4564 out:
4565 	vfs_unbusy(mp);
4566 	return (error);
4567 }
4568 
4569 /*
4570  * Unlike madvise(2), we do not make a best effort to remember every
4571  * possible caching hint.  Instead, we remember the last setting with
4572  * the exception that we will allow POSIX_FADV_NORMAL to adjust the
4573  * region of any current setting.
4574  */
4575 int
4576 kern_posix_fadvise(struct thread *td, int fd, off_t offset, off_t len,
4577     int advice)
4578 {
4579 	struct fadvise_info *fa, *new;
4580 	struct file *fp;
4581 	struct vnode *vp;
4582 	off_t end;
4583 	int error;
4584 
4585 	if (offset < 0 || len < 0 || offset > OFF_MAX - len)
4586 		return (EINVAL);
4587 	AUDIT_ARG_VALUE(advice);
4588 	switch (advice) {
4589 	case POSIX_FADV_SEQUENTIAL:
4590 	case POSIX_FADV_RANDOM:
4591 	case POSIX_FADV_NOREUSE:
4592 		new = malloc(sizeof(*fa), M_FADVISE, M_WAITOK);
4593 		break;
4594 	case POSIX_FADV_NORMAL:
4595 	case POSIX_FADV_WILLNEED:
4596 	case POSIX_FADV_DONTNEED:
4597 		new = NULL;
4598 		break;
4599 	default:
4600 		return (EINVAL);
4601 	}
4602 	/* XXX: CAP_POSIX_FADVISE? */
4603 	AUDIT_ARG_FD(fd);
4604 	error = fget(td, fd, &cap_no_rights, &fp);
4605 	if (error != 0)
4606 		goto out;
4607 	AUDIT_ARG_FILE(td->td_proc, fp);
4608 	if ((fp->f_ops->fo_flags & DFLAG_SEEKABLE) == 0) {
4609 		error = ESPIPE;
4610 		goto out;
4611 	}
4612 	if (fp->f_type != DTYPE_VNODE) {
4613 		error = ENODEV;
4614 		goto out;
4615 	}
4616 	vp = fp->f_vnode;
4617 	if (vp->v_type != VREG) {
4618 		error = ENODEV;
4619 		goto out;
4620 	}
4621 	if (len == 0)
4622 		end = OFF_MAX;
4623 	else
4624 		end = offset + len - 1;
4625 	switch (advice) {
4626 	case POSIX_FADV_SEQUENTIAL:
4627 	case POSIX_FADV_RANDOM:
4628 	case POSIX_FADV_NOREUSE:
4629 		/*
4630 		 * Try to merge any existing non-standard region with
4631 		 * this new region if possible, otherwise create a new
4632 		 * non-standard region for this request.
4633 		 */
4634 		mtx_pool_lock(mtxpool_sleep, fp);
4635 		fa = fp->f_advice;
4636 		if (fa != NULL && fa->fa_advice == advice &&
4637 		    ((fa->fa_start <= end && fa->fa_end >= offset) ||
4638 		    (end != OFF_MAX && fa->fa_start == end + 1) ||
4639 		    (fa->fa_end != OFF_MAX && fa->fa_end + 1 == offset))) {
4640 			if (offset < fa->fa_start)
4641 				fa->fa_start = offset;
4642 			if (end > fa->fa_end)
4643 				fa->fa_end = end;
4644 		} else {
4645 			new->fa_advice = advice;
4646 			new->fa_start = offset;
4647 			new->fa_end = end;
4648 			fp->f_advice = new;
4649 			new = fa;
4650 		}
4651 		mtx_pool_unlock(mtxpool_sleep, fp);
4652 		break;
4653 	case POSIX_FADV_NORMAL:
4654 		/*
4655 		 * If a the "normal" region overlaps with an existing
4656 		 * non-standard region, trim or remove the
4657 		 * non-standard region.
4658 		 */
4659 		mtx_pool_lock(mtxpool_sleep, fp);
4660 		fa = fp->f_advice;
4661 		if (fa != NULL) {
4662 			if (offset <= fa->fa_start && end >= fa->fa_end) {
4663 				new = fa;
4664 				fp->f_advice = NULL;
4665 			} else if (offset <= fa->fa_start &&
4666 			    end >= fa->fa_start)
4667 				fa->fa_start = end + 1;
4668 			else if (offset <= fa->fa_end && end >= fa->fa_end)
4669 				fa->fa_end = offset - 1;
4670 			else if (offset >= fa->fa_start && end <= fa->fa_end) {
4671 				/*
4672 				 * If the "normal" region is a middle
4673 				 * portion of the existing
4674 				 * non-standard region, just remove
4675 				 * the whole thing rather than picking
4676 				 * one side or the other to
4677 				 * preserve.
4678 				 */
4679 				new = fa;
4680 				fp->f_advice = NULL;
4681 			}
4682 		}
4683 		mtx_pool_unlock(mtxpool_sleep, fp);
4684 		break;
4685 	case POSIX_FADV_WILLNEED:
4686 	case POSIX_FADV_DONTNEED:
4687 		error = VOP_ADVISE(vp, offset, end, advice);
4688 		break;
4689 	}
4690 out:
4691 	if (fp != NULL)
4692 		fdrop(fp, td);
4693 	free(new, M_FADVISE);
4694 	return (error);
4695 }
4696 
4697 int
4698 sys_posix_fadvise(struct thread *td, struct posix_fadvise_args *uap)
4699 {
4700 	int error;
4701 
4702 	error = kern_posix_fadvise(td, uap->fd, uap->offset, uap->len,
4703 	    uap->advice);
4704 	return (kern_posix_error(td, error));
4705 }
4706 
4707 int
4708 kern_copy_file_range(struct thread *td, int infd, off_t *inoffp, int outfd,
4709     off_t *outoffp, size_t len, unsigned int flags)
4710 {
4711 	struct file *infp, *outfp;
4712 	struct vnode *invp, *outvp;
4713 	int error;
4714 	size_t retlen;
4715 	void *rl_rcookie, *rl_wcookie;
4716 	off_t savinoff, savoutoff;
4717 
4718 	infp = outfp = NULL;
4719 	rl_rcookie = rl_wcookie = NULL;
4720 	savinoff = -1;
4721 	error = 0;
4722 	retlen = 0;
4723 
4724 	if (flags != 0) {
4725 		error = EINVAL;
4726 		goto out;
4727 	}
4728 	if (len > SSIZE_MAX)
4729 		/*
4730 		 * Although the len argument is size_t, the return argument
4731 		 * is ssize_t (which is signed).  Therefore a size that won't
4732 		 * fit in ssize_t can't be returned.
4733 		 */
4734 		len = SSIZE_MAX;
4735 
4736 	/* Get the file structures for the file descriptors. */
4737 	error = fget_read(td, infd, &cap_read_rights, &infp);
4738 	if (error != 0)
4739 		goto out;
4740 	error = fget_write(td, outfd, &cap_write_rights, &outfp);
4741 	if (error != 0)
4742 		goto out;
4743 
4744 	/* Set the offset pointers to the correct place. */
4745 	if (inoffp == NULL)
4746 		inoffp = &infp->f_offset;
4747 	if (outoffp == NULL)
4748 		outoffp = &outfp->f_offset;
4749 	savinoff = *inoffp;
4750 	savoutoff = *outoffp;
4751 
4752 	invp = infp->f_vnode;
4753 	outvp = outfp->f_vnode;
4754 	/* Sanity check the f_flag bits. */
4755 	if ((outfp->f_flag & (FWRITE | FAPPEND)) != FWRITE ||
4756 	    (infp->f_flag & FREAD) == 0) {
4757 		error = EBADF;
4758 		goto out;
4759 	}
4760 
4761 	/* If len == 0, just return 0. */
4762 	if (len == 0)
4763 		goto out;
4764 
4765 	/*
4766 	 * If infp and outfp refer to the same file, the byte ranges cannot
4767 	 * overlap.
4768 	 */
4769 	if (invp == outvp && ((savinoff <= savoutoff && savinoff + len >
4770 	    savoutoff) || (savinoff > savoutoff && savoutoff + len >
4771 	    savinoff))) {
4772 		error = EINVAL;
4773 		goto out;
4774 	}
4775 
4776 	/* Range lock the byte ranges for both invp and outvp. */
4777 	for (;;) {
4778 		rl_wcookie = vn_rangelock_wlock(outvp, *outoffp, *outoffp +
4779 		    len);
4780 		rl_rcookie = vn_rangelock_tryrlock(invp, *inoffp, *inoffp +
4781 		    len);
4782 		if (rl_rcookie != NULL)
4783 			break;
4784 		vn_rangelock_unlock(outvp, rl_wcookie);
4785 		rl_rcookie = vn_rangelock_rlock(invp, *inoffp, *inoffp + len);
4786 		vn_rangelock_unlock(invp, rl_rcookie);
4787 	}
4788 
4789 	retlen = len;
4790 	error = vn_copy_file_range(invp, inoffp, outvp, outoffp, &retlen,
4791 	    flags, infp->f_cred, outfp->f_cred, td);
4792 out:
4793 	if (rl_rcookie != NULL)
4794 		vn_rangelock_unlock(invp, rl_rcookie);
4795 	if (rl_wcookie != NULL)
4796 		vn_rangelock_unlock(outvp, rl_wcookie);
4797 	if (savinoff != -1 && (error == EINTR || error == ERESTART)) {
4798 		*inoffp = savinoff;
4799 		*outoffp = savoutoff;
4800 	}
4801 	if (outfp != NULL)
4802 		fdrop(outfp, td);
4803 	if (infp != NULL)
4804 		fdrop(infp, td);
4805 	td->td_retval[0] = retlen;
4806 	return (error);
4807 }
4808 
4809 int
4810 sys_copy_file_range(struct thread *td, struct copy_file_range_args *uap)
4811 {
4812 	off_t inoff, outoff, *inoffp, *outoffp;
4813 	int error;
4814 
4815 	inoffp = outoffp = NULL;
4816 	if (uap->inoffp != NULL) {
4817 		error = copyin(uap->inoffp, &inoff, sizeof(off_t));
4818 		if (error != 0)
4819 			return (error);
4820 		inoffp = &inoff;
4821 	}
4822 	if (uap->outoffp != NULL) {
4823 		error = copyin(uap->outoffp, &outoff, sizeof(off_t));
4824 		if (error != 0)
4825 			return (error);
4826 		outoffp = &outoff;
4827 	}
4828 	error = kern_copy_file_range(td, uap->infd, inoffp, uap->outfd,
4829 	    outoffp, uap->len, uap->flags);
4830 	if (error == 0 && uap->inoffp != NULL)
4831 		error = copyout(inoffp, uap->inoffp, sizeof(off_t));
4832 	if (error == 0 && uap->outoffp != NULL)
4833 		error = copyout(outoffp, uap->outoffp, sizeof(off_t));
4834 	return (error);
4835 }
4836