Merge git://git.dragonflybsd.org/dragonfly
[dragonfly.git] / sys / kern / kern_fp.c
1 /*
2  * Copyright (c) 2003,2004 The DragonFly Project.  All rights reserved.
3  * 
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  * 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  * 
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 /*
36  * Direct file pointer API functions for in-kernel operations on files.  These
37  * functions provide a open/read/write/close like interface within the kernel
38  * for operating on files that are not necessarily associated with processes
39  * and which do not (typically) have descriptors.
40  *
41  * FUTURE: file handle conversion routines to support checkpointing, 
42  * and additional file operations (ioctl, fcntl).
43  */
44
45 #include <sys/param.h>
46 #include <sys/kernel.h>
47 #include <sys/systm.h>
48 #include <sys/malloc.h>
49 #include <sys/sysproto.h>
50 #include <sys/conf.h>
51 #include <sys/filedesc.h>
52 #include <sys/sysctl.h>
53 #include <sys/vnode.h>
54 #include <sys/proc.h>
55 #include <sys/priv.h>
56 #include <sys/nlookup.h>
57 #include <sys/file.h>
58 #include <sys/stat.h>
59 #include <sys/filio.h>
60 #include <sys/fcntl.h>
61 #include <sys/unistd.h>
62 #include <sys/resourcevar.h>
63 #include <sys/event.h>
64 #include <sys/mman.h>
65
66 #include <vm/vm.h>
67 #include <vm/vm_param.h>
68 #include <sys/lock.h>
69 #include <vm/pmap.h>
70 #include <vm/vm_map.h>
71 #include <vm/vm_object.h>
72 #include <vm/vm_page.h>
73 #include <vm/vm_pager.h>
74 #include <vm/vm_pageout.h>
75 #include <vm/vm_extern.h>
76 #include <vm/vm_kern.h>
77
78 #include <sys/file2.h>
79 #include <machine/limits.h>
80
81 typedef struct file *file_t;
82
83 /*
84  * fp_open:
85  *
86  *      Open a file as specified.  Use O_* flags for flags.
87  *
88  *      NOTE! O_ROOTCRED not quite working yet, vn_open() asserts that the
89  *      cred must match the process's cred. XXX
90  *
91  *      NOTE! when fp_open() is called from a pure thread, root creds are
92  *      used.
93  */
94 int
95 fp_open(const char *path, int flags, int mode, file_t *fpp)
96 {
97     struct nlookupdata nd;
98     struct thread *td;
99     struct file *fp;
100     int error;
101
102     if ((error = falloc(NULL, fpp, NULL)) != 0)
103         return (error);
104     fp = *fpp;
105     td = curthread;
106     if (td->td_proc) {
107         if ((flags & O_ROOTCRED) == 0)
108             fsetcred(fp, td->td_proc->p_ucred);
109     }
110     error = nlookup_init(&nd, path, UIO_SYSSPACE, NLC_LOCKVP);
111     flags = FFLAGS(flags);
112     if (error == 0)
113         error = vn_open(&nd, fp, flags, mode);
114     nlookup_done(&nd);
115     if (error) {
116         fdrop(fp);
117         *fpp = NULL;
118     }
119     return(error);
120 }
121
122
123 /*
124  * fp_vpopen(): convert a vnode to a file pointer, call VOP_OPEN() on the
125  * the vnode.  The vnode must be refd and locked.
126  *
127  * On success the vnode's ref is inherited by the file pointer and the caller
128  * should not vrele() it, and the vnode is unlocked.
129  *
130  * On failure the vnode remains locked and refd and the caller is responsible
131  * for vput()ing it.
132  */
133 int
134 fp_vpopen(struct vnode *vp, int flags, file_t *fpp)
135 {
136     struct thread *td;
137     struct file *fp;
138     int vmode;
139     int error;
140
141     td = curthread;
142
143     /*
144      * Vnode checks (from vn_open())
145      */
146     if (vp->v_type == VLNK) {
147         error = EMLINK;
148         goto bad2;
149     }
150     if (vp->v_type == VSOCK) {
151         error = EOPNOTSUPP;
152         goto bad2;
153     }
154     flags = FFLAGS(flags);
155     vmode = 0;
156     if (flags & (FWRITE | O_TRUNC)) {
157         if (vp->v_type == VDIR) {
158             error = EISDIR;
159             goto bad2;
160         }
161         error = vn_writechk(vp, NULL);
162         if (error)
163             goto bad2;
164         vmode |= VWRITE;
165     }
166     if (flags & FREAD)
167         vmode |= VREAD;
168     if (vmode) {
169         error = VOP_ACCESS(vp, vmode, td->td_proc->p_ucred);
170         if (error)
171             goto bad2;
172     }
173
174     /*
175      * File pointer setup
176      */
177     if ((error = falloc(NULL, fpp, NULL)) != 0)
178         goto bad2;
179     fp = *fpp;
180     if ((flags & O_ROOTCRED) == 0 && td->td_proc)
181         fsetcred(fp, td->td_proc->p_ucred);
182
183     error = VOP_OPEN(vp, flags, td->td_proc->p_ucred, fp);
184     if (error)
185         goto bad1;
186
187     vput(vp);
188     return (0);
189 bad1:
190     fp->f_ops = &badfileops;    /* open failed, don't close */
191     fp->f_data = NULL;
192     fdrop(fp);
193     /* leave the vnode intact, but fall through and unlock it anyway */
194 bad2:
195     *fpp = NULL;
196     return (error);
197 }
198
199 /*
200  * fp_*read() is meant to operate like the normal descriptor based syscalls
201  * would.  Note that if 'buf' points to user memory a UIO_USERSPACE
202  * transfer will be used.
203  */
204 int
205 fp_pread(file_t fp, void *buf, size_t nbytes, off_t offset, ssize_t *res,
206          enum uio_seg seg)
207 {
208     struct uio auio;
209     struct iovec aiov;
210     size_t count;
211     int error;
212
213     if (res)
214         *res = 0;
215     if (nbytes > LONG_MAX)
216         return (EINVAL);
217     bzero(&auio, sizeof(auio));
218     aiov.iov_base = (caddr_t)buf;
219     aiov.iov_len = nbytes;
220     auio.uio_iov = &aiov;
221     auio.uio_iovcnt = 1;
222     auio.uio_offset = offset;
223     auio.uio_resid = nbytes;
224     auio.uio_rw = UIO_READ;
225     auio.uio_segflg = seg;
226     auio.uio_td = curthread;
227
228     count = nbytes;
229     error = fo_read(fp, &auio, fp->f_cred, O_FOFFSET);
230     if (error) {
231         if (auio.uio_resid != nbytes && (error == ERESTART || error == EINTR ||
232             error == EWOULDBLOCK)
233         ) {
234             error = 0;
235         }
236     }
237     count -= auio.uio_resid;
238     if (res)
239         *res = count;
240     return(error);
241 }
242
243 int
244 fp_read(file_t fp, void *buf, size_t nbytes, ssize_t *res, int all,
245         enum uio_seg seg)
246 {
247     struct uio auio;
248     struct iovec aiov;
249     int error;
250     int lastresid;
251
252     if (res)
253         *res = 0;
254     if (nbytes > LONG_MAX)
255         return (EINVAL);
256     bzero(&auio, sizeof(auio));
257     aiov.iov_base = (caddr_t)buf;
258     aiov.iov_len = nbytes;
259     auio.uio_iov = &aiov;
260     auio.uio_iovcnt = 1;
261     auio.uio_offset = 0;
262     auio.uio_resid = nbytes;
263     auio.uio_rw = UIO_READ;
264     auio.uio_segflg = seg;
265     auio.uio_td = curthread;
266
267     /*
268      * If all is false call fo_read() once.
269      * If all is true we attempt to read the entire request.  We have to
270      * break out of the loop if an unrecoverable error or EOF occurs.
271      */
272     do {
273         lastresid = auio.uio_resid;
274         error = fo_read(fp, &auio, fp->f_cred, 0);
275     } while (all && auio.uio_resid &&
276              ((error == 0 && auio.uio_resid != lastresid) || 
277              error == ERESTART || error == EINTR));
278     if (all && error == 0 && auio.uio_resid)
279         error = ESPIPE;
280
281     /*
282      * If an error occured but some data was read, silently forget the
283      * error.  However, if this is a non-blocking descriptor and 'all'
284      * was specified, return an error even if some data was read (this
285      * is considered a bug in the caller for using an illegal combination
286      * of 'all' and a non-blocking descriptor).
287      */
288     if (error) {
289         if (auio.uio_resid != nbytes) {
290             if (error == ERESTART || error == EINTR)
291                 error = 0;
292             if (error == EWOULDBLOCK && all == 0)
293                 error = 0;
294         }
295     }
296     if (res)
297         *res = nbytes - auio.uio_resid;
298     return(error);
299 }
300
301 int
302 fp_pwrite(file_t fp, void *buf, size_t nbytes, off_t offset, ssize_t *res,
303           enum uio_seg seg)
304 {
305     struct uio auio;
306     struct iovec aiov;
307     size_t count;
308     int error;
309
310     if (res)
311         *res = 0;
312     if (nbytes > LONG_MAX)
313         return (EINVAL);
314     bzero(&auio, sizeof(auio));
315     aiov.iov_base = (caddr_t)buf;
316     aiov.iov_len = nbytes;
317     auio.uio_iov = &aiov;
318     auio.uio_iovcnt = 1;
319     auio.uio_offset = offset;
320     auio.uio_resid = nbytes;
321     auio.uio_rw = UIO_WRITE;
322     auio.uio_segflg = seg;
323     auio.uio_td = curthread;
324
325     count = nbytes;
326     error = fo_write(fp, &auio, fp->f_cred, O_FOFFSET);
327     if (error) {
328         if (auio.uio_resid != nbytes && (error == ERESTART || error == EINTR ||
329             error == EWOULDBLOCK)
330         ) {
331             error = 0;
332         }
333     }
334     count -= auio.uio_resid;
335     if (res)
336         *res = count;
337     return(error);
338 }
339
340
341 int
342 fp_write(file_t fp, void *buf, size_t nbytes, ssize_t *res, enum uio_seg seg)
343 {
344     struct uio auio;
345     struct iovec aiov;
346     size_t count;
347     int error;
348
349     if (res)
350         *res = 0;
351     if (nbytes > LONG_MAX)
352         return (EINVAL);
353     bzero(&auio, sizeof(auio));
354     aiov.iov_base = (caddr_t)buf;
355     aiov.iov_len = nbytes;
356     auio.uio_iov = &aiov;
357     auio.uio_iovcnt = 1;
358     auio.uio_offset = 0;
359     auio.uio_resid = nbytes;
360     auio.uio_rw = UIO_WRITE;
361     auio.uio_segflg = seg;
362     auio.uio_td = curthread;
363
364     count = nbytes;
365     error = fo_write(fp, &auio, fp->f_cred, 0);
366     if (error) {
367         if (auio.uio_resid != nbytes && (error == ERESTART || error == EINTR ||
368             error == EWOULDBLOCK)
369         ) {
370             error = 0;
371         }
372     }
373     count -= auio.uio_resid;
374     if (res)
375         *res = count;
376     return(error);
377 }
378
379 int
380 fp_stat(file_t fp, struct stat *ub)
381 {
382     int error;
383
384     error = fo_stat(fp, ub, fp->f_cred);
385     return(error);
386 }
387
388 /*
389  * non-anonymous, non-stack descriptor mappings only!
390  *
391  * This routine mostly snarfed from vm/vm_mmap.c
392  */
393 int
394 fp_mmap(void *addr_arg, size_t size, int prot, int flags, struct file *fp,
395     off_t pos, void **resp)
396 {
397     struct thread *td = curthread;
398     struct proc *p = td->td_proc;
399     vm_size_t pageoff;
400     vm_prot_t maxprot;
401     vm_offset_t addr;
402     void *handle;
403     int error;
404     vm_object_t obj;
405     struct vmspace *vms = p->p_vmspace;
406     struct vnode *vp;
407
408     prot &= VM_PROT_ALL;
409
410     if ((ssize_t)size < 0 || (flags & MAP_ANON))
411         return(EINVAL);
412
413     pageoff = (pos & PAGE_MASK);
414     pos -= pageoff;
415
416     /* Adjust size for rounding (on both ends). */
417     size += pageoff;                            /* low end... */
418     size = (vm_size_t)round_page(size);         /* hi end */
419     addr = (vm_offset_t)addr_arg;
420
421     /*
422      * Check for illegal addresses.  Watch out for address wrap... Note
423      * that VM_*_ADDRESS are not constants due to casts (argh).
424      */
425     if (flags & MAP_FIXED) {
426         /*
427          * The specified address must have the same remainder
428          * as the file offset taken modulo PAGE_SIZE, so it
429          * should be aligned after adjustment by pageoff.
430          */
431         addr -= pageoff;
432         if (addr & PAGE_MASK)
433             return (EINVAL);
434         /* Address range must be all in user VM space. */
435         if (VM_MAX_USER_ADDRESS > 0 && addr + size > VM_MAX_USER_ADDRESS)
436             return (EINVAL);
437         if (VM_MIN_USER_ADDRESS > 0 && addr < VM_MIN_USER_ADDRESS)
438             return (EINVAL);
439         if (addr + size < addr)
440             return (EINVAL);
441     } else if (addr == 0 ||
442         (addr >= round_page((vm_offset_t)vms->vm_taddr) &&
443          addr < round_page((vm_offset_t)vms->vm_daddr + maxdsiz))
444     ) {
445         /*
446          * XXX for non-fixed mappings where no hint is provided or
447          * the hint would fall in the potential heap space,
448          * place it after the end of the largest possible heap.
449          *
450          * There should really be a pmap call to determine a reasonable
451          * location.
452          */
453         addr = round_page((vm_offset_t)vms->vm_daddr + maxdsiz);
454     }
455
456     /*
457      * Mapping file, get fp for validation. Obtain vnode and make
458      * sure it is of appropriate type.
459      */
460     if (fp->f_type != DTYPE_VNODE)
461         return (EINVAL);
462
463     /*
464      * POSIX shared-memory objects are defined to have
465      * kernel persistence, and are not defined to support
466      * read(2)/write(2) -- or even open(2).  Thus, we can
467      * use MAP_ASYNC to trade on-disk coherence for speed.
468      * The shm_open(3) library routine turns on the FPOSIXSHM
469      * flag to request this behavior.
470      */
471     if (fp->f_flag & FPOSIXSHM)
472         flags |= MAP_NOSYNC;
473     vp = (struct vnode *) fp->f_data;
474     if (vp->v_type != VREG && vp->v_type != VCHR)
475         return (EINVAL);
476
477     /*
478      * Get the proper underlying object
479      */
480     if (vp->v_type == VREG) {
481         if ((obj = vp->v_object) == NULL)
482             return (EINVAL);
483         KKASSERT(vp == (struct vnode *)obj->handle);
484     }
485
486     /*
487      * XXX hack to handle use of /dev/zero to map anon memory (ala
488      * SunOS).
489      */
490     if (vp->v_type == VCHR && iszerodev(vp->v_rdev)) {
491         handle = NULL;
492         maxprot = VM_PROT_ALL;
493         flags |= MAP_ANON;
494         pos = 0;
495     } else {
496         /*
497          * cdevs does not provide private mappings of any kind.
498          */
499         if (vp->v_type == VCHR && 
500             (flags & (MAP_PRIVATE|MAP_COPY))) {
501                 error = EINVAL;
502                 goto done;
503         }
504         /*
505          * Ensure that file and memory protections are
506          * compatible.  Note that we only worry about
507          * writability if mapping is shared; in this case,
508          * current and max prot are dictated by the open file.
509          * XXX use the vnode instead?  Problem is: what
510          * credentials do we use for determination? What if
511          * proc does a setuid?
512          */
513         maxprot = VM_PROT_EXECUTE;      /* ??? */
514         if (fp->f_flag & FREAD) {
515             maxprot |= VM_PROT_READ;
516         } else if (prot & PROT_READ) {
517             error = EACCES;
518             goto done;
519         }
520         /*
521          * If we are sharing potential changes (either via
522          * MAP_SHARED or via the implicit sharing of character
523          * device mappings), and we are trying to get write
524          * permission although we opened it without asking
525          * for it, bail out.  
526          */
527
528         if ((flags & MAP_SHARED) != 0 ||
529             (vp->v_type == VCHR)
530         ) {
531             if ((fp->f_flag & FWRITE) != 0) {
532                 struct vattr va;
533                 if ((error = VOP_GETATTR(vp, &va))) {
534                     goto done;
535                 }
536                 if ((va.va_flags & (IMMUTABLE|APPEND)) == 0) {
537                     maxprot |= VM_PROT_WRITE;
538                 } else if (prot & PROT_WRITE) {
539                     error = EPERM;
540                     goto done;
541                 }
542             } else if ((prot & PROT_WRITE) != 0) {
543                 error = EACCES;
544                 goto done;
545             }
546         } else {
547             maxprot |= VM_PROT_WRITE;
548         }
549         handle = (void *)vp;
550     }
551     error = vm_mmap(&vms->vm_map, &addr, size, prot, 
552                     maxprot, flags, handle, pos);
553     if (error == 0 && addr_arg)
554         *resp = (void *)addr;
555 done:
556     return (error);
557 }
558
559 int
560 fp_close(file_t fp)
561 {
562     return(fdrop(fp));
563 }
564
565 int
566 fp_shutdown(file_t fp, int how)
567 {
568     return(fo_shutdown(fp, how));
569 }
570