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