]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/vfs_syscalls.c
socket: Implement SO_RERROR
[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                 return (error);
2443         error = VOP_STAT(nd.ni_vp, sbp, td->td_ucred, NOCRED, td);
2444         if (error == 0) {
2445                 if (__predict_false(hook != NULL))
2446                         hook(nd.ni_vp, sbp);
2447         }
2448         NDFREE_NOTHING(&nd);
2449         vput(nd.ni_vp);
2450 #ifdef __STAT_TIME_T_EXT
2451         sbp->st_atim_ext = 0;
2452         sbp->st_mtim_ext = 0;
2453         sbp->st_ctim_ext = 0;
2454         sbp->st_btim_ext = 0;
2455 #endif
2456 #ifdef KTRACE
2457         if (KTRPOINT(td, KTR_STRUCT))
2458                 ktrstat_error(sbp, error);
2459 #endif
2460         return (error);
2461 }
2462
2463 #if defined(COMPAT_FREEBSD11)
2464 /*
2465  * Implementation of the NetBSD [l]stat() functions.
2466  */
2467 void
2468 freebsd11_cvtnstat(struct stat *sb, struct nstat *nsb)
2469 {
2470
2471         bzero(nsb, sizeof(*nsb));
2472         nsb->st_dev = sb->st_dev;
2473         nsb->st_ino = sb->st_ino;
2474         nsb->st_mode = sb->st_mode;
2475         nsb->st_nlink = sb->st_nlink;
2476         nsb->st_uid = sb->st_uid;
2477         nsb->st_gid = sb->st_gid;
2478         nsb->st_rdev = sb->st_rdev;
2479         nsb->st_atim = sb->st_atim;
2480         nsb->st_mtim = sb->st_mtim;
2481         nsb->st_ctim = sb->st_ctim;
2482         nsb->st_size = sb->st_size;
2483         nsb->st_blocks = sb->st_blocks;
2484         nsb->st_blksize = sb->st_blksize;
2485         nsb->st_flags = sb->st_flags;
2486         nsb->st_gen = sb->st_gen;
2487         nsb->st_birthtim = sb->st_birthtim;
2488 }
2489
2490 #ifndef _SYS_SYSPROTO_H_
2491 struct freebsd11_nstat_args {
2492         char    *path;
2493         struct nstat *ub;
2494 };
2495 #endif
2496 int
2497 freebsd11_nstat(struct thread *td, struct freebsd11_nstat_args *uap)
2498 {
2499         struct stat sb;
2500         struct nstat nsb;
2501         int error;
2502
2503         error = kern_statat(td, 0, AT_FDCWD, uap->path, UIO_USERSPACE,
2504             &sb, NULL);
2505         if (error != 0)
2506                 return (error);
2507         freebsd11_cvtnstat(&sb, &nsb);
2508         return (copyout(&nsb, uap->ub, sizeof (nsb)));
2509 }
2510
2511 /*
2512  * NetBSD lstat.  Get file status; this version does not follow links.
2513  */
2514 #ifndef _SYS_SYSPROTO_H_
2515 struct freebsd11_nlstat_args {
2516         char    *path;
2517         struct nstat *ub;
2518 };
2519 #endif
2520 int
2521 freebsd11_nlstat(struct thread *td, struct freebsd11_nlstat_args *uap)
2522 {
2523         struct stat sb;
2524         struct nstat nsb;
2525         int error;
2526
2527         error = kern_statat(td, AT_SYMLINK_NOFOLLOW, AT_FDCWD, uap->path,
2528             UIO_USERSPACE, &sb, NULL);
2529         if (error != 0)
2530                 return (error);
2531         freebsd11_cvtnstat(&sb, &nsb);
2532         return (copyout(&nsb, uap->ub, sizeof (nsb)));
2533 }
2534 #endif /* COMPAT_FREEBSD11 */
2535
2536 /*
2537  * Get configurable pathname variables.
2538  */
2539 #ifndef _SYS_SYSPROTO_H_
2540 struct pathconf_args {
2541         char    *path;
2542         int     name;
2543 };
2544 #endif
2545 int
2546 sys_pathconf(struct thread *td, struct pathconf_args *uap)
2547 {
2548         long value;
2549         int error;
2550
2551         error = kern_pathconf(td, uap->path, UIO_USERSPACE, uap->name, FOLLOW,
2552             &value);
2553         if (error == 0)
2554                 td->td_retval[0] = value;
2555         return (error);
2556 }
2557
2558 #ifndef _SYS_SYSPROTO_H_
2559 struct lpathconf_args {
2560         char    *path;
2561         int     name;
2562 };
2563 #endif
2564 int
2565 sys_lpathconf(struct thread *td, struct lpathconf_args *uap)
2566 {
2567         long value;
2568         int error;
2569
2570         error = kern_pathconf(td, uap->path, UIO_USERSPACE, uap->name,
2571             NOFOLLOW, &value);
2572         if (error == 0)
2573                 td->td_retval[0] = value;
2574         return (error);
2575 }
2576
2577 int
2578 kern_pathconf(struct thread *td, const char *path, enum uio_seg pathseg,
2579     int name, u_long flags, long *valuep)
2580 {
2581         struct nameidata nd;
2582         int error;
2583
2584         NDINIT(&nd, LOOKUP, LOCKSHARED | LOCKLEAF | AUDITVNODE1 | flags,
2585             pathseg, path, td);
2586         if ((error = namei(&nd)) != 0)
2587                 return (error);
2588         NDFREE_NOTHING(&nd);
2589
2590         error = VOP_PATHCONF(nd.ni_vp, name, valuep);
2591         vput(nd.ni_vp);
2592         return (error);
2593 }
2594
2595 /*
2596  * Return target name of a symbolic link.
2597  */
2598 #ifndef _SYS_SYSPROTO_H_
2599 struct readlink_args {
2600         char    *path;
2601         char    *buf;
2602         size_t  count;
2603 };
2604 #endif
2605 int
2606 sys_readlink(struct thread *td, struct readlink_args *uap)
2607 {
2608
2609         return (kern_readlinkat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
2610             uap->buf, UIO_USERSPACE, uap->count));
2611 }
2612 #ifndef _SYS_SYSPROTO_H_
2613 struct readlinkat_args {
2614         int     fd;
2615         char    *path;
2616         char    *buf;
2617         size_t  bufsize;
2618 };
2619 #endif
2620 int
2621 sys_readlinkat(struct thread *td, struct readlinkat_args *uap)
2622 {
2623
2624         return (kern_readlinkat(td, uap->fd, uap->path, UIO_USERSPACE,
2625             uap->buf, UIO_USERSPACE, uap->bufsize));
2626 }
2627
2628 int
2629 kern_readlinkat(struct thread *td, int fd, const char *path,
2630     enum uio_seg pathseg, char *buf, enum uio_seg bufseg, size_t count)
2631 {
2632         struct vnode *vp;
2633         struct nameidata nd;
2634         int error;
2635
2636         if (count > IOSIZE_MAX)
2637                 return (EINVAL);
2638
2639         NDINIT_AT(&nd, LOOKUP, NOFOLLOW | LOCKSHARED | LOCKLEAF | AUDITVNODE1,
2640             pathseg, path, fd, td);
2641
2642         if ((error = namei(&nd)) != 0)
2643                 return (error);
2644         NDFREE_NOTHING(&nd);
2645         vp = nd.ni_vp;
2646
2647         error = kern_readlink_vp(vp, buf, bufseg, count, td);
2648         vput(vp);
2649
2650         return (error);
2651 }
2652
2653 /*
2654  * Helper function to readlink from a vnode
2655  */
2656 static int
2657 kern_readlink_vp(struct vnode *vp, char *buf, enum uio_seg bufseg, size_t count,
2658     struct thread *td)
2659 {
2660         struct iovec aiov;
2661         struct uio auio;
2662         int error;
2663
2664         ASSERT_VOP_LOCKED(vp, "kern_readlink_vp(): vp not locked");
2665 #ifdef MAC
2666         error = mac_vnode_check_readlink(td->td_ucred, vp);
2667         if (error != 0)
2668                 return (error);
2669 #endif
2670         if (vp->v_type != VLNK && (vp->v_vflag & VV_READLINK) == 0)
2671                 return (EINVAL);
2672
2673         aiov.iov_base = buf;
2674         aiov.iov_len = count;
2675         auio.uio_iov = &aiov;
2676         auio.uio_iovcnt = 1;
2677         auio.uio_offset = 0;
2678         auio.uio_rw = UIO_READ;
2679         auio.uio_segflg = bufseg;
2680         auio.uio_td = td;
2681         auio.uio_resid = count;
2682         error = VOP_READLINK(vp, &auio, td->td_ucred);
2683         td->td_retval[0] = count - auio.uio_resid;
2684         return (error);
2685 }
2686
2687 /*
2688  * Common implementation code for chflags() and fchflags().
2689  */
2690 static int
2691 setfflags(struct thread *td, struct vnode *vp, u_long flags)
2692 {
2693         struct mount *mp;
2694         struct vattr vattr;
2695         int error;
2696
2697         /* We can't support the value matching VNOVAL. */
2698         if (flags == VNOVAL)
2699                 return (EOPNOTSUPP);
2700
2701         /*
2702          * Prevent non-root users from setting flags on devices.  When
2703          * a device is reused, users can retain ownership of the device
2704          * if they are allowed to set flags and programs assume that
2705          * chown can't fail when done as root.
2706          */
2707         if (vp->v_type == VCHR || vp->v_type == VBLK) {
2708                 error = priv_check(td, PRIV_VFS_CHFLAGS_DEV);
2709                 if (error != 0)
2710                         return (error);
2711         }
2712
2713         if ((error = vn_start_write(vp, &mp, V_WAIT | PCATCH)) != 0)
2714                 return (error);
2715         VATTR_NULL(&vattr);
2716         vattr.va_flags = flags;
2717         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2718 #ifdef MAC
2719         error = mac_vnode_check_setflags(td->td_ucred, vp, vattr.va_flags);
2720         if (error == 0)
2721 #endif
2722                 error = VOP_SETATTR(vp, &vattr, td->td_ucred);
2723         VOP_UNLOCK(vp);
2724         vn_finished_write(mp);
2725         return (error);
2726 }
2727
2728 /*
2729  * Change flags of a file given a path name.
2730  */
2731 #ifndef _SYS_SYSPROTO_H_
2732 struct chflags_args {
2733         const char *path;
2734         u_long  flags;
2735 };
2736 #endif
2737 int
2738 sys_chflags(struct thread *td, struct chflags_args *uap)
2739 {
2740
2741         return (kern_chflagsat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
2742             uap->flags, 0));
2743 }
2744
2745 #ifndef _SYS_SYSPROTO_H_
2746 struct chflagsat_args {
2747         int     fd;
2748         const char *path;
2749         u_long  flags;
2750         int     atflag;
2751 }
2752 #endif
2753 int
2754 sys_chflagsat(struct thread *td, struct chflagsat_args *uap)
2755 {
2756
2757         if ((uap->atflag & ~(AT_SYMLINK_NOFOLLOW | AT_RESOLVE_BENEATH |
2758             AT_EMPTY_PATH)) != 0)
2759                 return (EINVAL);
2760
2761         return (kern_chflagsat(td, uap->fd, uap->path, UIO_USERSPACE,
2762             uap->flags, uap->atflag));
2763 }
2764
2765 /*
2766  * Same as chflags() but doesn't follow symlinks.
2767  */
2768 #ifndef _SYS_SYSPROTO_H_
2769 struct lchflags_args {
2770         const char *path;
2771         u_long flags;
2772 };
2773 #endif
2774 int
2775 sys_lchflags(struct thread *td, struct lchflags_args *uap)
2776 {
2777
2778         return (kern_chflagsat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
2779             uap->flags, AT_SYMLINK_NOFOLLOW));
2780 }
2781
2782 static int
2783 kern_chflagsat(struct thread *td, int fd, const char *path,
2784     enum uio_seg pathseg, u_long flags, int atflag)
2785 {
2786         struct nameidata nd;
2787         int error;
2788
2789         AUDIT_ARG_FFLAGS(flags);
2790         NDINIT_ATRIGHTS(&nd, LOOKUP, at2cnpflags(atflag, AT_SYMLINK_NOFOLLOW |
2791             AT_RESOLVE_BENEATH | AT_EMPTY_PATH) | AUDITVNODE1, pathseg, path,
2792             fd, &cap_fchflags_rights, td);
2793         if ((error = namei(&nd)) != 0)
2794                 return (error);
2795         NDFREE_NOTHING(&nd);
2796         error = setfflags(td, nd.ni_vp, flags);
2797         vrele(nd.ni_vp);
2798         return (error);
2799 }
2800
2801 /*
2802  * Change flags of a file given a file descriptor.
2803  */
2804 #ifndef _SYS_SYSPROTO_H_
2805 struct fchflags_args {
2806         int     fd;
2807         u_long  flags;
2808 };
2809 #endif
2810 int
2811 sys_fchflags(struct thread *td, struct fchflags_args *uap)
2812 {
2813         struct file *fp;
2814         int error;
2815
2816         AUDIT_ARG_FD(uap->fd);
2817         AUDIT_ARG_FFLAGS(uap->flags);
2818         error = getvnode(td, uap->fd, &cap_fchflags_rights,
2819             &fp);
2820         if (error != 0)
2821                 return (error);
2822 #ifdef AUDIT
2823         if (AUDITING_TD(td)) {
2824                 vn_lock(fp->f_vnode, LK_SHARED | LK_RETRY);
2825                 AUDIT_ARG_VNODE1(fp->f_vnode);
2826                 VOP_UNLOCK(fp->f_vnode);
2827         }
2828 #endif
2829         error = setfflags(td, fp->f_vnode, uap->flags);
2830         fdrop(fp, td);
2831         return (error);
2832 }
2833
2834 /*
2835  * Common implementation code for chmod(), lchmod() and fchmod().
2836  */
2837 int
2838 setfmode(struct thread *td, struct ucred *cred, struct vnode *vp, int mode)
2839 {
2840         struct mount *mp;
2841         struct vattr vattr;
2842         int error;
2843
2844         if ((error = vn_start_write(vp, &mp, V_WAIT | PCATCH)) != 0)
2845                 return (error);
2846         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2847         VATTR_NULL(&vattr);
2848         vattr.va_mode = mode & ALLPERMS;
2849 #ifdef MAC
2850         error = mac_vnode_check_setmode(cred, vp, vattr.va_mode);
2851         if (error == 0)
2852 #endif
2853                 error = VOP_SETATTR(vp, &vattr, cred);
2854         VOP_UNLOCK(vp);
2855         vn_finished_write(mp);
2856         return (error);
2857 }
2858
2859 /*
2860  * Change mode of a file given path name.
2861  */
2862 #ifndef _SYS_SYSPROTO_H_
2863 struct chmod_args {
2864         char    *path;
2865         int     mode;
2866 };
2867 #endif
2868 int
2869 sys_chmod(struct thread *td, struct chmod_args *uap)
2870 {
2871
2872         return (kern_fchmodat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
2873             uap->mode, 0));
2874 }
2875
2876 #ifndef _SYS_SYSPROTO_H_
2877 struct fchmodat_args {
2878         int     dirfd;
2879         char    *path;
2880         mode_t  mode;
2881         int     flag;
2882 }
2883 #endif
2884 int
2885 sys_fchmodat(struct thread *td, struct fchmodat_args *uap)
2886 {
2887
2888         if ((uap->flag & ~(AT_SYMLINK_NOFOLLOW | AT_RESOLVE_BENEATH |
2889             AT_EMPTY_PATH)) != 0)
2890                 return (EINVAL);
2891
2892         return (kern_fchmodat(td, uap->fd, uap->path, UIO_USERSPACE,
2893             uap->mode, uap->flag));
2894 }
2895
2896 /*
2897  * Change mode of a file given path name (don't follow links.)
2898  */
2899 #ifndef _SYS_SYSPROTO_H_
2900 struct lchmod_args {
2901         char    *path;
2902         int     mode;
2903 };
2904 #endif
2905 int
2906 sys_lchmod(struct thread *td, struct lchmod_args *uap)
2907 {
2908
2909         return (kern_fchmodat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
2910             uap->mode, AT_SYMLINK_NOFOLLOW));
2911 }
2912
2913 int
2914 kern_fchmodat(struct thread *td, int fd, const char *path,
2915     enum uio_seg pathseg, mode_t mode, int flag)
2916 {
2917         struct nameidata nd;
2918         int error;
2919
2920         AUDIT_ARG_MODE(mode);
2921         NDINIT_ATRIGHTS(&nd, LOOKUP, at2cnpflags(flag, AT_SYMLINK_NOFOLLOW |
2922             AT_RESOLVE_BENEATH | AT_EMPTY_PATH) | AUDITVNODE1, pathseg, path,
2923             fd, &cap_fchmod_rights, td);
2924         if ((error = namei(&nd)) != 0)
2925                 return (error);
2926         NDFREE_NOTHING(&nd);
2927         error = setfmode(td, td->td_ucred, nd.ni_vp, mode);
2928         vrele(nd.ni_vp);
2929         return (error);
2930 }
2931
2932 /*
2933  * Change mode of a file given a file descriptor.
2934  */
2935 #ifndef _SYS_SYSPROTO_H_
2936 struct fchmod_args {
2937         int     fd;
2938         int     mode;
2939 };
2940 #endif
2941 int
2942 sys_fchmod(struct thread *td, struct fchmod_args *uap)
2943 {
2944         struct file *fp;
2945         int error;
2946
2947         AUDIT_ARG_FD(uap->fd);
2948         AUDIT_ARG_MODE(uap->mode);
2949
2950         error = fget(td, uap->fd, &cap_fchmod_rights, &fp);
2951         if (error != 0)
2952                 return (error);
2953         error = fo_chmod(fp, uap->mode, td->td_ucred, td);
2954         fdrop(fp, td);
2955         return (error);
2956 }
2957
2958 /*
2959  * Common implementation for chown(), lchown(), and fchown()
2960  */
2961 int
2962 setfown(struct thread *td, struct ucred *cred, struct vnode *vp, uid_t uid,
2963     gid_t gid)
2964 {
2965         struct mount *mp;
2966         struct vattr vattr;
2967         int error;
2968
2969         if ((error = vn_start_write(vp, &mp, V_WAIT | PCATCH)) != 0)
2970                 return (error);
2971         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2972         VATTR_NULL(&vattr);
2973         vattr.va_uid = uid;
2974         vattr.va_gid = gid;
2975 #ifdef MAC
2976         error = mac_vnode_check_setowner(cred, vp, vattr.va_uid,
2977             vattr.va_gid);
2978         if (error == 0)
2979 #endif
2980                 error = VOP_SETATTR(vp, &vattr, cred);
2981         VOP_UNLOCK(vp);
2982         vn_finished_write(mp);
2983         return (error);
2984 }
2985
2986 /*
2987  * Set ownership given a path name.
2988  */
2989 #ifndef _SYS_SYSPROTO_H_
2990 struct chown_args {
2991         char    *path;
2992         int     uid;
2993         int     gid;
2994 };
2995 #endif
2996 int
2997 sys_chown(struct thread *td, struct chown_args *uap)
2998 {
2999
3000         return (kern_fchownat(td, AT_FDCWD, uap->path, UIO_USERSPACE, uap->uid,
3001             uap->gid, 0));
3002 }
3003
3004 #ifndef _SYS_SYSPROTO_H_
3005 struct fchownat_args {
3006         int fd;
3007         const char * path;
3008         uid_t uid;
3009         gid_t gid;
3010         int flag;
3011 };
3012 #endif
3013 int
3014 sys_fchownat(struct thread *td, struct fchownat_args *uap)
3015 {
3016
3017         if ((uap->flag & ~(AT_SYMLINK_NOFOLLOW | AT_RESOLVE_BENEATH |
3018             AT_EMPTY_PATH)) != 0)
3019                 return (EINVAL);
3020
3021         return (kern_fchownat(td, uap->fd, uap->path, UIO_USERSPACE, uap->uid,
3022             uap->gid, uap->flag));
3023 }
3024
3025 int
3026 kern_fchownat(struct thread *td, int fd, const char *path,
3027     enum uio_seg pathseg, int uid, int gid, int flag)
3028 {
3029         struct nameidata nd;
3030         int error;
3031
3032         AUDIT_ARG_OWNER(uid, gid);
3033         NDINIT_ATRIGHTS(&nd, LOOKUP, at2cnpflags(flag, AT_SYMLINK_NOFOLLOW |
3034             AT_RESOLVE_BENEATH | AT_EMPTY_PATH) | AUDITVNODE1, pathseg, path,
3035             fd, &cap_fchown_rights, td);
3036
3037         if ((error = namei(&nd)) != 0)
3038                 return (error);
3039         NDFREE_NOTHING(&nd);
3040         error = setfown(td, td->td_ucred, nd.ni_vp, uid, gid);
3041         vrele(nd.ni_vp);
3042         return (error);
3043 }
3044
3045 /*
3046  * Set ownership given a path name, do not cross symlinks.
3047  */
3048 #ifndef _SYS_SYSPROTO_H_
3049 struct lchown_args {
3050         char    *path;
3051         int     uid;
3052         int     gid;
3053 };
3054 #endif
3055 int
3056 sys_lchown(struct thread *td, struct lchown_args *uap)
3057 {
3058
3059         return (kern_fchownat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
3060             uap->uid, uap->gid, AT_SYMLINK_NOFOLLOW));
3061 }
3062
3063 /*
3064  * Set ownership given a file descriptor.
3065  */
3066 #ifndef _SYS_SYSPROTO_H_
3067 struct fchown_args {
3068         int     fd;
3069         int     uid;
3070         int     gid;
3071 };
3072 #endif
3073 int
3074 sys_fchown(struct thread *td, struct fchown_args *uap)
3075 {
3076         struct file *fp;
3077         int error;
3078
3079         AUDIT_ARG_FD(uap->fd);
3080         AUDIT_ARG_OWNER(uap->uid, uap->gid);
3081         error = fget(td, uap->fd, &cap_fchown_rights, &fp);
3082         if (error != 0)
3083                 return (error);
3084         error = fo_chown(fp, uap->uid, uap->gid, td->td_ucred, td);
3085         fdrop(fp, td);
3086         return (error);
3087 }
3088
3089 /*
3090  * Common implementation code for utimes(), lutimes(), and futimes().
3091  */
3092 static int
3093 getutimes(const struct timeval *usrtvp, enum uio_seg tvpseg,
3094     struct timespec *tsp)
3095 {
3096         struct timeval tv[2];
3097         const struct timeval *tvp;
3098         int error;
3099
3100         if (usrtvp == NULL) {
3101                 vfs_timestamp(&tsp[0]);
3102                 tsp[1] = tsp[0];
3103         } else {
3104                 if (tvpseg == UIO_SYSSPACE) {
3105                         tvp = usrtvp;
3106                 } else {
3107                         if ((error = copyin(usrtvp, tv, sizeof(tv))) != 0)
3108                                 return (error);
3109                         tvp = tv;
3110                 }
3111
3112                 if (tvp[0].tv_usec < 0 || tvp[0].tv_usec >= 1000000 ||
3113                     tvp[1].tv_usec < 0 || tvp[1].tv_usec >= 1000000)
3114                         return (EINVAL);
3115                 TIMEVAL_TO_TIMESPEC(&tvp[0], &tsp[0]);
3116                 TIMEVAL_TO_TIMESPEC(&tvp[1], &tsp[1]);
3117         }
3118         return (0);
3119 }
3120
3121 /*
3122  * Common implementation code for futimens(), utimensat().
3123  */
3124 #define UTIMENS_NULL    0x1
3125 #define UTIMENS_EXIT    0x2
3126 static int
3127 getutimens(const struct timespec *usrtsp, enum uio_seg tspseg,
3128     struct timespec *tsp, int *retflags)
3129 {
3130         struct timespec tsnow;
3131         int error;
3132
3133         vfs_timestamp(&tsnow);
3134         *retflags = 0;
3135         if (usrtsp == NULL) {
3136                 tsp[0] = tsnow;
3137                 tsp[1] = tsnow;
3138                 *retflags |= UTIMENS_NULL;
3139                 return (0);
3140         }
3141         if (tspseg == UIO_SYSSPACE) {
3142                 tsp[0] = usrtsp[0];
3143                 tsp[1] = usrtsp[1];
3144         } else if ((error = copyin(usrtsp, tsp, sizeof(*tsp) * 2)) != 0)
3145                 return (error);
3146         if (tsp[0].tv_nsec == UTIME_OMIT && tsp[1].tv_nsec == UTIME_OMIT)
3147                 *retflags |= UTIMENS_EXIT;
3148         if (tsp[0].tv_nsec == UTIME_NOW && tsp[1].tv_nsec == UTIME_NOW)
3149                 *retflags |= UTIMENS_NULL;
3150         if (tsp[0].tv_nsec == UTIME_OMIT)
3151                 tsp[0].tv_sec = VNOVAL;
3152         else if (tsp[0].tv_nsec == UTIME_NOW)
3153                 tsp[0] = tsnow;
3154         else if (tsp[0].tv_nsec < 0 || tsp[0].tv_nsec >= 1000000000L)
3155                 return (EINVAL);
3156         if (tsp[1].tv_nsec == UTIME_OMIT)
3157                 tsp[1].tv_sec = VNOVAL;
3158         else if (tsp[1].tv_nsec == UTIME_NOW)
3159                 tsp[1] = tsnow;
3160         else if (tsp[1].tv_nsec < 0 || tsp[1].tv_nsec >= 1000000000L)
3161                 return (EINVAL);
3162
3163         return (0);
3164 }
3165
3166 /*
3167  * Common implementation code for utimes(), lutimes(), futimes(), futimens(),
3168  * and utimensat().
3169  */
3170 static int
3171 setutimes(struct thread *td, struct vnode *vp, const struct timespec *ts,
3172     int numtimes, int nullflag)
3173 {
3174         struct mount *mp;
3175         struct vattr vattr;
3176         int error, setbirthtime;
3177
3178         if ((error = vn_start_write(vp, &mp, V_WAIT | PCATCH)) != 0)
3179                 return (error);
3180         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3181         setbirthtime = 0;
3182         if (numtimes < 3 && !VOP_GETATTR(vp, &vattr, td->td_ucred) &&
3183             timespeccmp(&ts[1], &vattr.va_birthtime, < ))
3184                 setbirthtime = 1;
3185         VATTR_NULL(&vattr);
3186         vattr.va_atime = ts[0];
3187         vattr.va_mtime = ts[1];
3188         if (setbirthtime)
3189                 vattr.va_birthtime = ts[1];
3190         if (numtimes > 2)
3191                 vattr.va_birthtime = ts[2];
3192         if (nullflag)
3193                 vattr.va_vaflags |= VA_UTIMES_NULL;
3194 #ifdef MAC
3195         error = mac_vnode_check_setutimes(td->td_ucred, vp, vattr.va_atime,
3196             vattr.va_mtime);
3197 #endif
3198         if (error == 0)
3199                 error = VOP_SETATTR(vp, &vattr, td->td_ucred);
3200         VOP_UNLOCK(vp);
3201         vn_finished_write(mp);
3202         return (error);
3203 }
3204
3205 /*
3206  * Set the access and modification times of a file.
3207  */
3208 #ifndef _SYS_SYSPROTO_H_
3209 struct utimes_args {
3210         char    *path;
3211         struct  timeval *tptr;
3212 };
3213 #endif
3214 int
3215 sys_utimes(struct thread *td, struct utimes_args *uap)
3216 {
3217
3218         return (kern_utimesat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
3219             uap->tptr, UIO_USERSPACE));
3220 }
3221
3222 #ifndef _SYS_SYSPROTO_H_
3223 struct futimesat_args {
3224         int fd;
3225         const char * path;
3226         const struct timeval * times;
3227 };
3228 #endif
3229 int
3230 sys_futimesat(struct thread *td, struct futimesat_args *uap)
3231 {
3232
3233         return (kern_utimesat(td, uap->fd, uap->path, UIO_USERSPACE,
3234             uap->times, UIO_USERSPACE));
3235 }
3236
3237 int
3238 kern_utimesat(struct thread *td, int fd, const char *path,
3239     enum uio_seg pathseg, struct timeval *tptr, enum uio_seg tptrseg)
3240 {
3241         struct nameidata nd;
3242         struct timespec ts[2];
3243         int error;
3244
3245         if ((error = getutimes(tptr, tptrseg, ts)) != 0)
3246                 return (error);
3247         NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | AUDITVNODE1, pathseg, path, fd,
3248             &cap_futimes_rights, td);
3249
3250         if ((error = namei(&nd)) != 0)
3251                 return (error);
3252         NDFREE_NOTHING(&nd);
3253         error = setutimes(td, nd.ni_vp, ts, 2, tptr == NULL);
3254         vrele(nd.ni_vp);
3255         return (error);
3256 }
3257
3258 /*
3259  * Set the access and modification times of a file.
3260  */
3261 #ifndef _SYS_SYSPROTO_H_
3262 struct lutimes_args {
3263         char    *path;
3264         struct  timeval *tptr;
3265 };
3266 #endif
3267 int
3268 sys_lutimes(struct thread *td, struct lutimes_args *uap)
3269 {
3270
3271         return (kern_lutimes(td, uap->path, UIO_USERSPACE, uap->tptr,
3272             UIO_USERSPACE));
3273 }
3274
3275 int
3276 kern_lutimes(struct thread *td, const char *path, enum uio_seg pathseg,
3277     struct timeval *tptr, enum uio_seg tptrseg)
3278 {
3279         struct timespec ts[2];
3280         struct nameidata nd;
3281         int error;
3282
3283         if ((error = getutimes(tptr, tptrseg, ts)) != 0)
3284                 return (error);
3285         NDINIT(&nd, LOOKUP, NOFOLLOW | AUDITVNODE1, pathseg, path, td);
3286         if ((error = namei(&nd)) != 0)
3287                 return (error);
3288         NDFREE_NOTHING(&nd);
3289         error = setutimes(td, nd.ni_vp, ts, 2, tptr == NULL);
3290         vrele(nd.ni_vp);
3291         return (error);
3292 }
3293
3294 /*
3295  * Set the access and modification times of a file.
3296  */
3297 #ifndef _SYS_SYSPROTO_H_
3298 struct futimes_args {
3299         int     fd;
3300         struct  timeval *tptr;
3301 };
3302 #endif
3303 int
3304 sys_futimes(struct thread *td, struct futimes_args *uap)
3305 {
3306
3307         return (kern_futimes(td, uap->fd, uap->tptr, UIO_USERSPACE));
3308 }
3309
3310 int
3311 kern_futimes(struct thread *td, int fd, struct timeval *tptr,
3312     enum uio_seg tptrseg)
3313 {
3314         struct timespec ts[2];
3315         struct file *fp;
3316         int error;
3317
3318         AUDIT_ARG_FD(fd);
3319         error = getutimes(tptr, tptrseg, ts);
3320         if (error != 0)
3321                 return (error);
3322         error = getvnode(td, fd, &cap_futimes_rights, &fp);
3323         if (error != 0)
3324                 return (error);
3325 #ifdef AUDIT
3326         if (AUDITING_TD(td)) {
3327                 vn_lock(fp->f_vnode, LK_SHARED | LK_RETRY);
3328                 AUDIT_ARG_VNODE1(fp->f_vnode);
3329                 VOP_UNLOCK(fp->f_vnode);
3330         }
3331 #endif
3332         error = setutimes(td, fp->f_vnode, ts, 2, tptr == NULL);
3333         fdrop(fp, td);
3334         return (error);
3335 }
3336
3337 int
3338 sys_futimens(struct thread *td, struct futimens_args *uap)
3339 {
3340
3341         return (kern_futimens(td, uap->fd, uap->times, UIO_USERSPACE));
3342 }
3343
3344 int
3345 kern_futimens(struct thread *td, int fd, struct timespec *tptr,
3346     enum uio_seg tptrseg)
3347 {
3348         struct timespec ts[2];
3349         struct file *fp;
3350         int error, flags;
3351
3352         AUDIT_ARG_FD(fd);
3353         error = getutimens(tptr, tptrseg, ts, &flags);
3354         if (error != 0)
3355                 return (error);
3356         if (flags & UTIMENS_EXIT)
3357                 return (0);
3358         error = getvnode(td, fd, &cap_futimes_rights, &fp);
3359         if (error != 0)
3360                 return (error);
3361 #ifdef AUDIT
3362         if (AUDITING_TD(td)) {
3363                 vn_lock(fp->f_vnode, LK_SHARED | LK_RETRY);
3364                 AUDIT_ARG_VNODE1(fp->f_vnode);
3365                 VOP_UNLOCK(fp->f_vnode);
3366         }
3367 #endif
3368         error = setutimes(td, fp->f_vnode, ts, 2, flags & UTIMENS_NULL);
3369         fdrop(fp, td);
3370         return (error);
3371 }
3372
3373 int
3374 sys_utimensat(struct thread *td, struct utimensat_args *uap)
3375 {
3376
3377         return (kern_utimensat(td, uap->fd, uap->path, UIO_USERSPACE,
3378             uap->times, UIO_USERSPACE, uap->flag));
3379 }
3380
3381 int
3382 kern_utimensat(struct thread *td, int fd, const char *path,
3383     enum uio_seg pathseg, struct timespec *tptr, enum uio_seg tptrseg,
3384     int flag)
3385 {
3386         struct nameidata nd;
3387         struct timespec ts[2];
3388         int error, flags;
3389
3390         if ((flag & ~(AT_SYMLINK_NOFOLLOW | AT_RESOLVE_BENEATH |
3391             AT_EMPTY_PATH)) != 0)
3392                 return (EINVAL);
3393
3394         if ((error = getutimens(tptr, tptrseg, ts, &flags)) != 0)
3395                 return (error);
3396         NDINIT_ATRIGHTS(&nd, LOOKUP, at2cnpflags(flag, AT_SYMLINK_NOFOLLOW |
3397             AT_RESOLVE_BENEATH | AT_EMPTY_PATH) | AUDITVNODE1,
3398             pathseg, path, fd, &cap_futimes_rights, td);
3399         if ((error = namei(&nd)) != 0)
3400                 return (error);
3401         /*
3402          * We are allowed to call namei() regardless of 2xUTIME_OMIT.
3403          * POSIX states:
3404          * "If both tv_nsec fields are UTIME_OMIT... EACCESS may be detected."
3405          * "Search permission is denied by a component of the path prefix."
3406          */
3407         NDFREE_NOTHING(&nd);
3408         if ((flags & UTIMENS_EXIT) == 0)
3409                 error = setutimes(td, nd.ni_vp, ts, 2, flags & UTIMENS_NULL);
3410         vrele(nd.ni_vp);
3411         return (error);
3412 }
3413
3414 /*
3415  * Truncate a file given its path name.
3416  */
3417 #ifndef _SYS_SYSPROTO_H_
3418 struct truncate_args {
3419         char    *path;
3420         int     pad;
3421         off_t   length;
3422 };
3423 #endif
3424 int
3425 sys_truncate(struct thread *td, struct truncate_args *uap)
3426 {
3427
3428         return (kern_truncate(td, uap->path, UIO_USERSPACE, uap->length));
3429 }
3430
3431 int
3432 kern_truncate(struct thread *td, const char *path, enum uio_seg pathseg,
3433     off_t length)
3434 {
3435         struct mount *mp;
3436         struct vnode *vp;
3437         void *rl_cookie;
3438         struct vattr vattr;
3439         struct nameidata nd;
3440         int error;
3441
3442         if (length < 0)
3443                 return (EINVAL);
3444         NDPREINIT(&nd);
3445 retry:
3446         NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, pathseg, path, td);
3447         if ((error = namei(&nd)) != 0)
3448                 return (error);
3449         vp = nd.ni_vp;
3450         rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
3451         if ((error = vn_start_write(vp, &mp, V_WAIT | PCATCH)) != 0) {
3452                 vn_rangelock_unlock(vp, rl_cookie);
3453                 vrele(vp);
3454                 return (error);
3455         }
3456         NDFREE(&nd, NDF_ONLY_PNBUF);
3457         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3458         if (vp->v_type == VDIR)
3459                 error = EISDIR;
3460 #ifdef MAC
3461         else if ((error = mac_vnode_check_write(td->td_ucred, NOCRED, vp))) {
3462         }
3463 #endif
3464         else if ((error = vn_writechk(vp)) == 0 &&
3465             (error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td)) == 0) {
3466                 VATTR_NULL(&vattr);
3467                 vattr.va_size = length;
3468                 error = VOP_SETATTR(vp, &vattr, td->td_ucred);
3469         }
3470         VOP_UNLOCK(vp);
3471         vn_finished_write(mp);
3472         vn_rangelock_unlock(vp, rl_cookie);
3473         vrele(vp);
3474         if (error == ERELOOKUP)
3475                 goto retry;
3476         return (error);
3477 }
3478
3479 #if defined(COMPAT_43)
3480 /*
3481  * Truncate a file given its path name.
3482  */
3483 #ifndef _SYS_SYSPROTO_H_
3484 struct otruncate_args {
3485         char    *path;
3486         long    length;
3487 };
3488 #endif
3489 int
3490 otruncate(struct thread *td, struct otruncate_args *uap)
3491 {
3492
3493         return (kern_truncate(td, uap->path, UIO_USERSPACE, uap->length));
3494 }
3495 #endif /* COMPAT_43 */
3496
3497 #if defined(COMPAT_FREEBSD6)
3498 /* Versions with the pad argument */
3499 int
3500 freebsd6_truncate(struct thread *td, struct freebsd6_truncate_args *uap)
3501 {
3502
3503         return (kern_truncate(td, uap->path, UIO_USERSPACE, uap->length));
3504 }
3505
3506 int
3507 freebsd6_ftruncate(struct thread *td, struct freebsd6_ftruncate_args *uap)
3508 {
3509
3510         return (kern_ftruncate(td, uap->fd, uap->length));
3511 }
3512 #endif
3513
3514 int
3515 kern_fsync(struct thread *td, int fd, bool fullsync)
3516 {
3517         struct vnode *vp;
3518         struct mount *mp;
3519         struct file *fp;
3520         int error, lock_flags;
3521
3522         AUDIT_ARG_FD(fd);
3523         error = getvnode(td, fd, &cap_fsync_rights, &fp);
3524         if (error != 0)
3525                 return (error);
3526         vp = fp->f_vnode;
3527 #if 0
3528         if (!fullsync)
3529                 /* XXXKIB: compete outstanding aio writes */;
3530 #endif
3531 retry:
3532         error = vn_start_write(vp, &mp, V_WAIT | PCATCH);
3533         if (error != 0)
3534                 goto drop;
3535         if (MNT_SHARED_WRITES(mp) ||
3536             ((mp == NULL) && MNT_SHARED_WRITES(vp->v_mount))) {
3537                 lock_flags = LK_SHARED;
3538         } else {
3539                 lock_flags = LK_EXCLUSIVE;
3540         }
3541         vn_lock(vp, lock_flags | LK_RETRY);
3542         AUDIT_ARG_VNODE1(vp);
3543         if (vp->v_object != NULL) {
3544                 VM_OBJECT_WLOCK(vp->v_object);
3545                 vm_object_page_clean(vp->v_object, 0, 0, 0);
3546                 VM_OBJECT_WUNLOCK(vp->v_object);
3547         }
3548         error = fullsync ? VOP_FSYNC(vp, MNT_WAIT, td) : VOP_FDATASYNC(vp, td);
3549         VOP_UNLOCK(vp);
3550         vn_finished_write(mp);
3551         if (error == ERELOOKUP)
3552                 goto retry;
3553 drop:
3554         fdrop(fp, td);
3555         return (error);
3556 }
3557
3558 /*
3559  * Sync an open file.
3560  */
3561 #ifndef _SYS_SYSPROTO_H_
3562 struct fsync_args {
3563         int     fd;
3564 };
3565 #endif
3566 int
3567 sys_fsync(struct thread *td, struct fsync_args *uap)
3568 {
3569
3570         return (kern_fsync(td, uap->fd, true));
3571 }
3572
3573 int
3574 sys_fdatasync(struct thread *td, struct fdatasync_args *uap)
3575 {
3576
3577         return (kern_fsync(td, uap->fd, false));
3578 }
3579
3580 /*
3581  * Rename files.  Source and destination must either both be directories, or
3582  * both not be directories.  If target is a directory, it must be empty.
3583  */
3584 #ifndef _SYS_SYSPROTO_H_
3585 struct rename_args {
3586         char    *from;
3587         char    *to;
3588 };
3589 #endif
3590 int
3591 sys_rename(struct thread *td, struct rename_args *uap)
3592 {
3593
3594         return (kern_renameat(td, AT_FDCWD, uap->from, AT_FDCWD,
3595             uap->to, UIO_USERSPACE));
3596 }
3597
3598 #ifndef _SYS_SYSPROTO_H_
3599 struct renameat_args {
3600         int     oldfd;
3601         char    *old;
3602         int     newfd;
3603         char    *new;
3604 };
3605 #endif
3606 int
3607 sys_renameat(struct thread *td, struct renameat_args *uap)
3608 {
3609
3610         return (kern_renameat(td, uap->oldfd, uap->old, uap->newfd, uap->new,
3611             UIO_USERSPACE));
3612 }
3613
3614 #ifdef MAC
3615 static int
3616 kern_renameat_mac(struct thread *td, int oldfd, const char *old, int newfd,
3617     const char *new, enum uio_seg pathseg, struct nameidata *fromnd)
3618 {
3619         int error;
3620
3621         NDINIT_ATRIGHTS(fromnd, DELETE, LOCKPARENT | LOCKLEAF | SAVESTART |
3622             AUDITVNODE1, pathseg, old, oldfd, &cap_renameat_source_rights, td);
3623         if ((error = namei(fromnd)) != 0)
3624                 return (error);
3625         error = mac_vnode_check_rename_from(td->td_ucred, fromnd->ni_dvp,
3626             fromnd->ni_vp, &fromnd->ni_cnd);
3627         VOP_UNLOCK(fromnd->ni_dvp);
3628         if (fromnd->ni_dvp != fromnd->ni_vp)
3629                 VOP_UNLOCK(fromnd->ni_vp);
3630         if (error != 0) {
3631                 NDFREE(fromnd, NDF_ONLY_PNBUF);
3632                 vrele(fromnd->ni_dvp);
3633                 vrele(fromnd->ni_vp);
3634                 if (fromnd->ni_startdir)
3635                         vrele(fromnd->ni_startdir);
3636         }
3637         return (error);
3638 }
3639 #endif
3640
3641 int
3642 kern_renameat(struct thread *td, int oldfd, const char *old, int newfd,
3643     const char *new, enum uio_seg pathseg)
3644 {
3645         struct mount *mp = NULL;
3646         struct vnode *tvp, *fvp, *tdvp;
3647         struct nameidata fromnd, tond;
3648         u_int64_t tondflags;
3649         int error;
3650
3651 again:
3652         bwillwrite();
3653 #ifdef MAC
3654         if (mac_vnode_check_rename_from_enabled()) {
3655                 error = kern_renameat_mac(td, oldfd, old, newfd, new, pathseg,
3656                     &fromnd);
3657                 if (error != 0)
3658                         return (error);
3659         } else {
3660 #endif
3661         NDINIT_ATRIGHTS(&fromnd, DELETE, WANTPARENT | SAVESTART | AUDITVNODE1,
3662             pathseg, old, oldfd, &cap_renameat_source_rights, td);
3663         if ((error = namei(&fromnd)) != 0)
3664                 return (error);
3665 #ifdef MAC
3666         }
3667 #endif
3668         fvp = fromnd.ni_vp;
3669         tondflags = LOCKPARENT | LOCKLEAF | NOCACHE | SAVESTART | AUDITVNODE2;
3670         if (fromnd.ni_vp->v_type == VDIR)
3671                 tondflags |= WILLBEDIR;
3672         NDINIT_ATRIGHTS(&tond, RENAME, tondflags, pathseg, new, newfd,
3673             &cap_renameat_target_rights, td);
3674         if ((error = namei(&tond)) != 0) {
3675                 /* Translate error code for rename("dir1", "dir2/."). */
3676                 if (error == EISDIR && fvp->v_type == VDIR)
3677                         error = EINVAL;
3678                 NDFREE(&fromnd, NDF_ONLY_PNBUF);
3679                 vrele(fromnd.ni_dvp);
3680                 vrele(fvp);
3681                 goto out1;
3682         }
3683         tdvp = tond.ni_dvp;
3684         tvp = tond.ni_vp;
3685         error = vn_start_write(fvp, &mp, V_NOWAIT);
3686         if (error != 0) {
3687                 NDFREE(&fromnd, NDF_ONLY_PNBUF);
3688                 NDFREE(&tond, NDF_ONLY_PNBUF);
3689                 if (tvp != NULL)
3690                         vput(tvp);
3691                 if (tdvp == tvp)
3692                         vrele(tdvp);
3693                 else
3694                         vput(tdvp);
3695                 vrele(fromnd.ni_dvp);
3696                 vrele(fvp);
3697                 vrele(tond.ni_startdir);
3698                 if (fromnd.ni_startdir != NULL)
3699                         vrele(fromnd.ni_startdir);
3700                 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
3701                 if (error != 0)
3702                         return (error);
3703                 goto again;
3704         }
3705         if (tvp != NULL) {
3706                 if (fvp->v_type == VDIR && tvp->v_type != VDIR) {
3707                         error = ENOTDIR;
3708                         goto out;
3709                 } else if (fvp->v_type != VDIR && tvp->v_type == VDIR) {
3710                         error = EISDIR;
3711                         goto out;
3712                 }
3713 #ifdef CAPABILITIES
3714                 if (newfd != AT_FDCWD && (tond.ni_resflags & NIRES_ABS) == 0) {
3715                         /*
3716                          * If the target already exists we require CAP_UNLINKAT
3717                          * from 'newfd', when newfd was used for the lookup.
3718                          */
3719                         error = cap_check(&tond.ni_filecaps.fc_rights,
3720                             &cap_unlinkat_rights);
3721                         if (error != 0)
3722                                 goto out;
3723                 }
3724 #endif
3725         }
3726         if (fvp == tdvp) {
3727                 error = EINVAL;
3728                 goto out;
3729         }
3730         /*
3731          * If the source is the same as the destination (that is, if they
3732          * are links to the same vnode), then there is nothing to do.
3733          */
3734         if (fvp == tvp)
3735                 error = ERESTART;
3736 #ifdef MAC
3737         else
3738                 error = mac_vnode_check_rename_to(td->td_ucred, tdvp,
3739                     tond.ni_vp, fromnd.ni_dvp == tdvp, &tond.ni_cnd);
3740 #endif
3741 out:
3742         if (error == 0) {
3743                 error = VOP_RENAME(fromnd.ni_dvp, fromnd.ni_vp, &fromnd.ni_cnd,
3744                     tond.ni_dvp, tond.ni_vp, &tond.ni_cnd);
3745                 NDFREE(&fromnd, NDF_ONLY_PNBUF);
3746                 NDFREE(&tond, NDF_ONLY_PNBUF);
3747         } else {
3748                 NDFREE(&fromnd, NDF_ONLY_PNBUF);
3749                 NDFREE(&tond, NDF_ONLY_PNBUF);
3750                 if (tvp != NULL)
3751                         vput(tvp);
3752                 if (tdvp == tvp)
3753                         vrele(tdvp);
3754                 else
3755                         vput(tdvp);
3756                 vrele(fromnd.ni_dvp);
3757                 vrele(fvp);
3758         }
3759         vrele(tond.ni_startdir);
3760         vn_finished_write(mp);
3761 out1:
3762         if (fromnd.ni_startdir)
3763                 vrele(fromnd.ni_startdir);
3764         if (error == ERESTART)
3765                 return (0);
3766         if (error == ERELOOKUP)
3767                 goto again;
3768         return (error);
3769 }
3770
3771 /*
3772  * Make a directory file.
3773  */
3774 #ifndef _SYS_SYSPROTO_H_
3775 struct mkdir_args {
3776         char    *path;
3777         int     mode;
3778 };
3779 #endif
3780 int
3781 sys_mkdir(struct thread *td, struct mkdir_args *uap)
3782 {
3783
3784         return (kern_mkdirat(td, AT_FDCWD, uap->path, UIO_USERSPACE,
3785             uap->mode));
3786 }
3787
3788 #ifndef _SYS_SYSPROTO_H_
3789 struct mkdirat_args {
3790         int     fd;
3791         char    *path;
3792         mode_t  mode;
3793 };
3794 #endif
3795 int
3796 sys_mkdirat(struct thread *td, struct mkdirat_args *uap)
3797 {
3798
3799         return (kern_mkdirat(td, uap->fd, uap->path, UIO_USERSPACE, uap->mode));
3800 }
3801
3802 int
3803 kern_mkdirat(struct thread *td, int fd, const char *path, enum uio_seg segflg,
3804     int mode)
3805 {
3806         struct mount *mp;
3807         struct vattr vattr;
3808         struct nameidata nd;
3809         int error;
3810
3811         AUDIT_ARG_MODE(mode);
3812         NDPREINIT(&nd);
3813 restart:
3814         bwillwrite();
3815         NDINIT_ATRIGHTS(&nd, CREATE, LOCKPARENT | SAVENAME | AUDITVNODE1 |
3816             NC_NOMAKEENTRY | NC_KEEPPOSENTRY | FAILIFEXISTS | WILLBEDIR,
3817             segflg, path, fd, &cap_mkdirat_rights, td);
3818         if ((error = namei(&nd)) != 0)
3819                 return (error);
3820         if (vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
3821                 NDFREE(&nd, NDF_ONLY_PNBUF);
3822                 vput(nd.ni_dvp);
3823                 if ((error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH)) != 0)
3824                         return (error);
3825                 goto restart;
3826         }
3827         VATTR_NULL(&vattr);
3828         vattr.va_type = VDIR;
3829         vattr.va_mode = (mode & ACCESSPERMS) &~ td->td_proc->p_pd->pd_cmask;
3830 #ifdef MAC
3831         error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
3832             &vattr);
3833         if (error != 0)
3834                 goto out;
3835 #endif
3836         error = VOP_MKDIR(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
3837 #ifdef MAC
3838 out:
3839 #endif
3840         NDFREE(&nd, NDF_ONLY_PNBUF);
3841         VOP_VPUT_PAIR(nd.ni_dvp, error == 0 ? &nd.ni_vp : NULL, true);
3842         vn_finished_write(mp);
3843         if (error == ERELOOKUP)
3844                 goto restart;
3845         return (error);
3846 }
3847
3848 /*
3849  * Remove a directory file.
3850  */
3851 #ifndef _SYS_SYSPROTO_H_
3852 struct rmdir_args {
3853         char    *path;
3854 };
3855 #endif
3856 int
3857 sys_rmdir(struct thread *td, struct rmdir_args *uap)
3858 {
3859
3860         return (kern_frmdirat(td, AT_FDCWD, uap->path, FD_NONE, UIO_USERSPACE,
3861             0));
3862 }
3863
3864 int
3865 kern_frmdirat(struct thread *td, int dfd, const char *path, int fd,
3866     enum uio_seg pathseg, int flag)
3867 {
3868         struct mount *mp;
3869         struct vnode *vp;
3870         struct file *fp;
3871         struct nameidata nd;
3872         cap_rights_t rights;
3873         int error;
3874
3875         fp = NULL;
3876         if (fd != FD_NONE) {
3877                 error = getvnode(td, fd, cap_rights_init_one(&rights,
3878                     CAP_LOOKUP), &fp);
3879                 if (error != 0)
3880                         return (error);
3881         }
3882
3883         NDPREINIT(&nd);
3884 restart:
3885         bwillwrite();
3886         NDINIT_ATRIGHTS(&nd, DELETE, LOCKPARENT | LOCKLEAF | AUDITVNODE1 |
3887             at2cnpflags(flag, AT_RESOLVE_BENEATH),
3888             pathseg, path, dfd, &cap_unlinkat_rights, td);
3889         if ((error = namei(&nd)) != 0)
3890                 goto fdout;
3891         vp = nd.ni_vp;
3892         if (vp->v_type != VDIR) {
3893                 error = ENOTDIR;
3894                 goto out;
3895         }
3896         /*
3897          * No rmdir "." please.
3898          */
3899         if (nd.ni_dvp == vp) {
3900                 error = EINVAL;
3901                 goto out;
3902         }
3903         /*
3904          * The root of a mounted filesystem cannot be deleted.
3905          */
3906         if (vp->v_vflag & VV_ROOT) {
3907                 error = EBUSY;
3908                 goto out;
3909         }
3910
3911         if (fp != NULL && fp->f_vnode != vp) {
3912                 if (VN_IS_DOOMED(fp->f_vnode))
3913                         error = EBADF;
3914                 else
3915                         error = EDEADLK;
3916                 goto out;
3917         }
3918
3919 #ifdef MAC
3920         error = mac_vnode_check_unlink(td->td_ucred, nd.ni_dvp, vp,
3921             &nd.ni_cnd);
3922         if (error != 0)
3923                 goto out;
3924 #endif
3925         if (vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
3926                 NDFREE(&nd, NDF_ONLY_PNBUF);
3927                 vput(vp);
3928                 if (nd.ni_dvp == vp)
3929                         vrele(nd.ni_dvp);
3930                 else
3931                         vput(nd.ni_dvp);
3932                 if ((error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH)) != 0)
3933                         goto fdout;
3934                 goto restart;
3935         }
3936         vfs_notify_upper(vp, VFS_NOTIFY_UPPER_UNLINK);
3937         error = VOP_RMDIR(nd.ni_dvp, nd.ni_vp, &nd.ni_cnd);
3938         vn_finished_write(mp);
3939 out:
3940         NDFREE(&nd, NDF_ONLY_PNBUF);
3941         vput(vp);
3942         if (nd.ni_dvp == vp)
3943                 vrele(nd.ni_dvp);
3944         else
3945                 vput(nd.ni_dvp);
3946         if (error == ERELOOKUP)
3947                 goto restart;
3948 fdout:
3949         if (fp != NULL)
3950                 fdrop(fp, td);
3951         return (error);
3952 }
3953
3954 #if defined(COMPAT_43) || defined(COMPAT_FREEBSD11)
3955 int
3956 freebsd11_kern_getdirentries(struct thread *td, int fd, char *ubuf, u_int count,
3957     long *basep, void (*func)(struct freebsd11_dirent *))
3958 {
3959         struct freebsd11_dirent dstdp;
3960         struct dirent *dp, *edp;
3961         char *dirbuf;
3962         off_t base;
3963         ssize_t resid, ucount;
3964         int error;
3965
3966         /* XXX arbitrary sanity limit on `count'. */
3967         count = min(count, 64 * 1024);
3968
3969         dirbuf = malloc(count, M_TEMP, M_WAITOK);
3970
3971         error = kern_getdirentries(td, fd, dirbuf, count, &base, &resid,
3972             UIO_SYSSPACE);
3973         if (error != 0)
3974                 goto done;
3975         if (basep != NULL)
3976                 *basep = base;
3977
3978         ucount = 0;
3979         for (dp = (struct dirent *)dirbuf,
3980             edp = (struct dirent *)&dirbuf[count - resid];
3981             ucount < count && dp < edp; ) {
3982                 if (dp->d_reclen == 0)
3983                         break;
3984                 MPASS(dp->d_reclen >= _GENERIC_DIRLEN(0));
3985                 if (dp->d_namlen >= sizeof(dstdp.d_name))
3986                         continue;
3987                 dstdp.d_type = dp->d_type;
3988                 dstdp.d_namlen = dp->d_namlen;
3989                 dstdp.d_fileno = dp->d_fileno;          /* truncate */
3990                 if (dstdp.d_fileno != dp->d_fileno) {
3991                         switch (ino64_trunc_error) {
3992                         default:
3993                         case 0:
3994                                 break;
3995                         case 1:
3996                                 error = EOVERFLOW;
3997                                 goto done;
3998                         case 2:
3999                                 dstdp.d_fileno = UINT32_MAX;
4000                                 break;
4001                         }
4002                 }
4003                 dstdp.d_reclen = sizeof(dstdp) - sizeof(dstdp.d_name) +
4004                     ((dp->d_namlen + 1 + 3) &~ 3);
4005                 bcopy(dp->d_name, dstdp.d_name, dstdp.d_namlen);
4006                 bzero(dstdp.d_name + dstdp.d_namlen,
4007                     dstdp.d_reclen - offsetof(struct freebsd11_dirent, d_name) -
4008                     dstdp.d_namlen);
4009                 MPASS(dstdp.d_reclen <= dp->d_reclen);
4010                 MPASS(ucount + dstdp.d_reclen <= count);
4011                 if (func != NULL)
4012                         func(&dstdp);
4013                 error = copyout(&dstdp, ubuf + ucount, dstdp.d_reclen);
4014                 if (error != 0)
4015                         break;
4016                 dp = (struct dirent *)((char *)dp + dp->d_reclen);
4017                 ucount += dstdp.d_reclen;
4018         }
4019
4020 done:
4021         free(dirbuf, M_TEMP);
4022         if (error == 0)
4023                 td->td_retval[0] = ucount;
4024         return (error);
4025 }
4026 #endif /* COMPAT */
4027
4028 #ifdef COMPAT_43
4029 static void
4030 ogetdirentries_cvt(struct freebsd11_dirent *dp)
4031 {
4032 #if (BYTE_ORDER == LITTLE_ENDIAN)
4033         /*
4034          * The expected low byte of dp->d_namlen is our dp->d_type.
4035          * The high MBZ byte of dp->d_namlen is our dp->d_namlen.
4036          */
4037         dp->d_type = dp->d_namlen;
4038         dp->d_namlen = 0;
4039 #else
4040         /*
4041          * The dp->d_type is the high byte of the expected dp->d_namlen,
4042          * so must be zero'ed.
4043          */
4044         dp->d_type = 0;
4045 #endif
4046 }
4047
4048 /*
4049  * Read a block of directory entries in a filesystem independent format.
4050  */
4051 #ifndef _SYS_SYSPROTO_H_
4052 struct ogetdirentries_args {
4053         int     fd;
4054         char    *buf;
4055         u_int   count;
4056         long    *basep;
4057 };
4058 #endif
4059 int
4060 ogetdirentries(struct thread *td, struct ogetdirentries_args *uap)
4061 {
4062         long loff;
4063         int error;
4064
4065         error = kern_ogetdirentries(td, uap, &loff);
4066         if (error == 0)
4067                 error = copyout(&loff, uap->basep, sizeof(long));
4068         return (error);
4069 }
4070
4071 int
4072 kern_ogetdirentries(struct thread *td, struct ogetdirentries_args *uap,
4073     long *ploff)
4074 {
4075         long base;
4076         int error;
4077
4078         /* XXX arbitrary sanity limit on `count'. */
4079         if (uap->count > 64 * 1024)
4080                 return (EINVAL);
4081
4082         error = freebsd11_kern_getdirentries(td, uap->fd, uap->buf, uap->count,
4083             &base, ogetdirentries_cvt);
4084
4085         if (error == 0 && uap->basep != NULL)
4086                 error = copyout(&base, uap->basep, sizeof(long));
4087
4088         return (error);
4089 }
4090 #endif /* COMPAT_43 */
4091
4092 #if defined(COMPAT_FREEBSD11)
4093 #ifndef _SYS_SYSPROTO_H_
4094 struct freebsd11_getdirentries_args {
4095         int     fd;
4096         char    *buf;
4097         u_int   count;
4098         long    *basep;
4099 };
4100 #endif
4101 int
4102 freebsd11_getdirentries(struct thread *td,
4103     struct freebsd11_getdirentries_args *uap)
4104 {
4105         long base;
4106         int error;
4107
4108         error = freebsd11_kern_getdirentries(td, uap->fd, uap->buf, uap->count,
4109             &base, NULL);
4110
4111         if (error == 0 && uap->basep != NULL)
4112                 error = copyout(&base, uap->basep, sizeof(long));
4113         return (error);
4114 }
4115
4116 int
4117 freebsd11_getdents(struct thread *td, struct freebsd11_getdents_args *uap)
4118 {
4119         struct freebsd11_getdirentries_args ap;
4120
4121         ap.fd = uap->fd;
4122         ap.buf = uap->buf;
4123         ap.count = uap->count;
4124         ap.basep = NULL;
4125         return (freebsd11_getdirentries(td, &ap));
4126 }
4127 #endif /* COMPAT_FREEBSD11 */
4128
4129 /*
4130  * Read a block of directory entries in a filesystem independent format.
4131  */
4132 int
4133 sys_getdirentries(struct thread *td, struct getdirentries_args *uap)
4134 {
4135         off_t base;
4136         int error;
4137
4138         error = kern_getdirentries(td, uap->fd, uap->buf, uap->count, &base,
4139             NULL, UIO_USERSPACE);
4140         if (error != 0)
4141                 return (error);
4142         if (uap->basep != NULL)
4143                 error = copyout(&base, uap->basep, sizeof(off_t));
4144         return (error);
4145 }
4146
4147 int
4148 kern_getdirentries(struct thread *td, int fd, char *buf, size_t count,
4149     off_t *basep, ssize_t *residp, enum uio_seg bufseg)
4150 {
4151         struct vnode *vp;
4152         struct file *fp;
4153         struct uio auio;
4154         struct iovec aiov;
4155         off_t loff;
4156         int error, eofflag;
4157         off_t foffset;
4158
4159         AUDIT_ARG_FD(fd);
4160         if (count > IOSIZE_MAX)
4161                 return (EINVAL);
4162         auio.uio_resid = count;
4163         error = getvnode(td, fd, &cap_read_rights, &fp);
4164         if (error != 0)
4165                 return (error);
4166         if ((fp->f_flag & FREAD) == 0) {
4167                 fdrop(fp, td);
4168                 return (EBADF);
4169         }
4170         vp = fp->f_vnode;
4171         foffset = foffset_lock(fp, 0);
4172 unionread:
4173         if (vp->v_type != VDIR) {
4174                 error = EINVAL;
4175                 goto fail;
4176         }
4177         aiov.iov_base = buf;
4178         aiov.iov_len = count;
4179         auio.uio_iov = &aiov;
4180         auio.uio_iovcnt = 1;
4181         auio.uio_rw = UIO_READ;
4182         auio.uio_segflg = bufseg;
4183         auio.uio_td = td;
4184         vn_lock(vp, LK_SHARED | LK_RETRY);
4185         AUDIT_ARG_VNODE1(vp);
4186         loff = auio.uio_offset = foffset;
4187 #ifdef MAC
4188         error = mac_vnode_check_readdir(td->td_ucred, vp);
4189         if (error == 0)
4190 #endif
4191                 error = VOP_READDIR(vp, &auio, fp->f_cred, &eofflag, NULL,
4192                     NULL);
4193         foffset = auio.uio_offset;
4194         if (error != 0) {
4195                 VOP_UNLOCK(vp);
4196                 goto fail;
4197         }
4198         if (count == auio.uio_resid &&
4199             (vp->v_vflag & VV_ROOT) &&
4200             (vp->v_mount->mnt_flag & MNT_UNION)) {
4201                 struct vnode *tvp = vp;
4202
4203                 vp = vp->v_mount->mnt_vnodecovered;
4204                 VREF(vp);
4205                 fp->f_vnode = vp;
4206                 foffset = 0;
4207                 vput(tvp);
4208                 goto unionread;
4209         }
4210         VOP_UNLOCK(vp);
4211         *basep = loff;
4212         if (residp != NULL)
4213                 *residp = auio.uio_resid;
4214         td->td_retval[0] = count - auio.uio_resid;
4215 fail:
4216         foffset_unlock(fp, foffset, 0);
4217         fdrop(fp, td);
4218         return (error);
4219 }
4220
4221 /*
4222  * Set the mode mask for creation of filesystem nodes.
4223  */
4224 #ifndef _SYS_SYSPROTO_H_
4225 struct umask_args {
4226         int     newmask;
4227 };
4228 #endif
4229 int
4230 sys_umask(struct thread *td, struct umask_args *uap)
4231 {
4232         struct pwddesc *pdp;
4233
4234         pdp = td->td_proc->p_pd;
4235         PWDDESC_XLOCK(pdp);
4236         td->td_retval[0] = pdp->pd_cmask;
4237         pdp->pd_cmask = uap->newmask & ALLPERMS;
4238         PWDDESC_XUNLOCK(pdp);
4239         return (0);
4240 }
4241
4242 /*
4243  * Void all references to file by ripping underlying filesystem away from
4244  * vnode.
4245  */
4246 #ifndef _SYS_SYSPROTO_H_
4247 struct revoke_args {
4248         char    *path;
4249 };
4250 #endif
4251 int
4252 sys_revoke(struct thread *td, struct revoke_args *uap)
4253 {
4254         struct vnode *vp;
4255         struct vattr vattr;
4256         struct nameidata nd;
4257         int error;
4258
4259         NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1, UIO_USERSPACE,
4260             uap->path, td);
4261         if ((error = namei(&nd)) != 0)
4262                 return (error);
4263         vp = nd.ni_vp;
4264         NDFREE_NOTHING(&nd);
4265         if (vp->v_type != VCHR || vp->v_rdev == NULL) {
4266                 error = EINVAL;
4267                 goto out;
4268         }
4269 #ifdef MAC
4270         error = mac_vnode_check_revoke(td->td_ucred, vp);
4271         if (error != 0)
4272                 goto out;
4273 #endif
4274         error = VOP_GETATTR(vp, &vattr, td->td_ucred);
4275         if (error != 0)
4276                 goto out;
4277         if (td->td_ucred->cr_uid != vattr.va_uid) {
4278                 error = priv_check(td, PRIV_VFS_ADMIN);
4279                 if (error != 0)
4280                         goto out;
4281         }
4282         if (devfs_usecount(vp) > 0)
4283                 VOP_REVOKE(vp, REVOKEALL);
4284 out:
4285         vput(vp);
4286         return (error);
4287 }
4288
4289 /*
4290  * This variant of getvnode() allows O_PATH files.  Caller should
4291  * ensure that returned file and vnode are only used for compatible
4292  * semantics.
4293  */
4294 int
4295 getvnode_path(struct thread *td, int fd, cap_rights_t *rightsp,
4296     struct file **fpp)
4297 {
4298         struct file *fp;
4299         int error;
4300
4301         error = fget_unlocked(td->td_proc->p_fd, fd, rightsp, &fp);
4302         if (error != 0)
4303                 return (error);
4304
4305         /*
4306          * The file could be not of the vnode type, or it may be not
4307          * yet fully initialized, in which case the f_vnode pointer
4308          * may be set, but f_ops is still badfileops.  E.g.,
4309          * devfs_open() transiently create such situation to
4310          * facilitate csw d_fdopen().
4311          *
4312          * Dupfdopen() handling in kern_openat() installs the
4313          * half-baked file into the process descriptor table, allowing
4314          * other thread to dereference it. Guard against the race by
4315          * checking f_ops.
4316          */
4317         if (fp->f_vnode == NULL || fp->f_ops == &badfileops) {
4318                 fdrop(fp, td);
4319                 return (EINVAL);
4320         }
4321
4322         *fpp = fp;
4323         return (0);
4324 }
4325
4326 /*
4327  * Convert a user file descriptor to a kernel file entry and check
4328  * that, if it is a capability, the correct rights are present.
4329  * A reference on the file entry is held upon returning.
4330  */
4331 int
4332 getvnode(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
4333 {
4334         int error;
4335
4336         error = getvnode_path(td, fd, rightsp, fpp);
4337
4338         /*
4339          * Filter out O_PATH file descriptors, most getvnode() callers
4340          * do not call fo_ methods.
4341          */
4342         if (error == 0 && (*fpp)->f_ops == &path_fileops) {
4343                 fdrop(*fpp, td);
4344                 error = EBADF;
4345         }
4346
4347         return (error);
4348 }
4349
4350 /*
4351  * Get an (NFS) file handle.
4352  */
4353 #ifndef _SYS_SYSPROTO_H_
4354 struct lgetfh_args {
4355         char *fname;
4356         fhandle_t *fhp;
4357 };
4358 #endif
4359 int
4360 sys_lgetfh(struct thread *td, struct lgetfh_args *uap)
4361 {
4362
4363         return (kern_getfhat(td, AT_SYMLINK_NOFOLLOW, AT_FDCWD, uap->fname,
4364             UIO_USERSPACE, uap->fhp, UIO_USERSPACE));
4365 }
4366
4367 #ifndef _SYS_SYSPROTO_H_
4368 struct getfh_args {
4369         char *fname;
4370         fhandle_t *fhp;
4371 };
4372 #endif
4373 int
4374 sys_getfh(struct thread *td, struct getfh_args *uap)
4375 {
4376
4377         return (kern_getfhat(td, 0, AT_FDCWD, uap->fname, UIO_USERSPACE,
4378             uap->fhp, UIO_USERSPACE));
4379 }
4380
4381 /*
4382  * syscall for the rpc.lockd to use to translate an open descriptor into
4383  * a NFS file handle.
4384  *
4385  * warning: do not remove the priv_check() call or this becomes one giant
4386  * security hole.
4387  */
4388 #ifndef _SYS_SYSPROTO_H_
4389 struct getfhat_args {
4390         int fd;
4391         char *path;
4392         fhandle_t *fhp;
4393         int flags;
4394 };
4395 #endif
4396 int
4397 sys_getfhat(struct thread *td, struct getfhat_args *uap)
4398 {
4399
4400         if ((uap->flags & ~(AT_SYMLINK_NOFOLLOW | AT_RESOLVE_BENEATH)) != 0)
4401                 return (EINVAL);
4402         return (kern_getfhat(td, uap->flags, uap->fd, uap->path, UIO_USERSPACE,
4403             uap->fhp, UIO_USERSPACE));
4404 }
4405
4406 int
4407 kern_getfhat(struct thread *td, int flags, int fd, const char *path,
4408     enum uio_seg pathseg, fhandle_t *fhp, enum uio_seg fhseg)
4409 {
4410         struct nameidata nd;
4411         fhandle_t fh;
4412         struct vnode *vp;
4413         int error;
4414
4415         error = priv_check(td, PRIV_VFS_GETFH);
4416         if (error != 0)
4417                 return (error);
4418         NDINIT_AT(&nd, LOOKUP, at2cnpflags(flags, AT_SYMLINK_NOFOLLOW |
4419             AT_RESOLVE_BENEATH) | LOCKLEAF | AUDITVNODE1, pathseg, path,
4420             fd, td);
4421         error = namei(&nd);
4422         if (error != 0)
4423                 return (error);
4424         NDFREE_NOTHING(&nd);
4425         vp = nd.ni_vp;
4426         bzero(&fh, sizeof(fh));
4427         fh.fh_fsid = vp->v_mount->mnt_stat.f_fsid;
4428         error = VOP_VPTOFH(vp, &fh.fh_fid);
4429         vput(vp);
4430         if (error == 0) {
4431                 if (fhseg == UIO_USERSPACE)
4432                         error = copyout(&fh, fhp, sizeof (fh));
4433                 else
4434                         memcpy(fhp, &fh, sizeof(fh));
4435         }
4436         return (error);
4437 }
4438
4439 #ifndef _SYS_SYSPROTO_H_
4440 struct fhlink_args {
4441         fhandle_t *fhp;
4442         const char *to;
4443 };
4444 #endif
4445 int
4446 sys_fhlink(struct thread *td, struct fhlink_args *uap)
4447 {
4448
4449         return (kern_fhlinkat(td, AT_FDCWD, uap->to, UIO_USERSPACE, uap->fhp));
4450 }
4451
4452 #ifndef _SYS_SYSPROTO_H_
4453 struct fhlinkat_args {
4454         fhandle_t *fhp;
4455         int tofd;
4456         const char *to;
4457 };
4458 #endif
4459 int
4460 sys_fhlinkat(struct thread *td, struct fhlinkat_args *uap)
4461 {
4462
4463         return (kern_fhlinkat(td, uap->tofd, uap->to, UIO_USERSPACE, uap->fhp));
4464 }
4465
4466 static int
4467 kern_fhlinkat(struct thread *td, int fd, const char *path,
4468     enum uio_seg pathseg, fhandle_t *fhp)
4469 {
4470         fhandle_t fh;
4471         struct mount *mp;
4472         struct vnode *vp;
4473         int error;
4474
4475         error = priv_check(td, PRIV_VFS_GETFH);
4476         if (error != 0)
4477                 return (error);
4478         error = copyin(fhp, &fh, sizeof(fh));
4479         if (error != 0)
4480                 return (error);
4481         do {
4482                 bwillwrite();
4483                 if ((mp = vfs_busyfs(&fh.fh_fsid)) == NULL)
4484                         return (ESTALE);
4485                 error = VFS_FHTOVP(mp, &fh.fh_fid, LK_SHARED, &vp);
4486                 vfs_unbusy(mp);
4487                 if (error != 0)
4488                         return (error);
4489                 VOP_UNLOCK(vp);
4490                 error = kern_linkat_vp(td, vp, fd, path, pathseg);
4491         } while (error == EAGAIN || error == ERELOOKUP);
4492         return (error);
4493 }
4494
4495 #ifndef _SYS_SYSPROTO_H_
4496 struct fhreadlink_args {
4497         fhandle_t *fhp;
4498         char *buf;
4499         size_t bufsize;
4500 };
4501 #endif
4502 int
4503 sys_fhreadlink(struct thread *td, struct fhreadlink_args *uap)
4504 {
4505         fhandle_t fh;
4506         struct mount *mp;
4507         struct vnode *vp;
4508         int error;
4509
4510         error = priv_check(td, PRIV_VFS_GETFH);
4511         if (error != 0)
4512                 return (error);
4513         if (uap->bufsize > IOSIZE_MAX)
4514                 return (EINVAL);
4515         error = copyin(uap->fhp, &fh, sizeof(fh));
4516         if (error != 0)
4517                 return (error);
4518         if ((mp = vfs_busyfs(&fh.fh_fsid)) == NULL)
4519                 return (ESTALE);
4520         error = VFS_FHTOVP(mp, &fh.fh_fid, LK_SHARED, &vp);
4521         vfs_unbusy(mp);
4522         if (error != 0)
4523                 return (error);
4524         error = kern_readlink_vp(vp, uap->buf, UIO_USERSPACE, uap->bufsize, td);
4525         vput(vp);
4526         return (error);
4527 }
4528
4529 /*
4530  * syscall for the rpc.lockd to use to translate a NFS file handle into an
4531  * open descriptor.
4532  *
4533  * warning: do not remove the priv_check() call or this becomes one giant
4534  * security hole.
4535  */
4536 #ifndef _SYS_SYSPROTO_H_
4537 struct fhopen_args {
4538         const struct fhandle *u_fhp;
4539         int flags;
4540 };
4541 #endif
4542 int
4543 sys_fhopen(struct thread *td, struct fhopen_args *uap)
4544 {
4545         return (kern_fhopen(td, uap->u_fhp, uap->flags));
4546 }
4547
4548 int
4549 kern_fhopen(struct thread *td, const struct fhandle *u_fhp, int flags)
4550 {
4551         struct mount *mp;
4552         struct vnode *vp;
4553         struct fhandle fhp;
4554         struct file *fp;
4555         int fmode, error;
4556         int indx;
4557
4558         error = priv_check(td, PRIV_VFS_FHOPEN);
4559         if (error != 0)
4560                 return (error);
4561         indx = -1;
4562         fmode = FFLAGS(flags);
4563         /* why not allow a non-read/write open for our lockd? */
4564         if (((fmode & (FREAD | FWRITE)) == 0) || (fmode & O_CREAT))
4565                 return (EINVAL);
4566         error = copyin(u_fhp, &fhp, sizeof(fhp));
4567         if (error != 0)
4568                 return(error);
4569         /* find the mount point */
4570         mp = vfs_busyfs(&fhp.fh_fsid);
4571         if (mp == NULL)
4572                 return (ESTALE);
4573         /* now give me my vnode, it gets returned to me locked */
4574         error = VFS_FHTOVP(mp, &fhp.fh_fid, LK_EXCLUSIVE, &vp);
4575         vfs_unbusy(mp);
4576         if (error != 0)
4577                 return (error);
4578
4579         error = falloc_noinstall(td, &fp);
4580         if (error != 0) {
4581                 vput(vp);
4582                 return (error);
4583         }
4584         /*
4585          * An extra reference on `fp' has been held for us by
4586          * falloc_noinstall().
4587          */
4588
4589 #ifdef INVARIANTS
4590         td->td_dupfd = -1;
4591 #endif
4592         error = vn_open_vnode(vp, fmode, td->td_ucred, td, fp);
4593         if (error != 0) {
4594                 KASSERT(fp->f_ops == &badfileops,
4595                     ("VOP_OPEN in fhopen() set f_ops"));
4596                 KASSERT(td->td_dupfd < 0,
4597                     ("fhopen() encountered fdopen()"));
4598
4599                 vput(vp);
4600                 goto bad;
4601         }
4602 #ifdef INVARIANTS
4603         td->td_dupfd = 0;
4604 #endif
4605         fp->f_vnode = vp;
4606         finit_vnode(fp, fmode, NULL, &vnops);
4607         VOP_UNLOCK(vp);
4608         if ((fmode & O_TRUNC) != 0) {
4609                 error = fo_truncate(fp, 0, td->td_ucred, td);
4610                 if (error != 0)
4611                         goto bad;
4612         }
4613
4614         error = finstall(td, fp, &indx, fmode, NULL);
4615 bad:
4616         fdrop(fp, td);
4617         td->td_retval[0] = indx;
4618         return (error);
4619 }
4620
4621 /*
4622  * Stat an (NFS) file handle.
4623  */
4624 #ifndef _SYS_SYSPROTO_H_
4625 struct fhstat_args {
4626         struct fhandle *u_fhp;
4627         struct stat *sb;
4628 };
4629 #endif
4630 int
4631 sys_fhstat(struct thread *td, struct fhstat_args *uap)
4632 {
4633         struct stat sb;
4634         struct fhandle fh;
4635         int error;
4636
4637         error = copyin(uap->u_fhp, &fh, sizeof(fh));
4638         if (error != 0)
4639                 return (error);
4640         error = kern_fhstat(td, fh, &sb);
4641         if (error == 0)
4642                 error = copyout(&sb, uap->sb, sizeof(sb));
4643         return (error);
4644 }
4645
4646 int
4647 kern_fhstat(struct thread *td, struct fhandle fh, struct stat *sb)
4648 {
4649         struct mount *mp;
4650         struct vnode *vp;
4651         int error;
4652
4653         error = priv_check(td, PRIV_VFS_FHSTAT);
4654         if (error != 0)
4655                 return (error);
4656         if ((mp = vfs_busyfs(&fh.fh_fsid)) == NULL)
4657                 return (ESTALE);
4658         error = VFS_FHTOVP(mp, &fh.fh_fid, LK_EXCLUSIVE, &vp);
4659         vfs_unbusy(mp);
4660         if (error != 0)
4661                 return (error);
4662         error = VOP_STAT(vp, sb, td->td_ucred, NOCRED, td);
4663         vput(vp);
4664         return (error);
4665 }
4666
4667 /*
4668  * Implement fstatfs() for (NFS) file handles.
4669  */
4670 #ifndef _SYS_SYSPROTO_H_
4671 struct fhstatfs_args {
4672         struct fhandle *u_fhp;
4673         struct statfs *buf;
4674 };
4675 #endif
4676 int
4677 sys_fhstatfs(struct thread *td, struct fhstatfs_args *uap)
4678 {
4679         struct statfs *sfp;
4680         fhandle_t fh;
4681         int error;
4682
4683         error = copyin(uap->u_fhp, &fh, sizeof(fhandle_t));
4684         if (error != 0)
4685                 return (error);
4686         sfp = malloc(sizeof(struct statfs), M_STATFS, M_WAITOK);
4687         error = kern_fhstatfs(td, fh, sfp);
4688         if (error == 0)
4689                 error = copyout(sfp, uap->buf, sizeof(*sfp));
4690         free(sfp, M_STATFS);
4691         return (error);
4692 }
4693
4694 int
4695 kern_fhstatfs(struct thread *td, fhandle_t fh, struct statfs *buf)
4696 {
4697         struct mount *mp;
4698         struct vnode *vp;
4699         int error;
4700
4701         error = priv_check(td, PRIV_VFS_FHSTATFS);
4702         if (error != 0)
4703                 return (error);
4704         if ((mp = vfs_busyfs(&fh.fh_fsid)) == NULL)
4705                 return (ESTALE);
4706         error = VFS_FHTOVP(mp, &fh.fh_fid, LK_EXCLUSIVE, &vp);
4707         if (error != 0) {
4708                 vfs_unbusy(mp);
4709                 return (error);
4710         }
4711         vput(vp);
4712         error = prison_canseemount(td->td_ucred, mp);
4713         if (error != 0)
4714                 goto out;
4715 #ifdef MAC
4716         error = mac_mount_check_stat(td->td_ucred, mp);
4717         if (error != 0)
4718                 goto out;
4719 #endif
4720         error = VFS_STATFS(mp, buf);
4721 out:
4722         vfs_unbusy(mp);
4723         return (error);
4724 }
4725
4726 /*
4727  * Unlike madvise(2), we do not make a best effort to remember every
4728  * possible caching hint.  Instead, we remember the last setting with
4729  * the exception that we will allow POSIX_FADV_NORMAL to adjust the
4730  * region of any current setting.
4731  */
4732 int
4733 kern_posix_fadvise(struct thread *td, int fd, off_t offset, off_t len,
4734     int advice)
4735 {
4736         struct fadvise_info *fa, *new;
4737         struct file *fp;
4738         struct vnode *vp;
4739         off_t end;
4740         int error;
4741
4742         if (offset < 0 || len < 0 || offset > OFF_MAX - len)
4743                 return (EINVAL);
4744         AUDIT_ARG_VALUE(advice);
4745         switch (advice) {
4746         case POSIX_FADV_SEQUENTIAL:
4747         case POSIX_FADV_RANDOM:
4748         case POSIX_FADV_NOREUSE:
4749                 new = malloc(sizeof(*fa), M_FADVISE, M_WAITOK);
4750                 break;
4751         case POSIX_FADV_NORMAL:
4752         case POSIX_FADV_WILLNEED:
4753         case POSIX_FADV_DONTNEED:
4754                 new = NULL;
4755                 break;
4756         default:
4757                 return (EINVAL);
4758         }
4759         /* XXX: CAP_POSIX_FADVISE? */
4760         AUDIT_ARG_FD(fd);
4761         error = fget(td, fd, &cap_no_rights, &fp);
4762         if (error != 0)
4763                 goto out;
4764         AUDIT_ARG_FILE(td->td_proc, fp);
4765         if ((fp->f_ops->fo_flags & DFLAG_SEEKABLE) == 0) {
4766                 error = ESPIPE;
4767                 goto out;
4768         }
4769         if (fp->f_type != DTYPE_VNODE) {
4770                 error = ENODEV;
4771                 goto out;
4772         }
4773         vp = fp->f_vnode;
4774         if (vp->v_type != VREG) {
4775                 error = ENODEV;
4776                 goto out;
4777         }
4778         if (len == 0)
4779                 end = OFF_MAX;
4780         else
4781                 end = offset + len - 1;
4782         switch (advice) {
4783         case POSIX_FADV_SEQUENTIAL:
4784         case POSIX_FADV_RANDOM:
4785         case POSIX_FADV_NOREUSE:
4786                 /*
4787                  * Try to merge any existing non-standard region with
4788                  * this new region if possible, otherwise create a new
4789                  * non-standard region for this request.
4790                  */
4791                 mtx_pool_lock(mtxpool_sleep, fp);
4792                 fa = fp->f_advice;
4793                 if (fa != NULL && fa->fa_advice == advice &&
4794                     ((fa->fa_start <= end && fa->fa_end >= offset) ||
4795                     (end != OFF_MAX && fa->fa_start == end + 1) ||
4796                     (fa->fa_end != OFF_MAX && fa->fa_end + 1 == offset))) {
4797                         if (offset < fa->fa_start)
4798                                 fa->fa_start = offset;
4799                         if (end > fa->fa_end)
4800                                 fa->fa_end = end;
4801                 } else {
4802                         new->fa_advice = advice;
4803                         new->fa_start = offset;
4804                         new->fa_end = end;
4805                         fp->f_advice = new;
4806                         new = fa;
4807                 }
4808                 mtx_pool_unlock(mtxpool_sleep, fp);
4809                 break;
4810         case POSIX_FADV_NORMAL:
4811                 /*
4812                  * If a the "normal" region overlaps with an existing
4813                  * non-standard region, trim or remove the
4814                  * non-standard region.
4815                  */
4816                 mtx_pool_lock(mtxpool_sleep, fp);
4817                 fa = fp->f_advice;
4818                 if (fa != NULL) {
4819                         if (offset <= fa->fa_start && end >= fa->fa_end) {
4820                                 new = fa;
4821                                 fp->f_advice = NULL;
4822                         } else if (offset <= fa->fa_start &&
4823                             end >= fa->fa_start)
4824                                 fa->fa_start = end + 1;
4825                         else if (offset <= fa->fa_end && end >= fa->fa_end)
4826                                 fa->fa_end = offset - 1;
4827                         else if (offset >= fa->fa_start && end <= fa->fa_end) {
4828                                 /*
4829                                  * If the "normal" region is a middle
4830                                  * portion of the existing
4831                                  * non-standard region, just remove
4832                                  * the whole thing rather than picking
4833                                  * one side or the other to
4834                                  * preserve.
4835                                  */
4836                                 new = fa;
4837                                 fp->f_advice = NULL;
4838                         }
4839                 }
4840                 mtx_pool_unlock(mtxpool_sleep, fp);
4841                 break;
4842         case POSIX_FADV_WILLNEED:
4843         case POSIX_FADV_DONTNEED:
4844                 error = VOP_ADVISE(vp, offset, end, advice);
4845                 break;
4846         }
4847 out:
4848         if (fp != NULL)
4849                 fdrop(fp, td);
4850         free(new, M_FADVISE);
4851         return (error);
4852 }
4853
4854 int
4855 sys_posix_fadvise(struct thread *td, struct posix_fadvise_args *uap)
4856 {
4857         int error;
4858
4859         error = kern_posix_fadvise(td, uap->fd, uap->offset, uap->len,
4860             uap->advice);
4861         return (kern_posix_error(td, error));
4862 }
4863
4864 int
4865 kern_copy_file_range(struct thread *td, int infd, off_t *inoffp, int outfd,
4866     off_t *outoffp, size_t len, unsigned int flags)
4867 {
4868         struct file *infp, *outfp;
4869         struct vnode *invp, *outvp;
4870         int error;
4871         size_t retlen;
4872         void *rl_rcookie, *rl_wcookie;
4873         off_t savinoff, savoutoff;
4874
4875         infp = outfp = NULL;
4876         rl_rcookie = rl_wcookie = NULL;
4877         savinoff = -1;
4878         error = 0;
4879         retlen = 0;
4880
4881         if (flags != 0) {
4882                 error = EINVAL;
4883                 goto out;
4884         }
4885         if (len > SSIZE_MAX)
4886                 /*
4887                  * Although the len argument is size_t, the return argument
4888                  * is ssize_t (which is signed).  Therefore a size that won't
4889                  * fit in ssize_t can't be returned.
4890                  */
4891                 len = SSIZE_MAX;
4892
4893         /* Get the file structures for the file descriptors. */
4894         error = fget_read(td, infd, &cap_read_rights, &infp);
4895         if (error != 0)
4896                 goto out;
4897         if (infp->f_ops == &badfileops) {
4898                 error = EBADF;
4899                 goto out;
4900         }
4901         if (infp->f_vnode == NULL) {
4902                 error = EINVAL;
4903                 goto out;
4904         }
4905         error = fget_write(td, outfd, &cap_write_rights, &outfp);
4906         if (error != 0)
4907                 goto out;
4908         if (outfp->f_ops == &badfileops) {
4909                 error = EBADF;
4910                 goto out;
4911         }
4912         if (outfp->f_vnode == NULL) {
4913                 error = EINVAL;
4914                 goto out;
4915         }
4916
4917         /* Set the offset pointers to the correct place. */
4918         if (inoffp == NULL)
4919                 inoffp = &infp->f_offset;
4920         if (outoffp == NULL)
4921                 outoffp = &outfp->f_offset;
4922         savinoff = *inoffp;
4923         savoutoff = *outoffp;
4924
4925         invp = infp->f_vnode;
4926         outvp = outfp->f_vnode;
4927         /* Sanity check the f_flag bits. */
4928         if ((outfp->f_flag & (FWRITE | FAPPEND)) != FWRITE ||
4929             (infp->f_flag & FREAD) == 0) {
4930                 error = EBADF;
4931                 goto out;
4932         }
4933
4934         /* If len == 0, just return 0. */
4935         if (len == 0)
4936                 goto out;
4937
4938         /*
4939          * If infp and outfp refer to the same file, the byte ranges cannot
4940          * overlap.
4941          */
4942         if (invp == outvp && ((savinoff <= savoutoff && savinoff + len >
4943             savoutoff) || (savinoff > savoutoff && savoutoff + len >
4944             savinoff))) {
4945                 error = EINVAL;
4946                 goto out;
4947         }
4948
4949         /* Range lock the byte ranges for both invp and outvp. */
4950         for (;;) {
4951                 rl_wcookie = vn_rangelock_wlock(outvp, *outoffp, *outoffp +
4952                     len);
4953                 rl_rcookie = vn_rangelock_tryrlock(invp, *inoffp, *inoffp +
4954                     len);
4955                 if (rl_rcookie != NULL)
4956                         break;
4957                 vn_rangelock_unlock(outvp, rl_wcookie);
4958                 rl_rcookie = vn_rangelock_rlock(invp, *inoffp, *inoffp + len);
4959                 vn_rangelock_unlock(invp, rl_rcookie);
4960         }
4961
4962         retlen = len;
4963         error = vn_copy_file_range(invp, inoffp, outvp, outoffp, &retlen,
4964             flags, infp->f_cred, outfp->f_cred, td);
4965 out:
4966         if (rl_rcookie != NULL)
4967                 vn_rangelock_unlock(invp, rl_rcookie);
4968         if (rl_wcookie != NULL)
4969                 vn_rangelock_unlock(outvp, rl_wcookie);
4970         if (savinoff != -1 && (error == EINTR || error == ERESTART)) {
4971                 *inoffp = savinoff;
4972                 *outoffp = savoutoff;
4973         }
4974         if (outfp != NULL)
4975                 fdrop(outfp, td);
4976         if (infp != NULL)
4977                 fdrop(infp, td);
4978         td->td_retval[0] = retlen;
4979         return (error);
4980 }
4981
4982 int
4983 sys_copy_file_range(struct thread *td, struct copy_file_range_args *uap)
4984 {
4985         off_t inoff, outoff, *inoffp, *outoffp;
4986         int error;
4987
4988         inoffp = outoffp = NULL;
4989         if (uap->inoffp != NULL) {
4990                 error = copyin(uap->inoffp, &inoff, sizeof(off_t));
4991                 if (error != 0)
4992                         return (error);
4993                 inoffp = &inoff;
4994         }
4995         if (uap->outoffp != NULL) {
4996                 error = copyin(uap->outoffp, &outoff, sizeof(off_t));
4997                 if (error != 0)
4998                         return (error);
4999                 outoffp = &outoff;
5000         }
5001         error = kern_copy_file_range(td, uap->infd, inoffp, uap->outfd,
5002             outoffp, uap->len, uap->flags);
5003         if (error == 0 && uap->inoffp != NULL)
5004                 error = copyout(inoffp, uap->inoffp, sizeof(off_t));
5005         if (error == 0 && uap->outoffp != NULL)
5006                 error = copyout(outoffp, uap->outoffp, sizeof(off_t));
5007         return (error);
5008 }