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