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