]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/fs/ext2fs/ext2_vnops.c
Add read-only support for extents in ext2fs.
[FreeBSD/stable/9.git] / sys / fs / ext2fs / ext2_vnops.c
1 /*-
2  *  modified for EXT2FS support in Lites 1.1
3  *
4  *  Aug 1995, Godmar Back (gback@cs.utah.edu)
5  *  University of Utah, Department of Computer Science
6  */
7 /*-
8  * Copyright (c) 1982, 1986, 1989, 1993
9  *      The Regents of the University of California.  All rights reserved.
10  * (c) UNIX System Laboratories, Inc.
11  * All or some portions of this file are derived from material licensed
12  * to the University of California by American Telephone and Telegraph
13  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
14  * the permission of UNIX System Laboratories, Inc.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  * 4. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  *
40  *      @(#)ufs_vnops.c 8.7 (Berkeley) 2/3/94
41  *      @(#)ufs_vnops.c 8.27 (Berkeley) 5/27/95
42  * $FreeBSD$
43  */
44
45 #include "opt_suiddir.h"
46
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/kernel.h>
50 #include <sys/fcntl.h>
51 #include <sys/filio.h>
52 #include <sys/stat.h>
53 #include <sys/bio.h>
54 #include <sys/buf.h>
55 #include <sys/endian.h>
56 #include <sys/priv.h>
57 #include <sys/mount.h>
58 #include <sys/unistd.h>
59 #include <sys/time.h>
60 #include <sys/vnode.h>
61 #include <sys/namei.h>
62 #include <sys/lockf.h>
63 #include <sys/event.h>
64 #include <sys/conf.h>
65 #include <sys/file.h>
66
67 #include <vm/vm.h>
68 #include <vm/vm_page.h>
69 #include <vm/vm_object.h>
70 #include <vm/vm_extern.h>
71 #include <vm/vnode_pager.h>
72
73 #include "opt_directio.h"
74
75 #include <fs/fifofs/fifo.h>
76
77 #include <ufs/ufs/dir.h>
78
79 #include <fs/ext2fs/fs.h>
80 #include <fs/ext2fs/inode.h>
81 #include <fs/ext2fs/ext2_extern.h>
82 #include <fs/ext2fs/ext2fs.h>
83 #include <fs/ext2fs/ext2_dinode.h>
84 #include <fs/ext2fs/ext2_dir.h>
85 #include <fs/ext2fs/ext2_mount.h>
86
87 static int ext2_makeinode(int mode, struct vnode *, struct vnode **, struct componentname *);
88 static void ext2_itimes_locked(struct vnode *);
89 static int ext4_ext_read(struct vop_read_args *);
90 static int ext2_ind_read(struct vop_read_args *);
91
92 static vop_access_t     ext2_access;
93 static int ext2_chmod(struct vnode *, int, struct ucred *, struct thread *);
94 static int ext2_chown(struct vnode *, uid_t, gid_t, struct ucred *,
95     struct thread *);
96 static vop_close_t      ext2_close;
97 static vop_create_t     ext2_create;
98 static vop_fsync_t      ext2_fsync;
99 static vop_getattr_t    ext2_getattr;
100 static vop_ioctl_t      ext2_ioctl;
101 static vop_link_t       ext2_link;
102 static vop_mkdir_t      ext2_mkdir;
103 static vop_mknod_t      ext2_mknod;
104 static vop_open_t       ext2_open;
105 static vop_pathconf_t   ext2_pathconf;
106 static vop_print_t      ext2_print;
107 static vop_read_t       ext2_read;
108 static vop_readlink_t   ext2_readlink;
109 static vop_remove_t     ext2_remove;
110 static vop_rename_t     ext2_rename;
111 static vop_rmdir_t      ext2_rmdir;
112 static vop_setattr_t    ext2_setattr;
113 static vop_strategy_t   ext2_strategy;
114 static vop_symlink_t    ext2_symlink;
115 static vop_write_t      ext2_write;
116 static vop_vptofh_t     ext2_vptofh;
117 static vop_close_t      ext2fifo_close;
118 static vop_kqfilter_t   ext2fifo_kqfilter;
119
120 /* Global vfs data structures for ext2. */
121 struct vop_vector ext2_vnodeops = {
122         .vop_default =          &default_vnodeops,
123         .vop_access =           ext2_access,
124         .vop_bmap =             ext2_bmap,
125         .vop_cachedlookup =     ext2_lookup,
126         .vop_close =            ext2_close,
127         .vop_create =           ext2_create,
128         .vop_fsync =            ext2_fsync,
129         .vop_getattr =          ext2_getattr,
130         .vop_inactive =         ext2_inactive,
131         .vop_ioctl =            ext2_ioctl,
132         .vop_link =             ext2_link,
133         .vop_lookup =           vfs_cache_lookup,
134         .vop_mkdir =            ext2_mkdir,
135         .vop_mknod =            ext2_mknod,
136         .vop_open =             ext2_open,
137         .vop_pathconf =         ext2_pathconf,
138         .vop_poll =             vop_stdpoll,
139         .vop_print =            ext2_print,
140         .vop_read =             ext2_read,
141         .vop_readdir =          ext2_readdir,
142         .vop_readlink =         ext2_readlink,
143         .vop_reallocblks =      ext2_reallocblks,
144         .vop_reclaim =          ext2_reclaim,
145         .vop_remove =           ext2_remove,
146         .vop_rename =           ext2_rename,
147         .vop_rmdir =            ext2_rmdir,
148         .vop_setattr =          ext2_setattr,
149         .vop_strategy =         ext2_strategy,
150         .vop_symlink =          ext2_symlink,
151         .vop_write =            ext2_write,
152         .vop_vptofh =           ext2_vptofh,
153 };
154
155 struct vop_vector ext2_fifoops = {
156         .vop_default =          &fifo_specops,
157         .vop_access =           ext2_access,
158         .vop_close =            ext2fifo_close,
159         .vop_fsync =            ext2_fsync,
160         .vop_getattr =          ext2_getattr,
161         .vop_inactive =         ext2_inactive,
162         .vop_kqfilter =         ext2fifo_kqfilter,
163         .vop_print =            ext2_print,
164         .vop_read =             VOP_PANIC,
165         .vop_reclaim =          ext2_reclaim,
166         .vop_setattr =          ext2_setattr,
167         .vop_write =            VOP_PANIC,
168         .vop_vptofh =           ext2_vptofh,
169 };
170
171 /*
172  * A virgin directory (no blushing please).
173  * Note that the type and namlen fields are reversed relative to ext2.
174  * Also, we don't use `struct odirtemplate', since it would just cause
175  * endianness problems.
176  */
177 static struct dirtemplate mastertemplate = {
178         0, 12, 1, EXT2_FT_DIR, ".",
179         0, DIRBLKSIZ - 12, 2, EXT2_FT_DIR, ".."
180 };
181 static struct dirtemplate omastertemplate = {
182         0, 12, 1, EXT2_FT_UNKNOWN, ".",
183         0, DIRBLKSIZ - 12, 2, EXT2_FT_UNKNOWN, ".."
184 };
185
186 static void
187 ext2_itimes_locked(struct vnode *vp)
188 {
189         struct inode *ip;
190         struct timespec ts;
191
192         ASSERT_VI_LOCKED(vp, __func__); 
193
194         ip = VTOI(vp);
195         if ((ip->i_flag & (IN_ACCESS | IN_CHANGE | IN_UPDATE)) == 0)
196                 return;
197         if ((vp->v_type == VBLK || vp->v_type == VCHR))
198                 ip->i_flag |= IN_LAZYMOD;
199         else
200                 ip->i_flag |= IN_MODIFIED;
201         if ((vp->v_mount->mnt_flag & MNT_RDONLY) == 0) {
202                 vfs_timestamp(&ts);
203                 if (ip->i_flag & IN_ACCESS) {
204                         ip->i_atime = ts.tv_sec;
205                         ip->i_atimensec = ts.tv_nsec;
206                 }
207                 if (ip->i_flag & IN_UPDATE) {
208                         ip->i_mtime = ts.tv_sec;
209                         ip->i_mtimensec = ts.tv_nsec;
210                         ip->i_modrev++;
211                 }
212                 if (ip->i_flag & IN_CHANGE) {
213                         ip->i_ctime = ts.tv_sec;
214                         ip->i_ctimensec = ts.tv_nsec;
215                 }
216         }
217         ip->i_flag &= ~(IN_ACCESS | IN_CHANGE | IN_UPDATE);
218 }
219
220 void
221 ext2_itimes(struct vnode *vp)
222 {
223
224         VI_LOCK(vp);
225         ext2_itimes_locked(vp);
226         VI_UNLOCK(vp);
227 }
228
229 /*
230  * Create a regular file
231  */
232 static int
233 ext2_create(struct vop_create_args *ap)
234 {
235         int error;
236
237         error =
238             ext2_makeinode(MAKEIMODE(ap->a_vap->va_type, ap->a_vap->va_mode),
239             ap->a_dvp, ap->a_vpp, ap->a_cnp);
240         if (error)
241                 return (error);
242         return (0);
243 }
244
245 static int
246 ext2_open(struct vop_open_args *ap)
247 {
248
249         if (ap->a_vp->v_type == VBLK || ap->a_vp->v_type == VCHR)
250                 return (EOPNOTSUPP);
251
252         /*
253          * Files marked append-only must be opened for appending.
254          */
255         if ((VTOI(ap->a_vp)->i_flags & APPEND) &&
256             (ap->a_mode & (FWRITE | O_APPEND)) == FWRITE)
257                 return (EPERM);
258
259         vnode_create_vobject(ap->a_vp, VTOI(ap->a_vp)->i_size, ap->a_td);
260
261         return (0);
262 }
263
264 /*
265  * Close called.
266  *
267  * Update the times on the inode.
268  */
269 static int
270 ext2_close(struct vop_close_args *ap)
271 {
272         struct vnode *vp = ap->a_vp;
273
274         VI_LOCK(vp);
275         if (vp->v_usecount > 1)
276                 ext2_itimes_locked(vp);
277         VI_UNLOCK(vp);
278         return (0);
279 }
280
281 static int
282 ext2_access(struct vop_access_args *ap)
283 {
284         struct vnode *vp = ap->a_vp;
285         struct inode *ip = VTOI(vp);
286         accmode_t accmode = ap->a_accmode;
287         int error;
288
289         if (vp->v_type == VBLK || vp->v_type == VCHR)
290                 return (EOPNOTSUPP);
291
292         /*
293          * Disallow write attempts on read-only file systems;
294          * unless the file is a socket, fifo, or a block or
295          * character device resident on the file system.
296          */
297         if (accmode & VWRITE) {
298                 switch (vp->v_type) {
299                 case VDIR:
300                 case VLNK:
301                 case VREG:
302                         if (vp->v_mount->mnt_flag & MNT_RDONLY)
303                                 return (EROFS);
304                         break;
305                 default:
306                         break;
307                 }
308         }
309
310         /* If immutable bit set, nobody gets to write it. */
311         if ((accmode & VWRITE) && (ip->i_flags & (SF_IMMUTABLE | SF_SNAPSHOT)))
312                 return (EPERM);
313
314         error = vaccess(vp->v_type, ip->i_mode, ip->i_uid, ip->i_gid,
315             ap->a_accmode, ap->a_cred, NULL);
316         return (error);
317 }
318
319 static int
320 ext2_getattr(struct vop_getattr_args *ap)
321 {
322         struct vnode *vp = ap->a_vp;
323         struct inode *ip = VTOI(vp);
324         struct vattr *vap = ap->a_vap;
325
326         ext2_itimes(vp);
327         /*
328          * Copy from inode table
329          */
330         vap->va_fsid = dev2udev(ip->i_devvp->v_rdev);
331         vap->va_fileid = ip->i_number;
332         vap->va_mode = ip->i_mode & ~IFMT;
333         vap->va_nlink = ip->i_nlink;
334         vap->va_uid = ip->i_uid;
335         vap->va_gid = ip->i_gid;
336         vap->va_rdev = ip->i_rdev;
337         vap->va_size = ip->i_size;
338         vap->va_atime.tv_sec = ip->i_atime;
339         vap->va_atime.tv_nsec = E2DI_HAS_XTIME(ip) ? ip->i_atimensec : 0;
340         vap->va_mtime.tv_sec = ip->i_mtime;
341         vap->va_mtime.tv_nsec = E2DI_HAS_XTIME(ip) ? ip->i_mtimensec : 0;
342         vap->va_ctime.tv_sec = ip->i_ctime;
343         vap->va_ctime.tv_nsec = E2DI_HAS_XTIME(ip) ? ip->i_ctimensec : 0;
344         if E2DI_HAS_XTIME(ip) {
345                 vap->va_birthtime.tv_sec = ip->i_birthtime;
346                 vap->va_birthtime.tv_nsec = ip->i_birthnsec;
347         }
348         vap->va_flags = ip->i_flags;
349         vap->va_gen = ip->i_gen;
350         vap->va_blocksize = vp->v_mount->mnt_stat.f_iosize;
351         vap->va_bytes = dbtob((u_quad_t)ip->i_blocks);
352         vap->va_type = IFTOVT(ip->i_mode);
353         vap->va_filerev = ip->i_modrev;
354         return (0);
355 }
356
357 /*
358  * Set attribute vnode op. called from several syscalls
359  */
360 static int
361 ext2_setattr(struct vop_setattr_args *ap)
362 {
363         struct vattr *vap = ap->a_vap;
364         struct vnode *vp = ap->a_vp;
365         struct inode *ip = VTOI(vp);
366         struct ucred *cred = ap->a_cred;
367         struct thread *td = curthread;
368         int error;
369
370         /*
371          * Check for unsettable attributes.
372          */
373         if ((vap->va_type != VNON) || (vap->va_nlink != VNOVAL) ||
374             (vap->va_fsid != VNOVAL) || (vap->va_fileid != VNOVAL) ||
375             (vap->va_blocksize != VNOVAL) || (vap->va_rdev != VNOVAL) ||
376             ((int)vap->va_bytes != VNOVAL) || (vap->va_gen != VNOVAL)) {
377                 return (EINVAL);
378         }
379         if (vap->va_flags != VNOVAL) {
380                 /* Disallow flags not supported by ext2fs. */
381                 if(vap->va_flags & ~(SF_APPEND | SF_IMMUTABLE | UF_NODUMP))
382                         return (EOPNOTSUPP);
383
384                 if (vp->v_mount->mnt_flag & MNT_RDONLY)
385                         return (EROFS);
386                 /*
387                  * Callers may only modify the file flags on objects they
388                  * have VADMIN rights for.
389                  */
390                 if ((error = VOP_ACCESS(vp, VADMIN, cred, td)))
391                         return (error);
392                 /*
393                  * Unprivileged processes and privileged processes in
394                  * jail() are not permitted to unset system flags, or
395                  * modify flags if any system flags are set.
396                  * Privileged non-jail processes may not modify system flags
397                  * if securelevel > 0 and any existing system flags are set.
398                  */
399                 if (!priv_check_cred(cred, PRIV_VFS_SYSFLAGS, 0)) {
400                         if (ip->i_flags &
401                             (SF_NOUNLINK | SF_IMMUTABLE | SF_APPEND)) {
402                                 error = securelevel_gt(cred, 0);
403                                 if (error)
404                                         return (error);
405                         }
406                         ip->i_flags = vap->va_flags;
407                 } else {
408                         if (ip->i_flags &
409                             (SF_NOUNLINK | SF_IMMUTABLE | SF_APPEND) ||
410                             (vap->va_flags & UF_SETTABLE) != vap->va_flags)
411                                 return (EPERM);
412                         ip->i_flags &= SF_SETTABLE;
413                         ip->i_flags |= (vap->va_flags & UF_SETTABLE);
414                 }
415                 ip->i_flag |= IN_CHANGE;
416                 if (ip->i_flags & (IMMUTABLE | APPEND))
417                         return (0);
418         }
419         if (ip->i_flags & (IMMUTABLE | APPEND))
420                 return (EPERM);
421         /*
422          * Go through the fields and update iff not VNOVAL.
423          */
424         if (vap->va_uid != (uid_t)VNOVAL || vap->va_gid != (gid_t)VNOVAL) {
425                 if (vp->v_mount->mnt_flag & MNT_RDONLY)
426                         return (EROFS);
427                 if ((error = ext2_chown(vp, vap->va_uid, vap->va_gid, cred,
428                     td)) != 0)
429                         return (error);
430         }
431         if (vap->va_size != VNOVAL) {
432                 /*
433                  * Disallow write attempts on read-only file systems;
434                  * unless the file is a socket, fifo, or a block or
435                  * character device resident on the file system.
436                  */
437                 switch (vp->v_type) {
438                 case VDIR:
439                         return (EISDIR);
440                 case VLNK:
441                 case VREG:
442                         if (vp->v_mount->mnt_flag & MNT_RDONLY)
443                                 return (EROFS);
444                         break;
445                 default:
446                         break;
447                 }
448                 if ((error = ext2_truncate(vp, vap->va_size, 0, cred, td)) != 0)
449                         return (error);
450         }
451         if (vap->va_atime.tv_sec != VNOVAL || vap->va_mtime.tv_sec != VNOVAL) {
452                 if (vp->v_mount->mnt_flag & MNT_RDONLY)
453                         return (EROFS);
454                 /*
455                  * From utimes(2):
456                  * If times is NULL, ... The caller must be the owner of
457                  * the file, have permission to write the file, or be the
458                  * super-user.
459                  * If times is non-NULL, ... The caller must be the owner of
460                  * the file or be the super-user.
461                  */
462                 if ((error = VOP_ACCESS(vp, VADMIN, cred, td)) &&
463                     ((vap->va_vaflags & VA_UTIMES_NULL) == 0 ||
464                     (error = VOP_ACCESS(vp, VWRITE, cred, td))))
465                         return (error);
466                 if (vap->va_atime.tv_sec != VNOVAL)
467                         ip->i_flag |= IN_ACCESS;
468                 if (vap->va_mtime.tv_sec != VNOVAL)
469                         ip->i_flag |= IN_CHANGE | IN_UPDATE;
470                 ext2_itimes(vp);
471                 if (vap->va_atime.tv_sec != VNOVAL) {
472                         ip->i_atime = vap->va_atime.tv_sec;
473                         ip->i_atimensec = vap->va_atime.tv_nsec;
474                 }
475                 if (vap->va_mtime.tv_sec != VNOVAL) {
476                         ip->i_mtime = vap->va_mtime.tv_sec;
477                         ip->i_mtimensec = vap->va_mtime.tv_nsec;
478                 }
479                 ip->i_birthtime = vap->va_birthtime.tv_sec;
480                 ip->i_birthnsec = vap->va_birthtime.tv_nsec;
481                 error = ext2_update(vp, 0);
482                 if (error)
483                         return (error);
484         }
485         error = 0;
486         if (vap->va_mode != (mode_t)VNOVAL) {
487                 if (vp->v_mount->mnt_flag & MNT_RDONLY)
488                         return (EROFS);
489                 error = ext2_chmod(vp, (int)vap->va_mode, cred, td);
490         }
491         return (error);
492 }
493
494 /*
495  * Change the mode on a file.
496  * Inode must be locked before calling.
497  */
498 static int
499 ext2_chmod(struct vnode *vp, int mode, struct ucred *cred, struct thread *td)
500 {
501         struct inode *ip = VTOI(vp);
502         int error;
503
504         /*
505          * To modify the permissions on a file, must possess VADMIN
506          * for that file.
507          */
508         if ((error = VOP_ACCESS(vp, VADMIN, cred, td)))
509                 return (error);
510         /*
511          * Privileged processes may set the sticky bit on non-directories,
512          * as well as set the setgid bit on a file with a group that the
513          * process is not a member of.
514          */
515         if (vp->v_type != VDIR && (mode & S_ISTXT)) {
516                 error = priv_check_cred(cred, PRIV_VFS_STICKYFILE, 0);
517                 if (error)
518                         return (EFTYPE);
519         }
520         if (!groupmember(ip->i_gid, cred) && (mode & ISGID)) {
521                 error = priv_check_cred(cred, PRIV_VFS_SETGID, 0);
522                 if (error)
523                         return (error);
524         }
525         ip->i_mode &= ~ALLPERMS;
526         ip->i_mode |= (mode & ALLPERMS);
527         ip->i_flag |= IN_CHANGE;
528         return (0);
529 }
530
531 /*
532  * Perform chown operation on inode ip;
533  * inode must be locked prior to call.
534  */
535 static int
536 ext2_chown(struct vnode *vp, uid_t uid, gid_t gid, struct ucred *cred,
537     struct thread *td)
538 {
539         struct inode *ip = VTOI(vp);
540         uid_t ouid;
541         gid_t ogid;
542         int error = 0;
543
544         if (uid == (uid_t)VNOVAL)
545                 uid = ip->i_uid;
546         if (gid == (gid_t)VNOVAL)
547                 gid = ip->i_gid;
548         /*
549          * To modify the ownership of a file, must possess VADMIN
550          * for that file.
551          */
552         if ((error = VOP_ACCESS(vp, VADMIN, cred, td)))
553                 return (error);
554         /*
555          * To change the owner of a file, or change the group of a file
556          * to a group of which we are not a member, the caller must
557          * have privilege.
558          */
559         if (uid != ip->i_uid || (gid != ip->i_gid &&
560             !groupmember(gid, cred))) {
561                 error = priv_check_cred(cred, PRIV_VFS_CHOWN, 0);
562                 if (error)
563                         return (error);
564         }
565         ogid = ip->i_gid;
566         ouid = ip->i_uid;
567         ip->i_gid = gid;
568         ip->i_uid = uid;
569         ip->i_flag |= IN_CHANGE;
570         if ((ip->i_mode & (ISUID | ISGID)) && (ouid != uid || ogid != gid)) {
571                 if (priv_check_cred(cred, PRIV_VFS_RETAINSUGID, 0) != 0)
572                         ip->i_mode &= ~(ISUID | ISGID);
573         }
574         return (0);
575 }
576
577 /*
578  * Synch an open file.
579  */
580 /* ARGSUSED */
581 static int
582 ext2_fsync(struct vop_fsync_args *ap)
583 {
584         /*
585          * Flush all dirty buffers associated with a vnode.
586          */
587
588         vop_stdfsync(ap);
589
590         return (ext2_update(ap->a_vp, ap->a_waitfor == MNT_WAIT));
591 }
592
593 /*
594  * Mknod vnode call
595  */
596 /* ARGSUSED */
597 static int
598 ext2_mknod(struct vop_mknod_args *ap)
599 {
600         struct vattr *vap = ap->a_vap;
601         struct vnode **vpp = ap->a_vpp;
602         struct inode *ip;
603         ino_t ino;
604         int error;
605
606         error = ext2_makeinode(MAKEIMODE(vap->va_type, vap->va_mode),
607             ap->a_dvp, vpp, ap->a_cnp);
608         if (error)
609                 return (error);
610         ip = VTOI(*vpp);
611         ip->i_flag |= IN_ACCESS | IN_CHANGE | IN_UPDATE;
612         if (vap->va_rdev != VNOVAL) {
613                 /*
614                  * Want to be able to use this to make badblock
615                  * inodes, so don't truncate the dev number.
616                  */
617                 ip->i_rdev = vap->va_rdev;
618         }
619         /*
620          * Remove inode, then reload it through VFS_VGET so it is
621          * checked to see if it is an alias of an existing entry in
622          * the inode cache.      XXX I don't believe this is necessary now.
623          */
624         (*vpp)->v_type = VNON;
625         ino = ip->i_number;     /* Save this before vgone() invalidates ip. */
626         vgone(*vpp);
627         vput(*vpp);
628         error = VFS_VGET(ap->a_dvp->v_mount, ino, LK_EXCLUSIVE, vpp);
629         if (error) {
630                 *vpp = NULL;
631                 return (error);
632         }
633         return (0);
634 }
635
636 static int
637 ext2_remove(struct vop_remove_args *ap)
638 {
639         struct inode *ip;
640         struct vnode *vp = ap->a_vp;
641         struct vnode *dvp = ap->a_dvp;
642         int error;
643
644         ip = VTOI(vp);
645         if ((ip->i_flags & (NOUNLINK | IMMUTABLE | APPEND)) ||
646             (VTOI(dvp)->i_flags & APPEND)) {
647                 error = EPERM;
648                 goto out;
649         }
650         error = ext2_dirremove(dvp, ap->a_cnp);
651         if (error == 0) {
652                 ip->i_nlink--;
653                 ip->i_flag |= IN_CHANGE;
654         }
655 out:
656         return (error);
657 }
658
659 /*
660  * link vnode call
661  */
662 static int
663 ext2_link(struct vop_link_args *ap)
664 {
665         struct vnode *vp = ap->a_vp;
666         struct vnode *tdvp = ap->a_tdvp;
667         struct componentname *cnp = ap->a_cnp;
668         struct inode *ip;
669         int error;
670
671 #ifdef INVARIANTS
672         if ((cnp->cn_flags & HASBUF) == 0)
673                 panic("ext2_link: no name");
674 #endif
675         if (tdvp->v_mount != vp->v_mount) {
676                 error = EXDEV;
677                 goto out;
678         }
679         ip = VTOI(vp);
680         if ((nlink_t)ip->i_nlink >= EXT2_LINK_MAX) {
681                 error = EMLINK;
682                 goto out;
683         }
684         if (ip->i_flags & (IMMUTABLE | APPEND)) {
685                 error = EPERM;
686                 goto out;
687         }
688         ip->i_nlink++;
689         ip->i_flag |= IN_CHANGE;
690         error = ext2_update(vp, !DOINGASYNC(vp));
691         if (!error)
692                 error = ext2_direnter(ip, tdvp, cnp);
693         if (error) {
694                 ip->i_nlink--;
695                 ip->i_flag |= IN_CHANGE;
696         }
697 out:
698         return (error);
699 }
700
701 /*
702  * Rename system call.
703  *      rename("foo", "bar");
704  * is essentially
705  *      unlink("bar");
706  *      link("foo", "bar");
707  *      unlink("foo");
708  * but ``atomically''.  Can't do full commit without saving state in the
709  * inode on disk which isn't feasible at this time.  Best we can do is
710  * always guarantee the target exists.
711  *
712  * Basic algorithm is:
713  *
714  * 1) Bump link count on source while we're linking it to the
715  *    target.  This also ensure the inode won't be deleted out
716  *    from underneath us while we work (it may be truncated by
717  *    a concurrent `trunc' or `open' for creation).
718  * 2) Link source to destination.  If destination already exists,
719  *    delete it first.
720  * 3) Unlink source reference to inode if still around. If a
721  *    directory was moved and the parent of the destination
722  *    is different from the source, patch the ".." entry in the
723  *    directory.
724  */
725 static int
726 ext2_rename(struct vop_rename_args *ap)
727 {
728         struct vnode *tvp = ap->a_tvp;
729         struct vnode *tdvp = ap->a_tdvp;
730         struct vnode *fvp = ap->a_fvp;
731         struct vnode *fdvp = ap->a_fdvp;
732         struct componentname *tcnp = ap->a_tcnp;
733         struct componentname *fcnp = ap->a_fcnp;
734         struct inode *ip, *xp, *dp;
735         struct dirtemplate dirbuf;
736         int doingdirectory = 0, oldparent = 0, newparent = 0;
737         int error = 0;
738         u_char namlen;
739
740 #ifdef INVARIANTS
741         if ((tcnp->cn_flags & HASBUF) == 0 ||
742             (fcnp->cn_flags & HASBUF) == 0)
743                 panic("ext2_rename: no name");
744 #endif
745         /*
746          * Check for cross-device rename.
747          */
748         if ((fvp->v_mount != tdvp->v_mount) ||
749             (tvp && (fvp->v_mount != tvp->v_mount))) {
750                 error = EXDEV;
751 abortit:
752                 if (tdvp == tvp)
753                         vrele(tdvp);
754                 else
755                         vput(tdvp);
756                 if (tvp)
757                         vput(tvp);
758                 vrele(fdvp);
759                 vrele(fvp);
760                 return (error);
761         }
762
763         if (tvp && ((VTOI(tvp)->i_flags & (NOUNLINK | IMMUTABLE | APPEND)) ||
764             (VTOI(tdvp)->i_flags & APPEND))) {
765                 error = EPERM;
766                 goto abortit;
767         }
768
769         /*
770          * Renaming a file to itself has no effect.  The upper layers should
771          * not call us in that case.  Temporarily just warn if they do.
772          */
773         if (fvp == tvp) {
774                 printf("ext2_rename: fvp == tvp (can't happen)\n");
775                 error = 0;
776                 goto abortit;
777         }
778
779         if ((error = vn_lock(fvp, LK_EXCLUSIVE)) != 0)
780                 goto abortit;
781         dp = VTOI(fdvp);
782         ip = VTOI(fvp);
783         if (ip->i_nlink >= EXT2_LINK_MAX) {
784                 VOP_UNLOCK(fvp, 0);
785                 error = EMLINK;
786                 goto abortit;
787         }
788         if ((ip->i_flags & (NOUNLINK | IMMUTABLE | APPEND))
789             || (dp->i_flags & APPEND)) {
790                 VOP_UNLOCK(fvp, 0);
791                 error = EPERM;
792                 goto abortit;
793         }
794         if ((ip->i_mode & IFMT) == IFDIR) {
795                 /*
796                  * Avoid ".", "..", and aliases of "." for obvious reasons.
797                  */
798                 if ((fcnp->cn_namelen == 1 && fcnp->cn_nameptr[0] == '.') ||
799                     dp == ip || (fcnp->cn_flags | tcnp->cn_flags) & ISDOTDOT ||
800                     (ip->i_flag & IN_RENAME)) {
801                         VOP_UNLOCK(fvp, 0);
802                         error = EINVAL;
803                         goto abortit;
804                 }
805                 ip->i_flag |= IN_RENAME;
806                 oldparent = dp->i_number;
807                 doingdirectory++;
808         }
809         vrele(fdvp);
810
811         /*
812          * When the target exists, both the directory
813          * and target vnodes are returned locked.
814          */
815         dp = VTOI(tdvp);
816         xp = NULL;
817         if (tvp)
818                 xp = VTOI(tvp);
819
820         /*
821          * 1) Bump link count while we're moving stuff
822          *    around.  If we crash somewhere before
823          *    completing our work, the link count
824          *    may be wrong, but correctable.
825          */
826         ip->i_nlink++;
827         ip->i_flag |= IN_CHANGE;
828         if ((error = ext2_update(fvp, !DOINGASYNC(fvp))) != 0) {
829                 VOP_UNLOCK(fvp, 0);
830                 goto bad;
831         }
832
833         /*
834          * If ".." must be changed (ie the directory gets a new
835          * parent) then the source directory must not be in the
836          * directory hierarchy above the target, as this would
837          * orphan everything below the source directory. Also
838          * the user must have write permission in the source so
839          * as to be able to change "..". We must repeat the call
840          * to namei, as the parent directory is unlocked by the
841          * call to checkpath().
842          */
843         error = VOP_ACCESS(fvp, VWRITE, tcnp->cn_cred, tcnp->cn_thread);
844         VOP_UNLOCK(fvp, 0);
845         if (oldparent != dp->i_number)
846                 newparent = dp->i_number;
847         if (doingdirectory && newparent) {
848                 if (error)      /* write access check above */
849                         goto bad;
850                 if (xp != NULL)
851                         vput(tvp);
852                 error = ext2_checkpath(ip, dp, tcnp->cn_cred);
853                 if (error)
854                         goto out;
855                 VREF(tdvp);
856                 error = relookup(tdvp, &tvp, tcnp);
857                 if (error)
858                         goto out;
859                 vrele(tdvp);
860                 dp = VTOI(tdvp);
861                 xp = NULL;
862                 if (tvp)
863                         xp = VTOI(tvp);
864         }
865         /*
866          * 2) If target doesn't exist, link the target
867          *    to the source and unlink the source.
868          *    Otherwise, rewrite the target directory
869          *    entry to reference the source inode and
870          *    expunge the original entry's existence.
871          */
872         if (xp == NULL) {
873                 if (dp->i_devvp != ip->i_devvp)
874                         panic("ext2_rename: EXDEV");
875                 /*
876                  * Account for ".." in new directory.
877                  * When source and destination have the same
878                  * parent we don't fool with the link count.
879                  */
880                 if (doingdirectory && newparent) {
881                         if ((nlink_t)dp->i_nlink >= EXT2_LINK_MAX) {
882                                 error = EMLINK;
883                                 goto bad;
884                         }
885                         dp->i_nlink++;
886                         dp->i_flag |= IN_CHANGE;
887                         error = ext2_update(tdvp, !DOINGASYNC(tdvp));
888                         if (error)
889                                 goto bad;
890                 }
891                 error = ext2_direnter(ip, tdvp, tcnp);
892                 if (error) {
893                         if (doingdirectory && newparent) {
894                                 dp->i_nlink--;
895                                 dp->i_flag |= IN_CHANGE;
896                                 (void)ext2_update(tdvp, 1);
897                         }
898                         goto bad;
899                 }
900                 vput(tdvp);
901         } else {
902                 if (xp->i_devvp != dp->i_devvp || xp->i_devvp != ip->i_devvp)
903                        panic("ext2_rename: EXDEV");
904                 /*
905                  * Short circuit rename(foo, foo).
906                  */
907                 if (xp->i_number == ip->i_number)
908                         panic("ext2_rename: same file");
909                 /*
910                  * If the parent directory is "sticky", then the user must
911                  * own the parent directory, or the destination of the rename,
912                  * otherwise the destination may not be changed (except by
913                  * root). This implements append-only directories.
914                  */
915                 if ((dp->i_mode & S_ISTXT) && tcnp->cn_cred->cr_uid != 0 &&
916                     tcnp->cn_cred->cr_uid != dp->i_uid &&
917                     xp->i_uid != tcnp->cn_cred->cr_uid) {
918                         error = EPERM;
919                         goto bad;
920                 }
921                 /*
922                  * Target must be empty if a directory and have no links
923                  * to it. Also, ensure source and target are compatible
924                  * (both directories, or both not directories).
925                  */
926                 if ((xp->i_mode&IFMT) == IFDIR) {
927                         if (! ext2_dirempty(xp, dp->i_number, tcnp->cn_cred) || 
928                             xp->i_nlink > 2) {
929                                 error = ENOTEMPTY;
930                                 goto bad;
931                         }
932                         if (!doingdirectory) {
933                                 error = ENOTDIR;
934                                 goto bad;
935                         }
936                         cache_purge(tdvp);
937                 } else if (doingdirectory) {
938                         error = EISDIR;
939                         goto bad;
940                 }
941                 error = ext2_dirrewrite(dp, ip, tcnp);
942                 if (error)
943                         goto bad;
944                 /*
945                  * If the target directory is in the same
946                  * directory as the source directory,
947                  * decrement the link count on the parent
948                  * of the target directory.
949                  */
950                 if (doingdirectory && !newparent) {
951                        dp->i_nlink--;
952                        dp->i_flag |= IN_CHANGE;
953                 }
954                 vput(tdvp);
955                 /*
956                  * Adjust the link count of the target to
957                  * reflect the dirrewrite above.  If this is
958                  * a directory it is empty and there are
959                  * no links to it, so we can squash the inode and
960                  * any space associated with it.  We disallowed
961                  * renaming over top of a directory with links to
962                  * it above, as the remaining link would point to
963                  * a directory without "." or ".." entries.
964                  */
965                 xp->i_nlink--;
966                 if (doingdirectory) {
967                         if (--xp->i_nlink != 0)
968                                 panic("ext2_rename: linked directory");
969                         error = ext2_truncate(tvp, (off_t)0, IO_SYNC,
970                             tcnp->cn_cred, tcnp->cn_thread);
971                 }
972                 xp->i_flag |= IN_CHANGE;
973                 vput(tvp);
974                 xp = NULL;
975         }
976
977         /*
978          * 3) Unlink the source.
979          */
980         fcnp->cn_flags &= ~MODMASK;
981         fcnp->cn_flags |= LOCKPARENT | LOCKLEAF;
982         VREF(fdvp);
983         error = relookup(fdvp, &fvp, fcnp);
984         if (error == 0)
985                 vrele(fdvp);
986         if (fvp != NULL) {
987                 xp = VTOI(fvp);
988                 dp = VTOI(fdvp);
989         } else {
990                 /*
991                  * From name has disappeared.
992                  */
993                 if (doingdirectory)
994                         panic("ext2_rename: lost dir entry");
995                 vrele(ap->a_fvp);
996                 return (0);
997         }
998         /*
999          * Ensure that the directory entry still exists and has not
1000          * changed while the new name has been entered. If the source is
1001          * a file then the entry may have been unlinked or renamed. In
1002          * either case there is no further work to be done. If the source
1003          * is a directory then it cannot have been rmdir'ed; its link
1004          * count of three would cause a rmdir to fail with ENOTEMPTY.
1005          * The IN_RENAME flag ensures that it cannot be moved by another
1006          * rename.
1007          */
1008         if (xp != ip) {
1009                 if (doingdirectory)
1010                         panic("ext2_rename: lost dir entry");
1011         } else {
1012                 /*
1013                  * If the source is a directory with a
1014                  * new parent, the link count of the old
1015                  * parent directory must be decremented
1016                  * and ".." set to point to the new parent.
1017                  */
1018                 if (doingdirectory && newparent) {
1019                         dp->i_nlink--;
1020                         dp->i_flag |= IN_CHANGE;
1021                         error = vn_rdwr(UIO_READ, fvp, (caddr_t)&dirbuf,
1022                                 sizeof(struct dirtemplate), (off_t)0,
1023                                 UIO_SYSSPACE, IO_NODELOCKED | IO_NOMACCHECK,
1024                                 tcnp->cn_cred, NOCRED, NULL, NULL);
1025                         if (error == 0) {
1026                                 /* Like ufs little-endian: */
1027                                 namlen = dirbuf.dotdot_type;
1028                                 if (namlen != 2 ||
1029                                     dirbuf.dotdot_name[0] != '.' ||
1030                                     dirbuf.dotdot_name[1] != '.') {
1031                                         ext2_dirbad(xp, (doff_t)12,
1032                                             "rename: mangled dir");
1033                                 } else {
1034                                         dirbuf.dotdot_ino = newparent;
1035                                         (void) vn_rdwr(UIO_WRITE, fvp,
1036                                             (caddr_t)&dirbuf,
1037                                             sizeof(struct dirtemplate),
1038                                             (off_t)0, UIO_SYSSPACE,
1039                                             IO_NODELOCKED | IO_SYNC |
1040                                             IO_NOMACCHECK, tcnp->cn_cred,
1041                                             NOCRED, NULL, NULL);
1042                                         cache_purge(fdvp);
1043                                 }
1044                         }
1045                 }
1046                 error = ext2_dirremove(fdvp, fcnp);
1047                 if (!error) {
1048                         xp->i_nlink--;
1049                         xp->i_flag |= IN_CHANGE;
1050                 }
1051                 xp->i_flag &= ~IN_RENAME;
1052         }
1053         if (dp)
1054                 vput(fdvp);
1055         if (xp)
1056                 vput(fvp);
1057         vrele(ap->a_fvp);
1058         return (error);
1059
1060 bad:
1061         if (xp)
1062                 vput(ITOV(xp));
1063         vput(ITOV(dp));
1064 out:
1065         if (doingdirectory)
1066                 ip->i_flag &= ~IN_RENAME;
1067         if (vn_lock(fvp, LK_EXCLUSIVE) == 0) {
1068                 ip->i_nlink--;
1069                 ip->i_flag |= IN_CHANGE;
1070                 ip->i_flag &= ~IN_RENAME;
1071                 vput(fvp);
1072         } else
1073                 vrele(fvp);
1074         return (error);
1075 }
1076
1077 /*
1078  * Mkdir system call
1079  */
1080 static int
1081 ext2_mkdir(struct vop_mkdir_args *ap)
1082 {
1083         struct vnode *dvp = ap->a_dvp;
1084         struct vattr *vap = ap->a_vap;
1085         struct componentname *cnp = ap->a_cnp;
1086         struct inode *ip, *dp;
1087         struct vnode *tvp;
1088         struct dirtemplate dirtemplate, *dtp;
1089         int error, dmode;
1090
1091 #ifdef INVARIANTS
1092         if ((cnp->cn_flags & HASBUF) == 0)
1093                 panic("ext2_mkdir: no name");
1094 #endif
1095         dp = VTOI(dvp);
1096         if ((nlink_t)dp->i_nlink >= EXT2_LINK_MAX) {
1097                 error = EMLINK;
1098                 goto out;
1099         }
1100         dmode = vap->va_mode & 0777;
1101         dmode |= IFDIR;
1102         /*
1103          * Must simulate part of ext2_makeinode here to acquire the inode,
1104          * but not have it entered in the parent directory. The entry is
1105          * made later after writing "." and ".." entries.
1106          */
1107         error = ext2_valloc(dvp, dmode, cnp->cn_cred, &tvp);
1108         if (error)
1109                 goto out;
1110         ip = VTOI(tvp);
1111         ip->i_gid = dp->i_gid;
1112 #ifdef SUIDDIR
1113         {
1114                 /*
1115                  * if we are hacking owners here, (only do this where told to)
1116                  * and we are not giving it TOO root, (would subvert quotas)
1117                  * then go ahead and give it to the other user.
1118                  * The new directory also inherits the SUID bit. 
1119                  * If user's UID and dir UID are the same,
1120                  * 'give it away' so that the SUID is still forced on.
1121                  */
1122                 if ( (dvp->v_mount->mnt_flag & MNT_SUIDDIR) &&
1123                    (dp->i_mode & ISUID) && dp->i_uid) {
1124                         dmode |= ISUID;
1125                         ip->i_uid = dp->i_uid;
1126                 } else {
1127                         ip->i_uid = cnp->cn_cred->cr_uid;
1128                 }
1129         }
1130 #else
1131         ip->i_uid = cnp->cn_cred->cr_uid;
1132 #endif
1133         ip->i_flag |= IN_ACCESS | IN_CHANGE | IN_UPDATE;
1134         ip->i_mode = dmode;
1135         tvp->v_type = VDIR;     /* Rest init'd in getnewvnode(). */
1136         ip->i_nlink = 2;
1137         if (cnp->cn_flags & ISWHITEOUT)
1138                 ip->i_flags |= UF_OPAQUE;
1139         error = ext2_update(tvp, 1);
1140
1141         /*
1142          * Bump link count in parent directory
1143          * to reflect work done below.  Should
1144          * be done before reference is created
1145          * so reparation is possible if we crash.
1146          */
1147         dp->i_nlink++;
1148         dp->i_flag |= IN_CHANGE;
1149         error = ext2_update(dvp, !DOINGASYNC(dvp));
1150         if (error)
1151                 goto bad;
1152
1153         /* Initialize directory with "." and ".." from static template. */
1154         if (EXT2_HAS_INCOMPAT_FEATURE(ip->i_e2fs,
1155             EXT2F_INCOMPAT_FTYPE))
1156                 dtp = &mastertemplate;
1157         else
1158                 dtp = &omastertemplate;
1159         dirtemplate = *dtp;
1160         dirtemplate.dot_ino = ip->i_number;
1161         dirtemplate.dotdot_ino = dp->i_number;
1162         /* note that in ext2 DIRBLKSIZ == blocksize, not DEV_BSIZE 
1163          * so let's just redefine it - for this function only
1164          */
1165 #undef  DIRBLKSIZ 
1166 #define DIRBLKSIZ  VTOI(dvp)->i_e2fs->e2fs_bsize
1167         dirtemplate.dotdot_reclen = DIRBLKSIZ - 12;
1168         error = vn_rdwr(UIO_WRITE, tvp, (caddr_t)&dirtemplate,
1169             sizeof(dirtemplate), (off_t)0, UIO_SYSSPACE,
1170             IO_NODELOCKED | IO_SYNC | IO_NOMACCHECK, cnp->cn_cred, NOCRED,
1171             NULL, NULL);
1172         if (error) {
1173                 dp->i_nlink--;
1174                 dp->i_flag |= IN_CHANGE;
1175                 goto bad;
1176         }
1177         if (DIRBLKSIZ > VFSTOEXT2(dvp->v_mount)->um_mountp->mnt_stat.f_bsize)
1178                 /* XXX should grow with balloc() */
1179                 panic("ext2_mkdir: blksize");
1180         else {
1181                 ip->i_size = DIRBLKSIZ;
1182                 ip->i_flag |= IN_CHANGE;
1183         }
1184
1185         /* Directory set up, now install its entry in the parent directory. */
1186         error = ext2_direnter(ip, dvp, cnp);
1187         if (error) {
1188                 dp->i_nlink--;
1189                 dp->i_flag |= IN_CHANGE;
1190         }
1191 bad:
1192         /*
1193          * No need to do an explicit VOP_TRUNCATE here, vrele will do this
1194          * for us because we set the link count to 0.
1195          */
1196         if (error) {
1197                 ip->i_nlink = 0;
1198                 ip->i_flag |= IN_CHANGE;
1199                 vput(tvp);
1200         } else
1201                 *ap->a_vpp = tvp;
1202 out:
1203         return (error);
1204 #undef  DIRBLKSIZ
1205 #define DIRBLKSIZ  DEV_BSIZE
1206 }
1207
1208 /*
1209  * Rmdir system call.
1210  */
1211 static int
1212 ext2_rmdir(struct vop_rmdir_args *ap)
1213 {
1214         struct vnode *vp = ap->a_vp;
1215         struct vnode *dvp = ap->a_dvp;
1216         struct componentname *cnp = ap->a_cnp;
1217         struct inode *ip, *dp;
1218         int error;
1219
1220         ip = VTOI(vp);
1221         dp = VTOI(dvp);
1222
1223         /*
1224          * Verify the directory is empty (and valid).
1225          * (Rmdir ".." won't be valid since
1226          *  ".." will contain a reference to
1227          *  the current directory and thus be
1228          *  non-empty.)
1229          */
1230         error = 0;
1231         if (ip->i_nlink != 2 || !ext2_dirempty(ip, dp->i_number, cnp->cn_cred)) {
1232                 error = ENOTEMPTY;
1233                 goto out;
1234         }
1235         if ((dp->i_flags & APPEND)
1236             || (ip->i_flags & (NOUNLINK | IMMUTABLE | APPEND))) {
1237                 error = EPERM;
1238                 goto out;
1239         }
1240         /*
1241          * Delete reference to directory before purging
1242          * inode.  If we crash in between, the directory
1243          * will be reattached to lost+found,
1244          */
1245         error = ext2_dirremove(dvp, cnp);
1246         if (error)
1247                 goto out;
1248         dp->i_nlink--;
1249         dp->i_flag |= IN_CHANGE;
1250         cache_purge(dvp);
1251         VOP_UNLOCK(dvp, 0);
1252         /*
1253          * Truncate inode.  The only stuff left
1254          * in the directory is "." and "..".  The
1255          * "." reference is inconsequential since
1256          * we're quashing it.  The ".." reference
1257          * has already been adjusted above.  We've
1258          * removed the "." reference and the reference
1259          * in the parent directory, but there may be
1260          * other hard links so decrement by 2 and
1261          * worry about them later.
1262          */
1263         ip->i_nlink -= 2;
1264         error = ext2_truncate(vp, (off_t)0, IO_SYNC, cnp->cn_cred,
1265             cnp->cn_thread);
1266         cache_purge(ITOV(ip));
1267         if (vn_lock(dvp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1268                 VOP_UNLOCK(vp, 0);
1269                 vn_lock(dvp, LK_EXCLUSIVE | LK_RETRY);
1270                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1271         }
1272 out:
1273         return (error);
1274 }
1275
1276 /*
1277  * symlink -- make a symbolic link
1278  */
1279 static int
1280 ext2_symlink(struct vop_symlink_args *ap)
1281 {
1282         struct vnode *vp, **vpp = ap->a_vpp;
1283         struct inode *ip;
1284         int len, error;
1285
1286         error = ext2_makeinode(IFLNK | ap->a_vap->va_mode, ap->a_dvp,
1287             vpp, ap->a_cnp);
1288         if (error)
1289                 return (error);
1290         vp = *vpp;
1291         len = strlen(ap->a_target);
1292         if (len < vp->v_mount->mnt_maxsymlinklen) {
1293                 ip = VTOI(vp);
1294                 bcopy(ap->a_target, (char *)ip->i_shortlink, len);
1295                 ip->i_size = len;
1296                 ip->i_flag |= IN_CHANGE | IN_UPDATE;
1297         } else
1298                 error = vn_rdwr(UIO_WRITE, vp, ap->a_target, len, (off_t)0,
1299                     UIO_SYSSPACE, IO_NODELOCKED | IO_NOMACCHECK,
1300                     ap->a_cnp->cn_cred, NOCRED, NULL, NULL);
1301         if (error)
1302                 vput(vp);
1303         return (error);
1304 }
1305
1306 /*
1307  * Return target name of a symbolic link
1308  */
1309 static int
1310 ext2_readlink(struct vop_readlink_args *ap)
1311 {
1312         struct vnode *vp = ap->a_vp;
1313         struct inode *ip = VTOI(vp);
1314         int isize;
1315
1316         isize = ip->i_size;
1317         if (isize < vp->v_mount->mnt_maxsymlinklen) {
1318                 uiomove((char *)ip->i_shortlink, isize, ap->a_uio);
1319                 return (0);
1320         }
1321         return (VOP_READ(vp, ap->a_uio, 0, ap->a_cred));
1322 }
1323
1324 /*
1325  * Calculate the logical to physical mapping if not done already,
1326  * then call the device strategy routine.
1327  *
1328  * In order to be able to swap to a file, the ext2_bmaparray() operation may not
1329  * deadlock on memory.  See ext2_bmap() for details.
1330  */
1331 static int
1332 ext2_strategy(struct vop_strategy_args *ap)
1333 {
1334         struct buf *bp = ap->a_bp;
1335         struct vnode *vp = ap->a_vp;
1336         struct inode *ip;
1337         struct bufobj *bo;
1338         daddr_t blkno;
1339         int error;
1340
1341         ip = VTOI(vp);
1342         if (vp->v_type == VBLK || vp->v_type == VCHR)
1343                 panic("ext2_strategy: spec");
1344         if (bp->b_blkno == bp->b_lblkno) {
1345                 error = ext2_bmaparray(vp, bp->b_lblkno, &blkno, NULL, NULL);
1346                 bp->b_blkno = blkno;
1347                 if (error) {
1348                         bp->b_error = error;
1349                         bp->b_ioflags |= BIO_ERROR;
1350                         bufdone(bp);
1351                         return (0);
1352                 }
1353                 if ((long)bp->b_blkno == -1)
1354                         vfs_bio_clrbuf(bp);
1355         }
1356         if ((long)bp->b_blkno == -1) {
1357                 bufdone(bp);
1358                 return (0);
1359         }
1360         bp->b_iooffset = dbtob(bp->b_blkno);
1361         bo = VFSTOEXT2(vp->v_mount)->um_bo;
1362         BO_STRATEGY(bo, bp);
1363         return (0);
1364 }
1365
1366 /*
1367  * Print out the contents of an inode.
1368  */
1369 static int
1370 ext2_print(struct vop_print_args *ap)
1371 {
1372         struct vnode *vp = ap->a_vp;
1373         struct inode *ip = VTOI(vp);
1374
1375         vn_printf(ip->i_devvp, "\tino %lu", (u_long)ip->i_number);
1376         if (vp->v_type == VFIFO)
1377                 fifo_printinfo(vp);
1378         printf("\n");
1379         return (0);
1380 }
1381
1382 /*
1383  * Close wrapper for fifos.
1384  *
1385  * Update the times on the inode then do device close.
1386  */
1387 static int
1388 ext2fifo_close(struct vop_close_args *ap)
1389 {
1390         struct vnode *vp = ap->a_vp;
1391
1392         VI_LOCK(vp);
1393         if (vp->v_usecount > 1)
1394                 ext2_itimes_locked(vp);
1395         VI_UNLOCK(vp);
1396         return (fifo_specops.vop_close(ap));
1397 }
1398
1399 /*
1400  * Kqfilter wrapper for fifos.
1401  *
1402  * Fall through to ext2 kqfilter routines if needed 
1403  */
1404 static int
1405 ext2fifo_kqfilter(struct vop_kqfilter_args *ap)
1406 {
1407         int error;
1408
1409         error = fifo_specops.vop_kqfilter(ap);
1410         if (error)
1411                 error = vfs_kqfilter(ap);
1412         return (error);
1413 }
1414
1415 /*
1416  * Return POSIX pathconf information applicable to ext2 filesystems.
1417  */
1418 static int
1419 ext2_pathconf(struct vop_pathconf_args *ap)
1420 {
1421         int error = 0;
1422
1423         switch (ap->a_name) {
1424         case _PC_LINK_MAX:
1425                 *ap->a_retval = EXT2_LINK_MAX;
1426                 break;
1427         case _PC_NAME_MAX:
1428                 *ap->a_retval = NAME_MAX;
1429                 break;
1430         case _PC_PATH_MAX:
1431                 *ap->a_retval = PATH_MAX;
1432                 break;
1433         case _PC_PIPE_BUF:
1434                 *ap->a_retval = PIPE_BUF;
1435                 break;
1436         case _PC_CHOWN_RESTRICTED:
1437                 *ap->a_retval = 1;
1438                 break;
1439         case _PC_NO_TRUNC:
1440                 *ap->a_retval = 1;
1441                 break;
1442         case _PC_MIN_HOLE_SIZE:
1443                 *ap->a_retval = ap->a_vp->v_mount->mnt_stat.f_iosize;
1444                 break;
1445         case _PC_ASYNC_IO:
1446                 /* _PC_ASYNC_IO should have been handled by upper layers. */
1447                 KASSERT(0, ("_PC_ASYNC_IO should not get here"));
1448                 error = EINVAL;
1449                 break;
1450         case _PC_PRIO_IO:
1451                 *ap->a_retval = 0;
1452                 break;
1453         case _PC_SYNC_IO:
1454                 *ap->a_retval = 0;
1455                 break;
1456         case _PC_ALLOC_SIZE_MIN:
1457                 *ap->a_retval = ap->a_vp->v_mount->mnt_stat.f_bsize;
1458                 break;
1459         case _PC_FILESIZEBITS:
1460                 *ap->a_retval = 64;
1461                 break;
1462         case _PC_REC_INCR_XFER_SIZE:
1463                 *ap->a_retval = ap->a_vp->v_mount->mnt_stat.f_iosize;
1464                 break;
1465         case _PC_REC_MAX_XFER_SIZE:
1466                 *ap->a_retval = -1; /* means ``unlimited'' */
1467                 break;
1468         case _PC_REC_MIN_XFER_SIZE:
1469                 *ap->a_retval = ap->a_vp->v_mount->mnt_stat.f_iosize;
1470                 break;
1471         case _PC_REC_XFER_ALIGN:
1472                 *ap->a_retval = PAGE_SIZE;
1473                 break;
1474         case _PC_SYMLINK_MAX:
1475                 *ap->a_retval = MAXPATHLEN;
1476                 break;
1477
1478         default:
1479                 error = EINVAL;
1480                 break;
1481         }
1482         return (error);
1483 }
1484
1485 /*
1486  * Vnode pointer to File handle
1487  */
1488 /* ARGSUSED */
1489 static int
1490 ext2_vptofh(struct vop_vptofh_args *ap)
1491 {
1492         struct inode *ip;
1493         struct ufid *ufhp;
1494
1495         ip = VTOI(ap->a_vp);
1496         ufhp = (struct ufid *)ap->a_fhp;
1497         ufhp->ufid_len = sizeof(struct ufid);
1498         ufhp->ufid_ino = ip->i_number;
1499         ufhp->ufid_gen = ip->i_gen;
1500         return (0);
1501 }
1502
1503 /*
1504  * Initialize the vnode associated with a new inode, handle aliased
1505  * vnodes.
1506  */
1507 int
1508 ext2_vinit(struct mount *mntp, struct vop_vector *fifoops, struct vnode **vpp)
1509 {
1510         struct inode *ip;
1511         struct vnode *vp;
1512
1513         vp = *vpp;
1514         ip = VTOI(vp);
1515         vp->v_type = IFTOVT(ip->i_mode);
1516         if (vp->v_type == VFIFO)
1517                 vp->v_op = fifoops;
1518
1519         if (ip->i_number == EXT2_ROOTINO)
1520                 vp->v_vflag |= VV_ROOT;
1521         ip->i_modrev = init_va_filerev();
1522         *vpp = vp;
1523         return (0);
1524 }
1525
1526 /*
1527  * Allocate a new inode.
1528  */
1529 static int
1530 ext2_makeinode(int mode, struct vnode *dvp, struct vnode **vpp,
1531     struct componentname *cnp)
1532 {
1533         struct inode *ip, *pdir;
1534         struct vnode *tvp;
1535         int error;
1536
1537         pdir = VTOI(dvp);
1538 #ifdef INVARIANTS
1539         if ((cnp->cn_flags & HASBUF) == 0)
1540                 panic("ext2_makeinode: no name");
1541 #endif
1542         *vpp = NULL;
1543         if ((mode & IFMT) == 0)
1544                 mode |= IFREG;
1545
1546         error = ext2_valloc(dvp, mode, cnp->cn_cred, &tvp);
1547         if (error) {
1548                 return (error);
1549         }
1550         ip = VTOI(tvp);
1551         ip->i_gid = pdir->i_gid;
1552 #ifdef SUIDDIR
1553         {
1554                 /*
1555                  * if we are
1556                  * not the owner of the directory,
1557                  * and we are hacking owners here, (only do this where told to)
1558                  * and we are not giving it TOO root, (would subvert quotas)
1559                  * then go ahead and give it to the other user.
1560                  * Note that this drops off the execute bits for security.
1561                  */
1562                 if ( (dvp->v_mount->mnt_flag & MNT_SUIDDIR) &&
1563                      (pdir->i_mode & ISUID) &&
1564                      (pdir->i_uid != cnp->cn_cred->cr_uid) && pdir->i_uid) {
1565                         ip->i_uid = pdir->i_uid;
1566                         mode &= ~07111;
1567                 } else {
1568                         ip->i_uid = cnp->cn_cred->cr_uid;
1569                 }
1570         }
1571 #else
1572         ip->i_uid = cnp->cn_cred->cr_uid;
1573 #endif
1574         ip->i_flag |= IN_ACCESS | IN_CHANGE | IN_UPDATE;
1575         ip->i_mode = mode;
1576         tvp->v_type = IFTOVT(mode);     /* Rest init'd in getnewvnode(). */
1577         ip->i_nlink = 1;
1578         if ((ip->i_mode & ISGID) && !groupmember(ip->i_gid, cnp->cn_cred)) {
1579                 if (priv_check_cred(cnp->cn_cred, PRIV_VFS_RETAINSUGID, 0))
1580                         ip->i_mode &= ~ISGID;
1581         }
1582
1583         if (cnp->cn_flags & ISWHITEOUT)
1584                 ip->i_flags |= UF_OPAQUE;
1585
1586         /*
1587          * Make sure inode goes to disk before directory entry.
1588          */
1589         error = ext2_update(tvp, !DOINGASYNC(tvp));
1590         if (error)
1591                 goto bad;
1592         error = ext2_direnter(ip, dvp, cnp);
1593         if (error)
1594                 goto bad;
1595
1596         *vpp = tvp;
1597         return (0);
1598
1599 bad:
1600         /*
1601          * Write error occurred trying to update the inode
1602          * or the directory so must deallocate the inode.
1603          */
1604         ip->i_nlink = 0;
1605         ip->i_flag |= IN_CHANGE;
1606         vput(tvp);
1607         return (error);
1608 }
1609
1610 /*
1611  * Vnode op for reading.
1612  */
1613 static int
1614 ext2_read(struct vop_read_args *ap)
1615 {
1616         struct vnode *vp;
1617         struct inode *ip;
1618         int error;
1619
1620         vp = ap->a_vp;
1621         ip = VTOI(vp);
1622
1623         /*EXT4_EXT_LOCK(ip);*/
1624         if (ip->i_flags & EXT4_EXTENTS)
1625                 error = ext4_ext_read(ap);
1626         else
1627                 error = ext2_ind_read(ap);
1628         /*EXT4_EXT_UNLOCK(ip);*/
1629         return (error);
1630 }
1631
1632
1633 /*
1634  * Vnode op for reading.
1635  */
1636 static int
1637 ext2_ind_read(struct vop_read_args *ap)
1638 {
1639         struct vnode *vp;
1640         struct inode *ip;
1641         struct uio *uio;
1642         struct m_ext2fs *fs;
1643         struct buf *bp;
1644         daddr_t lbn, nextlbn;
1645         off_t bytesinfile;
1646         long size, xfersize, blkoffset;
1647         int error, orig_resid, seqcount;
1648         int ioflag;
1649
1650         vp = ap->a_vp;
1651         uio = ap->a_uio;
1652         ioflag = ap->a_ioflag;
1653
1654         seqcount = ap->a_ioflag >> IO_SEQSHIFT;
1655         ip = VTOI(vp);
1656
1657 #ifdef INVARIANTS
1658         if (uio->uio_rw != UIO_READ)
1659                 panic("%s: mode", "ext2_read");
1660
1661         if (vp->v_type == VLNK) {
1662                 if ((int)ip->i_size < vp->v_mount->mnt_maxsymlinklen)
1663                         panic("%s: short symlink", "ext2_read");
1664         } else if (vp->v_type != VREG && vp->v_type != VDIR)
1665                 panic("%s: type %d", "ext2_read", vp->v_type);
1666 #endif
1667         orig_resid = uio->uio_resid;
1668         KASSERT(orig_resid >= 0, ("ext2_read: uio->uio_resid < 0"));
1669         if (orig_resid == 0)
1670                 return (0);
1671         KASSERT(uio->uio_offset >= 0, ("ext2_read: uio->uio_offset < 0"));
1672         fs = ip->i_e2fs;
1673         if (uio->uio_offset < ip->i_size &&
1674             uio->uio_offset >= fs->e2fs_maxfilesize)
1675                 return (EOVERFLOW);
1676
1677         for (error = 0, bp = NULL; uio->uio_resid > 0; bp = NULL) {
1678                 if ((bytesinfile = ip->i_size - uio->uio_offset) <= 0)
1679                         break;
1680                 lbn = lblkno(fs, uio->uio_offset);
1681                 nextlbn = lbn + 1;
1682                 size = blksize(fs, ip, lbn);
1683                 blkoffset = blkoff(fs, uio->uio_offset);
1684
1685                 xfersize = fs->e2fs_fsize - blkoffset;
1686                 if (uio->uio_resid < xfersize)
1687                         xfersize = uio->uio_resid;
1688                 if (bytesinfile < xfersize)
1689                         xfersize = bytesinfile;
1690
1691                 if (lblktosize(fs, nextlbn) >= ip->i_size)
1692                         error = bread(vp, lbn, size, NOCRED, &bp);
1693                 else if ((vp->v_mount->mnt_flag & MNT_NOCLUSTERR) == 0)
1694                         error = cluster_read(vp, ip->i_size, lbn, size,
1695                             NOCRED, blkoffset + uio->uio_resid, seqcount, &bp);
1696                 else if (seqcount > 1) {
1697                         int nextsize = blksize(fs, ip, nextlbn);
1698                         error = breadn(vp, lbn,
1699                             size, &nextlbn, &nextsize, 1, NOCRED, &bp);
1700                 } else
1701                         error = bread(vp, lbn, size, NOCRED, &bp);
1702                 if (error) {
1703                         brelse(bp);
1704                         bp = NULL;
1705                         break;
1706                 }
1707
1708                 /*
1709                  * If IO_DIRECT then set B_DIRECT for the buffer.  This
1710                  * will cause us to attempt to release the buffer later on
1711                  * and will cause the buffer cache to attempt to free the
1712                  * underlying pages.
1713                  */
1714                 if (ioflag & IO_DIRECT)
1715                         bp->b_flags |= B_DIRECT;
1716
1717                 /*
1718                  * We should only get non-zero b_resid when an I/O error
1719                  * has occurred, which should cause us to break above.
1720                  * However, if the short read did not cause an error,
1721                  * then we want to ensure that we do not uiomove bad
1722                  * or uninitialized data.
1723                  */
1724                 size -= bp->b_resid;
1725                 if (size < xfersize) {
1726                         if (size == 0)
1727                                 break;
1728                         xfersize = size;
1729                 }
1730                 error = uiomove((char *)bp->b_data + blkoffset,
1731                         (int)xfersize, uio);
1732                 if (error)
1733                         break;
1734
1735                 if (ioflag & (IO_VMIO|IO_DIRECT)) {
1736                         /*
1737                          * If it's VMIO or direct I/O, then we don't
1738                          * need the buf, mark it available for
1739                          * freeing. If it's non-direct VMIO, the VM has
1740                          * the data.
1741                          */
1742                         bp->b_flags |= B_RELBUF;
1743                         brelse(bp);
1744                 } else {
1745                         /*
1746                          * Otherwise let whoever
1747                          * made the request take care of
1748                          * freeing it. We just queue
1749                          * it onto another list.
1750                          */
1751                         bqrelse(bp);
1752                 }
1753         }
1754
1755         /* 
1756          * This can only happen in the case of an error
1757          * because the loop above resets bp to NULL on each iteration
1758          * and on normal completion has not set a new value into it.
1759          * so it must have come from a 'break' statement
1760          */
1761         if (bp != NULL) {
1762                 if (ioflag & (IO_VMIO|IO_DIRECT)) {
1763                         bp->b_flags |= B_RELBUF;
1764                         brelse(bp);
1765                 } else {
1766                         bqrelse(bp);
1767                 }
1768         }
1769
1770         if ((error == 0 || uio->uio_resid != orig_resid) &&
1771             (vp->v_mount->mnt_flag & MNT_NOATIME) == 0)
1772                 ip->i_flag |= IN_ACCESS;
1773         return (error);
1774 }
1775
1776 static int
1777 ext2_ioctl(struct vop_ioctl_args *ap)
1778 {
1779
1780         switch (ap->a_command) {
1781         case FIOSEEKDATA:
1782         case FIOSEEKHOLE:
1783                 return (vn_bmap_seekhole(ap->a_vp, ap->a_command,
1784                     (off_t *)ap->a_data, ap->a_cred));
1785         default:
1786                 return (ENOTTY);
1787         }
1788 }
1789
1790 /*
1791  * this function handles ext4 extents block mapping
1792  */
1793 static int
1794 ext4_ext_read(struct vop_read_args *ap)
1795 {
1796         struct vnode *vp;
1797         struct inode *ip;
1798         struct uio *uio;
1799         struct m_ext2fs *fs;
1800         struct buf *bp;
1801         struct ext4_extent nex, *ep;
1802         struct ext4_extent_path path;
1803         daddr_t lbn, newblk;
1804         off_t bytesinfile;
1805         int cache_type;
1806         ssize_t orig_resid;
1807         int error;
1808         long size, xfersize, blkoffset;
1809
1810         vp = ap->a_vp;
1811         ip = VTOI(vp);
1812         uio = ap->a_uio;
1813         memset(&path, 0, sizeof(path));
1814
1815         orig_resid = uio->uio_resid;
1816         KASSERT(orig_resid >= 0, ("%s: uio->uio_resid < 0", __func__));
1817         if (orig_resid == 0)
1818                 return (0);
1819         KASSERT(uio->uio_offset >= 0, ("%s: uio->uio_offset < 0", __func__));
1820         fs = ip->i_e2fs;
1821         if (uio->uio_offset < ip->i_size && uio->uio_offset >= fs->e2fs_maxfilesize)
1822                 return (EOVERFLOW);
1823
1824         while (uio->uio_resid > 0) {
1825                 if ((bytesinfile = ip->i_size - uio->uio_offset) <= 0)
1826                         break;
1827                 lbn = lblkno(fs, uio->uio_offset);
1828                 size = blksize(fs, ip, lbn);
1829                 blkoffset = blkoff(fs, uio->uio_offset);
1830
1831                 xfersize = fs->e2fs_fsize - blkoffset;
1832                 xfersize = MIN(xfersize, uio->uio_resid);
1833                 xfersize = MIN(xfersize, bytesinfile);
1834
1835                 /* get block from ext4 extent cache */
1836                 cache_type = ext4_ext_in_cache(ip, lbn, &nex);
1837                 switch (cache_type) {
1838                 case EXT4_EXT_CACHE_NO:
1839                         ext4_ext_find_extent(fs, ip, lbn, &path);
1840                         ep = path.ep_ext;
1841                         if (ep == NULL)
1842                                 return (EIO);
1843
1844                         ext4_ext_put_cache(ip, ep, EXT4_EXT_CACHE_IN);
1845
1846                         newblk = lbn - ep->e_blk + (ep->e_start_lo |
1847                             (daddr_t)ep->e_start_hi << 32);
1848
1849                         if (path.ep_bp != NULL) {
1850                                 brelse(path.ep_bp);
1851                                 path.ep_bp = NULL;
1852                         }
1853                         break;
1854
1855                 case EXT4_EXT_CACHE_GAP:
1856                         /* block has not been allocated yet */
1857                         return (0);
1858
1859                 case EXT4_EXT_CACHE_IN:
1860                         newblk = lbn - nex.e_blk + (nex.e_start_lo |
1861                             (daddr_t)nex.e_start_hi << 32);
1862                         break;
1863
1864                 default:
1865                         panic("%s: invalid cache type", __func__);
1866                 }
1867
1868                 error = bread(ip->i_devvp, fsbtodb(fs, newblk), size, NOCRED, &bp);
1869                 if (error) {
1870                         brelse(bp);
1871                         return (error);
1872                 }
1873
1874                 size -= bp->b_resid;
1875                 if (size < xfersize) {
1876                         if (size == 0) {
1877                                 bqrelse(bp);
1878                                 break;
1879                         }
1880                         xfersize = size;
1881                 }
1882                 error = uiomove(bp->b_data + blkoffset, (int)xfersize, uio);
1883                 bqrelse(bp);
1884                 if (error)
1885                         return (error);
1886         }
1887
1888         return (0);
1889 }
1890
1891 /*
1892  * Vnode op for writing.
1893  */
1894 static int
1895 ext2_write(struct vop_write_args *ap)
1896 {
1897         struct vnode *vp;
1898         struct uio *uio;
1899         struct inode *ip;
1900         struct m_ext2fs *fs;
1901         struct buf *bp;
1902         daddr_t lbn;
1903         off_t osize;
1904         int blkoffset, error, flags, ioflag, resid, size, seqcount, xfersize;
1905
1906         ioflag = ap->a_ioflag;
1907         uio = ap->a_uio;
1908         vp = ap->a_vp;
1909
1910         seqcount = ioflag >> IO_SEQSHIFT;
1911         ip = VTOI(vp);
1912
1913 #ifdef INVARIANTS
1914         if (uio->uio_rw != UIO_WRITE)
1915                 panic("%s: mode", "ext2_write");
1916 #endif
1917
1918         switch (vp->v_type) {
1919         case VREG:
1920                 if (ioflag & IO_APPEND)
1921                         uio->uio_offset = ip->i_size;
1922                 if ((ip->i_flags & APPEND) && uio->uio_offset != ip->i_size)
1923                         return (EPERM);
1924                 /* FALLTHROUGH */
1925         case VLNK:
1926                 break;
1927         case VDIR:
1928                 /* XXX differs from ffs -- this is called from ext2_mkdir(). */
1929                 if ((ioflag & IO_SYNC) == 0)
1930                 panic("ext2_write: nonsync dir write");
1931                 break;
1932         default:
1933                 panic("ext2_write: type %p %d (%jd,%jd)", (void *)vp,
1934                     vp->v_type, (intmax_t)uio->uio_offset,
1935                     (intmax_t)uio->uio_resid);
1936         }
1937
1938         KASSERT(uio->uio_resid >= 0, ("ext2_write: uio->uio_resid < 0"));
1939         KASSERT(uio->uio_offset >= 0, ("ext2_write: uio->uio_offset < 0"));
1940         fs = ip->i_e2fs;
1941         if ((uoff_t)uio->uio_offset + uio->uio_resid > fs->e2fs_maxfilesize)
1942                 return (EFBIG);
1943         /*
1944          * Maybe this should be above the vnode op call, but so long as
1945          * file servers have no limits, I don't think it matters.
1946          */
1947         if (vn_rlimit_fsize(vp, uio, uio->uio_td))
1948                 return (EFBIG);
1949
1950         resid = uio->uio_resid;
1951         osize = ip->i_size;
1952         if (seqcount > BA_SEQMAX)
1953                 flags = BA_SEQMAX << BA_SEQSHIFT;
1954         else
1955                 flags = seqcount << BA_SEQSHIFT;
1956         if ((ioflag & IO_SYNC) && !DOINGASYNC(vp))
1957                 flags |= IO_SYNC;
1958
1959         for (error = 0; uio->uio_resid > 0;) {
1960                 lbn = lblkno(fs, uio->uio_offset);
1961                 blkoffset = blkoff(fs, uio->uio_offset);
1962                 xfersize = fs->e2fs_fsize - blkoffset;
1963                 if (uio->uio_resid < xfersize)
1964                         xfersize = uio->uio_resid;
1965                 if (uio->uio_offset + xfersize > ip->i_size)
1966                         vnode_pager_setsize(vp, uio->uio_offset + xfersize);
1967
1968                 /*
1969                  * We must perform a read-before-write if the transfer size
1970                  * does not cover the entire buffer.
1971                  */
1972                 if (fs->e2fs_bsize > xfersize)
1973                         flags |= BA_CLRBUF;
1974                 else
1975                         flags &= ~BA_CLRBUF;
1976                 error = ext2_balloc(ip, lbn, blkoffset + xfersize,
1977                     ap->a_cred, &bp, flags);
1978                 if (error != 0)
1979                         break;
1980
1981                 if ((ioflag & (IO_SYNC|IO_INVAL)) == (IO_SYNC|IO_INVAL))
1982                         bp->b_flags |= B_NOCACHE;
1983                 if (uio->uio_offset + xfersize > ip->i_size)
1984                         ip->i_size = uio->uio_offset + xfersize;
1985                 size = blksize(fs, ip, lbn) - bp->b_resid;
1986                 if (size < xfersize)
1987                         xfersize = size;
1988
1989                 error =
1990                     uiomove((char *)bp->b_data + blkoffset, (int)xfersize, uio);
1991                 /*
1992                  * If the buffer is not already filled and we encounter an
1993                  * error while trying to fill it, we have to clear out any
1994                  * garbage data from the pages instantiated for the buffer.
1995                  * If we do not, a failed uiomove() during a write can leave
1996                  * the prior contents of the pages exposed to a userland mmap.
1997                  *
1998                  * Note that we need only clear buffers with a transfer size
1999                  * equal to the block size because buffers with a shorter
2000                  * transfer size were cleared above by the call to ext2_balloc()
2001                  * with the BA_CLRBUF flag set.
2002                  *
2003                  * If the source region for uiomove identically mmaps the
2004                  * buffer, uiomove() performed the NOP copy, and the buffer
2005                  * content remains valid because the page fault handler
2006                  * validated the pages.
2007                  */
2008                 if (error != 0 && (bp->b_flags & B_CACHE) == 0 &&
2009                     fs->e2fs_bsize == xfersize)
2010                         vfs_bio_clrbuf(bp);
2011                 if (ioflag & (IO_VMIO|IO_DIRECT)) {
2012                         bp->b_flags |= B_RELBUF;
2013                 }
2014
2015                 /*
2016                  * If IO_SYNC each buffer is written synchronously.  Otherwise
2017                  * if we have a severe page deficiency write the buffer
2018                  * asynchronously.  Otherwise try to cluster, and if that
2019                  * doesn't do it then either do an async write (if O_DIRECT),
2020                  * or a delayed write (if not).
2021                  */
2022                 if (ioflag & IO_SYNC) {
2023                         (void)bwrite(bp);
2024                 } else if (vm_page_count_severe() ||
2025                     buf_dirty_count_severe() ||
2026                     (ioflag & IO_ASYNC)) {
2027                         bp->b_flags |= B_CLUSTEROK;
2028                         bawrite(bp);
2029                 } else if (xfersize + blkoffset == fs->e2fs_fsize) {
2030                         if ((vp->v_mount->mnt_flag & MNT_NOCLUSTERW) == 0) {
2031                                 bp->b_flags |= B_CLUSTEROK;
2032                                 cluster_write(vp, bp, ip->i_size, seqcount);
2033                         } else {
2034                                 bawrite(bp);
2035                         }
2036                 } else if (ioflag & IO_DIRECT) {
2037                         bp->b_flags |= B_CLUSTEROK;
2038                         bawrite(bp);
2039                 } else {
2040                         bp->b_flags |= B_CLUSTEROK;
2041                         bdwrite(bp);
2042                 }
2043                 if (error || xfersize == 0)
2044                         break;
2045         }
2046         /*
2047          * If we successfully wrote any data, and we are not the superuser
2048          * we clear the setuid and setgid bits as a precaution against
2049          * tampering.
2050          */
2051         if ((ip->i_mode & (ISUID | ISGID)) && resid > uio->uio_resid &&
2052             ap->a_cred) {
2053                 if (priv_check_cred(ap->a_cred, PRIV_VFS_RETAINSUGID, 0))
2054                         ip->i_mode &= ~(ISUID | ISGID);
2055         }
2056         if (error) {
2057                 if (ioflag & IO_UNIT) {
2058                         (void)ext2_truncate(vp, osize,
2059                             ioflag & IO_SYNC, ap->a_cred, uio->uio_td);
2060                         uio->uio_offset -= resid - uio->uio_resid;
2061                         uio->uio_resid = resid;
2062                 }
2063         }
2064         if (uio->uio_resid != resid) {
2065                ip->i_flag |= IN_CHANGE | IN_UPDATE;
2066                if (ioflag & IO_SYNC)
2067                        error = ext2_update(vp, 1);
2068        }
2069         return (error);
2070 }