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