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