xref: /freebsd/sys/kern/vfs_syscalls.c (revision 069ac184)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #include <sys/cdefs.h>
38 #include "opt_capsicum.h"
39 #include "opt_ktrace.h"
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #ifdef COMPAT_FREEBSD11
44 #include <sys/abi_compat.h>
45 #endif
46 #include <sys/bio.h>
47 #include <sys/buf.h>
48 #include <sys/capsicum.h>
49 #include <sys/disk.h>
50 #include <sys/malloc.h>
51 #include <sys/mount.h>
52 #include <sys/mutex.h>
53 #include <sys/sysproto.h>
54 #include <sys/namei.h>
55 #include <sys/filedesc.h>
56 #include <sys/kernel.h>
57 #include <sys/fcntl.h>
58 #include <sys/file.h>
59 #include <sys/filio.h>
60 #include <sys/limits.h>
61 #include <sys/linker.h>
62 #include <sys/rwlock.h>
63 #include <sys/sdt.h>
64 #include <sys/stat.h>
65 #include <sys/sx.h>
66 #include <sys/unistd.h>
67 #include <sys/vnode.h>
68 #include <sys/priv.h>
69 #include <sys/proc.h>
70 #include <sys/dirent.h>
71 #include <sys/jail.h>
72 #include <sys/syscallsubr.h>
73 #include <sys/sysctl.h>
74 #ifdef KTRACE
75 #include <sys/ktrace.h>
76 #endif
77 
78 #include <machine/stdarg.h>
79 
80 #include <security/audit/audit.h>
81 #include <security/mac/mac_framework.h>
82 
83 #include <vm/vm.h>
84 #include <vm/vm_object.h>
85 #include <vm/vm_page.h>
86 #include <vm/uma.h>
87 
88 #include <fs/devfs/devfs.h>
89 
90 MALLOC_DEFINE(M_FADVISE, "fadvise", "posix_fadvise(2) information");
91 
92 static int kern_chflagsat(struct thread *td, int fd, const char *path,
93     enum uio_seg pathseg, u_long flags, int atflag);
94 static int setfflags(struct thread *td, struct vnode *, u_long);
95 static int getutimes(const struct timeval *, enum uio_seg, struct timespec *);
96 static int getutimens(const struct timespec *, enum uio_seg,
97     struct timespec *, int *);
98 static int setutimes(struct thread *td, struct vnode *,
99     const struct timespec *, int, int);
100 static int vn_access(struct vnode *vp, int user_flags, struct ucred *cred,
101     struct thread *td);
102 static int kern_fhlinkat(struct thread *td, int fd, const char *path,
103     enum uio_seg pathseg, fhandle_t *fhp);
104 static int kern_readlink_vp(struct vnode *vp, char *buf, enum uio_seg bufseg,
105     size_t count, struct thread *td);
106 static int kern_linkat_vp(struct thread *td, struct vnode *vp, int fd,
107     const char *path, enum uio_seg segflag);
108 
109 uint64_t
110 at2cnpflags(u_int at_flags, u_int mask)
111 {
112 	uint64_t res;
113 
114 	MPASS((at_flags & (AT_SYMLINK_FOLLOW | AT_SYMLINK_NOFOLLOW)) !=
115 	    (AT_SYMLINK_FOLLOW | AT_SYMLINK_NOFOLLOW));
116 
117 	res = 0;
118 	at_flags &= mask;
119 	if ((at_flags & AT_RESOLVE_BENEATH) != 0)
120 		res |= RBENEATH;
121 	if ((at_flags & AT_SYMLINK_FOLLOW) != 0)
122 		res |= FOLLOW;
123 	/* NOFOLLOW is pseudo flag */
124 	if ((mask & AT_SYMLINK_NOFOLLOW) != 0) {
125 		res |= (at_flags & AT_SYMLINK_NOFOLLOW) != 0 ? NOFOLLOW :
126 		    FOLLOW;
127 	}
128 	if ((mask & AT_EMPTY_PATH) != 0 && (at_flags & AT_EMPTY_PATH) != 0)
129 		res |= EMPTYPATH;
130 	return (res);
131 }
132 
133 int
134 kern_sync(struct thread *td)
135 {
136 	struct mount *mp, *nmp;
137 	int save;
138 
139 	mtx_lock(&mountlist_mtx);
140 	for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
141 		if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK)) {
142 			nmp = TAILQ_NEXT(mp, mnt_list);
143 			continue;
144 		}
145 		if ((mp->mnt_flag & MNT_RDONLY) == 0 &&
146 		    vn_start_write(NULL, &mp, V_NOWAIT) == 0) {
147 			save = curthread_pflags_set(TDP_SYNCIO);
148 			vfs_periodic(mp, MNT_NOWAIT);
149 			VFS_SYNC(mp, MNT_NOWAIT);
150 			curthread_pflags_restore(save);
151 			vn_finished_write(mp);
152 		}
153 		mtx_lock(&mountlist_mtx);
154 		nmp = TAILQ_NEXT(mp, mnt_list);
155 		vfs_unbusy(mp);
156 	}
157 	mtx_unlock(&mountlist_mtx);
158 	return (0);
159 }
160 
161 /*
162  * Sync each mounted filesystem.
163  */
164 #ifndef _SYS_SYSPROTO_H_
165 struct sync_args {
166 	int     dummy;
167 };
168 #endif
169 /* ARGSUSED */
170 int
171 sys_sync(struct thread *td, struct sync_args *uap)
172 {
173 
174 	return (kern_sync(td));
175 }
176 
177 /*
178  * Change filesystem quotas.
179  */
180 #ifndef _SYS_SYSPROTO_H_
181 struct quotactl_args {
182 	char *path;
183 	int cmd;
184 	int uid;
185 	caddr_t arg;
186 };
187 #endif
188 int
189 sys_quotactl(struct thread *td, struct quotactl_args *uap)
190 {
191 	struct mount *mp;
192 	struct nameidata nd;
193 	int error;
194 	bool mp_busy;
195 
196 	AUDIT_ARG_CMD(uap->cmd);
197 	AUDIT_ARG_UID(uap->uid);
198 	if (!prison_allow(td->td_ucred, PR_ALLOW_QUOTAS))
199 		return (EPERM);
200 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1, UIO_USERSPACE,
201 	    uap->path);
202 	if ((error = namei(&nd)) != 0)
203 		return (error);
204 	NDFREE_PNBUF(&nd);
205 	mp = nd.ni_vp->v_mount;
206 	vfs_ref(mp);
207 	vput(nd.ni_vp);
208 	error = vfs_busy(mp, 0);
209 	if (error != 0) {
210 		vfs_rel(mp);
211 		return (error);
212 	}
213 	mp_busy = true;
214 	error = VFS_QUOTACTL(mp, uap->cmd, uap->uid, uap->arg, &mp_busy);
215 
216 	/*
217 	 * Since quota on/off operations typically need to open quota
218 	 * files, the implementation may need to unbusy the mount point
219 	 * before calling into namei.  Otherwise, unmount might be
220 	 * started between two vfs_busy() invocations (first is ours,
221 	 * second is from mount point cross-walk code in lookup()),
222 	 * causing deadlock.
223 	 *
224 	 * Avoid unbusying mp if the implementation indicates it has
225 	 * already done so.
226 	 */
227 	if (mp_busy)
228 		vfs_unbusy(mp);
229 	vfs_rel(mp);
230 	return (error);
231 }
232 
233 /*
234  * Used by statfs conversion routines to scale the block size up if
235  * necessary so that all of the block counts are <= 'max_size'.  Note
236  * that 'max_size' should be a bitmask, i.e. 2^n - 1 for some non-zero
237  * value of 'n'.
238  */
239 void
240 statfs_scale_blocks(struct statfs *sf, long max_size)
241 {
242 	uint64_t count;
243 	int shift;
244 
245 	KASSERT(powerof2(max_size + 1), ("%s: invalid max_size", __func__));
246 
247 	/*
248 	 * Attempt to scale the block counts to give a more accurate
249 	 * overview to userland of the ratio of free space to used
250 	 * space.  To do this, find the largest block count and compute
251 	 * a divisor that lets it fit into a signed integer <= max_size.
252 	 */
253 	if (sf->f_bavail < 0)
254 		count = -sf->f_bavail;
255 	else
256 		count = sf->f_bavail;
257 	count = MAX(sf->f_blocks, MAX(sf->f_bfree, count));
258 	if (count <= max_size)
259 		return;
260 
261 	count >>= flsl(max_size);
262 	shift = 0;
263 	while (count > 0) {
264 		shift++;
265 		count >>=1;
266 	}
267 
268 	sf->f_bsize <<= shift;
269 	sf->f_blocks >>= shift;
270 	sf->f_bfree >>= shift;
271 	sf->f_bavail >>= shift;
272 }
273 
274 static int
275 kern_do_statfs(struct thread *td, struct mount *mp, struct statfs *buf)
276 {
277 	int error;
278 
279 	if (mp == NULL)
280 		return (EBADF);
281 	error = vfs_busy(mp, 0);
282 	vfs_rel(mp);
283 	if (error != 0)
284 		return (error);
285 #ifdef MAC
286 	error = mac_mount_check_stat(td->td_ucred, mp);
287 	if (error != 0)
288 		goto out;
289 #endif
290 	error = VFS_STATFS(mp, buf);
291 	if (error != 0)
292 		goto out;
293 	if (priv_check_cred_vfs_generation(td->td_ucred)) {
294 		buf->f_fsid.val[0] = buf->f_fsid.val[1] = 0;
295 		prison_enforce_statfs(td->td_ucred, mp, buf);
296 	}
297 out:
298 	vfs_unbusy(mp);
299 	return (error);
300 }
301 
302 /*
303  * Get filesystem statistics.
304  */
305 #ifndef _SYS_SYSPROTO_H_
306 struct statfs_args {
307 	char *path;
308 	struct statfs *buf;
309 };
310 #endif
311 int
312 sys_statfs(struct thread *td, struct statfs_args *uap)
313 {
314 	struct statfs *sfp;
315 	int error;
316 
317 	sfp = malloc(sizeof(struct statfs), M_STATFS, M_WAITOK);
318 	error = kern_statfs(td, uap->path, UIO_USERSPACE, sfp);
319 	if (error == 0)
320 		error = copyout(sfp, uap->buf, sizeof(struct statfs));
321 	free(sfp, M_STATFS);
322 	return (error);
323 }
324 
325 int
326 kern_statfs(struct thread *td, const char *path, enum uio_seg pathseg,
327     struct statfs *buf)
328 {
329 	struct mount *mp;
330 	struct nameidata nd;
331 	int error;
332 
333 	NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, pathseg, path);
334 	error = namei(&nd);
335 	if (error != 0)
336 		return (error);
337 	NDFREE_PNBUF(&nd);
338 	mp = vfs_ref_from_vp(nd.ni_vp);
339 	vrele(nd.ni_vp);
340 	return (kern_do_statfs(td, mp, buf));
341 }
342 
343 /*
344  * Get filesystem statistics.
345  */
346 #ifndef _SYS_SYSPROTO_H_
347 struct fstatfs_args {
348 	int fd;
349 	struct statfs *buf;
350 };
351 #endif
352 int
353 sys_fstatfs(struct thread *td, struct fstatfs_args *uap)
354 {
355 	struct statfs *sfp;
356 	int error;
357 
358 	sfp = malloc(sizeof(struct statfs), M_STATFS, M_WAITOK);
359 	error = kern_fstatfs(td, uap->fd, sfp);
360 	if (error == 0)
361 		error = copyout(sfp, uap->buf, sizeof(struct statfs));
362 	free(sfp, M_STATFS);
363 	return (error);
364 }
365 
366 int
367 kern_fstatfs(struct thread *td, int fd, struct statfs *buf)
368 {
369 	struct file *fp;
370 	struct mount *mp;
371 	struct vnode *vp;
372 	int error;
373 
374 	AUDIT_ARG_FD(fd);
375 	error = getvnode_path(td, fd, &cap_fstatfs_rights, &fp);
376 	if (error != 0)
377 		return (error);
378 	vp = fp->f_vnode;
379 #ifdef AUDIT
380 	if (AUDITING_TD(td)) {
381 		vn_lock(vp, LK_SHARED | LK_RETRY);
382 		AUDIT_ARG_VNODE1(vp);
383 		VOP_UNLOCK(vp);
384 	}
385 #endif
386 	mp = vfs_ref_from_vp(vp);
387 	fdrop(fp, td);
388 	return (kern_do_statfs(td, mp, buf));
389 }
390 
391 /*
392  * Get statistics on all filesystems.
393  */
394 #ifndef _SYS_SYSPROTO_H_
395 struct getfsstat_args {
396 	struct statfs *buf;
397 	long bufsize;
398 	int mode;
399 };
400 #endif
401 int
402 sys_getfsstat(struct thread *td, struct getfsstat_args *uap)
403 {
404 	size_t count;
405 	int error;
406 
407 	if (uap->bufsize < 0 || uap->bufsize > SIZE_MAX)
408 		return (EINVAL);
409 	error = kern_getfsstat(td, &uap->buf, uap->bufsize, &count,
410 	    UIO_USERSPACE, uap->mode);
411 	if (error == 0)
412 		td->td_retval[0] = count;
413 	return (error);
414 }
415 
416 /*
417  * If (bufsize > 0 && bufseg == UIO_SYSSPACE)
418  *	The caller is responsible for freeing memory which will be allocated
419  *	in '*buf'.
420  */
421 int
422 kern_getfsstat(struct thread *td, struct statfs **buf, size_t bufsize,
423     size_t *countp, enum uio_seg bufseg, int mode)
424 {
425 	struct mount *mp, *nmp;
426 	struct statfs *sfsp, *sp, *sptmp, *tofree;
427 	size_t count, maxcount;
428 	int error;
429 
430 	switch (mode) {
431 	case MNT_WAIT:
432 	case MNT_NOWAIT:
433 		break;
434 	default:
435 		if (bufseg == UIO_SYSSPACE)
436 			*buf = NULL;
437 		return (EINVAL);
438 	}
439 restart:
440 	maxcount = bufsize / sizeof(struct statfs);
441 	if (bufsize == 0) {
442 		sfsp = NULL;
443 		tofree = NULL;
444 	} else if (bufseg == UIO_USERSPACE) {
445 		sfsp = *buf;
446 		tofree = NULL;
447 	} else /* if (bufseg == UIO_SYSSPACE) */ {
448 		count = 0;
449 		mtx_lock(&mountlist_mtx);
450 		TAILQ_FOREACH(mp, &mountlist, mnt_list) {
451 			count++;
452 		}
453 		mtx_unlock(&mountlist_mtx);
454 		if (maxcount > count)
455 			maxcount = count;
456 		tofree = sfsp = *buf = malloc(maxcount * sizeof(struct statfs),
457 		    M_STATFS, M_WAITOK);
458 	}
459 
460 	count = 0;
461 
462 	/*
463 	 * If there is no target buffer they only want the count.
464 	 *
465 	 * This could be TAILQ_FOREACH but it is open-coded to match the original
466 	 * code below.
467 	 */
468 	if (sfsp == NULL) {
469 		mtx_lock(&mountlist_mtx);
470 		for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
471 			if (prison_canseemount(td->td_ucred, mp) != 0) {
472 				nmp = TAILQ_NEXT(mp, mnt_list);
473 				continue;
474 			}
475 #ifdef MAC
476 			if (mac_mount_check_stat(td->td_ucred, mp) != 0) {
477 				nmp = TAILQ_NEXT(mp, mnt_list);
478 				continue;
479 			}
480 #endif
481 			count++;
482 			nmp = TAILQ_NEXT(mp, mnt_list);
483 		}
484 		mtx_unlock(&mountlist_mtx);
485 		*countp = count;
486 		return (0);
487 	}
488 
489 	/*
490 	 * They want the entire thing.
491 	 *
492 	 * Short-circuit the corner case of no room for anything, avoids
493 	 * relocking below.
494 	 */
495 	if (maxcount < 1) {
496 		goto out;
497 	}
498 
499 	mtx_lock(&mountlist_mtx);
500 	for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
501 		if (prison_canseemount(td->td_ucred, mp) != 0) {
502 			nmp = TAILQ_NEXT(mp, mnt_list);
503 			continue;
504 		}
505 #ifdef MAC
506 		if (mac_mount_check_stat(td->td_ucred, mp) != 0) {
507 			nmp = TAILQ_NEXT(mp, mnt_list);
508 			continue;
509 		}
510 #endif
511 		if (mode == MNT_WAIT) {
512 			if (vfs_busy(mp, MBF_MNTLSTLOCK) != 0) {
513 				/*
514 				 * If vfs_busy() failed, and MBF_NOWAIT
515 				 * wasn't passed, then the mp is gone.
516 				 * Furthermore, because of MBF_MNTLSTLOCK,
517 				 * the mountlist_mtx was dropped.  We have
518 				 * no other choice than to start over.
519 				 */
520 				mtx_unlock(&mountlist_mtx);
521 				free(tofree, M_STATFS);
522 				goto restart;
523 			}
524 		} else {
525 			if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK) != 0) {
526 				nmp = TAILQ_NEXT(mp, mnt_list);
527 				continue;
528 			}
529 		}
530 		sp = &mp->mnt_stat;
531 		/*
532 		 * If MNT_NOWAIT is specified, do not refresh
533 		 * the fsstat cache.
534 		 */
535 		if (mode != MNT_NOWAIT) {
536 			error = VFS_STATFS(mp, sp);
537 			if (error != 0) {
538 				mtx_lock(&mountlist_mtx);
539 				nmp = TAILQ_NEXT(mp, mnt_list);
540 				vfs_unbusy(mp);
541 				continue;
542 			}
543 		}
544 		if (priv_check_cred_vfs_generation(td->td_ucred)) {
545 			sptmp = malloc(sizeof(struct statfs), M_STATFS,
546 			    M_WAITOK);
547 			*sptmp = *sp;
548 			sptmp->f_fsid.val[0] = sptmp->f_fsid.val[1] = 0;
549 			prison_enforce_statfs(td->td_ucred, mp, sptmp);
550 			sp = sptmp;
551 		} else
552 			sptmp = NULL;
553 		if (bufseg == UIO_SYSSPACE) {
554 			bcopy(sp, sfsp, sizeof(*sp));
555 			free(sptmp, M_STATFS);
556 		} else /* if (bufseg == UIO_USERSPACE) */ {
557 			error = copyout(sp, sfsp, sizeof(*sp));
558 			free(sptmp, M_STATFS);
559 			if (error != 0) {
560 				vfs_unbusy(mp);
561 				return (error);
562 			}
563 		}
564 		sfsp++;
565 		count++;
566 
567 		if (count == maxcount) {
568 			vfs_unbusy(mp);
569 			goto out;
570 		}
571 
572 		mtx_lock(&mountlist_mtx);
573 		nmp = TAILQ_NEXT(mp, mnt_list);
574 		vfs_unbusy(mp);
575 	}
576 	mtx_unlock(&mountlist_mtx);
577 out:
578 	*countp = count;
579 	return (0);
580 }
581 
582 #ifdef COMPAT_FREEBSD4
583 /*
584  * Get old format filesystem statistics.
585  */
586 static void freebsd4_cvtstatfs(struct statfs *, struct ostatfs *);
587 
588 #ifndef _SYS_SYSPROTO_H_
589 struct freebsd4_statfs_args {
590 	char *path;
591 	struct ostatfs *buf;
592 };
593 #endif
594 int
595 freebsd4_statfs(struct thread *td, struct freebsd4_statfs_args *uap)
596 {
597 	struct ostatfs osb;
598 	struct statfs *sfp;
599 	int error;
600 
601 	sfp = malloc(sizeof(struct statfs), M_STATFS, M_WAITOK);
602 	error = kern_statfs(td, uap->path, UIO_USERSPACE, sfp);
603 	if (error == 0) {
604 		freebsd4_cvtstatfs(sfp, &osb);
605 		error = copyout(&osb, uap->buf, sizeof(osb));
606 	}
607 	free(sfp, M_STATFS);
608 	return (error);
609 }
610 
611 /*
612  * Get filesystem statistics.
613  */
614 #ifndef _SYS_SYSPROTO_H_
615 struct freebsd4_fstatfs_args {
616 	int fd;
617 	struct ostatfs *buf;
618 };
619 #endif
620 int
621 freebsd4_fstatfs(struct thread *td, struct freebsd4_fstatfs_args *uap)
622 {
623 	struct ostatfs osb;
624 	struct statfs *sfp;
625 	int error;
626 
627 	sfp = malloc(sizeof(struct statfs), M_STATFS, M_WAITOK);
628 	error = kern_fstatfs(td, uap->fd, sfp);
629 	if (error == 0) {
630 		freebsd4_cvtstatfs(sfp, &osb);
631 		error = copyout(&osb, uap->buf, sizeof(osb));
632 	}
633 	free(sfp, M_STATFS);
634 	return (error);
635 }
636 
637 /*
638  * Get statistics on all filesystems.
639  */
640 #ifndef _SYS_SYSPROTO_H_
641 struct freebsd4_getfsstat_args {
642 	struct ostatfs *buf;
643 	long bufsize;
644 	int mode;
645 };
646 #endif
647 int
648 freebsd4_getfsstat(struct thread *td, struct freebsd4_getfsstat_args *uap)
649 {
650 	struct statfs *buf, *sp;
651 	struct ostatfs osb;
652 	size_t count, size;
653 	int error;
654 
655 	if (uap->bufsize < 0)
656 		return (EINVAL);
657 	count = uap->bufsize / sizeof(struct ostatfs);
658 	if (count > SIZE_MAX / sizeof(struct statfs))
659 		return (EINVAL);
660 	size = count * sizeof(struct statfs);
661 	error = kern_getfsstat(td, &buf, size, &count, UIO_SYSSPACE,
662 	    uap->mode);
663 	if (error == 0)
664 		td->td_retval[0] = count;
665 	if (size != 0) {
666 		sp = buf;
667 		while (count != 0 && error == 0) {
668 			freebsd4_cvtstatfs(sp, &osb);
669 			error = copyout(&osb, uap->buf, sizeof(osb));
670 			sp++;
671 			uap->buf++;
672 			count--;
673 		}
674 		free(buf, M_STATFS);
675 	}
676 	return (error);
677 }
678 
679 /*
680  * Implement fstatfs() for (NFS) file handles.
681  */
682 #ifndef _SYS_SYSPROTO_H_
683 struct freebsd4_fhstatfs_args {
684 	struct fhandle *u_fhp;
685 	struct ostatfs *buf;
686 };
687 #endif
688 int
689 freebsd4_fhstatfs(struct thread *td, struct freebsd4_fhstatfs_args *uap)
690 {
691 	struct ostatfs osb;
692 	struct statfs *sfp;
693 	fhandle_t fh;
694 	int error;
695 
696 	error = copyin(uap->u_fhp, &fh, sizeof(fhandle_t));
697 	if (error != 0)
698 		return (error);
699 	sfp = malloc(sizeof(struct statfs), M_STATFS, M_WAITOK);
700 	error = kern_fhstatfs(td, fh, sfp);
701 	if (error == 0) {
702 		freebsd4_cvtstatfs(sfp, &osb);
703 		error = copyout(&osb, uap->buf, sizeof(osb));
704 	}
705 	free(sfp, M_STATFS);
706 	return (error);
707 }
708 
709 /*
710  * Convert a new format statfs structure to an old format statfs structure.
711  */
712 static void
713 freebsd4_cvtstatfs(struct statfs *nsp, struct ostatfs *osp)
714 {
715 
716 	statfs_scale_blocks(nsp, LONG_MAX);
717 	bzero(osp, sizeof(*osp));
718 	osp->f_bsize = nsp->f_bsize;
719 	osp->f_iosize = MIN(nsp->f_iosize, LONG_MAX);
720 	osp->f_blocks = nsp->f_blocks;
721 	osp->f_bfree = nsp->f_bfree;
722 	osp->f_bavail = nsp->f_bavail;
723 	osp->f_files = MIN(nsp->f_files, LONG_MAX);
724 	osp->f_ffree = MIN(nsp->f_ffree, LONG_MAX);
725 	osp->f_owner = nsp->f_owner;
726 	osp->f_type = nsp->f_type;
727 	osp->f_flags = nsp->f_flags;
728 	osp->f_syncwrites = MIN(nsp->f_syncwrites, LONG_MAX);
729 	osp->f_asyncwrites = MIN(nsp->f_asyncwrites, LONG_MAX);
730 	osp->f_syncreads = MIN(nsp->f_syncreads, LONG_MAX);
731 	osp->f_asyncreads = MIN(nsp->f_asyncreads, LONG_MAX);
732 	strlcpy(osp->f_fstypename, nsp->f_fstypename,
733 	    MIN(MFSNAMELEN, OMFSNAMELEN));
734 	strlcpy(osp->f_mntonname, nsp->f_mntonname,
735 	    MIN(MNAMELEN, OMNAMELEN));
736 	strlcpy(osp->f_mntfromname, nsp->f_mntfromname,
737 	    MIN(MNAMELEN, OMNAMELEN));
738 	osp->f_fsid = nsp->f_fsid;
739 }
740 #endif /* COMPAT_FREEBSD4 */
741 
742 #if defined(COMPAT_FREEBSD11)
743 /*
744  * Get old format filesystem statistics.
745  */
746 static void freebsd11_cvtstatfs(struct statfs *, struct freebsd11_statfs *);
747 
748 int
749 freebsd11_statfs(struct thread *td, struct freebsd11_statfs_args *uap)
750 {
751 	struct freebsd11_statfs osb;
752 	struct statfs *sfp;
753 	int error;
754 
755 	sfp = malloc(sizeof(struct statfs), M_STATFS, M_WAITOK);
756 	error = kern_statfs(td, uap->path, UIO_USERSPACE, sfp);
757 	if (error == 0) {
758 		freebsd11_cvtstatfs(sfp, &osb);
759 		error = copyout(&osb, uap->buf, sizeof(osb));
760 	}
761 	free(sfp, M_STATFS);
762 	return (error);
763 }
764 
765 /*
766  * Get filesystem statistics.
767  */
768 int
769 freebsd11_fstatfs(struct thread *td, struct freebsd11_fstatfs_args *uap)
770 {
771 	struct freebsd11_statfs osb;
772 	struct statfs *sfp;
773 	int error;
774 
775 	sfp = malloc(sizeof(struct statfs), M_STATFS, M_WAITOK);
776 	error = kern_fstatfs(td, uap->fd, sfp);
777 	if (error == 0) {
778 		freebsd11_cvtstatfs(sfp, &osb);
779 		error = copyout(&osb, uap->buf, sizeof(osb));
780 	}
781 	free(sfp, M_STATFS);
782 	return (error);
783 }
784 
785 /*
786  * Get statistics on all filesystems.
787  */
788 int
789 freebsd11_getfsstat(struct thread *td, struct freebsd11_getfsstat_args *uap)
790 {
791 	return (kern_freebsd11_getfsstat(td, uap->buf, uap->bufsize, uap->mode));
792 }
793 
794 int
795 kern_freebsd11_getfsstat(struct thread *td, struct freebsd11_statfs * ubuf,
796     long bufsize, int mode)
797 {
798 	struct freebsd11_statfs osb;
799 	struct statfs *buf, *sp;
800 	size_t count, size;
801 	int error;
802 
803 	if (bufsize < 0)
804 		return (EINVAL);
805 
806 	count = bufsize / sizeof(struct ostatfs);
807 	size = count * sizeof(struct statfs);
808 	error = kern_getfsstat(td, &buf, size, &count, UIO_SYSSPACE, mode);
809 	if (error == 0)
810 		td->td_retval[0] = count;
811 	if (size > 0) {
812 		sp = buf;
813 		while (count > 0 && error == 0) {
814 			freebsd11_cvtstatfs(sp, &osb);
815 			error = copyout(&osb, ubuf, sizeof(osb));
816 			sp++;
817 			ubuf++;
818 			count--;
819 		}
820 		free(buf, M_STATFS);
821 	}
822 	return (error);
823 }
824 
825 /*
826  * Implement fstatfs() for (NFS) file handles.
827  */
828 int
829 freebsd11_fhstatfs(struct thread *td, struct freebsd11_fhstatfs_args *uap)
830 {
831 	struct freebsd11_statfs osb;
832 	struct statfs *sfp;
833 	fhandle_t fh;
834 	int error;
835 
836 	error = copyin(uap->u_fhp, &fh, sizeof(fhandle_t));
837 	if (error)
838 		return (error);
839 	sfp = malloc(sizeof(struct statfs), M_STATFS, M_WAITOK);
840 	error = kern_fhstatfs(td, fh, sfp);
841 	if (error == 0) {
842 		freebsd11_cvtstatfs(sfp, &osb);
843 		error = copyout(&osb, uap->buf, sizeof(osb));
844 	}
845 	free(sfp, M_STATFS);
846 	return (error);
847 }
848 
849 /*
850  * Convert a new format statfs structure to an old format statfs structure.
851  */
852 static void
853 freebsd11_cvtstatfs(struct statfs *nsp, struct freebsd11_statfs *osp)
854 {
855 
856 	bzero(osp, sizeof(*osp));
857 	osp->f_version = FREEBSD11_STATFS_VERSION;
858 	osp->f_type = nsp->f_type;
859 	osp->f_flags = nsp->f_flags;
860 	osp->f_bsize = nsp->f_bsize;
861 	osp->f_iosize = nsp->f_iosize;
862 	osp->f_blocks = nsp->f_blocks;
863 	osp->f_bfree = nsp->f_bfree;
864 	osp->f_bavail = nsp->f_bavail;
865 	osp->f_files = nsp->f_files;
866 	osp->f_ffree = nsp->f_ffree;
867 	osp->f_syncwrites = nsp->f_syncwrites;
868 	osp->f_asyncwrites = nsp->f_asyncwrites;
869 	osp->f_syncreads = nsp->f_syncreads;
870 	osp->f_asyncreads = nsp->f_asyncreads;
871 	osp->f_namemax = nsp->f_namemax;
872 	osp->f_owner = nsp->f_owner;
873 	osp->f_fsid = nsp->f_fsid;
874 	strlcpy(osp->f_fstypename, nsp->f_fstypename,
875 	    MIN(MFSNAMELEN, sizeof(osp->f_fstypename)));
876 	strlcpy(osp->f_mntonname, nsp->f_mntonname,
877 	    MIN(MNAMELEN, sizeof(osp->f_mntonname)));
878 	strlcpy(osp->f_mntfromname, nsp->f_mntfromname,
879 	    MIN(MNAMELEN, sizeof(osp->f_mntfromname)));
880 }
881 #endif /* COMPAT_FREEBSD11 */
882 
883 /*
884  * Change current working directory to a given file descriptor.
885  */
886 #ifndef _SYS_SYSPROTO_H_
887 struct fchdir_args {
888 	int	fd;
889 };
890 #endif
891 int
892 sys_fchdir(struct thread *td, struct fchdir_args *uap)
893 {
894 	struct vnode *vp, *tdp;
895 	struct mount *mp;
896 	struct file *fp;
897 	int error;
898 
899 	AUDIT_ARG_FD(uap->fd);
900 	error = getvnode_path(td, uap->fd, &cap_fchdir_rights,
901 	    &fp);
902 	if (error != 0)
903 		return (error);
904 	vp = fp->f_vnode;
905 	vrefact(vp);
906 	fdrop(fp, td);
907 	vn_lock(vp, LK_SHARED | LK_RETRY);
908 	AUDIT_ARG_VNODE1(vp);
909 	error = change_dir(vp, td);
910 	while (!error && (mp = vp->v_mountedhere) != NULL) {
911 		if (vfs_busy(mp, 0))
912 			continue;
913 		error = VFS_ROOT(mp, LK_SHARED, &tdp);
914 		vfs_unbusy(mp);
915 		if (error != 0)
916 			break;
917 		vput(vp);
918 		vp = tdp;
919 	}
920 	if (error != 0) {
921 		vput(vp);
922 		return (error);
923 	}
924 	VOP_UNLOCK(vp);
925 	pwd_chdir(td, vp);
926 	return (0);
927 }
928 
929 /*
930  * Change current working directory (``.'').
931  */
932 #ifndef _SYS_SYSPROTO_H_
933 struct chdir_args {
934 	char	*path;
935 };
936 #endif
937 int
938 sys_chdir(struct thread *td, struct chdir_args *uap)
939 {
940 
941 	return (kern_chdir(td, uap->path, UIO_USERSPACE));
942 }
943 
944 int
945 kern_chdir(struct thread *td, const char *path, enum uio_seg pathseg)
946 {
947 	struct nameidata nd;
948 	int error;
949 
950 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF | AUDITVNODE1,
951 	    pathseg, path);
952 	if ((error = namei(&nd)) != 0)
953 		return (error);
954 	if ((error = change_dir(nd.ni_vp, td)) != 0) {
955 		vput(nd.ni_vp);
956 		NDFREE_PNBUF(&nd);
957 		return (error);
958 	}
959 	VOP_UNLOCK(nd.ni_vp);
960 	NDFREE_PNBUF(&nd);
961 	pwd_chdir(td, nd.ni_vp);
962 	return (0);
963 }
964 
965 static int unprivileged_chroot = 0;
966 SYSCTL_INT(_security_bsd, OID_AUTO, unprivileged_chroot, CTLFLAG_RW,
967     &unprivileged_chroot, 0,
968     "Unprivileged processes can use chroot(2)");
969 /*
970  * Change notion of root (``/'') directory.
971  */
972 #ifndef _SYS_SYSPROTO_H_
973 struct chroot_args {
974 	char	*path;
975 };
976 #endif
977 int
978 sys_chroot(struct thread *td, struct chroot_args *uap)
979 {
980 	struct nameidata nd;
981 	struct proc *p;
982 	int error;
983 
984 	error = priv_check(td, PRIV_VFS_CHROOT);
985 	if (error != 0) {
986 		p = td->td_proc;
987 		PROC_LOCK(p);
988 		if (unprivileged_chroot == 0 ||
989 		    (p->p_flag2 & P2_NO_NEW_PRIVS) == 0) {
990 			PROC_UNLOCK(p);
991 			return (error);
992 		}
993 		PROC_UNLOCK(p);
994 	}
995 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF | AUDITVNODE1,
996 	    UIO_USERSPACE, uap->path);
997 	error = namei(&nd);
998 	if (error != 0)
999 		return (error);
1000 	NDFREE_PNBUF(&nd);
1001 	error = change_dir(nd.ni_vp, td);
1002 	if (error != 0)
1003 		goto e_vunlock;
1004 #ifdef MAC
1005 	error = mac_vnode_check_chroot(td->td_ucred, nd.ni_vp);
1006 	if (error != 0)
1007 		goto e_vunlock;
1008 #endif
1009 	VOP_UNLOCK(nd.ni_vp);
1010 	error = pwd_chroot(td, nd.ni_vp);
1011 	vrele(nd.ni_vp);
1012 	return (error);
1013 e_vunlock:
1014 	vput(nd.ni_vp);
1015 	return (error);
1016 }
1017 
1018 /*
1019  * Common routine for chroot and chdir.  Callers must provide a locked vnode
1020  * instance.
1021  */
1022 int
1023 change_dir(struct vnode *vp, struct thread *td)
1024 {
1025 #ifdef MAC
1026 	int error;
1027 #endif
1028 
1029 	ASSERT_VOP_LOCKED(vp, "change_dir(): vp not locked");
1030 	if (vp->v_type != VDIR)
1031 		return (ENOTDIR);
1032 #ifdef MAC
1033 	error = mac_vnode_check_chdir(td->td_ucred, vp);
1034 	if (error != 0)
1035 		return (error);
1036 #endif
1037 	return (VOP_ACCESS(vp, VEXEC, td->td_ucred, td));
1038 }
1039 
1040 static __inline void
1041 flags_to_rights(int flags, cap_rights_t *rightsp)
1042 {
1043 	if (flags & O_EXEC) {
1044 		cap_rights_set_one(rightsp, CAP_FEXECVE);
1045 		if (flags & O_PATH)
1046 			return;
1047 	} else {
1048 		switch ((flags & O_ACCMODE)) {
1049 		case O_RDONLY:
1050 			cap_rights_set_one(rightsp, CAP_READ);
1051 			break;
1052 		case O_RDWR:
1053 			cap_rights_set_one(rightsp, CAP_READ);
1054 			/* FALLTHROUGH */
1055 		case O_WRONLY:
1056 			cap_rights_set_one(rightsp, CAP_WRITE);
1057 			if (!(flags & (O_APPEND | O_TRUNC)))
1058 				cap_rights_set_one(rightsp, CAP_SEEK);
1059 			break;
1060 		}
1061 	}
1062 
1063 	if (flags & O_CREAT)
1064 		cap_rights_set_one(rightsp, CAP_CREATE);
1065 
1066 	if (flags & O_TRUNC)
1067 		cap_rights_set_one(rightsp, CAP_FTRUNCATE);
1068 
1069 	if (flags & (O_SYNC | O_FSYNC))
1070 		cap_rights_set_one(rightsp, CAP_FSYNC);
1071 
1072 	if (flags & (O_EXLOCK | O_SHLOCK))
1073 		cap_rights_set_one(rightsp, CAP_FLOCK);
1074 }
1075 
1076 /*
1077  * Check permissions, allocate an open file structure, and call the device
1078  * open routine if any.
1079  */
1080 #ifndef _SYS_SYSPROTO_H_
1081 struct open_args {
1082 	char	*path;
1083 	int	flags;
1084 	int	mode;
1085 };
1086 #endif
1087 int
1088 sys_open(struct thread *td, struct open_args *uap)
1089 {
1090 
1091 	return (kern_openat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
1092 	    uap->flags, uap->mode));
1093 }
1094 
1095 #ifndef _SYS_SYSPROTO_H_
1096 struct openat_args {
1097 	int	fd;
1098 	char	*path;
1099 	int	flag;
1100 	int	mode;
1101 };
1102 #endif
1103 int
1104 sys_openat(struct thread *td, struct openat_args *uap)
1105 {
1106 
1107 	AUDIT_ARG_FD(uap->fd);
1108 	return (kern_openat(td, uap->fd, uap->path, UIO_USERSPACE, uap->flag,
1109 	    uap->mode));
1110 }
1111 
1112 int
1113 kern_openat(struct thread *td, int fd, const char *path, enum uio_seg pathseg,
1114     int flags, int mode)
1115 {
1116 	struct proc *p = td->td_proc;
1117 	struct filedesc *fdp;
1118 	struct pwddesc *pdp;
1119 	struct file *fp;
1120 	struct vnode *vp;
1121 	struct nameidata nd;
1122 	cap_rights_t rights;
1123 	int cmode, error, indx;
1124 
1125 	indx = -1;
1126 	fdp = p->p_fd;
1127 	pdp = p->p_pd;
1128 
1129 	AUDIT_ARG_FFLAGS(flags);
1130 	AUDIT_ARG_MODE(mode);
1131 	cap_rights_init_one(&rights, CAP_LOOKUP);
1132 	flags_to_rights(flags, &rights);
1133 
1134 	/*
1135 	 * Only one of the O_EXEC, O_RDONLY, O_WRONLY and O_RDWR flags
1136 	 * may be specified.  On the other hand, for O_PATH any mode
1137 	 * except O_EXEC is ignored.
1138 	 */
1139 	if ((flags & O_PATH) != 0) {
1140 		flags &= ~(O_CREAT | O_ACCMODE);
1141 	} else if ((flags & O_EXEC) != 0) {
1142 		if (flags & O_ACCMODE)
1143 			return (EINVAL);
1144 	} else if ((flags & O_ACCMODE) == O_ACCMODE) {
1145 		return (EINVAL);
1146 	} else {
1147 		flags = FFLAGS(flags);
1148 	}
1149 
1150 	/*
1151 	 * Allocate a file structure. The descriptor to reference it
1152 	 * is allocated and used by finstall_refed() below.
1153 	 */
1154 	error = falloc_noinstall(td, &fp);
1155 	if (error != 0)
1156 		return (error);
1157 	/* Set the flags early so the finit in devfs can pick them up. */
1158 	fp->f_flag = flags & FMASK;
1159 	cmode = ((mode & ~pdp->pd_cmask) & ALLPERMS) & ~S_ISTXT;
1160 	NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | AUDITVNODE1 | WANTIOCTLCAPS,
1161 	    pathseg, path, fd, &rights);
1162 	td->td_dupfd = -1;		/* XXX check for fdopen */
1163 	error = vn_open_cred(&nd, &flags, cmode, VN_OPEN_WANTIOCTLCAPS,
1164 	    td->td_ucred, fp);
1165 	if (error != 0) {
1166 		/*
1167 		 * If the vn_open replaced the method vector, something
1168 		 * wonderous happened deep below and we just pass it up
1169 		 * pretending we know what we do.
1170 		 */
1171 		if (error == ENXIO && fp->f_ops != &badfileops) {
1172 			MPASS((flags & O_PATH) == 0);
1173 			goto success;
1174 		}
1175 
1176 		/*
1177 		 * Handle special fdopen() case. bleh.
1178 		 *
1179 		 * Don't do this for relative (capability) lookups; we don't
1180 		 * understand exactly what would happen, and we don't think
1181 		 * that it ever should.
1182 		 */
1183 		if ((nd.ni_resflags & NIRES_STRICTREL) == 0 &&
1184 		    (error == ENODEV || error == ENXIO) &&
1185 		    td->td_dupfd >= 0) {
1186 			error = dupfdopen(td, fdp, td->td_dupfd, flags, error,
1187 			    &indx);
1188 			if (error == 0)
1189 				goto success;
1190 		}
1191 
1192 		goto bad;
1193 	}
1194 	td->td_dupfd = 0;
1195 	NDFREE_PNBUF(&nd);
1196 	vp = nd.ni_vp;
1197 
1198 	/*
1199 	 * Store the vnode, for any f_type. Typically, the vnode use
1200 	 * count is decremented by direct call to vn_closefile() for
1201 	 * files that switched type in the cdevsw fdopen() method.
1202 	 */
1203 	fp->f_vnode = vp;
1204 
1205 	/*
1206 	 * If the file wasn't claimed by devfs bind it to the normal
1207 	 * vnode operations here.
1208 	 */
1209 	if (fp->f_ops == &badfileops) {
1210 		KASSERT(vp->v_type != VFIFO || (flags & O_PATH) != 0,
1211 		    ("Unexpected fifo fp %p vp %p", fp, vp));
1212 		if ((flags & O_PATH) != 0) {
1213 			finit(fp, (flags & FMASK) | (fp->f_flag & FKQALLOWED),
1214 			    DTYPE_VNODE, NULL, &path_fileops);
1215 		} else {
1216 			finit_vnode(fp, flags, NULL, &vnops);
1217 		}
1218 	}
1219 
1220 	VOP_UNLOCK(vp);
1221 	if (flags & O_TRUNC) {
1222 		error = fo_truncate(fp, 0, td->td_ucred, td);
1223 		if (error != 0)
1224 			goto bad;
1225 	}
1226 success:
1227 	/*
1228 	 * If we haven't already installed the FD (for dupfdopen), do so now.
1229 	 */
1230 	if (indx == -1) {
1231 		struct filecaps *fcaps;
1232 
1233 #ifdef CAPABILITIES
1234 		if ((nd.ni_resflags & NIRES_STRICTREL) != 0)
1235 			fcaps = &nd.ni_filecaps;
1236 		else
1237 #endif
1238 			fcaps = NULL;
1239 		error = finstall_refed(td, fp, &indx, flags, fcaps);
1240 		/* On success finstall_refed() consumes fcaps. */
1241 		if (error != 0) {
1242 			goto bad;
1243 		}
1244 	} else {
1245 		NDFREE_IOCTLCAPS(&nd);
1246 		falloc_abort(td, fp);
1247 	}
1248 
1249 	td->td_retval[0] = indx;
1250 	return (0);
1251 bad:
1252 	KASSERT(indx == -1, ("indx=%d, should be -1", indx));
1253 	NDFREE_IOCTLCAPS(&nd);
1254 	falloc_abort(td, fp);
1255 	return (error);
1256 }
1257 
1258 #ifdef COMPAT_43
1259 /*
1260  * Create a file.
1261  */
1262 #ifndef _SYS_SYSPROTO_H_
1263 struct ocreat_args {
1264 	char	*path;
1265 	int	mode;
1266 };
1267 #endif
1268 int
1269 ocreat(struct thread *td, struct ocreat_args *uap)
1270 {
1271 
1272 	return (kern_openat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
1273 	    O_WRONLY | O_CREAT | O_TRUNC, uap->mode));
1274 }
1275 #endif /* COMPAT_43 */
1276 
1277 /*
1278  * Create a special file.
1279  */
1280 #ifndef _SYS_SYSPROTO_H_
1281 struct mknodat_args {
1282 	int	fd;
1283 	char	*path;
1284 	mode_t	mode;
1285 	dev_t	dev;
1286 };
1287 #endif
1288 int
1289 sys_mknodat(struct thread *td, struct mknodat_args *uap)
1290 {
1291 
1292 	return (kern_mknodat(td, uap->fd, uap->path, UIO_USERSPACE, uap->mode,
1293 	    uap->dev));
1294 }
1295 
1296 #if defined(COMPAT_FREEBSD11)
1297 int
1298 freebsd11_mknod(struct thread *td,
1299     struct freebsd11_mknod_args *uap)
1300 {
1301 
1302 	return (kern_mknodat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
1303 	    uap->mode, uap->dev));
1304 }
1305 
1306 int
1307 freebsd11_mknodat(struct thread *td,
1308     struct freebsd11_mknodat_args *uap)
1309 {
1310 
1311 	return (kern_mknodat(td, uap->fd, uap->path, UIO_USERSPACE, uap->mode,
1312 	    uap->dev));
1313 }
1314 #endif /* COMPAT_FREEBSD11 */
1315 
1316 int
1317 kern_mknodat(struct thread *td, int fd, const char *path, enum uio_seg pathseg,
1318     int mode, dev_t dev)
1319 {
1320 	struct vnode *vp;
1321 	struct mount *mp;
1322 	struct vattr vattr;
1323 	struct nameidata nd;
1324 	int error, whiteout = 0;
1325 
1326 	AUDIT_ARG_MODE(mode);
1327 	AUDIT_ARG_DEV(dev);
1328 	switch (mode & S_IFMT) {
1329 	case S_IFCHR:
1330 	case S_IFBLK:
1331 		error = priv_check(td, PRIV_VFS_MKNOD_DEV);
1332 		if (error == 0 && dev == VNOVAL)
1333 			error = EINVAL;
1334 		break;
1335 	case S_IFWHT:
1336 		error = priv_check(td, PRIV_VFS_MKNOD_WHT);
1337 		break;
1338 	case S_IFIFO:
1339 		if (dev == 0)
1340 			return (kern_mkfifoat(td, fd, path, pathseg, mode));
1341 		/* FALLTHROUGH */
1342 	default:
1343 		error = EINVAL;
1344 		break;
1345 	}
1346 	if (error != 0)
1347 		return (error);
1348 	NDPREINIT(&nd);
1349 restart:
1350 	bwillwrite();
1351 	NDINIT_ATRIGHTS(&nd, CREATE, LOCKPARENT | AUDITVNODE1 | NOCACHE,
1352 	    pathseg, path, fd, &cap_mknodat_rights);
1353 	if ((error = namei(&nd)) != 0)
1354 		return (error);
1355 	vp = nd.ni_vp;
1356 	if (vp != NULL) {
1357 		NDFREE_PNBUF(&nd);
1358 		if (vp == nd.ni_dvp)
1359 			vrele(nd.ni_dvp);
1360 		else
1361 			vput(nd.ni_dvp);
1362 		vrele(vp);
1363 		return (EEXIST);
1364 	} else {
1365 		VATTR_NULL(&vattr);
1366 		vattr.va_mode = (mode & ALLPERMS) &
1367 		    ~td->td_proc->p_pd->pd_cmask;
1368 		vattr.va_rdev = dev;
1369 		whiteout = 0;
1370 
1371 		switch (mode & S_IFMT) {
1372 		case S_IFCHR:
1373 			vattr.va_type = VCHR;
1374 			break;
1375 		case S_IFBLK:
1376 			vattr.va_type = VBLK;
1377 			break;
1378 		case S_IFWHT:
1379 			whiteout = 1;
1380 			break;
1381 		default:
1382 			panic("kern_mknod: invalid mode");
1383 		}
1384 	}
1385 	if (vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
1386 		NDFREE_PNBUF(&nd);
1387 		vput(nd.ni_dvp);
1388 		if ((error = vn_start_write(NULL, &mp, V_XSLEEP | V_PCATCH)) != 0)
1389 			return (error);
1390 		goto restart;
1391 	}
1392 #ifdef MAC
1393 	if (error == 0 && !whiteout)
1394 		error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp,
1395 		    &nd.ni_cnd, &vattr);
1396 #endif
1397 	if (error == 0) {
1398 		if (whiteout)
1399 			error = VOP_WHITEOUT(nd.ni_dvp, &nd.ni_cnd, CREATE);
1400 		else {
1401 			error = VOP_MKNOD(nd.ni_dvp, &nd.ni_vp,
1402 						&nd.ni_cnd, &vattr);
1403 		}
1404 	}
1405 	VOP_VPUT_PAIR(nd.ni_dvp, error == 0 && !whiteout ? &nd.ni_vp : NULL,
1406 	    true);
1407 	vn_finished_write(mp);
1408 	NDFREE_PNBUF(&nd);
1409 	if (error == ERELOOKUP)
1410 		goto restart;
1411 	return (error);
1412 }
1413 
1414 /*
1415  * Create a named pipe.
1416  */
1417 #ifndef _SYS_SYSPROTO_H_
1418 struct mkfifo_args {
1419 	char	*path;
1420 	int	mode;
1421 };
1422 #endif
1423 int
1424 sys_mkfifo(struct thread *td, struct mkfifo_args *uap)
1425 {
1426 
1427 	return (kern_mkfifoat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
1428 	    uap->mode));
1429 }
1430 
1431 #ifndef _SYS_SYSPROTO_H_
1432 struct mkfifoat_args {
1433 	int	fd;
1434 	char	*path;
1435 	mode_t	mode;
1436 };
1437 #endif
1438 int
1439 sys_mkfifoat(struct thread *td, struct mkfifoat_args *uap)
1440 {
1441 
1442 	return (kern_mkfifoat(td, uap->fd, uap->path, UIO_USERSPACE,
1443 	    uap->mode));
1444 }
1445 
1446 int
1447 kern_mkfifoat(struct thread *td, int fd, const char *path,
1448     enum uio_seg pathseg, int mode)
1449 {
1450 	struct mount *mp;
1451 	struct vattr vattr;
1452 	struct nameidata nd;
1453 	int error;
1454 
1455 	AUDIT_ARG_MODE(mode);
1456 	NDPREINIT(&nd);
1457 restart:
1458 	bwillwrite();
1459 	NDINIT_ATRIGHTS(&nd, CREATE, LOCKPARENT | AUDITVNODE1 | NOCACHE,
1460 	    pathseg, path, fd, &cap_mkfifoat_rights);
1461 	if ((error = namei(&nd)) != 0)
1462 		return (error);
1463 	if (nd.ni_vp != NULL) {
1464 		NDFREE_PNBUF(&nd);
1465 		if (nd.ni_vp == nd.ni_dvp)
1466 			vrele(nd.ni_dvp);
1467 		else
1468 			vput(nd.ni_dvp);
1469 		vrele(nd.ni_vp);
1470 		return (EEXIST);
1471 	}
1472 	if (vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
1473 		NDFREE_PNBUF(&nd);
1474 		vput(nd.ni_dvp);
1475 		if ((error = vn_start_write(NULL, &mp, V_XSLEEP | V_PCATCH)) != 0)
1476 			return (error);
1477 		goto restart;
1478 	}
1479 	VATTR_NULL(&vattr);
1480 	vattr.va_type = VFIFO;
1481 	vattr.va_mode = (mode & ALLPERMS) & ~td->td_proc->p_pd->pd_cmask;
1482 #ifdef MAC
1483 	error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
1484 	    &vattr);
1485 	if (error != 0)
1486 		goto out;
1487 #endif
1488 	error = VOP_MKNOD(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
1489 #ifdef MAC
1490 out:
1491 #endif
1492 	VOP_VPUT_PAIR(nd.ni_dvp, error == 0 ? &nd.ni_vp : NULL, true);
1493 	vn_finished_write(mp);
1494 	NDFREE_PNBUF(&nd);
1495 	if (error == ERELOOKUP)
1496 		goto restart;
1497 	return (error);
1498 }
1499 
1500 /*
1501  * Make a hard file link.
1502  */
1503 #ifndef _SYS_SYSPROTO_H_
1504 struct link_args {
1505 	char	*path;
1506 	char	*link;
1507 };
1508 #endif
1509 int
1510 sys_link(struct thread *td, struct link_args *uap)
1511 {
1512 
1513 	return (kern_linkat(td, AT_FDCWD, AT_FDCWD, uap->path, uap->link,
1514 	    UIO_USERSPACE, AT_SYMLINK_FOLLOW));
1515 }
1516 
1517 #ifndef _SYS_SYSPROTO_H_
1518 struct linkat_args {
1519 	int	fd1;
1520 	char	*path1;
1521 	int	fd2;
1522 	char	*path2;
1523 	int	flag;
1524 };
1525 #endif
1526 int
1527 sys_linkat(struct thread *td, struct linkat_args *uap)
1528 {
1529 
1530 	return (kern_linkat(td, uap->fd1, uap->fd2, uap->path1, uap->path2,
1531 	    UIO_USERSPACE, uap->flag));
1532 }
1533 
1534 int hardlink_check_uid = 0;
1535 SYSCTL_INT(_security_bsd, OID_AUTO, hardlink_check_uid, CTLFLAG_RW,
1536     &hardlink_check_uid, 0,
1537     "Unprivileged processes cannot create hard links to files owned by other "
1538     "users");
1539 static int hardlink_check_gid = 0;
1540 SYSCTL_INT(_security_bsd, OID_AUTO, hardlink_check_gid, CTLFLAG_RW,
1541     &hardlink_check_gid, 0,
1542     "Unprivileged processes cannot create hard links to files owned by other "
1543     "groups");
1544 
1545 static int
1546 can_hardlink(struct vnode *vp, struct ucred *cred)
1547 {
1548 	struct vattr va;
1549 	int error;
1550 
1551 	if (!hardlink_check_uid && !hardlink_check_gid)
1552 		return (0);
1553 
1554 	error = VOP_GETATTR(vp, &va, cred);
1555 	if (error != 0)
1556 		return (error);
1557 
1558 	if (hardlink_check_uid && cred->cr_uid != va.va_uid) {
1559 		error = priv_check_cred(cred, PRIV_VFS_LINK);
1560 		if (error != 0)
1561 			return (error);
1562 	}
1563 
1564 	if (hardlink_check_gid && !groupmember(va.va_gid, cred)) {
1565 		error = priv_check_cred(cred, PRIV_VFS_LINK);
1566 		if (error != 0)
1567 			return (error);
1568 	}
1569 
1570 	return (0);
1571 }
1572 
1573 int
1574 kern_linkat(struct thread *td, int fd1, int fd2, const char *path1,
1575     const char *path2, enum uio_seg segflag, int flag)
1576 {
1577 	struct nameidata nd;
1578 	int error;
1579 
1580 	if ((flag & ~(AT_SYMLINK_FOLLOW | AT_RESOLVE_BENEATH |
1581 	    AT_EMPTY_PATH)) != 0)
1582 		return (EINVAL);
1583 
1584 	NDPREINIT(&nd);
1585 	do {
1586 		bwillwrite();
1587 		NDINIT_ATRIGHTS(&nd, LOOKUP, AUDITVNODE1 | at2cnpflags(flag,
1588 		    AT_SYMLINK_FOLLOW | AT_RESOLVE_BENEATH | AT_EMPTY_PATH),
1589 		    segflag, path1, fd1, &cap_linkat_source_rights);
1590 		if ((error = namei(&nd)) != 0)
1591 			return (error);
1592 		NDFREE_PNBUF(&nd);
1593 		if ((nd.ni_resflags & NIRES_EMPTYPATH) != 0) {
1594 			error = priv_check(td, PRIV_VFS_FHOPEN);
1595 			if (error != 0) {
1596 				vrele(nd.ni_vp);
1597 				return (error);
1598 			}
1599 		}
1600 		error = kern_linkat_vp(td, nd.ni_vp, fd2, path2, segflag);
1601 	} while (error ==  EAGAIN || error == ERELOOKUP);
1602 	return (error);
1603 }
1604 
1605 static int
1606 kern_linkat_vp(struct thread *td, struct vnode *vp, int fd, const char *path,
1607     enum uio_seg segflag)
1608 {
1609 	struct nameidata nd;
1610 	struct mount *mp;
1611 	int error;
1612 
1613 	if (vp->v_type == VDIR) {
1614 		vrele(vp);
1615 		return (EPERM);		/* POSIX */
1616 	}
1617 	NDINIT_ATRIGHTS(&nd, CREATE,
1618 	    LOCKPARENT | AUDITVNODE2 | NOCACHE, segflag, path, fd,
1619 	    &cap_linkat_target_rights);
1620 	if ((error = namei(&nd)) == 0) {
1621 		if (nd.ni_vp != NULL) {
1622 			NDFREE_PNBUF(&nd);
1623 			if (nd.ni_dvp == nd.ni_vp)
1624 				vrele(nd.ni_dvp);
1625 			else
1626 				vput(nd.ni_dvp);
1627 			vrele(nd.ni_vp);
1628 			vrele(vp);
1629 			return (EEXIST);
1630 		} else if (nd.ni_dvp->v_mount != vp->v_mount) {
1631 			/*
1632 			 * Cross-device link.  No need to recheck
1633 			 * vp->v_type, since it cannot change, except
1634 			 * to VBAD.
1635 			 */
1636 			NDFREE_PNBUF(&nd);
1637 			vput(nd.ni_dvp);
1638 			vrele(vp);
1639 			return (EXDEV);
1640 		} else if (vn_lock(vp, LK_EXCLUSIVE) == 0) {
1641 			error = can_hardlink(vp, td->td_ucred);
1642 #ifdef MAC
1643 			if (error == 0)
1644 				error = mac_vnode_check_link(td->td_ucred,
1645 				    nd.ni_dvp, vp, &nd.ni_cnd);
1646 #endif
1647 			if (error != 0) {
1648 				vput(vp);
1649 				vput(nd.ni_dvp);
1650 				NDFREE_PNBUF(&nd);
1651 				return (error);
1652 			}
1653 			error = vn_start_write(vp, &mp, V_NOWAIT);
1654 			if (error != 0) {
1655 				vput(vp);
1656 				vput(nd.ni_dvp);
1657 				NDFREE_PNBUF(&nd);
1658 				error = vn_start_write(NULL, &mp,
1659 				    V_XSLEEP | V_PCATCH);
1660 				if (error != 0)
1661 					return (error);
1662 				return (EAGAIN);
1663 			}
1664 			error = VOP_LINK(nd.ni_dvp, vp, &nd.ni_cnd);
1665 			VOP_VPUT_PAIR(nd.ni_dvp, &vp, true);
1666 			vn_finished_write(mp);
1667 			NDFREE_PNBUF(&nd);
1668 			vp = NULL;
1669 		} else {
1670 			vput(nd.ni_dvp);
1671 			NDFREE_PNBUF(&nd);
1672 			vrele(vp);
1673 			return (EAGAIN);
1674 		}
1675 	}
1676 	if (vp != NULL)
1677 		vrele(vp);
1678 	return (error);
1679 }
1680 
1681 /*
1682  * Make a symbolic link.
1683  */
1684 #ifndef _SYS_SYSPROTO_H_
1685 struct symlink_args {
1686 	char	*path;
1687 	char	*link;
1688 };
1689 #endif
1690 int
1691 sys_symlink(struct thread *td, struct symlink_args *uap)
1692 {
1693 
1694 	return (kern_symlinkat(td, uap->path, AT_FDCWD, uap->link,
1695 	    UIO_USERSPACE));
1696 }
1697 
1698 #ifndef _SYS_SYSPROTO_H_
1699 struct symlinkat_args {
1700 	char	*path;
1701 	int	fd;
1702 	char	*path2;
1703 };
1704 #endif
1705 int
1706 sys_symlinkat(struct thread *td, struct symlinkat_args *uap)
1707 {
1708 
1709 	return (kern_symlinkat(td, uap->path1, uap->fd, uap->path2,
1710 	    UIO_USERSPACE));
1711 }
1712 
1713 int
1714 kern_symlinkat(struct thread *td, const char *path1, int fd, const char *path2,
1715     enum uio_seg segflg)
1716 {
1717 	struct mount *mp;
1718 	struct vattr vattr;
1719 	const char *syspath;
1720 	char *tmppath;
1721 	struct nameidata nd;
1722 	int error;
1723 
1724 	if (segflg == UIO_SYSSPACE) {
1725 		syspath = path1;
1726 	} else {
1727 		tmppath = uma_zalloc(namei_zone, M_WAITOK);
1728 		if ((error = copyinstr(path1, tmppath, MAXPATHLEN, NULL)) != 0)
1729 			goto out;
1730 		syspath = tmppath;
1731 	}
1732 	AUDIT_ARG_TEXT(syspath);
1733 	NDPREINIT(&nd);
1734 restart:
1735 	bwillwrite();
1736 	NDINIT_ATRIGHTS(&nd, CREATE, LOCKPARENT | AUDITVNODE1 | NOCACHE, segflg,
1737 	    path2, fd, &cap_symlinkat_rights);
1738 	if ((error = namei(&nd)) != 0)
1739 		goto out;
1740 	if (nd.ni_vp) {
1741 		NDFREE_PNBUF(&nd);
1742 		if (nd.ni_vp == nd.ni_dvp)
1743 			vrele(nd.ni_dvp);
1744 		else
1745 			vput(nd.ni_dvp);
1746 		vrele(nd.ni_vp);
1747 		nd.ni_vp = NULL;
1748 		error = EEXIST;
1749 		goto out;
1750 	}
1751 	if (vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
1752 		NDFREE_PNBUF(&nd);
1753 		vput(nd.ni_dvp);
1754 		if ((error = vn_start_write(NULL, &mp, V_XSLEEP | V_PCATCH)) != 0)
1755 			goto out;
1756 		goto restart;
1757 	}
1758 	VATTR_NULL(&vattr);
1759 	vattr.va_mode = ACCESSPERMS &~ td->td_proc->p_pd->pd_cmask;
1760 #ifdef MAC
1761 	vattr.va_type = VLNK;
1762 	error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
1763 	    &vattr);
1764 	if (error != 0)
1765 		goto out2;
1766 #endif
1767 	error = VOP_SYMLINK(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr, syspath);
1768 #ifdef MAC
1769 out2:
1770 #endif
1771 	VOP_VPUT_PAIR(nd.ni_dvp, error == 0 ? &nd.ni_vp : NULL, true);
1772 	vn_finished_write(mp);
1773 	NDFREE_PNBUF(&nd);
1774 	if (error == ERELOOKUP)
1775 		goto restart;
1776 out:
1777 	if (segflg != UIO_SYSSPACE)
1778 		uma_zfree(namei_zone, tmppath);
1779 	return (error);
1780 }
1781 
1782 /*
1783  * Delete a whiteout from the filesystem.
1784  */
1785 #ifndef _SYS_SYSPROTO_H_
1786 struct undelete_args {
1787 	char *path;
1788 };
1789 #endif
1790 int
1791 sys_undelete(struct thread *td, struct undelete_args *uap)
1792 {
1793 	struct mount *mp;
1794 	struct nameidata nd;
1795 	int error;
1796 
1797 	NDPREINIT(&nd);
1798 restart:
1799 	bwillwrite();
1800 	NDINIT(&nd, DELETE, LOCKPARENT | DOWHITEOUT | AUDITVNODE1,
1801 	    UIO_USERSPACE, uap->path);
1802 	error = namei(&nd);
1803 	if (error != 0)
1804 		return (error);
1805 
1806 	if (nd.ni_vp != NULLVP || !(nd.ni_cnd.cn_flags & ISWHITEOUT)) {
1807 		NDFREE_PNBUF(&nd);
1808 		if (nd.ni_vp == nd.ni_dvp)
1809 			vrele(nd.ni_dvp);
1810 		else
1811 			vput(nd.ni_dvp);
1812 		if (nd.ni_vp)
1813 			vrele(nd.ni_vp);
1814 		return (EEXIST);
1815 	}
1816 	if (vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
1817 		NDFREE_PNBUF(&nd);
1818 		vput(nd.ni_dvp);
1819 		if ((error = vn_start_write(NULL, &mp, V_XSLEEP | V_PCATCH)) != 0)
1820 			return (error);
1821 		goto restart;
1822 	}
1823 	error = VOP_WHITEOUT(nd.ni_dvp, &nd.ni_cnd, DELETE);
1824 	NDFREE_PNBUF(&nd);
1825 	vput(nd.ni_dvp);
1826 	vn_finished_write(mp);
1827 	if (error == ERELOOKUP)
1828 		goto restart;
1829 	return (error);
1830 }
1831 
1832 /*
1833  * Delete a name from the filesystem.
1834  */
1835 #ifndef _SYS_SYSPROTO_H_
1836 struct unlink_args {
1837 	char	*path;
1838 };
1839 #endif
1840 int
1841 sys_unlink(struct thread *td, struct unlink_args *uap)
1842 {
1843 
1844 	return (kern_funlinkat(td, AT_FDCWD, uap->path, FD_NONE, UIO_USERSPACE,
1845 	    0, 0));
1846 }
1847 
1848 static int
1849 kern_funlinkat_ex(struct thread *td, int dfd, const char *path, int fd,
1850     int flag, enum uio_seg pathseg, ino_t oldinum)
1851 {
1852 
1853 	if ((flag & ~(AT_REMOVEDIR | AT_RESOLVE_BENEATH)) != 0)
1854 		return (EINVAL);
1855 
1856 	if ((flag & AT_REMOVEDIR) != 0)
1857 		return (kern_frmdirat(td, dfd, path, fd, UIO_USERSPACE, 0));
1858 
1859 	return (kern_funlinkat(td, dfd, path, fd, UIO_USERSPACE, 0, 0));
1860 }
1861 
1862 #ifndef _SYS_SYSPROTO_H_
1863 struct unlinkat_args {
1864 	int	fd;
1865 	char	*path;
1866 	int	flag;
1867 };
1868 #endif
1869 int
1870 sys_unlinkat(struct thread *td, struct unlinkat_args *uap)
1871 {
1872 
1873 	return (kern_funlinkat_ex(td, uap->fd, uap->path, FD_NONE, uap->flag,
1874 	    UIO_USERSPACE, 0));
1875 }
1876 
1877 #ifndef _SYS_SYSPROTO_H_
1878 struct funlinkat_args {
1879 	int		dfd;
1880 	const char	*path;
1881 	int		fd;
1882 	int		flag;
1883 };
1884 #endif
1885 int
1886 sys_funlinkat(struct thread *td, struct funlinkat_args *uap)
1887 {
1888 
1889 	return (kern_funlinkat_ex(td, uap->dfd, uap->path, uap->fd, uap->flag,
1890 	    UIO_USERSPACE, 0));
1891 }
1892 
1893 int
1894 kern_funlinkat(struct thread *td, int dfd, const char *path, int fd,
1895     enum uio_seg pathseg, int flag, ino_t oldinum)
1896 {
1897 	struct mount *mp;
1898 	struct file *fp;
1899 	struct vnode *vp;
1900 	struct nameidata nd;
1901 	struct stat sb;
1902 	int error;
1903 
1904 	fp = NULL;
1905 	if (fd != FD_NONE) {
1906 		error = getvnode_path(td, fd, &cap_no_rights, &fp);
1907 		if (error != 0)
1908 			return (error);
1909 	}
1910 
1911 	NDPREINIT(&nd);
1912 restart:
1913 	bwillwrite();
1914 	NDINIT_ATRIGHTS(&nd, DELETE, LOCKPARENT | LOCKLEAF | AUDITVNODE1 |
1915 	    at2cnpflags(flag, AT_RESOLVE_BENEATH),
1916 	    pathseg, path, dfd, &cap_unlinkat_rights);
1917 	if ((error = namei(&nd)) != 0) {
1918 		if (error == EINVAL)
1919 			error = EPERM;
1920 		goto fdout;
1921 	}
1922 	vp = nd.ni_vp;
1923 	if (vp->v_type == VDIR && oldinum == 0) {
1924 		error = EPERM;		/* POSIX */
1925 	} else if (oldinum != 0 &&
1926 	    ((error = VOP_STAT(vp, &sb, td->td_ucred, NOCRED)) == 0) &&
1927 	    sb.st_ino != oldinum) {
1928 		error = EIDRM;	/* Identifier removed */
1929 	} else if (fp != NULL && fp->f_vnode != vp) {
1930 		if (VN_IS_DOOMED(fp->f_vnode))
1931 			error = EBADF;
1932 		else
1933 			error = EDEADLK;
1934 	} else {
1935 		/*
1936 		 * The root of a mounted filesystem cannot be deleted.
1937 		 *
1938 		 * XXX: can this only be a VDIR case?
1939 		 */
1940 		if (vp->v_vflag & VV_ROOT)
1941 			error = EBUSY;
1942 	}
1943 	if (error == 0) {
1944 		if (vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
1945 			NDFREE_PNBUF(&nd);
1946 			vput(nd.ni_dvp);
1947 			if (vp == nd.ni_dvp)
1948 				vrele(vp);
1949 			else
1950 				vput(vp);
1951 			if ((error = vn_start_write(NULL, &mp,
1952 			    V_XSLEEP | V_PCATCH)) != 0) {
1953 				goto fdout;
1954 			}
1955 			goto restart;
1956 		}
1957 #ifdef MAC
1958 		error = mac_vnode_check_unlink(td->td_ucred, nd.ni_dvp, vp,
1959 		    &nd.ni_cnd);
1960 		if (error != 0)
1961 			goto out;
1962 #endif
1963 		vfs_notify_upper(vp, VFS_NOTIFY_UPPER_UNLINK);
1964 		error = VOP_REMOVE(nd.ni_dvp, vp, &nd.ni_cnd);
1965 #ifdef MAC
1966 out:
1967 #endif
1968 		vn_finished_write(mp);
1969 	}
1970 	NDFREE_PNBUF(&nd);
1971 	vput(nd.ni_dvp);
1972 	if (vp == nd.ni_dvp)
1973 		vrele(vp);
1974 	else
1975 		vput(vp);
1976 	if (error == ERELOOKUP)
1977 		goto restart;
1978 fdout:
1979 	if (fp != NULL)
1980 		fdrop(fp, td);
1981 	return (error);
1982 }
1983 
1984 /*
1985  * Reposition read/write file offset.
1986  */
1987 #ifndef _SYS_SYSPROTO_H_
1988 struct lseek_args {
1989 	int	fd;
1990 	int	pad;
1991 	off_t	offset;
1992 	int	whence;
1993 };
1994 #endif
1995 int
1996 sys_lseek(struct thread *td, struct lseek_args *uap)
1997 {
1998 
1999 	return (kern_lseek(td, uap->fd, uap->offset, uap->whence));
2000 }
2001 
2002 int
2003 kern_lseek(struct thread *td, int fd, off_t offset, int whence)
2004 {
2005 	struct file *fp;
2006 	int error;
2007 
2008 	AUDIT_ARG_FD(fd);
2009 	error = fget(td, fd, &cap_seek_rights, &fp);
2010 	if (error != 0)
2011 		return (error);
2012 	error = (fp->f_ops->fo_flags & DFLAG_SEEKABLE) != 0 ?
2013 	    fo_seek(fp, offset, whence, td) : ESPIPE;
2014 	fdrop(fp, td);
2015 	return (error);
2016 }
2017 
2018 #if defined(COMPAT_43)
2019 /*
2020  * Reposition read/write file offset.
2021  */
2022 #ifndef _SYS_SYSPROTO_H_
2023 struct olseek_args {
2024 	int	fd;
2025 	long	offset;
2026 	int	whence;
2027 };
2028 #endif
2029 int
2030 olseek(struct thread *td, struct olseek_args *uap)
2031 {
2032 
2033 	return (kern_lseek(td, uap->fd, uap->offset, uap->whence));
2034 }
2035 #endif /* COMPAT_43 */
2036 
2037 #if defined(COMPAT_FREEBSD6)
2038 /* Version with the 'pad' argument */
2039 int
2040 freebsd6_lseek(struct thread *td, struct freebsd6_lseek_args *uap)
2041 {
2042 
2043 	return (kern_lseek(td, uap->fd, uap->offset, uap->whence));
2044 }
2045 #endif
2046 
2047 /*
2048  * Check access permissions using passed credentials.
2049  */
2050 static int
2051 vn_access(struct vnode *vp, int user_flags, struct ucred *cred,
2052      struct thread *td)
2053 {
2054 	accmode_t accmode;
2055 	int error;
2056 
2057 	/* Flags == 0 means only check for existence. */
2058 	if (user_flags == 0)
2059 		return (0);
2060 
2061 	accmode = 0;
2062 	if (user_flags & R_OK)
2063 		accmode |= VREAD;
2064 	if (user_flags & W_OK)
2065 		accmode |= VWRITE;
2066 	if (user_flags & X_OK)
2067 		accmode |= VEXEC;
2068 #ifdef MAC
2069 	error = mac_vnode_check_access(cred, vp, accmode);
2070 	if (error != 0)
2071 		return (error);
2072 #endif
2073 	if ((accmode & VWRITE) == 0 || (error = vn_writechk(vp)) == 0)
2074 		error = VOP_ACCESS(vp, accmode, cred, td);
2075 	return (error);
2076 }
2077 
2078 /*
2079  * Check access permissions using "real" credentials.
2080  */
2081 #ifndef _SYS_SYSPROTO_H_
2082 struct access_args {
2083 	char	*path;
2084 	int	amode;
2085 };
2086 #endif
2087 int
2088 sys_access(struct thread *td, struct access_args *uap)
2089 {
2090 
2091 	return (kern_accessat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
2092 	    0, uap->amode));
2093 }
2094 
2095 #ifndef _SYS_SYSPROTO_H_
2096 struct faccessat_args {
2097 	int	dirfd;
2098 	char	*path;
2099 	int	amode;
2100 	int	flag;
2101 }
2102 #endif
2103 int
2104 sys_faccessat(struct thread *td, struct faccessat_args *uap)
2105 {
2106 
2107 	return (kern_accessat(td, uap->fd, uap->path, UIO_USERSPACE, uap->flag,
2108 	    uap->amode));
2109 }
2110 
2111 int
2112 kern_accessat(struct thread *td, int fd, const char *path,
2113     enum uio_seg pathseg, int flag, int amode)
2114 {
2115 	struct ucred *cred, *usecred;
2116 	struct vnode *vp;
2117 	struct nameidata nd;
2118 	int error;
2119 
2120 	if ((flag & ~(AT_EACCESS | AT_RESOLVE_BENEATH | AT_EMPTY_PATH)) != 0)
2121 		return (EINVAL);
2122 	if (amode != F_OK && (amode & ~(R_OK | W_OK | X_OK)) != 0)
2123 		return (EINVAL);
2124 
2125 	/*
2126 	 * Create and modify a temporary credential instead of one that
2127 	 * is potentially shared (if we need one).
2128 	 */
2129 	cred = td->td_ucred;
2130 	if ((flag & AT_EACCESS) == 0 &&
2131 	    ((cred->cr_uid != cred->cr_ruid ||
2132 	    cred->cr_rgid != cred->cr_groups[0]))) {
2133 		usecred = crdup(cred);
2134 		usecred->cr_uid = cred->cr_ruid;
2135 		usecred->cr_groups[0] = cred->cr_rgid;
2136 		td->td_ucred = usecred;
2137 	} else
2138 		usecred = cred;
2139 	AUDIT_ARG_VALUE(amode);
2140 	NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF |
2141 	    AUDITVNODE1 | at2cnpflags(flag, AT_RESOLVE_BENEATH |
2142 	    AT_EMPTY_PATH), pathseg, path, fd, &cap_fstat_rights);
2143 	if ((error = namei(&nd)) != 0)
2144 		goto out;
2145 	vp = nd.ni_vp;
2146 
2147 	error = vn_access(vp, amode, usecred, td);
2148 	NDFREE_PNBUF(&nd);
2149 	vput(vp);
2150 out:
2151 	if (usecred != cred) {
2152 		td->td_ucred = cred;
2153 		crfree(usecred);
2154 	}
2155 	return (error);
2156 }
2157 
2158 /*
2159  * Check access permissions using "effective" credentials.
2160  */
2161 #ifndef _SYS_SYSPROTO_H_
2162 struct eaccess_args {
2163 	char	*path;
2164 	int	amode;
2165 };
2166 #endif
2167 int
2168 sys_eaccess(struct thread *td, struct eaccess_args *uap)
2169 {
2170 
2171 	return (kern_accessat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
2172 	    AT_EACCESS, uap->amode));
2173 }
2174 
2175 #if defined(COMPAT_43)
2176 /*
2177  * Get file status; this version follows links.
2178  */
2179 #ifndef _SYS_SYSPROTO_H_
2180 struct ostat_args {
2181 	char	*path;
2182 	struct ostat *ub;
2183 };
2184 #endif
2185 int
2186 ostat(struct thread *td, struct ostat_args *uap)
2187 {
2188 	struct stat sb;
2189 	struct ostat osb;
2190 	int error;
2191 
2192 	error = kern_statat(td, 0, AT_FDCWD, uap->path, UIO_USERSPACE, &sb);
2193 	if (error != 0)
2194 		return (error);
2195 	cvtstat(&sb, &osb);
2196 	return (copyout(&osb, uap->ub, sizeof (osb)));
2197 }
2198 
2199 /*
2200  * Get file status; this version does not follow links.
2201  */
2202 #ifndef _SYS_SYSPROTO_H_
2203 struct olstat_args {
2204 	char	*path;
2205 	struct ostat *ub;
2206 };
2207 #endif
2208 int
2209 olstat(struct thread *td, struct olstat_args *uap)
2210 {
2211 	struct stat sb;
2212 	struct ostat osb;
2213 	int error;
2214 
2215 	error = kern_statat(td, AT_SYMLINK_NOFOLLOW, AT_FDCWD, uap->path,
2216 	    UIO_USERSPACE, &sb);
2217 	if (error != 0)
2218 		return (error);
2219 	cvtstat(&sb, &osb);
2220 	return (copyout(&osb, uap->ub, sizeof (osb)));
2221 }
2222 
2223 /*
2224  * Convert from an old to a new stat structure.
2225  * XXX: many values are blindly truncated.
2226  */
2227 void
2228 cvtstat(struct stat *st, struct ostat *ost)
2229 {
2230 
2231 	bzero(ost, sizeof(*ost));
2232 	ost->st_dev = st->st_dev;
2233 	ost->st_ino = st->st_ino;
2234 	ost->st_mode = st->st_mode;
2235 	ost->st_nlink = st->st_nlink;
2236 	ost->st_uid = st->st_uid;
2237 	ost->st_gid = st->st_gid;
2238 	ost->st_rdev = st->st_rdev;
2239 	ost->st_size = MIN(st->st_size, INT32_MAX);
2240 	ost->st_atim = st->st_atim;
2241 	ost->st_mtim = st->st_mtim;
2242 	ost->st_ctim = st->st_ctim;
2243 	ost->st_blksize = st->st_blksize;
2244 	ost->st_blocks = st->st_blocks;
2245 	ost->st_flags = st->st_flags;
2246 	ost->st_gen = st->st_gen;
2247 }
2248 #endif /* COMPAT_43 */
2249 
2250 #if defined(COMPAT_43) || defined(COMPAT_FREEBSD11)
2251 int ino64_trunc_error;
2252 SYSCTL_INT(_vfs, OID_AUTO, ino64_trunc_error, CTLFLAG_RW,
2253     &ino64_trunc_error, 0,
2254     "Error on truncation of device, file or inode number, or link count");
2255 
2256 int
2257 freebsd11_cvtstat(struct stat *st, struct freebsd11_stat *ost)
2258 {
2259 
2260 	ost->st_dev = st->st_dev;
2261 	if (ost->st_dev != st->st_dev) {
2262 		switch (ino64_trunc_error) {
2263 		default:
2264 			/*
2265 			 * Since dev_t is almost raw, don't clamp to the
2266 			 * maximum for case 2, but ignore the error.
2267 			 */
2268 			break;
2269 		case 1:
2270 			return (EOVERFLOW);
2271 		}
2272 	}
2273 	ost->st_ino = st->st_ino;
2274 	if (ost->st_ino != st->st_ino) {
2275 		switch (ino64_trunc_error) {
2276 		default:
2277 		case 0:
2278 			break;
2279 		case 1:
2280 			return (EOVERFLOW);
2281 		case 2:
2282 			ost->st_ino = UINT32_MAX;
2283 			break;
2284 		}
2285 	}
2286 	ost->st_mode = st->st_mode;
2287 	ost->st_nlink = st->st_nlink;
2288 	if (ost->st_nlink != st->st_nlink) {
2289 		switch (ino64_trunc_error) {
2290 		default:
2291 		case 0:
2292 			break;
2293 		case 1:
2294 			return (EOVERFLOW);
2295 		case 2:
2296 			ost->st_nlink = UINT16_MAX;
2297 			break;
2298 		}
2299 	}
2300 	ost->st_uid = st->st_uid;
2301 	ost->st_gid = st->st_gid;
2302 	ost->st_rdev = st->st_rdev;
2303 	if (ost->st_rdev != st->st_rdev) {
2304 		switch (ino64_trunc_error) {
2305 		default:
2306 			break;
2307 		case 1:
2308 			return (EOVERFLOW);
2309 		}
2310 	}
2311 	ost->st_atim = st->st_atim;
2312 	ost->st_mtim = st->st_mtim;
2313 	ost->st_ctim = st->st_ctim;
2314 	ost->st_size = st->st_size;
2315 	ost->st_blocks = st->st_blocks;
2316 	ost->st_blksize = st->st_blksize;
2317 	ost->st_flags = st->st_flags;
2318 	ost->st_gen = st->st_gen;
2319 	ost->st_lspare = 0;
2320 	ost->st_birthtim = st->st_birthtim;
2321 	bzero((char *)&ost->st_birthtim + sizeof(ost->st_birthtim),
2322 	    sizeof(*ost) - offsetof(struct freebsd11_stat,
2323 	    st_birthtim) - sizeof(ost->st_birthtim));
2324 	return (0);
2325 }
2326 
2327 int
2328 freebsd11_stat(struct thread *td, struct freebsd11_stat_args* uap)
2329 {
2330 	struct stat sb;
2331 	struct freebsd11_stat osb;
2332 	int error;
2333 
2334 	error = kern_statat(td, 0, AT_FDCWD, uap->path, UIO_USERSPACE, &sb);
2335 	if (error != 0)
2336 		return (error);
2337 	error = freebsd11_cvtstat(&sb, &osb);
2338 	if (error == 0)
2339 		error = copyout(&osb, uap->ub, sizeof(osb));
2340 	return (error);
2341 }
2342 
2343 int
2344 freebsd11_lstat(struct thread *td, struct freebsd11_lstat_args* uap)
2345 {
2346 	struct stat sb;
2347 	struct freebsd11_stat osb;
2348 	int error;
2349 
2350 	error = kern_statat(td, AT_SYMLINK_NOFOLLOW, AT_FDCWD, uap->path,
2351 	    UIO_USERSPACE, &sb);
2352 	if (error != 0)
2353 		return (error);
2354 	error = freebsd11_cvtstat(&sb, &osb);
2355 	if (error == 0)
2356 		error = copyout(&osb, uap->ub, sizeof(osb));
2357 	return (error);
2358 }
2359 
2360 int
2361 freebsd11_fhstat(struct thread *td, struct freebsd11_fhstat_args* uap)
2362 {
2363 	struct fhandle fh;
2364 	struct stat sb;
2365 	struct freebsd11_stat osb;
2366 	int error;
2367 
2368 	error = copyin(uap->u_fhp, &fh, sizeof(fhandle_t));
2369 	if (error != 0)
2370 		return (error);
2371 	error = kern_fhstat(td, fh, &sb);
2372 	if (error != 0)
2373 		return (error);
2374 	error = freebsd11_cvtstat(&sb, &osb);
2375 	if (error == 0)
2376 		error = copyout(&osb, uap->sb, sizeof(osb));
2377 	return (error);
2378 }
2379 
2380 int
2381 freebsd11_fstatat(struct thread *td, struct freebsd11_fstatat_args* uap)
2382 {
2383 	struct stat sb;
2384 	struct freebsd11_stat osb;
2385 	int error;
2386 
2387 	error = kern_statat(td, uap->flag, uap->fd, uap->path,
2388 	    UIO_USERSPACE, &sb);
2389 	if (error != 0)
2390 		return (error);
2391 	error = freebsd11_cvtstat(&sb, &osb);
2392 	if (error == 0)
2393 		error = copyout(&osb, uap->buf, sizeof(osb));
2394 	return (error);
2395 }
2396 #endif	/* COMPAT_FREEBSD11 */
2397 
2398 /*
2399  * Get file status
2400  */
2401 #ifndef _SYS_SYSPROTO_H_
2402 struct fstatat_args {
2403 	int	fd;
2404 	char	*path;
2405 	struct stat	*buf;
2406 	int	flag;
2407 }
2408 #endif
2409 int
2410 sys_fstatat(struct thread *td, struct fstatat_args *uap)
2411 {
2412 	struct stat sb;
2413 	int error;
2414 
2415 	error = kern_statat(td, uap->flag, uap->fd, uap->path,
2416 	    UIO_USERSPACE, &sb);
2417 	if (error == 0)
2418 		error = copyout(&sb, uap->buf, sizeof (sb));
2419 	return (error);
2420 }
2421 
2422 int
2423 kern_statat(struct thread *td, int flag, int fd, const char *path,
2424     enum uio_seg pathseg, struct stat *sbp)
2425 {
2426 	struct nameidata nd;
2427 	int error;
2428 
2429 	if ((flag & ~(AT_SYMLINK_NOFOLLOW | AT_RESOLVE_BENEATH |
2430 	    AT_EMPTY_PATH)) != 0)
2431 		return (EINVAL);
2432 
2433 	NDINIT_ATRIGHTS(&nd, LOOKUP, at2cnpflags(flag, AT_RESOLVE_BENEATH |
2434 	    AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH) | LOCKSHARED | LOCKLEAF |
2435 	    AUDITVNODE1, pathseg, path, fd, &cap_fstat_rights);
2436 
2437 	if ((error = namei(&nd)) != 0) {
2438 		if (error == ENOTDIR &&
2439 		    (nd.ni_resflags & NIRES_EMPTYPATH) != 0)
2440 			error = kern_fstat(td, fd, sbp);
2441 		return (error);
2442 	}
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,
4901 	    inoffp != NULL ? &cap_pread_rights : &cap_read_rights, &infp);
4902 	if (error != 0)
4903 		goto out;
4904 	if (infp->f_ops == &badfileops) {
4905 		error = EBADF;
4906 		goto out;
4907 	}
4908 	if (infp->f_vnode == NULL) {
4909 		error = EINVAL;
4910 		goto out;
4911 	}
4912 	error = fget_write(td, outfd,
4913 	    outoffp != NULL ? &cap_pwrite_rights : &cap_write_rights, &outfp);
4914 	if (error != 0)
4915 		goto out;
4916 	if (outfp->f_ops == &badfileops) {
4917 		error = EBADF;
4918 		goto out;
4919 	}
4920 	if (outfp->f_vnode == NULL) {
4921 		error = EINVAL;
4922 		goto out;
4923 	}
4924 
4925 	/* Set the offset pointers to the correct place. */
4926 	if (inoffp == NULL)
4927 		inoffp = &infp->f_offset;
4928 	if (outoffp == NULL)
4929 		outoffp = &outfp->f_offset;
4930 	savinoff = *inoffp;
4931 	savoutoff = *outoffp;
4932 
4933 	invp = infp->f_vnode;
4934 	outvp = outfp->f_vnode;
4935 	/* Sanity check the f_flag bits. */
4936 	if ((outfp->f_flag & (FWRITE | FAPPEND)) != FWRITE ||
4937 	    (infp->f_flag & FREAD) == 0) {
4938 		error = EBADF;
4939 		goto out;
4940 	}
4941 
4942 	/* If len == 0, just return 0. */
4943 	if (len == 0)
4944 		goto out;
4945 
4946 	/*
4947 	 * If infp and outfp refer to the same file, the byte ranges cannot
4948 	 * overlap.
4949 	 */
4950 	if (invp == outvp && ((savinoff <= savoutoff && savinoff + len >
4951 	    savoutoff) || (savinoff > savoutoff && savoutoff + len >
4952 	    savinoff))) {
4953 		error = EINVAL;
4954 		goto out;
4955 	}
4956 
4957 	/* Range lock the byte ranges for both invp and outvp. */
4958 	for (;;) {
4959 		rl_wcookie = vn_rangelock_wlock(outvp, *outoffp, *outoffp +
4960 		    len);
4961 		rl_rcookie = vn_rangelock_tryrlock(invp, *inoffp, *inoffp +
4962 		    len);
4963 		if (rl_rcookie != NULL)
4964 			break;
4965 		vn_rangelock_unlock(outvp, rl_wcookie);
4966 		rl_rcookie = vn_rangelock_rlock(invp, *inoffp, *inoffp + len);
4967 		vn_rangelock_unlock(invp, rl_rcookie);
4968 	}
4969 
4970 	retlen = len;
4971 	error = vn_copy_file_range(invp, inoffp, outvp, outoffp, &retlen,
4972 	    flags, infp->f_cred, outfp->f_cred, td);
4973 out:
4974 	if (rl_rcookie != NULL)
4975 		vn_rangelock_unlock(invp, rl_rcookie);
4976 	if (rl_wcookie != NULL)
4977 		vn_rangelock_unlock(outvp, rl_wcookie);
4978 	if (savinoff != -1 && (error == EINTR || error == ERESTART)) {
4979 		*inoffp = savinoff;
4980 		*outoffp = savoutoff;
4981 	}
4982 	if (outfp != NULL)
4983 		fdrop(outfp, td);
4984 	if (infp != NULL)
4985 		fdrop(infp, td);
4986 	td->td_retval[0] = retlen;
4987 	return (error);
4988 }
4989 
4990 int
4991 sys_copy_file_range(struct thread *td, struct copy_file_range_args *uap)
4992 {
4993 	off_t inoff, outoff, *inoffp, *outoffp;
4994 	int error;
4995 
4996 	inoffp = outoffp = NULL;
4997 	if (uap->inoffp != NULL) {
4998 		error = copyin(uap->inoffp, &inoff, sizeof(off_t));
4999 		if (error != 0)
5000 			return (error);
5001 		inoffp = &inoff;
5002 	}
5003 	if (uap->outoffp != NULL) {
5004 		error = copyin(uap->outoffp, &outoff, sizeof(off_t));
5005 		if (error != 0)
5006 			return (error);
5007 		outoffp = &outoff;
5008 	}
5009 	error = kern_copy_file_range(td, uap->infd, inoffp, uap->outfd,
5010 	    outoffp, uap->len, uap->flags);
5011 	if (error == 0 && uap->inoffp != NULL)
5012 		error = copyout(inoffp, uap->inoffp, sizeof(off_t));
5013 	if (error == 0 && uap->outoffp != NULL)
5014 		error = copyout(outoffp, uap->outoffp, sizeof(off_t));
5015 	return (error);
5016 }
5017