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