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