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