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