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