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