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