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