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