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