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