Merge from vendor branch HOSTAPD:
[dragonfly.git] / sys / kern / vfs_vnops.c
1 /*
2  * Copyright (c) 1982, 1986, 1989, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      @(#)vfs_vnops.c 8.2 (Berkeley) 1/21/94
39  * $FreeBSD: src/sys/kern/vfs_vnops.c,v 1.87.2.13 2002/12/29 18:19:53 dillon Exp $
40  * $DragonFly: src/sys/kern/vfs_vnops.c,v 1.52 2007/07/30 08:02:38 dillon Exp $
41  */
42
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/fcntl.h>
46 #include <sys/file.h>
47 #include <sys/stat.h>
48 #include <sys/proc.h>
49 #include <sys/mount.h>
50 #include <sys/nlookup.h>
51 #include <sys/vnode.h>
52 #include <sys/buf.h>
53 #include <sys/filio.h>
54 #include <sys/ttycom.h>
55 #include <sys/conf.h>
56 #include <sys/syslog.h>
57
58 static int vn_closefile (struct file *fp);
59 static int vn_ioctl (struct file *fp, u_long com, caddr_t data,
60                 struct ucred *cred);
61 static int vn_read (struct file *fp, struct uio *uio, 
62                 struct ucred *cred, int flags);
63 static int svn_read (struct file *fp, struct uio *uio, 
64                 struct ucred *cred, int flags);
65 static int vn_poll (struct file *fp, int events, struct ucred *cred);
66 static int vn_kqfilter (struct file *fp, struct knote *kn);
67 static int vn_statfile (struct file *fp, struct stat *sb, struct ucred *cred);
68 static int vn_write (struct file *fp, struct uio *uio, 
69                 struct ucred *cred, int flags);
70 static int svn_write (struct file *fp, struct uio *uio, 
71                 struct ucred *cred, int flags);
72
73 struct fileops vnode_fileops = {
74         .fo_read = vn_read,
75         .fo_write = vn_write,
76         .fo_ioctl = vn_ioctl,
77         .fo_poll = vn_poll,
78         .fo_kqfilter = vn_kqfilter,
79         .fo_stat = vn_statfile,
80         .fo_close = vn_closefile,
81         .fo_shutdown = nofo_shutdown
82 };
83
84 struct fileops specvnode_fileops = {
85         .fo_read = svn_read,
86         .fo_write = svn_write,
87         .fo_ioctl = vn_ioctl,
88         .fo_poll = vn_poll,
89         .fo_kqfilter = vn_kqfilter,
90         .fo_stat = vn_statfile,
91         .fo_close = vn_closefile,
92         .fo_shutdown = nofo_shutdown
93 };
94
95 /*
96  * Shortcut the device read/write.  This avoids a lot of vnode junk.
97  * Basically the specfs vnops for read and write take the locked vnode,
98  * unlock it (because we can't hold the vnode locked while reading or writing
99  * a device which may block indefinitely), issues the device operation, then
100  * relock the vnode before returning, plus other junk.  This bypasses all
101  * of that and just does the device operation.
102  */
103 void
104 vn_setspecops(struct file *fp)
105 {
106         if (vfs_fastdev && fp->f_ops == &vnode_fileops) {
107                 fp->f_ops = &specvnode_fileops;
108         }
109 }
110
111 /*
112  * Common code for vnode open operations.  Check permissions, and call
113  * the VOP_NOPEN or VOP_NCREATE routine.
114  *
115  * The caller is responsible for setting up nd with nlookup_init() and
116  * for cleaning it up with nlookup_done(), whether we return an error
117  * or not.
118  *
119  * On success nd->nl_open_vp will hold a referenced and, if requested,
120  * locked vnode.  A locked vnode is requested via NLC_LOCKVP.  If fp
121  * is non-NULL the vnode will be installed in the file pointer.
122  *
123  * NOTE: The vnode is referenced just once on return whether or not it
124  * is also installed in the file pointer.
125  */
126 int
127 vn_open(struct nlookupdata *nd, struct file *fp, int fmode, int cmode)
128 {
129         struct vnode *vp;
130         struct ucred *cred = nd->nl_cred;
131         struct vattr vat;
132         struct vattr *vap = &vat;
133         int mode, error;
134
135         /*
136          * Lookup the path and create or obtain the vnode.  After a
137          * successful lookup a locked nd->nl_nch will be returned.
138          *
139          * The result of this section should be a locked vnode.
140          *
141          * XXX with only a little work we should be able to avoid locking
142          * the vnode if FWRITE, O_CREAT, and O_TRUNC are *not* set.
143          */
144         if (fmode & O_CREAT) {
145                 /*
146                  * CONDITIONAL CREATE FILE CASE
147                  *
148                  * Setting NLC_CREATE causes a negative hit to store
149                  * the negative hit ncp and not return an error.  Then
150                  * nc_error or nc_vp may be checked to see if the ncp 
151                  * represents a negative hit.  NLC_CREATE also requires
152                  * write permission on the governing directory or EPERM
153                  * is returned.
154                  */
155                 if ((fmode & O_EXCL) == 0 && (fmode & O_NOFOLLOW) == 0)
156                         nd->nl_flags |= NLC_FOLLOW;
157                 nd->nl_flags |= NLC_CREATE;
158                 bwillwrite();
159                 error = nlookup(nd);
160         } else {
161                 /*
162                  * NORMAL OPEN FILE CASE
163                  */
164                 error = nlookup(nd);
165         }
166
167         if (error)
168                 return (error);
169
170         /*
171          * split case to allow us to re-resolve and retry the ncp in case
172          * we get ESTALE.
173          */
174 again:
175         if (fmode & O_CREAT) {
176                 if (nd->nl_nch.ncp->nc_vp == NULL) {
177                         if ((error = ncp_writechk(&nd->nl_nch)) != 0)
178                                 return (error);
179                         VATTR_NULL(vap);
180                         vap->va_type = VREG;
181                         vap->va_mode = cmode;
182                         if (fmode & O_EXCL)
183                                 vap->va_vaflags |= VA_EXCLUSIVE;
184                         error = VOP_NCREATE(&nd->nl_nch, &vp, nd->nl_cred, vap);
185                         if (error)
186                                 return (error);
187                         fmode &= ~O_TRUNC;
188                         /* locked vnode is returned */
189                 } else {
190                         if (fmode & O_EXCL) {
191                                 error = EEXIST;
192                         } else {
193                                 error = cache_vget(&nd->nl_nch, cred, 
194                                                     LK_EXCLUSIVE, &vp);
195                         }
196                         if (error)
197                                 return (error);
198                         fmode &= ~O_CREAT;
199                 }
200         } else {
201                 error = cache_vget(&nd->nl_nch, cred, LK_EXCLUSIVE, &vp);
202                 if (error)
203                         return (error);
204         }
205
206         /*
207          * We have a locked vnode and ncp now.  Note that the ncp will
208          * be cleaned up by the caller if nd->nl_nch is left intact.
209          */
210         if (vp->v_type == VLNK) {
211                 error = EMLINK;
212                 goto bad;
213         }
214         if (vp->v_type == VSOCK) {
215                 error = EOPNOTSUPP;
216                 goto bad;
217         }
218         if ((fmode & O_CREAT) == 0) {
219                 mode = 0;
220                 if (fmode & (FWRITE | O_TRUNC)) {
221                         if (vp->v_type == VDIR) {
222                                 error = EISDIR;
223                                 goto bad;
224                         }
225                         error = vn_writechk(vp, &nd->nl_nch);
226                         if (error) {
227                                 /*
228                                  * Special stale handling, re-resolve the
229                                  * vnode.
230                                  */
231                                 if (error == ESTALE) {
232                                         vput(vp);
233                                         vp = NULL;
234                                         cache_setunresolved(&nd->nl_nch);
235                                         error = cache_resolve(&nd->nl_nch, cred);
236                                         if (error == 0)
237                                                 goto again;
238                                 }
239                                 goto bad;
240                         }
241                         mode |= VWRITE;
242                 }
243                 if (fmode & FREAD)
244                         mode |= VREAD;
245                 if (mode) {
246                         error = VOP_ACCESS(vp, mode, cred);
247                         if (error) {
248                                 /*
249                                  * Special stale handling, re-resolve the
250                                  * vnode.
251                                  */
252                                 if (error == ESTALE) {
253                                         vput(vp);
254                                         vp = NULL;
255                                         cache_setunresolved(&nd->nl_nch);
256                                         error = cache_resolve(&nd->nl_nch, cred);
257                                         if (error == 0)
258                                                 goto again;
259                                 }
260                                 goto bad;
261                         }
262                 }
263         }
264         if (fmode & O_TRUNC) {
265                 vn_unlock(vp);                          /* XXX */
266                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);   /* XXX */
267                 VATTR_NULL(vap);
268                 vap->va_size = 0;
269                 error = VOP_SETATTR(vp, vap, cred);
270                 if (error)
271                         goto bad;
272         }
273
274         /*
275          * Setup the fp so VOP_OPEN can override it.  No descriptor has been
276          * associated with the fp yet so we own it clean.  
277          *
278          * f_nchandle inherits nl_nch.  This used to be necessary only for
279          * directories but now we do it unconditionally so f*() ops
280          * such as fchmod() can access the actual namespace that was
281          * used to open the file.
282          */
283         if (fp) {
284                 fp->f_nchandle = nd->nl_nch;
285                 cache_zero(&nd->nl_nch);
286                 cache_unlock(&fp->f_nchandle);
287         }
288
289         /*
290          * Get rid of nl_nch.  vn_open does not return it (it returns the
291          * vnode or the file pointer).  Note: we can't leave nl_nch locked
292          * through the VOP_OPEN anyway since the VOP_OPEN may block, e.g.
293          * on /dev/ttyd0
294          */
295         if (nd->nl_nch.ncp)
296                 cache_put(&nd->nl_nch);
297
298         error = VOP_OPEN(vp, fmode, cred, fp);
299         if (error) {
300                 /*
301                  * setting f_ops to &badfileops will prevent the descriptor
302                  * code from trying to close and release the vnode, since
303                  * the open failed we do not want to call close.
304                  */
305                 if (fp) {
306                         fp->f_data = NULL;
307                         fp->f_ops = &badfileops;
308                 }
309                 goto bad;
310         }
311
312 #if 0
313         /*
314          * Assert that VREG files have been setup for vmio.
315          */
316         KASSERT(vp->v_type != VREG || vp->v_object != NULL,
317                 ("vn_open: regular file was not VMIO enabled!"));
318 #endif
319
320         /*
321          * Return the vnode.  XXX needs some cleaning up.  The vnode is
322          * only returned in the fp == NULL case.
323          */
324         if (fp == NULL) {
325                 nd->nl_open_vp = vp;
326                 nd->nl_vp_fmode = fmode;
327                 if ((nd->nl_flags & NLC_LOCKVP) == 0)
328                         vn_unlock(vp);
329         } else {
330                 vput(vp);
331         }
332         return (0);
333 bad:
334         if (vp)
335                 vput(vp);
336         return (error);
337 }
338
339 int
340 vn_opendisk(const char *devname, int fmode, struct vnode **vpp)
341 {
342         struct vnode *vp;
343         int error;
344
345         if (strncmp(devname, "/dev/", 5) == 0)
346                 devname += 5;
347         if ((vp = getsynthvnode(devname)) == NULL) {
348                 error = ENODEV;
349         } else {
350                 error = VOP_OPEN(vp, fmode, proc0.p_ucred, NULL);
351                 vn_unlock(vp);
352                 if (error) {
353                         vrele(vp);
354                         vp = NULL;
355                 }
356         }
357         *vpp = vp;
358         return (error);
359 }
360
361 /*
362  * Check for write permissions on the specified vnode.  nch may be NULL.
363  */
364 int
365 vn_writechk(struct vnode *vp, struct nchandle *nch)
366 {
367         /*
368          * If there's shared text associated with
369          * the vnode, try to free it up once.  If
370          * we fail, we can't allow writing.
371          */
372         if (vp->v_flag & VTEXT)
373                 return (ETXTBSY);
374
375         /*
376          * If the vnode represents a regular file, check the mount
377          * point via the nch.  This may be a different mount point
378          * then the one embedded in the vnode (e.g. nullfs).
379          *
380          * We can still write to non-regular files (e.g. devices)
381          * via read-only mounts.
382          */
383         if (nch && nch->ncp && vp->v_type == VREG)
384                 return (ncp_writechk(nch));
385         return (0);
386 }
387
388 /*
389  * Check whether the underlying mount is read-only.  The mount point 
390  * referenced by the namecache may be different from the mount point
391  * used by the underlying vnode in the case of NULLFS, so a separate
392  * check is needed.
393  */
394 int
395 ncp_writechk(struct nchandle *nch)
396 {
397         if (nch->mount && (nch->mount->mnt_flag & MNT_RDONLY))
398                 return (EROFS);
399         return(0);
400 }
401
402 /*
403  * Vnode close call
404  */
405 int
406 vn_close(struct vnode *vp, int flags)
407 {
408         int error;
409
410         if ((error = vn_lock(vp, LK_EXCLUSIVE | LK_RETRY)) == 0) {
411                 error = VOP_CLOSE(vp, flags);
412                 vn_unlock(vp);
413         }
414         vrele(vp);
415         return (error);
416 }
417
418 static __inline
419 int
420 sequential_heuristic(struct uio *uio, struct file *fp)
421 {
422         /*
423          * Sequential heuristic - detect sequential operation
424          */
425         if ((uio->uio_offset == 0 && fp->f_seqcount > 0) ||
426             uio->uio_offset == fp->f_nextoff) {
427                 int tmpseq = fp->f_seqcount;
428                 /*
429                  * XXX we assume that the filesystem block size is
430                  * the default.  Not true, but still gives us a pretty
431                  * good indicator of how sequential the read operations
432                  * are.
433                  */
434                 tmpseq += (uio->uio_resid + BKVASIZE - 1) / BKVASIZE;
435                 if (tmpseq > IO_SEQMAX)
436                         tmpseq = IO_SEQMAX;
437                 fp->f_seqcount = tmpseq;
438                 return(fp->f_seqcount << IO_SEQSHIFT);
439         }
440
441         /*
442          * Not sequential, quick draw-down of seqcount
443          */
444         if (fp->f_seqcount > 1)
445                 fp->f_seqcount = 1;
446         else
447                 fp->f_seqcount = 0;
448         return(0);
449 }
450
451 /*
452  * Package up an I/O request on a vnode into a uio and do it.
453  */
454 int
455 vn_rdwr(enum uio_rw rw, struct vnode *vp, caddr_t base, int len,
456         off_t offset, enum uio_seg segflg, int ioflg, 
457         struct ucred *cred, int *aresid)
458 {
459         struct uio auio;
460         struct iovec aiov;
461         struct ccms_lock ccms_lock;
462         int error;
463
464         if ((ioflg & IO_NODELOCKED) == 0)
465                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
466         auio.uio_iov = &aiov;
467         auio.uio_iovcnt = 1;
468         aiov.iov_base = base;
469         aiov.iov_len = len;
470         auio.uio_resid = len;
471         auio.uio_offset = offset;
472         auio.uio_segflg = segflg;
473         auio.uio_rw = rw;
474         auio.uio_td = curthread;
475         ccms_lock_get_uio(&vp->v_ccms, &ccms_lock, &auio);
476         if (rw == UIO_READ) {
477                 error = VOP_READ(vp, &auio, ioflg, cred);
478         } else {
479                 error = VOP_WRITE(vp, &auio, ioflg, cred);
480         }
481         ccms_lock_put(&vp->v_ccms, &ccms_lock);
482         if (aresid)
483                 *aresid = auio.uio_resid;
484         else
485                 if (auio.uio_resid && error == 0)
486                         error = EIO;
487         if ((ioflg & IO_NODELOCKED) == 0)
488                 vn_unlock(vp);
489         return (error);
490 }
491
492 /*
493  * Package up an I/O request on a vnode into a uio and do it.  The I/O
494  * request is split up into smaller chunks and we try to avoid saturating
495  * the buffer cache while potentially holding a vnode locked, so we 
496  * check bwillwrite() before calling vn_rdwr().  We also call uio_yield()
497  * to give other processes a chance to lock the vnode (either other processes
498  * core'ing the same binary, or unrelated processes scanning the directory).
499  */
500 int
501 vn_rdwr_inchunks(enum uio_rw rw, struct vnode *vp, caddr_t base, int len,
502                  off_t offset, enum uio_seg segflg, int ioflg,
503                  struct ucred *cred, int *aresid)
504 {
505         int error = 0;
506
507         do {
508                 int chunk;
509
510                 /*
511                  * Force `offset' to a multiple of MAXBSIZE except possibly
512                  * for the first chunk, so that filesystems only need to
513                  * write full blocks except possibly for the first and last
514                  * chunks.
515                  */
516                 chunk = MAXBSIZE - (uoff_t)offset % MAXBSIZE;
517
518                 if (chunk > len)
519                         chunk = len;
520                 if (rw != UIO_READ && vp->v_type == VREG)
521                         bwillwrite();
522                 error = vn_rdwr(rw, vp, base, chunk, offset, segflg,
523                             ioflg, cred, aresid);
524                 len -= chunk;   /* aresid calc already includes length */
525                 if (error)
526                         break;
527                 offset += chunk;
528                 base += chunk;
529                 uio_yield();
530         } while (len);
531         if (aresid)
532                 *aresid += len;
533         return (error);
534 }
535
536 /*
537  * MPALMOSTSAFE - acquires mplock
538  */
539 static int
540 vn_read(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
541 {
542         struct ccms_lock ccms_lock;
543         struct vnode *vp;
544         int error, ioflag;
545
546         get_mplock();
547         KASSERT(uio->uio_td == curthread,
548                 ("uio_td %p is not td %p", uio->uio_td, curthread));
549         vp = (struct vnode *)fp->f_data;
550
551         ioflag = 0;
552         if (flags & O_FBLOCKING) {
553                 /* ioflag &= ~IO_NDELAY; */
554         } else if (flags & O_FNONBLOCKING) {
555                 ioflag |= IO_NDELAY;
556         } else if (fp->f_flag & FNONBLOCK) {
557                 ioflag |= IO_NDELAY;
558         }
559         if (flags & O_FBUFFERED) {
560                 /* ioflag &= ~IO_DIRECT; */
561         } else if (flags & O_FUNBUFFERED) {
562                 ioflag |= IO_DIRECT;
563         } else if (fp->f_flag & O_DIRECT) {
564                 ioflag |= IO_DIRECT;
565         }
566         vn_lock(vp, LK_SHARED | LK_RETRY);
567         if ((flags & O_FOFFSET) == 0)
568                 uio->uio_offset = fp->f_offset;
569         ioflag |= sequential_heuristic(uio, fp);
570
571         ccms_lock_get_uio(&vp->v_ccms, &ccms_lock, uio);
572         error = VOP_READ(vp, uio, ioflag, cred);
573         ccms_lock_put(&vp->v_ccms, &ccms_lock);
574         if ((flags & O_FOFFSET) == 0)
575                 fp->f_offset = uio->uio_offset;
576         fp->f_nextoff = uio->uio_offset;
577         vn_unlock(vp);
578         rel_mplock();
579         return (error);
580 }
581
582 /*
583  * Device-optimized file table vnode read routine.
584  *
585  * This bypasses the VOP table and talks directly to the device.  Most
586  * filesystems just route to specfs and can make this optimization.
587  *
588  * MPALMOSTSAFE - acquires mplock
589  */
590 static int
591 svn_read(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
592 {
593         struct vnode *vp;
594         int ioflag;
595         int error;
596         cdev_t dev;
597
598         get_mplock();
599         KASSERT(uio->uio_td == curthread,
600                 ("uio_td %p is not td %p", uio->uio_td, curthread));
601
602         vp = (struct vnode *)fp->f_data;
603         if (vp == NULL || vp->v_type == VBAD) {
604                 error = EBADF;
605                 goto done;
606         }
607
608         if ((dev = vp->v_rdev) == NULL) {
609                 error = EBADF;
610                 goto done;
611         }
612         reference_dev(dev);
613
614         if (uio->uio_resid == 0) {
615                 error = 0;
616                 goto done;
617         }
618         if ((flags & O_FOFFSET) == 0)
619                 uio->uio_offset = fp->f_offset;
620
621         ioflag = 0;
622         if (flags & O_FBLOCKING) {
623                 /* ioflag &= ~IO_NDELAY; */
624         } else if (flags & O_FNONBLOCKING) {
625                 ioflag |= IO_NDELAY;
626         } else if (fp->f_flag & FNONBLOCK) {
627                 ioflag |= IO_NDELAY;
628         }
629         if (flags & O_FBUFFERED) {
630                 /* ioflag &= ~IO_DIRECT; */
631         } else if (flags & O_FUNBUFFERED) {
632                 ioflag |= IO_DIRECT;
633         } else if (fp->f_flag & O_DIRECT) {
634                 ioflag |= IO_DIRECT;
635         }
636         ioflag |= sequential_heuristic(uio, fp);
637
638         error = dev_dread(dev, uio, ioflag);
639
640         release_dev(dev);
641         if ((flags & O_FOFFSET) == 0)
642                 fp->f_offset = uio->uio_offset;
643         fp->f_nextoff = uio->uio_offset;
644 done:
645         rel_mplock();
646         return (error);
647 }
648
649 /*
650  * MPALMOSTSAFE - acquires mplock
651  */
652 static int
653 vn_write(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
654 {
655         struct ccms_lock ccms_lock;
656         struct vnode *vp;
657         int error, ioflag;
658
659         get_mplock();
660         KASSERT(uio->uio_td == curthread,
661                 ("uio_td %p is not p %p", uio->uio_td, curthread));
662         vp = (struct vnode *)fp->f_data;
663         if (vp->v_type == VREG)
664                 bwillwrite();
665         vp = (struct vnode *)fp->f_data;        /* XXX needed? */
666
667         ioflag = IO_UNIT;
668         if (vp->v_type == VREG &&
669            ((fp->f_flag & O_APPEND) || (flags & O_FAPPEND))) {
670                 ioflag |= IO_APPEND;
671         }
672
673         if (flags & O_FBLOCKING) {
674                 /* ioflag &= ~IO_NDELAY; */
675         } else if (flags & O_FNONBLOCKING) {
676                 ioflag |= IO_NDELAY;
677         } else if (fp->f_flag & FNONBLOCK) {
678                 ioflag |= IO_NDELAY;
679         }
680         if (flags & O_FBUFFERED) {
681                 /* ioflag &= ~IO_DIRECT; */
682         } else if (flags & O_FUNBUFFERED) {
683                 ioflag |= IO_DIRECT;
684         } else if (fp->f_flag & O_DIRECT) {
685                 ioflag |= IO_DIRECT;
686         }
687         if (flags & O_FASYNCWRITE) {
688                 /* ioflag &= ~IO_SYNC; */
689         } else if (flags & O_FSYNCWRITE) {
690                 ioflag |= IO_SYNC;
691         } else if (fp->f_flag & O_FSYNC) {
692                 ioflag |= IO_SYNC;
693         }
694
695         if (vp->v_mount && (vp->v_mount->mnt_flag & MNT_SYNCHRONOUS))
696                 ioflag |= IO_SYNC;
697         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
698         if ((flags & O_FOFFSET) == 0)
699                 uio->uio_offset = fp->f_offset;
700         ioflag |= sequential_heuristic(uio, fp);
701         ccms_lock_get_uio(&vp->v_ccms, &ccms_lock, uio);
702         error = VOP_WRITE(vp, uio, ioflag, cred);
703         ccms_lock_put(&vp->v_ccms, &ccms_lock);
704         if ((flags & O_FOFFSET) == 0)
705                 fp->f_offset = uio->uio_offset;
706         fp->f_nextoff = uio->uio_offset;
707         vn_unlock(vp);
708         rel_mplock();
709         return (error);
710 }
711
712 /*
713  * Device-optimized file table vnode write routine.
714  *
715  * This bypasses the VOP table and talks directly to the device.  Most
716  * filesystems just route to specfs and can make this optimization.
717  *
718  * MPALMOSTSAFE - acquires mplock
719  */
720 static int
721 svn_write(struct file *fp, struct uio *uio, struct ucred *cred, int flags)
722 {
723         struct vnode *vp;
724         int ioflag;
725         int error;
726         cdev_t dev;
727
728         get_mplock();
729         KASSERT(uio->uio_td == curthread,
730                 ("uio_td %p is not p %p", uio->uio_td, curthread));
731
732         vp = (struct vnode *)fp->f_data;
733         if (vp == NULL || vp->v_type == VBAD) {
734                 error = EBADF;
735                 goto done;
736         }
737         if (vp->v_type == VREG)
738                 bwillwrite();
739         vp = (struct vnode *)fp->f_data;        /* XXX needed? */
740
741         if ((dev = vp->v_rdev) == NULL) {
742                 error = EBADF;
743                 goto done;
744         }
745         reference_dev(dev);
746
747         if ((flags & O_FOFFSET) == 0)
748                 uio->uio_offset = fp->f_offset;
749
750         ioflag = IO_UNIT;
751         if (vp->v_type == VREG && 
752            ((fp->f_flag & O_APPEND) || (flags & O_FAPPEND))) {
753                 ioflag |= IO_APPEND;
754         }
755
756         if (flags & O_FBLOCKING) {
757                 /* ioflag &= ~IO_NDELAY; */
758         } else if (flags & O_FNONBLOCKING) {
759                 ioflag |= IO_NDELAY;
760         } else if (fp->f_flag & FNONBLOCK) {
761                 ioflag |= IO_NDELAY;
762         }
763         if (flags & O_FBUFFERED) {
764                 /* ioflag &= ~IO_DIRECT; */
765         } else if (flags & O_FUNBUFFERED) {
766                 ioflag |= IO_DIRECT;
767         } else if (fp->f_flag & O_DIRECT) {
768                 ioflag |= IO_DIRECT;
769         }
770         if (flags & O_FASYNCWRITE) {
771                 /* ioflag &= ~IO_SYNC; */
772         } else if (flags & O_FSYNCWRITE) {
773                 ioflag |= IO_SYNC;
774         } else if (fp->f_flag & O_FSYNC) {
775                 ioflag |= IO_SYNC;
776         }
777
778         if (vp->v_mount && (vp->v_mount->mnt_flag & MNT_SYNCHRONOUS))
779                 ioflag |= IO_SYNC;
780         ioflag |= sequential_heuristic(uio, fp);
781
782         error = dev_dwrite(dev, uio, ioflag);
783
784         release_dev(dev);
785         if ((flags & O_FOFFSET) == 0)
786                 fp->f_offset = uio->uio_offset;
787         fp->f_nextoff = uio->uio_offset;
788 done:
789         rel_mplock();
790         return (error);
791 }
792
793 /*
794  * MPALMOSTSAFE - acquires mplock
795  */
796 static int
797 vn_statfile(struct file *fp, struct stat *sb, struct ucred *cred)
798 {
799         struct vnode *vp;
800         int error;
801
802         get_mplock();
803         vp = (struct vnode *)fp->f_data;
804         error = vn_stat(vp, sb, cred);
805         rel_mplock();
806         return (error);
807 }
808
809 int
810 vn_stat(struct vnode *vp, struct stat *sb, struct ucred *cred)
811 {
812         struct vattr vattr;
813         struct vattr *vap;
814         int error;
815         u_short mode;
816         cdev_t dev;
817
818         vap = &vattr;
819         error = VOP_GETATTR(vp, vap);
820         if (error)
821                 return (error);
822
823         /*
824          * Zero the spare stat fields
825          */
826         sb->st_lspare = 0;
827         sb->st_qspare = 0;
828
829         /*
830          * Copy from vattr table
831          */
832         if (vap->va_fsid != VNOVAL)
833                 sb->st_dev = vap->va_fsid;
834         else
835                 sb->st_dev = vp->v_mount->mnt_stat.f_fsid.val[0];
836         sb->st_ino = vap->va_fileid;
837         mode = vap->va_mode;
838         switch (vap->va_type) {
839         case VREG:
840                 mode |= S_IFREG;
841                 break;
842         case VDIR:
843                 mode |= S_IFDIR;
844                 break;
845         case VBLK:
846                 mode |= S_IFBLK;
847                 break;
848         case VCHR:
849                 mode |= S_IFCHR;
850                 break;
851         case VLNK:
852                 mode |= S_IFLNK;
853                 /* This is a cosmetic change, symlinks do not have a mode. */
854                 if (vp->v_mount->mnt_flag & MNT_NOSYMFOLLOW)
855                         sb->st_mode &= ~ACCESSPERMS;    /* 0000 */
856                 else
857                         sb->st_mode |= ACCESSPERMS;     /* 0777 */
858                 break;
859         case VSOCK:
860                 mode |= S_IFSOCK;
861                 break;
862         case VFIFO:
863                 mode |= S_IFIFO;
864                 break;
865         default:
866                 return (EBADF);
867         };
868         sb->st_mode = mode;
869         sb->st_nlink = vap->va_nlink;
870         sb->st_uid = vap->va_uid;
871         sb->st_gid = vap->va_gid;
872         sb->st_rdev = makeudev(vap->va_rmajor, vap->va_rminor);
873         sb->st_size = vap->va_size;
874         sb->st_atimespec = vap->va_atime;
875         sb->st_mtimespec = vap->va_mtime;
876         sb->st_ctimespec = vap->va_ctime;
877
878         /*
879          * A VCHR and VBLK device may track the last access and last modified
880          * time independantly of the filesystem.  This is particularly true
881          * because device read and write calls may bypass the filesystem.
882          */
883         if (vp->v_type == VCHR || vp->v_type == VBLK) {
884                 if ((dev = vp->v_rdev) != NULL) {
885                         if (dev->si_lastread) {
886                                 sb->st_atimespec.tv_sec = dev->si_lastread;
887                                 sb->st_atimespec.tv_nsec = 0;
888                         }
889                         if (dev->si_lastwrite) {
890                                 sb->st_atimespec.tv_sec = dev->si_lastwrite;
891                                 sb->st_atimespec.tv_nsec = 0;
892                         }
893                 }
894         }
895
896         /*
897          * According to www.opengroup.org, the meaning of st_blksize is 
898          *   "a filesystem-specific preferred I/O block size for this 
899          *    object.  In some filesystem types, this may vary from file
900          *    to file"
901          * Default to PAGE_SIZE after much discussion.
902          */
903
904         if (vap->va_type == VREG) {
905                 sb->st_blksize = vap->va_blocksize;
906         } else if (vn_isdisk(vp, NULL)) {
907                 /*
908                  * XXX this is broken.  If the device is not yet open (aka
909                  * stat() call, aka v_rdev == NULL), how are we supposed
910                  * to get a valid block size out of it?
911                  */
912                 cdev_t dev;
913
914                 if ((dev = vp->v_rdev) == NULL) {
915                         if (vp->v_type == VCHR)
916                                 dev = get_dev(vp->v_umajor, vp->v_uminor);
917                 }
918                 sb->st_blksize = dev->si_bsize_best;
919                 if (sb->st_blksize < dev->si_bsize_phys)
920                         sb->st_blksize = dev->si_bsize_phys;
921                 if (sb->st_blksize < BLKDEV_IOSIZE)
922                         sb->st_blksize = BLKDEV_IOSIZE;
923         } else {
924                 sb->st_blksize = PAGE_SIZE;
925         }
926         
927         sb->st_flags = vap->va_flags;
928         if (suser_cred(cred, 0))
929                 sb->st_gen = 0;
930         else
931                 sb->st_gen = vap->va_gen;
932
933 #if (S_BLKSIZE == 512)
934         /* Optimize this case */
935         sb->st_blocks = vap->va_bytes >> 9;
936 #else
937         sb->st_blocks = vap->va_bytes / S_BLKSIZE;
938 #endif
939         sb->st_fsmid = vap->va_fsmid;
940         return (0);
941 }
942
943 /*
944  * MPALMOSTSAFE - acquires mplock
945  */
946 static int
947 vn_ioctl(struct file *fp, u_long com, caddr_t data, struct ucred *ucred)
948 {
949         struct vnode *vp = ((struct vnode *)fp->f_data);
950         struct vnode *ovp;
951         struct vattr vattr;
952         int error;
953
954         get_mplock();
955
956         switch (vp->v_type) {
957         case VREG:
958         case VDIR:
959                 if (com == FIONREAD) {
960                         if ((error = VOP_GETATTR(vp, &vattr)) != 0)
961                                 break;
962                         *(int *)data = vattr.va_size - fp->f_offset;
963                         error = 0;
964                         break;
965                 }
966                 if (com == FIOASYNC) {                          /* XXX */
967                         error = 0;                              /* XXX */
968                         break;
969                 }
970                 /* fall into ... */
971         default:
972 #if 0
973                 return (ENOTTY);
974 #endif
975         case VFIFO:
976         case VCHR:
977         case VBLK:
978                 if (com == FIODTYPE) {
979                         if (vp->v_type != VCHR && vp->v_type != VBLK) {
980                                 error = ENOTTY;
981                                 break;
982                         }
983                         *(int *)data = dev_dflags(vp->v_rdev) & D_TYPEMASK;
984                         error = 0;
985                         break;
986                 }
987                 error = VOP_IOCTL(vp, com, data, fp->f_flag, ucred);
988                 if (error == 0 && com == TIOCSCTTY) {
989                         struct proc *p = curthread->td_proc;
990                         struct session *sess;
991
992                         if (p == NULL) {
993                                 error = ENOTTY;
994                                 break;
995                         }
996
997                         sess = p->p_session;
998                         /* Do nothing if reassigning same control tty */
999                         if (sess->s_ttyvp == vp) {
1000                                 error = 0;
1001                                 break;
1002                         }
1003
1004                         /* Get rid of reference to old control tty */
1005                         ovp = sess->s_ttyvp;
1006                         vref(vp);
1007                         sess->s_ttyvp = vp;
1008                         if (ovp)
1009                                 vrele(ovp);
1010                 }
1011                 break;
1012         }
1013         rel_mplock();
1014         return (error);
1015 }
1016
1017 /*
1018  * MPALMOSTSAFE - acquires mplock
1019  */
1020 static int
1021 vn_poll(struct file *fp, int events, struct ucred *cred)
1022 {
1023         int error;
1024
1025         get_mplock();
1026         error = VOP_POLL(((struct vnode *)fp->f_data), events, cred);
1027         rel_mplock();
1028         return (error);
1029 }
1030
1031 /*
1032  * Check that the vnode is still valid, and if so
1033  * acquire requested lock.
1034  */
1035 int
1036 #ifndef DEBUG_LOCKS
1037 vn_lock(struct vnode *vp, int flags)
1038 #else
1039 debug_vn_lock(struct vnode *vp, int flags, const char *filename, int line)
1040 #endif
1041 {
1042         int error;
1043         
1044         do {
1045 #ifdef  DEBUG_LOCKS
1046                 vp->filename = filename;
1047                 vp->line = line;
1048                 error = debuglockmgr(&vp->v_lock, flags,
1049                                      "vn_lock", filename, line);
1050 #else
1051                 error = lockmgr(&vp->v_lock, flags);
1052 #endif
1053                 if (error == 0)
1054                         break;
1055         } while (flags & LK_RETRY);
1056
1057         /*
1058          * Because we (had better!) have a ref on the vnode, once it
1059          * goes to VRECLAIMED state it will not be recycled until all
1060          * refs go away.  So we can just check the flag.
1061          */
1062         if (error == 0 && (vp->v_flag & VRECLAIMED)) {
1063                 lockmgr(&vp->v_lock, LK_RELEASE);
1064                 error = ENOENT;
1065         }
1066         return (error);
1067 }
1068
1069 void
1070 vn_unlock(struct vnode *vp)
1071 {
1072         lockmgr(&vp->v_lock, LK_RELEASE);
1073 }
1074
1075 int
1076 vn_islocked(struct vnode *vp)
1077 {
1078         return (lockstatus(&vp->v_lock, curthread));
1079 }
1080
1081 /*
1082  * MPALMOSTSAFE - acquires mplock
1083  */
1084 static int
1085 vn_closefile(struct file *fp)
1086 {
1087         int error;
1088
1089         get_mplock();
1090         fp->f_ops = &badfileops;
1091         error = vn_close(((struct vnode *)fp->f_data), fp->f_flag);
1092         rel_mplock();
1093         return(error);
1094 }
1095
1096 /*
1097  * MPALMOSTSAFE - acquires mplock
1098  */
1099 static int
1100 vn_kqfilter(struct file *fp, struct knote *kn)
1101 {
1102         int error;
1103
1104         get_mplock();
1105         error = VOP_KQFILTER(((struct vnode *)fp->f_data), kn);
1106         rel_mplock();
1107         return (error);
1108 }