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