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