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