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