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