xref: /titanic_50/usr/src/uts/common/fs/ufs/ufs_vnops.c (revision 142c9f13e148d687426ed2d4e8bd93717eeaebbc)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*	Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T	*/
27 /*	  All Rights Reserved  	*/
28 
29 /*
30  * Portions of this source code were derived from Berkeley 4.3 BSD
31  * under license from the Regents of the University of California.
32  */
33 
34 #pragma ident	"%Z%%M%	%I%	%E% SMI"
35 
36 #include <sys/types.h>
37 #include <sys/t_lock.h>
38 #include <sys/ksynch.h>
39 #include <sys/param.h>
40 #include <sys/time.h>
41 #include <sys/systm.h>
42 #include <sys/sysmacros.h>
43 #include <sys/resource.h>
44 #include <sys/signal.h>
45 #include <sys/cred.h>
46 #include <sys/user.h>
47 #include <sys/buf.h>
48 #include <sys/vfs.h>
49 #include <sys/vfs_opreg.h>
50 #include <sys/vnode.h>
51 #include <sys/proc.h>
52 #include <sys/disp.h>
53 #include <sys/file.h>
54 #include <sys/fcntl.h>
55 #include <sys/flock.h>
56 #include <sys/atomic.h>
57 #include <sys/kmem.h>
58 #include <sys/uio.h>
59 #include <sys/dnlc.h>
60 #include <sys/conf.h>
61 #include <sys/mman.h>
62 #include <sys/pathname.h>
63 #include <sys/debug.h>
64 #include <sys/vmsystm.h>
65 #include <sys/cmn_err.h>
66 #include <sys/filio.h>
67 #include <sys/policy.h>
68 
69 #include <sys/fs/ufs_fs.h>
70 #include <sys/fs/ufs_lockfs.h>
71 #include <sys/fs/ufs_filio.h>
72 #include <sys/fs/ufs_inode.h>
73 #include <sys/fs/ufs_fsdir.h>
74 #include <sys/fs/ufs_quota.h>
75 #include <sys/fs/ufs_log.h>
76 #include <sys/fs/ufs_snap.h>
77 #include <sys/fs/ufs_trans.h>
78 #include <sys/fs/ufs_panic.h>
79 #include <sys/fs/ufs_bio.h>
80 #include <sys/dirent.h>		/* must be AFTER <sys/fs/fsdir.h>! */
81 #include <sys/errno.h>
82 #include <sys/fssnap_if.h>
83 #include <sys/unistd.h>
84 #include <sys/sunddi.h>
85 
86 #include <sys/filio.h>		/* _FIOIO */
87 
88 #include <vm/hat.h>
89 #include <vm/page.h>
90 #include <vm/pvn.h>
91 #include <vm/as.h>
92 #include <vm/seg.h>
93 #include <vm/seg_map.h>
94 #include <vm/seg_vn.h>
95 #include <vm/seg_kmem.h>
96 #include <vm/rm.h>
97 #include <sys/swap.h>
98 
99 #include <fs/fs_subr.h>
100 
101 #include <sys/fs/decomp.h>
102 
103 static struct instats ins;
104 
105 static 	int ufs_getpage_ra(struct vnode *, u_offset_t, struct seg *, caddr_t);
106 static	int ufs_getpage_miss(struct vnode *, u_offset_t, size_t, struct seg *,
107 		caddr_t, struct page **, size_t, enum seg_rw, int);
108 static	int ufs_open(struct vnode **, int, struct cred *, caller_context_t *);
109 static	int ufs_close(struct vnode *, int, int, offset_t, struct cred *,
110 		caller_context_t *);
111 static	int ufs_read(struct vnode *, struct uio *, int, struct cred *,
112 		struct caller_context *);
113 static	int ufs_write(struct vnode *, struct uio *, int, struct cred *,
114 		struct caller_context *);
115 static	int ufs_ioctl(struct vnode *, int, intptr_t, int, struct cred *,
116 		int *, caller_context_t *);
117 static	int ufs_getattr(struct vnode *, struct vattr *, int, struct cred *,
118 		caller_context_t *);
119 static	int ufs_setattr(struct vnode *, struct vattr *, int, struct cred *,
120 		caller_context_t *);
121 static	int ufs_access(struct vnode *, int, int, struct cred *,
122 		caller_context_t *);
123 static	int ufs_lookup(struct vnode *, char *, struct vnode **,
124 		struct pathname *, int, struct vnode *, struct cred *,
125 		caller_context_t *, int *, pathname_t *);
126 static	int ufs_create(struct vnode *, char *, struct vattr *, enum vcexcl,
127 		int, struct vnode **, struct cred *, int,
128 		caller_context_t *, vsecattr_t  *);
129 static	int ufs_remove(struct vnode *, char *, struct cred *,
130 		caller_context_t *, int);
131 static	int ufs_link(struct vnode *, struct vnode *, char *, struct cred *,
132 		caller_context_t *, int);
133 static	int ufs_rename(struct vnode *, char *, struct vnode *, char *,
134 		struct cred *, caller_context_t *, int);
135 static	int ufs_mkdir(struct vnode *, char *, struct vattr *, struct vnode **,
136 		struct cred *, caller_context_t *, int, vsecattr_t *);
137 static	int ufs_rmdir(struct vnode *, char *, struct vnode *, struct cred *,
138 		caller_context_t *, int);
139 static	int ufs_readdir(struct vnode *, struct uio *, struct cred *, int *,
140 		caller_context_t *, int);
141 static	int ufs_symlink(struct vnode *, char *, struct vattr *, char *,
142 		struct cred *, caller_context_t *, int);
143 static	int ufs_readlink(struct vnode *, struct uio *, struct cred *,
144 		caller_context_t *);
145 static	int ufs_fsync(struct vnode *, int, struct cred *, caller_context_t *);
146 static	void ufs_inactive(struct vnode *, struct cred *, caller_context_t *);
147 static	int ufs_fid(struct vnode *, struct fid *, caller_context_t *);
148 static	int ufs_rwlock(struct vnode *, int, caller_context_t *);
149 static	void ufs_rwunlock(struct vnode *, int, caller_context_t *);
150 static	int ufs_seek(struct vnode *, offset_t, offset_t *, caller_context_t *);
151 static	int ufs_frlock(struct vnode *, int, struct flock64 *, int, offset_t,
152 		struct flk_callback *, struct cred *,
153 		caller_context_t *);
154 static  int ufs_space(struct vnode *, int, struct flock64 *, int, offset_t,
155 		cred_t *, caller_context_t *);
156 static	int ufs_getpage(struct vnode *, offset_t, size_t, uint_t *,
157 		struct page **, size_t, struct seg *, caddr_t,
158 		enum seg_rw, struct cred *, caller_context_t *);
159 static	int ufs_putpage(struct vnode *, offset_t, size_t, int, struct cred *,
160 		caller_context_t *);
161 static	int ufs_putpages(struct vnode *, offset_t, size_t, int, struct cred *);
162 static	int ufs_map(struct vnode *, offset_t, struct as *, caddr_t *, size_t,
163 		uchar_t, uchar_t, uint_t, struct cred *, caller_context_t *);
164 static	int ufs_addmap(struct vnode *, offset_t, struct as *, caddr_t,  size_t,
165 		uchar_t, uchar_t, uint_t, struct cred *, caller_context_t *);
166 static	int ufs_delmap(struct vnode *, offset_t, struct as *, caddr_t,  size_t,
167 		uint_t, uint_t, uint_t, struct cred *, caller_context_t *);
168 static	int ufs_poll(vnode_t *, short, int, short *, struct pollhead **,
169 		caller_context_t *);
170 static	int ufs_dump(vnode_t *, caddr_t, offset_t, offset_t,
171     caller_context_t *);
172 static	int ufs_l_pathconf(struct vnode *, int, ulong_t *, struct cred *,
173 		caller_context_t *);
174 static	int ufs_pageio(struct vnode *, struct page *, u_offset_t, size_t, int,
175 		struct cred *, caller_context_t *);
176 static	int ufs_dumpctl(vnode_t *, int, offset_t *, caller_context_t *);
177 static	daddr32_t *save_dblks(struct inode *, struct ufsvfs *, daddr32_t *,
178 		daddr32_t *, int, int);
179 static	int ufs_getsecattr(struct vnode *, vsecattr_t *, int, struct cred *,
180 		caller_context_t *);
181 static	int ufs_setsecattr(struct vnode *, vsecattr_t *, int, struct cred *,
182 		caller_context_t *);
183 extern int as_map_locked(struct as *, caddr_t, size_t, int ((*)()), void *);
184 
185 /*
186  * For lockfs: ulockfs begin/end is now inlined in the ufs_xxx functions.
187  *
188  * XXX - ULOCKFS in fs_pathconf and ufs_ioctl is not inlined yet.
189  */
190 struct vnodeops *ufs_vnodeops;
191 
192 /* NOTE: "not blkd" below  means that the operation isn't blocked by lockfs */
193 const fs_operation_def_t ufs_vnodeops_template[] = {
194 	VOPNAME_OPEN,		{ .vop_open = ufs_open },	/* not blkd */
195 	VOPNAME_CLOSE,		{ .vop_close = ufs_close },	/* not blkd */
196 	VOPNAME_READ,		{ .vop_read = ufs_read },
197 	VOPNAME_WRITE,		{ .vop_write = ufs_write },
198 	VOPNAME_IOCTL,		{ .vop_ioctl = ufs_ioctl },
199 	VOPNAME_GETATTR,	{ .vop_getattr = ufs_getattr },
200 	VOPNAME_SETATTR,	{ .vop_setattr = ufs_setattr },
201 	VOPNAME_ACCESS,		{ .vop_access = ufs_access },
202 	VOPNAME_LOOKUP,		{ .vop_lookup = ufs_lookup },
203 	VOPNAME_CREATE,		{ .vop_create = ufs_create },
204 	VOPNAME_REMOVE,		{ .vop_remove = ufs_remove },
205 	VOPNAME_LINK,		{ .vop_link = ufs_link },
206 	VOPNAME_RENAME,		{ .vop_rename = ufs_rename },
207 	VOPNAME_MKDIR,		{ .vop_mkdir = ufs_mkdir },
208 	VOPNAME_RMDIR,		{ .vop_rmdir = ufs_rmdir },
209 	VOPNAME_READDIR,	{ .vop_readdir = ufs_readdir },
210 	VOPNAME_SYMLINK,	{ .vop_symlink = ufs_symlink },
211 	VOPNAME_READLINK,	{ .vop_readlink = ufs_readlink },
212 	VOPNAME_FSYNC,		{ .vop_fsync = ufs_fsync },
213 	VOPNAME_INACTIVE,	{ .vop_inactive = ufs_inactive }, /* not blkd */
214 	VOPNAME_FID,		{ .vop_fid = ufs_fid },
215 	VOPNAME_RWLOCK,		{ .vop_rwlock = ufs_rwlock },	/* not blkd */
216 	VOPNAME_RWUNLOCK,	{ .vop_rwunlock = ufs_rwunlock }, /* not blkd */
217 	VOPNAME_SEEK,		{ .vop_seek = ufs_seek },
218 	VOPNAME_FRLOCK,		{ .vop_frlock = ufs_frlock },
219 	VOPNAME_SPACE,		{ .vop_space = ufs_space },
220 	VOPNAME_GETPAGE,	{ .vop_getpage = ufs_getpage },
221 	VOPNAME_PUTPAGE,	{ .vop_putpage = ufs_putpage },
222 	VOPNAME_MAP,		{ .vop_map = ufs_map },
223 	VOPNAME_ADDMAP,		{ .vop_addmap = ufs_addmap },	/* not blkd */
224 	VOPNAME_DELMAP,		{ .vop_delmap = ufs_delmap },	/* not blkd */
225 	VOPNAME_POLL,		{ .vop_poll = ufs_poll },	/* not blkd */
226 	VOPNAME_DUMP,		{ .vop_dump = ufs_dump },
227 	VOPNAME_PATHCONF,	{ .vop_pathconf = ufs_l_pathconf },
228 	VOPNAME_PAGEIO,		{ .vop_pageio = ufs_pageio },
229 	VOPNAME_DUMPCTL,	{ .vop_dumpctl = ufs_dumpctl },
230 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = ufs_getsecattr },
231 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = ufs_setsecattr },
232 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
233 	NULL,			NULL
234 };
235 
236 #define	MAX_BACKFILE_COUNT	9999
237 
238 /*
239  * Created by ufs_dumpctl() to store a file's disk block info into memory.
240  * Used by ufs_dump() to dump data to disk directly.
241  */
242 struct dump {
243 	struct inode	*ip;		/* the file we contain */
244 	daddr_t		fsbs;		/* number of blocks stored */
245 	struct timeval32 time;		/* time stamp for the struct */
246 	daddr32_t 	dblk[1];	/* place holder for block info */
247 };
248 
249 static struct dump *dump_info = NULL;
250 
251 /*
252  * Previously there was no special action required for ordinary files.
253  * (Devices are handled through the device file system.)
254  * Now we support Large Files and Large File API requires open to
255  * fail if file is large.
256  * We could take care to prevent data corruption
257  * by doing an atomic check of size and truncate if file is opened with
258  * FTRUNC flag set but traditionally this is being done by the vfs/vnode
259  * layers. So taking care of truncation here is a change in the existing
260  * semantics of VOP_OPEN and therefore we chose not to implement any thing
261  * here. The check for the size of the file > 2GB is being done at the
262  * vfs layer in routine vn_open().
263  */
264 
265 /* ARGSUSED */
266 static int
267 ufs_open(struct vnode **vpp, int flag, struct cred *cr, caller_context_t *ct)
268 {
269 	return (0);
270 }
271 
272 /*ARGSUSED*/
273 static int
274 ufs_close(struct vnode *vp, int flag, int count, offset_t offset,
275 	struct cred *cr, caller_context_t *ct)
276 {
277 	cleanlocks(vp, ttoproc(curthread)->p_pid, 0);
278 	cleanshares(vp, ttoproc(curthread)->p_pid);
279 
280 	/*
281 	 * Push partially filled cluster at last close.
282 	 * ``last close'' is approximated because the dnlc
283 	 * may have a hold on the vnode.
284 	 * Checking for VBAD here will also act as a forced umount check.
285 	 */
286 	if (vp->v_count <= 2 && vp->v_type != VBAD) {
287 		struct inode *ip = VTOI(vp);
288 		if (ip->i_delaylen) {
289 			ins.in_poc.value.ul++;
290 			(void) ufs_putpages(vp, ip->i_delayoff, ip->i_delaylen,
291 			    B_ASYNC | B_FREE, cr);
292 			ip->i_delaylen = 0;
293 		}
294 	}
295 
296 	return (0);
297 }
298 
299 /*ARGSUSED*/
300 static int
301 ufs_read(struct vnode *vp, struct uio *uiop, int ioflag, struct cred *cr,
302 	struct caller_context *ct)
303 {
304 	struct inode *ip = VTOI(vp);
305 	struct ufsvfs *ufsvfsp;
306 	struct ulockfs *ulp = NULL;
307 	int error = 0;
308 	int intrans = 0;
309 
310 	ASSERT(RW_READ_HELD(&ip->i_rwlock));
311 
312 	/*
313 	 * Mandatory locking needs to be done before ufs_lockfs_begin()
314 	 * and TRANS_BEGIN_SYNC() calls since mandatory locks can sleep.
315 	 */
316 	if (MANDLOCK(vp, ip->i_mode)) {
317 		/*
318 		 * ufs_getattr ends up being called by chklock
319 		 */
320 		error = chklock(vp, FREAD, uiop->uio_loffset,
321 		    uiop->uio_resid, uiop->uio_fmode, ct);
322 		if (error)
323 			goto out;
324 	}
325 
326 	ufsvfsp = ip->i_ufsvfs;
327 	error = ufs_lockfs_begin(ufsvfsp, &ulp, ULOCKFS_READ_MASK);
328 	if (error)
329 		goto out;
330 
331 	/*
332 	 * In the case that a directory is opened for reading as a file
333 	 * (eg "cat .") with the  O_RSYNC, O_SYNC and O_DSYNC flags set.
334 	 * The locking order had to be changed to avoid a deadlock with
335 	 * an update taking place on that directory at the same time.
336 	 */
337 	if ((ip->i_mode & IFMT) == IFDIR) {
338 
339 		rw_enter(&ip->i_contents, RW_READER);
340 		error = rdip(ip, uiop, ioflag, cr);
341 		rw_exit(&ip->i_contents);
342 
343 		if (error) {
344 			if (ulp)
345 				ufs_lockfs_end(ulp);
346 			goto out;
347 		}
348 
349 		if (ulp && (ioflag & FRSYNC) && (ioflag & (FSYNC | FDSYNC)) &&
350 		    TRANS_ISTRANS(ufsvfsp)) {
351 			rw_exit(&ip->i_rwlock);
352 			TRANS_BEGIN_SYNC(ufsvfsp, TOP_READ_SYNC, TOP_READ_SIZE,
353 			    error);
354 			ASSERT(!error);
355 			TRANS_END_SYNC(ufsvfsp, error, TOP_READ_SYNC,
356 			    TOP_READ_SIZE);
357 			rw_enter(&ip->i_rwlock, RW_READER);
358 		}
359 	} else {
360 		/*
361 		 * Only transact reads to files opened for sync-read and
362 		 * sync-write on a file system that is not write locked.
363 		 *
364 		 * The ``not write locked'' check prevents problems with
365 		 * enabling/disabling logging on a busy file system.  E.g.,
366 		 * logging exists at the beginning of the read but does not
367 		 * at the end.
368 		 *
369 		 */
370 		if (ulp && (ioflag & FRSYNC) && (ioflag & (FSYNC | FDSYNC)) &&
371 		    TRANS_ISTRANS(ufsvfsp)) {
372 			TRANS_BEGIN_SYNC(ufsvfsp, TOP_READ_SYNC, TOP_READ_SIZE,
373 			    error);
374 			ASSERT(!error);
375 			intrans = 1;
376 		}
377 
378 		rw_enter(&ip->i_contents, RW_READER);
379 		error = rdip(ip, uiop, ioflag, cr);
380 		rw_exit(&ip->i_contents);
381 
382 		if (intrans) {
383 			TRANS_END_SYNC(ufsvfsp, error, TOP_READ_SYNC,
384 			    TOP_READ_SIZE);
385 		}
386 	}
387 
388 	if (ulp) {
389 		ufs_lockfs_end(ulp);
390 	}
391 out:
392 
393 	return (error);
394 }
395 
396 extern	int	ufs_HW;		/* high water mark */
397 extern	int	ufs_LW;		/* low water mark */
398 int	ufs_WRITES = 1;		/* XXX - enable/disable */
399 int	ufs_throttles = 0;	/* throttling count */
400 int	ufs_allow_shared_writes = 1;	/* directio shared writes */
401 
402 static int
403 ufs_check_rewrite(struct inode *ip, struct uio *uiop, int ioflag)
404 {
405 	int	shared_write;
406 
407 	/*
408 	 * If the FDSYNC flag is set then ignore the global
409 	 * ufs_allow_shared_writes in this case.
410 	 */
411 	shared_write = (ioflag & FDSYNC) | ufs_allow_shared_writes;
412 
413 	/*
414 	 * Filter to determine if this request is suitable as a
415 	 * concurrent rewrite. This write must not allocate blocks
416 	 * by extending the file or filling in holes. No use trying
417 	 * through FSYNC descriptors as the inode will be synchronously
418 	 * updated after the write. The uio structure has not yet been
419 	 * checked for sanity, so assume nothing.
420 	 */
421 	return (((ip->i_mode & IFMT) == IFREG) && !(ioflag & FAPPEND) &&
422 	    (uiop->uio_loffset >= (offset_t)0) &&
423 	    (uiop->uio_loffset < ip->i_size) && (uiop->uio_resid > 0) &&
424 	    ((ip->i_size - uiop->uio_loffset) >= uiop->uio_resid) &&
425 	    !(ioflag & FSYNC) && !bmap_has_holes(ip) &&
426 	    shared_write);
427 }
428 
429 /*ARGSUSED*/
430 static int
431 ufs_write(struct vnode *vp, struct uio *uiop, int ioflag, cred_t *cr,
432 	caller_context_t *ct)
433 {
434 	struct inode *ip = VTOI(vp);
435 	struct ufsvfs *ufsvfsp;
436 	struct ulockfs *ulp;
437 	int retry = 1;
438 	int error, resv, resid = 0;
439 	int directio_status;
440 	int exclusive;
441 	int rewriteflg;
442 	long start_resid = uiop->uio_resid;
443 
444 	ASSERT(RW_LOCK_HELD(&ip->i_rwlock));
445 
446 retry_mandlock:
447 	/*
448 	 * Mandatory locking needs to be done before ufs_lockfs_begin()
449 	 * and TRANS_BEGIN_[A]SYNC() calls since mandatory locks can sleep.
450 	 * Check for forced unmounts normally done in ufs_lockfs_begin().
451 	 */
452 	if ((ufsvfsp = ip->i_ufsvfs) == NULL) {
453 		error = EIO;
454 		goto out;
455 	}
456 	if (MANDLOCK(vp, ip->i_mode)) {
457 
458 		ASSERT(RW_WRITE_HELD(&ip->i_rwlock));
459 
460 		/*
461 		 * ufs_getattr ends up being called by chklock
462 		 */
463 		error = chklock(vp, FWRITE, uiop->uio_loffset,
464 		    uiop->uio_resid, uiop->uio_fmode, ct);
465 		if (error)
466 			goto out;
467 	}
468 
469 	/* i_rwlock can change in chklock */
470 	exclusive = rw_write_held(&ip->i_rwlock);
471 	rewriteflg = ufs_check_rewrite(ip, uiop, ioflag);
472 
473 	/*
474 	 * Check for fast-path special case of directio re-writes.
475 	 */
476 	if ((ip->i_flag & IDIRECTIO || ufsvfsp->vfs_forcedirectio) &&
477 	    !exclusive && rewriteflg) {
478 
479 		error = ufs_lockfs_begin(ufsvfsp, &ulp, ULOCKFS_WRITE_MASK);
480 		if (error)
481 			goto out;
482 
483 		rw_enter(&ip->i_contents, RW_READER);
484 		error = ufs_directio_write(ip, uiop, ioflag, 1, cr,
485 		    &directio_status);
486 		if (directio_status == DIRECTIO_SUCCESS) {
487 			uint_t i_flag_save;
488 
489 			if (start_resid != uiop->uio_resid)
490 				error = 0;
491 			/*
492 			 * Special treatment of access times for re-writes.
493 			 * If IMOD is not already set, then convert it
494 			 * to IMODACC for this operation. This defers
495 			 * entering a delta into the log until the inode
496 			 * is flushed. This mimics what is done for read
497 			 * operations and inode access time.
498 			 */
499 			mutex_enter(&ip->i_tlock);
500 			i_flag_save = ip->i_flag;
501 			ip->i_flag |= IUPD | ICHG;
502 			ip->i_seq++;
503 			ITIMES_NOLOCK(ip);
504 			if ((i_flag_save & IMOD) == 0) {
505 				ip->i_flag &= ~IMOD;
506 				ip->i_flag |= IMODACC;
507 			}
508 			mutex_exit(&ip->i_tlock);
509 			rw_exit(&ip->i_contents);
510 			if (ulp)
511 				ufs_lockfs_end(ulp);
512 			goto out;
513 		}
514 		rw_exit(&ip->i_contents);
515 		if (ulp)
516 			ufs_lockfs_end(ulp);
517 	}
518 
519 	if (!exclusive && !rw_tryupgrade(&ip->i_rwlock)) {
520 		rw_exit(&ip->i_rwlock);
521 		rw_enter(&ip->i_rwlock, RW_WRITER);
522 		/*
523 		 * Mandatory locking could have been enabled
524 		 * after dropping the i_rwlock.
525 		 */
526 		if (MANDLOCK(vp, ip->i_mode))
527 			goto retry_mandlock;
528 	}
529 
530 	error = ufs_lockfs_begin(ufsvfsp, &ulp, ULOCKFS_WRITE_MASK);
531 	if (error)
532 		goto out;
533 
534 	/*
535 	 * Amount of log space needed for this write
536 	 */
537 	if (!rewriteflg || !(ioflag & FDSYNC))
538 		TRANS_WRITE_RESV(ip, uiop, ulp, &resv, &resid);
539 
540 	/*
541 	 * Throttle writes.
542 	 */
543 	if (ufs_WRITES && (ip->i_writes > ufs_HW)) {
544 		mutex_enter(&ip->i_tlock);
545 		while (ip->i_writes > ufs_HW) {
546 			ufs_throttles++;
547 			cv_wait(&ip->i_wrcv, &ip->i_tlock);
548 		}
549 		mutex_exit(&ip->i_tlock);
550 	}
551 
552 	/*
553 	 * Enter Transaction
554 	 *
555 	 * If the write is a rewrite there is no need to open a transaction
556 	 * if the FDSYNC flag is set and not the FSYNC.  In this case just
557 	 * set the IMODACC flag to modify do the update at a later time
558 	 * thus avoiding the overhead of the logging transaction that is
559 	 * not required.
560 	 */
561 	if (ioflag & (FSYNC|FDSYNC)) {
562 		if (ulp) {
563 			if (rewriteflg) {
564 				uint_t i_flag_save;
565 
566 				rw_enter(&ip->i_contents, RW_READER);
567 				mutex_enter(&ip->i_tlock);
568 				i_flag_save = ip->i_flag;
569 				ip->i_flag |= IUPD | ICHG;
570 				ip->i_seq++;
571 				ITIMES_NOLOCK(ip);
572 				if ((i_flag_save & IMOD) == 0) {
573 					ip->i_flag &= ~IMOD;
574 					ip->i_flag |= IMODACC;
575 				}
576 				mutex_exit(&ip->i_tlock);
577 				rw_exit(&ip->i_contents);
578 			} else {
579 				int terr = 0;
580 				TRANS_BEGIN_SYNC(ufsvfsp, TOP_WRITE_SYNC, resv,
581 				    terr);
582 				ASSERT(!terr);
583 			}
584 		}
585 	} else {
586 		if (ulp)
587 			TRANS_BEGIN_ASYNC(ufsvfsp, TOP_WRITE, resv);
588 	}
589 
590 	/*
591 	 * Write the file
592 	 */
593 	rw_enter(&ufsvfsp->vfs_dqrwlock, RW_READER);
594 	rw_enter(&ip->i_contents, RW_WRITER);
595 	if ((ioflag & FAPPEND) != 0 && (ip->i_mode & IFMT) == IFREG) {
596 		/*
597 		 * In append mode start at end of file.
598 		 */
599 		uiop->uio_loffset = ip->i_size;
600 	}
601 
602 	/*
603 	 * Mild optimisation, don't call ufs_trans_write() unless we have to
604 	 * Also, suppress file system full messages if we will retry.
605 	 */
606 	if (retry)
607 		ip->i_flag |= IQUIET;
608 	if (resid) {
609 		TRANS_WRITE(ip, uiop, ioflag, error, ulp, cr, resv, resid);
610 	} else {
611 		error = wrip(ip, uiop, ioflag, cr);
612 	}
613 	ip->i_flag &= ~IQUIET;
614 
615 	rw_exit(&ip->i_contents);
616 	rw_exit(&ufsvfsp->vfs_dqrwlock);
617 
618 	/*
619 	 * Leave Transaction
620 	 */
621 	if (ulp) {
622 		if (ioflag & (FSYNC|FDSYNC)) {
623 			if (!rewriteflg) {
624 				int terr = 0;
625 
626 				TRANS_END_SYNC(ufsvfsp, terr, TOP_WRITE_SYNC,
627 				    resv);
628 				if (error == 0)
629 					error = terr;
630 			}
631 		} else {
632 			TRANS_END_ASYNC(ufsvfsp, TOP_WRITE, resv);
633 		}
634 		ufs_lockfs_end(ulp);
635 	}
636 out:
637 	if ((error == ENOSPC) && retry && TRANS_ISTRANS(ufsvfsp)) {
638 		/*
639 		 * Any blocks tied up in pending deletes?
640 		 */
641 		ufs_delete_drain_wait(ufsvfsp, 1);
642 		retry = 0;
643 		goto retry_mandlock;
644 	}
645 
646 	if (error == ENOSPC && (start_resid != uiop->uio_resid))
647 		error = 0;
648 
649 	return (error);
650 }
651 
652 /*
653  * Don't cache write blocks to files with the sticky bit set.
654  * Used to keep swap files from blowing the page cache on a server.
655  */
656 int stickyhack = 1;
657 
658 /*
659  * Free behind hacks.  The pager is busted.
660  * XXX - need to pass the information down to writedone() in a flag like B_SEQ
661  * or B_FREE_IF_TIGHT_ON_MEMORY.
662  */
663 int	freebehind = 1;
664 int	smallfile = 0;
665 u_offset_t smallfile64 = 32 * 1024;
666 
667 /*
668  * While we should, in most cases, cache the pages for write, we
669  * may also want to cache the pages for read as long as they are
670  * frequently re-usable.
671  *
672  * If cache_read_ahead = 1, the pages for read will go to the tail
673  * of the cache list when they are released, otherwise go to the head.
674  */
675 int	cache_read_ahead = 0;
676 
677 /*
678  * Freebehind exists  so that as we read  large files  sequentially we
679  * don't consume most of memory with pages  from a few files. It takes
680  * longer to re-read from disk multiple small files as it does reading
681  * one large one sequentially.  As system  memory grows customers need
682  * to retain bigger chunks   of files in  memory.   The advent of  the
683  * cachelist opens up of the possibility freeing pages  to the head or
684  * tail of the list.
685  *
686  * Not freeing a page is a bet that the page will be read again before
687  * it's segmap slot is needed for something else. If we loose the bet,
688  * it means some  other thread is  burdened with the  page free we did
689  * not do. If we win we save a free and reclaim.
690  *
691  * Freeing it at the tail  vs the head of cachelist  is a bet that the
692  * page will survive until the next  read.  It's also saying that this
693  * page is more likely to  be re-used than a  page freed some time ago
694  * and never reclaimed.
695  *
696  * Freebehind maintains a  range of  file offset [smallfile1; smallfile2]
697  *
698  *            0 < offset < smallfile1 : pages are not freed.
699  *   smallfile1 < offset < smallfile2 : pages freed to tail of cachelist.
700  *   smallfile2 < offset              : pages freed to head of cachelist.
701  *
702  * The range  is  computed  at most  once  per second  and  depends on
703  * freemem  and  ncpus_online.  Both parameters  are   bounded to be
704  * >= smallfile && >= smallfile64.
705  *
706  * smallfile1 = (free memory / ncpu) / 1000
707  * smallfile2 = (free memory / ncpu) / 10
708  *
709  * A few examples values:
710  *
711  *       Free Mem (in Bytes) [smallfile1; smallfile2]  [smallfile1; smallfile2]
712  *                                 ncpus_online = 4          ncpus_online = 64
713  *       ------------------  -----------------------   -----------------------
714  *             1G                   [256K;  25M]               [32K; 1.5M]
715  *            10G                   [2.5M; 250M]              [156K; 15M]
716  *           100G                    [25M; 2.5G]              [1.5M; 150M]
717  *
718  */
719 
720 #define	SMALLFILE1_D 1000
721 #define	SMALLFILE2_D 10
722 static u_offset_t smallfile1 = 32 * 1024;
723 static u_offset_t smallfile2 = 32 * 1024;
724 static clock_t smallfile_update = 0; /* lbolt value of when to recompute */
725 uint_t smallfile1_d = SMALLFILE1_D;
726 uint_t smallfile2_d = SMALLFILE2_D;
727 
728 /*
729  * wrip does the real work of write requests for ufs.
730  */
731 int
732 wrip(struct inode *ip, struct uio *uio, int ioflag, struct cred *cr)
733 {
734 	rlim64_t limit = uio->uio_llimit;
735 	u_offset_t off;
736 	u_offset_t old_i_size;
737 	struct fs *fs;
738 	struct vnode *vp;
739 	struct ufsvfs *ufsvfsp;
740 	caddr_t base;
741 	long start_resid = uio->uio_resid;	/* save starting resid */
742 	long premove_resid;			/* resid before uiomove() */
743 	uint_t flags;
744 	int newpage;
745 	int iupdat_flag, directio_status;
746 	int n, on, mapon;
747 	int error, pagecreate;
748 	int do_dqrwlock;		/* drop/reacquire vfs_dqrwlock */
749 	int32_t	iblocks;
750 	int	new_iblocks;
751 
752 	/*
753 	 * ip->i_size is incremented before the uiomove
754 	 * is done on a write.  If the move fails (bad user
755 	 * address) reset ip->i_size.
756 	 * The better way would be to increment ip->i_size
757 	 * only if the uiomove succeeds.
758 	 */
759 	int i_size_changed = 0;
760 	o_mode_t type;
761 	int i_seq_needed = 0;
762 
763 	vp = ITOV(ip);
764 
765 	/*
766 	 * check for forced unmount - should not happen as
767 	 * the request passed the lockfs checks.
768 	 */
769 	if ((ufsvfsp = ip->i_ufsvfs) == NULL)
770 		return (EIO);
771 
772 	fs = ip->i_fs;
773 
774 	ASSERT(RW_WRITE_HELD(&ip->i_contents));
775 
776 	/* check for valid filetype */
777 	type = ip->i_mode & IFMT;
778 	if ((type != IFREG) && (type != IFDIR) && (type != IFATTRDIR) &&
779 	    (type != IFLNK) && (type != IFSHAD)) {
780 		return (EIO);
781 	}
782 
783 	/*
784 	 * the actual limit of UFS file size
785 	 * is UFS_MAXOFFSET_T
786 	 */
787 	if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
788 		limit = MAXOFFSET_T;
789 
790 	if (uio->uio_loffset >= limit) {
791 		proc_t *p = ttoproc(curthread);
792 
793 		mutex_enter(&p->p_lock);
794 		(void) rctl_action(rctlproc_legacy[RLIMIT_FSIZE], p->p_rctls,
795 		    p, RCA_UNSAFE_SIGINFO);
796 		mutex_exit(&p->p_lock);
797 		return (EFBIG);
798 	}
799 
800 	/*
801 	 * if largefiles are disallowed, the limit is
802 	 * the pre-largefiles value of 2GB
803 	 */
804 	if (ufsvfsp->vfs_lfflags & UFS_LARGEFILES)
805 		limit = MIN(UFS_MAXOFFSET_T, limit);
806 	else
807 		limit = MIN(MAXOFF32_T, limit);
808 
809 	if (uio->uio_loffset < (offset_t)0) {
810 		return (EINVAL);
811 	}
812 	if (uio->uio_resid == 0) {
813 		return (0);
814 	}
815 
816 	if (uio->uio_loffset >= limit)
817 		return (EFBIG);
818 
819 	ip->i_flag |= INOACC;	/* don't update ref time in getpage */
820 
821 	if (ioflag & (FSYNC|FDSYNC)) {
822 		ip->i_flag |= ISYNC;
823 		iupdat_flag = 1;
824 	}
825 	/*
826 	 * Try to go direct
827 	 */
828 	if (ip->i_flag & IDIRECTIO || ufsvfsp->vfs_forcedirectio) {
829 		uio->uio_llimit = limit;
830 		error = ufs_directio_write(ip, uio, ioflag, 0, cr,
831 		    &directio_status);
832 		/*
833 		 * If ufs_directio wrote to the file or set the flags,
834 		 * we need to update i_seq, but it may be deferred.
835 		 */
836 		if (start_resid != uio->uio_resid ||
837 		    (ip->i_flag & (ICHG|IUPD))) {
838 			i_seq_needed = 1;
839 			ip->i_flag |= ISEQ;
840 		}
841 		if (directio_status == DIRECTIO_SUCCESS)
842 			goto out;
843 	}
844 
845 	/*
846 	 * Behavior with respect to dropping/reacquiring vfs_dqrwlock:
847 	 *
848 	 * o shadow inodes: vfs_dqrwlock is not held at all
849 	 * o quota updates: vfs_dqrwlock is read or write held
850 	 * o other updates: vfs_dqrwlock is read held
851 	 *
852 	 * The first case is the only one where we do not hold
853 	 * vfs_dqrwlock at all while entering wrip().
854 	 * We must make sure not to downgrade/drop vfs_dqrwlock if we
855 	 * have it as writer, i.e. if we are updating the quota inode.
856 	 * There is no potential deadlock scenario in this case as
857 	 * ufs_getpage() takes care of this and avoids reacquiring
858 	 * vfs_dqrwlock in that case.
859 	 *
860 	 * This check is done here since the above conditions do not change
861 	 * and we possibly loop below, so save a few cycles.
862 	 */
863 	if ((type == IFSHAD) ||
864 	    (rw_owner(&ufsvfsp->vfs_dqrwlock) == curthread)) {
865 		do_dqrwlock = 0;
866 	} else {
867 		do_dqrwlock = 1;
868 	}
869 
870 	/*
871 	 * Large Files: We cast MAXBMASK to offset_t
872 	 * inorder to mask out the higher bits. Since offset_t
873 	 * is a signed value, the high order bit set in MAXBMASK
874 	 * value makes it do the right thing by having all bits 1
875 	 * in the higher word. May be removed for _SOLARIS64_.
876 	 */
877 
878 	fs = ip->i_fs;
879 	do {
880 		u_offset_t uoff = uio->uio_loffset;
881 		off = uoff & (offset_t)MAXBMASK;
882 		mapon = (int)(uoff & (offset_t)MAXBOFFSET);
883 		on = (int)blkoff(fs, uoff);
884 		n = (int)MIN(fs->fs_bsize - on, uio->uio_resid);
885 		new_iblocks = 1;
886 
887 		if (type == IFREG && uoff + n >= limit) {
888 			if (uoff >= limit) {
889 				error = EFBIG;
890 				goto out;
891 			}
892 			/*
893 			 * since uoff + n >= limit,
894 			 * therefore n >= limit - uoff, and n is an int
895 			 * so it is safe to cast it to an int
896 			 */
897 			n = (int)(limit - (rlim64_t)uoff);
898 		}
899 		if (uoff + n > ip->i_size) {
900 			/*
901 			 * We are extending the length of the file.
902 			 * bmap is used so that we are sure that
903 			 * if we need to allocate new blocks, that it
904 			 * is done here before we up the file size.
905 			 */
906 			error = bmap_write(ip, uoff, (int)(on + n),
907 			    mapon == 0, NULL, cr);
908 			/*
909 			 * bmap_write never drops i_contents so if
910 			 * the flags are set it changed the file.
911 			 */
912 			if (ip->i_flag & (ICHG|IUPD)) {
913 				i_seq_needed = 1;
914 				ip->i_flag |= ISEQ;
915 			}
916 			if (error)
917 				break;
918 			/*
919 			 * There is a window of vulnerability here.
920 			 * The sequence of operations: allocate file
921 			 * system blocks, uiomove the data into pages,
922 			 * and then update the size of the file in the
923 			 * inode, must happen atomically.  However, due
924 			 * to current locking constraints, this can not
925 			 * be done.
926 			 */
927 			ASSERT(ip->i_writer == NULL);
928 			ip->i_writer = curthread;
929 			i_size_changed = 1;
930 			/*
931 			 * If we are writing from the beginning of
932 			 * the mapping, we can just create the
933 			 * pages without having to read them.
934 			 */
935 			pagecreate = (mapon == 0);
936 		} else if (n == MAXBSIZE) {
937 			/*
938 			 * Going to do a whole mappings worth,
939 			 * so we can just create the pages w/o
940 			 * having to read them in.  But before
941 			 * we do that, we need to make sure any
942 			 * needed blocks are allocated first.
943 			 */
944 			iblocks = ip->i_blocks;
945 			error = bmap_write(ip, uoff, (int)(on + n),
946 			    BI_ALLOC_ONLY, NULL, cr);
947 			/*
948 			 * bmap_write never drops i_contents so if
949 			 * the flags are set it changed the file.
950 			 */
951 			if (ip->i_flag & (ICHG|IUPD)) {
952 				i_seq_needed = 1;
953 				ip->i_flag |= ISEQ;
954 			}
955 			if (error)
956 				break;
957 			pagecreate = 1;
958 			/*
959 			 * check if the new created page needed the
960 			 * allocation of new disk blocks.
961 			 */
962 			if (iblocks == ip->i_blocks)
963 				new_iblocks = 0; /* no new blocks allocated */
964 		} else {
965 			pagecreate = 0;
966 			/*
967 			 * In sync mode flush the indirect blocks which
968 			 * may have been allocated and not written on
969 			 * disk. In above cases bmap_write will allocate
970 			 * in sync mode.
971 			 */
972 			if (ioflag & (FSYNC|FDSYNC)) {
973 				error = ufs_indirblk_sync(ip, uoff);
974 				if (error)
975 					break;
976 			}
977 		}
978 
979 		/*
980 		 * At this point we can enter ufs_getpage() in one
981 		 * of two ways:
982 		 * 1) segmap_getmapflt() calls ufs_getpage() when the
983 		 *    forcefault parameter is true (pagecreate == 0)
984 		 * 2) uiomove() causes a page fault.
985 		 *
986 		 * We have to drop the contents lock to prevent the VM
987 		 * system from trying to reacquire it in ufs_getpage()
988 		 * should the uiomove cause a pagefault.
989 		 *
990 		 * We have to drop the reader vfs_dqrwlock here as well.
991 		 */
992 		rw_exit(&ip->i_contents);
993 		if (do_dqrwlock) {
994 			ASSERT(RW_LOCK_HELD(&ufsvfsp->vfs_dqrwlock));
995 			ASSERT(!(RW_WRITE_HELD(&ufsvfsp->vfs_dqrwlock)));
996 			rw_exit(&ufsvfsp->vfs_dqrwlock);
997 		}
998 
999 		newpage = 0;
1000 		premove_resid = uio->uio_resid;
1001 		if (vpm_enable) {
1002 			/*
1003 			 * Copy data. If new pages are created, part of
1004 			 * the page that is not written will be initizliazed
1005 			 * with zeros.
1006 			 */
1007 			error = vpm_data_copy(vp, (off + mapon), (uint_t)n,
1008 			    uio, !pagecreate, &newpage, 0, S_WRITE);
1009 		} else {
1010 
1011 			base = segmap_getmapflt(segkmap, vp, (off + mapon),
1012 			    (uint_t)n, !pagecreate, S_WRITE);
1013 
1014 			/*
1015 			 * segmap_pagecreate() returns 1 if it calls
1016 			 * page_create_va() to allocate any pages.
1017 			 */
1018 
1019 			if (pagecreate)
1020 				newpage = segmap_pagecreate(segkmap, base,
1021 				    (size_t)n, 0);
1022 
1023 			error = uiomove(base + mapon, (long)n, UIO_WRITE, uio);
1024 		}
1025 
1026 		/*
1027 		 * If "newpage" is set, then a new page was created and it
1028 		 * does not contain valid data, so it needs to be initialized
1029 		 * at this point.
1030 		 * Otherwise the page contains old data, which was overwritten
1031 		 * partially or as a whole in uiomove.
1032 		 * If there is only one iovec structure within uio, then
1033 		 * on error uiomove will not be able to update uio->uio_loffset
1034 		 * and we would zero the whole page here!
1035 		 *
1036 		 * If uiomove fails because of an error, the old valid data
1037 		 * is kept instead of filling the rest of the page with zero's.
1038 		 */
1039 		if (!vpm_enable && newpage &&
1040 		    uio->uio_loffset < roundup(off + mapon + n, PAGESIZE)) {
1041 			/*
1042 			 * We created pages w/o initializing them completely,
1043 			 * thus we need to zero the part that wasn't set up.
1044 			 * This happens on most EOF write cases and if
1045 			 * we had some sort of error during the uiomove.
1046 			 */
1047 			int nzero, nmoved;
1048 
1049 			nmoved = (int)(uio->uio_loffset - (off + mapon));
1050 			ASSERT(nmoved >= 0 && nmoved <= n);
1051 			nzero = roundup(on + n, PAGESIZE) - nmoved;
1052 			ASSERT(nzero > 0 && mapon + nmoved + nzero <= MAXBSIZE);
1053 			(void) kzero(base + mapon + nmoved, (uint_t)nzero);
1054 		}
1055 
1056 		/*
1057 		 * Unlock the pages allocated by page_create_va()
1058 		 * in segmap_pagecreate()
1059 		 */
1060 		if (!vpm_enable && newpage)
1061 			segmap_pageunlock(segkmap, base, (size_t)n, S_WRITE);
1062 
1063 		/*
1064 		 * If the size of the file changed, then update the
1065 		 * size field in the inode now.  This can't be done
1066 		 * before the call to segmap_pageunlock or there is
1067 		 * a potential deadlock with callers to ufs_putpage().
1068 		 * They will be holding i_contents and trying to lock
1069 		 * a page, while this thread is holding a page locked
1070 		 * and trying to acquire i_contents.
1071 		 */
1072 		if (i_size_changed) {
1073 			rw_enter(&ip->i_contents, RW_WRITER);
1074 			old_i_size = ip->i_size;
1075 			UFS_SET_ISIZE(uoff + n, ip);
1076 			TRANS_INODE(ufsvfsp, ip);
1077 			/*
1078 			 * file has grown larger than 2GB. Set flag
1079 			 * in superblock to indicate this, if it
1080 			 * is not already set.
1081 			 */
1082 			if ((ip->i_size > MAXOFF32_T) &&
1083 			    !(fs->fs_flags & FSLARGEFILES)) {
1084 				ASSERT(ufsvfsp->vfs_lfflags & UFS_LARGEFILES);
1085 				mutex_enter(&ufsvfsp->vfs_lock);
1086 				fs->fs_flags |= FSLARGEFILES;
1087 				ufs_sbwrite(ufsvfsp);
1088 				mutex_exit(&ufsvfsp->vfs_lock);
1089 			}
1090 			mutex_enter(&ip->i_tlock);
1091 			ip->i_writer = NULL;
1092 			cv_broadcast(&ip->i_wrcv);
1093 			mutex_exit(&ip->i_tlock);
1094 			rw_exit(&ip->i_contents);
1095 		}
1096 
1097 		if (error) {
1098 			/*
1099 			 * If we failed on a write, we may have already
1100 			 * allocated file blocks as well as pages.  It's
1101 			 * hard to undo the block allocation, but we must
1102 			 * be sure to invalidate any pages that may have
1103 			 * been allocated.
1104 			 *
1105 			 * If the page was created without initialization
1106 			 * then we must check if it should be possible
1107 			 * to destroy the new page and to keep the old data
1108 			 * on the disk.
1109 			 *
1110 			 * It is possible to destroy the page without
1111 			 * having to write back its contents only when
1112 			 * - the size of the file keeps unchanged
1113 			 * - bmap_write() did not allocate new disk blocks
1114 			 *   it is possible to create big files using "seek" and
1115 			 *   write to the end of the file. A "write" to a
1116 			 *   position before the end of the file would not
1117 			 *   change the size of the file but it would allocate
1118 			 *   new disk blocks.
1119 			 * - uiomove intended to overwrite the whole page.
1120 			 * - a new page was created (newpage == 1).
1121 			 */
1122 
1123 			if (i_size_changed == 0 && new_iblocks == 0 &&
1124 			    newpage) {
1125 
1126 				/* unwind what uiomove eventually last did */
1127 				uio->uio_resid = premove_resid;
1128 
1129 				/*
1130 				 * destroy the page, do not write ambiguous
1131 				 * data to the disk.
1132 				 */
1133 				flags = SM_DESTROY;
1134 			} else {
1135 				/*
1136 				 * write the page back to the disk, if dirty,
1137 				 * and remove the page from the cache.
1138 				 */
1139 				flags = SM_INVAL;
1140 			}
1141 
1142 			if (vpm_enable) {
1143 				/*
1144 				 *  Flush pages.
1145 				 */
1146 				(void) vpm_sync_pages(vp, off, n, flags);
1147 			} else {
1148 				(void) segmap_release(segkmap, base, flags);
1149 			}
1150 		} else {
1151 			flags = 0;
1152 			/*
1153 			 * Force write back for synchronous write cases.
1154 			 */
1155 			if ((ioflag & (FSYNC|FDSYNC)) || type == IFDIR) {
1156 				/*
1157 				 * If the sticky bit is set but the
1158 				 * execute bit is not set, we do a
1159 				 * synchronous write back and free
1160 				 * the page when done.  We set up swap
1161 				 * files to be handled this way to
1162 				 * prevent servers from keeping around
1163 				 * the client's swap pages too long.
1164 				 * XXX - there ought to be a better way.
1165 				 */
1166 				if (IS_SWAPVP(vp)) {
1167 					flags = SM_WRITE | SM_FREE |
1168 					    SM_DONTNEED;
1169 					iupdat_flag = 0;
1170 				} else {
1171 					flags = SM_WRITE;
1172 				}
1173 			} else if (n + on == MAXBSIZE || IS_SWAPVP(vp)) {
1174 				/*
1175 				 * Have written a whole block.
1176 				 * Start an asynchronous write and
1177 				 * mark the buffer to indicate that
1178 				 * it won't be needed again soon.
1179 				 */
1180 				flags = SM_WRITE | SM_ASYNC | SM_DONTNEED;
1181 			}
1182 			if (vpm_enable) {
1183 				/*
1184 				 * Flush pages.
1185 				 */
1186 				error = vpm_sync_pages(vp, off, n, flags);
1187 			} else {
1188 				error = segmap_release(segkmap, base, flags);
1189 			}
1190 			/*
1191 			 * If the operation failed and is synchronous,
1192 			 * then we need to unwind what uiomove() last
1193 			 * did so we can potentially return an error to
1194 			 * the caller.  If this write operation was
1195 			 * done in two pieces and the first succeeded,
1196 			 * then we won't return an error for the second
1197 			 * piece that failed.  However, we only want to
1198 			 * return a resid value that reflects what was
1199 			 * really done.
1200 			 *
1201 			 * Failures for non-synchronous operations can
1202 			 * be ignored since the page subsystem will
1203 			 * retry the operation until it succeeds or the
1204 			 * file system is unmounted.
1205 			 */
1206 			if (error) {
1207 				if ((ioflag & (FSYNC | FDSYNC)) ||
1208 				    type == IFDIR) {
1209 					uio->uio_resid = premove_resid;
1210 				} else {
1211 					error = 0;
1212 				}
1213 			}
1214 		}
1215 
1216 		/*
1217 		 * Re-acquire contents lock.
1218 		 * If it was dropped, reacquire reader vfs_dqrwlock as well.
1219 		 */
1220 		if (do_dqrwlock)
1221 			rw_enter(&ufsvfsp->vfs_dqrwlock, RW_READER);
1222 		rw_enter(&ip->i_contents, RW_WRITER);
1223 
1224 		/*
1225 		 * If the uiomove() failed or if a synchronous
1226 		 * page push failed, fix up i_size.
1227 		 */
1228 		if (error) {
1229 			if (i_size_changed) {
1230 				/*
1231 				 * The uiomove failed, and we
1232 				 * allocated blocks,so get rid
1233 				 * of them.
1234 				 */
1235 				(void) ufs_itrunc(ip, old_i_size, 0, cr);
1236 			}
1237 		} else {
1238 			/*
1239 			 * XXX - Can this be out of the loop?
1240 			 */
1241 			ip->i_flag |= IUPD | ICHG;
1242 			/*
1243 			 * Only do one increase of i_seq for multiple
1244 			 * pieces.  Because we drop locks, record
1245 			 * the fact that we changed the timestamp and
1246 			 * are deferring the increase in case another thread
1247 			 * pushes our timestamp update.
1248 			 */
1249 			i_seq_needed = 1;
1250 			ip->i_flag |= ISEQ;
1251 			if (i_size_changed)
1252 				ip->i_flag |= IATTCHG;
1253 			if ((ip->i_mode & (IEXEC | (IEXEC >> 3) |
1254 			    (IEXEC >> 6))) != 0 &&
1255 			    (ip->i_mode & (ISUID | ISGID)) != 0 &&
1256 			    secpolicy_vnode_setid_retain(cr,
1257 			    (ip->i_mode & ISUID) != 0 && ip->i_uid == 0) != 0) {
1258 				/*
1259 				 * Clear Set-UID & Set-GID bits on
1260 				 * successful write if not privileged
1261 				 * and at least one of the execute bits
1262 				 * is set.  If we always clear Set-GID,
1263 				 * mandatory file and record locking is
1264 				 * unuseable.
1265 				 */
1266 				ip->i_mode &= ~(ISUID | ISGID);
1267 			}
1268 		}
1269 		/*
1270 		 * In the case the FDSYNC flag is set and this is a
1271 		 * "rewrite" we won't log a delta.
1272 		 * The FSYNC flag overrides all cases.
1273 		 */
1274 		if (!ufs_check_rewrite(ip, uio, ioflag) || !(ioflag & FDSYNC)) {
1275 			TRANS_INODE(ufsvfsp, ip);
1276 		}
1277 	} while (error == 0 && uio->uio_resid > 0 && n != 0);
1278 
1279 out:
1280 	/*
1281 	 * Make sure i_seq is increased at least once per write
1282 	 */
1283 	if (i_seq_needed) {
1284 		ip->i_seq++;
1285 		ip->i_flag &= ~ISEQ;	/* no longer deferred */
1286 	}
1287 
1288 	/*
1289 	 * Inode is updated according to this table -
1290 	 *
1291 	 *   FSYNC	  FDSYNC(posix.4)
1292 	 *   --------------------------
1293 	 *   always@	  IATTCHG|IBDWRITE
1294 	 *
1295 	 * @ - 	If we are doing synchronous write the only time we should
1296 	 *	not be sync'ing the ip here is if we have the stickyhack
1297 	 *	activated, the file is marked with the sticky bit and
1298 	 *	no exec bit, the file length has not been changed and
1299 	 *	no new blocks have been allocated during this write.
1300 	 */
1301 
1302 	if ((ip->i_flag & ISYNC) != 0) {
1303 		/*
1304 		 * we have eliminated nosync
1305 		 */
1306 		if ((ip->i_flag & (IATTCHG|IBDWRITE)) ||
1307 		    ((ioflag & FSYNC) && iupdat_flag)) {
1308 			ufs_iupdat(ip, 1);
1309 		}
1310 	}
1311 
1312 	/*
1313 	 * If we've already done a partial-write, terminate
1314 	 * the write but return no error unless the error is ENOSPC
1315 	 * because the caller can detect this and free resources and
1316 	 * try again.
1317 	 */
1318 	if ((start_resid != uio->uio_resid) && (error != ENOSPC))
1319 		error = 0;
1320 
1321 	ip->i_flag &= ~(INOACC | ISYNC);
1322 	ITIMES_NOLOCK(ip);
1323 	return (error);
1324 }
1325 
1326 /*
1327  * rdip does the real work of read requests for ufs.
1328  */
1329 int
1330 rdip(struct inode *ip, struct uio *uio, int ioflag, cred_t *cr)
1331 {
1332 	u_offset_t off;
1333 	caddr_t base;
1334 	struct fs *fs;
1335 	struct ufsvfs *ufsvfsp;
1336 	struct vnode *vp;
1337 	long oresid = uio->uio_resid;
1338 	u_offset_t n, on, mapon;
1339 	int error = 0;
1340 	int doupdate = 1;
1341 	uint_t flags;
1342 	int dofree, directio_status;
1343 	krw_t rwtype;
1344 	o_mode_t type;
1345 
1346 	vp = ITOV(ip);
1347 
1348 	ASSERT(RW_LOCK_HELD(&ip->i_contents));
1349 
1350 	ufsvfsp = ip->i_ufsvfs;
1351 
1352 	if (ufsvfsp == NULL)
1353 		return (EIO);
1354 
1355 	fs = ufsvfsp->vfs_fs;
1356 
1357 	/* check for valid filetype */
1358 	type = ip->i_mode & IFMT;
1359 	if ((type != IFREG) && (type != IFDIR) && (type != IFATTRDIR) &&
1360 	    (type != IFLNK) && (type != IFSHAD)) {
1361 		return (EIO);
1362 	}
1363 
1364 	if (uio->uio_loffset > UFS_MAXOFFSET_T) {
1365 		error = 0;
1366 		goto out;
1367 	}
1368 	if (uio->uio_loffset < (offset_t)0) {
1369 		return (EINVAL);
1370 	}
1371 	if (uio->uio_resid == 0) {
1372 		return (0);
1373 	}
1374 
1375 	if (!ULOCKFS_IS_NOIACC(ITOUL(ip)) && (fs->fs_ronly == 0) &&
1376 	    (!ufsvfsp->vfs_noatime)) {
1377 		mutex_enter(&ip->i_tlock);
1378 		ip->i_flag |= IACC;
1379 		mutex_exit(&ip->i_tlock);
1380 	}
1381 	/*
1382 	 * Try to go direct
1383 	 */
1384 	if (ip->i_flag & IDIRECTIO || ufsvfsp->vfs_forcedirectio) {
1385 		error = ufs_directio_read(ip, uio, cr, &directio_status);
1386 		if (directio_status == DIRECTIO_SUCCESS)
1387 			goto out;
1388 	}
1389 
1390 	rwtype = (rw_write_held(&ip->i_contents)?RW_WRITER:RW_READER);
1391 
1392 	do {
1393 		offset_t diff;
1394 		u_offset_t uoff = uio->uio_loffset;
1395 		off = uoff & (offset_t)MAXBMASK;
1396 		mapon = (u_offset_t)(uoff & (offset_t)MAXBOFFSET);
1397 		on = (u_offset_t)blkoff(fs, uoff);
1398 		n = MIN((u_offset_t)fs->fs_bsize - on,
1399 		    (u_offset_t)uio->uio_resid);
1400 
1401 		diff = ip->i_size - uoff;
1402 
1403 		if (diff <= (offset_t)0) {
1404 			error = 0;
1405 			goto out;
1406 		}
1407 		if (diff < (offset_t)n)
1408 			n = (int)diff;
1409 
1410 		/*
1411 		 * We update smallfile2 and smallfile1 at most every second.
1412 		 */
1413 		if (lbolt >= smallfile_update) {
1414 			uint64_t percpufreeb;
1415 			if (smallfile1_d == 0) smallfile1_d = SMALLFILE1_D;
1416 			if (smallfile2_d == 0) smallfile2_d = SMALLFILE2_D;
1417 			percpufreeb = ptob((uint64_t)freemem) / ncpus_online;
1418 			smallfile1 = percpufreeb / smallfile1_d;
1419 			smallfile2 = percpufreeb / smallfile2_d;
1420 			smallfile1 = MAX(smallfile1, smallfile);
1421 			smallfile1 = MAX(smallfile1, smallfile64);
1422 			smallfile2 = MAX(smallfile1, smallfile2);
1423 			smallfile_update = lbolt + hz;
1424 		}
1425 
1426 		dofree = freebehind &&
1427 		    ip->i_nextr == (off & PAGEMASK) && off > smallfile1;
1428 
1429 		/*
1430 		 * At this point we can enter ufs_getpage() in one of two
1431 		 * ways:
1432 		 * 1) segmap_getmapflt() calls ufs_getpage() when the
1433 		 *    forcefault parameter is true (value of 1 is passed)
1434 		 * 2) uiomove() causes a page fault.
1435 		 *
1436 		 * We cannot hold onto an i_contents reader lock without
1437 		 * risking deadlock in ufs_getpage() so drop a reader lock.
1438 		 * The ufs_getpage() dolock logic already allows for a
1439 		 * thread holding i_contents as writer to work properly
1440 		 * so we keep a writer lock.
1441 		 */
1442 		if (rwtype == RW_READER)
1443 			rw_exit(&ip->i_contents);
1444 
1445 		if (vpm_enable) {
1446 			/*
1447 			 * Copy data.
1448 			 */
1449 			error = vpm_data_copy(vp, (off + mapon), (uint_t)n,
1450 			    uio, 1, NULL, 0, S_READ);
1451 		} else {
1452 			base = segmap_getmapflt(segkmap, vp, (off + mapon),
1453 			    (uint_t)n, 1, S_READ);
1454 			error = uiomove(base + mapon, (long)n, UIO_READ, uio);
1455 		}
1456 
1457 		flags = 0;
1458 		if (!error) {
1459 			/*
1460 			 * If  reading sequential  we won't need  this
1461 			 * buffer again  soon.  For  offsets in  range
1462 			 * [smallfile1,  smallfile2] release the pages
1463 			 * at   the  tail  of the   cache list, larger
1464 			 * offsets are released at the head.
1465 			 */
1466 			if (dofree) {
1467 				flags = SM_FREE | SM_ASYNC;
1468 				if ((cache_read_ahead == 0) &&
1469 				    (off > smallfile2))
1470 					flags |=  SM_DONTNEED;
1471 			}
1472 			/*
1473 			 * In POSIX SYNC (FSYNC and FDSYNC) read mode,
1474 			 * we want to make sure that the page which has
1475 			 * been read, is written on disk if it is dirty.
1476 			 * And corresponding indirect blocks should also
1477 			 * be flushed out.
1478 			 */
1479 			if ((ioflag & FRSYNC) && (ioflag & (FSYNC|FDSYNC))) {
1480 				flags &= ~SM_ASYNC;
1481 				flags |= SM_WRITE;
1482 			}
1483 			if (vpm_enable) {
1484 				error = vpm_sync_pages(vp, off, n, flags);
1485 			} else {
1486 				error = segmap_release(segkmap, base, flags);
1487 			}
1488 		} else {
1489 			if (vpm_enable) {
1490 				(void) vpm_sync_pages(vp, off, n, flags);
1491 			} else {
1492 				(void) segmap_release(segkmap, base, flags);
1493 			}
1494 		}
1495 
1496 		if (rwtype == RW_READER)
1497 			rw_enter(&ip->i_contents, rwtype);
1498 	} while (error == 0 && uio->uio_resid > 0 && n != 0);
1499 out:
1500 	/*
1501 	 * Inode is updated according to this table if FRSYNC is set.
1502 	 *
1503 	 *   FSYNC	  FDSYNC(posix.4)
1504 	 *   --------------------------
1505 	 *   always	  IATTCHG|IBDWRITE
1506 	 */
1507 	/*
1508 	 * The inode is not updated if we're logging and the inode is a
1509 	 * directory with FRSYNC, FSYNC and FDSYNC flags set.
1510 	 */
1511 	if (ioflag & FRSYNC) {
1512 		if (TRANS_ISTRANS(ufsvfsp) && ((ip->i_mode & IFMT) == IFDIR)) {
1513 			doupdate = 0;
1514 		}
1515 		if (doupdate) {
1516 			if ((ioflag & FSYNC) ||
1517 			    ((ioflag & FDSYNC) &&
1518 			    (ip->i_flag & (IATTCHG|IBDWRITE)))) {
1519 				ufs_iupdat(ip, 1);
1520 			}
1521 		}
1522 	}
1523 	/*
1524 	 * If we've already done a partial read, terminate
1525 	 * the read but return no error.
1526 	 */
1527 	if (oresid != uio->uio_resid)
1528 		error = 0;
1529 	ITIMES(ip);
1530 
1531 	return (error);
1532 }
1533 
1534 /* ARGSUSED */
1535 static int
1536 ufs_ioctl(
1537 	struct vnode	*vp,
1538 	int		cmd,
1539 	intptr_t	arg,
1540 	int		flag,
1541 	struct cred	*cr,
1542 	int		*rvalp,
1543 	caller_context_t *ct)
1544 {
1545 	struct lockfs	lockfs, lockfs_out;
1546 	struct ufsvfs	*ufsvfsp = VTOI(vp)->i_ufsvfs;
1547 	char		*comment, *original_comment;
1548 	struct fs	*fs;
1549 	struct ulockfs	*ulp;
1550 	offset_t	off;
1551 	extern int	maxphys;
1552 	int		error;
1553 	int		issync;
1554 	int		trans_size;
1555 
1556 
1557 	/*
1558 	 * forcibly unmounted
1559 	 */
1560 	if (ufsvfsp == NULL) {
1561 		return (EIO);
1562 	}
1563 
1564 	fs = ufsvfsp->vfs_fs;
1565 
1566 	if (cmd == Q_QUOTACTL) {
1567 		error = ufs_lockfs_begin(ufsvfsp, &ulp, ULOCKFS_QUOTA_MASK);
1568 		if (error)
1569 			return (error);
1570 
1571 		if (ulp) {
1572 			TRANS_BEGIN_ASYNC(ufsvfsp, TOP_QUOTA,
1573 			    TOP_SETQUOTA_SIZE(fs));
1574 		}
1575 
1576 		error = quotactl(vp, arg, flag, cr);
1577 
1578 		if (ulp) {
1579 			TRANS_END_ASYNC(ufsvfsp, TOP_QUOTA,
1580 			    TOP_SETQUOTA_SIZE(fs));
1581 			ufs_lockfs_end(ulp);
1582 		}
1583 		return (error);
1584 	}
1585 
1586 	switch (cmd) {
1587 		case _FIOLFS:
1588 			/*
1589 			 * file system locking
1590 			 */
1591 			if (secpolicy_fs_config(cr, ufsvfsp->vfs_vfs) != 0)
1592 				return (EPERM);
1593 
1594 			if ((flag & DATAMODEL_MASK) == DATAMODEL_NATIVE) {
1595 				if (copyin((caddr_t)arg, &lockfs,
1596 				    sizeof (struct lockfs)))
1597 					return (EFAULT);
1598 			}
1599 #ifdef _SYSCALL32_IMPL
1600 			else {
1601 				struct lockfs32	lockfs32;
1602 				/* Translate ILP32 lockfs to LP64 lockfs */
1603 				if (copyin((caddr_t)arg, &lockfs32,
1604 				    sizeof (struct lockfs32)))
1605 					return (EFAULT);
1606 				lockfs.lf_lock = (ulong_t)lockfs32.lf_lock;
1607 				lockfs.lf_flags = (ulong_t)lockfs32.lf_flags;
1608 				lockfs.lf_key = (ulong_t)lockfs32.lf_key;
1609 				lockfs.lf_comlen = (ulong_t)lockfs32.lf_comlen;
1610 				lockfs.lf_comment =
1611 				    (caddr_t)(uintptr_t)lockfs32.lf_comment;
1612 			}
1613 #endif /* _SYSCALL32_IMPL */
1614 
1615 			if (lockfs.lf_comlen) {
1616 				if (lockfs.lf_comlen > LOCKFS_MAXCOMMENTLEN)
1617 					return (ENAMETOOLONG);
1618 				comment =
1619 				    kmem_alloc(lockfs.lf_comlen, KM_SLEEP);
1620 				if (copyin(lockfs.lf_comment, comment,
1621 				    lockfs.lf_comlen)) {
1622 					kmem_free(comment, lockfs.lf_comlen);
1623 					return (EFAULT);
1624 				}
1625 				original_comment = lockfs.lf_comment;
1626 				lockfs.lf_comment = comment;
1627 			}
1628 			if ((error = ufs_fiolfs(vp, &lockfs, 0)) == 0) {
1629 				lockfs.lf_comment = original_comment;
1630 
1631 				if ((flag & DATAMODEL_MASK) ==
1632 				    DATAMODEL_NATIVE) {
1633 					(void) copyout(&lockfs, (caddr_t)arg,
1634 					    sizeof (struct lockfs));
1635 				}
1636 #ifdef _SYSCALL32_IMPL
1637 				else {
1638 					struct lockfs32	lockfs32;
1639 					/* Translate LP64 to ILP32 lockfs */
1640 					lockfs32.lf_lock =
1641 					    (uint32_t)lockfs.lf_lock;
1642 					lockfs32.lf_flags =
1643 					    (uint32_t)lockfs.lf_flags;
1644 					lockfs32.lf_key =
1645 					    (uint32_t)lockfs.lf_key;
1646 					lockfs32.lf_comlen =
1647 					    (uint32_t)lockfs.lf_comlen;
1648 					lockfs32.lf_comment =
1649 					    (uint32_t)(uintptr_t)
1650 					    lockfs.lf_comment;
1651 					(void) copyout(&lockfs32, (caddr_t)arg,
1652 					    sizeof (struct lockfs32));
1653 				}
1654 #endif /* _SYSCALL32_IMPL */
1655 
1656 			} else {
1657 				if (lockfs.lf_comlen)
1658 					kmem_free(comment, lockfs.lf_comlen);
1659 			}
1660 			return (error);
1661 
1662 		case _FIOLFSS:
1663 			/*
1664 			 * get file system locking status
1665 			 */
1666 
1667 			if ((flag & DATAMODEL_MASK) == DATAMODEL_NATIVE) {
1668 				if (copyin((caddr_t)arg, &lockfs,
1669 				    sizeof (struct lockfs)))
1670 					return (EFAULT);
1671 			}
1672 #ifdef _SYSCALL32_IMPL
1673 			else {
1674 				struct lockfs32	lockfs32;
1675 				/* Translate ILP32 lockfs to LP64 lockfs */
1676 				if (copyin((caddr_t)arg, &lockfs32,
1677 				    sizeof (struct lockfs32)))
1678 					return (EFAULT);
1679 				lockfs.lf_lock = (ulong_t)lockfs32.lf_lock;
1680 				lockfs.lf_flags = (ulong_t)lockfs32.lf_flags;
1681 				lockfs.lf_key = (ulong_t)lockfs32.lf_key;
1682 				lockfs.lf_comlen = (ulong_t)lockfs32.lf_comlen;
1683 				lockfs.lf_comment =
1684 				    (caddr_t)(uintptr_t)lockfs32.lf_comment;
1685 			}
1686 #endif /* _SYSCALL32_IMPL */
1687 
1688 			if (error =  ufs_fiolfss(vp, &lockfs_out))
1689 				return (error);
1690 			lockfs.lf_lock = lockfs_out.lf_lock;
1691 			lockfs.lf_key = lockfs_out.lf_key;
1692 			lockfs.lf_flags = lockfs_out.lf_flags;
1693 			lockfs.lf_comlen = MIN(lockfs.lf_comlen,
1694 			    lockfs_out.lf_comlen);
1695 
1696 			if ((flag & DATAMODEL_MASK) == DATAMODEL_NATIVE) {
1697 				if (copyout(&lockfs, (caddr_t)arg,
1698 				    sizeof (struct lockfs)))
1699 					return (EFAULT);
1700 			}
1701 #ifdef _SYSCALL32_IMPL
1702 			else {
1703 				/* Translate LP64 to ILP32 lockfs */
1704 				struct lockfs32	lockfs32;
1705 				lockfs32.lf_lock = (uint32_t)lockfs.lf_lock;
1706 				lockfs32.lf_flags = (uint32_t)lockfs.lf_flags;
1707 				lockfs32.lf_key = (uint32_t)lockfs.lf_key;
1708 				lockfs32.lf_comlen = (uint32_t)lockfs.lf_comlen;
1709 				lockfs32.lf_comment =
1710 				    (uint32_t)(uintptr_t)lockfs.lf_comment;
1711 				if (copyout(&lockfs32, (caddr_t)arg,
1712 				    sizeof (struct lockfs32)))
1713 					return (EFAULT);
1714 			}
1715 #endif /* _SYSCALL32_IMPL */
1716 
1717 			if (lockfs.lf_comlen &&
1718 			    lockfs.lf_comment && lockfs_out.lf_comment)
1719 				if (copyout(lockfs_out.lf_comment,
1720 				    lockfs.lf_comment, lockfs.lf_comlen))
1721 					return (EFAULT);
1722 			return (0);
1723 
1724 		case _FIOSATIME:
1725 			/*
1726 			 * set access time
1727 			 */
1728 
1729 			/*
1730 			 * if mounted w/o atime, return quietly.
1731 			 * I briefly thought about returning ENOSYS, but
1732 			 * figured that most apps would consider this fatal
1733 			 * but the idea is to make this as seamless as poss.
1734 			 */
1735 			if (ufsvfsp->vfs_noatime)
1736 				return (0);
1737 
1738 			error = ufs_lockfs_begin(ufsvfsp, &ulp,
1739 			    ULOCKFS_SETATTR_MASK);
1740 			if (error)
1741 				return (error);
1742 
1743 			if (ulp) {
1744 				trans_size = (int)TOP_SETATTR_SIZE(VTOI(vp));
1745 				TRANS_BEGIN_CSYNC(ufsvfsp, issync,
1746 				    TOP_SETATTR, trans_size);
1747 			}
1748 
1749 			error = ufs_fiosatime(vp, (struct timeval *)arg,
1750 			    flag, cr);
1751 
1752 			if (ulp) {
1753 				TRANS_END_CSYNC(ufsvfsp, error, issync,
1754 				    TOP_SETATTR, trans_size);
1755 				ufs_lockfs_end(ulp);
1756 			}
1757 			return (error);
1758 
1759 		case _FIOSDIO:
1760 			/*
1761 			 * set delayed-io
1762 			 */
1763 			return (ufs_fiosdio(vp, (uint_t *)arg, flag, cr));
1764 
1765 		case _FIOGDIO:
1766 			/*
1767 			 * get delayed-io
1768 			 */
1769 			return (ufs_fiogdio(vp, (uint_t *)arg, flag, cr));
1770 
1771 		case _FIOIO:
1772 			/*
1773 			 * inode open
1774 			 */
1775 			error = ufs_lockfs_begin(ufsvfsp, &ulp,
1776 			    ULOCKFS_VGET_MASK);
1777 			if (error)
1778 				return (error);
1779 
1780 			error = ufs_fioio(vp, (struct fioio *)arg, flag, cr);
1781 
1782 			if (ulp) {
1783 				ufs_lockfs_end(ulp);
1784 			}
1785 			return (error);
1786 
1787 		case _FIOFFS:
1788 			/*
1789 			 * file system flush (push w/invalidate)
1790 			 */
1791 			if ((caddr_t)arg != NULL)
1792 				return (EINVAL);
1793 			return (ufs_fioffs(vp, NULL, cr));
1794 
1795 		case _FIOISBUSY:
1796 			/*
1797 			 * Contract-private interface for Legato
1798 			 * Purge this vnode from the DNLC and decide
1799 			 * if this vnode is busy (*arg == 1) or not
1800 			 * (*arg == 0)
1801 			 */
1802 			if (secpolicy_fs_config(cr, ufsvfsp->vfs_vfs) != 0)
1803 				return (EPERM);
1804 			error = ufs_fioisbusy(vp, (int *)arg, cr);
1805 			return (error);
1806 
1807 		case _FIODIRECTIO:
1808 			return (ufs_fiodirectio(vp, (int)arg, cr));
1809 
1810 		case _FIOTUNE:
1811 			/*
1812 			 * Tune the file system (aka setting fs attributes)
1813 			 */
1814 			error = ufs_lockfs_begin(ufsvfsp, &ulp,
1815 			    ULOCKFS_SETATTR_MASK);
1816 			if (error)
1817 				return (error);
1818 
1819 			error = ufs_fiotune(vp, (struct fiotune *)arg, cr);
1820 
1821 			if (ulp)
1822 				ufs_lockfs_end(ulp);
1823 			return (error);
1824 
1825 		case _FIOLOGENABLE:
1826 			if (secpolicy_fs_config(cr, ufsvfsp->vfs_vfs) != 0)
1827 				return (EPERM);
1828 			return (ufs_fiologenable(vp, (void *)arg, cr, flag));
1829 
1830 		case _FIOLOGDISABLE:
1831 			if (secpolicy_fs_config(cr, ufsvfsp->vfs_vfs) != 0)
1832 				return (EPERM);
1833 			return (ufs_fiologdisable(vp, (void *)arg, cr, flag));
1834 
1835 		case _FIOISLOG:
1836 			return (ufs_fioislog(vp, (void *)arg, cr, flag));
1837 
1838 		case _FIOSNAPSHOTCREATE_MULTI:
1839 		{
1840 			struct fiosnapcreate_multi	fc, *fcp;
1841 			size_t	fcm_size;
1842 
1843 			if (copyin((void *)arg, &fc, sizeof (fc)))
1844 				return (EFAULT);
1845 			if (fc.backfilecount > MAX_BACKFILE_COUNT)
1846 				return (EINVAL);
1847 			fcm_size = sizeof (struct fiosnapcreate_multi) +
1848 			    (fc.backfilecount - 1) * sizeof (int);
1849 			fcp = (struct fiosnapcreate_multi *)
1850 			    kmem_alloc(fcm_size, KM_SLEEP);
1851 			if (copyin((void *)arg, fcp, fcm_size)) {
1852 				kmem_free(fcp, fcm_size);
1853 				return (EFAULT);
1854 			}
1855 			error = ufs_snap_create(vp, fcp, cr);
1856 			/*
1857 			 * Do copyout even if there is an error because
1858 			 * the details of error is stored in fcp.
1859 			 */
1860 			if (copyout(fcp, (void *)arg, fcm_size))
1861 				error = EFAULT;
1862 			kmem_free(fcp, fcm_size);
1863 			return (error);
1864 		}
1865 
1866 		case _FIOSNAPSHOTDELETE:
1867 		{
1868 			struct fiosnapdelete	fc;
1869 
1870 			if (copyin((void *)arg, &fc, sizeof (fc)))
1871 				return (EFAULT);
1872 			error = ufs_snap_delete(vp, &fc, cr);
1873 			if (!error && copyout(&fc, (void *)arg, sizeof (fc)))
1874 				error = EFAULT;
1875 			return (error);
1876 		}
1877 
1878 		case _FIOGETSUPERBLOCK:
1879 			if (copyout(fs, (void *)arg, SBSIZE))
1880 				return (EFAULT);
1881 			return (0);
1882 
1883 		case _FIOGETMAXPHYS:
1884 			if (copyout(&maxphys, (void *)arg, sizeof (maxphys)))
1885 				return (EFAULT);
1886 			return (0);
1887 
1888 		/*
1889 		 * The following 3 ioctls are for TSufs support
1890 		 * although could potentially be used elsewhere
1891 		 */
1892 		case _FIO_SET_LUFS_DEBUG:
1893 			if (secpolicy_fs_config(cr, ufsvfsp->vfs_vfs) != 0)
1894 				return (EPERM);
1895 			lufs_debug = (uint32_t)arg;
1896 			return (0);
1897 
1898 		case _FIO_SET_LUFS_ERROR:
1899 			if (secpolicy_fs_config(cr, ufsvfsp->vfs_vfs) != 0)
1900 				return (EPERM);
1901 			TRANS_SETERROR(ufsvfsp);
1902 			return (0);
1903 
1904 		case _FIO_GET_TOP_STATS:
1905 		{
1906 			fio_lufs_stats_t *ls;
1907 			ml_unit_t *ul = ufsvfsp->vfs_log;
1908 
1909 			ls = kmem_zalloc(sizeof (*ls), KM_SLEEP);
1910 			ls->ls_debug = ul->un_debug; /* return debug value */
1911 			/* Copy stucture if statistics are being kept */
1912 			if (ul->un_logmap->mtm_tops) {
1913 				ls->ls_topstats = *(ul->un_logmap->mtm_tops);
1914 			}
1915 			error = 0;
1916 			if (copyout(ls, (void *)arg, sizeof (*ls)))
1917 				error = EFAULT;
1918 			kmem_free(ls, sizeof (*ls));
1919 			return (error);
1920 		}
1921 
1922 		case _FIO_SEEK_DATA:
1923 		case _FIO_SEEK_HOLE:
1924 			if (ddi_copyin((void *)arg, &off, sizeof (off), flag))
1925 				return (EFAULT);
1926 			/* offset paramater is in/out */
1927 			error = ufs_fio_holey(vp, cmd, &off);
1928 			if (error)
1929 				return (error);
1930 			if (ddi_copyout(&off, (void *)arg, sizeof (off), flag))
1931 				return (EFAULT);
1932 			return (0);
1933 
1934 		case _FIO_COMPRESSED:
1935 		{
1936 			/*
1937 			 * This is a project private ufs ioctl() to mark
1938 			 * the inode as that belonging to a compressed
1939 			 * file. This is used to mark individual
1940 			 * files in a miniroot archive for SPARC boot.
1941 			 * The files compressed in this manner are
1942 			 * automatically decompressed by the dcfs filesystem
1943 			 * (via an interception in ufs_lookup - see decompvp())
1944 			 * which is layered on top of ufs on a system running
1945 			 * the new archive booted SPARC system. See
1946 			 * uts/common/fs/dcfs for details.
1947 			 * This ioctl only marks the file as compressed - the
1948 			 * actual compression is done by fiocompress (a
1949 			 * userland utility) which invokes this ioctl().
1950 			 */
1951 			struct inode *ip = VTOI(vp);
1952 
1953 			error = ufs_lockfs_begin(ufsvfsp, &ulp,
1954 			    ULOCKFS_SETATTR_MASK);
1955 			if (error)
1956 				return (error);
1957 
1958 			if (ulp) {
1959 				TRANS_BEGIN_ASYNC(ufsvfsp, TOP_IUPDAT,
1960 				    TOP_IUPDAT_SIZE(ip));
1961 			}
1962 
1963 			error = ufs_mark_compressed(vp);
1964 
1965 			if (ulp) {
1966 				TRANS_END_ASYNC(ufsvfsp, TOP_IUPDAT,
1967 				    TOP_IUPDAT_SIZE(ip));
1968 				ufs_lockfs_end(ulp);
1969 			}
1970 
1971 			return (error);
1972 
1973 		}
1974 
1975 		default:
1976 			return (ENOTTY);
1977 	}
1978 }
1979 
1980 
1981 /* ARGSUSED */
1982 static int
1983 ufs_getattr(struct vnode *vp, struct vattr *vap, int flags,
1984 	struct cred *cr, caller_context_t *ct)
1985 {
1986 	struct inode *ip = VTOI(vp);
1987 	struct ufsvfs *ufsvfsp;
1988 	int err;
1989 
1990 	if (vap->va_mask == AT_SIZE) {
1991 		/*
1992 		 * for performance, if only the size is requested don't bother
1993 		 * with anything else.
1994 		 */
1995 		UFS_GET_ISIZE(&vap->va_size, ip);
1996 		return (0);
1997 	}
1998 
1999 	/*
2000 	 * inlined lockfs checks
2001 	 */
2002 	ufsvfsp = ip->i_ufsvfs;
2003 	if ((ufsvfsp == NULL) || ULOCKFS_IS_HLOCK(&ufsvfsp->vfs_ulockfs)) {
2004 		err = EIO;
2005 		goto out;
2006 	}
2007 
2008 	rw_enter(&ip->i_contents, RW_READER);
2009 	/*
2010 	 * Return all the attributes.  This should be refined so
2011 	 * that it only returns what's asked for.
2012 	 */
2013 
2014 	/*
2015 	 * Copy from inode table.
2016 	 */
2017 	vap->va_type = vp->v_type;
2018 	vap->va_mode = ip->i_mode & MODEMASK;
2019 	/*
2020 	 * If there is an ACL and there is a mask entry, then do the
2021 	 * extra work that completes the equivalent of an acltomode(3)
2022 	 * call.  According to POSIX P1003.1e, the acl mask should be
2023 	 * returned in the group permissions field.
2024 	 *
2025 	 * - start with the original permission and mode bits (from above)
2026 	 * - clear the group owner bits
2027 	 * - add in the mask bits.
2028 	 */
2029 	if (ip->i_ufs_acl && ip->i_ufs_acl->aclass.acl_ismask) {
2030 		vap->va_mode &= ~((VREAD | VWRITE | VEXEC) >> 3);
2031 		vap->va_mode |=
2032 		    (ip->i_ufs_acl->aclass.acl_maskbits & PERMMASK) << 3;
2033 	}
2034 	vap->va_uid = ip->i_uid;
2035 	vap->va_gid = ip->i_gid;
2036 	vap->va_fsid = ip->i_dev;
2037 	vap->va_nodeid = (ino64_t)ip->i_number;
2038 	vap->va_nlink = ip->i_nlink;
2039 	vap->va_size = ip->i_size;
2040 	if (vp->v_type == VCHR || vp->v_type == VBLK)
2041 		vap->va_rdev = ip->i_rdev;
2042 	else
2043 		vap->va_rdev = 0;	/* not a b/c spec. */
2044 	mutex_enter(&ip->i_tlock);
2045 	ITIMES_NOLOCK(ip);	/* mark correct time in inode */
2046 	vap->va_seq = ip->i_seq;
2047 	vap->va_atime.tv_sec = (time_t)ip->i_atime.tv_sec;
2048 	vap->va_atime.tv_nsec = ip->i_atime.tv_usec*1000;
2049 	vap->va_mtime.tv_sec = (time_t)ip->i_mtime.tv_sec;
2050 	vap->va_mtime.tv_nsec = ip->i_mtime.tv_usec*1000;
2051 	vap->va_ctime.tv_sec = (time_t)ip->i_ctime.tv_sec;
2052 	vap->va_ctime.tv_nsec = ip->i_ctime.tv_usec*1000;
2053 	mutex_exit(&ip->i_tlock);
2054 
2055 	switch (ip->i_mode & IFMT) {
2056 
2057 	case IFBLK:
2058 		vap->va_blksize = MAXBSIZE;		/* was BLKDEV_IOSIZE */
2059 		break;
2060 
2061 	case IFCHR:
2062 		vap->va_blksize = MAXBSIZE;
2063 		break;
2064 
2065 	default:
2066 		vap->va_blksize = ip->i_fs->fs_bsize;
2067 		break;
2068 	}
2069 	vap->va_nblocks = (fsblkcnt64_t)ip->i_blocks;
2070 	rw_exit(&ip->i_contents);
2071 	err = 0;
2072 
2073 out:
2074 	return (err);
2075 }
2076 
2077 /*ARGSUSED4*/
2078 static int
2079 ufs_setattr(
2080 	struct vnode *vp,
2081 	struct vattr *vap,
2082 	int flags,
2083 	struct cred *cr,
2084 	caller_context_t *ct)
2085 {
2086 	struct inode *ip = VTOI(vp);
2087 	struct ufsvfs *ufsvfsp = ip->i_ufsvfs;
2088 	struct fs *fs;
2089 	struct ulockfs *ulp;
2090 	char *errmsg1;
2091 	char *errmsg2;
2092 	long blocks;
2093 	long int mask = vap->va_mask;
2094 	size_t len1, len2;
2095 	int issync;
2096 	int trans_size;
2097 	int dotrans;
2098 	int dorwlock;
2099 	int error;
2100 	int owner_change;
2101 	int dodqlock;
2102 	timestruc_t now;
2103 	vattr_t oldva;
2104 	int retry = 1;
2105 	int indeadlock;
2106 
2107 	/*
2108 	 * Cannot set these attributes.
2109 	 */
2110 	if ((mask & AT_NOSET) || (mask & AT_XVATTR))
2111 		return (EINVAL);
2112 
2113 	/*
2114 	 * check for forced unmount
2115 	 */
2116 	if (ufsvfsp == NULL)
2117 		return (EIO);
2118 
2119 	fs = ufsvfsp->vfs_fs;
2120 	if (fs->fs_ronly != 0)
2121 		return (EROFS);
2122 
2123 again:
2124 	errmsg1 = NULL;
2125 	errmsg2 = NULL;
2126 	dotrans = 0;
2127 	dorwlock = 0;
2128 	dodqlock = 0;
2129 
2130 	error = ufs_lockfs_begin(ufsvfsp, &ulp, ULOCKFS_SETATTR_MASK);
2131 	if (error)
2132 		goto out;
2133 
2134 	/*
2135 	 * Acquire i_rwlock before TRANS_BEGIN_CSYNC() if this is a file.
2136 	 * This follows the protocol for read()/write().
2137 	 */
2138 	if (vp->v_type != VDIR) {
2139 		/*
2140 		 * ufs_tryirwlock uses rw_tryenter and checks for SLOCK to
2141 		 * avoid i_rwlock, ufs_lockfs_begin deadlock. If deadlock
2142 		 * possible, retries the operation.
2143 		 */
2144 		ufs_tryirwlock(&ip->i_rwlock, RW_WRITER, retry_file);
2145 		if (indeadlock) {
2146 			if (ulp)
2147 				ufs_lockfs_end(ulp);
2148 			goto again;
2149 		}
2150 		dorwlock = 1;
2151 	}
2152 
2153 	/*
2154 	 * Truncate file.  Must have write permission and not be a directory.
2155 	 */
2156 	if (mask & AT_SIZE) {
2157 		rw_enter(&ip->i_contents, RW_WRITER);
2158 		if (vp->v_type == VDIR) {
2159 			error = EISDIR;
2160 			goto update_inode;
2161 		}
2162 		if (error = ufs_iaccess(ip, IWRITE, cr))
2163 			goto update_inode;
2164 
2165 		rw_exit(&ip->i_contents);
2166 		error = TRANS_ITRUNC(ip, vap->va_size, 0, cr);
2167 		if (error) {
2168 			rw_enter(&ip->i_contents, RW_WRITER);
2169 			goto update_inode;
2170 		}
2171 	}
2172 
2173 	if (ulp) {
2174 		trans_size = (int)TOP_SETATTR_SIZE(ip);
2175 		TRANS_BEGIN_CSYNC(ufsvfsp, issync, TOP_SETATTR, trans_size);
2176 		++dotrans;
2177 	}
2178 
2179 	/*
2180 	 * Acquire i_rwlock after TRANS_BEGIN_CSYNC() if this is a directory.
2181 	 * This follows the protocol established by
2182 	 * ufs_link/create/remove/rename/mkdir/rmdir/symlink.
2183 	 */
2184 	if (vp->v_type == VDIR) {
2185 		ufs_tryirwlock_trans(&ip->i_rwlock, RW_WRITER, TOP_SETATTR,
2186 		    retry_dir);
2187 		if (indeadlock)
2188 			goto again;
2189 		dorwlock = 1;
2190 	}
2191 
2192 	/*
2193 	 * Grab quota lock if we are changing the file's owner.
2194 	 */
2195 	if (mask & AT_UID) {
2196 		rw_enter(&ufsvfsp->vfs_dqrwlock, RW_READER);
2197 		dodqlock = 1;
2198 	}
2199 	rw_enter(&ip->i_contents, RW_WRITER);
2200 
2201 	oldva.va_mode = ip->i_mode;
2202 	oldva.va_uid = ip->i_uid;
2203 	oldva.va_gid = ip->i_gid;
2204 
2205 	vap->va_mask &= ~AT_SIZE;
2206 	/*
2207 	 * ufs_iaccess is "close enough"; that's because it doesn't
2208 	 * map the defines.
2209 	 */
2210 	error = secpolicy_vnode_setattr(cr, vp, vap, &oldva, flags,
2211 	    ufs_iaccess, ip);
2212 	if (error)
2213 		goto update_inode;
2214 
2215 	mask = vap->va_mask;
2216 
2217 	/*
2218 	 * Change file access modes.
2219 	 */
2220 	if (mask & AT_MODE) {
2221 		ip->i_mode = (ip->i_mode & IFMT) | (vap->va_mode & ~IFMT);
2222 		TRANS_INODE(ufsvfsp, ip);
2223 		ip->i_flag |= ICHG;
2224 		if (stickyhack) {
2225 			mutex_enter(&vp->v_lock);
2226 			if ((ip->i_mode & (ISVTX | IEXEC | IFDIR)) == ISVTX)
2227 				vp->v_flag |= VSWAPLIKE;
2228 			else
2229 				vp->v_flag &= ~VSWAPLIKE;
2230 			mutex_exit(&vp->v_lock);
2231 		}
2232 	}
2233 	if (mask & (AT_UID|AT_GID)) {
2234 		if (mask & AT_UID) {
2235 			/*
2236 			 * Don't change ownership of the quota inode.
2237 			 */
2238 			if (ufsvfsp->vfs_qinod == ip) {
2239 				ASSERT(ufsvfsp->vfs_qflags & MQ_ENABLED);
2240 				error = EINVAL;
2241 				goto update_inode;
2242 			}
2243 
2244 			/*
2245 			 * No real ownership change.
2246 			 */
2247 			if (ip->i_uid == vap->va_uid) {
2248 				blocks = 0;
2249 				owner_change = 0;
2250 			}
2251 			/*
2252 			 * Remove the blocks and the file, from the old user's
2253 			 * quota.
2254 			 */
2255 			else {
2256 				blocks = ip->i_blocks;
2257 				owner_change = 1;
2258 
2259 				(void) chkdq(ip, -blocks, /* force */ 1, cr,
2260 				    (char **)NULL, (size_t *)NULL);
2261 				(void) chkiq(ufsvfsp, /* change */ -1, ip,
2262 				    (uid_t)ip->i_uid, /* force */ 1, cr,
2263 				    (char **)NULL, (size_t *)NULL);
2264 				dqrele(ip->i_dquot);
2265 			}
2266 
2267 			ip->i_uid = vap->va_uid;
2268 
2269 			/*
2270 			 * There is a real ownership change.
2271 			 */
2272 			if (owner_change) {
2273 				/*
2274 				 * Add the blocks and the file to the new
2275 				 * user's quota.
2276 				 */
2277 				ip->i_dquot = getinoquota(ip);
2278 				(void) chkdq(ip, blocks, /* force */ 1, cr,
2279 				    &errmsg1, &len1);
2280 				(void) chkiq(ufsvfsp, /* change */ 1,
2281 				    (struct inode *)NULL, (uid_t)ip->i_uid,
2282 				    /* force */ 1, cr, &errmsg2, &len2);
2283 			}
2284 		}
2285 		if (mask & AT_GID) {
2286 			ip->i_gid = vap->va_gid;
2287 		}
2288 		TRANS_INODE(ufsvfsp, ip);
2289 		ip->i_flag |= ICHG;
2290 	}
2291 	/*
2292 	 * Change file access or modified times.
2293 	 */
2294 	if (mask & (AT_ATIME|AT_MTIME)) {
2295 		/* Check that the time value is within ufs range */
2296 		if (((mask & AT_ATIME) && TIMESPEC_OVERFLOW(&vap->va_atime)) ||
2297 		    ((mask & AT_MTIME) && TIMESPEC_OVERFLOW(&vap->va_mtime))) {
2298 			error = EOVERFLOW;
2299 			goto update_inode;
2300 		}
2301 
2302 		/*
2303 		 * if the "noaccess" mount option is set and only atime
2304 		 * update is requested, do nothing. No error is returned.
2305 		 */
2306 		if ((ufsvfsp->vfs_noatime) &&
2307 		    ((mask & (AT_ATIME|AT_MTIME)) == AT_ATIME))
2308 			goto skip_atime;
2309 
2310 		if (mask & AT_ATIME) {
2311 			ip->i_atime.tv_sec = vap->va_atime.tv_sec;
2312 			ip->i_atime.tv_usec = vap->va_atime.tv_nsec / 1000;
2313 			ip->i_flag &= ~IACC;
2314 		}
2315 		if (mask & AT_MTIME) {
2316 			ip->i_mtime.tv_sec = vap->va_mtime.tv_sec;
2317 			ip->i_mtime.tv_usec = vap->va_mtime.tv_nsec / 1000;
2318 			gethrestime(&now);
2319 			if (now.tv_sec > TIME32_MAX) {
2320 				/*
2321 				 * In 2038, ctime sticks forever..
2322 				 */
2323 				ip->i_ctime.tv_sec = TIME32_MAX;
2324 				ip->i_ctime.tv_usec = 0;
2325 			} else {
2326 				ip->i_ctime.tv_sec = now.tv_sec;
2327 				ip->i_ctime.tv_usec = now.tv_nsec / 1000;
2328 			}
2329 			ip->i_flag &= ~(IUPD|ICHG);
2330 			ip->i_flag |= IMODTIME;
2331 		}
2332 		TRANS_INODE(ufsvfsp, ip);
2333 		ip->i_flag |= IMOD;
2334 	}
2335 
2336 skip_atime:
2337 	/*
2338 	 * The presence of a shadow inode may indicate an ACL, but does
2339 	 * not imply an ACL.  Future FSD types should be handled here too
2340 	 * and check for the presence of the attribute-specific data
2341 	 * before referencing it.
2342 	 */
2343 	if (ip->i_shadow) {
2344 		/*
2345 		 * XXX if ufs_iupdat is changed to sandbagged write fix
2346 		 * ufs_acl_setattr to push ip to keep acls consistent
2347 		 *
2348 		 * Suppress out of inodes messages if we will retry.
2349 		 */
2350 		if (retry)
2351 			ip->i_flag |= IQUIET;
2352 		error = ufs_acl_setattr(ip, vap, cr);
2353 		ip->i_flag &= ~IQUIET;
2354 	}
2355 
2356 update_inode:
2357 	/*
2358 	 * Setattr always increases the sequence number
2359 	 */
2360 	ip->i_seq++;
2361 
2362 	/*
2363 	 * if nfsd and not logging; push synchronously
2364 	 */
2365 	if ((curthread->t_flag & T_DONTPEND) && !TRANS_ISTRANS(ufsvfsp)) {
2366 		ufs_iupdat(ip, 1);
2367 	} else {
2368 		ITIMES_NOLOCK(ip);
2369 	}
2370 
2371 	rw_exit(&ip->i_contents);
2372 	if (dodqlock) {
2373 		rw_exit(&ufsvfsp->vfs_dqrwlock);
2374 	}
2375 	if (dorwlock)
2376 		rw_exit(&ip->i_rwlock);
2377 
2378 	if (ulp) {
2379 		if (dotrans) {
2380 			int terr = 0;
2381 			TRANS_END_CSYNC(ufsvfsp, terr, issync, TOP_SETATTR,
2382 			    trans_size);
2383 			if (error == 0)
2384 				error = terr;
2385 		}
2386 		ufs_lockfs_end(ulp);
2387 	}
2388 out:
2389 	/*
2390 	 * If out of inodes or blocks, see if we can free something
2391 	 * up from the delete queue.
2392 	 */
2393 	if ((error == ENOSPC) && retry && TRANS_ISTRANS(ufsvfsp)) {
2394 		ufs_delete_drain_wait(ufsvfsp, 1);
2395 		retry = 0;
2396 		if (errmsg1 != NULL)
2397 			kmem_free(errmsg1, len1);
2398 		if (errmsg2 != NULL)
2399 			kmem_free(errmsg2, len2);
2400 		goto again;
2401 	}
2402 	if (errmsg1 != NULL) {
2403 		uprintf(errmsg1);
2404 		kmem_free(errmsg1, len1);
2405 	}
2406 	if (errmsg2 != NULL) {
2407 		uprintf(errmsg2);
2408 		kmem_free(errmsg2, len2);
2409 	}
2410 	return (error);
2411 }
2412 
2413 /*ARGSUSED*/
2414 static int
2415 ufs_access(struct vnode *vp, int mode, int flags, struct cred *cr,
2416 	caller_context_t *ct)
2417 {
2418 	struct inode *ip = VTOI(vp);
2419 	int error;
2420 
2421 	if (ip->i_ufsvfs == NULL)
2422 		return (EIO);
2423 
2424 	rw_enter(&ip->i_contents, RW_READER);
2425 
2426 	/*
2427 	 * The ufs_iaccess function wants to be called with
2428 	 * mode bits expressed as "ufs specific" bits.
2429 	 * I.e., VWRITE|VREAD|VEXEC do not make sense to
2430 	 * ufs_iaccess() but IWRITE|IREAD|IEXEC do.
2431 	 * But since they're the same we just pass the vnode mode
2432 	 * bit but just verify that assumption at compile time.
2433 	 */
2434 #if IWRITE != VWRITE || IREAD != VREAD || IEXEC != VEXEC
2435 #error "ufs_access needs to map Vmodes to Imodes"
2436 #endif
2437 	error = ufs_iaccess(ip, mode, cr);
2438 
2439 	rw_exit(&ip->i_contents);
2440 
2441 	return (error);
2442 }
2443 
2444 /* ARGSUSED */
2445 static int
2446 ufs_readlink(struct vnode *vp, struct uio *uiop, struct cred *cr,
2447 	caller_context_t *ct)
2448 {
2449 	struct inode *ip = VTOI(vp);
2450 	struct ufsvfs *ufsvfsp;
2451 	struct ulockfs *ulp;
2452 	int error;
2453 	int fastsymlink;
2454 
2455 	if (vp->v_type != VLNK) {
2456 		error = EINVAL;
2457 		goto nolockout;
2458 	}
2459 
2460 	/*
2461 	 * If the symbolic link is empty there is nothing to read.
2462 	 * Fast-track these empty symbolic links
2463 	 */
2464 	if (ip->i_size == 0) {
2465 		error = 0;
2466 		goto nolockout;
2467 	}
2468 
2469 	ufsvfsp = ip->i_ufsvfs;
2470 	error = ufs_lockfs_begin(ufsvfsp, &ulp, ULOCKFS_READLINK_MASK);
2471 	if (error)
2472 		goto nolockout;
2473 	/*
2474 	 * The ip->i_rwlock protects the data blocks used for FASTSYMLINK
2475 	 */
2476 again:
2477 	fastsymlink = 0;
2478 	if (ip->i_flag & IFASTSYMLNK) {
2479 		rw_enter(&ip->i_rwlock, RW_READER);
2480 		rw_enter(&ip->i_contents, RW_READER);
2481 		if (ip->i_flag & IFASTSYMLNK) {
2482 			if (!ULOCKFS_IS_NOIACC(ITOUL(ip)) &&
2483 			    (ip->i_fs->fs_ronly == 0) &&
2484 			    (!ufsvfsp->vfs_noatime)) {
2485 				mutex_enter(&ip->i_tlock);
2486 				ip->i_flag |= IACC;
2487 				mutex_exit(&ip->i_tlock);
2488 			}
2489 			error = uiomove((caddr_t)&ip->i_db[1],
2490 			    MIN(ip->i_size, uiop->uio_resid),
2491 			    UIO_READ, uiop);
2492 			ITIMES(ip);
2493 			++fastsymlink;
2494 		}
2495 		rw_exit(&ip->i_contents);
2496 		rw_exit(&ip->i_rwlock);
2497 	}
2498 	if (!fastsymlink) {
2499 		ssize_t size;	/* number of bytes read  */
2500 		caddr_t basep;	/* pointer to input data */
2501 		ino_t ino;
2502 		long  igen;
2503 		struct uio tuio;	/* temp uio struct */
2504 		struct uio *tuiop;
2505 		iovec_t tiov;		/* temp iovec struct */
2506 		char kbuf[FSL_SIZE];	/* buffer to hold fast symlink */
2507 		int tflag = 0;		/* flag to indicate temp vars used */
2508 
2509 		ino = ip->i_number;
2510 		igen = ip->i_gen;
2511 		size = uiop->uio_resid;
2512 		basep = uiop->uio_iov->iov_base;
2513 		tuiop = uiop;
2514 
2515 		rw_enter(&ip->i_rwlock, RW_WRITER);
2516 		rw_enter(&ip->i_contents, RW_WRITER);
2517 		if (ip->i_flag & IFASTSYMLNK) {
2518 			rw_exit(&ip->i_contents);
2519 			rw_exit(&ip->i_rwlock);
2520 			goto again;
2521 		}
2522 
2523 		/* can this be a fast symlink and is it a user buffer? */
2524 		if (ip->i_size <= FSL_SIZE &&
2525 		    (uiop->uio_segflg == UIO_USERSPACE ||
2526 		    uiop->uio_segflg == UIO_USERISPACE)) {
2527 
2528 			bzero(&tuio, sizeof (struct uio));
2529 			/*
2530 			 * setup a kernel buffer to read link into.  this
2531 			 * is to fix a race condition where the user buffer
2532 			 * got corrupted before copying it into the inode.
2533 			 */
2534 			size = ip->i_size;
2535 			tiov.iov_len = size;
2536 			tiov.iov_base = kbuf;
2537 			tuio.uio_iov = &tiov;
2538 			tuio.uio_iovcnt = 1;
2539 			tuio.uio_offset = uiop->uio_offset;
2540 			tuio.uio_segflg = UIO_SYSSPACE;
2541 			tuio.uio_fmode = uiop->uio_fmode;
2542 			tuio.uio_extflg = uiop->uio_extflg;
2543 			tuio.uio_limit = uiop->uio_limit;
2544 			tuio.uio_resid = size;
2545 
2546 			basep = tuio.uio_iov->iov_base;
2547 			tuiop = &tuio;
2548 			tflag = 1;
2549 		}
2550 
2551 		error = rdip(ip, tuiop, 0, cr);
2552 		if (!(error == 0 && ip->i_number == ino && ip->i_gen == igen)) {
2553 			rw_exit(&ip->i_contents);
2554 			rw_exit(&ip->i_rwlock);
2555 			goto out;
2556 		}
2557 
2558 		if (tflag == 0)
2559 			size -= uiop->uio_resid;
2560 
2561 		if ((tflag == 0 && ip->i_size <= FSL_SIZE &&
2562 		    ip->i_size == size) || (tflag == 1 &&
2563 		    tuio.uio_resid == 0)) {
2564 			error = kcopy(basep, &ip->i_db[1], ip->i_size);
2565 			if (error == 0) {
2566 				ip->i_flag |= IFASTSYMLNK;
2567 				/*
2568 				 * free page
2569 				 */
2570 				(void) VOP_PUTPAGE(ITOV(ip),
2571 				    (offset_t)0, PAGESIZE,
2572 				    (B_DONTNEED | B_FREE | B_FORCE | B_ASYNC),
2573 				    cr, ct);
2574 			} else {
2575 				int i;
2576 				/* error, clear garbage left behind */
2577 				for (i = 1; i < NDADDR; i++)
2578 					ip->i_db[i] = 0;
2579 				for (i = 0; i < NIADDR; i++)
2580 					ip->i_ib[i] = 0;
2581 			}
2582 		}
2583 		if (tflag == 1) {
2584 			/* now, copy it into the user buffer */
2585 			error = uiomove((caddr_t)kbuf,
2586 			    MIN(size, uiop->uio_resid),
2587 			    UIO_READ, uiop);
2588 		}
2589 		rw_exit(&ip->i_contents);
2590 		rw_exit(&ip->i_rwlock);
2591 	}
2592 out:
2593 	if (ulp) {
2594 		ufs_lockfs_end(ulp);
2595 	}
2596 nolockout:
2597 	return (error);
2598 }
2599 
2600 /* ARGSUSED */
2601 static int
2602 ufs_fsync(struct vnode *vp, int syncflag, struct cred *cr,
2603 	caller_context_t *ct)
2604 {
2605 	struct inode *ip = VTOI(vp);
2606 	struct ufsvfs *ufsvfsp = ip->i_ufsvfs;
2607 	struct ulockfs *ulp;
2608 	int error;
2609 
2610 	error = ufs_lockfs_begin(ufsvfsp, &ulp, ULOCKFS_FSYNC_MASK);
2611 	if (error)
2612 		return (error);
2613 
2614 	if (TRANS_ISTRANS(ufsvfsp)) {
2615 		/*
2616 		 * First push out any data pages
2617 		 */
2618 		if (vn_has_cached_data(vp) && !(syncflag & FNODSYNC) &&
2619 		    (vp->v_type != VCHR) && !(IS_SWAPVP(vp))) {
2620 			error = VOP_PUTPAGE(vp, (offset_t)0, (size_t)0,
2621 			    0, CRED(), ct);
2622 			if (error)
2623 				goto out;
2624 		}
2625 
2626 		/*
2627 		 * Delta any delayed inode times updates
2628 		 * and push inode to log.
2629 		 * All other inode deltas will have already been delta'd
2630 		 * and will be pushed during the commit.
2631 		 */
2632 		if (!(syncflag & FDSYNC) &&
2633 		    ((ip->i_flag & (IMOD|IMODACC)) == IMODACC)) {
2634 			if (ulp) {
2635 				TRANS_BEGIN_ASYNC(ufsvfsp, TOP_FSYNC,
2636 				    TOP_SYNCIP_SIZE);
2637 			}
2638 			rw_enter(&ip->i_contents, RW_READER);
2639 			mutex_enter(&ip->i_tlock);
2640 			ip->i_flag &= ~IMODTIME;
2641 			mutex_exit(&ip->i_tlock);
2642 			ufs_iupdat(ip, I_SYNC);
2643 			rw_exit(&ip->i_contents);
2644 			if (ulp) {
2645 				TRANS_END_ASYNC(ufsvfsp, TOP_FSYNC,
2646 				    TOP_SYNCIP_SIZE);
2647 			}
2648 		}
2649 
2650 		/*
2651 		 * Commit the Moby transaction
2652 		 *
2653 		 * Deltas have already been made so we just need to
2654 		 * commit them with a synchronous transaction.
2655 		 * TRANS_BEGIN_SYNC() will return an error
2656 		 * if there are no deltas to commit, for an
2657 		 * empty transaction.
2658 		 */
2659 		if (ulp) {
2660 			TRANS_BEGIN_SYNC(ufsvfsp, TOP_FSYNC, TOP_COMMIT_SIZE,
2661 			    error);
2662 			if (error) {
2663 				error = 0; /* commit wasn't needed */
2664 				goto out;
2665 			}
2666 			TRANS_END_SYNC(ufsvfsp, error, TOP_FSYNC,
2667 			    TOP_COMMIT_SIZE);
2668 		}
2669 	} else {	/* not logging */
2670 		if (!(IS_SWAPVP(vp)))
2671 			if (syncflag & FNODSYNC) {
2672 				/* Just update the inode only */
2673 				TRANS_IUPDAT(ip, 1);
2674 				error = 0;
2675 			} else if (syncflag & FDSYNC)
2676 				/* Do data-synchronous writes */
2677 				error = TRANS_SYNCIP(ip, 0, I_DSYNC, TOP_FSYNC);
2678 			else
2679 				/* Do synchronous writes */
2680 				error = TRANS_SYNCIP(ip, 0, I_SYNC, TOP_FSYNC);
2681 
2682 		rw_enter(&ip->i_contents, RW_WRITER);
2683 		if (!error)
2684 			error = ufs_sync_indir(ip);
2685 		rw_exit(&ip->i_contents);
2686 	}
2687 out:
2688 	if (ulp) {
2689 		ufs_lockfs_end(ulp);
2690 	}
2691 	return (error);
2692 }
2693 
2694 /*ARGSUSED*/
2695 static void
2696 ufs_inactive(struct vnode *vp, struct cred *cr, caller_context_t *ct)
2697 {
2698 	ufs_iinactive(VTOI(vp));
2699 }
2700 
2701 /*
2702  * Unix file system operations having to do with directory manipulation.
2703  */
2704 int ufs_lookup_idle_count = 2;	/* Number of inodes to idle each time */
2705 /* ARGSUSED */
2706 static int
2707 ufs_lookup(struct vnode *dvp, char *nm, struct vnode **vpp,
2708 	struct pathname *pnp, int flags, struct vnode *rdir, struct cred *cr,
2709 	caller_context_t *ct, int *direntflags, pathname_t *realpnp)
2710 {
2711 	struct inode *ip;
2712 	struct inode *sip;
2713 	struct inode *xip;
2714 	struct ufsvfs *ufsvfsp;
2715 	struct ulockfs *ulp;
2716 	struct vnode *vp;
2717 	int error;
2718 
2719 	/*
2720 	 * Check flags for type of lookup (regular file or attribute file)
2721 	 */
2722 
2723 	ip = VTOI(dvp);
2724 
2725 	if (flags & LOOKUP_XATTR) {
2726 
2727 		/*
2728 		 * If not mounted with XATTR support then return EINVAL
2729 		 */
2730 
2731 		if (!(ip->i_ufsvfs->vfs_vfs->vfs_flag & VFS_XATTR))
2732 			return (EINVAL);
2733 		/*
2734 		 * We don't allow recursive attributes...
2735 		 * Maybe someday we will.
2736 		 */
2737 		if ((ip->i_cflags & IXATTR)) {
2738 			return (EINVAL);
2739 		}
2740 
2741 		if ((vp = dnlc_lookup(dvp, XATTR_DIR_NAME)) == NULL) {
2742 			error = ufs_xattr_getattrdir(dvp, &sip, flags, cr);
2743 			if (error) {
2744 				*vpp = NULL;
2745 				goto out;
2746 			}
2747 
2748 			vp = ITOV(sip);
2749 			dnlc_update(dvp, XATTR_DIR_NAME, vp);
2750 		}
2751 
2752 		/*
2753 		 * Check accessibility of directory.
2754 		 */
2755 		if (vp == DNLC_NO_VNODE) {
2756 			VN_RELE(vp);
2757 			error = ENOENT;
2758 			goto out;
2759 		}
2760 		if ((error = ufs_iaccess(VTOI(vp), IEXEC, cr)) != 0) {
2761 			VN_RELE(vp);
2762 			goto out;
2763 		}
2764 
2765 		*vpp = vp;
2766 		return (0);
2767 	}
2768 
2769 	/*
2770 	 * Check for a null component, which we should treat as
2771 	 * looking at dvp from within it's parent, so we don't
2772 	 * need a call to ufs_iaccess(), as it has already been
2773 	 * done.
2774 	 */
2775 	if (nm[0] == 0) {
2776 		VN_HOLD(dvp);
2777 		error = 0;
2778 		*vpp = dvp;
2779 		goto out;
2780 	}
2781 
2782 	/*
2783 	 * Check for "." ie itself. this is a quick check and
2784 	 * avoids adding "." into the dnlc (which have been seen
2785 	 * to occupy >10% of the cache).
2786 	 */
2787 	if ((nm[0] == '.') && (nm[1] == 0)) {
2788 		/*
2789 		 * Don't return without checking accessibility
2790 		 * of the directory. We only need the lock if
2791 		 * we are going to return it.
2792 		 */
2793 		if ((error = ufs_iaccess(ip, IEXEC, cr)) == 0) {
2794 			VN_HOLD(dvp);
2795 			*vpp = dvp;
2796 		}
2797 		goto out;
2798 	}
2799 
2800 	/*
2801 	 * Fast path: Check the directory name lookup cache.
2802 	 */
2803 	if (vp = dnlc_lookup(dvp, nm)) {
2804 		/*
2805 		 * Check accessibility of directory.
2806 		 */
2807 		if ((error = ufs_iaccess(ip, IEXEC, cr)) != 0) {
2808 			VN_RELE(vp);
2809 			goto out;
2810 		}
2811 		if (vp == DNLC_NO_VNODE) {
2812 			VN_RELE(vp);
2813 			error = ENOENT;
2814 			goto out;
2815 		}
2816 		xip = VTOI(vp);
2817 		ulp = NULL;
2818 		goto fastpath;
2819 	}
2820 
2821 	/*
2822 	 * Keep the idle queue from getting too long by
2823 	 * idling two inodes before attempting to allocate another.
2824 	 *    This operation must be performed before entering
2825 	 *    lockfs or a transaction.
2826 	 */
2827 	if (ufs_idle_q.uq_ne > ufs_idle_q.uq_hiwat)
2828 		if ((curthread->t_flag & T_DONTBLOCK) == 0) {
2829 			ins.in_lidles.value.ul += ufs_lookup_idle_count;
2830 			ufs_idle_some(ufs_lookup_idle_count);
2831 		}
2832 
2833 retry_lookup:
2834 	ufsvfsp = ip->i_ufsvfs;
2835 	error = ufs_lockfs_begin(ufsvfsp, &ulp, ULOCKFS_LOOKUP_MASK);
2836 	if (error)
2837 		goto out;
2838 
2839 	error = ufs_dirlook(ip, nm, &xip, cr, 1);
2840 
2841 fastpath:
2842 	if (error == 0) {
2843 		ip = xip;
2844 		*vpp = ITOV(ip);
2845 
2846 		/*
2847 		 * If vnode is a device return special vnode instead.
2848 		 */
2849 		if (IS_DEVVP(*vpp)) {
2850 			struct vnode *newvp;
2851 
2852 			newvp = specvp(*vpp, (*vpp)->v_rdev, (*vpp)->v_type,
2853 			    cr);
2854 			VN_RELE(*vpp);
2855 			if (newvp == NULL)
2856 				error = ENOSYS;
2857 			else
2858 				*vpp = newvp;
2859 		} else if (ip->i_cflags & ICOMPRESS) {
2860 			struct vnode *newvp;
2861 
2862 			/*
2863 			 * Compressed file, substitute dcfs vnode
2864 			 */
2865 			newvp = decompvp(*vpp, cr, ct);
2866 			VN_RELE(*vpp);
2867 			if (newvp == NULL)
2868 				error = ENOSYS;
2869 			else
2870 				*vpp = newvp;
2871 		}
2872 	}
2873 	if (ulp) {
2874 		ufs_lockfs_end(ulp);
2875 	}
2876 
2877 	if (error == EAGAIN)
2878 		goto retry_lookup;
2879 
2880 out:
2881 	return (error);
2882 }
2883 
2884 /*ARGSUSED*/
2885 static int
2886 ufs_create(struct vnode *dvp, char *name, struct vattr *vap, enum vcexcl excl,
2887 	int mode, struct vnode **vpp, struct cred *cr, int flag,
2888 	caller_context_t *ct, vsecattr_t *vsecp)
2889 {
2890 	struct inode *ip;
2891 	struct inode *xip;
2892 	struct inode *dip;
2893 	struct vnode *xvp;
2894 	struct ufsvfs *ufsvfsp;
2895 	struct ulockfs *ulp;
2896 	int error;
2897 	int issync;
2898 	int truncflag;
2899 	int trans_size;
2900 	int noentry;
2901 	int defer_dip_seq_update = 0;	/* need to defer update of dip->i_seq */
2902 	int retry = 1;
2903 	int indeadlock;
2904 
2905 again:
2906 	ip = VTOI(dvp);
2907 	ufsvfsp = ip->i_ufsvfs;
2908 	truncflag = 0;
2909 
2910 	error = ufs_lockfs_begin(ufsvfsp, &ulp, ULOCKFS_CREATE_MASK);
2911 	if (error)
2912 		goto out;
2913 
2914 	if (ulp) {
2915 		trans_size = (int)TOP_CREATE_SIZE(ip);
2916 		TRANS_BEGIN_CSYNC(ufsvfsp, issync, TOP_CREATE, trans_size);
2917 	}
2918 
2919 	if ((vap->va_mode & VSVTX) && secpolicy_vnode_stky_modify(cr) != 0)
2920 		vap->va_mode &= ~VSVTX;
2921 
2922 	if (*name == '\0') {
2923 		/*
2924 		 * Null component name refers to the directory itself.
2925 		 */
2926 		VN_HOLD(dvp);
2927 		/*
2928 		 * Even though this is an error case, we need to grab the
2929 		 * quota lock since the error handling code below is common.
2930 		 */
2931 		rw_enter(&ufsvfsp->vfs_dqrwlock, RW_READER);
2932 		rw_enter(&ip->i_contents, RW_WRITER);
2933 		error = EEXIST;
2934 	} else {
2935 		xip = NULL;
2936 		noentry = 0;
2937 		/*
2938 		 * ufs_tryirwlock_trans uses rw_tryenter and checks for SLOCK
2939 		 * to avoid i_rwlock, ufs_lockfs_begin deadlock. If deadlock
2940 		 * possible, retries the operation.
2941 		 */
2942 		ufs_tryirwlock_trans(&ip->i_rwlock, RW_WRITER, TOP_CREATE,
2943 		    retry_dir);
2944 		if (indeadlock)
2945 			goto again;
2946 
2947 		xvp = dnlc_lookup(dvp, name);
2948 		if (xvp == DNLC_NO_VNODE) {
2949 			noentry = 1;
2950 			VN_RELE(xvp);
2951 			xvp = NULL;
2952 		}
2953 		if (xvp) {
2954 			rw_exit(&ip->i_rwlock);
2955 			if (error = ufs_iaccess(ip, IEXEC, cr)) {
2956 				VN_RELE(xvp);
2957 			} else {
2958 				error = EEXIST;
2959 				xip = VTOI(xvp);
2960 			}
2961 		} else {
2962 			/*
2963 			 * Suppress file system full message if we will retry
2964 			 */
2965 			error = ufs_direnter_cm(ip, name, DE_CREATE,
2966 			    vap, &xip, cr, (noentry | (retry ? IQUIET : 0)));
2967 			if (error == EAGAIN) {
2968 				if (ulp) {
2969 					TRANS_END_CSYNC(ufsvfsp, error, issync,
2970 					    TOP_CREATE, trans_size);
2971 					ufs_lockfs_end(ulp);
2972 				}
2973 				goto again;
2974 			}
2975 			rw_exit(&ip->i_rwlock);
2976 		}
2977 		ip = xip;
2978 		if (ip != NULL) {
2979 			rw_enter(&ufsvfsp->vfs_dqrwlock, RW_READER);
2980 			rw_enter(&ip->i_contents, RW_WRITER);
2981 		}
2982 	}
2983 
2984 	/*
2985 	 * If the file already exists and this is a non-exclusive create,
2986 	 * check permissions and allow access for non-directories.
2987 	 * Read-only create of an existing directory is also allowed.
2988 	 * We fail an exclusive create of anything which already exists.
2989 	 */
2990 	if (error == EEXIST) {
2991 		dip = VTOI(dvp);
2992 		if (excl == NONEXCL) {
2993 			if ((((ip->i_mode & IFMT) == IFDIR) ||
2994 			    ((ip->i_mode & IFMT) == IFATTRDIR)) &&
2995 			    (mode & IWRITE))
2996 				error = EISDIR;
2997 			else if (mode)
2998 				error = ufs_iaccess(ip, mode, cr);
2999 			else
3000 				error = 0;
3001 		}
3002 		if (error) {
3003 			rw_exit(&ip->i_contents);
3004 			rw_exit(&ufsvfsp->vfs_dqrwlock);
3005 			VN_RELE(ITOV(ip));
3006 			goto unlock;
3007 		}
3008 		/*
3009 		 * If the error EEXIST was set, then i_seq can not
3010 		 * have been updated. The sequence number interface
3011 		 * is defined such that a non-error VOP_CREATE must
3012 		 * increase the dir va_seq it by at least one. If we
3013 		 * have cleared the error, increase i_seq. Note that
3014 		 * we are increasing the dir i_seq and in rare cases
3015 		 * ip may actually be from the dvp, so we already have
3016 		 * the locks and it will not be subject to truncation.
3017 		 * In case we have to update i_seq of the parent
3018 		 * directory dip, we have to defer it till we have
3019 		 * released our locks on ip due to lock ordering requirements.
3020 		 */
3021 		if (ip != dip)
3022 			defer_dip_seq_update = 1;
3023 		else
3024 			ip->i_seq++;
3025 
3026 		if (((ip->i_mode & IFMT) == IFREG) &&
3027 		    (vap->va_mask & AT_SIZE) && vap->va_size == 0) {
3028 			/*
3029 			 * Truncate regular files, if requested by caller.
3030 			 * Grab i_rwlock to make sure no one else is
3031 			 * currently writing to the file (we promised
3032 			 * bmap we would do this).
3033 			 * Must get the locks in the correct order.
3034 			 */
3035 			if (ip->i_size == 0) {
3036 				ip->i_flag |= ICHG | IUPD;
3037 				ip->i_seq++;
3038 				TRANS_INODE(ufsvfsp, ip);
3039 			} else {
3040 				/*
3041 				 * Large Files: Why this check here?
3042 				 * Though we do it in vn_create() we really
3043 				 * want to guarantee that we do not destroy
3044 				 * Large file data by atomically checking
3045 				 * the size while holding the contents
3046 				 * lock.
3047 				 */
3048 				if (flag && !(flag & FOFFMAX) &&
3049 				    ((ip->i_mode & IFMT) == IFREG) &&
3050 				    (ip->i_size > (offset_t)MAXOFF32_T)) {
3051 					rw_exit(&ip->i_contents);
3052 					rw_exit(&ufsvfsp->vfs_dqrwlock);
3053 					error = EOVERFLOW;
3054 					goto unlock;
3055 				}
3056 				if (TRANS_ISTRANS(ufsvfsp))
3057 					truncflag++;
3058 				else {
3059 					rw_exit(&ip->i_contents);
3060 					rw_exit(&ufsvfsp->vfs_dqrwlock);
3061 					ufs_tryirwlock_trans(&ip->i_rwlock,
3062 					    RW_WRITER, TOP_CREATE,
3063 					    retry_file);
3064 					if (indeadlock) {
3065 						VN_RELE(ITOV(ip));
3066 						goto again;
3067 					}
3068 					rw_enter(&ufsvfsp->vfs_dqrwlock,
3069 					    RW_READER);
3070 					rw_enter(&ip->i_contents, RW_WRITER);
3071 					(void) ufs_itrunc(ip, (u_offset_t)0, 0,
3072 					    cr);
3073 					rw_exit(&ip->i_rwlock);
3074 				}
3075 
3076 			}
3077 			if (error == 0) {
3078 				vnevent_create(ITOV(ip), ct);
3079 			}
3080 		}
3081 	}
3082 
3083 	if (error) {
3084 		if (ip != NULL) {
3085 			rw_exit(&ufsvfsp->vfs_dqrwlock);
3086 			rw_exit(&ip->i_contents);
3087 		}
3088 		goto unlock;
3089 	}
3090 
3091 	*vpp = ITOV(ip);
3092 	ITIMES(ip);
3093 	rw_exit(&ip->i_contents);
3094 	rw_exit(&ufsvfsp->vfs_dqrwlock);
3095 
3096 	/*
3097 	 * If vnode is a device return special vnode instead.
3098 	 */
3099 	if (!error && IS_DEVVP(*vpp)) {
3100 		struct vnode *newvp;
3101 
3102 		newvp = specvp(*vpp, (*vpp)->v_rdev, (*vpp)->v_type, cr);
3103 		VN_RELE(*vpp);
3104 		if (newvp == NULL) {
3105 			error = ENOSYS;
3106 			goto unlock;
3107 		}
3108 		truncflag = 0;
3109 		*vpp = newvp;
3110 	}
3111 unlock:
3112 
3113 	/*
3114 	 * Do the deferred update of the parent directory's sequence
3115 	 * number now.
3116 	 */
3117 	if (defer_dip_seq_update == 1) {
3118 		rw_enter(&dip->i_contents, RW_READER);
3119 		mutex_enter(&dip->i_tlock);
3120 		dip->i_seq++;
3121 		mutex_exit(&dip->i_tlock);
3122 		rw_exit(&dip->i_contents);
3123 	}
3124 
3125 	if (ulp) {
3126 		int terr = 0;
3127 
3128 		TRANS_END_CSYNC(ufsvfsp, terr, issync, TOP_CREATE,
3129 		    trans_size);
3130 
3131 		/*
3132 		 * If we haven't had a more interesting failure
3133 		 * already, then anything that might've happened
3134 		 * here should be reported.
3135 		 */
3136 		if (error == 0)
3137 			error = terr;
3138 	}
3139 
3140 	if (!error && truncflag) {
3141 		ufs_tryirwlock(&ip->i_rwlock, RW_WRITER, retry_trunc);
3142 		if (indeadlock) {
3143 			if (ulp)
3144 				ufs_lockfs_end(ulp);
3145 			VN_RELE(ITOV(ip));
3146 			goto again;
3147 		}
3148 		(void) TRANS_ITRUNC(ip, (u_offset_t)0, 0, cr);
3149 		rw_exit(&ip->i_rwlock);
3150 	}
3151 
3152 	if (ulp)
3153 		ufs_lockfs_end(ulp);
3154 
3155 	/*
3156 	 * If no inodes available, try to free one up out of the
3157 	 * pending delete queue.
3158 	 */
3159 	if ((error == ENOSPC) && retry && TRANS_ISTRANS(ufsvfsp)) {
3160 		ufs_delete_drain_wait(ufsvfsp, 1);
3161 		retry = 0;
3162 		goto again;
3163 	}
3164 
3165 out:
3166 	return (error);
3167 }
3168 
3169 extern int ufs_idle_max;
3170 /*ARGSUSED*/
3171 static int
3172 ufs_remove(struct vnode *vp, char *nm, struct cred *cr,
3173 	caller_context_t *ct, int flags)
3174 {
3175 	struct inode *ip = VTOI(vp);
3176 	struct ufsvfs *ufsvfsp	= ip->i_ufsvfs;
3177 	struct ulockfs *ulp;
3178 	vnode_t *rmvp = NULL;	/* Vnode corresponding to name being removed */
3179 	int indeadlock;
3180 	int error;
3181 	int issync;
3182 	int trans_size;
3183 
3184 	/*
3185 	 * don't let the delete queue get too long
3186 	 */
3187 	if (ufsvfsp == NULL) {
3188 		error = EIO;
3189 		goto out;
3190 	}
3191 	if (ufsvfsp->vfs_delete.uq_ne > ufs_idle_max)
3192 		ufs_delete_drain(vp->v_vfsp, 1, 1);
3193 
3194 retry_remove:
3195 	error = ufs_lockfs_begin(ufsvfsp, &ulp, ULOCKFS_REMOVE_MASK);
3196 	if (error)
3197 		goto out;
3198 
3199 	if (ulp)
3200 		TRANS_BEGIN_CSYNC(ufsvfsp, issync, TOP_REMOVE,
3201 		    trans_size = (int)TOP_REMOVE_SIZE(VTOI(vp)));
3202 
3203 	/*
3204 	 * ufs_tryirwlock_trans uses rw_tryenter and checks for SLOCK
3205 	 * to avoid i_rwlock, ufs_lockfs_begin deadlock. If deadlock
3206 	 * possible, retries the operation.
3207 	 */
3208 	ufs_tryirwlock_trans(&ip->i_rwlock, RW_WRITER, TOP_REMOVE, retry);
3209 	if (indeadlock)
3210 		goto retry_remove;
3211 	error = ufs_dirremove(ip, nm, (struct inode *)0, (struct vnode *)0,
3212 	    DR_REMOVE, cr, &rmvp);
3213 	rw_exit(&ip->i_rwlock);
3214 
3215 	if (ulp) {
3216 		TRANS_END_CSYNC(ufsvfsp, error, issync, TOP_REMOVE, trans_size);
3217 		ufs_lockfs_end(ulp);
3218 	}
3219 
3220 	/*
3221 	 * This must be called after the remove transaction is closed.
3222 	 */
3223 	if (rmvp != NULL) {
3224 		/* Only send the event if there were no errors */
3225 		if (error == 0)
3226 			vnevent_remove(rmvp, vp, nm, ct);
3227 		VN_RELE(rmvp);
3228 	}
3229 out:
3230 	return (error);
3231 }
3232 
3233 /*
3234  * Link a file or a directory.  Only privileged processes are allowed to
3235  * make links to directories.
3236  */
3237 /*ARGSUSED*/
3238 static int
3239 ufs_link(struct vnode *tdvp, struct vnode *svp, char *tnm, struct cred *cr,
3240 	caller_context_t *ct, int flags)
3241 {
3242 	struct inode *sip;
3243 	struct inode *tdp = VTOI(tdvp);
3244 	struct ufsvfs *ufsvfsp = tdp->i_ufsvfs;
3245 	struct ulockfs *ulp;
3246 	struct vnode *realvp;
3247 	int error;
3248 	int issync;
3249 	int trans_size;
3250 	int isdev;
3251 	int indeadlock;
3252 
3253 retry_link:
3254 	error = ufs_lockfs_begin(ufsvfsp, &ulp, ULOCKFS_LINK_MASK);
3255 	if (error)
3256 		goto out;
3257 
3258 	if (ulp)
3259 		TRANS_BEGIN_CSYNC(ufsvfsp, issync, TOP_LINK,
3260 		    trans_size = (int)TOP_LINK_SIZE(VTOI(tdvp)));
3261 
3262 	if (VOP_REALVP(svp, &realvp, ct) == 0)
3263 		svp = realvp;
3264 
3265 	/*
3266 	 * Make sure link for extended attributes is valid
3267 	 * We only support hard linking of attr in ATTRDIR to ATTRDIR
3268 	 *
3269 	 * Make certain we don't attempt to look at a device node as
3270 	 * a ufs inode.
3271 	 */
3272 
3273 	isdev = IS_DEVVP(svp);
3274 	if (((isdev == 0) && ((VTOI(svp)->i_cflags & IXATTR) == 0) &&
3275 	    ((tdp->i_mode & IFMT) == IFATTRDIR)) ||
3276 	    ((isdev == 0) && (VTOI(svp)->i_cflags & IXATTR) &&
3277 	    ((tdp->i_mode & IFMT) == IFDIR))) {
3278 		error = EINVAL;
3279 		goto unlock;
3280 	}
3281 
3282 	sip = VTOI(svp);
3283 	if ((svp->v_type == VDIR &&
3284 	    secpolicy_fs_linkdir(cr, ufsvfsp->vfs_vfs) != 0) ||
3285 	    (sip->i_uid != crgetuid(cr) && secpolicy_basic_link(cr) != 0)) {
3286 		error = EPERM;
3287 		goto unlock;
3288 	}
3289 
3290 	/*
3291 	 * ufs_tryirwlock_trans uses rw_tryenter and checks for SLOCK
3292 	 * to avoid i_rwlock, ufs_lockfs_begin deadlock. If deadlock
3293 	 * possible, retries the operation.
3294 	 */
3295 	ufs_tryirwlock_trans(&tdp->i_rwlock, RW_WRITER, TOP_LINK, retry);
3296 	if (indeadlock)
3297 		goto retry_link;
3298 	error = ufs_direnter_lr(tdp, tnm, DE_LINK, (struct inode *)0,
3299 	    sip, cr, NULL);
3300 	rw_exit(&tdp->i_rwlock);
3301 
3302 unlock:
3303 	if (ulp) {
3304 		TRANS_END_CSYNC(ufsvfsp, error, issync, TOP_LINK, trans_size);
3305 		ufs_lockfs_end(ulp);
3306 	}
3307 
3308 	if (!error) {
3309 		vnevent_link(svp, ct);
3310 	}
3311 out:
3312 	return (error);
3313 }
3314 
3315 uint64_t ufs_rename_retry_cnt;
3316 uint64_t ufs_rename_upgrade_retry_cnt;
3317 uint64_t ufs_rename_dircheck_retry_cnt;
3318 clock_t	 ufs_rename_backoff_delay = 1;
3319 
3320 /*
3321  * Rename a file or directory.
3322  * We are given the vnode and entry string of the source and the
3323  * vnode and entry string of the place we want to move the source
3324  * to (the target). The essential operation is:
3325  *	unlink(target);
3326  *	link(source, target);
3327  *	unlink(source);
3328  * but "atomically".  Can't do full commit without saving state in
3329  * the inode on disk, which isn't feasible at this time.  Best we
3330  * can do is always guarantee that the TARGET exists.
3331  */
3332 
3333 /*ARGSUSED*/
3334 static int
3335 ufs_rename(
3336 	struct vnode *sdvp,		/* old (source) parent vnode */
3337 	char *snm,			/* old (source) entry name */
3338 	struct vnode *tdvp,		/* new (target) parent vnode */
3339 	char *tnm,			/* new (target) entry name */
3340 	struct cred *cr,
3341 	caller_context_t *ct,
3342 	int flags)
3343 {
3344 	struct inode *sip = NULL;	/* source inode */
3345 	struct inode *ip = NULL;	/* check inode */
3346 	struct inode *sdp;		/* old (source) parent inode */
3347 	struct inode *tdp;		/* new (target) parent inode */
3348 	struct vnode *tvp = NULL;	/* target vnode, if it exists */
3349 	struct vnode *realvp;
3350 	struct ufsvfs *ufsvfsp;
3351 	struct ulockfs *ulp;
3352 	struct ufs_slot slot;
3353 	timestruc_t now;
3354 	int error;
3355 	int issync;
3356 	int trans_size;
3357 	krwlock_t *first_lock;
3358 	krwlock_t *second_lock;
3359 	krwlock_t *reverse_lock;
3360 
3361 	sdp = VTOI(sdvp);
3362 	slot.fbp = NULL;
3363 	ufsvfsp = sdp->i_ufsvfs;
3364 retry_rename:
3365 	error = ufs_lockfs_begin(ufsvfsp, &ulp, ULOCKFS_RENAME_MASK);
3366 	if (error)
3367 		goto out;
3368 
3369 	if (ulp)
3370 		TRANS_BEGIN_CSYNC(ufsvfsp, issync, TOP_RENAME,
3371 		    trans_size = (int)TOP_RENAME_SIZE(sdp));
3372 
3373 	if (VOP_REALVP(tdvp, &realvp, ct) == 0)
3374 		tdvp = realvp;
3375 
3376 	tdp = VTOI(tdvp);
3377 
3378 
3379 	/*
3380 	 * We only allow renaming of attributes from ATTRDIR to ATTRDIR.
3381 	 */
3382 	if ((tdp->i_mode & IFMT) != (sdp->i_mode & IFMT)) {
3383 		error = EINVAL;
3384 		goto unlock;
3385 	}
3386 
3387 	/*
3388 	 * Look up inode of file we're supposed to rename.
3389 	 */
3390 	gethrestime(&now);
3391 	if (error = ufs_dirlook(sdp, snm, &sip, cr, 0)) {
3392 		if (error == EAGAIN) {
3393 			if (ulp) {
3394 				TRANS_END_CSYNC(ufsvfsp, error, issync,
3395 				    TOP_RENAME, trans_size);
3396 				ufs_lockfs_end(ulp);
3397 			}
3398 			goto retry_rename;
3399 		}
3400 
3401 		goto unlock;
3402 	}
3403 
3404 	/*
3405 	 * Lock both the source and target directories (they may be
3406 	 * the same) to provide the atomicity semantics that was
3407 	 * previously provided by the per file system vfs_rename_lock
3408 	 *
3409 	 * with vfs_rename_lock removed to allow simultaneous renames
3410 	 * within a file system, ufs_dircheckpath can deadlock while
3411 	 * traversing back to ensure that source is not a parent directory
3412 	 * of target parent directory. This is because we get into
3413 	 * ufs_dircheckpath with the sdp and tdp locks held as RW_WRITER.
3414 	 * If the tdp and sdp of the simultaneous renames happen to be
3415 	 * in the path of each other, it can lead to a deadlock. This
3416 	 * can be avoided by getting the locks as RW_READER here and then
3417 	 * upgrading to RW_WRITER after completing the ufs_dircheckpath.
3418 	 *
3419 	 * We hold the target directory's i_rwlock after calling
3420 	 * ufs_lockfs_begin but in many other operations (like ufs_readdir)
3421 	 * VOP_RWLOCK is explicitly called by the filesystem independent code
3422 	 * before calling the file system operation. In these cases the order
3423 	 * is reversed (i.e i_rwlock is taken first and then ufs_lockfs_begin
3424 	 * is called). This is fine as long as ufs_lockfs_begin acts as a VOP
3425 	 * counter but with ufs_quiesce setting the SLOCK bit this becomes a
3426 	 * synchronizing object which might lead to a deadlock. So we use
3427 	 * rw_tryenter instead of rw_enter. If we fail to get this lock and
3428 	 * find that SLOCK bit is set, we call ufs_lockfs_end and restart the
3429 	 * operation.
3430 	 */
3431 retry:
3432 	first_lock = &tdp->i_rwlock;
3433 	second_lock = &sdp->i_rwlock;
3434 retry_firstlock:
3435 	if (!rw_tryenter(first_lock, RW_READER)) {
3436 		/*
3437 		 * We didn't get the lock. Check if the SLOCK is set in the
3438 		 * ufsvfs. If yes, we might be in a deadlock. Safer to give up
3439 		 * and wait for SLOCK to be cleared.
3440 		 */
3441 
3442 		if (ulp && ULOCKFS_IS_SLOCK(ulp)) {
3443 			TRANS_END_CSYNC(ufsvfsp, error, issync, TOP_RENAME,
3444 			    trans_size);
3445 			ufs_lockfs_end(ulp);
3446 			goto retry_rename;
3447 
3448 		} else {
3449 			/*
3450 			 * SLOCK isn't set so this is a genuine synchronization
3451 			 * case. Let's try again after giving them a breather.
3452 			 */
3453 			delay(RETRY_LOCK_DELAY);
3454 			goto  retry_firstlock;
3455 		}
3456 	}
3457 	/*
3458 	 * Need to check if the tdp and sdp are same !!!
3459 	 */
3460 	if ((tdp != sdp) && (!rw_tryenter(second_lock, RW_READER))) {
3461 		/*
3462 		 * We didn't get the lock. Check if the SLOCK is set in the
3463 		 * ufsvfs. If yes, we might be in a deadlock. Safer to give up
3464 		 * and wait for SLOCK to be cleared.
3465 		 */
3466 
3467 		rw_exit(first_lock);
3468 		if (ulp && ULOCKFS_IS_SLOCK(ulp)) {
3469 			TRANS_END_CSYNC(ufsvfsp, error, issync, TOP_RENAME,
3470 			    trans_size);
3471 			ufs_lockfs_end(ulp);
3472 			goto retry_rename;
3473 
3474 		} else {
3475 			/*
3476 			 * So we couldn't get the second level peer lock *and*
3477 			 * the SLOCK bit isn't set. Too bad we can be
3478 			 * contentding with someone wanting these locks otherway
3479 			 * round. Reverse the locks in case there is a heavy
3480 			 * contention for the second level lock.
3481 			 */
3482 			reverse_lock = first_lock;
3483 			first_lock = second_lock;
3484 			second_lock = reverse_lock;
3485 			ufs_rename_retry_cnt++;
3486 			goto  retry_firstlock;
3487 		}
3488 	}
3489 
3490 	if (sip == tdp) {
3491 		error = EINVAL;
3492 		goto errout;
3493 	}
3494 	/*
3495 	 * Make sure we can delete the source entry.  This requires
3496 	 * write permission on the containing directory.
3497 	 * Check for sticky directories.
3498 	 */
3499 	rw_enter(&sdp->i_contents, RW_READER);
3500 	rw_enter(&sip->i_contents, RW_READER);
3501 	if ((error = ufs_iaccess(sdp, IWRITE, cr)) != 0 ||
3502 	    (error = ufs_sticky_remove_access(sdp, sip, cr)) != 0) {
3503 		rw_exit(&sip->i_contents);
3504 		rw_exit(&sdp->i_contents);
3505 		goto errout;
3506 	}
3507 
3508 	/*
3509 	 * If this is a rename of a directory and the parent is
3510 	 * different (".." must be changed), then the source
3511 	 * directory must not be in the directory hierarchy
3512 	 * above the target, as this would orphan everything
3513 	 * below the source directory.  Also the user must have
3514 	 * write permission in the source so as to be able to
3515 	 * change "..".
3516 	 */
3517 	if ((((sip->i_mode & IFMT) == IFDIR) ||
3518 	    ((sip->i_mode & IFMT) == IFATTRDIR)) && sdp != tdp) {
3519 		ino_t	inum;
3520 
3521 		if ((error = ufs_iaccess(sip, IWRITE, cr))) {
3522 			rw_exit(&sip->i_contents);
3523 			rw_exit(&sdp->i_contents);
3524 			goto errout;
3525 		}
3526 		inum = sip->i_number;
3527 		rw_exit(&sip->i_contents);
3528 		rw_exit(&sdp->i_contents);
3529 		if ((error = ufs_dircheckpath(inum, tdp, sdp, cr))) {
3530 			/*
3531 			 * If we got EAGAIN ufs_dircheckpath detected a
3532 			 * potential deadlock and backed out. We need
3533 			 * to retry the operation since sdp and tdp have
3534 			 * to be released to avoid the deadlock.
3535 			 */
3536 			if (error == EAGAIN) {
3537 				rw_exit(&tdp->i_rwlock);
3538 				if (tdp != sdp)
3539 					rw_exit(&sdp->i_rwlock);
3540 				delay(ufs_rename_backoff_delay);
3541 				ufs_rename_dircheck_retry_cnt++;
3542 				goto retry;
3543 			}
3544 			goto errout;
3545 		}
3546 	} else {
3547 		rw_exit(&sip->i_contents);
3548 		rw_exit(&sdp->i_contents);
3549 	}
3550 
3551 
3552 	/*
3553 	 * Check for renaming '.' or '..' or alias of '.'
3554 	 */
3555 	if (strcmp(snm, ".") == 0 || strcmp(snm, "..") == 0 || sdp == sip) {
3556 		error = EINVAL;
3557 		goto errout;
3558 	}
3559 
3560 	/*
3561 	 * Simultaneous renames can deadlock in ufs_dircheckpath since it
3562 	 * tries to traverse back the file tree with both tdp and sdp held
3563 	 * as RW_WRITER. To avoid that we have to hold the tdp and sdp locks
3564 	 * as RW_READERS  till ufs_dircheckpath is done.
3565 	 * Now that ufs_dircheckpath is done with, we can upgrade the locks
3566 	 * to RW_WRITER.
3567 	 */
3568 	if (!rw_tryupgrade(&tdp->i_rwlock)) {
3569 		/*
3570 		 * The upgrade failed. We got to give away the lock
3571 		 * as to avoid deadlocking with someone else who is
3572 		 * waiting for writer lock. With the lock gone, we
3573 		 * cannot be sure the checks done above will hold
3574 		 * good when we eventually get them back as writer.
3575 		 * So if we can't upgrade we drop the locks and retry
3576 		 * everything again.
3577 		 */
3578 		rw_exit(&tdp->i_rwlock);
3579 		if (tdp != sdp)
3580 			rw_exit(&sdp->i_rwlock);
3581 		delay(ufs_rename_backoff_delay);
3582 		ufs_rename_upgrade_retry_cnt++;
3583 		goto retry;
3584 	}
3585 	if (tdp != sdp) {
3586 		if (!rw_tryupgrade(&sdp->i_rwlock)) {
3587 			/*
3588 			 * The upgrade failed. We got to give away the lock
3589 			 * as to avoid deadlocking with someone else who is
3590 			 * waiting for writer lock. With the lock gone, we
3591 			 * cannot be sure the checks done above will hold
3592 			 * good when we eventually get them back as writer.
3593 			 * So if we can't upgrade we drop the locks and retry
3594 			 * everything again.
3595 			 */
3596 			rw_exit(&tdp->i_rwlock);
3597 			rw_exit(&sdp->i_rwlock);
3598 			delay(ufs_rename_backoff_delay);
3599 			ufs_rename_upgrade_retry_cnt++;
3600 			goto retry;
3601 		}
3602 	}
3603 
3604 	/*
3605 	 * Now that all the locks are held check to make sure another thread
3606 	 * didn't slip in and take out the sip.
3607 	 */
3608 	slot.status = NONE;
3609 	if ((sip->i_ctime.tv_usec * 1000) > now.tv_nsec ||
3610 	    sip->i_ctime.tv_sec > now.tv_sec) {
3611 		rw_enter(&sdp->i_ufsvfs->vfs_dqrwlock, RW_READER);
3612 		rw_enter(&sdp->i_contents, RW_WRITER);
3613 		error = ufs_dircheckforname(sdp, snm, strlen(snm), &slot,
3614 		    &ip, cr, 0);
3615 		rw_exit(&sdp->i_contents);
3616 		rw_exit(&sdp->i_ufsvfs->vfs_dqrwlock);
3617 		if (error) {
3618 			goto errout;
3619 		}
3620 		if (ip == NULL) {
3621 			error = ENOENT;
3622 			goto errout;
3623 		} else {
3624 			/*
3625 			 * If the inode was found need to drop the v_count
3626 			 * so as not to keep the filesystem from being
3627 			 * unmounted at a later time.
3628 			 */
3629 			VN_RELE(ITOV(ip));
3630 		}
3631 
3632 		/*
3633 		 * Release the slot.fbp that has the page mapped and
3634 		 * locked SE_SHARED, and could be used in in
3635 		 * ufs_direnter_lr() which needs to get the SE_EXCL lock
3636 		 * on said page.
3637 		 */
3638 		if (slot.fbp) {
3639 			fbrelse(slot.fbp, S_OTHER);
3640 			slot.fbp = NULL;
3641 		}
3642 	}
3643 
3644 	/*
3645 	 * Link source to the target.  If a target exists, return its
3646 	 * vnode pointer in tvp.  We'll release it after sending the
3647 	 * vnevent.
3648 	 */
3649 	if (error = ufs_direnter_lr(tdp, tnm, DE_RENAME, sdp, sip, cr, &tvp)) {
3650 		/*
3651 		 * ESAME isn't really an error; it indicates that the
3652 		 * operation should not be done because the source and target
3653 		 * are the same file, but that no error should be reported.
3654 		 */
3655 		if (error == ESAME)
3656 			error = 0;
3657 		goto errout;
3658 	}
3659 
3660 	/*
3661 	 * Unlink the source.
3662 	 * Remove the source entry.  ufs_dirremove() checks that the entry
3663 	 * still reflects sip, and returns an error if it doesn't.
3664 	 * If the entry has changed just forget about it.  Release
3665 	 * the source inode.
3666 	 */
3667 	if ((error = ufs_dirremove(sdp, snm, sip, (struct vnode *)0,
3668 	    DR_RENAME, cr, NULL)) == ENOENT)
3669 		error = 0;
3670 
3671 errout:
3672 	if (slot.fbp)
3673 		fbrelse(slot.fbp, S_OTHER);
3674 
3675 	rw_exit(&tdp->i_rwlock);
3676 	if (sdp != tdp) {
3677 		rw_exit(&sdp->i_rwlock);
3678 	}
3679 
3680 unlock:
3681 	if (ulp) {
3682 		TRANS_END_CSYNC(ufsvfsp, error, issync, TOP_RENAME, trans_size);
3683 		ufs_lockfs_end(ulp);
3684 	}
3685 
3686 	/*
3687 	 * If no errors, send the appropriate events on the source
3688 	 * and destination (a.k.a, target) vnodes, if they exist.
3689 	 * This has to be done after the rename transaction has closed.
3690 	 */
3691 	if (error == 0) {
3692 		if (tvp != NULL)
3693 			vnevent_rename_dest(tvp, tdvp, tnm, ct);
3694 
3695 		/*
3696 		 * Notify the target directory of the rename event
3697 		 * if source and target directories are not same.
3698 		 */
3699 		if (sdvp != tdvp)
3700 			vnevent_rename_dest_dir(tdvp, ct);
3701 
3702 		/*
3703 		 * Note that if ufs_direnter_lr() returned ESAME then
3704 		 * this event will still be sent.  This isn't expected
3705 		 * to be a problem for anticipated usage by consumers.
3706 		 */
3707 		if (sip != NULL)
3708 			vnevent_rename_src(ITOV(sip), sdvp, snm, ct);
3709 	}
3710 
3711 	if (tvp != NULL)
3712 		VN_RELE(tvp);
3713 
3714 	if (sip != NULL)
3715 		VN_RELE(ITOV(sip));
3716 
3717 out:
3718 	return (error);
3719 }
3720 
3721 /*ARGSUSED*/
3722 static int
3723 ufs_mkdir(struct vnode *dvp, char *dirname, struct vattr *vap,
3724 	struct vnode **vpp, struct cred *cr, caller_context_t *ct, int flags,
3725 	vsecattr_t *vsecp)
3726 {
3727 	struct inode *ip;
3728 	struct inode *xip;
3729 	struct ufsvfs *ufsvfsp;
3730 	struct ulockfs *ulp;
3731 	int error;
3732 	int issync;
3733 	int trans_size;
3734 	int indeadlock;
3735 	int retry = 1;
3736 
3737 	ASSERT((vap->va_mask & (AT_TYPE|AT_MODE)) == (AT_TYPE|AT_MODE));
3738 
3739 	/*
3740 	 * Can't make directory in attr hidden dir
3741 	 */
3742 	if ((VTOI(dvp)->i_mode & IFMT) == IFATTRDIR)
3743 		return (EINVAL);
3744 
3745 again:
3746 	ip = VTOI(dvp);
3747 	ufsvfsp = ip->i_ufsvfs;
3748 	error = ufs_lockfs_begin(ufsvfsp, &ulp, ULOCKFS_MKDIR_MASK);
3749 	if (error)
3750 		goto out;
3751 	if (ulp)
3752 		TRANS_BEGIN_CSYNC(ufsvfsp, issync, TOP_MKDIR,
3753 		    trans_size = (int)TOP_MKDIR_SIZE(ip));
3754 
3755 	/*
3756 	 * ufs_tryirwlock_trans uses rw_tryenter and checks for SLOCK
3757 	 * to avoid i_rwlock, ufs_lockfs_begin deadlock. If deadlock
3758 	 * possible, retries the operation.
3759 	 */
3760 	ufs_tryirwlock_trans(&ip->i_rwlock, RW_WRITER, TOP_MKDIR, retry);
3761 	if (indeadlock)
3762 		goto again;
3763 
3764 	error = ufs_direnter_cm(ip, dirname, DE_MKDIR, vap, &xip, cr,
3765 	    (retry ? IQUIET : 0));
3766 	if (error == EAGAIN) {
3767 		if (ulp) {
3768 			TRANS_END_CSYNC(ufsvfsp, error, issync, TOP_MKDIR,
3769 			    trans_size);
3770 			ufs_lockfs_end(ulp);
3771 		}
3772 		goto again;
3773 	}
3774 
3775 	rw_exit(&ip->i_rwlock);
3776 	if (error == 0) {
3777 		ip = xip;
3778 		*vpp = ITOV(ip);
3779 	} else if (error == EEXIST)
3780 		VN_RELE(ITOV(xip));
3781 
3782 	if (ulp) {
3783 		int terr = 0;
3784 		TRANS_END_CSYNC(ufsvfsp, terr, issync, TOP_MKDIR, trans_size);
3785 		ufs_lockfs_end(ulp);
3786 		if (error == 0)
3787 			error = terr;
3788 	}
3789 out:
3790 	if ((error == ENOSPC) && retry && TRANS_ISTRANS(ufsvfsp)) {
3791 		ufs_delete_drain_wait(ufsvfsp, 1);
3792 		retry = 0;
3793 		goto again;
3794 	}
3795 
3796 	return (error);
3797 }
3798 
3799 /*ARGSUSED*/
3800 static int
3801 ufs_rmdir(struct vnode *vp, char *nm, struct vnode *cdir, struct cred *cr,
3802 	caller_context_t *ct, int flags)
3803 {
3804 	struct inode *ip = VTOI(vp);
3805 	struct ufsvfs *ufsvfsp = ip->i_ufsvfs;
3806 	struct ulockfs *ulp;
3807 	vnode_t *rmvp = NULL;	/* Vnode of removed directory */
3808 	int error;
3809 	int issync;
3810 	int trans_size;
3811 	int indeadlock;
3812 
3813 	/*
3814 	 * don't let the delete queue get too long
3815 	 */
3816 	if (ufsvfsp == NULL) {
3817 		error = EIO;
3818 		goto out;
3819 	}
3820 	if (ufsvfsp->vfs_delete.uq_ne > ufs_idle_max)
3821 		ufs_delete_drain(vp->v_vfsp, 1, 1);
3822 
3823 retry_rmdir:
3824 	error = ufs_lockfs_begin(ufsvfsp, &ulp, ULOCKFS_RMDIR_MASK);
3825 	if (error)
3826 		goto out;
3827 
3828 	if (ulp)
3829 		TRANS_BEGIN_CSYNC(ufsvfsp, issync, TOP_RMDIR,
3830 		    trans_size = TOP_RMDIR_SIZE);
3831 
3832 	/*
3833 	 * ufs_tryirwlock_trans uses rw_tryenter and checks for SLOCK
3834 	 * to avoid i_rwlock, ufs_lockfs_begin deadlock. If deadlock
3835 	 * possible, retries the operation.
3836 	 */
3837 	ufs_tryirwlock_trans(&ip->i_rwlock, RW_WRITER, TOP_RMDIR, retry);
3838 	if (indeadlock)
3839 		goto retry_rmdir;
3840 	error = ufs_dirremove(ip, nm, (struct inode *)0, cdir, DR_RMDIR, cr,
3841 	    &rmvp);
3842 	rw_exit(&ip->i_rwlock);
3843 
3844 	if (ulp) {
3845 		TRANS_END_CSYNC(ufsvfsp, error, issync, TOP_RMDIR,
3846 		    trans_size);
3847 		ufs_lockfs_end(ulp);
3848 	}
3849 
3850 	/*
3851 	 * This must be done AFTER the rmdir transaction has closed.
3852 	 */
3853 	if (rmvp != NULL) {
3854 		/* Only send the event if there were no errors */
3855 		if (error == 0)
3856 			vnevent_rmdir(rmvp, vp, nm, ct);
3857 		VN_RELE(rmvp);
3858 	}
3859 out:
3860 	return (error);
3861 }
3862 
3863 /* ARGSUSED */
3864 static int
3865 ufs_readdir(
3866 	struct vnode *vp,
3867 	struct uio *uiop,
3868 	struct cred *cr,
3869 	int *eofp,
3870 	caller_context_t *ct,
3871 	int flags)
3872 {
3873 	struct iovec *iovp;
3874 	struct inode *ip;
3875 	struct direct *idp;
3876 	struct dirent64 *odp;
3877 	struct fbuf *fbp;
3878 	struct ufsvfs *ufsvfsp;
3879 	struct ulockfs *ulp;
3880 	caddr_t outbuf;
3881 	size_t bufsize;
3882 	uint_t offset;
3883 	uint_t bytes_wanted, total_bytes_wanted;
3884 	int incount = 0;
3885 	int outcount = 0;
3886 	int error;
3887 
3888 	ip = VTOI(vp);
3889 	ASSERT(RW_READ_HELD(&ip->i_rwlock));
3890 
3891 	if (uiop->uio_loffset >= MAXOFF32_T) {
3892 		if (eofp)
3893 			*eofp = 1;
3894 		return (0);
3895 	}
3896 
3897 	/*
3898 	 * Check if we have been called with a valid iov_len
3899 	 * and bail out if not, otherwise we may potentially loop
3900 	 * forever further down.
3901 	 */
3902 	if (uiop->uio_iov->iov_len <= 0) {
3903 		error = EINVAL;
3904 		goto out;
3905 	}
3906 
3907 	/*
3908 	 * Large Files: When we come here we are guaranteed that
3909 	 * uio_offset can be used safely. The high word is zero.
3910 	 */
3911 
3912 	ufsvfsp = ip->i_ufsvfs;
3913 	error = ufs_lockfs_begin(ufsvfsp, &ulp, ULOCKFS_READDIR_MASK);
3914 	if (error)
3915 		goto out;
3916 
3917 	iovp = uiop->uio_iov;
3918 	total_bytes_wanted = iovp->iov_len;
3919 
3920 	/* Large Files: directory files should not be "large" */
3921 
3922 	ASSERT(ip->i_size <= MAXOFF32_T);
3923 
3924 	/* Force offset to be valid (to guard against bogus lseek() values) */
3925 	offset = (uint_t)uiop->uio_offset & ~(DIRBLKSIZ - 1);
3926 
3927 	/* Quit if at end of file or link count of zero (posix) */
3928 	if (offset >= (uint_t)ip->i_size || ip->i_nlink <= 0) {
3929 		if (eofp)
3930 			*eofp = 1;
3931 		error = 0;
3932 		goto unlock;
3933 	}
3934 
3935 	/*
3936 	 * Get space to change directory entries into fs independent format.
3937 	 * Do fast alloc for the most commonly used-request size (filesystem
3938 	 * block size).
3939 	 */
3940 	if (uiop->uio_segflg != UIO_SYSSPACE || uiop->uio_iovcnt != 1) {
3941 		bufsize = total_bytes_wanted;
3942 		outbuf = kmem_alloc(bufsize, KM_SLEEP);
3943 		odp = (struct dirent64 *)outbuf;
3944 	} else {
3945 		bufsize = total_bytes_wanted;
3946 		odp = (struct dirent64 *)iovp->iov_base;
3947 	}
3948 
3949 nextblk:
3950 	bytes_wanted = total_bytes_wanted;
3951 
3952 	/* Truncate request to file size */
3953 	if (offset + bytes_wanted > (int)ip->i_size)
3954 		bytes_wanted = (int)(ip->i_size - offset);
3955 
3956 	/* Comply with MAXBSIZE boundary restrictions of fbread() */
3957 	if ((offset & MAXBOFFSET) + bytes_wanted > MAXBSIZE)
3958 		bytes_wanted = MAXBSIZE - (offset & MAXBOFFSET);
3959 
3960 	/*
3961 	 * Read in the next chunk.
3962 	 * We are still holding the i_rwlock.
3963 	 */
3964 	error = fbread(vp, (offset_t)offset, bytes_wanted, S_OTHER, &fbp);
3965 
3966 	if (error)
3967 		goto update_inode;
3968 	if (!ULOCKFS_IS_NOIACC(ITOUL(ip)) && (ip->i_fs->fs_ronly == 0) &&
3969 	    (!ufsvfsp->vfs_noatime)) {
3970 		ip->i_flag |= IACC;
3971 	}
3972 	incount = 0;
3973 	idp = (struct direct *)fbp->fb_addr;
3974 	if (idp->d_ino == 0 && idp->d_reclen == 0 && idp->d_namlen == 0) {
3975 		cmn_err(CE_WARN, "ufs_readdir: bad dir, inumber = %llu, "
3976 		    "fs = %s\n",
3977 		    (u_longlong_t)ip->i_number, ufsvfsp->vfs_fs->fs_fsmnt);
3978 		fbrelse(fbp, S_OTHER);
3979 		error = ENXIO;
3980 		goto update_inode;
3981 	}
3982 	/* Transform to file-system independent format */
3983 	while (incount < bytes_wanted) {
3984 		/*
3985 		 * If the current directory entry is mangled, then skip
3986 		 * to the next block.  It would be nice to set the FSBAD
3987 		 * flag in the super-block so that a fsck is forced on
3988 		 * next reboot, but locking is a problem.
3989 		 */
3990 		if (idp->d_reclen & 0x3) {
3991 			offset = (offset + DIRBLKSIZ) & ~(DIRBLKSIZ-1);
3992 			break;
3993 		}
3994 
3995 		/* Skip to requested offset and skip empty entries */
3996 		if (idp->d_ino != 0 && offset >= (uint_t)uiop->uio_offset) {
3997 			ushort_t this_reclen =
3998 			    DIRENT64_RECLEN(idp->d_namlen);
3999 			/* Buffer too small for any entries */
4000 			if (!outcount && this_reclen > bufsize) {
4001 				fbrelse(fbp, S_OTHER);
4002 				error = EINVAL;
4003 				goto update_inode;
4004 			}
4005 			/* If would overrun the buffer, quit */
4006 			if (outcount + this_reclen > bufsize) {
4007 				break;
4008 			}
4009 			/* Take this entry */
4010 			odp->d_ino = (ino64_t)idp->d_ino;
4011 			odp->d_reclen = (ushort_t)this_reclen;
4012 			odp->d_off = (offset_t)(offset + idp->d_reclen);
4013 
4014 			/* use strncpy(9f) to zero out uninitialized bytes */
4015 
4016 			ASSERT(strlen(idp->d_name) + 1 <=
4017 			    DIRENT64_NAMELEN(this_reclen));
4018 			(void) strncpy(odp->d_name, idp->d_name,
4019 			    DIRENT64_NAMELEN(this_reclen));
4020 			outcount += odp->d_reclen;
4021 			odp = (struct dirent64 *)
4022 			    ((intptr_t)odp + odp->d_reclen);
4023 			ASSERT(outcount <= bufsize);
4024 		}
4025 		if (idp->d_reclen) {
4026 			incount += idp->d_reclen;
4027 			offset += idp->d_reclen;
4028 			idp = (struct direct *)((intptr_t)idp + idp->d_reclen);
4029 		} else {
4030 			offset = (offset + DIRBLKSIZ) & ~(DIRBLKSIZ-1);
4031 			break;
4032 		}
4033 	}
4034 	/* Release the chunk */
4035 	fbrelse(fbp, S_OTHER);
4036 
4037 	/* Read whole block, but got no entries, read another if not eof */
4038 
4039 	/*
4040 	 * Large Files: casting i_size to int here is not a problem
4041 	 * because directory sizes are always less than MAXOFF32_T.
4042 	 * See assertion above.
4043 	 */
4044 
4045 	if (offset < (int)ip->i_size && !outcount)
4046 		goto nextblk;
4047 
4048 	/* Copy out the entry data */
4049 	if (uiop->uio_segflg == UIO_SYSSPACE && uiop->uio_iovcnt == 1) {
4050 		iovp->iov_base += outcount;
4051 		iovp->iov_len -= outcount;
4052 		uiop->uio_resid -= outcount;
4053 		uiop->uio_offset = offset;
4054 	} else if ((error = uiomove(outbuf, (long)outcount, UIO_READ,
4055 	    uiop)) == 0)
4056 		uiop->uio_offset = offset;
4057 update_inode:
4058 	ITIMES(ip);
4059 	if (uiop->uio_segflg != UIO_SYSSPACE || uiop->uio_iovcnt != 1)
4060 		kmem_free(outbuf, bufsize);
4061 
4062 	if (eofp && error == 0)
4063 		*eofp = (uiop->uio_offset >= (int)ip->i_size);
4064 unlock:
4065 	if (ulp) {
4066 		ufs_lockfs_end(ulp);
4067 	}
4068 out:
4069 	return (error);
4070 }
4071 
4072 /*ARGSUSED*/
4073 static int
4074 ufs_symlink(
4075 	struct vnode *dvp,		/* ptr to parent dir vnode */
4076 	char *linkname,			/* name of symbolic link */
4077 	struct vattr *vap,		/* attributes */
4078 	char *target,			/* target path */
4079 	struct cred *cr,		/* user credentials */
4080 	caller_context_t *ct,
4081 	int flags)
4082 {
4083 	struct inode *ip, *dip = VTOI(dvp);
4084 	struct ufsvfs *ufsvfsp = dip->i_ufsvfs;
4085 	struct ulockfs *ulp;
4086 	int error;
4087 	int issync;
4088 	int trans_size;
4089 	int residual;
4090 	int ioflag;
4091 	int retry = 1;
4092 
4093 	/*
4094 	 * No symlinks in attrdirs at this time
4095 	 */
4096 	if ((VTOI(dvp)->i_mode & IFMT) == IFATTRDIR)
4097 		return (EINVAL);
4098 
4099 again:
4100 	ip = (struct inode *)NULL;
4101 	vap->va_type = VLNK;
4102 	vap->va_rdev = 0;
4103 
4104 	error = ufs_lockfs_begin(ufsvfsp, &ulp, ULOCKFS_SYMLINK_MASK);
4105 	if (error)
4106 		goto out;
4107 
4108 	if (ulp)
4109 		TRANS_BEGIN_CSYNC(ufsvfsp, issync, TOP_SYMLINK,
4110 		    trans_size = (int)TOP_SYMLINK_SIZE(dip));
4111 
4112 	/*
4113 	 * We must create the inode before the directory entry, to avoid
4114 	 * racing with readlink().  ufs_dirmakeinode requires that we
4115 	 * hold the quota lock as reader, and directory locks as writer.
4116 	 */
4117 
4118 	rw_enter(&dip->i_rwlock, RW_WRITER);
4119 	rw_enter(&ufsvfsp->vfs_dqrwlock, RW_READER);
4120 	rw_enter(&dip->i_contents, RW_WRITER);
4121 
4122 	/*
4123 	 * Suppress any out of inodes messages if we will retry on
4124 	 * ENOSP
4125 	 */
4126 	if (retry)
4127 		dip->i_flag |= IQUIET;
4128 
4129 	error = ufs_dirmakeinode(dip, &ip, vap, DE_SYMLINK, cr);
4130 
4131 	dip->i_flag &= ~IQUIET;
4132 
4133 	rw_exit(&dip->i_contents);
4134 	rw_exit(&ufsvfsp->vfs_dqrwlock);
4135 	rw_exit(&dip->i_rwlock);
4136 
4137 	if (error)
4138 		goto unlock;
4139 
4140 	/*
4141 	 * OK.  The inode has been created.  Write out the data of the
4142 	 * symbolic link.  Since symbolic links are metadata, and should
4143 	 * remain consistent across a system crash, we need to force the
4144 	 * data out synchronously.
4145 	 *
4146 	 * (This is a change from the semantics in earlier releases, which
4147 	 * only created symbolic links synchronously if the semi-documented
4148 	 * 'syncdir' option was set, or if we were being invoked by the NFS
4149 	 * server, which requires symbolic links to be created synchronously.)
4150 	 *
4151 	 * We need to pass in a pointer for the residual length; otherwise
4152 	 * ufs_rdwri() will always return EIO if it can't write the data,
4153 	 * even if the error was really ENOSPC or EDQUOT.
4154 	 */
4155 
4156 	ioflag = FWRITE | FDSYNC;
4157 	residual = 0;
4158 
4159 	rw_enter(&ufsvfsp->vfs_dqrwlock, RW_READER);
4160 	rw_enter(&ip->i_contents, RW_WRITER);
4161 
4162 	/*
4163 	 * Suppress file system full messages if we will retry
4164 	 */
4165 	if (retry)
4166 		ip->i_flag |= IQUIET;
4167 
4168 	error = ufs_rdwri(UIO_WRITE, ioflag, ip, target, strlen(target),
4169 	    (offset_t)0, UIO_SYSSPACE, &residual, cr);
4170 
4171 	ip->i_flag &= ~IQUIET;
4172 
4173 	if (error) {
4174 		rw_exit(&ip->i_contents);
4175 		rw_exit(&ufsvfsp->vfs_dqrwlock);
4176 		goto remove;
4177 	}
4178 
4179 	/*
4180 	 * If the link's data is small enough, we can cache it in the inode.
4181 	 * This is a "fast symbolic link".  We don't use the first direct
4182 	 * block because that's actually used to point at the symbolic link's
4183 	 * contents on disk; but we know that none of the other direct or
4184 	 * indirect blocks can be used because symbolic links are restricted
4185 	 * to be smaller than a file system block.
4186 	 */
4187 
4188 	ASSERT(MAXPATHLEN <= VBSIZE(ITOV(ip)));
4189 
4190 	if (ip->i_size > 0 && ip->i_size <= FSL_SIZE) {
4191 		if (kcopy(target, &ip->i_db[1], ip->i_size) == 0) {
4192 			ip->i_flag |= IFASTSYMLNK;
4193 		} else {
4194 			int i;
4195 			/* error, clear garbage left behind */
4196 			for (i = 1; i < NDADDR; i++)
4197 				ip->i_db[i] = 0;
4198 			for (i = 0; i < NIADDR; i++)
4199 				ip->i_ib[i] = 0;
4200 		}
4201 	}
4202 
4203 	rw_exit(&ip->i_contents);
4204 	rw_exit(&ufsvfsp->vfs_dqrwlock);
4205 
4206 	/*
4207 	 * OK.  We've successfully created the symbolic link.  All that
4208 	 * remains is to insert it into the appropriate directory.
4209 	 */
4210 
4211 	rw_enter(&dip->i_rwlock, RW_WRITER);
4212 	error = ufs_direnter_lr(dip, linkname, DE_SYMLINK, NULL, ip, cr, NULL);
4213 	rw_exit(&dip->i_rwlock);
4214 
4215 	/*
4216 	 * Fall through into remove-on-error code.  We're either done, or we
4217 	 * need to remove the inode (if we couldn't insert it).
4218 	 */
4219 
4220 remove:
4221 	if (error && (ip != NULL)) {
4222 		rw_enter(&ip->i_contents, RW_WRITER);
4223 		ip->i_nlink--;
4224 		ip->i_flag |= ICHG;
4225 		ip->i_seq++;
4226 		ufs_setreclaim(ip);
4227 		rw_exit(&ip->i_contents);
4228 	}
4229 
4230 unlock:
4231 	if (ip != NULL)
4232 		VN_RELE(ITOV(ip));
4233 
4234 	if (ulp) {
4235 		int terr = 0;
4236 
4237 		TRANS_END_CSYNC(ufsvfsp, terr, issync, TOP_SYMLINK,
4238 		    trans_size);
4239 		ufs_lockfs_end(ulp);
4240 		if (error == 0)
4241 			error = terr;
4242 	}
4243 
4244 	/*
4245 	 * We may have failed due to lack of an inode or of a block to
4246 	 * store the target in.  Try flushing the delete queue to free
4247 	 * logically-available things up and try again.
4248 	 */
4249 	if ((error == ENOSPC) && retry && TRANS_ISTRANS(ufsvfsp)) {
4250 		ufs_delete_drain_wait(ufsvfsp, 1);
4251 		retry = 0;
4252 		goto again;
4253 	}
4254 
4255 out:
4256 	return (error);
4257 }
4258 
4259 /*
4260  * Ufs specific routine used to do ufs io.
4261  */
4262 int
4263 ufs_rdwri(enum uio_rw rw, int ioflag, struct inode *ip, caddr_t base,
4264 	ssize_t len, offset_t offset, enum uio_seg seg, int *aresid,
4265 	struct cred *cr)
4266 {
4267 	struct uio auio;
4268 	struct iovec aiov;
4269 	int error;
4270 
4271 	ASSERT(RW_LOCK_HELD(&ip->i_contents));
4272 
4273 	bzero((caddr_t)&auio, sizeof (uio_t));
4274 	bzero((caddr_t)&aiov, sizeof (iovec_t));
4275 
4276 	aiov.iov_base = base;
4277 	aiov.iov_len = len;
4278 	auio.uio_iov = &aiov;
4279 	auio.uio_iovcnt = 1;
4280 	auio.uio_loffset = offset;
4281 	auio.uio_segflg = (short)seg;
4282 	auio.uio_resid = len;
4283 
4284 	if (rw == UIO_WRITE) {
4285 		auio.uio_fmode = FWRITE;
4286 		auio.uio_extflg = UIO_COPY_DEFAULT;
4287 		auio.uio_llimit = curproc->p_fsz_ctl;
4288 		error = wrip(ip, &auio, ioflag, cr);
4289 	} else {
4290 		auio.uio_fmode = FREAD;
4291 		auio.uio_extflg = UIO_COPY_CACHED;
4292 		auio.uio_llimit = MAXOFFSET_T;
4293 		error = rdip(ip, &auio, ioflag, cr);
4294 	}
4295 
4296 	if (aresid) {
4297 		*aresid = auio.uio_resid;
4298 	} else if (auio.uio_resid) {
4299 		error = EIO;
4300 	}
4301 	return (error);
4302 }
4303 
4304 /*ARGSUSED*/
4305 static int
4306 ufs_fid(struct vnode *vp, struct fid *fidp, caller_context_t *ct)
4307 {
4308 	struct ufid *ufid;
4309 	struct inode *ip = VTOI(vp);
4310 
4311 	if (ip->i_ufsvfs == NULL)
4312 		return (EIO);
4313 
4314 	if (fidp->fid_len < (sizeof (struct ufid) - sizeof (ushort_t))) {
4315 		fidp->fid_len = sizeof (struct ufid) - sizeof (ushort_t);
4316 		return (ENOSPC);
4317 	}
4318 
4319 	ufid = (struct ufid *)fidp;
4320 	bzero((char *)ufid, sizeof (struct ufid));
4321 	ufid->ufid_len = sizeof (struct ufid) - sizeof (ushort_t);
4322 	ufid->ufid_ino = ip->i_number;
4323 	ufid->ufid_gen = ip->i_gen;
4324 
4325 	return (0);
4326 }
4327 
4328 /* ARGSUSED2 */
4329 static int
4330 ufs_rwlock(struct vnode *vp, int write_lock, caller_context_t *ctp)
4331 {
4332 	struct inode	*ip = VTOI(vp);
4333 	struct ufsvfs	*ufsvfsp;
4334 	int		forcedirectio;
4335 
4336 	/*
4337 	 * Read case is easy.
4338 	 */
4339 	if (!write_lock) {
4340 		rw_enter(&ip->i_rwlock, RW_READER);
4341 		return (V_WRITELOCK_FALSE);
4342 	}
4343 
4344 	/*
4345 	 * Caller has requested a writer lock, but that inhibits any
4346 	 * concurrency in the VOPs that follow. Acquire the lock shared
4347 	 * and defer exclusive access until it is known to be needed in
4348 	 * other VOP handlers. Some cases can be determined here.
4349 	 */
4350 
4351 	/*
4352 	 * If directio is not set, there is no chance of concurrency,
4353 	 * so just acquire the lock exclusive. Beware of a forced
4354 	 * unmount before looking at the mount option.
4355 	 */
4356 	ufsvfsp = ip->i_ufsvfs;
4357 	forcedirectio = ufsvfsp ? ufsvfsp->vfs_forcedirectio : 0;
4358 	if (!(ip->i_flag & IDIRECTIO || forcedirectio) ||
4359 	    !ufs_allow_shared_writes) {
4360 		rw_enter(&ip->i_rwlock, RW_WRITER);
4361 		return (V_WRITELOCK_TRUE);
4362 	}
4363 
4364 	/*
4365 	 * Mandatory locking forces acquiring i_rwlock exclusive.
4366 	 */
4367 	if (MANDLOCK(vp, ip->i_mode)) {
4368 		rw_enter(&ip->i_rwlock, RW_WRITER);
4369 		return (V_WRITELOCK_TRUE);
4370 	}
4371 
4372 	/*
4373 	 * Acquire the lock shared in case a concurrent write follows.
4374 	 * Mandatory locking could have become enabled before the lock
4375 	 * was acquired. Re-check and upgrade if needed.
4376 	 */
4377 	rw_enter(&ip->i_rwlock, RW_READER);
4378 	if (MANDLOCK(vp, ip->i_mode)) {
4379 		rw_exit(&ip->i_rwlock);
4380 		rw_enter(&ip->i_rwlock, RW_WRITER);
4381 		return (V_WRITELOCK_TRUE);
4382 	}
4383 	return (V_WRITELOCK_FALSE);
4384 }
4385 
4386 /*ARGSUSED*/
4387 static void
4388 ufs_rwunlock(struct vnode *vp, int write_lock, caller_context_t *ctp)
4389 {
4390 	struct inode	*ip = VTOI(vp);
4391 
4392 	rw_exit(&ip->i_rwlock);
4393 }
4394 
4395 /* ARGSUSED */
4396 static int
4397 ufs_seek(struct vnode *vp, offset_t ooff, offset_t *noffp,
4398 	caller_context_t *ct)
4399 {
4400 	return ((*noffp < 0 || *noffp > MAXOFFSET_T) ? EINVAL : 0);
4401 }
4402 
4403 /* ARGSUSED */
4404 static int
4405 ufs_frlock(struct vnode *vp, int cmd, struct flock64 *bfp, int flag,
4406 	offset_t offset, struct flk_callback *flk_cbp, struct cred *cr,
4407 	caller_context_t *ct)
4408 {
4409 	struct inode *ip = VTOI(vp);
4410 
4411 	if (ip->i_ufsvfs == NULL)
4412 		return (EIO);
4413 
4414 	/*
4415 	 * If file is being mapped, disallow frlock.
4416 	 * XXX I am not holding tlock while checking i_mapcnt because the
4417 	 * current locking strategy drops all locks before calling fs_frlock.
4418 	 * So, mapcnt could change before we enter fs_frlock making is
4419 	 * meaningless to have held tlock in the first place.
4420 	 */
4421 	if (ip->i_mapcnt > 0 && MANDLOCK(vp, ip->i_mode))
4422 		return (EAGAIN);
4423 	return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct));
4424 }
4425 
4426 /* ARGSUSED */
4427 static int
4428 ufs_space(struct vnode *vp, int cmd, struct flock64 *bfp, int flag,
4429 	offset_t offset, cred_t *cr, caller_context_t *ct)
4430 {
4431 	struct ufsvfs *ufsvfsp = VTOI(vp)->i_ufsvfs;
4432 	struct ulockfs *ulp;
4433 	int error;
4434 
4435 	if ((error = convoff(vp, bfp, 0, offset)) == 0) {
4436 		if (cmd == F_FREESP) {
4437 			error = ufs_lockfs_begin(ufsvfsp, &ulp,
4438 			    ULOCKFS_SPACE_MASK);
4439 			if (error)
4440 				return (error);
4441 			error = ufs_freesp(vp, bfp, flag, cr);
4442 		} else if (cmd == F_ALLOCSP) {
4443 			error = ufs_lockfs_begin(ufsvfsp, &ulp,
4444 			    ULOCKFS_FALLOCATE_MASK);
4445 			if (error)
4446 				return (error);
4447 			error = ufs_allocsp(vp, bfp, cr);
4448 		} else
4449 			return (EINVAL); /* Command not handled here */
4450 
4451 		if (ulp)
4452 			ufs_lockfs_end(ulp);
4453 
4454 	}
4455 	return (error);
4456 }
4457 
4458 /*
4459  * Used to determine if read ahead should be done. Also used to
4460  * to determine when write back occurs.
4461  */
4462 #define	CLUSTSZ(ip)		((ip)->i_ufsvfs->vfs_ioclustsz)
4463 
4464 /*
4465  * A faster version of ufs_getpage.
4466  *
4467  * We optimize by inlining the pvn_getpages iterator, eliminating
4468  * calls to bmap_read if file doesn't have UFS holes, and avoiding
4469  * the overhead of page_exists().
4470  *
4471  * When files has UFS_HOLES and ufs_getpage is called with S_READ,
4472  * we set *protp to PROT_READ to avoid calling bmap_read. This approach
4473  * victimizes performance when a file with UFS holes is faulted
4474  * first in the S_READ mode, and then in the S_WRITE mode. We will get
4475  * two MMU faults in this case.
4476  *
4477  * XXX - the inode fields which control the sequential mode are not
4478  *	 protected by any mutex. The read ahead will act wild if
4479  *	 multiple processes will access the file concurrently and
4480  *	 some of them in sequential mode. One particulary bad case
4481  *	 is if another thread will change the value of i_nextrio between
4482  *	 the time this thread tests the i_nextrio value and then reads it
4483  *	 again to use it as the offset for the read ahead.
4484  */
4485 /*ARGSUSED*/
4486 static int
4487 ufs_getpage(struct vnode *vp, offset_t off, size_t len, uint_t *protp,
4488 	page_t *plarr[], size_t plsz, struct seg *seg, caddr_t addr,
4489 	enum seg_rw rw, struct cred *cr, caller_context_t *ct)
4490 {
4491 	u_offset_t	uoff = (u_offset_t)off; /* type conversion */
4492 	u_offset_t	pgoff;
4493 	u_offset_t	eoff;
4494 	struct inode 	*ip = VTOI(vp);
4495 	struct ufsvfs	*ufsvfsp = ip->i_ufsvfs;
4496 	struct fs 	*fs;
4497 	struct ulockfs	*ulp;
4498 	page_t		**pl;
4499 	caddr_t		pgaddr;
4500 	krw_t		rwtype;
4501 	int 		err;
4502 	int		has_holes;
4503 	int		beyond_eof;
4504 	int		seqmode;
4505 	int		pgsize = PAGESIZE;
4506 	int		dolock;
4507 	int		do_qlock;
4508 	int		trans_size;
4509 
4510 	ASSERT((uoff & PAGEOFFSET) == 0);
4511 
4512 	if (protp)
4513 		*protp = PROT_ALL;
4514 
4515 	/*
4516 	 * Obey the lockfs protocol
4517 	 */
4518 	err = ufs_lockfs_begin_getpage(ufsvfsp, &ulp, seg,
4519 	    rw == S_READ || rw == S_EXEC, protp);
4520 	if (err)
4521 		goto out;
4522 
4523 	fs = ufsvfsp->vfs_fs;
4524 
4525 	if (ulp && (rw == S_CREATE || rw == S_WRITE) &&
4526 	    !(vp->v_flag & VISSWAP)) {
4527 		/*
4528 		 * Try to start a transaction, will return if blocking is
4529 		 * expected to occur and the address space is not the
4530 		 * kernel address space.
4531 		 */
4532 		trans_size = TOP_GETPAGE_SIZE(ip);
4533 		if (seg->s_as != &kas) {
4534 			TRANS_TRY_BEGIN_ASYNC(ufsvfsp, TOP_GETPAGE,
4535 			    trans_size, err)
4536 			if (err == EWOULDBLOCK) {
4537 				/*
4538 				 * Use EDEADLK here because the VM code
4539 				 * can normally never see this error.
4540 				 */
4541 				err = EDEADLK;
4542 				ufs_lockfs_end(ulp);
4543 				goto out;
4544 			}
4545 		} else {
4546 			TRANS_BEGIN_ASYNC(ufsvfsp, TOP_GETPAGE, trans_size);
4547 		}
4548 	}
4549 
4550 	if (vp->v_flag & VNOMAP) {
4551 		err = ENOSYS;
4552 		goto unlock;
4553 	}
4554 
4555 	seqmode = ip->i_nextr == uoff && rw != S_CREATE;
4556 
4557 	rwtype = RW_READER;		/* start as a reader */
4558 	dolock = (rw_owner(&ip->i_contents) != curthread);
4559 	/*
4560 	 * If this thread owns the lock, i.e., this thread grabbed it
4561 	 * as writer somewhere above, then we don't need to grab the
4562 	 * lock as reader in this routine.
4563 	 */
4564 	do_qlock = (rw_owner(&ufsvfsp->vfs_dqrwlock) != curthread);
4565 
4566 retrylock:
4567 	if (dolock) {
4568 		/*
4569 		 * Grab the quota lock if we need to call
4570 		 * bmap_write() below (with i_contents as writer).
4571 		 */
4572 		if (do_qlock && rwtype == RW_WRITER)
4573 			rw_enter(&ufsvfsp->vfs_dqrwlock, RW_READER);
4574 		rw_enter(&ip->i_contents, rwtype);
4575 	}
4576 
4577 	/*
4578 	 * We may be getting called as a side effect of a bmap using
4579 	 * fbread() when the blocks might be being allocated and the
4580 	 * size has not yet been up'ed.  In this case we want to be
4581 	 * able to return zero pages if we get back UFS_HOLE from
4582 	 * calling bmap for a non write case here.  We also might have
4583 	 * to read some frags from the disk into a page if we are
4584 	 * extending the number of frags for a given lbn in bmap().
4585 	 * Large Files: The read of i_size here is atomic because
4586 	 * i_contents is held here. If dolock is zero, the lock
4587 	 * is held in bmap routines.
4588 	 */
4589 	beyond_eof = uoff + len >
4590 	    ((ip->i_size + PAGEOFFSET) & (uintptr_t)PAGEMASK);
4591 	if (beyond_eof && seg != segkmap) {
4592 		if (dolock) {
4593 			rw_exit(&ip->i_contents);
4594 			if (do_qlock && rwtype == RW_WRITER)
4595 				rw_exit(&ufsvfsp->vfs_dqrwlock);
4596 		}
4597 		err = EFAULT;
4598 		goto unlock;
4599 	}
4600 
4601 	/*
4602 	 * Must hold i_contents lock throughout the call to pvn_getpages
4603 	 * since locked pages are returned from each call to ufs_getapage.
4604 	 * Must *not* return locked pages and then try for contents lock
4605 	 * due to lock ordering requirements (inode > page)
4606 	 */
4607 
4608 	has_holes = bmap_has_holes(ip);
4609 
4610 	if ((rw == S_WRITE || rw == S_CREATE) && has_holes && !beyond_eof) {
4611 		int	blk_size;
4612 		u_offset_t offset;
4613 
4614 		/*
4615 		 * We must acquire the RW_WRITER lock in order to
4616 		 * call bmap_write().
4617 		 */
4618 		if (dolock && rwtype == RW_READER) {
4619 			rwtype = RW_WRITER;
4620 
4621 			/*
4622 			 * Grab the quota lock before
4623 			 * upgrading i_contents, but if we can't grab it
4624 			 * don't wait here due to lock order:
4625 			 * vfs_dqrwlock > i_contents.
4626 			 */
4627 			if (do_qlock &&
4628 			    rw_tryenter(&ufsvfsp->vfs_dqrwlock, RW_READER)
4629 			    == 0) {
4630 				rw_exit(&ip->i_contents);
4631 				goto retrylock;
4632 			}
4633 			if (!rw_tryupgrade(&ip->i_contents)) {
4634 				rw_exit(&ip->i_contents);
4635 				if (do_qlock)
4636 					rw_exit(&ufsvfsp->vfs_dqrwlock);
4637 				goto retrylock;
4638 			}
4639 		}
4640 
4641 		/*
4642 		 * May be allocating disk blocks for holes here as
4643 		 * a result of mmap faults. write(2) does the bmap_write
4644 		 * in rdip/wrip, not here. We are not dealing with frags
4645 		 * in this case.
4646 		 */
4647 		/*
4648 		 * Large Files: We cast fs_bmask field to offset_t
4649 		 * just as we do for MAXBMASK because uoff is a 64-bit
4650 		 * data type. fs_bmask will still be a 32-bit type
4651 		 * as we cannot change any ondisk data structures.
4652 		 */
4653 
4654 		offset = uoff & (offset_t)fs->fs_bmask;
4655 		while (offset < uoff + len) {
4656 			blk_size = (int)blksize(fs, ip, lblkno(fs, offset));
4657 			err = bmap_write(ip, offset, blk_size,
4658 			    BI_NORMAL, NULL, cr);
4659 			if (ip->i_flag & (ICHG|IUPD))
4660 				ip->i_seq++;
4661 			if (err)
4662 				goto update_inode;
4663 			offset += blk_size; /* XXX - make this contig */
4664 		}
4665 	}
4666 
4667 	/*
4668 	 * Can be a reader from now on.
4669 	 */
4670 	if (dolock && rwtype == RW_WRITER) {
4671 		rw_downgrade(&ip->i_contents);
4672 		/*
4673 		 * We can release vfs_dqrwlock early so do it, but make
4674 		 * sure we don't try to release it again at the bottom.
4675 		 */
4676 		if (do_qlock) {
4677 			rw_exit(&ufsvfsp->vfs_dqrwlock);
4678 			do_qlock = 0;
4679 		}
4680 	}
4681 
4682 	/*
4683 	 * We remove PROT_WRITE in cases when the file has UFS holes
4684 	 * because we don't  want to call bmap_read() to check each
4685 	 * page if it is backed with a disk block.
4686 	 */
4687 	if (protp && has_holes && rw != S_WRITE && rw != S_CREATE)
4688 		*protp &= ~PROT_WRITE;
4689 
4690 	err = 0;
4691 
4692 	/*
4693 	 * The loop looks up pages in the range [off, off + len).
4694 	 * For each page, we first check if we should initiate an asynchronous
4695 	 * read ahead before we call page_lookup (we may sleep in page_lookup
4696 	 * for a previously initiated disk read).
4697 	 */
4698 	eoff = (uoff + len);
4699 	for (pgoff = uoff, pgaddr = addr, pl = plarr;
4700 	    pgoff < eoff; /* empty */) {
4701 		page_t	*pp;
4702 		u_offset_t	nextrio;
4703 		se_t	se;
4704 		int retval;
4705 
4706 		se = ((rw == S_CREATE || rw == S_OTHER) ? SE_EXCL : SE_SHARED);
4707 
4708 		/* Handle async getpage (faultahead) */
4709 		if (plarr == NULL) {
4710 			ip->i_nextrio = pgoff;
4711 			(void) ufs_getpage_ra(vp, pgoff, seg, pgaddr);
4712 			pgoff += pgsize;
4713 			pgaddr += pgsize;
4714 			continue;
4715 		}
4716 		/*
4717 		 * Check if we should initiate read ahead of next cluster.
4718 		 * We call page_exists only when we need to confirm that
4719 		 * we have the current page before we initiate the read ahead.
4720 		 */
4721 		nextrio = ip->i_nextrio;
4722 		if (seqmode &&
4723 		    pgoff + CLUSTSZ(ip) >= nextrio && pgoff <= nextrio &&
4724 		    nextrio < ip->i_size && page_exists(vp, pgoff)) {
4725 			retval = ufs_getpage_ra(vp, pgoff, seg, pgaddr);
4726 			/*
4727 			 * We always read ahead the next cluster of data
4728 			 * starting from i_nextrio. If the page (vp,nextrio)
4729 			 * is actually in core at this point, the routine
4730 			 * ufs_getpage_ra() will stop pre-fetching data
4731 			 * until we read that page in a synchronized manner
4732 			 * through ufs_getpage_miss(). So, we should increase
4733 			 * i_nextrio if the page (vp, nextrio) exists.
4734 			 */
4735 			if ((retval == 0) && page_exists(vp, nextrio)) {
4736 				ip->i_nextrio = nextrio + pgsize;
4737 			}
4738 		}
4739 
4740 		if ((pp = page_lookup(vp, pgoff, se)) != NULL) {
4741 			/*
4742 			 * We found the page in the page cache.
4743 			 */
4744 			*pl++ = pp;
4745 			pgoff += pgsize;
4746 			pgaddr += pgsize;
4747 			len -= pgsize;
4748 			plsz -= pgsize;
4749 		} else  {
4750 			/*
4751 			 * We have to create the page, or read it from disk.
4752 			 */
4753 			if (err = ufs_getpage_miss(vp, pgoff, len, seg, pgaddr,
4754 			    pl, plsz, rw, seqmode))
4755 				goto error;
4756 
4757 			while (*pl != NULL) {
4758 				pl++;
4759 				pgoff += pgsize;
4760 				pgaddr += pgsize;
4761 				len -= pgsize;
4762 				plsz -= pgsize;
4763 			}
4764 		}
4765 	}
4766 
4767 	/*
4768 	 * Return pages up to plsz if they are in the page cache.
4769 	 * We cannot return pages if there is a chance that they are
4770 	 * backed with a UFS hole and rw is S_WRITE or S_CREATE.
4771 	 */
4772 	if (plarr && !(has_holes && (rw == S_WRITE || rw == S_CREATE))) {
4773 
4774 		ASSERT((protp == NULL) ||
4775 		    !(has_holes && (*protp & PROT_WRITE)));
4776 
4777 		eoff = pgoff + plsz;
4778 		while (pgoff < eoff) {
4779 			page_t		*pp;
4780 
4781 			if ((pp = page_lookup_nowait(vp, pgoff,
4782 			    SE_SHARED)) == NULL)
4783 				break;
4784 
4785 			*pl++ = pp;
4786 			pgoff += pgsize;
4787 			plsz -= pgsize;
4788 		}
4789 	}
4790 
4791 	if (plarr)
4792 		*pl = NULL;			/* Terminate page list */
4793 	ip->i_nextr = pgoff;
4794 
4795 error:
4796 	if (err && plarr) {
4797 		/*
4798 		 * Release any pages we have locked.
4799 		 */
4800 		while (pl > &plarr[0])
4801 			page_unlock(*--pl);
4802 
4803 		plarr[0] = NULL;
4804 	}
4805 
4806 update_inode:
4807 	/*
4808 	 * If the inode is not already marked for IACC (in rdip() for read)
4809 	 * and the inode is not marked for no access time update (in wrip()
4810 	 * for write) then update the inode access time and mod time now.
4811 	 */
4812 	if ((ip->i_flag & (IACC | INOACC)) == 0) {
4813 		if ((rw != S_OTHER) && (ip->i_mode & IFMT) != IFDIR) {
4814 			if (!ULOCKFS_IS_NOIACC(ITOUL(ip)) &&
4815 			    (fs->fs_ronly == 0) &&
4816 			    (!ufsvfsp->vfs_noatime)) {
4817 				mutex_enter(&ip->i_tlock);
4818 				ip->i_flag |= IACC;
4819 				ITIMES_NOLOCK(ip);
4820 				mutex_exit(&ip->i_tlock);
4821 			}
4822 		}
4823 	}
4824 
4825 	if (dolock) {
4826 		rw_exit(&ip->i_contents);
4827 		if (do_qlock && rwtype == RW_WRITER)
4828 			rw_exit(&ufsvfsp->vfs_dqrwlock);
4829 	}
4830 
4831 unlock:
4832 	if (ulp) {
4833 		if ((rw == S_CREATE || rw == S_WRITE) &&
4834 		    !(vp->v_flag & VISSWAP)) {
4835 			TRANS_END_ASYNC(ufsvfsp, TOP_GETPAGE, trans_size);
4836 		}
4837 		ufs_lockfs_end(ulp);
4838 	}
4839 out:
4840 	return (err);
4841 }
4842 
4843 /*
4844  * ufs_getpage_miss is called when ufs_getpage missed the page in the page
4845  * cache. The page is either read from the disk, or it's created.
4846  * A page is created (without disk read) if rw == S_CREATE, or if
4847  * the page is not backed with a real disk block (UFS hole).
4848  */
4849 /* ARGSUSED */
4850 static int
4851 ufs_getpage_miss(struct vnode *vp, u_offset_t off, size_t len, struct seg *seg,
4852 	caddr_t addr, page_t *pl[], size_t plsz, enum seg_rw rw, int seq)
4853 {
4854 	struct inode	*ip = VTOI(vp);
4855 	page_t		*pp;
4856 	daddr_t		bn;
4857 	size_t		io_len;
4858 	int		crpage = 0;
4859 	int		err;
4860 	int		contig;
4861 	int		bsize = ip->i_fs->fs_bsize;
4862 
4863 	/*
4864 	 * Figure out whether the page can be created, or must be
4865 	 * must be read from the disk.
4866 	 */
4867 	if (rw == S_CREATE)
4868 		crpage = 1;
4869 	else {
4870 		contig = 0;
4871 		if (err = bmap_read(ip, off, &bn, &contig))
4872 			return (err);
4873 
4874 		crpage = (bn == UFS_HOLE);
4875 
4876 		/*
4877 		 * If its also a fallocated block that hasn't been written to
4878 		 * yet, we will treat it just like a UFS_HOLE and create
4879 		 * a zero page for it
4880 		 */
4881 		if (ISFALLOCBLK(ip, bn))
4882 			crpage = 1;
4883 	}
4884 
4885 	if (crpage) {
4886 		if ((pp = page_create_va(vp, off, PAGESIZE, PG_WAIT, seg,
4887 		    addr)) == NULL) {
4888 			return (ufs_fault(vp,
4889 			    "ufs_getpage_miss: page_create == NULL"));
4890 		}
4891 
4892 		if (rw != S_CREATE)
4893 			pagezero(pp, 0, PAGESIZE);
4894 
4895 		io_len = PAGESIZE;
4896 	} else {
4897 		u_offset_t	io_off;
4898 		uint_t	xlen;
4899 		struct buf	*bp;
4900 		ufsvfs_t	*ufsvfsp = ip->i_ufsvfs;
4901 
4902 		/*
4903 		 * If access is not in sequential order, we read from disk
4904 		 * in bsize units.
4905 		 *
4906 		 * We limit the size of the transfer to bsize if we are reading
4907 		 * from the beginning of the file. Note in this situation we
4908 		 * will hedge our bets and initiate an async read ahead of
4909 		 * the second block.
4910 		 */
4911 		if (!seq || off == 0)
4912 			contig = MIN(contig, bsize);
4913 
4914 		pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
4915 		    &io_len, off, contig, 0);
4916 
4917 		/*
4918 		 * Some other thread has entered the page.
4919 		 * ufs_getpage will retry page_lookup.
4920 		 */
4921 		if (pp == NULL) {
4922 			pl[0] = NULL;
4923 			return (0);
4924 		}
4925 
4926 		/*
4927 		 * Zero part of the page which we are not
4928 		 * going to read from the disk.
4929 		 */
4930 		xlen = io_len & PAGEOFFSET;
4931 		if (xlen != 0)
4932 			pagezero(pp->p_prev, xlen, PAGESIZE - xlen);
4933 
4934 		bp = pageio_setup(pp, io_len, ip->i_devvp, B_READ);
4935 		bp->b_edev = ip->i_dev;
4936 		bp->b_dev = cmpdev(ip->i_dev);
4937 		bp->b_blkno = bn;
4938 		bp->b_un.b_addr = (caddr_t)0;
4939 		bp->b_file = ip->i_vnode;
4940 		bp->b_offset = off;
4941 
4942 		if (ufsvfsp->vfs_log) {
4943 			lufs_read_strategy(ufsvfsp->vfs_log, bp);
4944 		} else if (ufsvfsp->vfs_snapshot) {
4945 			fssnap_strategy(&ufsvfsp->vfs_snapshot, bp);
4946 		} else {
4947 			ufsvfsp->vfs_iotstamp = lbolt;
4948 			ub.ub_getpages.value.ul++;
4949 			(void) bdev_strategy(bp);
4950 			lwp_stat_update(LWP_STAT_INBLK, 1);
4951 		}
4952 
4953 		ip->i_nextrio = off + ((io_len + PAGESIZE - 1) & PAGEMASK);
4954 
4955 		/*
4956 		 * If the file access is sequential, initiate read ahead
4957 		 * of the next cluster.
4958 		 */
4959 		if (seq && ip->i_nextrio < ip->i_size)
4960 			(void) ufs_getpage_ra(vp, off, seg, addr);
4961 		err = biowait(bp);
4962 		pageio_done(bp);
4963 
4964 		if (err) {
4965 			pvn_read_done(pp, B_ERROR);
4966 			return (err);
4967 		}
4968 	}
4969 
4970 	pvn_plist_init(pp, pl, plsz, off, io_len, rw);
4971 	return (0);
4972 }
4973 
4974 /*
4975  * Read ahead a cluster from the disk. Returns the length in bytes.
4976  */
4977 static int
4978 ufs_getpage_ra(struct vnode *vp, u_offset_t off, struct seg *seg, caddr_t addr)
4979 {
4980 	struct inode	*ip = VTOI(vp);
4981 	page_t		*pp;
4982 	u_offset_t	io_off = ip->i_nextrio;
4983 	ufsvfs_t	*ufsvfsp;
4984 	caddr_t		addr2 = addr + (io_off - off);
4985 	struct buf	*bp;
4986 	daddr_t		bn;
4987 	size_t		io_len;
4988 	int		err;
4989 	int		contig;
4990 	int		xlen;
4991 	int		bsize = ip->i_fs->fs_bsize;
4992 
4993 	/*
4994 	 * If the directio advisory is in effect on this file,
4995 	 * then do not do buffered read ahead. Read ahead makes
4996 	 * it more difficult on threads using directio as they
4997 	 * will be forced to flush the pages from this vnode.
4998 	 */
4999 	if ((ufsvfsp = ip->i_ufsvfs) == NULL)
5000 		return (0);
5001 	if (ip->i_flag & IDIRECTIO || ufsvfsp->vfs_forcedirectio)
5002 		return (0);
5003 
5004 	/*
5005 	 * Is this test needed?
5006 	 */
5007 	if (addr2 >= seg->s_base + seg->s_size)
5008 		return (0);
5009 
5010 	contig = 0;
5011 	err = bmap_read(ip, io_off, &bn, &contig);
5012 	/*
5013 	 * If its a UFS_HOLE or a fallocated block, do not perform
5014 	 * any read ahead's since there probably is nothing to read ahead
5015 	 */
5016 	if (err || bn == UFS_HOLE || ISFALLOCBLK(ip, bn))
5017 		return (0);
5018 
5019 	/*
5020 	 * Limit the transfer size to bsize if this is the 2nd block.
5021 	 */
5022 	if (io_off == (u_offset_t)bsize)
5023 		contig = MIN(contig, bsize);
5024 
5025 	if ((pp = pvn_read_kluster(vp, io_off, seg, addr2, &io_off,
5026 	    &io_len, io_off, contig, 1)) == NULL)
5027 		return (0);
5028 
5029 	/*
5030 	 * Zero part of page which we are not going to read from disk
5031 	 */
5032 	if ((xlen = (io_len & PAGEOFFSET)) > 0)
5033 		pagezero(pp->p_prev, xlen, PAGESIZE - xlen);
5034 
5035 	ip->i_nextrio = (io_off + io_len + PAGESIZE - 1) & PAGEMASK;
5036 
5037 	bp = pageio_setup(pp, io_len, ip->i_devvp, B_READ | B_ASYNC);
5038 	bp->b_edev = ip->i_dev;
5039 	bp->b_dev = cmpdev(ip->i_dev);
5040 	bp->b_blkno = bn;
5041 	bp->b_un.b_addr = (caddr_t)0;
5042 	bp->b_file = ip->i_vnode;
5043 	bp->b_offset = off;
5044 
5045 	if (ufsvfsp->vfs_log) {
5046 		lufs_read_strategy(ufsvfsp->vfs_log, bp);
5047 	} else if (ufsvfsp->vfs_snapshot) {
5048 		fssnap_strategy(&ufsvfsp->vfs_snapshot, bp);
5049 	} else {
5050 		ufsvfsp->vfs_iotstamp = lbolt;
5051 		ub.ub_getras.value.ul++;
5052 		(void) bdev_strategy(bp);
5053 		lwp_stat_update(LWP_STAT_INBLK, 1);
5054 	}
5055 
5056 	return (io_len);
5057 }
5058 
5059 int	ufs_delay = 1;
5060 /*
5061  * Flags are composed of {B_INVAL, B_FREE, B_DONTNEED, B_FORCE, B_ASYNC}
5062  *
5063  * LMXXX - the inode really ought to contain a pointer to one of these
5064  * async args.  Stuff gunk in there and just hand the whole mess off.
5065  * This would replace i_delaylen, i_delayoff.
5066  */
5067 /*ARGSUSED*/
5068 static int
5069 ufs_putpage(struct vnode *vp, offset_t off, size_t len, int flags,
5070 	struct cred *cr, caller_context_t *ct)
5071 {
5072 	struct inode *ip = VTOI(vp);
5073 	int err = 0;
5074 
5075 	if (vp->v_count == 0) {
5076 		return (ufs_fault(vp, "ufs_putpage: bad v_count == 0"));
5077 	}
5078 
5079 	/*
5080 	 * XXX - Why should this check be made here?
5081 	 */
5082 	if (vp->v_flag & VNOMAP) {
5083 		err = ENOSYS;
5084 		goto errout;
5085 	}
5086 
5087 	if (ip->i_ufsvfs == NULL) {
5088 		err = EIO;
5089 		goto errout;
5090 	}
5091 
5092 	if (flags & B_ASYNC) {
5093 		if (ufs_delay && len &&
5094 		    (flags & ~(B_ASYNC|B_DONTNEED|B_FREE)) == 0) {
5095 			mutex_enter(&ip->i_tlock);
5096 			/*
5097 			 * If nobody stalled, start a new cluster.
5098 			 */
5099 			if (ip->i_delaylen == 0) {
5100 				ip->i_delayoff = off;
5101 				ip->i_delaylen = len;
5102 				mutex_exit(&ip->i_tlock);
5103 				goto errout;
5104 			}
5105 			/*
5106 			 * If we have a full cluster or they are not contig,
5107 			 * then push last cluster and start over.
5108 			 */
5109 			if (ip->i_delaylen >= CLUSTSZ(ip) ||
5110 			    ip->i_delayoff + ip->i_delaylen != off) {
5111 				u_offset_t doff;
5112 				size_t dlen;
5113 
5114 				doff = ip->i_delayoff;
5115 				dlen = ip->i_delaylen;
5116 				ip->i_delayoff = off;
5117 				ip->i_delaylen = len;
5118 				mutex_exit(&ip->i_tlock);
5119 				err = ufs_putpages(vp, doff, dlen,
5120 				    flags, cr);
5121 				/* LMXXX - flags are new val, not old */
5122 				goto errout;
5123 			}
5124 			/*
5125 			 * There is something there, it's not full, and
5126 			 * it is contig.
5127 			 */
5128 			ip->i_delaylen += len;
5129 			mutex_exit(&ip->i_tlock);
5130 			goto errout;
5131 		}
5132 		/*
5133 		 * Must have weird flags or we are not clustering.
5134 		 */
5135 	}
5136 
5137 	err = ufs_putpages(vp, off, len, flags, cr);
5138 
5139 errout:
5140 	return (err);
5141 }
5142 
5143 /*
5144  * If len == 0, do from off to EOF.
5145  *
5146  * The normal cases should be len == 0 & off == 0 (entire vp list),
5147  * len == MAXBSIZE (from segmap_release actions), and len == PAGESIZE
5148  * (from pageout).
5149  */
5150 /*ARGSUSED*/
5151 static int
5152 ufs_putpages(
5153 	struct vnode *vp,
5154 	offset_t off,
5155 	size_t len,
5156 	int flags,
5157 	struct cred *cr)
5158 {
5159 	u_offset_t io_off;
5160 	u_offset_t eoff;
5161 	struct inode *ip = VTOI(vp);
5162 	page_t *pp;
5163 	size_t io_len;
5164 	int err = 0;
5165 	int dolock;
5166 
5167 	if (vp->v_count == 0)
5168 		return (ufs_fault(vp, "ufs_putpages: v_count == 0"));
5169 	/*
5170 	 * Acquire the readers/write inode lock before locking
5171 	 * any pages in this inode.
5172 	 * The inode lock is held during i/o.
5173 	 */
5174 	if (len == 0) {
5175 		mutex_enter(&ip->i_tlock);
5176 		ip->i_delayoff = ip->i_delaylen = 0;
5177 		mutex_exit(&ip->i_tlock);
5178 	}
5179 	dolock = (rw_owner(&ip->i_contents) != curthread);
5180 	if (dolock) {
5181 		/*
5182 		 * Must synchronize this thread and any possible thread
5183 		 * operating in the window of vulnerability in wrip().
5184 		 * It is dangerous to allow both a thread doing a putpage
5185 		 * and a thread writing, so serialize them.  The exception
5186 		 * is when the thread in wrip() does something which causes
5187 		 * a putpage operation.  Then, the thread must be allowed
5188 		 * to continue.  It may encounter a bmap_read problem in
5189 		 * ufs_putapage, but that is handled in ufs_putapage.
5190 		 * Allow async writers to proceed, we don't want to block
5191 		 * the pageout daemon.
5192 		 */
5193 		if (ip->i_writer == curthread)
5194 			rw_enter(&ip->i_contents, RW_READER);
5195 		else {
5196 			for (;;) {
5197 				rw_enter(&ip->i_contents, RW_READER);
5198 				mutex_enter(&ip->i_tlock);
5199 				/*
5200 				 * If there is no thread in the critical
5201 				 * section of wrip(), then proceed.
5202 				 * Otherwise, wait until there isn't one.
5203 				 */
5204 				if (ip->i_writer == NULL) {
5205 					mutex_exit(&ip->i_tlock);
5206 					break;
5207 				}
5208 				rw_exit(&ip->i_contents);
5209 				/*
5210 				 * Bounce async writers when we have a writer
5211 				 * working on this file so we don't deadlock
5212 				 * the pageout daemon.
5213 				 */
5214 				if (flags & B_ASYNC) {
5215 					mutex_exit(&ip->i_tlock);
5216 					return (0);
5217 				}
5218 				cv_wait(&ip->i_wrcv, &ip->i_tlock);
5219 				mutex_exit(&ip->i_tlock);
5220 			}
5221 		}
5222 	}
5223 
5224 	if (!vn_has_cached_data(vp)) {
5225 		if (dolock)
5226 			rw_exit(&ip->i_contents);
5227 		return (0);
5228 	}
5229 
5230 	if (len == 0) {
5231 		/*
5232 		 * Search the entire vp list for pages >= off.
5233 		 */
5234 		err = pvn_vplist_dirty(vp, (u_offset_t)off, ufs_putapage,
5235 		    flags, cr);
5236 	} else {
5237 		/*
5238 		 * Loop over all offsets in the range looking for
5239 		 * pages to deal with.
5240 		 */
5241 		if ((eoff = blkroundup(ip->i_fs, ip->i_size)) != 0)
5242 			eoff = MIN(off + len, eoff);
5243 		else
5244 			eoff = off + len;
5245 
5246 		for (io_off = off; io_off < eoff; io_off += io_len) {
5247 			/*
5248 			 * If we are not invalidating, synchronously
5249 			 * freeing or writing pages, use the routine
5250 			 * page_lookup_nowait() to prevent reclaiming
5251 			 * them from the free list.
5252 			 */
5253 			if ((flags & B_INVAL) || ((flags & B_ASYNC) == 0)) {
5254 				pp = page_lookup(vp, io_off,
5255 				    (flags & (B_INVAL | B_FREE)) ?
5256 				    SE_EXCL : SE_SHARED);
5257 			} else {
5258 				pp = page_lookup_nowait(vp, io_off,
5259 				    (flags & B_FREE) ? SE_EXCL : SE_SHARED);
5260 			}
5261 
5262 			if (pp == NULL || pvn_getdirty(pp, flags) == 0)
5263 				io_len = PAGESIZE;
5264 			else {
5265 				u_offset_t *io_offp = &io_off;
5266 
5267 				err = ufs_putapage(vp, pp, io_offp, &io_len,
5268 				    flags, cr);
5269 				if (err != 0)
5270 					break;
5271 				/*
5272 				 * "io_off" and "io_len" are returned as
5273 				 * the range of pages we actually wrote.
5274 				 * This allows us to skip ahead more quickly
5275 				 * since several pages may've been dealt
5276 				 * with by this iteration of the loop.
5277 				 */
5278 			}
5279 		}
5280 	}
5281 	if (err == 0 && off == 0 && (len == 0 || len >= ip->i_size)) {
5282 		/*
5283 		 * We have just sync'ed back all the pages on
5284 		 * the inode, turn off the IMODTIME flag.
5285 		 */
5286 		mutex_enter(&ip->i_tlock);
5287 		ip->i_flag &= ~IMODTIME;
5288 		mutex_exit(&ip->i_tlock);
5289 	}
5290 	if (dolock)
5291 		rw_exit(&ip->i_contents);
5292 	return (err);
5293 }
5294 
5295 static void
5296 ufs_iodone(buf_t *bp)
5297 {
5298 	struct inode *ip;
5299 
5300 	ASSERT((bp->b_pages->p_vnode != NULL) && !(bp->b_flags & B_READ));
5301 
5302 	bp->b_iodone = NULL;
5303 
5304 	ip = VTOI(bp->b_pages->p_vnode);
5305 
5306 	mutex_enter(&ip->i_tlock);
5307 	if (ip->i_writes >= ufs_LW) {
5308 		if ((ip->i_writes -= bp->b_bcount) <= ufs_LW)
5309 			if (ufs_WRITES)
5310 				cv_broadcast(&ip->i_wrcv); /* wake all up */
5311 	} else {
5312 		ip->i_writes -= bp->b_bcount;
5313 	}
5314 
5315 	mutex_exit(&ip->i_tlock);
5316 	iodone(bp);
5317 }
5318 
5319 /*
5320  * Write out a single page, possibly klustering adjacent
5321  * dirty pages.  The inode lock must be held.
5322  *
5323  * LMXXX - bsize < pagesize not done.
5324  */
5325 /*ARGSUSED*/
5326 int
5327 ufs_putapage(
5328 	struct vnode *vp,
5329 	page_t *pp,
5330 	u_offset_t *offp,
5331 	size_t *lenp,		/* return values */
5332 	int flags,
5333 	struct cred *cr)
5334 {
5335 	u_offset_t io_off;
5336 	u_offset_t off;
5337 	struct inode *ip = VTOI(vp);
5338 	struct ufsvfs *ufsvfsp = ip->i_ufsvfs;
5339 	struct fs *fs;
5340 	struct buf *bp;
5341 	size_t io_len;
5342 	daddr_t bn;
5343 	int err;
5344 	int contig;
5345 	int dotrans;
5346 
5347 	ASSERT(RW_LOCK_HELD(&ip->i_contents));
5348 
5349 	if (ufsvfsp == NULL) {
5350 		err = EIO;
5351 		goto out_trace;
5352 	}
5353 
5354 	fs = ip->i_fs;
5355 	ASSERT(fs->fs_ronly == 0);
5356 
5357 	/*
5358 	 * If the modified time on the inode has not already been
5359 	 * set elsewhere (e.g. for write/setattr) we set the time now.
5360 	 * This gives us approximate modified times for mmap'ed files
5361 	 * which are modified via stores in the user address space.
5362 	 */
5363 	if ((ip->i_flag & IMODTIME) == 0) {
5364 		mutex_enter(&ip->i_tlock);
5365 		ip->i_flag |= IUPD;
5366 		ip->i_seq++;
5367 		ITIMES_NOLOCK(ip);
5368 		mutex_exit(&ip->i_tlock);
5369 	}
5370 
5371 	/*
5372 	 * Align the request to a block boundry (for old file systems),
5373 	 * and go ask bmap() how contiguous things are for this file.
5374 	 */
5375 	off = pp->p_offset & (offset_t)fs->fs_bmask;	/* block align it */
5376 	contig = 0;
5377 	err = bmap_read(ip, off, &bn, &contig);
5378 	if (err)
5379 		goto out;
5380 	if (bn == UFS_HOLE) {			/* putpage never allocates */
5381 		/*
5382 		 * logging device is in error mode; simply return EIO
5383 		 */
5384 		if (TRANS_ISERROR(ufsvfsp)) {
5385 			err = EIO;
5386 			goto out;
5387 		}
5388 		/*
5389 		 * Oops, the thread in the window in wrip() did some
5390 		 * sort of operation which caused a putpage in the bad
5391 		 * range.  In this case, just return an error which will
5392 		 * cause the software modified bit on the page to set
5393 		 * and the page will get written out again later.
5394 		 */
5395 		if (ip->i_writer == curthread) {
5396 			err = EIO;
5397 			goto out;
5398 		}
5399 		/*
5400 		 * If the pager is trying to push a page in the bad range
5401 		 * just tell him to try again later when things are better.
5402 		 */
5403 		if (flags & B_ASYNC) {
5404 			err = EAGAIN;
5405 			goto out;
5406 		}
5407 		err = ufs_fault(ITOV(ip), "ufs_putapage: bn == UFS_HOLE");
5408 		goto out;
5409 	}
5410 
5411 	/*
5412 	 * If it is an fallocate'd block, reverse the negativity since
5413 	 * we are now writing to it
5414 	 */
5415 	if (ISFALLOCBLK(ip, bn)) {
5416 		err = bmap_set_bn(vp, off, dbtofsb(fs, -bn));
5417 		if (err)
5418 			goto out;
5419 
5420 		bn = -bn;
5421 	}
5422 
5423 	/*
5424 	 * Take the length (of contiguous bytes) passed back from bmap()
5425 	 * and _try_ and get a set of pages covering that extent.
5426 	 */
5427 	pp = pvn_write_kluster(vp, pp, &io_off, &io_len, off, contig, flags);
5428 
5429 	/*
5430 	 * May have run out of memory and not clustered backwards.
5431 	 * off		p_offset
5432 	 * [  pp - 1  ][   pp   ]
5433 	 * [	block		]
5434 	 * We told bmap off, so we have to adjust the bn accordingly.
5435 	 */
5436 	if (io_off > off) {
5437 		bn += btod(io_off - off);
5438 		contig -= (io_off - off);
5439 	}
5440 
5441 	/*
5442 	 * bmap was carefull to tell us the right size so use that.
5443 	 * There might be unallocated frags at the end.
5444 	 * LMXXX - bzero the end of the page?  We must be writing after EOF.
5445 	 */
5446 	if (io_len > contig) {
5447 		ASSERT(io_len - contig < fs->fs_bsize);
5448 		io_len -= (io_len - contig);
5449 	}
5450 
5451 	/*
5452 	 * Handle the case where we are writing the last page after EOF.
5453 	 *
5454 	 * XXX - just a patch for i-mt3.
5455 	 */
5456 	if (io_len == 0) {
5457 		ASSERT(pp->p_offset >=
5458 		    (u_offset_t)(roundup(ip->i_size, PAGESIZE)));
5459 		io_len = PAGESIZE;
5460 	}
5461 
5462 	bp = pageio_setup(pp, io_len, ip->i_devvp, B_WRITE | flags);
5463 
5464 	ULOCKFS_SET_MOD(ITOUL(ip));
5465 
5466 	bp->b_edev = ip->i_dev;
5467 	bp->b_dev = cmpdev(ip->i_dev);
5468 	bp->b_blkno = bn;
5469 	bp->b_un.b_addr = (caddr_t)0;
5470 	bp->b_file = ip->i_vnode;
5471 
5472 	/*
5473 	 * File contents of shadow or quota inodes are metadata, and updates
5474 	 * to these need to be put into a logging transaction. All direct
5475 	 * callers in UFS do that, but fsflush can come here _before_ the
5476 	 * normal codepath. An example would be updating ACL information, for
5477 	 * which the normal codepath would be:
5478 	 *	ufs_si_store()
5479 	 *	ufs_rdwri()
5480 	 *	wrip()
5481 	 *	segmap_release()
5482 	 *	VOP_PUTPAGE()
5483 	 * Here, fsflush can pick up the dirty page before segmap_release()
5484 	 * forces it out. If that happens, there's no transaction.
5485 	 * We therefore need to test whether a transaction exists, and if not
5486 	 * create one - for fsflush.
5487 	 */
5488 	dotrans =
5489 	    (((ip->i_mode & IFMT) == IFSHAD || ufsvfsp->vfs_qinod == ip) &&
5490 	    ((curthread->t_flag & T_DONTBLOCK) == 0) &&
5491 	    (TRANS_ISTRANS(ufsvfsp)));
5492 
5493 	if (dotrans) {
5494 		curthread->t_flag |= T_DONTBLOCK;
5495 		TRANS_BEGIN_ASYNC(ufsvfsp, TOP_PUTPAGE, TOP_PUTPAGE_SIZE(ip));
5496 	}
5497 	if (TRANS_ISTRANS(ufsvfsp)) {
5498 		if ((ip->i_mode & IFMT) == IFSHAD) {
5499 			TRANS_BUF(ufsvfsp, 0, io_len, bp, DT_SHAD);
5500 		} else if (ufsvfsp->vfs_qinod == ip) {
5501 			TRANS_DELTA(ufsvfsp, ldbtob(bn), bp->b_bcount, DT_QR,
5502 			    0, 0);
5503 		}
5504 	}
5505 	if (dotrans) {
5506 		TRANS_END_ASYNC(ufsvfsp, TOP_PUTPAGE, TOP_PUTPAGE_SIZE(ip));
5507 		curthread->t_flag &= ~T_DONTBLOCK;
5508 	}
5509 
5510 	/* write throttle */
5511 
5512 	ASSERT(bp->b_iodone == NULL);
5513 	bp->b_iodone = (int (*)())ufs_iodone;
5514 	mutex_enter(&ip->i_tlock);
5515 	ip->i_writes += bp->b_bcount;
5516 	mutex_exit(&ip->i_tlock);
5517 
5518 	if (bp->b_flags & B_ASYNC) {
5519 		if (ufsvfsp->vfs_log) {
5520 			lufs_write_strategy(ufsvfsp->vfs_log, bp);
5521 		} else if (ufsvfsp->vfs_snapshot) {
5522 			fssnap_strategy(&ufsvfsp->vfs_snapshot, bp);
5523 		} else {
5524 			ufsvfsp->vfs_iotstamp = lbolt;
5525 			ub.ub_putasyncs.value.ul++;
5526 			(void) bdev_strategy(bp);
5527 			lwp_stat_update(LWP_STAT_OUBLK, 1);
5528 		}
5529 	} else {
5530 		if (ufsvfsp->vfs_log) {
5531 			lufs_write_strategy(ufsvfsp->vfs_log, bp);
5532 		} else if (ufsvfsp->vfs_snapshot) {
5533 			fssnap_strategy(&ufsvfsp->vfs_snapshot, bp);
5534 		} else {
5535 			ufsvfsp->vfs_iotstamp = lbolt;
5536 			ub.ub_putsyncs.value.ul++;
5537 			(void) bdev_strategy(bp);
5538 			lwp_stat_update(LWP_STAT_OUBLK, 1);
5539 		}
5540 		err = biowait(bp);
5541 		pageio_done(bp);
5542 		pvn_write_done(pp, ((err) ? B_ERROR : 0) | B_WRITE | flags);
5543 	}
5544 
5545 	pp = NULL;
5546 
5547 out:
5548 	if (err != 0 && pp != NULL)
5549 		pvn_write_done(pp, B_ERROR | B_WRITE | flags);
5550 
5551 	if (offp)
5552 		*offp = io_off;
5553 	if (lenp)
5554 		*lenp = io_len;
5555 out_trace:
5556 	return (err);
5557 }
5558 
5559 uint64_t ufs_map_alock_retry_cnt;
5560 uint64_t ufs_map_lockfs_retry_cnt;
5561 
5562 /* ARGSUSED */
5563 static int
5564 ufs_map(struct vnode *vp,
5565 	offset_t off,
5566 	struct as *as,
5567 	caddr_t *addrp,
5568 	size_t len,
5569 	uchar_t prot,
5570 	uchar_t maxprot,
5571 	uint_t flags,
5572 	struct cred *cr,
5573 	caller_context_t *ct)
5574 {
5575 	struct segvn_crargs vn_a;
5576 	struct ufsvfs *ufsvfsp = VTOI(vp)->i_ufsvfs;
5577 	struct ulockfs *ulp;
5578 	int error, sig;
5579 	k_sigset_t smask;
5580 
5581 	if (vp->v_flag & VNOMAP) {
5582 		error = ENOSYS;
5583 		goto out;
5584 	}
5585 
5586 	if (off < (offset_t)0 || (offset_t)(off + len) < (offset_t)0) {
5587 		error = ENXIO;
5588 		goto out;
5589 	}
5590 
5591 	if (vp->v_type != VREG) {
5592 		error = ENODEV;
5593 		goto out;
5594 	}
5595 
5596 retry_map:
5597 	/*
5598 	 * If file is being locked, disallow mapping.
5599 	 */
5600 	if (vn_has_mandatory_locks(vp, VTOI(vp)->i_mode)) {
5601 		error = EAGAIN;
5602 		goto out;
5603 	}
5604 
5605 	as_rangelock(as);
5606 	/*
5607 	 * Note that if we are retrying (because ufs_lockfs_trybegin failed in
5608 	 * the previous attempt), some other thread could have grabbed
5609 	 * the same VA range if MAP_FIXED is set. In that case, choose_addr
5610 	 * would unmap the valid VA range, that is ok.
5611 	 */
5612 	error = choose_addr(as, addrp, len, off, ADDR_VACALIGN, flags);
5613 	if (error != 0) {
5614 		as_rangeunlock(as);
5615 		goto out;
5616 	}
5617 
5618 	/*
5619 	 * a_lock has to be acquired before entering the lockfs protocol
5620 	 * because that is the order in which pagefault works. Also we cannot
5621 	 * block on a_lock here because this waiting writer will prevent
5622 	 * further readers like ufs_read from progressing and could cause
5623 	 * deadlock between ufs_read/ufs_map/pagefault when a quiesce is
5624 	 * pending.
5625 	 */
5626 	while (!AS_LOCK_TRYENTER(as, &as->a_lock, RW_WRITER)) {
5627 		ufs_map_alock_retry_cnt++;
5628 		delay(RETRY_LOCK_DELAY);
5629 	}
5630 
5631 	/*
5632 	 * We can't hold as->a_lock and wait for lockfs to succeed because
5633 	 * the proc tools might hang on a_lock, so call ufs_lockfs_trybegin()
5634 	 * instead.
5635 	 */
5636 	if (error = ufs_lockfs_trybegin(ufsvfsp, &ulp, ULOCKFS_MAP_MASK)) {
5637 		/*
5638 		 * ufs_lockfs_trybegin() did not succeed. It is safer to give up
5639 		 * as->a_lock and wait for ulp->ul_fs_lock status to change.
5640 		 */
5641 		ufs_map_lockfs_retry_cnt++;
5642 		AS_LOCK_EXIT(as, &as->a_lock);
5643 		as_rangeunlock(as);
5644 		if (error == EIO)
5645 			goto out;
5646 
5647 		mutex_enter(&ulp->ul_lock);
5648 		while (ulp->ul_fs_lock & ULOCKFS_MAP_MASK) {
5649 			if (ULOCKFS_IS_SLOCK(ulp) || ufsvfsp->vfs_nointr) {
5650 				cv_wait(&ulp->ul_cv, &ulp->ul_lock);
5651 			} else {
5652 				sigintr(&smask, 1);
5653 				sig = cv_wait_sig(&ulp->ul_cv, &ulp->ul_lock);
5654 				sigunintr(&smask);
5655 				if (((ulp->ul_fs_lock & ULOCKFS_MAP_MASK) &&
5656 				    !sig) || ufsvfsp->vfs_dontblock) {
5657 					mutex_exit(&ulp->ul_lock);
5658 					return (EINTR);
5659 				}
5660 			}
5661 		}
5662 		mutex_exit(&ulp->ul_lock);
5663 		goto retry_map;
5664 	}
5665 
5666 	vn_a.vp = vp;
5667 	vn_a.offset = (u_offset_t)off;
5668 	vn_a.type = flags & MAP_TYPE;
5669 	vn_a.prot = prot;
5670 	vn_a.maxprot = maxprot;
5671 	vn_a.cred = cr;
5672 	vn_a.amp = NULL;
5673 	vn_a.flags = flags & ~MAP_TYPE;
5674 	vn_a.szc = 0;
5675 	vn_a.lgrp_mem_policy_flags = 0;
5676 
5677 	error = as_map_locked(as, *addrp, len, segvn_create, &vn_a);
5678 	if (ulp)
5679 		ufs_lockfs_end(ulp);
5680 	as_rangeunlock(as);
5681 out:
5682 	return (error);
5683 }
5684 
5685 /* ARGSUSED */
5686 static int
5687 ufs_addmap(struct vnode *vp,
5688 	offset_t off,
5689 	struct as *as,
5690 	caddr_t addr,
5691 	size_t	len,
5692 	uchar_t  prot,
5693 	uchar_t  maxprot,
5694 	uint_t    flags,
5695 	struct cred *cr,
5696 	caller_context_t *ct)
5697 {
5698 	struct inode *ip = VTOI(vp);
5699 
5700 	if (vp->v_flag & VNOMAP) {
5701 		return (ENOSYS);
5702 	}
5703 
5704 	mutex_enter(&ip->i_tlock);
5705 	ip->i_mapcnt += btopr(len);
5706 	mutex_exit(&ip->i_tlock);
5707 	return (0);
5708 }
5709 
5710 /*ARGSUSED*/
5711 static int
5712 ufs_delmap(struct vnode *vp, offset_t off, struct as *as, caddr_t addr,
5713 	size_t len, uint_t prot,  uint_t maxprot,  uint_t flags,
5714 	struct cred *cr, caller_context_t *ct)
5715 {
5716 	struct inode *ip = VTOI(vp);
5717 
5718 	if (vp->v_flag & VNOMAP) {
5719 		return (ENOSYS);
5720 	}
5721 
5722 	mutex_enter(&ip->i_tlock);
5723 	ip->i_mapcnt -= btopr(len); 	/* Count released mappings */
5724 	ASSERT(ip->i_mapcnt >= 0);
5725 	mutex_exit(&ip->i_tlock);
5726 	return (0);
5727 }
5728 /*
5729  * Return the answer requested to poll() for non-device files
5730  */
5731 struct pollhead ufs_pollhd;
5732 
5733 /* ARGSUSED */
5734 int
5735 ufs_poll(vnode_t *vp, short ev, int any, short *revp, struct pollhead **phpp,
5736 	caller_context_t *ct)
5737 {
5738 	struct ufsvfs	*ufsvfsp;
5739 
5740 	*revp = 0;
5741 	ufsvfsp = VTOI(vp)->i_ufsvfs;
5742 
5743 	if (!ufsvfsp) {
5744 		*revp = POLLHUP;
5745 		goto out;
5746 	}
5747 
5748 	if (ULOCKFS_IS_HLOCK(&ufsvfsp->vfs_ulockfs) ||
5749 	    ULOCKFS_IS_ELOCK(&ufsvfsp->vfs_ulockfs)) {
5750 		*revp |= POLLERR;
5751 
5752 	} else {
5753 		if ((ev & POLLOUT) && !ufsvfsp->vfs_fs->fs_ronly &&
5754 		    !ULOCKFS_IS_WLOCK(&ufsvfsp->vfs_ulockfs))
5755 			*revp |= POLLOUT;
5756 
5757 		if ((ev & POLLWRBAND) && !ufsvfsp->vfs_fs->fs_ronly &&
5758 		    !ULOCKFS_IS_WLOCK(&ufsvfsp->vfs_ulockfs))
5759 			*revp |= POLLWRBAND;
5760 
5761 		if (ev & POLLIN)
5762 			*revp |= POLLIN;
5763 
5764 		if (ev & POLLRDNORM)
5765 			*revp |= POLLRDNORM;
5766 
5767 		if (ev & POLLRDBAND)
5768 			*revp |= POLLRDBAND;
5769 	}
5770 
5771 	if ((ev & POLLPRI) && (*revp & (POLLERR|POLLHUP)))
5772 		*revp |= POLLPRI;
5773 out:
5774 	*phpp = !any && !*revp ? &ufs_pollhd : (struct pollhead *)NULL;
5775 
5776 	return (0);
5777 }
5778 
5779 /* ARGSUSED */
5780 static int
5781 ufs_l_pathconf(struct vnode *vp, int cmd, ulong_t *valp, struct cred *cr,
5782 	caller_context_t *ct)
5783 {
5784 	struct ufsvfs	*ufsvfsp = VTOI(vp)->i_ufsvfs;
5785 	struct ulockfs	*ulp = NULL;
5786 	struct inode 	*sip = NULL;
5787 	int		error;
5788 	struct inode 	*ip = VTOI(vp);
5789 	int		issync;
5790 
5791 	error = ufs_lockfs_begin(ufsvfsp, &ulp, ULOCKFS_PATHCONF_MASK);
5792 	if (error)
5793 		return (error);
5794 
5795 	switch (cmd) {
5796 		/*
5797 		 * Have to handle _PC_NAME_MAX here, because the normal way
5798 		 * [fs_pathconf() -> VOP_STATVFS() -> ufs_statvfs()]
5799 		 * results in a lock ordering reversal between
5800 		 * ufs_lockfs_{begin,end}() and
5801 		 * ufs_thread_{suspend,continue}().
5802 		 *
5803 		 * Keep in sync with ufs_statvfs().
5804 		 */
5805 	case _PC_NAME_MAX:
5806 		*valp = MAXNAMLEN;
5807 		break;
5808 
5809 	case _PC_FILESIZEBITS:
5810 		if (ufsvfsp->vfs_lfflags & UFS_LARGEFILES)
5811 			*valp = UFS_FILESIZE_BITS;
5812 		else
5813 			*valp = 32;
5814 		break;
5815 
5816 	case _PC_XATTR_EXISTS:
5817 		if (vp->v_vfsp->vfs_flag & VFS_XATTR) {
5818 
5819 			error =
5820 			    ufs_xattr_getattrdir(vp, &sip, LOOKUP_XATTR, cr);
5821 			if (error ==  0 && sip != NULL) {
5822 				/* Start transaction */
5823 				if (ulp) {
5824 					TRANS_BEGIN_CSYNC(ufsvfsp, issync,
5825 					    TOP_RMDIR, TOP_RMDIR_SIZE);
5826 				}
5827 				/*
5828 				 * Is directory empty
5829 				 */
5830 				rw_enter(&sip->i_rwlock, RW_WRITER);
5831 				rw_enter(&sip->i_contents, RW_WRITER);
5832 				if (ufs_xattrdirempty(sip,
5833 				    sip->i_number, CRED())) {
5834 					rw_enter(&ip->i_contents, RW_WRITER);
5835 					ufs_unhook_shadow(ip, sip);
5836 					rw_exit(&ip->i_contents);
5837 
5838 					*valp = 0;
5839 
5840 				} else
5841 					*valp = 1;
5842 				rw_exit(&sip->i_contents);
5843 				rw_exit(&sip->i_rwlock);
5844 				if (ulp) {
5845 					TRANS_END_CSYNC(ufsvfsp, error, issync,
5846 					    TOP_RMDIR, TOP_RMDIR_SIZE);
5847 				}
5848 				VN_RELE(ITOV(sip));
5849 			} else if (error == ENOENT) {
5850 				*valp = 0;
5851 				error = 0;
5852 			}
5853 		} else {
5854 			error = fs_pathconf(vp, cmd, valp, cr, ct);
5855 		}
5856 		break;
5857 
5858 	case _PC_ACL_ENABLED:
5859 		*valp = _ACL_ACLENT_ENABLED;
5860 		break;
5861 
5862 	case _PC_MIN_HOLE_SIZE:
5863 		*valp = (ulong_t)ip->i_fs->fs_bsize;
5864 		break;
5865 
5866 	case _PC_SATTR_ENABLED:
5867 	case _PC_SATTR_EXISTS:
5868 		*valp = vfs_has_feature(vp->v_vfsp, VFSFT_XVATTR) &&
5869 		    (vp->v_type == VREG || vp->v_type == VDIR);
5870 		break;
5871 
5872 	default:
5873 		error = fs_pathconf(vp, cmd, valp, cr, ct);
5874 	}
5875 
5876 	if (ulp != NULL) {
5877 		ufs_lockfs_end(ulp);
5878 	}
5879 	return (error);
5880 }
5881 
5882 int ufs_pageio_writes, ufs_pageio_reads;
5883 
5884 /*ARGSUSED*/
5885 static int
5886 ufs_pageio(struct vnode *vp, page_t *pp, u_offset_t io_off, size_t io_len,
5887 	int flags, struct cred *cr, caller_context_t *ct)
5888 {
5889 	struct inode *ip = VTOI(vp);
5890 	struct ufsvfs *ufsvfsp;
5891 	page_t *npp = NULL, *opp = NULL, *cpp = pp;
5892 	struct buf *bp;
5893 	daddr_t bn;
5894 	size_t done_len = 0, cur_len = 0;
5895 	int err = 0;
5896 	int contig = 0;
5897 	int dolock;
5898 	int vmpss = 0;
5899 	struct ulockfs *ulp;
5900 
5901 	if ((flags & B_READ) && pp != NULL && pp->p_vnode == vp &&
5902 	    vp->v_mpssdata != NULL) {
5903 		vmpss = 1;
5904 	}
5905 
5906 	dolock = (rw_owner(&ip->i_contents) != curthread);
5907 	/*
5908 	 * We need a better check.  Ideally, we would use another
5909 	 * vnodeops so that hlocked and forcibly unmounted file
5910 	 * systems would return EIO where appropriate and w/o the
5911 	 * need for these checks.
5912 	 */
5913 	if ((ufsvfsp = ip->i_ufsvfs) == NULL)
5914 		return (EIO);
5915 
5916 	/*
5917 	 * For vmpss (pp can be NULL) case respect the quiesce protocol.
5918 	 * ul_lock must be taken before locking pages so we can't use it here
5919 	 * if pp is non NULL because segvn already locked pages
5920 	 * SE_EXCL. Instead we rely on the fact that a forced umount or
5921 	 * applying a filesystem lock via ufs_fiolfs() will block in the
5922 	 * implicit call to ufs_flush() until we unlock the pages after the
5923 	 * return to segvn. Other ufs_quiesce() callers keep ufs_quiesce_pend
5924 	 * above 0 until they are done. We have to be careful not to increment
5925 	 * ul_vnops_cnt here after forceful unmount hlocks the file system.
5926 	 *
5927 	 * If pp is NULL use ul_lock to make sure we don't increment
5928 	 * ul_vnops_cnt after forceful unmount hlocks the file system.
5929 	 */
5930 	if (vmpss || pp == NULL) {
5931 		ulp = &ufsvfsp->vfs_ulockfs;
5932 		if (pp == NULL)
5933 			mutex_enter(&ulp->ul_lock);
5934 		if (ulp->ul_fs_lock & ULOCKFS_GETREAD_MASK) {
5935 			if (pp == NULL) {
5936 				mutex_exit(&ulp->ul_lock);
5937 			}
5938 			return (vmpss ? EIO : EINVAL);
5939 		}
5940 		atomic_add_long(&ulp->ul_vnops_cnt, 1);
5941 		if (pp == NULL)
5942 			mutex_exit(&ulp->ul_lock);
5943 		if (ufs_quiesce_pend) {
5944 			if (!atomic_add_long_nv(&ulp->ul_vnops_cnt, -1))
5945 				cv_broadcast(&ulp->ul_cv);
5946 			return (vmpss ? EIO : EINVAL);
5947 		}
5948 	}
5949 
5950 	if (dolock) {
5951 		/*
5952 		 * segvn may call VOP_PAGEIO() instead of VOP_GETPAGE() to
5953 		 * handle a fault against a segment that maps vnode pages with
5954 		 * large mappings.  Segvn creates pages and holds them locked
5955 		 * SE_EXCL during VOP_PAGEIO() call. In this case we have to
5956 		 * use rw_tryenter() to avoid a potential deadlock since in
5957 		 * lock order i_contents needs to be taken first.
5958 		 * Segvn will retry via VOP_GETPAGE() if VOP_PAGEIO() fails.
5959 		 */
5960 		if (!vmpss) {
5961 			rw_enter(&ip->i_contents, RW_READER);
5962 		} else if (!rw_tryenter(&ip->i_contents, RW_READER)) {
5963 			if (!atomic_add_long_nv(&ulp->ul_vnops_cnt, -1))
5964 				cv_broadcast(&ulp->ul_cv);
5965 			return (EDEADLK);
5966 		}
5967 	}
5968 
5969 	/*
5970 	 * Return an error to segvn because the pagefault request is beyond
5971 	 * PAGESIZE rounded EOF.
5972 	 */
5973 	if (vmpss && btopr(io_off + io_len) > btopr(ip->i_size)) {
5974 		if (dolock)
5975 			rw_exit(&ip->i_contents);
5976 		if (!atomic_add_long_nv(&ulp->ul_vnops_cnt, -1))
5977 			cv_broadcast(&ulp->ul_cv);
5978 		return (EFAULT);
5979 	}
5980 
5981 	if (pp == NULL) {
5982 		if (bmap_has_holes(ip)) {
5983 			err = ENOSYS;
5984 		} else {
5985 			err = EINVAL;
5986 		}
5987 		if (dolock)
5988 			rw_exit(&ip->i_contents);
5989 		if (!atomic_add_long_nv(&ulp->ul_vnops_cnt, -1))
5990 			cv_broadcast(&ulp->ul_cv);
5991 		return (err);
5992 	}
5993 
5994 	/*
5995 	 * Break the io request into chunks, one for each contiguous
5996 	 * stretch of disk blocks in the target file.
5997 	 */
5998 	while (done_len < io_len) {
5999 		ASSERT(cpp);
6000 		contig = 0;
6001 		if (err = bmap_read(ip, (u_offset_t)(io_off + done_len),
6002 		    &bn, &contig))
6003 			break;
6004 
6005 		if (bn == UFS_HOLE) {	/* No holey swapfiles */
6006 			if (vmpss) {
6007 				err = EFAULT;
6008 				break;
6009 			}
6010 			err = ufs_fault(ITOV(ip), "ufs_pageio: bn == UFS_HOLE");
6011 			break;
6012 		}
6013 
6014 		cur_len = MIN(io_len - done_len, contig);
6015 		/*
6016 		 * Zero out a page beyond EOF, when the last block of
6017 		 * a file is a UFS fragment so that ufs_pageio() can be used
6018 		 * instead of ufs_getpage() to handle faults against
6019 		 * segvn segments that use large pages.
6020 		 */
6021 		page_list_break(&cpp, &npp, btopr(cur_len));
6022 		if ((flags & B_READ) && (cur_len & PAGEOFFSET)) {
6023 			size_t xlen = cur_len & PAGEOFFSET;
6024 			pagezero(cpp->p_prev, xlen, PAGESIZE - xlen);
6025 		}
6026 
6027 		bp = pageio_setup(cpp, cur_len, ip->i_devvp, flags);
6028 		ASSERT(bp != NULL);
6029 
6030 		bp->b_edev = ip->i_dev;
6031 		bp->b_dev = cmpdev(ip->i_dev);
6032 		bp->b_blkno = bn;
6033 		bp->b_un.b_addr = (caddr_t)0;
6034 		bp->b_file = ip->i_vnode;
6035 
6036 		ufsvfsp->vfs_iotstamp = lbolt;
6037 		ub.ub_pageios.value.ul++;
6038 		if (ufsvfsp->vfs_snapshot)
6039 			fssnap_strategy(&(ufsvfsp->vfs_snapshot), bp);
6040 		else
6041 			(void) bdev_strategy(bp);
6042 
6043 		if (flags & B_READ)
6044 			ufs_pageio_reads++;
6045 		else
6046 			ufs_pageio_writes++;
6047 		if (flags & B_READ)
6048 			lwp_stat_update(LWP_STAT_INBLK, 1);
6049 		else
6050 			lwp_stat_update(LWP_STAT_OUBLK, 1);
6051 		/*
6052 		 * If the request is not B_ASYNC, wait for i/o to complete
6053 		 * and re-assemble the page list to return to the caller.
6054 		 * If it is B_ASYNC we leave the page list in pieces and
6055 		 * cleanup() will dispose of them.
6056 		 */
6057 		if ((flags & B_ASYNC) == 0) {
6058 			err = biowait(bp);
6059 			pageio_done(bp);
6060 			if (err)
6061 				break;
6062 			page_list_concat(&opp, &cpp);
6063 		}
6064 		cpp = npp;
6065 		npp = NULL;
6066 		if (flags & B_READ)
6067 			cur_len = P2ROUNDUP_TYPED(cur_len, PAGESIZE, size_t);
6068 		done_len += cur_len;
6069 	}
6070 	ASSERT(err || (cpp == NULL && npp == NULL && done_len == io_len));
6071 	if (err) {
6072 		if (flags & B_ASYNC) {
6073 			/* Cleanup unprocessed parts of list */
6074 			page_list_concat(&cpp, &npp);
6075 			if (flags & B_READ)
6076 				pvn_read_done(cpp, B_ERROR);
6077 			else
6078 				pvn_write_done(cpp, B_ERROR);
6079 		} else {
6080 			/* Re-assemble list and let caller clean up */
6081 			page_list_concat(&opp, &cpp);
6082 			page_list_concat(&opp, &npp);
6083 		}
6084 	}
6085 
6086 	if (vmpss && !(ip->i_flag & IACC) && !ULOCKFS_IS_NOIACC(ulp) &&
6087 	    ufsvfsp->vfs_fs->fs_ronly == 0 && !ufsvfsp->vfs_noatime) {
6088 		mutex_enter(&ip->i_tlock);
6089 		ip->i_flag |= IACC;
6090 		ITIMES_NOLOCK(ip);
6091 		mutex_exit(&ip->i_tlock);
6092 	}
6093 
6094 	if (dolock)
6095 		rw_exit(&ip->i_contents);
6096 	if (vmpss && !atomic_add_long_nv(&ulp->ul_vnops_cnt, -1))
6097 		cv_broadcast(&ulp->ul_cv);
6098 	return (err);
6099 }
6100 
6101 /*
6102  * Called when the kernel is in a frozen state to dump data
6103  * directly to the device. It uses a private dump data structure,
6104  * set up by dump_ctl, to locate the correct disk block to which to dump.
6105  */
6106 /*ARGSUSED*/
6107 static int
6108 ufs_dump(vnode_t *vp, caddr_t addr, offset_t ldbn, offset_t dblks,
6109     caller_context_t *ct)
6110 {
6111 	u_offset_t	file_size;
6112 	struct inode    *ip = VTOI(vp);
6113 	struct fs	*fs = ip->i_fs;
6114 	daddr_t		dbn, lfsbn;
6115 	int		disk_blks = fs->fs_bsize >> DEV_BSHIFT;
6116 	int		error = 0;
6117 	int		ndbs, nfsbs;
6118 
6119 	/*
6120 	 * forced unmount case
6121 	 */
6122 	if (ip->i_ufsvfs == NULL)
6123 		return (EIO);
6124 	/*
6125 	 * Validate the inode that it has not been modified since
6126 	 * the dump structure is allocated.
6127 	 */
6128 	mutex_enter(&ip->i_tlock);
6129 	if ((dump_info == NULL) ||
6130 	    (dump_info->ip != ip) ||
6131 	    (dump_info->time.tv_sec != ip->i_mtime.tv_sec) ||
6132 	    (dump_info->time.tv_usec != ip->i_mtime.tv_usec)) {
6133 		mutex_exit(&ip->i_tlock);
6134 		return (-1);
6135 	}
6136 	mutex_exit(&ip->i_tlock);
6137 
6138 	/*
6139 	 * See that the file has room for this write
6140 	 */
6141 	UFS_GET_ISIZE(&file_size, ip);
6142 
6143 	if (ldbtob(ldbn + dblks) > file_size)
6144 		return (ENOSPC);
6145 
6146 	/*
6147 	 * Find the physical disk block numbers from the dump
6148 	 * private data structure directly and write out the data
6149 	 * in contiguous block lumps
6150 	 */
6151 	while (dblks > 0 && !error) {
6152 		lfsbn = (daddr_t)lblkno(fs, ldbtob(ldbn));
6153 		dbn = fsbtodb(fs, dump_info->dblk[lfsbn]) + ldbn % disk_blks;
6154 		nfsbs = 1;
6155 		ndbs = disk_blks - ldbn % disk_blks;
6156 		while (ndbs < dblks && fsbtodb(fs, dump_info->dblk[lfsbn +
6157 		    nfsbs]) == dbn + ndbs) {
6158 			nfsbs++;
6159 			ndbs += disk_blks;
6160 		}
6161 		if (ndbs > dblks)
6162 			ndbs = dblks;
6163 		error = bdev_dump(ip->i_dev, addr, dbn, ndbs);
6164 		addr += ldbtob((offset_t)ndbs);
6165 		dblks -= ndbs;
6166 		ldbn += ndbs;
6167 	}
6168 	return (error);
6169 
6170 }
6171 
6172 /*
6173  * Prepare the file system before and after the dump operation.
6174  *
6175  * action = DUMP_ALLOC:
6176  * Preparation before dump, allocate dump private data structure
6177  * to hold all the direct and indirect block info for dump.
6178  *
6179  * action = DUMP_FREE:
6180  * Clean up after dump, deallocate the dump private data structure.
6181  *
6182  * action = DUMP_SCAN:
6183  * Scan dump_info for *blkp DEV_BSIZE blocks of contig fs space;
6184  * if found, the starting file-relative DEV_BSIZE lbn is written
6185  * to *bklp; that lbn is intended for use with VOP_DUMP()
6186  */
6187 /*ARGSUSED*/
6188 static int
6189 ufs_dumpctl(vnode_t *vp, int action, offset_t *blkp, caller_context_t *ct)
6190 {
6191 	struct inode	*ip = VTOI(vp);
6192 	ufsvfs_t	*ufsvfsp = ip->i_ufsvfs;
6193 	struct fs	*fs;
6194 	daddr32_t	*dblk, *storeblk;
6195 	daddr32_t	*nextblk, *endblk;
6196 	struct buf	*bp;
6197 	int		i, entry, entries;
6198 	int		n, ncontig;
6199 
6200 	/*
6201 	 * check for forced unmount
6202 	 */
6203 	if (ufsvfsp == NULL)
6204 		return (EIO);
6205 
6206 	if (action == DUMP_ALLOC) {
6207 		/*
6208 		 * alloc and record dump_info
6209 		 */
6210 		if (dump_info != NULL)
6211 			return (EINVAL);
6212 
6213 		ASSERT(vp->v_type == VREG);
6214 		fs = ufsvfsp->vfs_fs;
6215 
6216 		rw_enter(&ip->i_contents, RW_READER);
6217 
6218 		if (bmap_has_holes(ip)) {
6219 			rw_exit(&ip->i_contents);
6220 			return (EFAULT);
6221 		}
6222 
6223 		/*
6224 		 * calculate and allocate space needed according to i_size
6225 		 */
6226 		entries = (int)lblkno(fs, blkroundup(fs, ip->i_size));
6227 		dump_info = kmem_alloc(sizeof (struct dump) +
6228 		    (entries - 1) * sizeof (daddr32_t), KM_NOSLEEP);
6229 		if (dump_info == NULL) {
6230 			rw_exit(&ip->i_contents);
6231 			return (ENOMEM);
6232 		}
6233 
6234 		/* Start saving the info */
6235 		dump_info->fsbs = entries;
6236 		dump_info->ip = ip;
6237 		storeblk = &dump_info->dblk[0];
6238 
6239 		/* Direct Blocks */
6240 		for (entry = 0; entry < NDADDR && entry < entries; entry++)
6241 			*storeblk++ = ip->i_db[entry];
6242 
6243 		/* Indirect Blocks */
6244 		for (i = 0; i < NIADDR; i++) {
6245 			int error = 0;
6246 
6247 			bp = UFS_BREAD(ufsvfsp,
6248 			    ip->i_dev, fsbtodb(fs, ip->i_ib[i]), fs->fs_bsize);
6249 			if (bp->b_flags & B_ERROR)
6250 				error = EIO;
6251 			else {
6252 				dblk = bp->b_un.b_daddr;
6253 				if ((storeblk = save_dblks(ip, ufsvfsp,
6254 				    storeblk, dblk, i, entries)) == NULL)
6255 					error = EIO;
6256 			}
6257 
6258 			brelse(bp);
6259 
6260 			if (error != 0) {
6261 				kmem_free(dump_info, sizeof (struct dump) +
6262 				    (entries - 1) * sizeof (daddr32_t));
6263 				rw_exit(&ip->i_contents);
6264 				dump_info = NULL;
6265 				return (error);
6266 			}
6267 		}
6268 		/* and time stamp the information */
6269 		mutex_enter(&ip->i_tlock);
6270 		dump_info->time = ip->i_mtime;
6271 		mutex_exit(&ip->i_tlock);
6272 
6273 		rw_exit(&ip->i_contents);
6274 	} else if (action == DUMP_FREE) {
6275 		/*
6276 		 * free dump_info
6277 		 */
6278 		if (dump_info == NULL)
6279 			return (EINVAL);
6280 		entries = dump_info->fsbs - 1;
6281 		kmem_free(dump_info, sizeof (struct dump) +
6282 		    entries * sizeof (daddr32_t));
6283 		dump_info = NULL;
6284 	} else if (action == DUMP_SCAN) {
6285 		/*
6286 		 * scan dump_info
6287 		 */
6288 		if (dump_info == NULL)
6289 			return (EINVAL);
6290 
6291 		dblk = dump_info->dblk;
6292 		nextblk = dblk + 1;
6293 		endblk = dblk + dump_info->fsbs - 1;
6294 		fs = ufsvfsp->vfs_fs;
6295 		ncontig = *blkp >> (fs->fs_bshift - DEV_BSHIFT);
6296 
6297 		/*
6298 		 * scan dblk[] entries; contig fs space is found when:
6299 		 * ((current blkno + frags per block) == next blkno)
6300 		 */
6301 		n = 0;
6302 		while (n < ncontig && dblk < endblk) {
6303 			if ((*dblk + fs->fs_frag) == *nextblk)
6304 				n++;
6305 			else
6306 				n = 0;
6307 			dblk++;
6308 			nextblk++;
6309 		}
6310 
6311 		/*
6312 		 * index is where size bytes of contig space begins;
6313 		 * conversion from index to the file's DEV_BSIZE lbn
6314 		 * is equivalent to:  (index * fs_bsize) / DEV_BSIZE
6315 		 */
6316 		if (n == ncontig) {
6317 			i = (dblk - dump_info->dblk) - ncontig;
6318 			*blkp = i << (fs->fs_bshift - DEV_BSHIFT);
6319 		} else
6320 			return (EFAULT);
6321 	}
6322 	return (0);
6323 }
6324 
6325 /*
6326  * Recursive helper function for ufs_dumpctl().  It follows the indirect file
6327  * system  blocks until it reaches the the disk block addresses, which are
6328  * then stored into the given buffer, storeblk.
6329  */
6330 static daddr32_t *
6331 save_dblks(struct inode *ip, struct ufsvfs *ufsvfsp,  daddr32_t *storeblk,
6332     daddr32_t *dblk, int level, int entries)
6333 {
6334 	struct fs	*fs = ufsvfsp->vfs_fs;
6335 	struct buf	*bp;
6336 	int		i;
6337 
6338 	if (level == 0) {
6339 		for (i = 0; i < NINDIR(fs); i++) {
6340 			if (storeblk - dump_info->dblk >= entries)
6341 				break;
6342 			*storeblk++ = dblk[i];
6343 		}
6344 		return (storeblk);
6345 	}
6346 	for (i = 0; i < NINDIR(fs); i++) {
6347 		if (storeblk - dump_info->dblk >= entries)
6348 			break;
6349 		bp = UFS_BREAD(ufsvfsp,
6350 		    ip->i_dev, fsbtodb(fs, dblk[i]), fs->fs_bsize);
6351 		if (bp->b_flags & B_ERROR) {
6352 			brelse(bp);
6353 			return (NULL);
6354 		}
6355 		storeblk = save_dblks(ip, ufsvfsp, storeblk, bp->b_un.b_daddr,
6356 		    level - 1, entries);
6357 		brelse(bp);
6358 
6359 		if (storeblk == NULL)
6360 			return (NULL);
6361 	}
6362 	return (storeblk);
6363 }
6364 
6365 /* ARGSUSED */
6366 static int
6367 ufs_getsecattr(struct vnode *vp, vsecattr_t *vsap, int flag,
6368 	struct cred *cr, caller_context_t *ct)
6369 {
6370 	struct inode	*ip = VTOI(vp);
6371 	struct ulockfs	*ulp;
6372 	struct ufsvfs	*ufsvfsp = ip->i_ufsvfs;
6373 	ulong_t		vsa_mask = vsap->vsa_mask;
6374 	int		err = EINVAL;
6375 
6376 	vsa_mask &= (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT);
6377 
6378 	/*
6379 	 * Only grab locks if needed - they're not needed to check vsa_mask
6380 	 * or if the mask contains no acl flags.
6381 	 */
6382 	if (vsa_mask != 0) {
6383 		if (err = ufs_lockfs_begin(ufsvfsp, &ulp,
6384 		    ULOCKFS_GETATTR_MASK))
6385 			return (err);
6386 
6387 		rw_enter(&ip->i_contents, RW_READER);
6388 		err = ufs_acl_get(ip, vsap, flag, cr);
6389 		rw_exit(&ip->i_contents);
6390 
6391 		if (ulp)
6392 			ufs_lockfs_end(ulp);
6393 	}
6394 	return (err);
6395 }
6396 
6397 /* ARGSUSED */
6398 static int
6399 ufs_setsecattr(struct vnode *vp, vsecattr_t *vsap, int flag, struct cred *cr,
6400 	caller_context_t *ct)
6401 {
6402 	struct inode	*ip = VTOI(vp);
6403 	struct ulockfs	*ulp = NULL;
6404 	struct ufsvfs	*ufsvfsp = VTOI(vp)->i_ufsvfs;
6405 	ulong_t		vsa_mask = vsap->vsa_mask;
6406 	int		err;
6407 	int		haverwlock = 1;
6408 	int		trans_size;
6409 	int		donetrans = 0;
6410 	int		retry = 1;
6411 
6412 	ASSERT(RW_LOCK_HELD(&ip->i_rwlock));
6413 
6414 	/* Abort now if the request is either empty or invalid. */
6415 	vsa_mask &= (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT);
6416 	if ((vsa_mask == 0) ||
6417 	    ((vsap->vsa_aclentp == NULL) &&
6418 	    (vsap->vsa_dfaclentp == NULL))) {
6419 		err = EINVAL;
6420 		goto out;
6421 	}
6422 
6423 	/*
6424 	 * Following convention, if this is a directory then we acquire the
6425 	 * inode's i_rwlock after starting a UFS logging transaction;
6426 	 * otherwise, we acquire it beforehand. Since we were called (and
6427 	 * must therefore return) with the lock held, we will have to drop it,
6428 	 * and later reacquire it, if operating on a directory.
6429 	 */
6430 	if (vp->v_type == VDIR) {
6431 		rw_exit(&ip->i_rwlock);
6432 		haverwlock = 0;
6433 	} else {
6434 		/* Upgrade the lock if required. */
6435 		if (!rw_write_held(&ip->i_rwlock)) {
6436 			rw_exit(&ip->i_rwlock);
6437 			rw_enter(&ip->i_rwlock, RW_WRITER);
6438 		}
6439 	}
6440 
6441 again:
6442 	ASSERT(!(vp->v_type == VDIR && haverwlock));
6443 	if (err = ufs_lockfs_begin(ufsvfsp, &ulp, ULOCKFS_SETATTR_MASK)) {
6444 		ulp = NULL;
6445 		retry = 0;
6446 		goto out;
6447 	}
6448 
6449 	/*
6450 	 * Check that the file system supports this operation. Note that
6451 	 * ufs_lockfs_begin() will have checked that the file system had
6452 	 * not been forcibly unmounted.
6453 	 */
6454 	if (ufsvfsp->vfs_fs->fs_ronly) {
6455 		err = EROFS;
6456 		goto out;
6457 	}
6458 	if (ufsvfsp->vfs_nosetsec) {
6459 		err = ENOSYS;
6460 		goto out;
6461 	}
6462 
6463 	if (ulp) {
6464 		TRANS_BEGIN_ASYNC(ufsvfsp, TOP_SETSECATTR,
6465 		    trans_size = TOP_SETSECATTR_SIZE(VTOI(vp)));
6466 		donetrans = 1;
6467 	}
6468 
6469 	if (vp->v_type == VDIR) {
6470 		rw_enter(&ip->i_rwlock, RW_WRITER);
6471 		haverwlock = 1;
6472 	}
6473 
6474 	ASSERT(haverwlock);
6475 
6476 	/* Do the actual work. */
6477 	rw_enter(&ip->i_contents, RW_WRITER);
6478 	/*
6479 	 * Suppress out of inodes messages if we will retry.
6480 	 */
6481 	if (retry)
6482 		ip->i_flag |= IQUIET;
6483 	err = ufs_acl_set(ip, vsap, flag, cr);
6484 	ip->i_flag &= ~IQUIET;
6485 	rw_exit(&ip->i_contents);
6486 
6487 out:
6488 	if (ulp) {
6489 		if (donetrans) {
6490 			/*
6491 			 * top_end_async() can eventually call
6492 			 * top_end_sync(), which can block. We must
6493 			 * therefore observe the lock-ordering protocol
6494 			 * here as well.
6495 			 */
6496 			if (vp->v_type == VDIR) {
6497 				rw_exit(&ip->i_rwlock);
6498 				haverwlock = 0;
6499 			}
6500 			TRANS_END_ASYNC(ufsvfsp, TOP_SETSECATTR, trans_size);
6501 		}
6502 		ufs_lockfs_end(ulp);
6503 	}
6504 	/*
6505 	 * If no inodes available, try scaring a logically-
6506 	 * free one out of the delete queue to someplace
6507 	 * that we can find it.
6508 	 */
6509 	if ((err == ENOSPC) && retry && TRANS_ISTRANS(ufsvfsp)) {
6510 		ufs_delete_drain_wait(ufsvfsp, 1);
6511 		retry = 0;
6512 		if (vp->v_type == VDIR && haverwlock) {
6513 			rw_exit(&ip->i_rwlock);
6514 			haverwlock = 0;
6515 		}
6516 		goto again;
6517 	}
6518 	/*
6519 	 * If we need to reacquire the lock then it is safe to do so
6520 	 * as a reader. This is because ufs_rwunlock(), which will be
6521 	 * called by our caller after we return, does not differentiate
6522 	 * between shared and exclusive locks.
6523 	 */
6524 	if (!haverwlock) {
6525 		ASSERT(vp->v_type == VDIR);
6526 		rw_enter(&ip->i_rwlock, RW_READER);
6527 	}
6528 
6529 	return (err);
6530 }
6531