xref: /freebsd/sys/kern/vfs_syscalls.c (revision 7937bfbc0ca53fe7cdd0d54414f9296e273a518e)
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 |
2155 	    AT_SYMLINK_NOFOLLOW)) != 0)
2156 		return (EINVAL);
2157 	if (amode != F_OK && (amode & ~(R_OK | W_OK | X_OK)) != 0)
2158 		return (EINVAL);
2159 
2160 	/*
2161 	 * Create and modify a temporary credential instead of one that
2162 	 * is potentially shared (if we need one).
2163 	 */
2164 	cred = td->td_ucred;
2165 	if ((flag & AT_EACCESS) == 0 &&
2166 	    ((cred->cr_uid != cred->cr_ruid ||
2167 	    cred->cr_rgid != cred->cr_groups[0]))) {
2168 		usecred = crdup(cred);
2169 		usecred->cr_uid = cred->cr_ruid;
2170 		usecred->cr_groups[0] = cred->cr_rgid;
2171 		td->td_ucred = usecred;
2172 	} else
2173 		usecred = cred;
2174 	AUDIT_ARG_VALUE(amode);
2175 	NDINIT_ATRIGHTS(&nd, LOOKUP, LOCKSHARED | LOCKLEAF |
2176 	    AUDITVNODE1 | at2cnpflags(flag, AT_RESOLVE_BENEATH | AT_SYMLINK_NOFOLLOW |
2177 	    AT_EMPTY_PATH), pathseg, path, fd, &cap_fstat_rights);
2178 	if ((error = namei(&nd)) != 0)
2179 		goto out;
2180 	vp = nd.ni_vp;
2181 
2182 	error = vn_access(vp, amode, usecred, td);
2183 	NDFREE_PNBUF(&nd);
2184 	vput(vp);
2185 out:
2186 	if (usecred != cred) {
2187 		td->td_ucred = cred;
2188 		crfree(usecred);
2189 	}
2190 	return (error);
2191 }
2192 
2193 /*
2194  * Check access permissions using "effective" credentials.
2195  */
2196 #ifndef _SYS_SYSPROTO_H_
2197 struct eaccess_args {
2198 	char	*path;
2199 	int	amode;
2200 };
2201 #endif
2202 int
2203 sys_eaccess(struct thread *td, struct eaccess_args *uap)
2204 {
2205 
2206 	return (kern_accessat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
2207 	    AT_EACCESS, uap->amode));
2208 }
2209 
2210 #if defined(COMPAT_43)
2211 /*
2212  * Get file status; this version follows links.
2213  */
2214 #ifndef _SYS_SYSPROTO_H_
2215 struct ostat_args {
2216 	char	*path;
2217 	struct ostat *ub;
2218 };
2219 #endif
2220 int
2221 ostat(struct thread *td, struct ostat_args *uap)
2222 {
2223 	struct stat sb;
2224 	struct ostat osb;
2225 	int error;
2226 
2227 	error = kern_statat(td, 0, AT_FDCWD, uap->path, UIO_USERSPACE, &sb);
2228 	if (error != 0)
2229 		return (error);
2230 	cvtstat(&sb, &osb);
2231 	return (copyout(&osb, uap->ub, sizeof (osb)));
2232 }
2233 
2234 /*
2235  * Get file status; this version does not follow links.
2236  */
2237 #ifndef _SYS_SYSPROTO_H_
2238 struct olstat_args {
2239 	char	*path;
2240 	struct ostat *ub;
2241 };
2242 #endif
2243 int
2244 olstat(struct thread *td, struct olstat_args *uap)
2245 {
2246 	struct stat sb;
2247 	struct ostat osb;
2248 	int error;
2249 
2250 	error = kern_statat(td, AT_SYMLINK_NOFOLLOW, AT_FDCWD, uap->path,
2251 	    UIO_USERSPACE, &sb);
2252 	if (error != 0)
2253 		return (error);
2254 	cvtstat(&sb, &osb);
2255 	return (copyout(&osb, uap->ub, sizeof (osb)));
2256 }
2257 
2258 /*
2259  * Convert from an old to a new stat structure.
2260  * XXX: many values are blindly truncated.
2261  */
2262 void
2263 cvtstat(struct stat *st, struct ostat *ost)
2264 {
2265 
2266 	bzero(ost, sizeof(*ost));
2267 	ost->st_dev = st->st_dev;
2268 	ost->st_ino = st->st_ino;
2269 	ost->st_mode = st->st_mode;
2270 	ost->st_nlink = st->st_nlink;
2271 	ost->st_uid = st->st_uid;
2272 	ost->st_gid = st->st_gid;
2273 	ost->st_rdev = st->st_rdev;
2274 	ost->st_size = MIN(st->st_size, INT32_MAX);
2275 	ost->st_atim = st->st_atim;
2276 	ost->st_mtim = st->st_mtim;
2277 	ost->st_ctim = st->st_ctim;
2278 	ost->st_blksize = st->st_blksize;
2279 	ost->st_blocks = st->st_blocks;
2280 	ost->st_flags = st->st_flags;
2281 	ost->st_gen = st->st_gen;
2282 }
2283 #endif /* COMPAT_43 */
2284 
2285 #if defined(COMPAT_43) || defined(COMPAT_FREEBSD11)
2286 int ino64_trunc_error;
2287 SYSCTL_INT(_vfs, OID_AUTO, ino64_trunc_error, CTLFLAG_RW,
2288     &ino64_trunc_error, 0,
2289     "Error on truncation of device, file or inode number, or link count");
2290 
2291 int
2292 freebsd11_cvtstat(struct stat *st, struct freebsd11_stat *ost)
2293 {
2294 
2295 	ost->st_dev = st->st_dev;
2296 	if (ost->st_dev != st->st_dev) {
2297 		switch (ino64_trunc_error) {
2298 		default:
2299 			/*
2300 			 * Since dev_t is almost raw, don't clamp to the
2301 			 * maximum for case 2, but ignore the error.
2302 			 */
2303 			break;
2304 		case 1:
2305 			return (EOVERFLOW);
2306 		}
2307 	}
2308 	ost->st_ino = st->st_ino;
2309 	if (ost->st_ino != st->st_ino) {
2310 		switch (ino64_trunc_error) {
2311 		default:
2312 		case 0:
2313 			break;
2314 		case 1:
2315 			return (EOVERFLOW);
2316 		case 2:
2317 			ost->st_ino = UINT32_MAX;
2318 			break;
2319 		}
2320 	}
2321 	ost->st_mode = st->st_mode;
2322 	ost->st_nlink = st->st_nlink;
2323 	if (ost->st_nlink != st->st_nlink) {
2324 		switch (ino64_trunc_error) {
2325 		default:
2326 		case 0:
2327 			break;
2328 		case 1:
2329 			return (EOVERFLOW);
2330 		case 2:
2331 			ost->st_nlink = UINT16_MAX;
2332 			break;
2333 		}
2334 	}
2335 	ost->st_uid = st->st_uid;
2336 	ost->st_gid = st->st_gid;
2337 	ost->st_rdev = st->st_rdev;
2338 	if (ost->st_rdev != st->st_rdev) {
2339 		switch (ino64_trunc_error) {
2340 		default:
2341 			break;
2342 		case 1:
2343 			return (EOVERFLOW);
2344 		}
2345 	}
2346 	ost->st_atim = st->st_atim;
2347 	ost->st_mtim = st->st_mtim;
2348 	ost->st_ctim = st->st_ctim;
2349 	ost->st_size = st->st_size;
2350 	ost->st_blocks = st->st_blocks;
2351 	ost->st_blksize = st->st_blksize;
2352 	ost->st_flags = st->st_flags;
2353 	ost->st_gen = st->st_gen;
2354 	ost->st_lspare = 0;
2355 	ost->st_birthtim = st->st_birthtim;
2356 	bzero((char *)&ost->st_birthtim + sizeof(ost->st_birthtim),
2357 	    sizeof(*ost) - offsetof(struct freebsd11_stat,
2358 	    st_birthtim) - sizeof(ost->st_birthtim));
2359 	return (0);
2360 }
2361 
2362 int
2363 freebsd11_stat(struct thread *td, struct freebsd11_stat_args* uap)
2364 {
2365 	struct stat sb;
2366 	struct freebsd11_stat osb;
2367 	int error;
2368 
2369 	error = kern_statat(td, 0, AT_FDCWD, uap->path, UIO_USERSPACE, &sb);
2370 	if (error != 0)
2371 		return (error);
2372 	error = freebsd11_cvtstat(&sb, &osb);
2373 	if (error == 0)
2374 		error = copyout(&osb, uap->ub, sizeof(osb));
2375 	return (error);
2376 }
2377 
2378 int
2379 freebsd11_lstat(struct thread *td, struct freebsd11_lstat_args* uap)
2380 {
2381 	struct stat sb;
2382 	struct freebsd11_stat osb;
2383 	int error;
2384 
2385 	error = kern_statat(td, AT_SYMLINK_NOFOLLOW, AT_FDCWD, uap->path,
2386 	    UIO_USERSPACE, &sb);
2387 	if (error != 0)
2388 		return (error);
2389 	error = freebsd11_cvtstat(&sb, &osb);
2390 	if (error == 0)
2391 		error = copyout(&osb, uap->ub, sizeof(osb));
2392 	return (error);
2393 }
2394 
2395 int
2396 freebsd11_fhstat(struct thread *td, struct freebsd11_fhstat_args* uap)
2397 {
2398 	struct fhandle fh;
2399 	struct stat sb;
2400 	struct freebsd11_stat osb;
2401 	int error;
2402 
2403 	error = copyin(uap->u_fhp, &fh, sizeof(fhandle_t));
2404 	if (error != 0)
2405 		return (error);
2406 	error = kern_fhstat(td, fh, &sb);
2407 	if (error != 0)
2408 		return (error);
2409 	error = freebsd11_cvtstat(&sb, &osb);
2410 	if (error == 0)
2411 		error = copyout(&osb, uap->sb, sizeof(osb));
2412 	return (error);
2413 }
2414 
2415 int
2416 freebsd11_fstatat(struct thread *td, struct freebsd11_fstatat_args* uap)
2417 {
2418 	struct stat sb;
2419 	struct freebsd11_stat osb;
2420 	int error;
2421 
2422 	error = kern_statat(td, uap->flag, uap->fd, uap->path,
2423 	    UIO_USERSPACE, &sb);
2424 	if (error != 0)
2425 		return (error);
2426 	error = freebsd11_cvtstat(&sb, &osb);
2427 	if (error == 0)
2428 		error = copyout(&osb, uap->buf, sizeof(osb));
2429 	return (error);
2430 }
2431 #endif	/* COMPAT_FREEBSD11 */
2432 
2433 /*
2434  * Get file status
2435  */
2436 #ifndef _SYS_SYSPROTO_H_
2437 struct fstatat_args {
2438 	int	fd;
2439 	char	*path;
2440 	struct stat	*buf;
2441 	int	flag;
2442 }
2443 #endif
2444 int
2445 sys_fstatat(struct thread *td, struct fstatat_args *uap)
2446 {
2447 	struct stat sb;
2448 	int error;
2449 
2450 	error = kern_statat(td, uap->flag, uap->fd, uap->path,
2451 	    UIO_USERSPACE, &sb);
2452 	if (error == 0)
2453 		error = copyout(&sb, uap->buf, sizeof (sb));
2454 	return (error);
2455 }
2456 
2457 int
2458 kern_statat(struct thread *td, int flag, int fd, const char *path,
2459     enum uio_seg pathseg, struct stat *sbp)
2460 {
2461 	struct nameidata nd;
2462 	int error;
2463 
2464 	if ((flag & ~(AT_SYMLINK_NOFOLLOW | AT_RESOLVE_BENEATH |
2465 	    AT_EMPTY_PATH)) != 0)
2466 		return (EINVAL);
2467 
2468 	NDINIT_ATRIGHTS(&nd, LOOKUP, at2cnpflags(flag, AT_RESOLVE_BENEATH |
2469 	    AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH) | LOCKSHARED | LOCKLEAF |
2470 	    AUDITVNODE1, pathseg, path, fd, &cap_fstat_rights);
2471 
2472 	if ((error = namei(&nd)) != 0) {
2473 		if (error == ENOTDIR &&
2474 		    (nd.ni_resflags & NIRES_EMPTYPATH) != 0)
2475 			error = kern_fstat(td, fd, sbp);
2476 		return (error);
2477 	}
2478 	error = VOP_STAT(nd.ni_vp, sbp, td->td_ucred, NOCRED);
2479 	NDFREE_PNBUF(&nd);
2480 	vput(nd.ni_vp);
2481 #ifdef __STAT_TIME_T_EXT
2482 	sbp->st_atim_ext = 0;
2483 	sbp->st_mtim_ext = 0;
2484 	sbp->st_ctim_ext = 0;
2485 	sbp->st_btim_ext = 0;
2486 #endif
2487 #ifdef KTRACE
2488 	if (KTRPOINT(td, KTR_STRUCT))
2489 		ktrstat_error(sbp, error);
2490 #endif
2491 	return (error);
2492 }
2493 
2494 #if defined(COMPAT_FREEBSD11)
2495 /*
2496  * Implementation of the NetBSD [l]stat() functions.
2497  */
2498 int
2499 freebsd11_cvtnstat(struct stat *sb, struct nstat *nsb)
2500 {
2501 	struct freebsd11_stat sb11;
2502 	int error;
2503 
2504 	error = freebsd11_cvtstat(sb, &sb11);
2505 	if (error != 0)
2506 		return (error);
2507 
2508 	bzero(nsb, sizeof(*nsb));
2509 	CP(sb11, *nsb, st_dev);
2510 	CP(sb11, *nsb, st_ino);
2511 	CP(sb11, *nsb, st_mode);
2512 	CP(sb11, *nsb, st_nlink);
2513 	CP(sb11, *nsb, st_uid);
2514 	CP(sb11, *nsb, st_gid);
2515 	CP(sb11, *nsb, st_rdev);
2516 	CP(sb11, *nsb, st_atim);
2517 	CP(sb11, *nsb, st_mtim);
2518 	CP(sb11, *nsb, st_ctim);
2519 	CP(sb11, *nsb, st_size);
2520 	CP(sb11, *nsb, st_blocks);
2521 	CP(sb11, *nsb, st_blksize);
2522 	CP(sb11, *nsb, st_flags);
2523 	CP(sb11, *nsb, st_gen);
2524 	CP(sb11, *nsb, st_birthtim);
2525 	return (0);
2526 }
2527 
2528 #ifndef _SYS_SYSPROTO_H_
2529 struct freebsd11_nstat_args {
2530 	char	*path;
2531 	struct nstat *ub;
2532 };
2533 #endif
2534 int
2535 freebsd11_nstat(struct thread *td, struct freebsd11_nstat_args *uap)
2536 {
2537 	struct stat sb;
2538 	struct nstat nsb;
2539 	int error;
2540 
2541 	error = kern_statat(td, 0, AT_FDCWD, uap->path, UIO_USERSPACE, &sb);
2542 	if (error != 0)
2543 		return (error);
2544 	error = freebsd11_cvtnstat(&sb, &nsb);
2545 	if (error == 0)
2546 		error = copyout(&nsb, uap->ub, sizeof (nsb));
2547 	return (error);
2548 }
2549 
2550 /*
2551  * NetBSD lstat.  Get file status; this version does not follow links.
2552  */
2553 #ifndef _SYS_SYSPROTO_H_
2554 struct freebsd11_nlstat_args {
2555 	char	*path;
2556 	struct nstat *ub;
2557 };
2558 #endif
2559 int
2560 freebsd11_nlstat(struct thread *td, struct freebsd11_nlstat_args *uap)
2561 {
2562 	struct stat sb;
2563 	struct nstat nsb;
2564 	int error;
2565 
2566 	error = kern_statat(td, AT_SYMLINK_NOFOLLOW, AT_FDCWD, uap->path,
2567 	    UIO_USERSPACE, &sb);
2568 	if (error != 0)
2569 		return (error);
2570 	error = freebsd11_cvtnstat(&sb, &nsb);
2571 	if (error == 0)
2572 		error = copyout(&nsb, uap->ub, sizeof (nsb));
2573 	return (error);
2574 }
2575 #endif /* COMPAT_FREEBSD11 */
2576 
2577 /*
2578  * Get configurable pathname variables.
2579  */
2580 #ifndef _SYS_SYSPROTO_H_
2581 struct pathconf_args {
2582 	char	*path;
2583 	int	name;
2584 };
2585 #endif
2586 int
2587 sys_pathconf(struct thread *td, struct pathconf_args *uap)
2588 {
2589 	long value;
2590 	int error;
2591 
2592 	error = kern_pathconf(td, uap->path, UIO_USERSPACE, uap->name, FOLLOW,
2593 	    &value);
2594 	if (error == 0)
2595 		td->td_retval[0] = value;
2596 	return (error);
2597 }
2598 
2599 #ifndef _SYS_SYSPROTO_H_
2600 struct lpathconf_args {
2601 	char	*path;
2602 	int	name;
2603 };
2604 #endif
2605 int
2606 sys_lpathconf(struct thread *td, struct lpathconf_args *uap)
2607 {
2608 	long value;
2609 	int error;
2610 
2611 	error = kern_pathconf(td, uap->path, UIO_USERSPACE, uap->name,
2612 	    NOFOLLOW, &value);
2613 	if (error == 0)
2614 		td->td_retval[0] = value;
2615 	return (error);
2616 }
2617 
2618 int
2619 kern_pathconf(struct thread *td, const char *path, enum uio_seg pathseg,
2620     int name, u_long flags, long *valuep)
2621 {
2622 	struct nameidata nd;
2623 	int error;
2624 
2625 	NDINIT(&nd, LOOKUP, LOCKSHARED | LOCKLEAF | AUDITVNODE1 | flags,
2626 	       pathseg, path);
2627 	if ((error = namei(&nd)) != 0)
2628 		return (error);
2629 	NDFREE_PNBUF(&nd);
2630 
2631 	error = VOP_PATHCONF(nd.ni_vp, name, valuep);
2632 	vput(nd.ni_vp);
2633 	return (error);
2634 }
2635 
2636 /*
2637  * Return target name of a symbolic link.
2638  */
2639 #ifndef _SYS_SYSPROTO_H_
2640 struct readlink_args {
2641 	char	*path;
2642 	char	*buf;
2643 	size_t	count;
2644 };
2645 #endif
2646 int
2647 sys_readlink(struct thread *td, struct readlink_args *uap)
2648 {
2649 
2650 	return (kern_readlinkat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
2651 	    uap->buf, UIO_USERSPACE, uap->count));
2652 }
2653 #ifndef _SYS_SYSPROTO_H_
2654 struct readlinkat_args {
2655 	int	fd;
2656 	char	*path;
2657 	char	*buf;
2658 	size_t	bufsize;
2659 };
2660 #endif
2661 int
2662 sys_readlinkat(struct thread *td, struct readlinkat_args *uap)
2663 {
2664 
2665 	return (kern_readlinkat(td, uap->fd, uap->path, UIO_USERSPACE,
2666 	    uap->buf, UIO_USERSPACE, uap->bufsize));
2667 }
2668 
2669 int
2670 kern_readlinkat(struct thread *td, int fd, const char *path,
2671     enum uio_seg pathseg, char *buf, enum uio_seg bufseg, size_t count)
2672 {
2673 	struct vnode *vp;
2674 	struct nameidata nd;
2675 	int error;
2676 
2677 	if (count > IOSIZE_MAX)
2678 		return (EINVAL);
2679 
2680 	NDINIT_AT(&nd, LOOKUP, NOFOLLOW | LOCKSHARED | LOCKLEAF | AUDITVNODE1 |
2681 	    EMPTYPATH, pathseg, path, fd);
2682 
2683 	if ((error = namei(&nd)) != 0)
2684 		return (error);
2685 	NDFREE_PNBUF(&nd);
2686 	vp = nd.ni_vp;
2687 
2688 	error = kern_readlink_vp(vp, buf, bufseg, count, td);
2689 	vput(vp);
2690 
2691 	return (error);
2692 }
2693 
2694 /*
2695  * Helper function to readlink from a vnode
2696  */
2697 static int
2698 kern_readlink_vp(struct vnode *vp, char *buf, enum uio_seg bufseg, size_t count,
2699     struct thread *td)
2700 {
2701 	struct iovec aiov;
2702 	struct uio auio;
2703 	int error;
2704 
2705 	ASSERT_VOP_LOCKED(vp, "kern_readlink_vp(): vp not locked");
2706 #ifdef MAC
2707 	error = mac_vnode_check_readlink(td->td_ucred, vp);
2708 	if (error != 0)
2709 		return (error);
2710 #endif
2711 	if (vp->v_type != VLNK && (vp->v_vflag & VV_READLINK) == 0)
2712 		return (EINVAL);
2713 
2714 	aiov.iov_base = buf;
2715 	aiov.iov_len = count;
2716 	auio.uio_iov = &aiov;
2717 	auio.uio_iovcnt = 1;
2718 	auio.uio_offset = 0;
2719 	auio.uio_rw = UIO_READ;
2720 	auio.uio_segflg = bufseg;
2721 	auio.uio_td = td;
2722 	auio.uio_resid = count;
2723 	error = VOP_READLINK(vp, &auio, td->td_ucred);
2724 	td->td_retval[0] = count - auio.uio_resid;
2725 	return (error);
2726 }
2727 
2728 /*
2729  * Common implementation code for chflags() and fchflags().
2730  */
2731 static int
2732 setfflags(struct thread *td, struct vnode *vp, u_long flags)
2733 {
2734 	struct mount *mp;
2735 	struct vattr vattr;
2736 	int error;
2737 
2738 	/* We can't support the value matching VNOVAL. */
2739 	if (flags == VNOVAL)
2740 		return (EOPNOTSUPP);
2741 
2742 	/*
2743 	 * Prevent non-root users from setting flags on devices.  When
2744 	 * a device is reused, users can retain ownership of the device
2745 	 * if they are allowed to set flags and programs assume that
2746 	 * chown can't fail when done as root.
2747 	 */
2748 	if (vp->v_type == VCHR || vp->v_type == VBLK) {
2749 		error = priv_check(td, PRIV_VFS_CHFLAGS_DEV);
2750 		if (error != 0)
2751 			return (error);
2752 	}
2753 
2754 	if ((error = vn_start_write(vp, &mp, V_WAIT | V_PCATCH)) != 0)
2755 		return (error);
2756 	VATTR_NULL(&vattr);
2757 	vattr.va_flags = flags;
2758 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2759 #ifdef MAC
2760 	error = mac_vnode_check_setflags(td->td_ucred, vp, vattr.va_flags);
2761 	if (error == 0)
2762 #endif
2763 		error = VOP_SETATTR(vp, &vattr, td->td_ucred);
2764 	VOP_UNLOCK(vp);
2765 	vn_finished_write(mp);
2766 	return (error);
2767 }
2768 
2769 /*
2770  * Change flags of a file given a path name.
2771  */
2772 #ifndef _SYS_SYSPROTO_H_
2773 struct chflags_args {
2774 	const char *path;
2775 	u_long	flags;
2776 };
2777 #endif
2778 int
2779 sys_chflags(struct thread *td, struct chflags_args *uap)
2780 {
2781 
2782 	return (kern_chflagsat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
2783 	    uap->flags, 0));
2784 }
2785 
2786 #ifndef _SYS_SYSPROTO_H_
2787 struct chflagsat_args {
2788 	int	fd;
2789 	const char *path;
2790 	u_long	flags;
2791 	int	atflag;
2792 }
2793 #endif
2794 int
2795 sys_chflagsat(struct thread *td, struct chflagsat_args *uap)
2796 {
2797 
2798 	return (kern_chflagsat(td, uap->fd, uap->path, UIO_USERSPACE,
2799 	    uap->flags, uap->atflag));
2800 }
2801 
2802 /*
2803  * Same as chflags() but doesn't follow symlinks.
2804  */
2805 #ifndef _SYS_SYSPROTO_H_
2806 struct lchflags_args {
2807 	const char *path;
2808 	u_long flags;
2809 };
2810 #endif
2811 int
2812 sys_lchflags(struct thread *td, struct lchflags_args *uap)
2813 {
2814 
2815 	return (kern_chflagsat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
2816 	    uap->flags, AT_SYMLINK_NOFOLLOW));
2817 }
2818 
2819 static int
2820 kern_chflagsat(struct thread *td, int fd, const char *path,
2821     enum uio_seg pathseg, u_long flags, int atflag)
2822 {
2823 	struct nameidata nd;
2824 	int error;
2825 
2826 	if ((atflag & ~(AT_SYMLINK_NOFOLLOW | AT_RESOLVE_BENEATH |
2827 	    AT_EMPTY_PATH)) != 0)
2828 		return (EINVAL);
2829 
2830 	AUDIT_ARG_FFLAGS(flags);
2831 	NDINIT_ATRIGHTS(&nd, LOOKUP, at2cnpflags(atflag, AT_SYMLINK_NOFOLLOW |
2832 	    AT_RESOLVE_BENEATH | AT_EMPTY_PATH) | AUDITVNODE1, pathseg, path,
2833 	    fd, &cap_fchflags_rights);
2834 	if ((error = namei(&nd)) != 0)
2835 		return (error);
2836 	NDFREE_PNBUF(&nd);
2837 	error = setfflags(td, nd.ni_vp, flags);
2838 	vrele(nd.ni_vp);
2839 	return (error);
2840 }
2841 
2842 /*
2843  * Change flags of a file given a file descriptor.
2844  */
2845 #ifndef _SYS_SYSPROTO_H_
2846 struct fchflags_args {
2847 	int	fd;
2848 	u_long	flags;
2849 };
2850 #endif
2851 int
2852 sys_fchflags(struct thread *td, struct fchflags_args *uap)
2853 {
2854 	struct file *fp;
2855 	int error;
2856 
2857 	AUDIT_ARG_FD(uap->fd);
2858 	AUDIT_ARG_FFLAGS(uap->flags);
2859 	error = getvnode(td, uap->fd, &cap_fchflags_rights,
2860 	    &fp);
2861 	if (error != 0)
2862 		return (error);
2863 #ifdef AUDIT
2864 	if (AUDITING_TD(td)) {
2865 		vn_lock(fp->f_vnode, LK_SHARED | LK_RETRY);
2866 		AUDIT_ARG_VNODE1(fp->f_vnode);
2867 		VOP_UNLOCK(fp->f_vnode);
2868 	}
2869 #endif
2870 	error = setfflags(td, fp->f_vnode, uap->flags);
2871 	fdrop(fp, td);
2872 	return (error);
2873 }
2874 
2875 /*
2876  * Common implementation code for chmod(), lchmod() and fchmod().
2877  */
2878 int
2879 setfmode(struct thread *td, struct ucred *cred, struct vnode *vp, int mode)
2880 {
2881 	struct mount *mp;
2882 	struct vattr vattr;
2883 	int error;
2884 
2885 	if ((error = vn_start_write(vp, &mp, V_WAIT | V_PCATCH)) != 0)
2886 		return (error);
2887 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2888 	VATTR_NULL(&vattr);
2889 	vattr.va_mode = mode & ALLPERMS;
2890 #ifdef MAC
2891 	error = mac_vnode_check_setmode(cred, vp, vattr.va_mode);
2892 	if (error == 0)
2893 #endif
2894 		error = VOP_SETATTR(vp, &vattr, cred);
2895 	VOP_UNLOCK(vp);
2896 	vn_finished_write(mp);
2897 	return (error);
2898 }
2899 
2900 /*
2901  * Change mode of a file given path name.
2902  */
2903 #ifndef _SYS_SYSPROTO_H_
2904 struct chmod_args {
2905 	char	*path;
2906 	int	mode;
2907 };
2908 #endif
2909 int
2910 sys_chmod(struct thread *td, struct chmod_args *uap)
2911 {
2912 
2913 	return (kern_fchmodat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
2914 	    uap->mode, 0));
2915 }
2916 
2917 #ifndef _SYS_SYSPROTO_H_
2918 struct fchmodat_args {
2919 	int	dirfd;
2920 	char	*path;
2921 	mode_t	mode;
2922 	int	flag;
2923 }
2924 #endif
2925 int
2926 sys_fchmodat(struct thread *td, struct fchmodat_args *uap)
2927 {
2928 
2929 	return (kern_fchmodat(td, uap->fd, uap->path, UIO_USERSPACE,
2930 	    uap->mode, uap->flag));
2931 }
2932 
2933 /*
2934  * Change mode of a file given path name (don't follow links.)
2935  */
2936 #ifndef _SYS_SYSPROTO_H_
2937 struct lchmod_args {
2938 	char	*path;
2939 	int	mode;
2940 };
2941 #endif
2942 int
2943 sys_lchmod(struct thread *td, struct lchmod_args *uap)
2944 {
2945 
2946 	return (kern_fchmodat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
2947 	    uap->mode, AT_SYMLINK_NOFOLLOW));
2948 }
2949 
2950 int
2951 kern_fchmodat(struct thread *td, int fd, const char *path,
2952     enum uio_seg pathseg, mode_t mode, int flag)
2953 {
2954 	struct nameidata nd;
2955 	int error;
2956 
2957 	if ((flag & ~(AT_SYMLINK_NOFOLLOW | AT_RESOLVE_BENEATH |
2958 	    AT_EMPTY_PATH)) != 0)
2959 		return (EINVAL);
2960 
2961 	AUDIT_ARG_MODE(mode);
2962 	NDINIT_ATRIGHTS(&nd, LOOKUP, at2cnpflags(flag, AT_SYMLINK_NOFOLLOW |
2963 	    AT_RESOLVE_BENEATH | AT_EMPTY_PATH) | AUDITVNODE1, pathseg, path,
2964 	    fd, &cap_fchmod_rights);
2965 	if ((error = namei(&nd)) != 0)
2966 		return (error);
2967 	NDFREE_PNBUF(&nd);
2968 	error = setfmode(td, td->td_ucred, nd.ni_vp, mode);
2969 	vrele(nd.ni_vp);
2970 	return (error);
2971 }
2972 
2973 /*
2974  * Change mode of a file given a file descriptor.
2975  */
2976 #ifndef _SYS_SYSPROTO_H_
2977 struct fchmod_args {
2978 	int	fd;
2979 	int	mode;
2980 };
2981 #endif
2982 int
2983 sys_fchmod(struct thread *td, struct fchmod_args *uap)
2984 {
2985 	struct file *fp;
2986 	int error;
2987 
2988 	AUDIT_ARG_FD(uap->fd);
2989 	AUDIT_ARG_MODE(uap->mode);
2990 
2991 	error = fget(td, uap->fd, &cap_fchmod_rights, &fp);
2992 	if (error != 0)
2993 		return (error);
2994 	error = fo_chmod(fp, uap->mode, td->td_ucred, td);
2995 	fdrop(fp, td);
2996 	return (error);
2997 }
2998 
2999 /*
3000  * Common implementation for chown(), lchown(), and fchown()
3001  */
3002 int
3003 setfown(struct thread *td, struct ucred *cred, struct vnode *vp, uid_t uid,
3004     gid_t gid)
3005 {
3006 	struct mount *mp;
3007 	struct vattr vattr;
3008 	int error;
3009 
3010 	if ((error = vn_start_write(vp, &mp, V_WAIT | V_PCATCH)) != 0)
3011 		return (error);
3012 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3013 	VATTR_NULL(&vattr);
3014 	vattr.va_uid = uid;
3015 	vattr.va_gid = gid;
3016 #ifdef MAC
3017 	error = mac_vnode_check_setowner(cred, vp, vattr.va_uid,
3018 	    vattr.va_gid);
3019 	if (error == 0)
3020 #endif
3021 		error = VOP_SETATTR(vp, &vattr, cred);
3022 	VOP_UNLOCK(vp);
3023 	vn_finished_write(mp);
3024 	return (error);
3025 }
3026 
3027 /*
3028  * Set ownership given a path name.
3029  */
3030 #ifndef _SYS_SYSPROTO_H_
3031 struct chown_args {
3032 	char	*path;
3033 	int	uid;
3034 	int	gid;
3035 };
3036 #endif
3037 int
3038 sys_chown(struct thread *td, struct chown_args *uap)
3039 {
3040 
3041 	return (kern_fchownat(td, AT_FDCWD, uap->path, UIO_USERSPACE, uap->uid,
3042 	    uap->gid, 0));
3043 }
3044 
3045 #ifndef _SYS_SYSPROTO_H_
3046 struct fchownat_args {
3047 	int fd;
3048 	const char * path;
3049 	uid_t uid;
3050 	gid_t gid;
3051 	int flag;
3052 };
3053 #endif
3054 int
3055 sys_fchownat(struct thread *td, struct fchownat_args *uap)
3056 {
3057 
3058 	return (kern_fchownat(td, uap->fd, uap->path, UIO_USERSPACE, uap->uid,
3059 	    uap->gid, uap->flag));
3060 }
3061 
3062 int
3063 kern_fchownat(struct thread *td, int fd, const char *path,
3064     enum uio_seg pathseg, int uid, int gid, int flag)
3065 {
3066 	struct nameidata nd;
3067 	int error;
3068 
3069 	if ((flag & ~(AT_SYMLINK_NOFOLLOW | AT_RESOLVE_BENEATH |
3070 	    AT_EMPTY_PATH)) != 0)
3071 		return (EINVAL);
3072 
3073 	AUDIT_ARG_OWNER(uid, gid);
3074 	NDINIT_ATRIGHTS(&nd, LOOKUP, at2cnpflags(flag, AT_SYMLINK_NOFOLLOW |
3075 	    AT_RESOLVE_BENEATH | AT_EMPTY_PATH) | AUDITVNODE1, pathseg, path,
3076 	    fd, &cap_fchown_rights);
3077 
3078 	if ((error = namei(&nd)) != 0)
3079 		return (error);
3080 	NDFREE_PNBUF(&nd);
3081 	error = setfown(td, td->td_ucred, nd.ni_vp, uid, gid);
3082 	vrele(nd.ni_vp);
3083 	return (error);
3084 }
3085 
3086 /*
3087  * Set ownership given a path name, do not cross symlinks.
3088  */
3089 #ifndef _SYS_SYSPROTO_H_
3090 struct lchown_args {
3091 	char	*path;
3092 	int	uid;
3093 	int	gid;
3094 };
3095 #endif
3096 int
3097 sys_lchown(struct thread *td, struct lchown_args *uap)
3098 {
3099 
3100 	return (kern_fchownat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
3101 	    uap->uid, uap->gid, AT_SYMLINK_NOFOLLOW));
3102 }
3103 
3104 /*
3105  * Set ownership given a file descriptor.
3106  */
3107 #ifndef _SYS_SYSPROTO_H_
3108 struct fchown_args {
3109 	int	fd;
3110 	int	uid;
3111 	int	gid;
3112 };
3113 #endif
3114 int
3115 sys_fchown(struct thread *td, struct fchown_args *uap)
3116 {
3117 	struct file *fp;
3118 	int error;
3119 
3120 	AUDIT_ARG_FD(uap->fd);
3121 	AUDIT_ARG_OWNER(uap->uid, uap->gid);
3122 	error = fget(td, uap->fd, &cap_fchown_rights, &fp);
3123 	if (error != 0)
3124 		return (error);
3125 	error = fo_chown(fp, uap->uid, uap->gid, td->td_ucred, td);
3126 	fdrop(fp, td);
3127 	return (error);
3128 }
3129 
3130 /*
3131  * Common implementation code for utimes(), lutimes(), and futimes().
3132  */
3133 static int
3134 getutimes(const struct timeval *usrtvp, enum uio_seg tvpseg,
3135     struct timespec *tsp)
3136 {
3137 	struct timeval tv[2];
3138 	const struct timeval *tvp;
3139 	int error;
3140 
3141 	if (usrtvp == NULL) {
3142 		vfs_timestamp(&tsp[0]);
3143 		tsp[1] = tsp[0];
3144 	} else {
3145 		if (tvpseg == UIO_SYSSPACE) {
3146 			tvp = usrtvp;
3147 		} else {
3148 			if ((error = copyin(usrtvp, tv, sizeof(tv))) != 0)
3149 				return (error);
3150 			tvp = tv;
3151 		}
3152 
3153 		if (tvp[0].tv_usec < 0 || tvp[0].tv_usec >= 1000000 ||
3154 		    tvp[1].tv_usec < 0 || tvp[1].tv_usec >= 1000000)
3155 			return (EINVAL);
3156 		TIMEVAL_TO_TIMESPEC(&tvp[0], &tsp[0]);
3157 		TIMEVAL_TO_TIMESPEC(&tvp[1], &tsp[1]);
3158 	}
3159 	return (0);
3160 }
3161 
3162 /*
3163  * Common implementation code for futimens(), utimensat().
3164  */
3165 #define	UTIMENS_NULL	0x1
3166 #define	UTIMENS_EXIT	0x2
3167 static int
3168 getutimens(const struct timespec *usrtsp, enum uio_seg tspseg,
3169     struct timespec *tsp, int *retflags)
3170 {
3171 	struct timespec tsnow;
3172 	int error;
3173 
3174 	vfs_timestamp(&tsnow);
3175 	*retflags = 0;
3176 	if (usrtsp == NULL) {
3177 		tsp[0] = tsnow;
3178 		tsp[1] = tsnow;
3179 		*retflags |= UTIMENS_NULL;
3180 		return (0);
3181 	}
3182 	if (tspseg == UIO_SYSSPACE) {
3183 		tsp[0] = usrtsp[0];
3184 		tsp[1] = usrtsp[1];
3185 	} else if ((error = copyin(usrtsp, tsp, sizeof(*tsp) * 2)) != 0)
3186 		return (error);
3187 	if (tsp[0].tv_nsec == UTIME_OMIT && tsp[1].tv_nsec == UTIME_OMIT)
3188 		*retflags |= UTIMENS_EXIT;
3189 	if (tsp[0].tv_nsec == UTIME_NOW && tsp[1].tv_nsec == UTIME_NOW)
3190 		*retflags |= UTIMENS_NULL;
3191 	if (tsp[0].tv_nsec == UTIME_OMIT)
3192 		tsp[0].tv_sec = VNOVAL;
3193 	else if (tsp[0].tv_nsec == UTIME_NOW)
3194 		tsp[0] = tsnow;
3195 	else if (tsp[0].tv_nsec < 0 || tsp[0].tv_nsec >= 1000000000L)
3196 		return (EINVAL);
3197 	if (tsp[1].tv_nsec == UTIME_OMIT)
3198 		tsp[1].tv_sec = VNOVAL;
3199 	else if (tsp[1].tv_nsec == UTIME_NOW)
3200 		tsp[1] = tsnow;
3201 	else if (tsp[1].tv_nsec < 0 || tsp[1].tv_nsec >= 1000000000L)
3202 		return (EINVAL);
3203 
3204 	return (0);
3205 }
3206 
3207 /*
3208  * Common implementation code for utimes(), lutimes(), futimes(), futimens(),
3209  * and utimensat().
3210  */
3211 static int
3212 setutimes(struct thread *td, struct vnode *vp, const struct timespec *ts,
3213     int numtimes, int nullflag)
3214 {
3215 	struct mount *mp;
3216 	struct vattr vattr;
3217 	int error;
3218 	bool setbirthtime;
3219 
3220 	setbirthtime = false;
3221 	vattr.va_birthtime.tv_sec = VNOVAL;
3222 	vattr.va_birthtime.tv_nsec = 0;
3223 
3224 	if ((error = vn_start_write(vp, &mp, V_WAIT | V_PCATCH)) != 0)
3225 		return (error);
3226 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3227 	if (numtimes < 3 && VOP_GETATTR(vp, &vattr, td->td_ucred) == 0 &&
3228 	    timespeccmp(&ts[1], &vattr.va_birthtime, < ))
3229 		setbirthtime = true;
3230 	VATTR_NULL(&vattr);
3231 	vattr.va_atime = ts[0];
3232 	vattr.va_mtime = ts[1];
3233 	if (setbirthtime)
3234 		vattr.va_birthtime = ts[1];
3235 	if (numtimes > 2)
3236 		vattr.va_birthtime = ts[2];
3237 	if (nullflag)
3238 		vattr.va_vaflags |= VA_UTIMES_NULL;
3239 #ifdef MAC
3240 	error = mac_vnode_check_setutimes(td->td_ucred, vp, vattr.va_atime,
3241 	    vattr.va_mtime);
3242 #endif
3243 	if (error == 0)
3244 		error = VOP_SETATTR(vp, &vattr, td->td_ucred);
3245 	VOP_UNLOCK(vp);
3246 	vn_finished_write(mp);
3247 	return (error);
3248 }
3249 
3250 /*
3251  * Set the access and modification times of a file.
3252  */
3253 #ifndef _SYS_SYSPROTO_H_
3254 struct utimes_args {
3255 	char	*path;
3256 	struct	timeval *tptr;
3257 };
3258 #endif
3259 int
3260 sys_utimes(struct thread *td, struct utimes_args *uap)
3261 {
3262 
3263 	return (kern_utimesat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
3264 	    uap->tptr, UIO_USERSPACE));
3265 }
3266 
3267 #ifndef _SYS_SYSPROTO_H_
3268 struct futimesat_args {
3269 	int fd;
3270 	const char * path;
3271 	const struct timeval * times;
3272 };
3273 #endif
3274 int
3275 sys_futimesat(struct thread *td, struct futimesat_args *uap)
3276 {
3277 
3278 	return (kern_utimesat(td, uap->fd, uap->path, UIO_USERSPACE,
3279 	    uap->times, UIO_USERSPACE));
3280 }
3281 
3282 int
3283 kern_utimesat(struct thread *td, int fd, const char *path,
3284     enum uio_seg pathseg, const struct timeval *tptr, enum uio_seg tptrseg)
3285 {
3286 	struct nameidata nd;
3287 	struct timespec ts[2];
3288 	int error;
3289 
3290 	if ((error = getutimes(tptr, tptrseg, ts)) != 0)
3291 		return (error);
3292 	NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | AUDITVNODE1, pathseg, path, fd,
3293 	    &cap_futimes_rights);
3294 
3295 	if ((error = namei(&nd)) != 0)
3296 		return (error);
3297 	NDFREE_PNBUF(&nd);
3298 	error = setutimes(td, nd.ni_vp, ts, 2, tptr == NULL);
3299 	vrele(nd.ni_vp);
3300 	return (error);
3301 }
3302 
3303 /*
3304  * Set the access and modification times of a file.
3305  */
3306 #ifndef _SYS_SYSPROTO_H_
3307 struct lutimes_args {
3308 	char	*path;
3309 	struct	timeval *tptr;
3310 };
3311 #endif
3312 int
3313 sys_lutimes(struct thread *td, struct lutimes_args *uap)
3314 {
3315 
3316 	return (kern_lutimes(td, uap->path, UIO_USERSPACE, uap->tptr,
3317 	    UIO_USERSPACE));
3318 }
3319 
3320 int
3321 kern_lutimes(struct thread *td, const char *path, enum uio_seg pathseg,
3322     const struct timeval *tptr, enum uio_seg tptrseg)
3323 {
3324 	struct timespec ts[2];
3325 	struct nameidata nd;
3326 	int error;
3327 
3328 	if ((error = getutimes(tptr, tptrseg, ts)) != 0)
3329 		return (error);
3330 	NDINIT(&nd, LOOKUP, NOFOLLOW | AUDITVNODE1, pathseg, path);
3331 	if ((error = namei(&nd)) != 0)
3332 		return (error);
3333 	NDFREE_PNBUF(&nd);
3334 	error = setutimes(td, nd.ni_vp, ts, 2, tptr == NULL);
3335 	vrele(nd.ni_vp);
3336 	return (error);
3337 }
3338 
3339 /*
3340  * Set the access and modification times of a file.
3341  */
3342 #ifndef _SYS_SYSPROTO_H_
3343 struct futimes_args {
3344 	int	fd;
3345 	struct	timeval *tptr;
3346 };
3347 #endif
3348 int
3349 sys_futimes(struct thread *td, struct futimes_args *uap)
3350 {
3351 
3352 	return (kern_futimes(td, uap->fd, uap->tptr, UIO_USERSPACE));
3353 }
3354 
3355 int
3356 kern_futimes(struct thread *td, int fd, const struct timeval *tptr,
3357     enum uio_seg tptrseg)
3358 {
3359 	struct timespec ts[2];
3360 	struct file *fp;
3361 	int error;
3362 
3363 	AUDIT_ARG_FD(fd);
3364 	error = getutimes(tptr, tptrseg, ts);
3365 	if (error != 0)
3366 		return (error);
3367 	error = getvnode(td, fd, &cap_futimes_rights, &fp);
3368 	if (error != 0)
3369 		return (error);
3370 #ifdef AUDIT
3371 	if (AUDITING_TD(td)) {
3372 		vn_lock(fp->f_vnode, LK_SHARED | LK_RETRY);
3373 		AUDIT_ARG_VNODE1(fp->f_vnode);
3374 		VOP_UNLOCK(fp->f_vnode);
3375 	}
3376 #endif
3377 	error = setutimes(td, fp->f_vnode, ts, 2, tptr == NULL);
3378 	fdrop(fp, td);
3379 	return (error);
3380 }
3381 
3382 int
3383 sys_futimens(struct thread *td, struct futimens_args *uap)
3384 {
3385 
3386 	return (kern_futimens(td, uap->fd, uap->times, UIO_USERSPACE));
3387 }
3388 
3389 int
3390 kern_futimens(struct thread *td, int fd, const struct timespec *tptr,
3391     enum uio_seg tptrseg)
3392 {
3393 	struct timespec ts[2];
3394 	struct file *fp;
3395 	int error, flags;
3396 
3397 	AUDIT_ARG_FD(fd);
3398 	error = getutimens(tptr, tptrseg, ts, &flags);
3399 	if (error != 0)
3400 		return (error);
3401 	if (flags & UTIMENS_EXIT)
3402 		return (0);
3403 	error = getvnode(td, fd, &cap_futimes_rights, &fp);
3404 	if (error != 0)
3405 		return (error);
3406 #ifdef AUDIT
3407 	if (AUDITING_TD(td)) {
3408 		vn_lock(fp->f_vnode, LK_SHARED | LK_RETRY);
3409 		AUDIT_ARG_VNODE1(fp->f_vnode);
3410 		VOP_UNLOCK(fp->f_vnode);
3411 	}
3412 #endif
3413 	error = setutimes(td, fp->f_vnode, ts, 2, flags & UTIMENS_NULL);
3414 	fdrop(fp, td);
3415 	return (error);
3416 }
3417 
3418 int
3419 sys_utimensat(struct thread *td, struct utimensat_args *uap)
3420 {
3421 
3422 	return (kern_utimensat(td, uap->fd, uap->path, UIO_USERSPACE,
3423 	    uap->times, UIO_USERSPACE, uap->flag));
3424 }
3425 
3426 int
3427 kern_utimensat(struct thread *td, int fd, const char *path,
3428     enum uio_seg pathseg, const struct timespec *tptr, enum uio_seg tptrseg,
3429     int flag)
3430 {
3431 	struct nameidata nd;
3432 	struct timespec ts[2];
3433 	int error, flags;
3434 
3435 	if ((flag & ~(AT_SYMLINK_NOFOLLOW | AT_RESOLVE_BENEATH |
3436 	    AT_EMPTY_PATH)) != 0)
3437 		return (EINVAL);
3438 
3439 	if ((error = getutimens(tptr, tptrseg, ts, &flags)) != 0)
3440 		return (error);
3441 	NDINIT_ATRIGHTS(&nd, LOOKUP, at2cnpflags(flag, AT_SYMLINK_NOFOLLOW |
3442 	    AT_RESOLVE_BENEATH | AT_EMPTY_PATH) | AUDITVNODE1,
3443 	    pathseg, path, fd, &cap_futimes_rights);
3444 	if ((error = namei(&nd)) != 0)
3445 		return (error);
3446 	/*
3447 	 * We are allowed to call namei() regardless of 2xUTIME_OMIT.
3448 	 * POSIX states:
3449 	 * "If both tv_nsec fields are UTIME_OMIT... EACCESS may be detected."
3450 	 * "Search permission is denied by a component of the path prefix."
3451 	 */
3452 	NDFREE_PNBUF(&nd);
3453 	if ((flags & UTIMENS_EXIT) == 0)
3454 		error = setutimes(td, nd.ni_vp, ts, 2, flags & UTIMENS_NULL);
3455 	vrele(nd.ni_vp);
3456 	return (error);
3457 }
3458 
3459 /*
3460  * Truncate a file given its path name.
3461  */
3462 #ifndef _SYS_SYSPROTO_H_
3463 struct truncate_args {
3464 	char	*path;
3465 	int	pad;
3466 	off_t	length;
3467 };
3468 #endif
3469 int
3470 sys_truncate(struct thread *td, struct truncate_args *uap)
3471 {
3472 
3473 	return (kern_truncate(td, uap->path, UIO_USERSPACE, uap->length));
3474 }
3475 
3476 int
3477 kern_truncate(struct thread *td, const char *path, enum uio_seg pathseg,
3478     off_t length)
3479 {
3480 	struct mount *mp;
3481 	struct vnode *vp;
3482 	void *rl_cookie;
3483 	struct nameidata nd;
3484 	int error;
3485 
3486 	if (length < 0)
3487 		return (EINVAL);
3488 	NDPREINIT(&nd);
3489 retry:
3490 	NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, pathseg, path);
3491 	if ((error = namei(&nd)) != 0)
3492 		return (error);
3493 	vp = nd.ni_vp;
3494 	NDFREE_PNBUF(&nd);
3495 	rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
3496 	if ((error = vn_start_write(vp, &mp, V_WAIT | V_PCATCH)) != 0) {
3497 		vn_rangelock_unlock(vp, rl_cookie);
3498 		vrele(vp);
3499 		return (error);
3500 	}
3501 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3502 	if (vp->v_type == VDIR) {
3503 		error = EISDIR;
3504 		goto out;
3505 	}
3506 #ifdef MAC
3507 	error = mac_vnode_check_write(td->td_ucred, NOCRED, vp);
3508 	if (error != 0)
3509 		goto out;
3510 #endif
3511 	error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
3512 	if (error != 0)
3513 		goto out;
3514 
3515 	error = vn_truncate_locked(vp, length, false, td->td_ucred);
3516 out:
3517 	VOP_UNLOCK(vp);
3518 	vn_finished_write(mp);
3519 	vn_rangelock_unlock(vp, rl_cookie);
3520 	vrele(vp);
3521 	if (error == ERELOOKUP)
3522 		goto retry;
3523 	return (error);
3524 }
3525 
3526 #if defined(COMPAT_43)
3527 /*
3528  * Truncate a file given its path name.
3529  */
3530 #ifndef _SYS_SYSPROTO_H_
3531 struct otruncate_args {
3532 	char	*path;
3533 	long	length;
3534 };
3535 #endif
3536 int
3537 otruncate(struct thread *td, struct otruncate_args *uap)
3538 {
3539 
3540 	return (kern_truncate(td, uap->path, UIO_USERSPACE, uap->length));
3541 }
3542 #endif /* COMPAT_43 */
3543 
3544 #if defined(COMPAT_FREEBSD6)
3545 /* Versions with the pad argument */
3546 int
3547 freebsd6_truncate(struct thread *td, struct freebsd6_truncate_args *uap)
3548 {
3549 
3550 	return (kern_truncate(td, uap->path, UIO_USERSPACE, uap->length));
3551 }
3552 
3553 int
3554 freebsd6_ftruncate(struct thread *td, struct freebsd6_ftruncate_args *uap)
3555 {
3556 
3557 	return (kern_ftruncate(td, uap->fd, uap->length));
3558 }
3559 #endif
3560 
3561 int
3562 kern_fsync(struct thread *td, int fd, bool fullsync)
3563 {
3564 	struct vnode *vp;
3565 	struct mount *mp;
3566 	struct file *fp;
3567 	int error;
3568 
3569 	AUDIT_ARG_FD(fd);
3570 	error = getvnode(td, fd, &cap_fsync_rights, &fp);
3571 	if (error != 0)
3572 		return (error);
3573 	vp = fp->f_vnode;
3574 #if 0
3575 	if (!fullsync)
3576 		/* XXXKIB: compete outstanding aio writes */;
3577 #endif
3578 retry:
3579 	error = vn_start_write(vp, &mp, V_WAIT | V_PCATCH);
3580 	if (error != 0)
3581 		goto drop;
3582 	vn_lock(vp, vn_lktype_write(mp, vp) | LK_RETRY);
3583 	AUDIT_ARG_VNODE1(vp);
3584 	vnode_pager_clean_async(vp);
3585 	error = fullsync ? VOP_FSYNC(vp, MNT_WAIT, td) : VOP_FDATASYNC(vp, td);
3586 	VOP_UNLOCK(vp);
3587 	vn_finished_write(mp);
3588 	if (error == ERELOOKUP)
3589 		goto retry;
3590 drop:
3591 	fdrop(fp, td);
3592 	return (error);
3593 }
3594 
3595 /*
3596  * Sync an open file.
3597  */
3598 #ifndef _SYS_SYSPROTO_H_
3599 struct fsync_args {
3600 	int	fd;
3601 };
3602 #endif
3603 int
3604 sys_fsync(struct thread *td, struct fsync_args *uap)
3605 {
3606 
3607 	return (kern_fsync(td, uap->fd, true));
3608 }
3609 
3610 int
3611 sys_fdatasync(struct thread *td, struct fdatasync_args *uap)
3612 {
3613 
3614 	return (kern_fsync(td, uap->fd, false));
3615 }
3616 
3617 /*
3618  * Rename files.  Source and destination must either both be directories, or
3619  * both not be directories.  If target is a directory, it must be empty.
3620  */
3621 #ifndef _SYS_SYSPROTO_H_
3622 struct rename_args {
3623 	char	*from;
3624 	char	*to;
3625 };
3626 #endif
3627 int
3628 sys_rename(struct thread *td, struct rename_args *uap)
3629 {
3630 
3631 	return (kern_renameat(td, AT_FDCWD, uap->from, AT_FDCWD,
3632 	    uap->to, UIO_USERSPACE));
3633 }
3634 
3635 #ifndef _SYS_SYSPROTO_H_
3636 struct renameat_args {
3637 	int	oldfd;
3638 	char	*old;
3639 	int	newfd;
3640 	char	*new;
3641 };
3642 #endif
3643 int
3644 sys_renameat(struct thread *td, struct renameat_args *uap)
3645 {
3646 
3647 	return (kern_renameat(td, uap->oldfd, uap->old, uap->newfd, uap->new,
3648 	    UIO_USERSPACE));
3649 }
3650 
3651 #ifdef MAC
3652 static int
3653 kern_renameat_mac(struct thread *td, int oldfd, const char *old, int newfd,
3654     const char *new, enum uio_seg pathseg, struct nameidata *fromnd)
3655 {
3656 	int error;
3657 
3658 	NDINIT_ATRIGHTS(fromnd, DELETE, LOCKPARENT | LOCKLEAF | AUDITVNODE1,
3659 	    pathseg, old, oldfd, &cap_renameat_source_rights);
3660 	if ((error = namei(fromnd)) != 0)
3661 		return (error);
3662 	error = mac_vnode_check_rename_from(td->td_ucred, fromnd->ni_dvp,
3663 	    fromnd->ni_vp, &fromnd->ni_cnd);
3664 	VOP_UNLOCK(fromnd->ni_dvp);
3665 	if (fromnd->ni_dvp != fromnd->ni_vp)
3666 		VOP_UNLOCK(fromnd->ni_vp);
3667 	if (error != 0) {
3668 		NDFREE_PNBUF(fromnd);
3669 		vrele(fromnd->ni_dvp);
3670 		vrele(fromnd->ni_vp);
3671 	}
3672 	return (error);
3673 }
3674 #endif
3675 
3676 int
3677 kern_renameat(struct thread *td, int oldfd, const char *old, int newfd,
3678     const char *new, enum uio_seg pathseg)
3679 {
3680 	struct mount *mp = NULL;
3681 	struct vnode *tvp, *fvp, *tdvp;
3682 	struct nameidata fromnd, tond;
3683 	uint64_t tondflags;
3684 	int error;
3685 
3686 again:
3687 	bwillwrite();
3688 #ifdef MAC
3689 	if (mac_vnode_check_rename_from_enabled()) {
3690 		error = kern_renameat_mac(td, oldfd, old, newfd, new, pathseg,
3691 		    &fromnd);
3692 		if (error != 0)
3693 			return (error);
3694 	} else {
3695 #endif
3696 	NDINIT_ATRIGHTS(&fromnd, DELETE, WANTPARENT | AUDITVNODE1,
3697 	    pathseg, old, oldfd, &cap_renameat_source_rights);
3698 	if ((error = namei(&fromnd)) != 0)
3699 		return (error);
3700 #ifdef MAC
3701 	}
3702 #endif
3703 	fvp = fromnd.ni_vp;
3704 	tondflags = LOCKPARENT | LOCKLEAF | NOCACHE | AUDITVNODE2;
3705 	if (fromnd.ni_vp->v_type == VDIR)
3706 		tondflags |= WILLBEDIR;
3707 	NDINIT_ATRIGHTS(&tond, RENAME, tondflags, pathseg, new, newfd,
3708 	    &cap_renameat_target_rights);
3709 	if ((error = namei(&tond)) != 0) {
3710 		/* Translate error code for rename("dir1", "dir2/."). */
3711 		if (error == EISDIR && fvp->v_type == VDIR)
3712 			error = EINVAL;
3713 		NDFREE_PNBUF(&fromnd);
3714 		vrele(fromnd.ni_dvp);
3715 		vrele(fvp);
3716 		goto out1;
3717 	}
3718 	tdvp = tond.ni_dvp;
3719 	tvp = tond.ni_vp;
3720 	error = vn_start_write(fvp, &mp, V_NOWAIT);
3721 	if (error != 0) {
3722 		NDFREE_PNBUF(&fromnd);
3723 		NDFREE_PNBUF(&tond);
3724 		if (tvp != NULL)
3725 			vput(tvp);
3726 		if (tdvp == tvp)
3727 			vrele(tdvp);
3728 		else
3729 			vput(tdvp);
3730 		vrele(fromnd.ni_dvp);
3731 		vrele(fvp);
3732 		error = vn_start_write(NULL, &mp, V_XSLEEP | V_PCATCH);
3733 		if (error != 0)
3734 			return (error);
3735 		goto again;
3736 	}
3737 	if (tvp != NULL) {
3738 		if (fvp->v_type == VDIR && tvp->v_type != VDIR) {
3739 			error = ENOTDIR;
3740 			goto out;
3741 		} else if (fvp->v_type != VDIR && tvp->v_type == VDIR) {
3742 			error = EISDIR;
3743 			goto out;
3744 		}
3745 #ifdef CAPABILITIES
3746 		if (newfd != AT_FDCWD && (tond.ni_resflags & NIRES_ABS) == 0) {
3747 			/*
3748 			 * If the target already exists we require CAP_UNLINKAT
3749 			 * from 'newfd', when newfd was used for the lookup.
3750 			 */
3751 			error = cap_check(&tond.ni_filecaps.fc_rights,
3752 			    &cap_unlinkat_rights);
3753 			if (error != 0)
3754 				goto out;
3755 		}
3756 #endif
3757 	}
3758 	if (fvp == tdvp) {
3759 		error = EINVAL;
3760 		goto out;
3761 	}
3762 	/*
3763 	 * If the source is the same as the destination (that is, if they
3764 	 * are links to the same vnode), then there is nothing to do.
3765 	 */
3766 	if (fvp == tvp)
3767 		error = ERESTART;
3768 #ifdef MAC
3769 	else
3770 		error = mac_vnode_check_rename_to(td->td_ucred, tdvp,
3771 		    tond.ni_vp, fromnd.ni_dvp == tdvp, &tond.ni_cnd);
3772 #endif
3773 out:
3774 	if (error == 0) {
3775 		error = VOP_RENAME(fromnd.ni_dvp, fromnd.ni_vp, &fromnd.ni_cnd,
3776 		    tond.ni_dvp, tond.ni_vp, &tond.ni_cnd);
3777 		NDFREE_PNBUF(&fromnd);
3778 		NDFREE_PNBUF(&tond);
3779 	} else {
3780 		NDFREE_PNBUF(&fromnd);
3781 		NDFREE_PNBUF(&tond);
3782 		if (tvp != NULL)
3783 			vput(tvp);
3784 		if (tdvp == tvp)
3785 			vrele(tdvp);
3786 		else
3787 			vput(tdvp);
3788 		vrele(fromnd.ni_dvp);
3789 		vrele(fvp);
3790 	}
3791 	vn_finished_write(mp);
3792 out1:
3793 	if (error == ERESTART)
3794 		return (0);
3795 	if (error == ERELOOKUP)
3796 		goto again;
3797 	return (error);
3798 }
3799 
3800 /*
3801  * Make a directory file.
3802  */
3803 #ifndef _SYS_SYSPROTO_H_
3804 struct mkdir_args {
3805 	char	*path;
3806 	int	mode;
3807 };
3808 #endif
3809 int
3810 sys_mkdir(struct thread *td, struct mkdir_args *uap)
3811 {
3812 
3813 	return (kern_mkdirat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
3814 	    uap->mode));
3815 }
3816 
3817 #ifndef _SYS_SYSPROTO_H_
3818 struct mkdirat_args {
3819 	int	fd;
3820 	char	*path;
3821 	mode_t	mode;
3822 };
3823 #endif
3824 int
3825 sys_mkdirat(struct thread *td, struct mkdirat_args *uap)
3826 {
3827 
3828 	return (kern_mkdirat(td, uap->fd, uap->path, UIO_USERSPACE, uap->mode));
3829 }
3830 
3831 int
3832 kern_mkdirat(struct thread *td, int fd, const char *path, enum uio_seg segflg,
3833     int mode)
3834 {
3835 	struct mount *mp;
3836 	struct vattr vattr;
3837 	struct nameidata nd;
3838 	int error;
3839 
3840 	AUDIT_ARG_MODE(mode);
3841 	NDPREINIT(&nd);
3842 restart:
3843 	bwillwrite();
3844 	NDINIT_ATRIGHTS(&nd, CREATE, LOCKPARENT | AUDITVNODE1 |
3845 	    NC_NOMAKEENTRY | NC_KEEPPOSENTRY | FAILIFEXISTS | WILLBEDIR,
3846 	    segflg, path, fd, &cap_mkdirat_rights);
3847 	if ((error = namei(&nd)) != 0)
3848 		return (error);
3849 	if (vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
3850 		NDFREE_PNBUF(&nd);
3851 		vput(nd.ni_dvp);
3852 		if ((error = vn_start_write(NULL, &mp, V_XSLEEP | V_PCATCH)) != 0)
3853 			return (error);
3854 		goto restart;
3855 	}
3856 	VATTR_NULL(&vattr);
3857 	vattr.va_type = VDIR;
3858 	vattr.va_mode = (mode & ACCESSPERMS) &~ td->td_proc->p_pd->pd_cmask;
3859 #ifdef MAC
3860 	error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
3861 	    &vattr);
3862 	if (error != 0)
3863 		goto out;
3864 #endif
3865 	error = VOP_MKDIR(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
3866 #ifdef MAC
3867 out:
3868 #endif
3869 	NDFREE_PNBUF(&nd);
3870 	VOP_VPUT_PAIR(nd.ni_dvp, error == 0 ? &nd.ni_vp : NULL, true);
3871 	vn_finished_write(mp);
3872 	if (error == ERELOOKUP)
3873 		goto restart;
3874 	return (error);
3875 }
3876 
3877 /*
3878  * Remove a directory file.
3879  */
3880 #ifndef _SYS_SYSPROTO_H_
3881 struct rmdir_args {
3882 	char	*path;
3883 };
3884 #endif
3885 int
3886 sys_rmdir(struct thread *td, struct rmdir_args *uap)
3887 {
3888 
3889 	return (kern_frmdirat(td, AT_FDCWD, uap->path, FD_NONE, UIO_USERSPACE,
3890 	    0));
3891 }
3892 
3893 int
3894 kern_frmdirat(struct thread *td, int dfd, const char *path, int fd,
3895     enum uio_seg pathseg, int flag)
3896 {
3897 	struct mount *mp;
3898 	struct vnode *vp;
3899 	struct file *fp;
3900 	struct nameidata nd;
3901 	cap_rights_t rights;
3902 	int error;
3903 
3904 	fp = NULL;
3905 	if (fd != FD_NONE) {
3906 		error = getvnode(td, fd, cap_rights_init_one(&rights,
3907 		    CAP_LOOKUP), &fp);
3908 		if (error != 0)
3909 			return (error);
3910 	}
3911 
3912 	NDPREINIT(&nd);
3913 restart:
3914 	bwillwrite();
3915 	NDINIT_ATRIGHTS(&nd, DELETE, LOCKPARENT | LOCKLEAF | AUDITVNODE1 |
3916 	    at2cnpflags(flag, AT_RESOLVE_BENEATH),
3917 	    pathseg, path, dfd, &cap_unlinkat_rights);
3918 	if ((error = namei(&nd)) != 0)
3919 		goto fdout;
3920 	vp = nd.ni_vp;
3921 	if (vp->v_type != VDIR) {
3922 		error = ENOTDIR;
3923 		goto out;
3924 	}
3925 	/*
3926 	 * No rmdir "." please.
3927 	 */
3928 	if (nd.ni_dvp == vp) {
3929 		error = EINVAL;
3930 		goto out;
3931 	}
3932 	/*
3933 	 * The root of a mounted filesystem cannot be deleted.
3934 	 */
3935 	if (vp->v_vflag & VV_ROOT) {
3936 		error = EBUSY;
3937 		goto out;
3938 	}
3939 
3940 	if (fp != NULL && fp->f_vnode != vp) {
3941 		if (VN_IS_DOOMED(fp->f_vnode))
3942 			error = EBADF;
3943 		else
3944 			error = EDEADLK;
3945 		goto out;
3946 	}
3947 
3948 #ifdef MAC
3949 	error = mac_vnode_check_unlink(td->td_ucred, nd.ni_dvp, vp,
3950 	    &nd.ni_cnd);
3951 	if (error != 0)
3952 		goto out;
3953 #endif
3954 	if (vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
3955 		NDFREE_PNBUF(&nd);
3956 		vput(vp);
3957 		if (nd.ni_dvp == vp)
3958 			vrele(nd.ni_dvp);
3959 		else
3960 			vput(nd.ni_dvp);
3961 		if ((error = vn_start_write(NULL, &mp, V_XSLEEP | V_PCATCH)) != 0)
3962 			goto fdout;
3963 		goto restart;
3964 	}
3965 	vfs_notify_upper(vp, VFS_NOTIFY_UPPER_UNLINK);
3966 	error = VOP_RMDIR(nd.ni_dvp, nd.ni_vp, &nd.ni_cnd);
3967 	vn_finished_write(mp);
3968 out:
3969 	NDFREE_PNBUF(&nd);
3970 	vput(vp);
3971 	if (nd.ni_dvp == vp)
3972 		vrele(nd.ni_dvp);
3973 	else
3974 		vput(nd.ni_dvp);
3975 	if (error == ERELOOKUP)
3976 		goto restart;
3977 fdout:
3978 	if (fp != NULL)
3979 		fdrop(fp, td);
3980 	return (error);
3981 }
3982 
3983 #if defined(COMPAT_43) || defined(COMPAT_FREEBSD11)
3984 int
3985 freebsd11_kern_getdirentries(struct thread *td, int fd, char *ubuf, u_int count,
3986     long *basep, void (*func)(struct freebsd11_dirent *))
3987 {
3988 	struct freebsd11_dirent dstdp;
3989 	struct dirent *dp, *edp;
3990 	char *dirbuf;
3991 	off_t base;
3992 	ssize_t resid, ucount;
3993 	int error;
3994 
3995 	/* XXX arbitrary sanity limit on `count'. */
3996 	count = min(count, 64 * 1024);
3997 
3998 	dirbuf = malloc(count, M_TEMP, M_WAITOK);
3999 
4000 	error = kern_getdirentries(td, fd, dirbuf, count, &base, &resid,
4001 	    UIO_SYSSPACE);
4002 	if (error != 0)
4003 		goto done;
4004 	if (basep != NULL)
4005 		*basep = base;
4006 
4007 	ucount = 0;
4008 	for (dp = (struct dirent *)dirbuf,
4009 	    edp = (struct dirent *)&dirbuf[count - resid];
4010 	    ucount < count && dp < edp; ) {
4011 		if (dp->d_reclen == 0)
4012 			break;
4013 		MPASS(dp->d_reclen >= _GENERIC_DIRLEN(0));
4014 		if (dp->d_namlen >= sizeof(dstdp.d_name))
4015 			continue;
4016 		dstdp.d_type = dp->d_type;
4017 		dstdp.d_namlen = dp->d_namlen;
4018 		dstdp.d_fileno = dp->d_fileno;		/* truncate */
4019 		if (dstdp.d_fileno != dp->d_fileno) {
4020 			switch (ino64_trunc_error) {
4021 			default:
4022 			case 0:
4023 				break;
4024 			case 1:
4025 				error = EOVERFLOW;
4026 				goto done;
4027 			case 2:
4028 				dstdp.d_fileno = UINT32_MAX;
4029 				break;
4030 			}
4031 		}
4032 		dstdp.d_reclen = sizeof(dstdp) - sizeof(dstdp.d_name) +
4033 		    ((dp->d_namlen + 1 + 3) &~ 3);
4034 		bcopy(dp->d_name, dstdp.d_name, dstdp.d_namlen);
4035 		bzero(dstdp.d_name + dstdp.d_namlen,
4036 		    dstdp.d_reclen - offsetof(struct freebsd11_dirent, d_name) -
4037 		    dstdp.d_namlen);
4038 		MPASS(dstdp.d_reclen <= dp->d_reclen);
4039 		MPASS(ucount + dstdp.d_reclen <= count);
4040 		if (func != NULL)
4041 			func(&dstdp);
4042 		error = copyout(&dstdp, ubuf + ucount, dstdp.d_reclen);
4043 		if (error != 0)
4044 			break;
4045 		dp = (struct dirent *)((char *)dp + dp->d_reclen);
4046 		ucount += dstdp.d_reclen;
4047 	}
4048 
4049 done:
4050 	free(dirbuf, M_TEMP);
4051 	if (error == 0)
4052 		td->td_retval[0] = ucount;
4053 	return (error);
4054 }
4055 #endif /* COMPAT */
4056 
4057 #ifdef COMPAT_43
4058 static void
4059 ogetdirentries_cvt(struct freebsd11_dirent *dp)
4060 {
4061 #if (BYTE_ORDER == LITTLE_ENDIAN)
4062 	/*
4063 	 * The expected low byte of dp->d_namlen is our dp->d_type.
4064 	 * The high MBZ byte of dp->d_namlen is our dp->d_namlen.
4065 	 */
4066 	dp->d_type = dp->d_namlen;
4067 	dp->d_namlen = 0;
4068 #else
4069 	/*
4070 	 * The dp->d_type is the high byte of the expected dp->d_namlen,
4071 	 * so must be zero'ed.
4072 	 */
4073 	dp->d_type = 0;
4074 #endif
4075 }
4076 
4077 /*
4078  * Read a block of directory entries in a filesystem independent format.
4079  */
4080 #ifndef _SYS_SYSPROTO_H_
4081 struct ogetdirentries_args {
4082 	int	fd;
4083 	char	*buf;
4084 	u_int	count;
4085 	long	*basep;
4086 };
4087 #endif
4088 int
4089 ogetdirentries(struct thread *td, struct ogetdirentries_args *uap)
4090 {
4091 	long loff;
4092 	int error;
4093 
4094 	error = kern_ogetdirentries(td, uap, &loff);
4095 	if (error == 0)
4096 		error = copyout(&loff, uap->basep, sizeof(long));
4097 	return (error);
4098 }
4099 
4100 int
4101 kern_ogetdirentries(struct thread *td, struct ogetdirentries_args *uap,
4102     long *ploff)
4103 {
4104 	long base;
4105 	int error;
4106 
4107 	/* XXX arbitrary sanity limit on `count'. */
4108 	if (uap->count > 64 * 1024)
4109 		return (EINVAL);
4110 
4111 	error = freebsd11_kern_getdirentries(td, uap->fd, uap->buf, uap->count,
4112 	    &base, ogetdirentries_cvt);
4113 
4114 	if (error == 0 && uap->basep != NULL)
4115 		error = copyout(&base, uap->basep, sizeof(long));
4116 
4117 	return (error);
4118 }
4119 #endif /* COMPAT_43 */
4120 
4121 #if defined(COMPAT_FREEBSD11)
4122 #ifndef _SYS_SYSPROTO_H_
4123 struct freebsd11_getdirentries_args {
4124 	int	fd;
4125 	char	*buf;
4126 	u_int	count;
4127 	long	*basep;
4128 };
4129 #endif
4130 int
4131 freebsd11_getdirentries(struct thread *td,
4132     struct freebsd11_getdirentries_args *uap)
4133 {
4134 	long base;
4135 	int error;
4136 
4137 	error = freebsd11_kern_getdirentries(td, uap->fd, uap->buf, uap->count,
4138 	    &base, NULL);
4139 
4140 	if (error == 0 && uap->basep != NULL)
4141 		error = copyout(&base, uap->basep, sizeof(long));
4142 	return (error);
4143 }
4144 
4145 int
4146 freebsd11_getdents(struct thread *td, struct freebsd11_getdents_args *uap)
4147 {
4148 	struct freebsd11_getdirentries_args ap;
4149 
4150 	ap.fd = uap->fd;
4151 	ap.buf = uap->buf;
4152 	ap.count = uap->count;
4153 	ap.basep = NULL;
4154 	return (freebsd11_getdirentries(td, &ap));
4155 }
4156 #endif /* COMPAT_FREEBSD11 */
4157 
4158 /*
4159  * Read a block of directory entries in a filesystem independent format.
4160  */
4161 int
4162 sys_getdirentries(struct thread *td, struct getdirentries_args *uap)
4163 {
4164 	off_t base;
4165 	int error;
4166 
4167 	error = kern_getdirentries(td, uap->fd, uap->buf, uap->count, &base,
4168 	    NULL, UIO_USERSPACE);
4169 	if (error != 0)
4170 		return (error);
4171 	if (uap->basep != NULL)
4172 		error = copyout(&base, uap->basep, sizeof(off_t));
4173 	return (error);
4174 }
4175 
4176 int
4177 kern_getdirentries(struct thread *td, int fd, char *buf, size_t count,
4178     off_t *basep, ssize_t *residp, enum uio_seg bufseg)
4179 {
4180 	struct vnode *vp;
4181 	struct file *fp;
4182 	struct uio auio;
4183 	struct iovec aiov;
4184 	off_t loff;
4185 	int error, eofflag;
4186 	off_t foffset;
4187 
4188 	AUDIT_ARG_FD(fd);
4189 	if (count > IOSIZE_MAX)
4190 		return (EINVAL);
4191 	auio.uio_resid = count;
4192 	error = getvnode(td, fd, &cap_read_rights, &fp);
4193 	if (error != 0)
4194 		return (error);
4195 	if ((fp->f_flag & FREAD) == 0) {
4196 		fdrop(fp, td);
4197 		return (EBADF);
4198 	}
4199 	vp = fp->f_vnode;
4200 	foffset = foffset_lock(fp, 0);
4201 unionread:
4202 	if (vp->v_type != VDIR) {
4203 		error = EINVAL;
4204 		goto fail;
4205 	}
4206 	if (__predict_false((vp->v_vflag & VV_UNLINKED) != 0)) {
4207 		error = ENOENT;
4208 		goto fail;
4209 	}
4210 	aiov.iov_base = buf;
4211 	aiov.iov_len = count;
4212 	auio.uio_iov = &aiov;
4213 	auio.uio_iovcnt = 1;
4214 	auio.uio_rw = UIO_READ;
4215 	auio.uio_segflg = bufseg;
4216 	auio.uio_td = td;
4217 	vn_lock(vp, LK_SHARED | LK_RETRY);
4218 	AUDIT_ARG_VNODE1(vp);
4219 	loff = auio.uio_offset = foffset;
4220 #ifdef MAC
4221 	error = mac_vnode_check_readdir(td->td_ucred, vp);
4222 	if (error == 0)
4223 #endif
4224 		error = VOP_READDIR(vp, &auio, fp->f_cred, &eofflag, NULL,
4225 		    NULL);
4226 	foffset = auio.uio_offset;
4227 	if (error != 0) {
4228 		VOP_UNLOCK(vp);
4229 		goto fail;
4230 	}
4231 	if (count == auio.uio_resid &&
4232 	    (vp->v_vflag & VV_ROOT) &&
4233 	    (vp->v_mount->mnt_flag & MNT_UNION)) {
4234 		struct vnode *tvp = vp;
4235 
4236 		vp = vp->v_mount->mnt_vnodecovered;
4237 		VREF(vp);
4238 		fp->f_vnode = vp;
4239 		foffset = 0;
4240 		vput(tvp);
4241 		goto unionread;
4242 	}
4243 	VOP_UNLOCK(vp);
4244 	*basep = loff;
4245 	if (residp != NULL)
4246 		*residp = auio.uio_resid;
4247 	td->td_retval[0] = count - auio.uio_resid;
4248 fail:
4249 	foffset_unlock(fp, foffset, 0);
4250 	fdrop(fp, td);
4251 	return (error);
4252 }
4253 
4254 /*
4255  * Set the mode mask for creation of filesystem nodes.
4256  */
4257 #ifndef _SYS_SYSPROTO_H_
4258 struct umask_args {
4259 	int	newmask;
4260 };
4261 #endif
4262 int
4263 sys_umask(struct thread *td, struct umask_args *uap)
4264 {
4265 	struct pwddesc *pdp;
4266 
4267 	pdp = td->td_proc->p_pd;
4268 	PWDDESC_XLOCK(pdp);
4269 	td->td_retval[0] = pdp->pd_cmask;
4270 	pdp->pd_cmask = uap->newmask & ALLPERMS;
4271 	PWDDESC_XUNLOCK(pdp);
4272 	return (0);
4273 }
4274 
4275 /*
4276  * Void all references to file by ripping underlying filesystem away from
4277  * vnode.
4278  */
4279 #ifndef _SYS_SYSPROTO_H_
4280 struct revoke_args {
4281 	char	*path;
4282 };
4283 #endif
4284 int
4285 sys_revoke(struct thread *td, struct revoke_args *uap)
4286 {
4287 	struct vnode *vp;
4288 	struct vattr vattr;
4289 	struct nameidata nd;
4290 	int error;
4291 
4292 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1, UIO_USERSPACE,
4293 	    uap->path);
4294 	if ((error = namei(&nd)) != 0)
4295 		return (error);
4296 	vp = nd.ni_vp;
4297 	NDFREE_PNBUF(&nd);
4298 	if (vp->v_type != VCHR || vp->v_rdev == NULL) {
4299 		error = EINVAL;
4300 		goto out;
4301 	}
4302 #ifdef MAC
4303 	error = mac_vnode_check_revoke(td->td_ucred, vp);
4304 	if (error != 0)
4305 		goto out;
4306 #endif
4307 	error = VOP_GETATTR(vp, &vattr, td->td_ucred);
4308 	if (error != 0)
4309 		goto out;
4310 	if (td->td_ucred->cr_uid != vattr.va_uid) {
4311 		error = priv_check(td, PRIV_VFS_ADMIN);
4312 		if (error != 0)
4313 			goto out;
4314 	}
4315 	if (devfs_usecount(vp) > 0)
4316 		VOP_REVOKE(vp, REVOKEALL);
4317 out:
4318 	vput(vp);
4319 	return (error);
4320 }
4321 
4322 /*
4323  * This variant of getvnode() allows O_PATH files.  Caller should
4324  * ensure that returned file and vnode are only used for compatible
4325  * semantics.
4326  */
4327 int
4328 getvnode_path(struct thread *td, int fd, cap_rights_t *rightsp,
4329     struct file **fpp)
4330 {
4331 	struct file *fp;
4332 	int error;
4333 
4334 	error = fget_unlocked(td, fd, rightsp, &fp);
4335 	if (error != 0)
4336 		return (error);
4337 
4338 	/*
4339 	 * The file could be not of the vnode type, or it may be not
4340 	 * yet fully initialized, in which case the f_vnode pointer
4341 	 * may be set, but f_ops is still badfileops.  E.g.,
4342 	 * devfs_open() transiently create such situation to
4343 	 * facilitate csw d_fdopen().
4344 	 *
4345 	 * Dupfdopen() handling in kern_openat() installs the
4346 	 * half-baked file into the process descriptor table, allowing
4347 	 * other thread to dereference it. Guard against the race by
4348 	 * checking f_ops.
4349 	 */
4350 	if (__predict_false(fp->f_vnode == NULL || fp->f_ops == &badfileops)) {
4351 		fdrop(fp, td);
4352 		*fpp = NULL;
4353 		return (EINVAL);
4354 	}
4355 
4356 	*fpp = fp;
4357 	return (0);
4358 }
4359 
4360 /*
4361  * Convert a user file descriptor to a kernel file entry and check
4362  * that, if it is a capability, the correct rights are present.
4363  * A reference on the file entry is held upon returning.
4364  */
4365 int
4366 getvnode(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
4367 {
4368 	int error;
4369 
4370 	error = getvnode_path(td, fd, rightsp, fpp);
4371 	if (__predict_false(error != 0))
4372 		return (error);
4373 
4374 	/*
4375 	 * Filter out O_PATH file descriptors, most getvnode() callers
4376 	 * do not call fo_ methods.
4377 	 */
4378 	if (__predict_false((*fpp)->f_ops == &path_fileops)) {
4379 		fdrop(*fpp, td);
4380 		*fpp = NULL;
4381 		error = EBADF;
4382 	}
4383 
4384 	return (error);
4385 }
4386 
4387 /*
4388  * Get an (NFS) file handle.
4389  */
4390 #ifndef _SYS_SYSPROTO_H_
4391 struct lgetfh_args {
4392 	char *fname;
4393 	fhandle_t *fhp;
4394 };
4395 #endif
4396 int
4397 sys_lgetfh(struct thread *td, struct lgetfh_args *uap)
4398 {
4399 
4400 	return (kern_getfhat(td, AT_SYMLINK_NOFOLLOW, AT_FDCWD, uap->fname,
4401 	    UIO_USERSPACE, uap->fhp, UIO_USERSPACE));
4402 }
4403 
4404 #ifndef _SYS_SYSPROTO_H_
4405 struct getfh_args {
4406 	char *fname;
4407 	fhandle_t *fhp;
4408 };
4409 #endif
4410 int
4411 sys_getfh(struct thread *td, struct getfh_args *uap)
4412 {
4413 
4414 	return (kern_getfhat(td, 0, AT_FDCWD, uap->fname, UIO_USERSPACE,
4415 	    uap->fhp, UIO_USERSPACE));
4416 }
4417 
4418 /*
4419  * syscall for the rpc.lockd to use to translate an open descriptor into
4420  * a NFS file handle.
4421  *
4422  * warning: do not remove the priv_check() call or this becomes one giant
4423  * security hole.
4424  */
4425 #ifndef _SYS_SYSPROTO_H_
4426 struct getfhat_args {
4427 	int fd;
4428 	char *path;
4429 	fhandle_t *fhp;
4430 	int flags;
4431 };
4432 #endif
4433 int
4434 sys_getfhat(struct thread *td, struct getfhat_args *uap)
4435 {
4436 
4437 	return (kern_getfhat(td, uap->flags, uap->fd, uap->path, UIO_USERSPACE,
4438 	    uap->fhp, UIO_USERSPACE));
4439 }
4440 
4441 int
4442 kern_getfhat(struct thread *td, int flags, int fd, const char *path,
4443     enum uio_seg pathseg, fhandle_t *fhp, enum uio_seg fhseg)
4444 {
4445 	struct nameidata nd;
4446 	fhandle_t fh;
4447 	struct vnode *vp;
4448 	int error;
4449 
4450 	if ((flags & ~(AT_SYMLINK_NOFOLLOW | AT_RESOLVE_BENEATH)) != 0)
4451 		return (EINVAL);
4452 	error = priv_check(td, PRIV_VFS_GETFH);
4453 	if (error != 0)
4454 		return (error);
4455 	NDINIT_AT(&nd, LOOKUP, at2cnpflags(flags, AT_SYMLINK_NOFOLLOW |
4456 	    AT_RESOLVE_BENEATH) | LOCKLEAF | AUDITVNODE1, pathseg, path,
4457 	    fd);
4458 	error = namei(&nd);
4459 	if (error != 0)
4460 		return (error);
4461 	NDFREE_PNBUF(&nd);
4462 	vp = nd.ni_vp;
4463 	bzero(&fh, sizeof(fh));
4464 	fh.fh_fsid = vp->v_mount->mnt_stat.f_fsid;
4465 	error = VOP_VPTOFH(vp, &fh.fh_fid);
4466 	vput(vp);
4467 	if (error == 0) {
4468 		if (fhseg == UIO_USERSPACE)
4469 			error = copyout(&fh, fhp, sizeof (fh));
4470 		else
4471 			memcpy(fhp, &fh, sizeof(fh));
4472 	}
4473 	return (error);
4474 }
4475 
4476 #ifndef _SYS_SYSPROTO_H_
4477 struct fhlink_args {
4478 	fhandle_t *fhp;
4479 	const char *to;
4480 };
4481 #endif
4482 int
4483 sys_fhlink(struct thread *td, struct fhlink_args *uap)
4484 {
4485 
4486 	return (kern_fhlinkat(td, AT_FDCWD, uap->to, UIO_USERSPACE, uap->fhp));
4487 }
4488 
4489 #ifndef _SYS_SYSPROTO_H_
4490 struct fhlinkat_args {
4491 	fhandle_t *fhp;
4492 	int tofd;
4493 	const char *to;
4494 };
4495 #endif
4496 int
4497 sys_fhlinkat(struct thread *td, struct fhlinkat_args *uap)
4498 {
4499 
4500 	return (kern_fhlinkat(td, uap->tofd, uap->to, UIO_USERSPACE, uap->fhp));
4501 }
4502 
4503 static int
4504 kern_fhlinkat(struct thread *td, int fd, const char *path,
4505     enum uio_seg pathseg, fhandle_t *fhp)
4506 {
4507 	fhandle_t fh;
4508 	struct mount *mp;
4509 	struct vnode *vp;
4510 	int error;
4511 
4512 	error = priv_check(td, PRIV_VFS_GETFH);
4513 	if (error != 0)
4514 		return (error);
4515 	error = copyin(fhp, &fh, sizeof(fh));
4516 	if (error != 0)
4517 		return (error);
4518 	do {
4519 		bwillwrite();
4520 		if ((mp = vfs_busyfs(&fh.fh_fsid)) == NULL)
4521 			return (ESTALE);
4522 		error = VFS_FHTOVP(mp, &fh.fh_fid, LK_SHARED, &vp);
4523 		vfs_unbusy(mp);
4524 		if (error != 0)
4525 			return (error);
4526 		VOP_UNLOCK(vp);
4527 		error = kern_linkat_vp(td, vp, fd, path, pathseg);
4528 	} while (error == EAGAIN || error == ERELOOKUP);
4529 	return (error);
4530 }
4531 
4532 #ifndef _SYS_SYSPROTO_H_
4533 struct fhreadlink_args {
4534 	fhandle_t *fhp;
4535 	char *buf;
4536 	size_t bufsize;
4537 };
4538 #endif
4539 int
4540 sys_fhreadlink(struct thread *td, struct fhreadlink_args *uap)
4541 {
4542 	fhandle_t fh;
4543 	struct mount *mp;
4544 	struct vnode *vp;
4545 	int error;
4546 
4547 	error = priv_check(td, PRIV_VFS_GETFH);
4548 	if (error != 0)
4549 		return (error);
4550 	if (uap->bufsize > IOSIZE_MAX)
4551 		return (EINVAL);
4552 	error = copyin(uap->fhp, &fh, sizeof(fh));
4553 	if (error != 0)
4554 		return (error);
4555 	if ((mp = vfs_busyfs(&fh.fh_fsid)) == NULL)
4556 		return (ESTALE);
4557 	error = VFS_FHTOVP(mp, &fh.fh_fid, LK_SHARED, &vp);
4558 	vfs_unbusy(mp);
4559 	if (error != 0)
4560 		return (error);
4561 	error = kern_readlink_vp(vp, uap->buf, UIO_USERSPACE, uap->bufsize, td);
4562 	vput(vp);
4563 	return (error);
4564 }
4565 
4566 /*
4567  * syscall for the rpc.lockd to use to translate a NFS file handle into an
4568  * open descriptor.
4569  *
4570  * warning: do not remove the priv_check() call or this becomes one giant
4571  * security hole.
4572  */
4573 #ifndef _SYS_SYSPROTO_H_
4574 struct fhopen_args {
4575 	const struct fhandle *u_fhp;
4576 	int flags;
4577 };
4578 #endif
4579 int
4580 sys_fhopen(struct thread *td, struct fhopen_args *uap)
4581 {
4582 	return (kern_fhopen(td, uap->u_fhp, uap->flags));
4583 }
4584 
4585 int
4586 kern_fhopen(struct thread *td, const struct fhandle *u_fhp, int flags)
4587 {
4588 	struct mount *mp;
4589 	struct vnode *vp;
4590 	struct fhandle fhp;
4591 	struct file *fp;
4592 	int fmode, error;
4593 	int indx;
4594 
4595 	error = priv_check(td, PRIV_VFS_FHOPEN);
4596 	if (error != 0)
4597 		return (error);
4598 	indx = -1;
4599 	fmode = FFLAGS(flags);
4600 	/* why not allow a non-read/write open for our lockd? */
4601 	if (((fmode & (FREAD | FWRITE)) == 0) || (fmode & O_CREAT))
4602 		return (EINVAL);
4603 	error = copyin(u_fhp, &fhp, sizeof(fhp));
4604 	if (error != 0)
4605 		return(error);
4606 	/* find the mount point */
4607 	mp = vfs_busyfs(&fhp.fh_fsid);
4608 	if (mp == NULL)
4609 		return (ESTALE);
4610 	/* now give me my vnode, it gets returned to me locked */
4611 	error = VFS_FHTOVP(mp, &fhp.fh_fid, LK_EXCLUSIVE, &vp);
4612 	vfs_unbusy(mp);
4613 	if (error != 0)
4614 		return (error);
4615 
4616 	error = falloc_noinstall(td, &fp);
4617 	if (error != 0) {
4618 		vput(vp);
4619 		return (error);
4620 	}
4621 	/*
4622 	 * An extra reference on `fp' has been held for us by
4623 	 * falloc_noinstall().
4624 	 */
4625 
4626 #ifdef INVARIANTS
4627 	td->td_dupfd = -1;
4628 #endif
4629 	error = vn_open_vnode(vp, fmode, td->td_ucred, td, fp);
4630 	if (error != 0) {
4631 		KASSERT(fp->f_ops == &badfileops,
4632 		    ("VOP_OPEN in fhopen() set f_ops"));
4633 		KASSERT(td->td_dupfd < 0,
4634 		    ("fhopen() encountered fdopen()"));
4635 
4636 		vput(vp);
4637 		goto bad;
4638 	}
4639 #ifdef INVARIANTS
4640 	td->td_dupfd = 0;
4641 #endif
4642 	fp->f_vnode = vp;
4643 	finit_vnode(fp, fmode, NULL, &vnops);
4644 	VOP_UNLOCK(vp);
4645 	if ((fmode & O_TRUNC) != 0) {
4646 		error = fo_truncate(fp, 0, td->td_ucred, td);
4647 		if (error != 0)
4648 			goto bad;
4649 	}
4650 
4651 	error = finstall(td, fp, &indx, fmode, NULL);
4652 bad:
4653 	fdrop(fp, td);
4654 	td->td_retval[0] = indx;
4655 	return (error);
4656 }
4657 
4658 /*
4659  * Stat an (NFS) file handle.
4660  */
4661 #ifndef _SYS_SYSPROTO_H_
4662 struct fhstat_args {
4663 	struct fhandle *u_fhp;
4664 	struct stat *sb;
4665 };
4666 #endif
4667 int
4668 sys_fhstat(struct thread *td, struct fhstat_args *uap)
4669 {
4670 	struct stat sb;
4671 	struct fhandle fh;
4672 	int error;
4673 
4674 	error = copyin(uap->u_fhp, &fh, sizeof(fh));
4675 	if (error != 0)
4676 		return (error);
4677 	error = kern_fhstat(td, fh, &sb);
4678 	if (error == 0)
4679 		error = copyout(&sb, uap->sb, sizeof(sb));
4680 	return (error);
4681 }
4682 
4683 int
4684 kern_fhstat(struct thread *td, struct fhandle fh, struct stat *sb)
4685 {
4686 	struct mount *mp;
4687 	struct vnode *vp;
4688 	int error;
4689 
4690 	error = priv_check(td, PRIV_VFS_FHSTAT);
4691 	if (error != 0)
4692 		return (error);
4693 	if ((mp = vfs_busyfs(&fh.fh_fsid)) == NULL)
4694 		return (ESTALE);
4695 	error = VFS_FHTOVP(mp, &fh.fh_fid, LK_EXCLUSIVE, &vp);
4696 	vfs_unbusy(mp);
4697 	if (error != 0)
4698 		return (error);
4699 	error = VOP_STAT(vp, sb, td->td_ucred, NOCRED);
4700 	vput(vp);
4701 	return (error);
4702 }
4703 
4704 /*
4705  * Implement fstatfs() for (NFS) file handles.
4706  */
4707 #ifndef _SYS_SYSPROTO_H_
4708 struct fhstatfs_args {
4709 	struct fhandle *u_fhp;
4710 	struct statfs *buf;
4711 };
4712 #endif
4713 int
4714 sys_fhstatfs(struct thread *td, struct fhstatfs_args *uap)
4715 {
4716 	struct statfs *sfp;
4717 	fhandle_t fh;
4718 	int error;
4719 
4720 	error = copyin(uap->u_fhp, &fh, sizeof(fhandle_t));
4721 	if (error != 0)
4722 		return (error);
4723 	sfp = malloc(sizeof(struct statfs), M_STATFS, M_WAITOK);
4724 	error = kern_fhstatfs(td, fh, sfp);
4725 	if (error == 0)
4726 		error = copyout(sfp, uap->buf, sizeof(*sfp));
4727 	free(sfp, M_STATFS);
4728 	return (error);
4729 }
4730 
4731 int
4732 kern_fhstatfs(struct thread *td, fhandle_t fh, struct statfs *buf)
4733 {
4734 	struct mount *mp;
4735 	struct vnode *vp;
4736 	int error;
4737 
4738 	error = priv_check(td, PRIV_VFS_FHSTATFS);
4739 	if (error != 0)
4740 		return (error);
4741 	if ((mp = vfs_busyfs(&fh.fh_fsid)) == NULL)
4742 		return (ESTALE);
4743 	error = VFS_FHTOVP(mp, &fh.fh_fid, LK_EXCLUSIVE, &vp);
4744 	if (error != 0) {
4745 		vfs_unbusy(mp);
4746 		return (error);
4747 	}
4748 	vput(vp);
4749 	error = prison_canseemount(td->td_ucred, mp);
4750 	if (error != 0)
4751 		goto out;
4752 #ifdef MAC
4753 	error = mac_mount_check_stat(td->td_ucred, mp);
4754 	if (error != 0)
4755 		goto out;
4756 #endif
4757 	error = VFS_STATFS(mp, buf);
4758 out:
4759 	vfs_unbusy(mp);
4760 	return (error);
4761 }
4762 
4763 /*
4764  * Unlike madvise(2), we do not make a best effort to remember every
4765  * possible caching hint.  Instead, we remember the last setting with
4766  * the exception that we will allow POSIX_FADV_NORMAL to adjust the
4767  * region of any current setting.
4768  */
4769 int
4770 kern_posix_fadvise(struct thread *td, int fd, off_t offset, off_t len,
4771     int advice)
4772 {
4773 	struct fadvise_info *fa, *new;
4774 	struct file *fp;
4775 	struct vnode *vp;
4776 	off_t end;
4777 	int error;
4778 
4779 	if (offset < 0 || len < 0 || offset > OFF_MAX - len)
4780 		return (EINVAL);
4781 	AUDIT_ARG_VALUE(advice);
4782 	switch (advice) {
4783 	case POSIX_FADV_SEQUENTIAL:
4784 	case POSIX_FADV_RANDOM:
4785 	case POSIX_FADV_NOREUSE:
4786 		new = malloc(sizeof(*fa), M_FADVISE, M_WAITOK);
4787 		break;
4788 	case POSIX_FADV_NORMAL:
4789 	case POSIX_FADV_WILLNEED:
4790 	case POSIX_FADV_DONTNEED:
4791 		new = NULL;
4792 		break;
4793 	default:
4794 		return (EINVAL);
4795 	}
4796 	/* XXX: CAP_POSIX_FADVISE? */
4797 	AUDIT_ARG_FD(fd);
4798 	error = fget(td, fd, &cap_no_rights, &fp);
4799 	if (error != 0)
4800 		goto out;
4801 	AUDIT_ARG_FILE(td->td_proc, fp);
4802 	if ((fp->f_ops->fo_flags & DFLAG_SEEKABLE) == 0) {
4803 		error = ESPIPE;
4804 		goto out;
4805 	}
4806 	if (fp->f_type != DTYPE_VNODE) {
4807 		error = ENODEV;
4808 		goto out;
4809 	}
4810 	vp = fp->f_vnode;
4811 	if (vp->v_type != VREG) {
4812 		error = ENODEV;
4813 		goto out;
4814 	}
4815 	if (len == 0)
4816 		end = OFF_MAX;
4817 	else
4818 		end = offset + len - 1;
4819 	switch (advice) {
4820 	case POSIX_FADV_SEQUENTIAL:
4821 	case POSIX_FADV_RANDOM:
4822 	case POSIX_FADV_NOREUSE:
4823 		/*
4824 		 * Try to merge any existing non-standard region with
4825 		 * this new region if possible, otherwise create a new
4826 		 * non-standard region for this request.
4827 		 */
4828 		mtx_pool_lock(mtxpool_sleep, fp);
4829 		fa = fp->f_advice;
4830 		if (fa != NULL && fa->fa_advice == advice &&
4831 		    ((fa->fa_start <= end && fa->fa_end >= offset) ||
4832 		    (end != OFF_MAX && fa->fa_start == end + 1) ||
4833 		    (fa->fa_end != OFF_MAX && fa->fa_end + 1 == offset))) {
4834 			if (offset < fa->fa_start)
4835 				fa->fa_start = offset;
4836 			if (end > fa->fa_end)
4837 				fa->fa_end = end;
4838 		} else {
4839 			new->fa_advice = advice;
4840 			new->fa_start = offset;
4841 			new->fa_end = end;
4842 			fp->f_advice = new;
4843 			new = fa;
4844 		}
4845 		mtx_pool_unlock(mtxpool_sleep, fp);
4846 		break;
4847 	case POSIX_FADV_NORMAL:
4848 		/*
4849 		 * If a the "normal" region overlaps with an existing
4850 		 * non-standard region, trim or remove the
4851 		 * non-standard region.
4852 		 */
4853 		mtx_pool_lock(mtxpool_sleep, fp);
4854 		fa = fp->f_advice;
4855 		if (fa != NULL) {
4856 			if (offset <= fa->fa_start && end >= fa->fa_end) {
4857 				new = fa;
4858 				fp->f_advice = NULL;
4859 			} else if (offset <= fa->fa_start &&
4860 			    end >= fa->fa_start)
4861 				fa->fa_start = end + 1;
4862 			else if (offset <= fa->fa_end && end >= fa->fa_end)
4863 				fa->fa_end = offset - 1;
4864 			else if (offset >= fa->fa_start && end <= fa->fa_end) {
4865 				/*
4866 				 * If the "normal" region is a middle
4867 				 * portion of the existing
4868 				 * non-standard region, just remove
4869 				 * the whole thing rather than picking
4870 				 * one side or the other to
4871 				 * preserve.
4872 				 */
4873 				new = fa;
4874 				fp->f_advice = NULL;
4875 			}
4876 		}
4877 		mtx_pool_unlock(mtxpool_sleep, fp);
4878 		break;
4879 	case POSIX_FADV_WILLNEED:
4880 	case POSIX_FADV_DONTNEED:
4881 		error = VOP_ADVISE(vp, offset, end, advice);
4882 		break;
4883 	}
4884 out:
4885 	if (fp != NULL)
4886 		fdrop(fp, td);
4887 	free(new, M_FADVISE);
4888 	return (error);
4889 }
4890 
4891 int
4892 sys_posix_fadvise(struct thread *td, struct posix_fadvise_args *uap)
4893 {
4894 	int error;
4895 
4896 	error = kern_posix_fadvise(td, uap->fd, uap->offset, uap->len,
4897 	    uap->advice);
4898 	return (kern_posix_error(td, error));
4899 }
4900 
4901 int
4902 kern_copy_file_range(struct thread *td, int infd, off_t *inoffp, int outfd,
4903     off_t *outoffp, size_t len, unsigned int flags)
4904 {
4905 	struct file *infp, *outfp;
4906 	struct vnode *invp, *outvp;
4907 	int error;
4908 	size_t retlen;
4909 	void *rl_rcookie, *rl_wcookie;
4910 	off_t savinoff, savoutoff;
4911 
4912 	infp = outfp = NULL;
4913 	rl_rcookie = rl_wcookie = NULL;
4914 	savinoff = -1;
4915 	error = 0;
4916 	retlen = 0;
4917 
4918 	if (flags != 0) {
4919 		error = EINVAL;
4920 		goto out;
4921 	}
4922 	if (len > SSIZE_MAX)
4923 		/*
4924 		 * Although the len argument is size_t, the return argument
4925 		 * is ssize_t (which is signed).  Therefore a size that won't
4926 		 * fit in ssize_t can't be returned.
4927 		 */
4928 		len = SSIZE_MAX;
4929 
4930 	/* Get the file structures for the file descriptors. */
4931 	error = fget_read(td, infd,
4932 	    inoffp != NULL ? &cap_pread_rights : &cap_read_rights, &infp);
4933 	if (error != 0)
4934 		goto out;
4935 	if (infp->f_ops == &badfileops) {
4936 		error = EBADF;
4937 		goto out;
4938 	}
4939 	if (infp->f_vnode == NULL) {
4940 		error = EINVAL;
4941 		goto out;
4942 	}
4943 	error = fget_write(td, outfd,
4944 	    outoffp != NULL ? &cap_pwrite_rights : &cap_write_rights, &outfp);
4945 	if (error != 0)
4946 		goto out;
4947 	if (outfp->f_ops == &badfileops) {
4948 		error = EBADF;
4949 		goto out;
4950 	}
4951 	if (outfp->f_vnode == NULL) {
4952 		error = EINVAL;
4953 		goto out;
4954 	}
4955 
4956 	/* Set the offset pointers to the correct place. */
4957 	if (inoffp == NULL)
4958 		inoffp = &infp->f_offset;
4959 	if (outoffp == NULL)
4960 		outoffp = &outfp->f_offset;
4961 	savinoff = *inoffp;
4962 	savoutoff = *outoffp;
4963 
4964 	invp = infp->f_vnode;
4965 	outvp = outfp->f_vnode;
4966 	/* Sanity check the f_flag bits. */
4967 	if ((outfp->f_flag & (FWRITE | FAPPEND)) != FWRITE ||
4968 	    (infp->f_flag & FREAD) == 0) {
4969 		error = EBADF;
4970 		goto out;
4971 	}
4972 
4973 	/* If len == 0, just return 0. */
4974 	if (len == 0)
4975 		goto out;
4976 
4977 	/*
4978 	 * If infp and outfp refer to the same file, the byte ranges cannot
4979 	 * overlap.
4980 	 */
4981 	if (invp == outvp) {
4982 		if ((savinoff <= savoutoff && savinoff + len > savoutoff) ||
4983 		    (savinoff > savoutoff && savoutoff + len > savinoff)) {
4984 			error = EINVAL;
4985 			goto out;
4986 		}
4987 		rangelock_may_recurse(&invp->v_rl);
4988 	}
4989 
4990 	/* Range lock the byte ranges for both invp and outvp. */
4991 	for (;;) {
4992 		rl_wcookie = vn_rangelock_wlock(outvp, *outoffp, *outoffp +
4993 		    len);
4994 		rl_rcookie = vn_rangelock_tryrlock(invp, *inoffp, *inoffp +
4995 		    len);
4996 		if (rl_rcookie != NULL)
4997 			break;
4998 		vn_rangelock_unlock(outvp, rl_wcookie);
4999 		rl_rcookie = vn_rangelock_rlock(invp, *inoffp, *inoffp + len);
5000 		vn_rangelock_unlock(invp, rl_rcookie);
5001 	}
5002 
5003 	retlen = len;
5004 	error = vn_copy_file_range(invp, inoffp, outvp, outoffp, &retlen,
5005 	    flags, infp->f_cred, outfp->f_cred, td);
5006 out:
5007 	if (rl_rcookie != NULL)
5008 		vn_rangelock_unlock(invp, rl_rcookie);
5009 	if (rl_wcookie != NULL)
5010 		vn_rangelock_unlock(outvp, rl_wcookie);
5011 	if (savinoff != -1 && (error == EINTR || error == ERESTART)) {
5012 		*inoffp = savinoff;
5013 		*outoffp = savoutoff;
5014 	}
5015 	if (outfp != NULL)
5016 		fdrop(outfp, td);
5017 	if (infp != NULL)
5018 		fdrop(infp, td);
5019 	td->td_retval[0] = retlen;
5020 	return (error);
5021 }
5022 
5023 int
5024 sys_copy_file_range(struct thread *td, struct copy_file_range_args *uap)
5025 {
5026 	off_t inoff, outoff, *inoffp, *outoffp;
5027 	int error;
5028 
5029 	inoffp = outoffp = NULL;
5030 	if (uap->inoffp != NULL) {
5031 		error = copyin(uap->inoffp, &inoff, sizeof(off_t));
5032 		if (error != 0)
5033 			return (error);
5034 		inoffp = &inoff;
5035 	}
5036 	if (uap->outoffp != NULL) {
5037 		error = copyin(uap->outoffp, &outoff, sizeof(off_t));
5038 		if (error != 0)
5039 			return (error);
5040 		outoffp = &outoff;
5041 	}
5042 	error = kern_copy_file_range(td, uap->infd, inoffp, uap->outfd,
5043 	    outoffp, uap->len, uap->flags);
5044 	if (error == 0 && uap->inoffp != NULL)
5045 		error = copyout(inoffp, uap->inoffp, sizeof(off_t));
5046 	if (error == 0 && uap->outoffp != NULL)
5047 		error = copyout(outoffp, uap->outoffp, sizeof(off_t));
5048 	return (error);
5049 }
5050