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