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