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