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