xref: /titanic_50/usr/src/uts/common/fs/ufs/ufs_vnops.c (revision c51cb4bc539e1650eb5bb4f805cc779bfce99c06)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*	Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T	*/
27 /*	  All Rights Reserved  	*/
28 
29 /*
30  * Portions of this source code were derived from Berkeley 4.3 BSD
31  * under license from the Regents of the University of California.
32  */
33 
34 #pragma ident	"%Z%%M%	%I%	%E% SMI"
35 
36 #include <sys/types.h>
37 #include <sys/t_lock.h>
38 #include <sys/ksynch.h>
39 #include <sys/param.h>
40 #include <sys/time.h>
41 #include <sys/systm.h>
42 #include <sys/sysmacros.h>
43 #include <sys/resource.h>
44 #include <sys/signal.h>
45 #include <sys/cred.h>
46 #include <sys/user.h>
47 #include <sys/buf.h>
48 #include <sys/vfs.h>
49 #include <sys/vfs_opreg.h>
50 #include <sys/vnode.h>
51 #include <sys/proc.h>
52 #include <sys/disp.h>
53 #include <sys/file.h>
54 #include <sys/fcntl.h>
55 #include <sys/flock.h>
56 #include <sys/atomic.h>
57 #include <sys/kmem.h>
58 #include <sys/uio.h>
59 #include <sys/dnlc.h>
60 #include <sys/conf.h>
61 #include <sys/mman.h>
62 #include <sys/pathname.h>
63 #include <sys/debug.h>
64 #include <sys/vmsystm.h>
65 #include <sys/cmn_err.h>
66 #include <sys/filio.h>
67 #include <sys/policy.h>
68 
69 #include <sys/fs/ufs_fs.h>
70 #include <sys/fs/ufs_lockfs.h>
71 #include <sys/fs/ufs_filio.h>
72 #include <sys/fs/ufs_inode.h>
73 #include <sys/fs/ufs_fsdir.h>
74 #include <sys/fs/ufs_quota.h>
75 #include <sys/fs/ufs_log.h>
76 #include <sys/fs/ufs_snap.h>
77 #include <sys/fs/ufs_trans.h>
78 #include <sys/fs/ufs_panic.h>
79 #include <sys/fs/ufs_bio.h>
80 #include <sys/dirent.h>		/* must be AFTER <sys/fs/fsdir.h>! */
81 #include <sys/errno.h>
82 #include <sys/fssnap_if.h>
83 #include <sys/unistd.h>
84 #include <sys/sunddi.h>
85 
86 #include <sys/filio.h>		/* _FIOIO */
87 
88 #include <vm/hat.h>
89 #include <vm/page.h>
90 #include <vm/pvn.h>
91 #include <vm/as.h>
92 #include <vm/seg.h>
93 #include <vm/seg_map.h>
94 #include <vm/seg_vn.h>
95 #include <vm/seg_kmem.h>
96 #include <vm/rm.h>
97 #include <sys/swap.h>
98 
99 #include <fs/fs_subr.h>
100 
101 #include <sys/fs/decomp.h>
102 
103 static struct instats ins;
104 
105 static 	int ufs_getpage_ra(struct vnode *, u_offset_t, struct seg *, caddr_t);
106 static	int ufs_getpage_miss(struct vnode *, u_offset_t, size_t, struct seg *,
107 		caddr_t, struct page **, size_t, enum seg_rw, int);
108 static	int ufs_open(struct vnode **, int, struct cred *, caller_context_t *);
109 static	int ufs_close(struct vnode *, int, int, offset_t, struct cred *,
110 		caller_context_t *);
111 static	int ufs_read(struct vnode *, struct uio *, int, struct cred *,
112 		struct caller_context *);
113 static	int ufs_write(struct vnode *, struct uio *, int, struct cred *,
114 		struct caller_context *);
115 static	int ufs_ioctl(struct vnode *, int, intptr_t, int, struct cred *,
116 		int *, caller_context_t *);
117 static	int ufs_getattr(struct vnode *, struct vattr *, int, struct cred *,
118 		caller_context_t *);
119 static	int ufs_setattr(struct vnode *, struct vattr *, int, struct cred *,
120 		caller_context_t *);
121 static	int ufs_access(struct vnode *, int, int, struct cred *,
122 		caller_context_t *);
123 static	int ufs_lookup(struct vnode *, char *, struct vnode **,
124 		struct pathname *, int, struct vnode *, struct cred *,
125 		caller_context_t *, int *, pathname_t *);
126 static	int ufs_create(struct vnode *, char *, struct vattr *, enum vcexcl,
127 		int, struct vnode **, struct cred *, int,
128 		caller_context_t *, vsecattr_t  *);
129 static	int ufs_remove(struct vnode *, char *, struct cred *,
130 		caller_context_t *, int);
131 static	int ufs_link(struct vnode *, struct vnode *, char *, struct cred *,
132 		caller_context_t *, int);
133 static	int ufs_rename(struct vnode *, char *, struct vnode *, char *,
134 		struct cred *, caller_context_t *, int);
135 static	int ufs_mkdir(struct vnode *, char *, struct vattr *, struct vnode **,
136 		struct cred *, caller_context_t *, int, vsecattr_t *);
137 static	int ufs_rmdir(struct vnode *, char *, struct vnode *, struct cred *,
138 		caller_context_t *, int);
139 static	int ufs_readdir(struct vnode *, struct uio *, struct cred *, int *,
140 		caller_context_t *, int);
141 static	int ufs_symlink(struct vnode *, char *, struct vattr *, char *,
142 		struct cred *, caller_context_t *, int);
143 static	int ufs_readlink(struct vnode *, struct uio *, struct cred *,
144 		caller_context_t *);
145 static	int ufs_fsync(struct vnode *, int, struct cred *, caller_context_t *);
146 static	void ufs_inactive(struct vnode *, struct cred *, caller_context_t *);
147 static	int ufs_fid(struct vnode *, struct fid *, caller_context_t *);
148 static	int ufs_rwlock(struct vnode *, int, caller_context_t *);
149 static	void ufs_rwunlock(struct vnode *, int, caller_context_t *);
150 static	int ufs_seek(struct vnode *, offset_t, offset_t *, caller_context_t *);
151 static	int ufs_frlock(struct vnode *, int, struct flock64 *, int, offset_t,
152 		struct flk_callback *, struct cred *,
153 		caller_context_t *);
154 static  int ufs_space(struct vnode *, int, struct flock64 *, int, offset_t,
155 		cred_t *, caller_context_t *);
156 static	int ufs_getpage(struct vnode *, offset_t, size_t, uint_t *,
157 		struct page **, size_t, struct seg *, caddr_t,
158 		enum seg_rw, struct cred *, caller_context_t *);
159 static	int ufs_putpage(struct vnode *, offset_t, size_t, int, struct cred *,
160 		caller_context_t *);
161 static	int ufs_putpages(struct vnode *, offset_t, size_t, int, struct cred *);
162 static	int ufs_map(struct vnode *, offset_t, struct as *, caddr_t *, size_t,
163 		uchar_t, uchar_t, uint_t, struct cred *, caller_context_t *);
164 static	int ufs_addmap(struct vnode *, offset_t, struct as *, caddr_t,  size_t,
165 		uchar_t, uchar_t, uint_t, struct cred *, caller_context_t *);
166 static	int ufs_delmap(struct vnode *, offset_t, struct as *, caddr_t,  size_t,
167 		uint_t, uint_t, uint_t, struct cred *, caller_context_t *);
168 static	int ufs_poll(vnode_t *, short, int, short *, struct pollhead **,
169 		caller_context_t *);
170 static	int ufs_dump(vnode_t *, caddr_t, offset_t, offset_t,
171     caller_context_t *);
172 static	int ufs_l_pathconf(struct vnode *, int, ulong_t *, struct cred *,
173 		caller_context_t *);
174 static	int ufs_pageio(struct vnode *, struct page *, u_offset_t, size_t, int,
175 		struct cred *, caller_context_t *);
176 static	int ufs_dumpctl(vnode_t *, int, offset_t *, caller_context_t *);
177 static	daddr32_t *save_dblks(struct inode *, struct ufsvfs *, daddr32_t *,
178 		daddr32_t *, int, int);
179 static	int ufs_getsecattr(struct vnode *, vsecattr_t *, int, struct cred *,
180 		caller_context_t *);
181 static	int ufs_setsecattr(struct vnode *, vsecattr_t *, int, struct cred *,
182 		caller_context_t *);
183 extern int as_map_locked(struct as *, caddr_t, size_t, int ((*)()), void *);
184 
185 /*
186  * For lockfs: ulockfs begin/end is now inlined in the ufs_xxx functions.
187  *
188  * XXX - ULOCKFS in fs_pathconf and ufs_ioctl is not inlined yet.
189  */
190 struct vnodeops *ufs_vnodeops;
191 
192 /* NOTE: "not blkd" below  means that the operation isn't blocked by lockfs */
193 const fs_operation_def_t ufs_vnodeops_template[] = {
194 	VOPNAME_OPEN,		{ .vop_open = ufs_open },	/* not blkd */
195 	VOPNAME_CLOSE,		{ .vop_close = ufs_close },	/* not blkd */
196 	VOPNAME_READ,		{ .vop_read = ufs_read },
197 	VOPNAME_WRITE,		{ .vop_write = ufs_write },
198 	VOPNAME_IOCTL,		{ .vop_ioctl = ufs_ioctl },
199 	VOPNAME_GETATTR,	{ .vop_getattr = ufs_getattr },
200 	VOPNAME_SETATTR,	{ .vop_setattr = ufs_setattr },
201 	VOPNAME_ACCESS,		{ .vop_access = ufs_access },
202 	VOPNAME_LOOKUP,		{ .vop_lookup = ufs_lookup },
203 	VOPNAME_CREATE,		{ .vop_create = ufs_create },
204 	VOPNAME_REMOVE,		{ .vop_remove = ufs_remove },
205 	VOPNAME_LINK,		{ .vop_link = ufs_link },
206 	VOPNAME_RENAME,		{ .vop_rename = ufs_rename },
207 	VOPNAME_MKDIR,		{ .vop_mkdir = ufs_mkdir },
208 	VOPNAME_RMDIR,		{ .vop_rmdir = ufs_rmdir },
209 	VOPNAME_READDIR,	{ .vop_readdir = ufs_readdir },
210 	VOPNAME_SYMLINK,	{ .vop_symlink = ufs_symlink },
211 	VOPNAME_READLINK,	{ .vop_readlink = ufs_readlink },
212 	VOPNAME_FSYNC,		{ .vop_fsync = ufs_fsync },
213 	VOPNAME_INACTIVE,	{ .vop_inactive = ufs_inactive }, /* not blkd */
214 	VOPNAME_FID,		{ .vop_fid = ufs_fid },
215 	VOPNAME_RWLOCK,		{ .vop_rwlock = ufs_rwlock },	/* not blkd */
216 	VOPNAME_RWUNLOCK,	{ .vop_rwunlock = ufs_rwunlock }, /* not blkd */
217 	VOPNAME_SEEK,		{ .vop_seek = ufs_seek },
218 	VOPNAME_FRLOCK,		{ .vop_frlock = ufs_frlock },
219 	VOPNAME_SPACE,		{ .vop_space = ufs_space },
220 	VOPNAME_GETPAGE,	{ .vop_getpage = ufs_getpage },
221 	VOPNAME_PUTPAGE,	{ .vop_putpage = ufs_putpage },
222 	VOPNAME_MAP,		{ .vop_map = ufs_map },
223 	VOPNAME_ADDMAP,		{ .vop_addmap = ufs_addmap },	/* not blkd */
224 	VOPNAME_DELMAP,		{ .vop_delmap = ufs_delmap },	/* not blkd */
225 	VOPNAME_POLL,		{ .vop_poll = ufs_poll },	/* not blkd */
226 	VOPNAME_DUMP,		{ .vop_dump = ufs_dump },
227 	VOPNAME_PATHCONF,	{ .vop_pathconf = ufs_l_pathconf },
228 	VOPNAME_PAGEIO,		{ .vop_pageio = ufs_pageio },
229 	VOPNAME_DUMPCTL,	{ .vop_dumpctl = ufs_dumpctl },
230 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = ufs_getsecattr },
231 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = ufs_setsecattr },
232 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
233 	NULL,			NULL
234 };
235 
236 #define	MAX_BACKFILE_COUNT	9999
237 
238 /*
239  * Created by ufs_dumpctl() to store a file's disk block info into memory.
240  * Used by ufs_dump() to dump data to disk directly.
241  */
242 struct dump {
243 	struct inode	*ip;		/* the file we contain */
244 	daddr_t		fsbs;		/* number of blocks stored */
245 	struct timeval32 time;		/* time stamp for the struct */
246 	daddr32_t 	dblk[1];	/* place holder for block info */
247 };
248 
249 static struct dump *dump_info = NULL;
250 
251 /*
252  * Previously there was no special action required for ordinary files.
253  * (Devices are handled through the device file system.)
254  * Now we support Large Files and Large File API requires open to
255  * fail if file is large.
256  * We could take care to prevent data corruption
257  * by doing an atomic check of size and truncate if file is opened with
258  * FTRUNC flag set but traditionally this is being done by the vfs/vnode
259  * layers. So taking care of truncation here is a change in the existing
260  * semantics of VOP_OPEN and therefore we chose not to implement any thing
261  * here. The check for the size of the file > 2GB is being done at the
262  * vfs layer in routine vn_open().
263  */
264 
265 /* ARGSUSED */
266 static int
267 ufs_open(struct vnode **vpp, int flag, struct cred *cr, caller_context_t *ct)
268 {
269 	return (0);
270 }
271 
272 /*ARGSUSED*/
273 static int
274 ufs_close(struct vnode *vp, int flag, int count, offset_t offset,
275 	struct cred *cr, caller_context_t *ct)
276 {
277 	cleanlocks(vp, ttoproc(curthread)->p_pid, 0);
278 	cleanshares(vp, ttoproc(curthread)->p_pid);
279 
280 	/*
281 	 * Push partially filled cluster at last close.
282 	 * ``last close'' is approximated because the dnlc
283 	 * may have a hold on the vnode.
284 	 * Checking for VBAD here will also act as a forced umount check.
285 	 */
286 	if (vp->v_count <= 2 && vp->v_type != VBAD) {
287 		struct inode *ip = VTOI(vp);
288 		if (ip->i_delaylen) {
289 			ins.in_poc.value.ul++;
290 			(void) ufs_putpages(vp, ip->i_delayoff, ip->i_delaylen,
291 			    B_ASYNC | B_FREE, cr);
292 			ip->i_delaylen = 0;
293 		}
294 	}
295 
296 	return (0);
297 }
298 
299 /*ARGSUSED*/
300 static int
301 ufs_read(struct vnode *vp, struct uio *uiop, int ioflag, struct cred *cr,
302 	struct caller_context *ct)
303 {
304 	struct inode *ip = VTOI(vp);
305 	struct ufsvfs *ufsvfsp;
306 	struct ulockfs *ulp = NULL;
307 	int error = 0;
308 	int intrans = 0;
309 
310 	ASSERT(RW_READ_HELD(&ip->i_rwlock));
311 
312 	/*
313 	 * Mandatory locking needs to be done before ufs_lockfs_begin()
314 	 * and TRANS_BEGIN_SYNC() calls since mandatory locks can sleep.
315 	 */
316 	if (MANDLOCK(vp, ip->i_mode)) {
317 		/*
318 		 * ufs_getattr ends up being called by chklock
319 		 */
320 		error = chklock(vp, FREAD, uiop->uio_loffset,
321 		    uiop->uio_resid, uiop->uio_fmode, ct);
322 		if (error)
323 			goto out;
324 	}
325 
326 	ufsvfsp = ip->i_ufsvfs;
327 	error = ufs_lockfs_begin(ufsvfsp, &ulp, ULOCKFS_READ_MASK);
328 	if (error)
329 		goto out;
330 
331 	/*
332 	 * In the case that a directory is opened for reading as a file
333 	 * (eg "cat .") with the  O_RSYNC, O_SYNC and O_DSYNC flags set.
334 	 * The locking order had to be changed to avoid a deadlock with
335 	 * an update taking place on that directory at the same time.
336 	 */
337 	if ((ip->i_mode & IFMT) == IFDIR) {
338 
339 		rw_enter(&ip->i_contents, RW_READER);
340 		error = rdip(ip, uiop, ioflag, cr);
341 		rw_exit(&ip->i_contents);
342 
343 		if (error) {
344 			if (ulp)
345 				ufs_lockfs_end(ulp);
346 			goto out;
347 		}
348 
349 		if (ulp && (ioflag & FRSYNC) && (ioflag & (FSYNC | FDSYNC)) &&
350 		    TRANS_ISTRANS(ufsvfsp)) {
351 			rw_exit(&ip->i_rwlock);
352 			TRANS_BEGIN_SYNC(ufsvfsp, TOP_READ_SYNC, TOP_READ_SIZE,
353 			    error);
354 			ASSERT(!error);
355 			TRANS_END_SYNC(ufsvfsp, error, TOP_READ_SYNC,
356 			    TOP_READ_SIZE);
357 			rw_enter(&ip->i_rwlock, RW_READER);
358 		}
359 	} else {
360 		/*
361 		 * Only transact reads to files opened for sync-read and
362 		 * sync-write on a file system that is not write locked.
363 		 *
364 		 * The ``not write locked'' check prevents problems with
365 		 * enabling/disabling logging on a busy file system.  E.g.,
366 		 * logging exists at the beginning of the read but does not
367 		 * at the end.
368 		 *
369 		 */
370 		if (ulp && (ioflag & FRSYNC) && (ioflag & (FSYNC | FDSYNC)) &&
371 		    TRANS_ISTRANS(ufsvfsp)) {
372 			TRANS_BEGIN_SYNC(ufsvfsp, TOP_READ_SYNC, TOP_READ_SIZE,
373 			    error);
374 			ASSERT(!error);
375 			intrans = 1;
376 		}
377 
378 		rw_enter(&ip->i_contents, RW_READER);
379 		error = rdip(ip, uiop, ioflag, cr);
380 		rw_exit(&ip->i_contents);
381 
382 		if (intrans) {
383 			TRANS_END_SYNC(ufsvfsp, error, TOP_READ_SYNC,
384 			    TOP_READ_SIZE);
385 		}
386 	}
387 
388 	if (ulp) {
389 		ufs_lockfs_end(ulp);
390 	}
391 out:
392 
393 	return (error);
394 }
395 
396 extern	int	ufs_HW;		/* high water mark */
397 extern	int	ufs_LW;		/* low water mark */
398 int	ufs_WRITES = 1;		/* XXX - enable/disable */
399 int	ufs_throttles = 0;	/* throttling count */
400 int	ufs_allow_shared_writes = 1;	/* directio shared writes */
401 
402 static int
403 ufs_check_rewrite(struct inode *ip, struct uio *uiop, int ioflag)
404 {
405 	int	shared_write;
406 
407 	/*
408 	 * If the FDSYNC flag is set then ignore the global
409 	 * ufs_allow_shared_writes in this case.
410 	 */
411 	shared_write = (ioflag & FDSYNC) | ufs_allow_shared_writes;
412 
413 	/*
414 	 * Filter to determine if this request is suitable as a
415 	 * concurrent rewrite. This write must not allocate blocks
416 	 * by extending the file or filling in holes. No use trying
417 	 * through FSYNC descriptors as the inode will be synchronously
418 	 * updated after the write. The uio structure has not yet been
419 	 * checked for sanity, so assume nothing.
420 	 */
421 	return (((ip->i_mode & IFMT) == IFREG) && !(ioflag & FAPPEND) &&
422 	    (uiop->uio_loffset >= (offset_t)0) &&
423 	    (uiop->uio_loffset < ip->i_size) && (uiop->uio_resid > 0) &&
424 	    ((ip->i_size - uiop->uio_loffset) >= uiop->uio_resid) &&
425 	    !(ioflag & FSYNC) && !bmap_has_holes(ip) &&
426 	    shared_write);
427 }
428 
429 /*ARGSUSED*/
430 static int
431 ufs_write(struct vnode *vp, struct uio *uiop, int ioflag, cred_t *cr,
432 	caller_context_t *ct)
433 {
434 	struct inode *ip = VTOI(vp);
435 	struct ufsvfs *ufsvfsp;
436 	struct ulockfs *ulp;
437 	int retry = 1;
438 	int error, resv, resid = 0;
439 	int directio_status;
440 	int exclusive;
441 	int rewriteflg;
442 	long start_resid = uiop->uio_resid;
443 
444 	ASSERT(RW_LOCK_HELD(&ip->i_rwlock));
445 
446 retry_mandlock:
447 	/*
448 	 * Mandatory locking needs to be done before ufs_lockfs_begin()
449 	 * and TRANS_BEGIN_[A]SYNC() calls since mandatory locks can sleep.
450 	 * Check for forced unmounts normally done in ufs_lockfs_begin().
451 	 */
452 	if ((ufsvfsp = ip->i_ufsvfs) == NULL) {
453 		error = EIO;
454 		goto out;
455 	}
456 	if (MANDLOCK(vp, ip->i_mode)) {
457 
458 		ASSERT(RW_WRITE_HELD(&ip->i_rwlock));
459 
460 		/*
461 		 * ufs_getattr ends up being called by chklock
462 		 */
463 		error = chklock(vp, FWRITE, uiop->uio_loffset,
464 		    uiop->uio_resid, uiop->uio_fmode, ct);
465 		if (error)
466 			goto out;
467 	}
468 
469 	/* i_rwlock can change in chklock */
470 	exclusive = rw_write_held(&ip->i_rwlock);
471 	rewriteflg = ufs_check_rewrite(ip, uiop, ioflag);
472 
473 	/*
474 	 * Check for fast-path special case of directio re-writes.
475 	 */
476 	if ((ip->i_flag & IDIRECTIO || ufsvfsp->vfs_forcedirectio) &&
477 	    !exclusive && rewriteflg) {
478 
479 		error = ufs_lockfs_begin(ufsvfsp, &ulp, ULOCKFS_WRITE_MASK);
480 		if (error)
481 			goto out;
482 
483 		rw_enter(&ip->i_contents, RW_READER);
484 		error = ufs_directio_write(ip, uiop, ioflag, 1, cr,
485 		    &directio_status);
486 		if (directio_status == DIRECTIO_SUCCESS) {
487 			uint_t i_flag_save;
488 
489 			if (start_resid != uiop->uio_resid)
490 				error = 0;
491 			/*
492 			 * Special treatment of access times for re-writes.
493 			 * If IMOD is not already set, then convert it
494 			 * to IMODACC for this operation. This defers
495 			 * entering a delta into the log until the inode
496 			 * is flushed. This mimics what is done for read
497 			 * operations and inode access time.
498 			 */
499 			mutex_enter(&ip->i_tlock);
500 			i_flag_save = ip->i_flag;
501 			ip->i_flag |= IUPD | ICHG;
502 			ip->i_seq++;
503 			ITIMES_NOLOCK(ip);
504 			if ((i_flag_save & IMOD) == 0) {
505 				ip->i_flag &= ~IMOD;
506 				ip->i_flag |= IMODACC;
507 			}
508 			mutex_exit(&ip->i_tlock);
509 			rw_exit(&ip->i_contents);
510 			if (ulp)
511 				ufs_lockfs_end(ulp);
512 			goto out;
513 		}
514 		rw_exit(&ip->i_contents);
515 		if (ulp)
516 			ufs_lockfs_end(ulp);
517 	}
518 
519 	if (!exclusive && !rw_tryupgrade(&ip->i_rwlock)) {
520 		rw_exit(&ip->i_rwlock);
521 		rw_enter(&ip->i_rwlock, RW_WRITER);
522 		/*
523 		 * Mandatory locking could have been enabled
524 		 * after dropping the i_rwlock.
525 		 */
526 		if (MANDLOCK(vp, ip->i_mode))
527 			goto retry_mandlock;
528 	}
529 
530 	error = ufs_lockfs_begin(ufsvfsp, &ulp, ULOCKFS_WRITE_MASK);
531 	if (error)
532 		goto out;
533 
534 	/*
535 	 * Amount of log space needed for this write
536 	 */
537 	if (!rewriteflg || !(ioflag & FDSYNC))
538 		TRANS_WRITE_RESV(ip, uiop, ulp, &resv, &resid);
539 
540 	/*
541 	 * Throttle writes.
542 	 */
543 	if (ufs_WRITES && (ip->i_writes > ufs_HW)) {
544 		mutex_enter(&ip->i_tlock);
545 		while (ip->i_writes > ufs_HW) {
546 			ufs_throttles++;
547 			cv_wait(&ip->i_wrcv, &ip->i_tlock);
548 		}
549 		mutex_exit(&ip->i_tlock);
550 	}
551 
552 	/*
553 	 * Enter Transaction
554 	 *
555 	 * If the write is a rewrite there is no need to open a transaction
556 	 * if the FDSYNC flag is set and not the FSYNC.  In this case just
557 	 * set the IMODACC flag to modify do the update at a later time
558 	 * thus avoiding the overhead of the logging transaction that is
559 	 * not required.
560 	 */
561 	if (ioflag & (FSYNC|FDSYNC)) {
562 		if (ulp) {
563 			if (rewriteflg) {
564 				uint_t i_flag_save;
565 
566 				rw_enter(&ip->i_contents, RW_READER);
567 				mutex_enter(&ip->i_tlock);
568 				i_flag_save = ip->i_flag;
569 				ip->i_flag |= IUPD | ICHG;
570 				ip->i_seq++;
571 				ITIMES_NOLOCK(ip);
572 				if ((i_flag_save & IMOD) == 0) {
573 					ip->i_flag &= ~IMOD;
574 					ip->i_flag |= IMODACC;
575 				}
576 				mutex_exit(&ip->i_tlock);
577 				rw_exit(&ip->i_contents);
578 			} else {
579 				int terr = 0;
580 				TRANS_BEGIN_SYNC(ufsvfsp, TOP_WRITE_SYNC, resv,
581 				    terr);
582 				ASSERT(!terr);
583 			}
584 		}
585 	} else {
586 		if (ulp)
587 			TRANS_BEGIN_ASYNC(ufsvfsp, TOP_WRITE, resv);
588 	}
589 
590 	/*
591 	 * Write the file
592 	 */
593 	rw_enter(&ufsvfsp->vfs_dqrwlock, RW_READER);
594 	rw_enter(&ip->i_contents, RW_WRITER);
595 	if ((ioflag & FAPPEND) != 0 && (ip->i_mode & IFMT) == IFREG) {
596 		/*
597 		 * In append mode start at end of file.
598 		 */
599 		uiop->uio_loffset = ip->i_size;
600 	}
601 
602 	/*
603 	 * Mild optimisation, don't call ufs_trans_write() unless we have to
604 	 * Also, suppress file system full messages if we will retry.
605 	 */
606 	if (retry)
607 		ip->i_flag |= IQUIET;
608 	if (resid) {
609 		TRANS_WRITE(ip, uiop, ioflag, error, ulp, cr, resv, resid);
610 	} else {
611 		error = wrip(ip, uiop, ioflag, cr);
612 	}
613 	ip->i_flag &= ~IQUIET;
614 
615 	rw_exit(&ip->i_contents);
616 	rw_exit(&ufsvfsp->vfs_dqrwlock);
617 
618 	/*
619 	 * Leave Transaction
620 	 */
621 	if (ulp) {
622 		if (ioflag & (FSYNC|FDSYNC)) {
623 			if (!rewriteflg) {
624 				int terr = 0;
625 
626 				TRANS_END_SYNC(ufsvfsp, terr, TOP_WRITE_SYNC,
627 				    resv);
628 				if (error == 0)
629 					error = terr;
630 			}
631 		} else {
632 			TRANS_END_ASYNC(ufsvfsp, TOP_WRITE, resv);
633 		}
634 		ufs_lockfs_end(ulp);
635 	}
636 out:
637 	if ((error == ENOSPC) && retry && TRANS_ISTRANS(ufsvfsp)) {
638 		/*
639 		 * Any blocks tied up in pending deletes?
640 		 */
641 		ufs_delete_drain_wait(ufsvfsp, 1);
642 		retry = 0;
643 		goto retry_mandlock;
644 	}
645 
646 	if (error == ENOSPC && (start_resid != uiop->uio_resid))
647 		error = 0;
648 
649 	return (error);
650 }
651 
652 /*
653  * Don't cache write blocks to files with the sticky bit set.
654  * Used to keep swap files from blowing the page cache on a server.
655  */
656 int stickyhack = 1;
657 
658 /*
659  * Free behind hacks.  The pager is busted.
660  * XXX - need to pass the information down to writedone() in a flag like B_SEQ
661  * or B_FREE_IF_TIGHT_ON_MEMORY.
662  */
663 int	freebehind = 1;
664 int	smallfile = 0;
665 u_offset_t smallfile64 = 32 * 1024;
666 
667 /*
668  * While we should, in most cases, cache the pages for write, we
669  * may also want to cache the pages for read as long as they are
670  * frequently re-usable.
671  *
672  * If cache_read_ahead = 1, the pages for read will go to the tail
673  * of the cache list when they are released, otherwise go to the head.
674  */
675 int	cache_read_ahead = 0;
676 
677 /*
678  * Freebehind exists  so that as we read  large files  sequentially we
679  * don't consume most of memory with pages  from a few files. It takes
680  * longer to re-read from disk multiple small files as it does reading
681  * one large one sequentially.  As system  memory grows customers need
682  * to retain bigger chunks   of files in  memory.   The advent of  the
683  * cachelist opens up of the possibility freeing pages  to the head or
684  * tail of the list.
685  *
686  * Not freeing a page is a bet that the page will be read again before
687  * it's segmap slot is needed for something else. If we loose the bet,
688  * it means some  other thread is  burdened with the  page free we did
689  * not do. If we win we save a free and reclaim.
690  *
691  * Freeing it at the tail  vs the head of cachelist  is a bet that the
692  * page will survive until the next  read.  It's also saying that this
693  * page is more likely to  be re-used than a  page freed some time ago
694  * and never reclaimed.
695  *
696  * Freebehind maintains a  range of  file offset [smallfile1; smallfile2]
697  *
698  *            0 < offset < smallfile1 : pages are not freed.
699  *   smallfile1 < offset < smallfile2 : pages freed to tail of cachelist.
700  *   smallfile2 < offset              : pages freed to head of cachelist.
701  *
702  * The range  is  computed  at most  once  per second  and  depends on
703  * freemem  and  ncpus_online.  Both parameters  are   bounded to be
704  * >= smallfile && >= smallfile64.
705  *
706  * smallfile1 = (free memory / ncpu) / 1000
707  * smallfile2 = (free memory / ncpu) / 10
708  *
709  * A few examples values:
710  *
711  *       Free Mem (in Bytes) [smallfile1; smallfile2]  [smallfile1; smallfile2]
712  *                                 ncpus_online = 4          ncpus_online = 64
713  *       ------------------  -----------------------   -----------------------
714  *             1G                   [256K;  25M]               [32K; 1.5M]
715  *            10G                   [2.5M; 250M]              [156K; 15M]
716  *           100G                    [25M; 2.5G]              [1.5M; 150M]
717  *
718  */
719 
720 #define	SMALLFILE1_D 1000
721 #define	SMALLFILE2_D 10
722 static u_offset_t smallfile1 = 32 * 1024;
723 static u_offset_t smallfile2 = 32 * 1024;
724 static clock_t smallfile_update = 0; /* lbolt value of when to recompute */
725 uint_t smallfile1_d = SMALLFILE1_D;
726 uint_t smallfile2_d = SMALLFILE2_D;
727 
728 /*
729  * wrip does the real work of write requests for ufs.
730  */
731 int
732 wrip(struct inode *ip, struct uio *uio, int ioflag, struct cred *cr)
733 {
734 	rlim64_t limit = uio->uio_llimit;
735 	u_offset_t off;
736 	u_offset_t old_i_size;
737 	struct fs *fs;
738 	struct vnode *vp;
739 	struct ufsvfs *ufsvfsp;
740 	caddr_t base;
741 	long start_resid = uio->uio_resid;	/* save starting resid */
742 	long premove_resid;			/* resid before uiomove() */
743 	uint_t flags;
744 	int newpage;
745 	int iupdat_flag, directio_status;
746 	int n, on, mapon;
747 	int error, pagecreate;
748 	int do_dqrwlock;		/* drop/reacquire vfs_dqrwlock */
749 	int32_t	iblocks;
750 	int	new_iblocks;
751 
752 	/*
753 	 * ip->i_size is incremented before the uiomove
754 	 * is done on a write.  If the move fails (bad user
755 	 * address) reset ip->i_size.
756 	 * The better way would be to increment ip->i_size
757 	 * only if the uiomove succeeds.
758 	 */
759 	int i_size_changed = 0;
760 	o_mode_t type;
761 	int i_seq_needed = 0;
762 
763 	vp = ITOV(ip);
764 
765 	/*
766 	 * check for forced unmount - should not happen as
767 	 * the request passed the lockfs checks.
768 	 */
769 	if ((ufsvfsp = ip->i_ufsvfs) == NULL)
770 		return (EIO);
771 
772 	fs = ip->i_fs;
773 
774 	ASSERT(RW_WRITE_HELD(&ip->i_contents));
775 
776 	/* check for valid filetype */
777 	type = ip->i_mode & IFMT;
778 	if ((type != IFREG) && (type != IFDIR) && (type != IFATTRDIR) &&
779 	    (type != IFLNK) && (type != IFSHAD)) {
780 		return (EIO);
781 	}
782 
783 	/*
784 	 * the actual limit of UFS file size
785 	 * is UFS_MAXOFFSET_T
786 	 */
787 	if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
788 		limit = MAXOFFSET_T;
789 
790 	if (uio->uio_loffset >= limit) {
791 		proc_t *p = ttoproc(curthread);
792 
793 		mutex_enter(&p->p_lock);
794 		(void) rctl_action(rctlproc_legacy[RLIMIT_FSIZE], p->p_rctls,
795 		    p, RCA_UNSAFE_SIGINFO);
796 		mutex_exit(&p->p_lock);
797 		return (EFBIG);
798 	}
799 
800 	/*
801 	 * if largefiles are disallowed, the limit is
802 	 * the pre-largefiles value of 2GB
803 	 */
804 	if (ufsvfsp->vfs_lfflags & UFS_LARGEFILES)
805 		limit = MIN(UFS_MAXOFFSET_T, limit);
806 	else
807 		limit = MIN(MAXOFF32_T, limit);
808 
809 	if (uio->uio_loffset < (offset_t)0) {
810 		return (EINVAL);
811 	}
812 	if (uio->uio_resid == 0) {
813 		return (0);
814 	}
815 
816 	if (uio->uio_loffset >= limit)
817 		return (EFBIG);
818 
819 	ip->i_flag |= INOACC;	/* don't update ref time in getpage */
820 
821 	if (ioflag & (FSYNC|FDSYNC)) {
822 		ip->i_flag |= ISYNC;
823 		iupdat_flag = 1;
824 	}
825 	/*
826 	 * Try to go direct
827 	 */
828 	if (ip->i_flag & IDIRECTIO || ufsvfsp->vfs_forcedirectio) {
829 		uio->uio_llimit = limit;
830 		error = ufs_directio_write(ip, uio, ioflag, 0, cr,
831 		    &directio_status);
832 		/*
833 		 * If ufs_directio wrote to the file or set the flags,
834 		 * we need to update i_seq, but it may be deferred.
835 		 */
836 		if (start_resid != uio->uio_resid ||
837 		    (ip->i_flag & (ICHG|IUPD))) {
838 			i_seq_needed = 1;
839 			ip->i_flag |= ISEQ;
840 		}
841 		if (directio_status == DIRECTIO_SUCCESS)
842 			goto out;
843 	}
844 
845 	/*
846 	 * Behavior with respect to dropping/reacquiring vfs_dqrwlock:
847 	 *
848 	 * o shadow inodes: vfs_dqrwlock is not held at all
849 	 * o quota updates: vfs_dqrwlock is read or write held
850 	 * o other updates: vfs_dqrwlock is read held
851 	 *
852 	 * The first case is the only one where we do not hold
853 	 * vfs_dqrwlock at all while entering wrip().
854 	 * We must make sure not to downgrade/drop vfs_dqrwlock if we
855 	 * have it as writer, i.e. if we are updating the quota inode.
856 	 * There is no potential deadlock scenario in this case as
857 	 * ufs_getpage() takes care of this and avoids reacquiring
858 	 * vfs_dqrwlock in that case.
859 	 *
860 	 * This check is done here since the above conditions do not change
861 	 * and we possibly loop below, so save a few cycles.
862 	 */
863 	if ((type == IFSHAD) ||
864 	    (rw_owner(&ufsvfsp->vfs_dqrwlock) == curthread)) {
865 		do_dqrwlock = 0;
866 	} else {
867 		do_dqrwlock = 1;
868 	}
869 
870 	/*
871 	 * Large Files: We cast MAXBMASK to offset_t
872 	 * inorder to mask out the higher bits. Since offset_t
873 	 * is a signed value, the high order bit set in MAXBMASK
874 	 * value makes it do the right thing by having all bits 1
875 	 * in the higher word. May be removed for _SOLARIS64_.
876 	 */
877 
878 	fs = ip->i_fs;
879 	do {
880 		u_offset_t uoff = uio->uio_loffset;
881 		off = uoff & (offset_t)MAXBMASK;
882 		mapon = (int)(uoff & (offset_t)MAXBOFFSET);
883 		on = (int)blkoff(fs, uoff);
884 		n = (int)MIN(fs->fs_bsize - on, uio->uio_resid);
885 		new_iblocks = 1;
886 
887 		if (type == IFREG && uoff + n >= limit) {
888 			if (uoff >= limit) {
889 				error = EFBIG;
890 				goto out;
891 			}
892 			/*
893 			 * since uoff + n >= limit,
894 			 * therefore n >= limit - uoff, and n is an int
895 			 * so it is safe to cast it to an int
896 			 */
897 			n = (int)(limit - (rlim64_t)uoff);
898 		}
899 		if (uoff + n > ip->i_size) {
900 			/*
901 			 * We are extending the length of the file.
902 			 * bmap is used so that we are sure that
903 			 * if we need to allocate new blocks, that it
904 			 * is done here before we up the file size.
905 			 */
906 			error = bmap_write(ip, uoff, (int)(on + n),
907 			    mapon == 0, NULL, cr);
908 			/*
909 			 * bmap_write never drops i_contents so if
910 			 * the flags are set it changed the file.
911 			 */
912 			if (ip->i_flag & (ICHG|IUPD)) {
913 				i_seq_needed = 1;
914 				ip->i_flag |= ISEQ;
915 			}
916 			if (error)
917 				break;
918 			/*
919 			 * There is a window of vulnerability here.
920 			 * The sequence of operations: allocate file
921 			 * system blocks, uiomove the data into pages,
922 			 * and then update the size of the file in the
923 			 * inode, must happen atomically.  However, due
924 			 * to current locking constraints, this can not
925 			 * be done.
926 			 */
927 			ASSERT(ip->i_writer == NULL);
928 			ip->i_writer = curthread;
929 			i_size_changed = 1;
930 			/*
931 			 * If we are writing from the beginning of
932 			 * the mapping, we can just create the
933 			 * pages without having to read them.
934 			 */
935 			pagecreate = (mapon == 0);
936 		} else if (n == MAXBSIZE) {
937 			/*
938 			 * Going to do a whole mappings worth,
939 			 * so we can just create the pages w/o
940 			 * having to read them in.  But before
941 			 * we do that, we need to make sure any
942 			 * needed blocks are allocated first.
943 			 */
944 			iblocks = ip->i_blocks;
945 			error = bmap_write(ip, uoff, (int)(on + n),
946 			    BI_ALLOC_ONLY, NULL, cr);
947 			/*
948 			 * bmap_write never drops i_contents so if
949 			 * the flags are set it changed the file.
950 			 */
951 			if (ip->i_flag & (ICHG|IUPD)) {
952 				i_seq_needed = 1;
953 				ip->i_flag |= ISEQ;
954 			}
955 			if (error)
956 				break;
957 			pagecreate = 1;
958 			/*
959 			 * check if the new created page needed the
960 			 * allocation of new disk blocks.
961 			 */
962 			if (iblocks == ip->i_blocks)
963 				new_iblocks = 0; /* no new blocks allocated */
964 		} else {
965 			pagecreate = 0;
966 			/*
967 			 * In sync mode flush the indirect blocks which
968 			 * may have been allocated and not written on
969 			 * disk. In above cases bmap_write will allocate
970 			 * in sync mode.
971 			 */
972 			if (ioflag & (FSYNC|FDSYNC)) {
973 				error = ufs_indirblk_sync(ip, uoff);
974 				if (error)
975 					break;
976 			}
977 		}
978 
979 		/*
980 		 * At this point we can enter ufs_getpage() in one
981 		 * of two ways:
982 		 * 1) segmap_getmapflt() calls ufs_getpage() when the
983 		 *    forcefault parameter is true (pagecreate == 0)
984 		 * 2) uiomove() causes a page fault.
985 		 *
986 		 * We have to drop the contents lock to prevent the VM
987 		 * system from trying to reacquire it in ufs_getpage()
988 		 * should the uiomove cause a pagefault.
989 		 *
990 		 * We have to drop the reader vfs_dqrwlock here as well.
991 		 */
992 		rw_exit(&ip->i_contents);
993 		if (do_dqrwlock) {
994 			ASSERT(RW_LOCK_HELD(&ufsvfsp->vfs_dqrwlock));
995 			ASSERT(!(RW_WRITE_HELD(&ufsvfsp->vfs_dqrwlock)));
996 			rw_exit(&ufsvfsp->vfs_dqrwlock);
997 		}
998 
999 		newpage = 0;
1000 		premove_resid = uio->uio_resid;
1001 		if (vpm_enable) {
1002 			/*
1003 			 * Copy data. If new pages are created, part of
1004 			 * the page that is not written will be initizliazed
1005 			 * with zeros.
1006 			 */
1007 			error = vpm_data_copy(vp, (off + mapon), (uint_t)n,
1008 			    uio, !pagecreate, &newpage, 0, S_WRITE);
1009 		} else {
1010 
1011 			base = segmap_getmapflt(segkmap, vp, (off + mapon),
1012 			    (uint_t)n, !pagecreate, S_WRITE);
1013 
1014 			/*
1015 			 * segmap_pagecreate() returns 1 if it calls
1016 			 * page_create_va() to allocate any pages.
1017 			 */
1018 
1019 			if (pagecreate)
1020 				newpage = segmap_pagecreate(segkmap, base,
1021 				    (size_t)n, 0);
1022 
1023 			error = uiomove(base + mapon, (long)n, UIO_WRITE, uio);
1024 		}
1025 
1026 		/*
1027 		 * If "newpage" is set, then a new page was created and it
1028 		 * does not contain valid data, so it needs to be initialized
1029 		 * at this point.
1030 		 * Otherwise the page contains old data, which was overwritten
1031 		 * partially or as a whole in uiomove.
1032 		 * If there is only one iovec structure within uio, then
1033 		 * on error uiomove will not be able to update uio->uio_loffset
1034 		 * and we would zero the whole page here!
1035 		 *
1036 		 * If uiomove fails because of an error, the old valid data
1037 		 * is kept instead of filling the rest of the page with zero's.
1038 		 */
1039 		if (!vpm_enable && newpage &&
1040 		    uio->uio_loffset < roundup(off + mapon + n, PAGESIZE)) {
1041 			/*
1042 			 * We created pages w/o initializing them completely,
1043 			 * thus we need to zero the part that wasn't set up.
1044 			 * This happens on most EOF write cases and if
1045 			 * we had some sort of error during the uiomove.
1046 			 */
1047 			int nzero, nmoved;
1048 
1049 			nmoved = (int)(uio->uio_loffset - (off + mapon));
1050 			ASSERT(nmoved >= 0 && nmoved <= n);
1051 			nzero = roundup(on + n, PAGESIZE) - nmoved;
1052 			ASSERT(nzero > 0 && mapon + nmoved + nzero <= MAXBSIZE);
1053 			(void) kzero(base + mapon + nmoved, (uint_t)nzero);
1054 		}
1055 
1056 		/*
1057 		 * Unlock the pages allocated by page_create_va()
1058 		 * in segmap_pagecreate()
1059 		 */
1060 		if (!vpm_enable && newpage)
1061 			segmap_pageunlock(segkmap, base, (size_t)n, S_WRITE);
1062 
1063 		/*
1064 		 * If the size of the file changed, then update the
1065 		 * size field in the inode now.  This can't be done
1066 		 * before the call to segmap_pageunlock or there is
1067 		 * a potential deadlock with callers to ufs_putpage().
1068 		 * They will be holding i_contents and trying to lock
1069 		 * a page, while this thread is holding a page locked
1070 		 * and trying to acquire i_contents.
1071 		 */
1072 		if (i_size_changed) {
1073 			rw_enter(&ip->i_contents, RW_WRITER);
1074 			old_i_size = ip->i_size;
1075 			UFS_SET_ISIZE(uoff + n, ip);
1076 			TRANS_INODE(ufsvfsp, ip);
1077 			/*
1078 			 * file has grown larger than 2GB. Set flag
1079 			 * in superblock to indicate this, if it
1080 			 * is not already set.
1081 			 */
1082 			if ((ip->i_size > MAXOFF32_T) &&
1083 			    !(fs->fs_flags & FSLARGEFILES)) {
1084 				ASSERT(ufsvfsp->vfs_lfflags & UFS_LARGEFILES);
1085 				mutex_enter(&ufsvfsp->vfs_lock);
1086 				fs->fs_flags |= FSLARGEFILES;
1087 				ufs_sbwrite(ufsvfsp);
1088 				mutex_exit(&ufsvfsp->vfs_lock);
1089 			}
1090 			mutex_enter(&ip->i_tlock);
1091 			ip->i_writer = NULL;
1092 			cv_broadcast(&ip->i_wrcv);
1093 			mutex_exit(&ip->i_tlock);
1094 			rw_exit(&ip->i_contents);
1095 		}
1096 
1097 		if (error) {
1098 			/*
1099 			 * If we failed on a write, we may have already
1100 			 * allocated file blocks as well as pages.  It's
1101 			 * hard to undo the block allocation, but we must
1102 			 * be sure to invalidate any pages that may have
1103 			 * been allocated.
1104 			 *
1105 			 * If the page was created without initialization
1106 			 * then we must check if it should be possible
1107 			 * to destroy the new page and to keep the old data
1108 			 * on the disk.
1109 			 *
1110 			 * It is possible to destroy the page without
1111 			 * having to write back its contents only when
1112 			 * - the size of the file keeps unchanged
1113 			 * - bmap_write() did not allocate new disk blocks
1114 			 *   it is possible to create big files using "seek" and
1115 			 *   write to the end of the file. A "write" to a
1116 			 *   position before the end of the file would not
1117 			 *   change the size of the file but it would allocate
1118 			 *   new disk blocks.
1119 			 * - uiomove intended to overwrite the whole page.
1120 			 * - a new page was created (newpage == 1).
1121 			 */
1122 
1123 			if (i_size_changed == 0 && new_iblocks == 0 &&
1124 			    newpage) {
1125 
1126 				/* unwind what uiomove eventually last did */
1127 				uio->uio_resid = premove_resid;
1128 
1129 				/*
1130 				 * destroy the page, do not write ambiguous
1131 				 * data to the disk.
1132 				 */
1133 				flags = SM_DESTROY;
1134 			} else {
1135 				/*
1136 				 * write the page back to the disk, if dirty,
1137 				 * and remove the page from the cache.
1138 				 */
1139 				flags = SM_INVAL;
1140 			}
1141 
1142 			if (vpm_enable) {
1143 				/*
1144 				 *  Flush pages.
1145 				 */
1146 				(void) vpm_sync_pages(vp, off, n, flags);
1147 			} else {
1148 				(void) segmap_release(segkmap, base, flags);
1149 			}
1150 		} else {
1151 			flags = 0;
1152 			/*
1153 			 * Force write back for synchronous write cases.
1154 			 */
1155 			if ((ioflag & (FSYNC|FDSYNC)) || type == IFDIR) {
1156 				/*
1157 				 * If the sticky bit is set but the
1158 				 * execute bit is not set, we do a
1159 				 * synchronous write back and free
1160 				 * the page when done.  We set up swap
1161 				 * files to be handled this way to
1162 				 * prevent servers from keeping around
1163 				 * the client's swap pages too long.
1164 				 * XXX - there ought to be a better way.
1165 				 */
1166 				if (IS_SWAPVP(vp)) {
1167 					flags = SM_WRITE | SM_FREE |
1168 					    SM_DONTNEED;
1169 					iupdat_flag = 0;
1170 				} else {
1171 					flags = SM_WRITE;
1172 				}
1173 			} else if (n + on == MAXBSIZE || IS_SWAPVP(vp)) {
1174 				/*
1175 				 * Have written a whole block.
1176 				 * Start an asynchronous write and
1177 				 * mark the buffer to indicate that
1178 				 * it won't be needed again soon.
1179 				 */
1180 				flags = SM_WRITE | SM_ASYNC | SM_DONTNEED;
1181 			}
1182 			if (vpm_enable) {
1183 				/*
1184 				 * Flush pages.
1185 				 */
1186 				error = vpm_sync_pages(vp, off, n, flags);
1187 			} else {
1188 				error = segmap_release(segkmap, base, flags);
1189 			}
1190 			/*
1191 			 * If the operation failed and is synchronous,
1192 			 * then we need to unwind what uiomove() last
1193 			 * did so we can potentially return an error to
1194 			 * the caller.  If this write operation was
1195 			 * done in two pieces and the first succeeded,
1196 			 * then we won't return an error for the second
1197 			 * piece that failed.  However, we only want to
1198 			 * return a resid value that reflects what was
1199 			 * really done.
1200 			 *
1201 			 * Failures for non-synchronous operations can
1202 			 * be ignored since the page subsystem will
1203 			 * retry the operation until it succeeds or the
1204 			 * file system is unmounted.
1205 			 */
1206 			if (error) {
1207 				if ((ioflag & (FSYNC | FDSYNC)) ||
1208 				    type == IFDIR) {
1209 					uio->uio_resid = premove_resid;
1210 				} else {
1211 					error = 0;
1212 				}
1213 			}
1214 		}
1215 
1216 		/*
1217 		 * Re-acquire contents lock.
1218 		 * If it was dropped, reacquire reader vfs_dqrwlock as well.
1219 		 */
1220 		if (do_dqrwlock)
1221 			rw_enter(&ufsvfsp->vfs_dqrwlock, RW_READER);
1222 		rw_enter(&ip->i_contents, RW_WRITER);
1223 
1224 		/*
1225 		 * If the uiomove() failed or if a synchronous
1226 		 * page push failed, fix up i_size.
1227 		 */
1228 		if (error) {
1229 			if (i_size_changed) {
1230 				/*
1231 				 * The uiomove failed, and we
1232 				 * allocated blocks,so get rid
1233 				 * of them.
1234 				 */
1235 				(void) ufs_itrunc(ip, old_i_size, 0, cr);
1236 			}
1237 		} else {
1238 			/*
1239 			 * XXX - Can this be out of the loop?
1240 			 */
1241 			ip->i_flag |= IUPD | ICHG;
1242 			/*
1243 			 * Only do one increase of i_seq for multiple
1244 			 * pieces.  Because we drop locks, record
1245 			 * the fact that we changed the timestamp and
1246 			 * are deferring the increase in case another thread
1247 			 * pushes our timestamp update.
1248 			 */
1249 			i_seq_needed = 1;
1250 			ip->i_flag |= ISEQ;
1251 			if (i_size_changed)
1252 				ip->i_flag |= IATTCHG;
1253 			if ((ip->i_mode & (IEXEC | (IEXEC >> 3) |
1254 			    (IEXEC >> 6))) != 0 &&
1255 			    (ip->i_mode & (ISUID | ISGID)) != 0 &&
1256 			    secpolicy_vnode_setid_retain(cr,
1257 			    (ip->i_mode & ISUID) != 0 && ip->i_uid == 0) != 0) {
1258 				/*
1259 				 * Clear Set-UID & Set-GID bits on
1260 				 * successful write if not privileged
1261 				 * and at least one of the execute bits
1262 				 * is set.  If we always clear Set-GID,
1263 				 * mandatory file and record locking is
1264 				 * unuseable.
1265 				 */
1266 				ip->i_mode &= ~(ISUID | ISGID);
1267 			}
1268 		}
1269 		/*
1270 		 * In the case the FDSYNC flag is set and this is a
1271 		 * "rewrite" we won't log a delta.
1272 		 * The FSYNC flag overrides all cases.
1273 		 */
1274 		if (!ufs_check_rewrite(ip, uio, ioflag) || !(ioflag & FDSYNC)) {
1275 			TRANS_INODE(ufsvfsp, ip);
1276 		}
1277 	} while (error == 0 && uio->uio_resid > 0 && n != 0);
1278 
1279 out:
1280 	/*
1281 	 * Make sure i_seq is increased at least once per write
1282 	 */
1283 	if (i_seq_needed) {
1284 		ip->i_seq++;
1285 		ip->i_flag &= ~ISEQ;	/* no longer deferred */
1286 	}
1287 
1288 	/*
1289 	 * Inode is updated according to this table -
1290 	 *
1291 	 *   FSYNC	  FDSYNC(posix.4)
1292 	 *   --------------------------
1293 	 *   always@	  IATTCHG|IBDWRITE
1294 	 *
1295 	 * @ - 	If we are doing synchronous write the only time we should
1296 	 *	not be sync'ing the ip here is if we have the stickyhack
1297 	 *	activated, the file is marked with the sticky bit and
1298 	 *	no exec bit, the file length has not been changed and
1299 	 *	no new blocks have been allocated during this write.
1300 	 */
1301 
1302 	if ((ip->i_flag & ISYNC) != 0) {
1303 		/*
1304 		 * we have eliminated nosync
1305 		 */
1306 		if ((ip->i_flag & (IATTCHG|IBDWRITE)) ||
1307 		    ((ioflag & FSYNC) && iupdat_flag)) {
1308 			ufs_iupdat(ip, 1);
1309 		}
1310 	}
1311 
1312 	/*
1313 	 * If we've already done a partial-write, terminate
1314 	 * the write but return no error unless the error is ENOSPC
1315 	 * because the caller can detect this and free resources and
1316 	 * try again.
1317 	 */
1318 	if ((start_resid != uio->uio_resid) && (error != ENOSPC))
1319 		error = 0;
1320 
1321 	ip->i_flag &= ~(INOACC | ISYNC);
1322 	ITIMES_NOLOCK(ip);
1323 	return (error);
1324 }
1325 
1326 /*
1327  * rdip does the real work of read requests for ufs.
1328  */
1329 int
1330 rdip(struct inode *ip, struct uio *uio, int ioflag, cred_t *cr)
1331 {
1332 	u_offset_t off;
1333 	caddr_t base;
1334 	struct fs *fs;
1335 	struct ufsvfs *ufsvfsp;
1336 	struct vnode *vp;
1337 	long oresid = uio->uio_resid;
1338 	u_offset_t n, on, mapon;
1339 	int error = 0;
1340 	int doupdate = 1;
1341 	uint_t flags;
1342 	int dofree, directio_status;
1343 	krw_t rwtype;
1344 	o_mode_t type;
1345 
1346 	vp = ITOV(ip);
1347 
1348 	ASSERT(RW_LOCK_HELD(&ip->i_contents));
1349 
1350 	ufsvfsp = ip->i_ufsvfs;
1351 
1352 	if (ufsvfsp == NULL)
1353 		return (EIO);
1354 
1355 	fs = ufsvfsp->vfs_fs;
1356 
1357 	/* check for valid filetype */
1358 	type = ip->i_mode & IFMT;
1359 	if ((type != IFREG) && (type != IFDIR) && (type != IFATTRDIR) &&
1360 	    (type != IFLNK) && (type != IFSHAD)) {
1361 		return (EIO);
1362 	}
1363 
1364 	if (uio->uio_loffset > UFS_MAXOFFSET_T) {
1365 		error = 0;
1366 		goto out;
1367 	}
1368 	if (uio->uio_loffset < (offset_t)0) {
1369 		return (EINVAL);
1370 	}
1371 	if (uio->uio_resid == 0) {
1372 		return (0);
1373 	}
1374 
1375 	if (!ULOCKFS_IS_NOIACC(ITOUL(ip)) && (fs->fs_ronly == 0) &&
1376 	    (!ufsvfsp->vfs_noatime)) {
1377 		mutex_enter(&ip->i_tlock);
1378 		ip->i_flag |= IACC;
1379 		mutex_exit(&ip->i_tlock);
1380 	}
1381 	/*
1382 	 * Try to go direct
1383 	 */
1384 	if (ip->i_flag & IDIRECTIO || ufsvfsp->vfs_forcedirectio) {
1385 		error = ufs_directio_read(ip, uio, cr, &directio_status);
1386 		if (directio_status == DIRECTIO_SUCCESS)
1387 			goto out;
1388 	}
1389 
1390 	rwtype = (rw_write_held(&ip->i_contents)?RW_WRITER:RW_READER);
1391 
1392 	do {
1393 		offset_t diff;
1394 		u_offset_t uoff = uio->uio_loffset;
1395 		off = uoff & (offset_t)MAXBMASK;
1396 		mapon = (u_offset_t)(uoff & (offset_t)MAXBOFFSET);
1397 		on = (u_offset_t)blkoff(fs, uoff);
1398 		n = MIN((u_offset_t)fs->fs_bsize - on,
1399 		    (u_offset_t)uio->uio_resid);
1400 
1401 		diff = ip->i_size - uoff;
1402 
1403 		if (diff <= (offset_t)0) {
1404 			error = 0;
1405 			goto out;
1406 		}
1407 		if (diff < (offset_t)n)
1408 			n = (int)diff;
1409 
1410 		/*
1411 		 * We update smallfile2 and smallfile1 at most every second.
1412 		 */
1413 		if (lbolt >= smallfile_update) {
1414 			uint64_t percpufreeb;
1415 			if (smallfile1_d == 0) smallfile1_d = SMALLFILE1_D;
1416 			if (smallfile2_d == 0) smallfile2_d = SMALLFILE2_D;
1417 			percpufreeb = ptob((uint64_t)freemem) / ncpus_online;
1418 			smallfile1 = percpufreeb / smallfile1_d;
1419 			smallfile2 = percpufreeb / smallfile2_d;
1420 			smallfile1 = MAX(smallfile1, smallfile);
1421 			smallfile1 = MAX(smallfile1, smallfile64);
1422 			smallfile2 = MAX(smallfile1, smallfile2);
1423 			smallfile_update = lbolt + hz;
1424 		}
1425 
1426 		dofree = freebehind &&
1427 		    ip->i_nextr == (off & PAGEMASK) && off > smallfile1;
1428 
1429 		/*
1430 		 * At this point we can enter ufs_getpage() in one of two
1431 		 * ways:
1432 		 * 1) segmap_getmapflt() calls ufs_getpage() when the
1433 		 *    forcefault parameter is true (value of 1 is passed)
1434 		 * 2) uiomove() causes a page fault.
1435 		 *
1436 		 * We cannot hold onto an i_contents reader lock without
1437 		 * risking deadlock in ufs_getpage() so drop a reader lock.
1438 		 * The ufs_getpage() dolock logic already allows for a
1439 		 * thread holding i_contents as writer to work properly
1440 		 * so we keep a writer lock.
1441 		 */
1442 		if (rwtype == RW_READER)
1443 			rw_exit(&ip->i_contents);
1444 
1445 		if (vpm_enable) {
1446 			/*
1447 			 * Copy data.
1448 			 */
1449 			error = vpm_data_copy(vp, (off + mapon), (uint_t)n,
1450 			    uio, 1, NULL, 0, S_READ);
1451 		} else {
1452 			base = segmap_getmapflt(segkmap, vp, (off + mapon),
1453 			    (uint_t)n, 1, S_READ);
1454 			error = uiomove(base + mapon, (long)n, UIO_READ, uio);
1455 		}
1456 
1457 		flags = 0;
1458 		if (!error) {
1459 			/*
1460 			 * If  reading sequential  we won't need  this
1461 			 * buffer again  soon.  For  offsets in  range
1462 			 * [smallfile1,  smallfile2] release the pages
1463 			 * at   the  tail  of the   cache list, larger
1464 			 * offsets are released at the head.
1465 			 */
1466 			if (dofree) {
1467 				flags = SM_FREE | SM_ASYNC;
1468 				if ((cache_read_ahead == 0) &&
1469 				    (off > smallfile2))
1470 					flags |=  SM_DONTNEED;
1471 			}
1472 			/*
1473 			 * In POSIX SYNC (FSYNC and FDSYNC) read mode,
1474 			 * we want to make sure that the page which has
1475 			 * been read, is written on disk if it is dirty.
1476 			 * And corresponding indirect blocks should also
1477 			 * be flushed out.
1478 			 */
1479 			if ((ioflag & FRSYNC) && (ioflag & (FSYNC|FDSYNC))) {
1480 				flags &= ~SM_ASYNC;
1481 				flags |= SM_WRITE;
1482 			}
1483 			if (vpm_enable) {
1484 				error = vpm_sync_pages(vp, off, n, flags);
1485 			} else {
1486 				error = segmap_release(segkmap, base, flags);
1487 			}
1488 		} else {
1489 			if (vpm_enable) {
1490 				(void) vpm_sync_pages(vp, off, n, flags);
1491 			} else {
1492 				(void) segmap_release(segkmap, base, flags);
1493 			}
1494 		}
1495 
1496 		if (rwtype == RW_READER)
1497 			rw_enter(&ip->i_contents, rwtype);
1498 	} while (error == 0 && uio->uio_resid > 0 && n != 0);
1499 out:
1500 	/*
1501 	 * Inode is updated according to this table if FRSYNC is set.
1502 	 *
1503 	 *   FSYNC	  FDSYNC(posix.4)
1504 	 *   --------------------------
1505 	 *   always	  IATTCHG|IBDWRITE
1506 	 */
1507 	/*
1508 	 * The inode is not updated if we're logging and the inode is a
1509 	 * directory with FRSYNC, FSYNC and FDSYNC flags set.
1510 	 */
1511 	if (ioflag & FRSYNC) {
1512 		if (TRANS_ISTRANS(ufsvfsp) && ((ip->i_mode & IFMT) == IFDIR)) {
1513 			doupdate = 0;
1514 		}
1515 		if (doupdate) {
1516 			if ((ioflag & FSYNC) ||
1517 			    ((ioflag & FDSYNC) &&
1518 			    (ip->i_flag & (IATTCHG|IBDWRITE)))) {
1519 				ufs_iupdat(ip, 1);
1520 			}
1521 		}
1522 	}
1523 	/*
1524 	 * If we've already done a partial read, terminate
1525 	 * the read but return no error.
1526 	 */
1527 	if (oresid != uio->uio_resid)
1528 		error = 0;
1529 	ITIMES(ip);
1530 
1531 	return (error);
1532 }
1533 
1534 /* ARGSUSED */
1535 static int
1536 ufs_ioctl(
1537 	struct vnode	*vp,
1538 	int		cmd,
1539 	intptr_t	arg,
1540 	int		flag,
1541 	struct cred	*cr,
1542 	int		*rvalp,
1543 	caller_context_t *ct)
1544 {
1545 	struct lockfs	lockfs, lockfs_out;
1546 	struct ufsvfs	*ufsvfsp = VTOI(vp)->i_ufsvfs;
1547 	char		*comment, *original_comment;
1548 	struct fs	*fs;
1549 	struct ulockfs	*ulp;
1550 	offset_t	off;
1551 	extern int	maxphys;
1552 	int		error;
1553 	int		issync;
1554 	int		trans_size;
1555 
1556 
1557 	/*
1558 	 * forcibly unmounted
1559 	 */
1560 	if (ufsvfsp == NULL || vp->v_vfsp == NULL ||
1561 	    vp->v_vfsp->vfs_flag & VFS_UNMOUNTED)
1562 		return (EIO);
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 >
4589 	    P2ROUNDUP_TYPED(ip->i_size, PAGESIZE, u_offset_t);
4590 	if (beyond_eof && seg != segkmap) {
4591 		if (dolock) {
4592 			rw_exit(&ip->i_contents);
4593 			if (do_qlock && rwtype == RW_WRITER)
4594 				rw_exit(&ufsvfsp->vfs_dqrwlock);
4595 		}
4596 		err = EFAULT;
4597 		goto unlock;
4598 	}
4599 
4600 	/*
4601 	 * Must hold i_contents lock throughout the call to pvn_getpages
4602 	 * since locked pages are returned from each call to ufs_getapage.
4603 	 * Must *not* return locked pages and then try for contents lock
4604 	 * due to lock ordering requirements (inode > page)
4605 	 */
4606 
4607 	has_holes = bmap_has_holes(ip);
4608 
4609 	if ((rw == S_WRITE || rw == S_CREATE) && has_holes && !beyond_eof) {
4610 		int	blk_size;
4611 		u_offset_t offset;
4612 
4613 		/*
4614 		 * We must acquire the RW_WRITER lock in order to
4615 		 * call bmap_write().
4616 		 */
4617 		if (dolock && rwtype == RW_READER) {
4618 			rwtype = RW_WRITER;
4619 
4620 			/*
4621 			 * Grab the quota lock before
4622 			 * upgrading i_contents, but if we can't grab it
4623 			 * don't wait here due to lock order:
4624 			 * vfs_dqrwlock > i_contents.
4625 			 */
4626 			if (do_qlock &&
4627 			    rw_tryenter(&ufsvfsp->vfs_dqrwlock, RW_READER)
4628 			    == 0) {
4629 				rw_exit(&ip->i_contents);
4630 				goto retrylock;
4631 			}
4632 			if (!rw_tryupgrade(&ip->i_contents)) {
4633 				rw_exit(&ip->i_contents);
4634 				if (do_qlock)
4635 					rw_exit(&ufsvfsp->vfs_dqrwlock);
4636 				goto retrylock;
4637 			}
4638 		}
4639 
4640 		/*
4641 		 * May be allocating disk blocks for holes here as
4642 		 * a result of mmap faults. write(2) does the bmap_write
4643 		 * in rdip/wrip, not here. We are not dealing with frags
4644 		 * in this case.
4645 		 */
4646 		/*
4647 		 * Large Files: We cast fs_bmask field to offset_t
4648 		 * just as we do for MAXBMASK because uoff is a 64-bit
4649 		 * data type. fs_bmask will still be a 32-bit type
4650 		 * as we cannot change any ondisk data structures.
4651 		 */
4652 
4653 		offset = uoff & (offset_t)fs->fs_bmask;
4654 		while (offset < uoff + len) {
4655 			blk_size = (int)blksize(fs, ip, lblkno(fs, offset));
4656 			err = bmap_write(ip, offset, blk_size,
4657 			    BI_NORMAL, NULL, cr);
4658 			if (ip->i_flag & (ICHG|IUPD))
4659 				ip->i_seq++;
4660 			if (err)
4661 				goto update_inode;
4662 			offset += blk_size; /* XXX - make this contig */
4663 		}
4664 	}
4665 
4666 	/*
4667 	 * Can be a reader from now on.
4668 	 */
4669 	if (dolock && rwtype == RW_WRITER) {
4670 		rw_downgrade(&ip->i_contents);
4671 		/*
4672 		 * We can release vfs_dqrwlock early so do it, but make
4673 		 * sure we don't try to release it again at the bottom.
4674 		 */
4675 		if (do_qlock) {
4676 			rw_exit(&ufsvfsp->vfs_dqrwlock);
4677 			do_qlock = 0;
4678 		}
4679 	}
4680 
4681 	/*
4682 	 * We remove PROT_WRITE in cases when the file has UFS holes
4683 	 * because we don't  want to call bmap_read() to check each
4684 	 * page if it is backed with a disk block.
4685 	 */
4686 	if (protp && has_holes && rw != S_WRITE && rw != S_CREATE)
4687 		*protp &= ~PROT_WRITE;
4688 
4689 	err = 0;
4690 
4691 	/*
4692 	 * The loop looks up pages in the range [off, off + len).
4693 	 * For each page, we first check if we should initiate an asynchronous
4694 	 * read ahead before we call page_lookup (we may sleep in page_lookup
4695 	 * for a previously initiated disk read).
4696 	 */
4697 	eoff = (uoff + len);
4698 	for (pgoff = uoff, pgaddr = addr, pl = plarr;
4699 	    pgoff < eoff; /* empty */) {
4700 		page_t	*pp;
4701 		u_offset_t	nextrio;
4702 		se_t	se;
4703 		int retval;
4704 
4705 		se = ((rw == S_CREATE || rw == S_OTHER) ? SE_EXCL : SE_SHARED);
4706 
4707 		/* Handle async getpage (faultahead) */
4708 		if (plarr == NULL) {
4709 			ip->i_nextrio = pgoff;
4710 			(void) ufs_getpage_ra(vp, pgoff, seg, pgaddr);
4711 			pgoff += pgsize;
4712 			pgaddr += pgsize;
4713 			continue;
4714 		}
4715 		/*
4716 		 * Check if we should initiate read ahead of next cluster.
4717 		 * We call page_exists only when we need to confirm that
4718 		 * we have the current page before we initiate the read ahead.
4719 		 */
4720 		nextrio = ip->i_nextrio;
4721 		if (seqmode &&
4722 		    pgoff + CLUSTSZ(ip) >= nextrio && pgoff <= nextrio &&
4723 		    nextrio < ip->i_size && page_exists(vp, pgoff)) {
4724 			retval = ufs_getpage_ra(vp, pgoff, seg, pgaddr);
4725 			/*
4726 			 * We always read ahead the next cluster of data
4727 			 * starting from i_nextrio. If the page (vp,nextrio)
4728 			 * is actually in core at this point, the routine
4729 			 * ufs_getpage_ra() will stop pre-fetching data
4730 			 * until we read that page in a synchronized manner
4731 			 * through ufs_getpage_miss(). So, we should increase
4732 			 * i_nextrio if the page (vp, nextrio) exists.
4733 			 */
4734 			if ((retval == 0) && page_exists(vp, nextrio)) {
4735 				ip->i_nextrio = nextrio + pgsize;
4736 			}
4737 		}
4738 
4739 		if ((pp = page_lookup(vp, pgoff, se)) != NULL) {
4740 			/*
4741 			 * We found the page in the page cache.
4742 			 */
4743 			*pl++ = pp;
4744 			pgoff += pgsize;
4745 			pgaddr += pgsize;
4746 			len -= pgsize;
4747 			plsz -= pgsize;
4748 		} else  {
4749 			/*
4750 			 * We have to create the page, or read it from disk.
4751 			 */
4752 			if (err = ufs_getpage_miss(vp, pgoff, len, seg, pgaddr,
4753 			    pl, plsz, rw, seqmode))
4754 				goto error;
4755 
4756 			while (*pl != NULL) {
4757 				pl++;
4758 				pgoff += pgsize;
4759 				pgaddr += pgsize;
4760 				len -= pgsize;
4761 				plsz -= pgsize;
4762 			}
4763 		}
4764 	}
4765 
4766 	/*
4767 	 * Return pages up to plsz if they are in the page cache.
4768 	 * We cannot return pages if there is a chance that they are
4769 	 * backed with a UFS hole and rw is S_WRITE or S_CREATE.
4770 	 */
4771 	if (plarr && !(has_holes && (rw == S_WRITE || rw == S_CREATE))) {
4772 
4773 		ASSERT((protp == NULL) ||
4774 		    !(has_holes && (*protp & PROT_WRITE)));
4775 
4776 		eoff = pgoff + plsz;
4777 		while (pgoff < eoff) {
4778 			page_t		*pp;
4779 
4780 			if ((pp = page_lookup_nowait(vp, pgoff,
4781 			    SE_SHARED)) == NULL)
4782 				break;
4783 
4784 			*pl++ = pp;
4785 			pgoff += pgsize;
4786 			plsz -= pgsize;
4787 		}
4788 	}
4789 
4790 	if (plarr)
4791 		*pl = NULL;			/* Terminate page list */
4792 	ip->i_nextr = pgoff;
4793 
4794 error:
4795 	if (err && plarr) {
4796 		/*
4797 		 * Release any pages we have locked.
4798 		 */
4799 		while (pl > &plarr[0])
4800 			page_unlock(*--pl);
4801 
4802 		plarr[0] = NULL;
4803 	}
4804 
4805 update_inode:
4806 	/*
4807 	 * If the inode is not already marked for IACC (in rdip() for read)
4808 	 * and the inode is not marked for no access time update (in wrip()
4809 	 * for write) then update the inode access time and mod time now.
4810 	 */
4811 	if ((ip->i_flag & (IACC | INOACC)) == 0) {
4812 		if ((rw != S_OTHER) && (ip->i_mode & IFMT) != IFDIR) {
4813 			if (!ULOCKFS_IS_NOIACC(ITOUL(ip)) &&
4814 			    (fs->fs_ronly == 0) &&
4815 			    (!ufsvfsp->vfs_noatime)) {
4816 				mutex_enter(&ip->i_tlock);
4817 				ip->i_flag |= IACC;
4818 				ITIMES_NOLOCK(ip);
4819 				mutex_exit(&ip->i_tlock);
4820 			}
4821 		}
4822 	}
4823 
4824 	if (dolock) {
4825 		rw_exit(&ip->i_contents);
4826 		if (do_qlock && rwtype == RW_WRITER)
4827 			rw_exit(&ufsvfsp->vfs_dqrwlock);
4828 	}
4829 
4830 unlock:
4831 	if (ulp) {
4832 		if ((rw == S_CREATE || rw == S_WRITE) &&
4833 		    !(vp->v_flag & VISSWAP)) {
4834 			TRANS_END_ASYNC(ufsvfsp, TOP_GETPAGE, trans_size);
4835 		}
4836 		ufs_lockfs_end(ulp);
4837 	}
4838 out:
4839 	return (err);
4840 }
4841 
4842 /*
4843  * ufs_getpage_miss is called when ufs_getpage missed the page in the page
4844  * cache. The page is either read from the disk, or it's created.
4845  * A page is created (without disk read) if rw == S_CREATE, or if
4846  * the page is not backed with a real disk block (UFS hole).
4847  */
4848 /* ARGSUSED */
4849 static int
4850 ufs_getpage_miss(struct vnode *vp, u_offset_t off, size_t len, struct seg *seg,
4851 	caddr_t addr, page_t *pl[], size_t plsz, enum seg_rw rw, int seq)
4852 {
4853 	struct inode	*ip = VTOI(vp);
4854 	page_t		*pp;
4855 	daddr_t		bn;
4856 	size_t		io_len;
4857 	int		crpage = 0;
4858 	int		err;
4859 	int		contig;
4860 	int		bsize = ip->i_fs->fs_bsize;
4861 
4862 	/*
4863 	 * Figure out whether the page can be created, or must be
4864 	 * must be read from the disk.
4865 	 */
4866 	if (rw == S_CREATE)
4867 		crpage = 1;
4868 	else {
4869 		contig = 0;
4870 		if (err = bmap_read(ip, off, &bn, &contig))
4871 			return (err);
4872 
4873 		crpage = (bn == UFS_HOLE);
4874 
4875 		/*
4876 		 * If its also a fallocated block that hasn't been written to
4877 		 * yet, we will treat it just like a UFS_HOLE and create
4878 		 * a zero page for it
4879 		 */
4880 		if (ISFALLOCBLK(ip, bn))
4881 			crpage = 1;
4882 	}
4883 
4884 	if (crpage) {
4885 		if ((pp = page_create_va(vp, off, PAGESIZE, PG_WAIT, seg,
4886 		    addr)) == NULL) {
4887 			return (ufs_fault(vp,
4888 			    "ufs_getpage_miss: page_create == NULL"));
4889 		}
4890 
4891 		if (rw != S_CREATE)
4892 			pagezero(pp, 0, PAGESIZE);
4893 
4894 		io_len = PAGESIZE;
4895 	} else {
4896 		u_offset_t	io_off;
4897 		uint_t	xlen;
4898 		struct buf	*bp;
4899 		ufsvfs_t	*ufsvfsp = ip->i_ufsvfs;
4900 
4901 		/*
4902 		 * If access is not in sequential order, we read from disk
4903 		 * in bsize units.
4904 		 *
4905 		 * We limit the size of the transfer to bsize if we are reading
4906 		 * from the beginning of the file. Note in this situation we
4907 		 * will hedge our bets and initiate an async read ahead of
4908 		 * the second block.
4909 		 */
4910 		if (!seq || off == 0)
4911 			contig = MIN(contig, bsize);
4912 
4913 		pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
4914 		    &io_len, off, contig, 0);
4915 
4916 		/*
4917 		 * Some other thread has entered the page.
4918 		 * ufs_getpage will retry page_lookup.
4919 		 */
4920 		if (pp == NULL) {
4921 			pl[0] = NULL;
4922 			return (0);
4923 		}
4924 
4925 		/*
4926 		 * Zero part of the page which we are not
4927 		 * going to read from the disk.
4928 		 */
4929 		xlen = io_len & PAGEOFFSET;
4930 		if (xlen != 0)
4931 			pagezero(pp->p_prev, xlen, PAGESIZE - xlen);
4932 
4933 		bp = pageio_setup(pp, io_len, ip->i_devvp, B_READ);
4934 		bp->b_edev = ip->i_dev;
4935 		bp->b_dev = cmpdev(ip->i_dev);
4936 		bp->b_blkno = bn;
4937 		bp->b_un.b_addr = (caddr_t)0;
4938 		bp->b_file = ip->i_vnode;
4939 		bp->b_offset = off;
4940 
4941 		if (ufsvfsp->vfs_log) {
4942 			lufs_read_strategy(ufsvfsp->vfs_log, bp);
4943 		} else if (ufsvfsp->vfs_snapshot) {
4944 			fssnap_strategy(&ufsvfsp->vfs_snapshot, bp);
4945 		} else {
4946 			ufsvfsp->vfs_iotstamp = lbolt;
4947 			ub.ub_getpages.value.ul++;
4948 			(void) bdev_strategy(bp);
4949 			lwp_stat_update(LWP_STAT_INBLK, 1);
4950 		}
4951 
4952 		ip->i_nextrio = off + ((io_len + PAGESIZE - 1) & PAGEMASK);
4953 
4954 		/*
4955 		 * If the file access is sequential, initiate read ahead
4956 		 * of the next cluster.
4957 		 */
4958 		if (seq && ip->i_nextrio < ip->i_size)
4959 			(void) ufs_getpage_ra(vp, off, seg, addr);
4960 		err = biowait(bp);
4961 		pageio_done(bp);
4962 
4963 		if (err) {
4964 			pvn_read_done(pp, B_ERROR);
4965 			return (err);
4966 		}
4967 	}
4968 
4969 	pvn_plist_init(pp, pl, plsz, off, io_len, rw);
4970 	return (0);
4971 }
4972 
4973 /*
4974  * Read ahead a cluster from the disk. Returns the length in bytes.
4975  */
4976 static int
4977 ufs_getpage_ra(struct vnode *vp, u_offset_t off, struct seg *seg, caddr_t addr)
4978 {
4979 	struct inode	*ip = VTOI(vp);
4980 	page_t		*pp;
4981 	u_offset_t	io_off = ip->i_nextrio;
4982 	ufsvfs_t	*ufsvfsp;
4983 	caddr_t		addr2 = addr + (io_off - off);
4984 	struct buf	*bp;
4985 	daddr_t		bn;
4986 	size_t		io_len;
4987 	int		err;
4988 	int		contig;
4989 	int		xlen;
4990 	int		bsize = ip->i_fs->fs_bsize;
4991 
4992 	/*
4993 	 * If the directio advisory is in effect on this file,
4994 	 * then do not do buffered read ahead. Read ahead makes
4995 	 * it more difficult on threads using directio as they
4996 	 * will be forced to flush the pages from this vnode.
4997 	 */
4998 	if ((ufsvfsp = ip->i_ufsvfs) == NULL)
4999 		return (0);
5000 	if (ip->i_flag & IDIRECTIO || ufsvfsp->vfs_forcedirectio)
5001 		return (0);
5002 
5003 	/*
5004 	 * Is this test needed?
5005 	 */
5006 	if (addr2 >= seg->s_base + seg->s_size)
5007 		return (0);
5008 
5009 	contig = 0;
5010 	err = bmap_read(ip, io_off, &bn, &contig);
5011 	/*
5012 	 * If its a UFS_HOLE or a fallocated block, do not perform
5013 	 * any read ahead's since there probably is nothing to read ahead
5014 	 */
5015 	if (err || bn == UFS_HOLE || ISFALLOCBLK(ip, bn))
5016 		return (0);
5017 
5018 	/*
5019 	 * Limit the transfer size to bsize if this is the 2nd block.
5020 	 */
5021 	if (io_off == (u_offset_t)bsize)
5022 		contig = MIN(contig, bsize);
5023 
5024 	if ((pp = pvn_read_kluster(vp, io_off, seg, addr2, &io_off,
5025 	    &io_len, io_off, contig, 1)) == NULL)
5026 		return (0);
5027 
5028 	/*
5029 	 * Zero part of page which we are not going to read from disk
5030 	 */
5031 	if ((xlen = (io_len & PAGEOFFSET)) > 0)
5032 		pagezero(pp->p_prev, xlen, PAGESIZE - xlen);
5033 
5034 	ip->i_nextrio = (io_off + io_len + PAGESIZE - 1) & PAGEMASK;
5035 
5036 	bp = pageio_setup(pp, io_len, ip->i_devvp, B_READ | B_ASYNC);
5037 	bp->b_edev = ip->i_dev;
5038 	bp->b_dev = cmpdev(ip->i_dev);
5039 	bp->b_blkno = bn;
5040 	bp->b_un.b_addr = (caddr_t)0;
5041 	bp->b_file = ip->i_vnode;
5042 	bp->b_offset = off;
5043 
5044 	if (ufsvfsp->vfs_log) {
5045 		lufs_read_strategy(ufsvfsp->vfs_log, bp);
5046 	} else if (ufsvfsp->vfs_snapshot) {
5047 		fssnap_strategy(&ufsvfsp->vfs_snapshot, bp);
5048 	} else {
5049 		ufsvfsp->vfs_iotstamp = lbolt;
5050 		ub.ub_getras.value.ul++;
5051 		(void) bdev_strategy(bp);
5052 		lwp_stat_update(LWP_STAT_INBLK, 1);
5053 	}
5054 
5055 	return (io_len);
5056 }
5057 
5058 int	ufs_delay = 1;
5059 /*
5060  * Flags are composed of {B_INVAL, B_FREE, B_DONTNEED, B_FORCE, B_ASYNC}
5061  *
5062  * LMXXX - the inode really ought to contain a pointer to one of these
5063  * async args.  Stuff gunk in there and just hand the whole mess off.
5064  * This would replace i_delaylen, i_delayoff.
5065  */
5066 /*ARGSUSED*/
5067 static int
5068 ufs_putpage(struct vnode *vp, offset_t off, size_t len, int flags,
5069 	struct cred *cr, caller_context_t *ct)
5070 {
5071 	struct inode *ip = VTOI(vp);
5072 	int err = 0;
5073 
5074 	if (vp->v_count == 0) {
5075 		return (ufs_fault(vp, "ufs_putpage: bad v_count == 0"));
5076 	}
5077 
5078 	/*
5079 	 * XXX - Why should this check be made here?
5080 	 */
5081 	if (vp->v_flag & VNOMAP) {
5082 		err = ENOSYS;
5083 		goto errout;
5084 	}
5085 
5086 	if (ip->i_ufsvfs == NULL) {
5087 		err = EIO;
5088 		goto errout;
5089 	}
5090 
5091 	if (flags & B_ASYNC) {
5092 		if (ufs_delay && len &&
5093 		    (flags & ~(B_ASYNC|B_DONTNEED|B_FREE)) == 0) {
5094 			mutex_enter(&ip->i_tlock);
5095 			/*
5096 			 * If nobody stalled, start a new cluster.
5097 			 */
5098 			if (ip->i_delaylen == 0) {
5099 				ip->i_delayoff = off;
5100 				ip->i_delaylen = len;
5101 				mutex_exit(&ip->i_tlock);
5102 				goto errout;
5103 			}
5104 			/*
5105 			 * If we have a full cluster or they are not contig,
5106 			 * then push last cluster and start over.
5107 			 */
5108 			if (ip->i_delaylen >= CLUSTSZ(ip) ||
5109 			    ip->i_delayoff + ip->i_delaylen != off) {
5110 				u_offset_t doff;
5111 				size_t dlen;
5112 
5113 				doff = ip->i_delayoff;
5114 				dlen = ip->i_delaylen;
5115 				ip->i_delayoff = off;
5116 				ip->i_delaylen = len;
5117 				mutex_exit(&ip->i_tlock);
5118 				err = ufs_putpages(vp, doff, dlen,
5119 				    flags, cr);
5120 				/* LMXXX - flags are new val, not old */
5121 				goto errout;
5122 			}
5123 			/*
5124 			 * There is something there, it's not full, and
5125 			 * it is contig.
5126 			 */
5127 			ip->i_delaylen += len;
5128 			mutex_exit(&ip->i_tlock);
5129 			goto errout;
5130 		}
5131 		/*
5132 		 * Must have weird flags or we are not clustering.
5133 		 */
5134 	}
5135 
5136 	err = ufs_putpages(vp, off, len, flags, cr);
5137 
5138 errout:
5139 	return (err);
5140 }
5141 
5142 /*
5143  * If len == 0, do from off to EOF.
5144  *
5145  * The normal cases should be len == 0 & off == 0 (entire vp list),
5146  * len == MAXBSIZE (from segmap_release actions), and len == PAGESIZE
5147  * (from pageout).
5148  */
5149 /*ARGSUSED*/
5150 static int
5151 ufs_putpages(
5152 	struct vnode *vp,
5153 	offset_t off,
5154 	size_t len,
5155 	int flags,
5156 	struct cred *cr)
5157 {
5158 	u_offset_t io_off;
5159 	u_offset_t eoff;
5160 	struct inode *ip = VTOI(vp);
5161 	page_t *pp;
5162 	size_t io_len;
5163 	int err = 0;
5164 	int dolock;
5165 
5166 	if (vp->v_count == 0)
5167 		return (ufs_fault(vp, "ufs_putpages: v_count == 0"));
5168 	/*
5169 	 * Acquire the readers/write inode lock before locking
5170 	 * any pages in this inode.
5171 	 * The inode lock is held during i/o.
5172 	 */
5173 	if (len == 0) {
5174 		mutex_enter(&ip->i_tlock);
5175 		ip->i_delayoff = ip->i_delaylen = 0;
5176 		mutex_exit(&ip->i_tlock);
5177 	}
5178 	dolock = (rw_owner(&ip->i_contents) != curthread);
5179 	if (dolock) {
5180 		/*
5181 		 * Must synchronize this thread and any possible thread
5182 		 * operating in the window of vulnerability in wrip().
5183 		 * It is dangerous to allow both a thread doing a putpage
5184 		 * and a thread writing, so serialize them.  The exception
5185 		 * is when the thread in wrip() does something which causes
5186 		 * a putpage operation.  Then, the thread must be allowed
5187 		 * to continue.  It may encounter a bmap_read problem in
5188 		 * ufs_putapage, but that is handled in ufs_putapage.
5189 		 * Allow async writers to proceed, we don't want to block
5190 		 * the pageout daemon.
5191 		 */
5192 		if (ip->i_writer == curthread)
5193 			rw_enter(&ip->i_contents, RW_READER);
5194 		else {
5195 			for (;;) {
5196 				rw_enter(&ip->i_contents, RW_READER);
5197 				mutex_enter(&ip->i_tlock);
5198 				/*
5199 				 * If there is no thread in the critical
5200 				 * section of wrip(), then proceed.
5201 				 * Otherwise, wait until there isn't one.
5202 				 */
5203 				if (ip->i_writer == NULL) {
5204 					mutex_exit(&ip->i_tlock);
5205 					break;
5206 				}
5207 				rw_exit(&ip->i_contents);
5208 				/*
5209 				 * Bounce async writers when we have a writer
5210 				 * working on this file so we don't deadlock
5211 				 * the pageout daemon.
5212 				 */
5213 				if (flags & B_ASYNC) {
5214 					mutex_exit(&ip->i_tlock);
5215 					return (0);
5216 				}
5217 				cv_wait(&ip->i_wrcv, &ip->i_tlock);
5218 				mutex_exit(&ip->i_tlock);
5219 			}
5220 		}
5221 	}
5222 
5223 	if (!vn_has_cached_data(vp)) {
5224 		if (dolock)
5225 			rw_exit(&ip->i_contents);
5226 		return (0);
5227 	}
5228 
5229 	if (len == 0) {
5230 		/*
5231 		 * Search the entire vp list for pages >= off.
5232 		 */
5233 		err = pvn_vplist_dirty(vp, (u_offset_t)off, ufs_putapage,
5234 		    flags, cr);
5235 	} else {
5236 		/*
5237 		 * Loop over all offsets in the range looking for
5238 		 * pages to deal with.
5239 		 */
5240 		if ((eoff = blkroundup(ip->i_fs, ip->i_size)) != 0)
5241 			eoff = MIN(off + len, eoff);
5242 		else
5243 			eoff = off + len;
5244 
5245 		for (io_off = off; io_off < eoff; io_off += io_len) {
5246 			/*
5247 			 * If we are not invalidating, synchronously
5248 			 * freeing or writing pages, use the routine
5249 			 * page_lookup_nowait() to prevent reclaiming
5250 			 * them from the free list.
5251 			 */
5252 			if ((flags & B_INVAL) || ((flags & B_ASYNC) == 0)) {
5253 				pp = page_lookup(vp, io_off,
5254 				    (flags & (B_INVAL | B_FREE)) ?
5255 				    SE_EXCL : SE_SHARED);
5256 			} else {
5257 				pp = page_lookup_nowait(vp, io_off,
5258 				    (flags & B_FREE) ? SE_EXCL : SE_SHARED);
5259 			}
5260 
5261 			if (pp == NULL || pvn_getdirty(pp, flags) == 0)
5262 				io_len = PAGESIZE;
5263 			else {
5264 				u_offset_t *io_offp = &io_off;
5265 
5266 				err = ufs_putapage(vp, pp, io_offp, &io_len,
5267 				    flags, cr);
5268 				if (err != 0)
5269 					break;
5270 				/*
5271 				 * "io_off" and "io_len" are returned as
5272 				 * the range of pages we actually wrote.
5273 				 * This allows us to skip ahead more quickly
5274 				 * since several pages may've been dealt
5275 				 * with by this iteration of the loop.
5276 				 */
5277 			}
5278 		}
5279 	}
5280 	if (err == 0 && off == 0 && (len == 0 || len >= ip->i_size)) {
5281 		/*
5282 		 * We have just sync'ed back all the pages on
5283 		 * the inode, turn off the IMODTIME flag.
5284 		 */
5285 		mutex_enter(&ip->i_tlock);
5286 		ip->i_flag &= ~IMODTIME;
5287 		mutex_exit(&ip->i_tlock);
5288 	}
5289 	if (dolock)
5290 		rw_exit(&ip->i_contents);
5291 	return (err);
5292 }
5293 
5294 static void
5295 ufs_iodone(buf_t *bp)
5296 {
5297 	struct inode *ip;
5298 
5299 	ASSERT((bp->b_pages->p_vnode != NULL) && !(bp->b_flags & B_READ));
5300 
5301 	bp->b_iodone = NULL;
5302 
5303 	ip = VTOI(bp->b_pages->p_vnode);
5304 
5305 	mutex_enter(&ip->i_tlock);
5306 	if (ip->i_writes >= ufs_LW) {
5307 		if ((ip->i_writes -= bp->b_bcount) <= ufs_LW)
5308 			if (ufs_WRITES)
5309 				cv_broadcast(&ip->i_wrcv); /* wake all up */
5310 	} else {
5311 		ip->i_writes -= bp->b_bcount;
5312 	}
5313 
5314 	mutex_exit(&ip->i_tlock);
5315 	iodone(bp);
5316 }
5317 
5318 /*
5319  * Write out a single page, possibly klustering adjacent
5320  * dirty pages.  The inode lock must be held.
5321  *
5322  * LMXXX - bsize < pagesize not done.
5323  */
5324 /*ARGSUSED*/
5325 int
5326 ufs_putapage(
5327 	struct vnode *vp,
5328 	page_t *pp,
5329 	u_offset_t *offp,
5330 	size_t *lenp,		/* return values */
5331 	int flags,
5332 	struct cred *cr)
5333 {
5334 	u_offset_t io_off;
5335 	u_offset_t off;
5336 	struct inode *ip = VTOI(vp);
5337 	struct ufsvfs *ufsvfsp = ip->i_ufsvfs;
5338 	struct fs *fs;
5339 	struct buf *bp;
5340 	size_t io_len;
5341 	daddr_t bn;
5342 	int err;
5343 	int contig;
5344 	int dotrans;
5345 
5346 	ASSERT(RW_LOCK_HELD(&ip->i_contents));
5347 
5348 	if (ufsvfsp == NULL) {
5349 		err = EIO;
5350 		goto out_trace;
5351 	}
5352 
5353 	fs = ip->i_fs;
5354 	ASSERT(fs->fs_ronly == 0);
5355 
5356 	/*
5357 	 * If the modified time on the inode has not already been
5358 	 * set elsewhere (e.g. for write/setattr) we set the time now.
5359 	 * This gives us approximate modified times for mmap'ed files
5360 	 * which are modified via stores in the user address space.
5361 	 */
5362 	if ((ip->i_flag & IMODTIME) == 0) {
5363 		mutex_enter(&ip->i_tlock);
5364 		ip->i_flag |= IUPD;
5365 		ip->i_seq++;
5366 		ITIMES_NOLOCK(ip);
5367 		mutex_exit(&ip->i_tlock);
5368 	}
5369 
5370 	/*
5371 	 * Align the request to a block boundry (for old file systems),
5372 	 * and go ask bmap() how contiguous things are for this file.
5373 	 */
5374 	off = pp->p_offset & (offset_t)fs->fs_bmask;	/* block align it */
5375 	contig = 0;
5376 	err = bmap_read(ip, off, &bn, &contig);
5377 	if (err)
5378 		goto out;
5379 	if (bn == UFS_HOLE) {			/* putpage never allocates */
5380 		/*
5381 		 * logging device is in error mode; simply return EIO
5382 		 */
5383 		if (TRANS_ISERROR(ufsvfsp)) {
5384 			err = EIO;
5385 			goto out;
5386 		}
5387 		/*
5388 		 * Oops, the thread in the window in wrip() did some
5389 		 * sort of operation which caused a putpage in the bad
5390 		 * range.  In this case, just return an error which will
5391 		 * cause the software modified bit on the page to set
5392 		 * and the page will get written out again later.
5393 		 */
5394 		if (ip->i_writer == curthread) {
5395 			err = EIO;
5396 			goto out;
5397 		}
5398 		/*
5399 		 * If the pager is trying to push a page in the bad range
5400 		 * just tell him to try again later when things are better.
5401 		 */
5402 		if (flags & B_ASYNC) {
5403 			err = EAGAIN;
5404 			goto out;
5405 		}
5406 		err = ufs_fault(ITOV(ip), "ufs_putapage: bn == UFS_HOLE");
5407 		goto out;
5408 	}
5409 
5410 	/*
5411 	 * If it is an fallocate'd block, reverse the negativity since
5412 	 * we are now writing to it
5413 	 */
5414 	if (ISFALLOCBLK(ip, bn)) {
5415 		err = bmap_set_bn(vp, off, dbtofsb(fs, -bn));
5416 		if (err)
5417 			goto out;
5418 
5419 		bn = -bn;
5420 	}
5421 
5422 	/*
5423 	 * Take the length (of contiguous bytes) passed back from bmap()
5424 	 * and _try_ and get a set of pages covering that extent.
5425 	 */
5426 	pp = pvn_write_kluster(vp, pp, &io_off, &io_len, off, contig, flags);
5427 
5428 	/*
5429 	 * May have run out of memory and not clustered backwards.
5430 	 * off		p_offset
5431 	 * [  pp - 1  ][   pp   ]
5432 	 * [	block		]
5433 	 * We told bmap off, so we have to adjust the bn accordingly.
5434 	 */
5435 	if (io_off > off) {
5436 		bn += btod(io_off - off);
5437 		contig -= (io_off - off);
5438 	}
5439 
5440 	/*
5441 	 * bmap was carefull to tell us the right size so use that.
5442 	 * There might be unallocated frags at the end.
5443 	 * LMXXX - bzero the end of the page?  We must be writing after EOF.
5444 	 */
5445 	if (io_len > contig) {
5446 		ASSERT(io_len - contig < fs->fs_bsize);
5447 		io_len -= (io_len - contig);
5448 	}
5449 
5450 	/*
5451 	 * Handle the case where we are writing the last page after EOF.
5452 	 *
5453 	 * XXX - just a patch for i-mt3.
5454 	 */
5455 	if (io_len == 0) {
5456 		ASSERT(pp->p_offset >=
5457 		    (u_offset_t)(roundup(ip->i_size, PAGESIZE)));
5458 		io_len = PAGESIZE;
5459 	}
5460 
5461 	bp = pageio_setup(pp, io_len, ip->i_devvp, B_WRITE | flags);
5462 
5463 	ULOCKFS_SET_MOD(ITOUL(ip));
5464 
5465 	bp->b_edev = ip->i_dev;
5466 	bp->b_dev = cmpdev(ip->i_dev);
5467 	bp->b_blkno = bn;
5468 	bp->b_un.b_addr = (caddr_t)0;
5469 	bp->b_file = ip->i_vnode;
5470 
5471 	/*
5472 	 * File contents of shadow or quota inodes are metadata, and updates
5473 	 * to these need to be put into a logging transaction. All direct
5474 	 * callers in UFS do that, but fsflush can come here _before_ the
5475 	 * normal codepath. An example would be updating ACL information, for
5476 	 * which the normal codepath would be:
5477 	 *	ufs_si_store()
5478 	 *	ufs_rdwri()
5479 	 *	wrip()
5480 	 *	segmap_release()
5481 	 *	VOP_PUTPAGE()
5482 	 * Here, fsflush can pick up the dirty page before segmap_release()
5483 	 * forces it out. If that happens, there's no transaction.
5484 	 * We therefore need to test whether a transaction exists, and if not
5485 	 * create one - for fsflush.
5486 	 */
5487 	dotrans =
5488 	    (((ip->i_mode & IFMT) == IFSHAD || ufsvfsp->vfs_qinod == ip) &&
5489 	    ((curthread->t_flag & T_DONTBLOCK) == 0) &&
5490 	    (TRANS_ISTRANS(ufsvfsp)));
5491 
5492 	if (dotrans) {
5493 		curthread->t_flag |= T_DONTBLOCK;
5494 		TRANS_BEGIN_ASYNC(ufsvfsp, TOP_PUTPAGE, TOP_PUTPAGE_SIZE(ip));
5495 	}
5496 	if (TRANS_ISTRANS(ufsvfsp)) {
5497 		if ((ip->i_mode & IFMT) == IFSHAD) {
5498 			TRANS_BUF(ufsvfsp, 0, io_len, bp, DT_SHAD);
5499 		} else if (ufsvfsp->vfs_qinod == ip) {
5500 			TRANS_DELTA(ufsvfsp, ldbtob(bn), bp->b_bcount, DT_QR,
5501 			    0, 0);
5502 		}
5503 	}
5504 	if (dotrans) {
5505 		TRANS_END_ASYNC(ufsvfsp, TOP_PUTPAGE, TOP_PUTPAGE_SIZE(ip));
5506 		curthread->t_flag &= ~T_DONTBLOCK;
5507 	}
5508 
5509 	/* write throttle */
5510 
5511 	ASSERT(bp->b_iodone == NULL);
5512 	bp->b_iodone = (int (*)())ufs_iodone;
5513 	mutex_enter(&ip->i_tlock);
5514 	ip->i_writes += bp->b_bcount;
5515 	mutex_exit(&ip->i_tlock);
5516 
5517 	if (bp->b_flags & B_ASYNC) {
5518 		if (ufsvfsp->vfs_log) {
5519 			lufs_write_strategy(ufsvfsp->vfs_log, bp);
5520 		} else if (ufsvfsp->vfs_snapshot) {
5521 			fssnap_strategy(&ufsvfsp->vfs_snapshot, bp);
5522 		} else {
5523 			ufsvfsp->vfs_iotstamp = lbolt;
5524 			ub.ub_putasyncs.value.ul++;
5525 			(void) bdev_strategy(bp);
5526 			lwp_stat_update(LWP_STAT_OUBLK, 1);
5527 		}
5528 	} else {
5529 		if (ufsvfsp->vfs_log) {
5530 			lufs_write_strategy(ufsvfsp->vfs_log, bp);
5531 		} else if (ufsvfsp->vfs_snapshot) {
5532 			fssnap_strategy(&ufsvfsp->vfs_snapshot, bp);
5533 		} else {
5534 			ufsvfsp->vfs_iotstamp = lbolt;
5535 			ub.ub_putsyncs.value.ul++;
5536 			(void) bdev_strategy(bp);
5537 			lwp_stat_update(LWP_STAT_OUBLK, 1);
5538 		}
5539 		err = biowait(bp);
5540 		pageio_done(bp);
5541 		pvn_write_done(pp, ((err) ? B_ERROR : 0) | B_WRITE | flags);
5542 	}
5543 
5544 	pp = NULL;
5545 
5546 out:
5547 	if (err != 0 && pp != NULL)
5548 		pvn_write_done(pp, B_ERROR | B_WRITE | flags);
5549 
5550 	if (offp)
5551 		*offp = io_off;
5552 	if (lenp)
5553 		*lenp = io_len;
5554 out_trace:
5555 	return (err);
5556 }
5557 
5558 uint64_t ufs_map_alock_retry_cnt;
5559 uint64_t ufs_map_lockfs_retry_cnt;
5560 
5561 /* ARGSUSED */
5562 static int
5563 ufs_map(struct vnode *vp,
5564 	offset_t off,
5565 	struct as *as,
5566 	caddr_t *addrp,
5567 	size_t len,
5568 	uchar_t prot,
5569 	uchar_t maxprot,
5570 	uint_t flags,
5571 	struct cred *cr,
5572 	caller_context_t *ct)
5573 {
5574 	struct segvn_crargs vn_a;
5575 	struct ufsvfs *ufsvfsp = VTOI(vp)->i_ufsvfs;
5576 	struct ulockfs *ulp;
5577 	int error, sig;
5578 	k_sigset_t smask;
5579 	caddr_t hint = *addrp;
5580 
5581 	if (vp->v_flag & VNOMAP) {
5582 		error = ENOSYS;
5583 		goto out;
5584 	}
5585 
5586 	if (off < (offset_t)0 || (offset_t)(off + len) < (offset_t)0) {
5587 		error = ENXIO;
5588 		goto out;
5589 	}
5590 
5591 	if (vp->v_type != VREG) {
5592 		error = ENODEV;
5593 		goto out;
5594 	}
5595 
5596 retry_map:
5597 	*addrp = hint;
5598 	/*
5599 	 * If file is being locked, disallow mapping.
5600 	 */
5601 	if (vn_has_mandatory_locks(vp, VTOI(vp)->i_mode)) {
5602 		error = EAGAIN;
5603 		goto out;
5604 	}
5605 
5606 	as_rangelock(as);
5607 	/*
5608 	 * Note that if we are retrying (because ufs_lockfs_trybegin failed in
5609 	 * the previous attempt), some other thread could have grabbed
5610 	 * the same VA range if MAP_FIXED is set. In that case, choose_addr
5611 	 * would unmap the valid VA range, that is ok.
5612 	 */
5613 	error = choose_addr(as, addrp, len, off, ADDR_VACALIGN, flags);
5614 	if (error != 0) {
5615 		as_rangeunlock(as);
5616 		goto out;
5617 	}
5618 
5619 	/*
5620 	 * a_lock has to be acquired before entering the lockfs protocol
5621 	 * because that is the order in which pagefault works. Also we cannot
5622 	 * block on a_lock here because this waiting writer will prevent
5623 	 * further readers like ufs_read from progressing and could cause
5624 	 * deadlock between ufs_read/ufs_map/pagefault when a quiesce is
5625 	 * pending.
5626 	 */
5627 	while (!AS_LOCK_TRYENTER(as, &as->a_lock, RW_WRITER)) {
5628 		ufs_map_alock_retry_cnt++;
5629 		delay(RETRY_LOCK_DELAY);
5630 	}
5631 
5632 	/*
5633 	 * We can't hold as->a_lock and wait for lockfs to succeed because
5634 	 * the proc tools might hang on a_lock, so call ufs_lockfs_trybegin()
5635 	 * instead.
5636 	 */
5637 	if (error = ufs_lockfs_trybegin(ufsvfsp, &ulp, ULOCKFS_MAP_MASK)) {
5638 		/*
5639 		 * ufs_lockfs_trybegin() did not succeed. It is safer to give up
5640 		 * as->a_lock and wait for ulp->ul_fs_lock status to change.
5641 		 */
5642 		ufs_map_lockfs_retry_cnt++;
5643 		AS_LOCK_EXIT(as, &as->a_lock);
5644 		as_rangeunlock(as);
5645 		if (error == EIO)
5646 			goto out;
5647 
5648 		mutex_enter(&ulp->ul_lock);
5649 		while (ulp->ul_fs_lock & ULOCKFS_MAP_MASK) {
5650 			if (ULOCKFS_IS_SLOCK(ulp) || ufsvfsp->vfs_nointr) {
5651 				cv_wait(&ulp->ul_cv, &ulp->ul_lock);
5652 			} else {
5653 				sigintr(&smask, 1);
5654 				sig = cv_wait_sig(&ulp->ul_cv, &ulp->ul_lock);
5655 				sigunintr(&smask);
5656 				if (((ulp->ul_fs_lock & ULOCKFS_MAP_MASK) &&
5657 				    !sig) || ufsvfsp->vfs_dontblock) {
5658 					mutex_exit(&ulp->ul_lock);
5659 					return (EINTR);
5660 				}
5661 			}
5662 		}
5663 		mutex_exit(&ulp->ul_lock);
5664 		goto retry_map;
5665 	}
5666 
5667 	vn_a.vp = vp;
5668 	vn_a.offset = (u_offset_t)off;
5669 	vn_a.type = flags & MAP_TYPE;
5670 	vn_a.prot = prot;
5671 	vn_a.maxprot = maxprot;
5672 	vn_a.cred = cr;
5673 	vn_a.amp = NULL;
5674 	vn_a.flags = flags & ~MAP_TYPE;
5675 	vn_a.szc = 0;
5676 	vn_a.lgrp_mem_policy_flags = 0;
5677 
5678 	error = as_map_locked(as, *addrp, len, segvn_create, &vn_a);
5679 	if (ulp)
5680 		ufs_lockfs_end(ulp);
5681 	as_rangeunlock(as);
5682 out:
5683 	return (error);
5684 }
5685 
5686 /* ARGSUSED */
5687 static int
5688 ufs_addmap(struct vnode *vp,
5689 	offset_t off,
5690 	struct as *as,
5691 	caddr_t addr,
5692 	size_t	len,
5693 	uchar_t  prot,
5694 	uchar_t  maxprot,
5695 	uint_t    flags,
5696 	struct cred *cr,
5697 	caller_context_t *ct)
5698 {
5699 	struct inode *ip = VTOI(vp);
5700 
5701 	if (vp->v_flag & VNOMAP) {
5702 		return (ENOSYS);
5703 	}
5704 
5705 	mutex_enter(&ip->i_tlock);
5706 	ip->i_mapcnt += btopr(len);
5707 	mutex_exit(&ip->i_tlock);
5708 	return (0);
5709 }
5710 
5711 /*ARGSUSED*/
5712 static int
5713 ufs_delmap(struct vnode *vp, offset_t off, struct as *as, caddr_t addr,
5714 	size_t len, uint_t prot,  uint_t maxprot,  uint_t flags,
5715 	struct cred *cr, caller_context_t *ct)
5716 {
5717 	struct inode *ip = VTOI(vp);
5718 
5719 	if (vp->v_flag & VNOMAP) {
5720 		return (ENOSYS);
5721 	}
5722 
5723 	mutex_enter(&ip->i_tlock);
5724 	ip->i_mapcnt -= btopr(len); 	/* Count released mappings */
5725 	ASSERT(ip->i_mapcnt >= 0);
5726 	mutex_exit(&ip->i_tlock);
5727 	return (0);
5728 }
5729 /*
5730  * Return the answer requested to poll() for non-device files
5731  */
5732 struct pollhead ufs_pollhd;
5733 
5734 /* ARGSUSED */
5735 int
5736 ufs_poll(vnode_t *vp, short ev, int any, short *revp, struct pollhead **phpp,
5737 	caller_context_t *ct)
5738 {
5739 	struct ufsvfs	*ufsvfsp;
5740 
5741 	*revp = 0;
5742 	ufsvfsp = VTOI(vp)->i_ufsvfs;
5743 
5744 	if (!ufsvfsp) {
5745 		*revp = POLLHUP;
5746 		goto out;
5747 	}
5748 
5749 	if (ULOCKFS_IS_HLOCK(&ufsvfsp->vfs_ulockfs) ||
5750 	    ULOCKFS_IS_ELOCK(&ufsvfsp->vfs_ulockfs)) {
5751 		*revp |= POLLERR;
5752 
5753 	} else {
5754 		if ((ev & POLLOUT) && !ufsvfsp->vfs_fs->fs_ronly &&
5755 		    !ULOCKFS_IS_WLOCK(&ufsvfsp->vfs_ulockfs))
5756 			*revp |= POLLOUT;
5757 
5758 		if ((ev & POLLWRBAND) && !ufsvfsp->vfs_fs->fs_ronly &&
5759 		    !ULOCKFS_IS_WLOCK(&ufsvfsp->vfs_ulockfs))
5760 			*revp |= POLLWRBAND;
5761 
5762 		if (ev & POLLIN)
5763 			*revp |= POLLIN;
5764 
5765 		if (ev & POLLRDNORM)
5766 			*revp |= POLLRDNORM;
5767 
5768 		if (ev & POLLRDBAND)
5769 			*revp |= POLLRDBAND;
5770 	}
5771 
5772 	if ((ev & POLLPRI) && (*revp & (POLLERR|POLLHUP)))
5773 		*revp |= POLLPRI;
5774 out:
5775 	*phpp = !any && !*revp ? &ufs_pollhd : (struct pollhead *)NULL;
5776 
5777 	return (0);
5778 }
5779 
5780 /* ARGSUSED */
5781 static int
5782 ufs_l_pathconf(struct vnode *vp, int cmd, ulong_t *valp, struct cred *cr,
5783 	caller_context_t *ct)
5784 {
5785 	struct ufsvfs	*ufsvfsp = VTOI(vp)->i_ufsvfs;
5786 	struct ulockfs	*ulp = NULL;
5787 	struct inode 	*sip = NULL;
5788 	int		error;
5789 	struct inode 	*ip = VTOI(vp);
5790 	int		issync;
5791 
5792 	error = ufs_lockfs_begin(ufsvfsp, &ulp, ULOCKFS_PATHCONF_MASK);
5793 	if (error)
5794 		return (error);
5795 
5796 	switch (cmd) {
5797 		/*
5798 		 * Have to handle _PC_NAME_MAX here, because the normal way
5799 		 * [fs_pathconf() -> VOP_STATVFS() -> ufs_statvfs()]
5800 		 * results in a lock ordering reversal between
5801 		 * ufs_lockfs_{begin,end}() and
5802 		 * ufs_thread_{suspend,continue}().
5803 		 *
5804 		 * Keep in sync with ufs_statvfs().
5805 		 */
5806 	case _PC_NAME_MAX:
5807 		*valp = MAXNAMLEN;
5808 		break;
5809 
5810 	case _PC_FILESIZEBITS:
5811 		if (ufsvfsp->vfs_lfflags & UFS_LARGEFILES)
5812 			*valp = UFS_FILESIZE_BITS;
5813 		else
5814 			*valp = 32;
5815 		break;
5816 
5817 	case _PC_XATTR_EXISTS:
5818 		if (vp->v_vfsp->vfs_flag & VFS_XATTR) {
5819 
5820 			error =
5821 			    ufs_xattr_getattrdir(vp, &sip, LOOKUP_XATTR, cr);
5822 			if (error ==  0 && sip != NULL) {
5823 				/* Start transaction */
5824 				if (ulp) {
5825 					TRANS_BEGIN_CSYNC(ufsvfsp, issync,
5826 					    TOP_RMDIR, TOP_RMDIR_SIZE);
5827 				}
5828 				/*
5829 				 * Is directory empty
5830 				 */
5831 				rw_enter(&sip->i_rwlock, RW_WRITER);
5832 				rw_enter(&sip->i_contents, RW_WRITER);
5833 				if (ufs_xattrdirempty(sip,
5834 				    sip->i_number, CRED())) {
5835 					rw_enter(&ip->i_contents, RW_WRITER);
5836 					ufs_unhook_shadow(ip, sip);
5837 					rw_exit(&ip->i_contents);
5838 
5839 					*valp = 0;
5840 
5841 				} else
5842 					*valp = 1;
5843 				rw_exit(&sip->i_contents);
5844 				rw_exit(&sip->i_rwlock);
5845 				if (ulp) {
5846 					TRANS_END_CSYNC(ufsvfsp, error, issync,
5847 					    TOP_RMDIR, TOP_RMDIR_SIZE);
5848 				}
5849 				VN_RELE(ITOV(sip));
5850 			} else if (error == ENOENT) {
5851 				*valp = 0;
5852 				error = 0;
5853 			}
5854 		} else {
5855 			error = fs_pathconf(vp, cmd, valp, cr, ct);
5856 		}
5857 		break;
5858 
5859 	case _PC_ACL_ENABLED:
5860 		*valp = _ACL_ACLENT_ENABLED;
5861 		break;
5862 
5863 	case _PC_MIN_HOLE_SIZE:
5864 		*valp = (ulong_t)ip->i_fs->fs_bsize;
5865 		break;
5866 
5867 	case _PC_SATTR_ENABLED:
5868 	case _PC_SATTR_EXISTS:
5869 		*valp = vfs_has_feature(vp->v_vfsp, VFSFT_XVATTR) &&
5870 		    (vp->v_type == VREG || vp->v_type == VDIR);
5871 		break;
5872 
5873 	default:
5874 		error = fs_pathconf(vp, cmd, valp, cr, ct);
5875 	}
5876 
5877 	if (ulp != NULL) {
5878 		ufs_lockfs_end(ulp);
5879 	}
5880 	return (error);
5881 }
5882 
5883 int ufs_pageio_writes, ufs_pageio_reads;
5884 
5885 /*ARGSUSED*/
5886 static int
5887 ufs_pageio(struct vnode *vp, page_t *pp, u_offset_t io_off, size_t io_len,
5888 	int flags, struct cred *cr, caller_context_t *ct)
5889 {
5890 	struct inode *ip = VTOI(vp);
5891 	struct ufsvfs *ufsvfsp;
5892 	page_t *npp = NULL, *opp = NULL, *cpp = pp;
5893 	struct buf *bp;
5894 	daddr_t bn;
5895 	size_t done_len = 0, cur_len = 0;
5896 	int err = 0;
5897 	int contig = 0;
5898 	int dolock;
5899 	int vmpss = 0;
5900 	struct ulockfs *ulp;
5901 
5902 	if ((flags & B_READ) && pp != NULL && pp->p_vnode == vp &&
5903 	    vp->v_mpssdata != NULL) {
5904 		vmpss = 1;
5905 	}
5906 
5907 	dolock = (rw_owner(&ip->i_contents) != curthread);
5908 	/*
5909 	 * We need a better check.  Ideally, we would use another
5910 	 * vnodeops so that hlocked and forcibly unmounted file
5911 	 * systems would return EIO where appropriate and w/o the
5912 	 * need for these checks.
5913 	 */
5914 	if ((ufsvfsp = ip->i_ufsvfs) == NULL)
5915 		return (EIO);
5916 
5917 	/*
5918 	 * For vmpss (pp can be NULL) case respect the quiesce protocol.
5919 	 * ul_lock must be taken before locking pages so we can't use it here
5920 	 * if pp is non NULL because segvn already locked pages
5921 	 * SE_EXCL. Instead we rely on the fact that a forced umount or
5922 	 * applying a filesystem lock via ufs_fiolfs() will block in the
5923 	 * implicit call to ufs_flush() until we unlock the pages after the
5924 	 * return to segvn. Other ufs_quiesce() callers keep ufs_quiesce_pend
5925 	 * above 0 until they are done. We have to be careful not to increment
5926 	 * ul_vnops_cnt here after forceful unmount hlocks the file system.
5927 	 *
5928 	 * If pp is NULL use ul_lock to make sure we don't increment
5929 	 * ul_vnops_cnt after forceful unmount hlocks the file system.
5930 	 */
5931 	if (vmpss || pp == NULL) {
5932 		ulp = &ufsvfsp->vfs_ulockfs;
5933 		if (pp == NULL)
5934 			mutex_enter(&ulp->ul_lock);
5935 		if (ulp->ul_fs_lock & ULOCKFS_GETREAD_MASK) {
5936 			if (pp == NULL) {
5937 				mutex_exit(&ulp->ul_lock);
5938 			}
5939 			return (vmpss ? EIO : EINVAL);
5940 		}
5941 		atomic_add_long(&ulp->ul_vnops_cnt, 1);
5942 		if (pp == NULL)
5943 			mutex_exit(&ulp->ul_lock);
5944 		if (ufs_quiesce_pend) {
5945 			if (!atomic_add_long_nv(&ulp->ul_vnops_cnt, -1))
5946 				cv_broadcast(&ulp->ul_cv);
5947 			return (vmpss ? EIO : EINVAL);
5948 		}
5949 	}
5950 
5951 	if (dolock) {
5952 		/*
5953 		 * segvn may call VOP_PAGEIO() instead of VOP_GETPAGE() to
5954 		 * handle a fault against a segment that maps vnode pages with
5955 		 * large mappings.  Segvn creates pages and holds them locked
5956 		 * SE_EXCL during VOP_PAGEIO() call. In this case we have to
5957 		 * use rw_tryenter() to avoid a potential deadlock since in
5958 		 * lock order i_contents needs to be taken first.
5959 		 * Segvn will retry via VOP_GETPAGE() if VOP_PAGEIO() fails.
5960 		 */
5961 		if (!vmpss) {
5962 			rw_enter(&ip->i_contents, RW_READER);
5963 		} else if (!rw_tryenter(&ip->i_contents, RW_READER)) {
5964 			if (!atomic_add_long_nv(&ulp->ul_vnops_cnt, -1))
5965 				cv_broadcast(&ulp->ul_cv);
5966 			return (EDEADLK);
5967 		}
5968 	}
5969 
5970 	/*
5971 	 * Return an error to segvn because the pagefault request is beyond
5972 	 * PAGESIZE rounded EOF.
5973 	 */
5974 	if (vmpss && btopr(io_off + io_len) > btopr(ip->i_size)) {
5975 		if (dolock)
5976 			rw_exit(&ip->i_contents);
5977 		if (!atomic_add_long_nv(&ulp->ul_vnops_cnt, -1))
5978 			cv_broadcast(&ulp->ul_cv);
5979 		return (EFAULT);
5980 	}
5981 
5982 	if (pp == NULL) {
5983 		if (bmap_has_holes(ip)) {
5984 			err = ENOSYS;
5985 		} else {
5986 			err = EINVAL;
5987 		}
5988 		if (dolock)
5989 			rw_exit(&ip->i_contents);
5990 		if (!atomic_add_long_nv(&ulp->ul_vnops_cnt, -1))
5991 			cv_broadcast(&ulp->ul_cv);
5992 		return (err);
5993 	}
5994 
5995 	/*
5996 	 * Break the io request into chunks, one for each contiguous
5997 	 * stretch of disk blocks in the target file.
5998 	 */
5999 	while (done_len < io_len) {
6000 		ASSERT(cpp);
6001 		contig = 0;
6002 		if (err = bmap_read(ip, (u_offset_t)(io_off + done_len),
6003 		    &bn, &contig))
6004 			break;
6005 
6006 		if (bn == UFS_HOLE) {	/* No holey swapfiles */
6007 			if (vmpss) {
6008 				err = EFAULT;
6009 				break;
6010 			}
6011 			err = ufs_fault(ITOV(ip), "ufs_pageio: bn == UFS_HOLE");
6012 			break;
6013 		}
6014 
6015 		cur_len = MIN(io_len - done_len, contig);
6016 		/*
6017 		 * Zero out a page beyond EOF, when the last block of
6018 		 * a file is a UFS fragment so that ufs_pageio() can be used
6019 		 * instead of ufs_getpage() to handle faults against
6020 		 * segvn segments that use large pages.
6021 		 */
6022 		page_list_break(&cpp, &npp, btopr(cur_len));
6023 		if ((flags & B_READ) && (cur_len & PAGEOFFSET)) {
6024 			size_t xlen = cur_len & PAGEOFFSET;
6025 			pagezero(cpp->p_prev, xlen, PAGESIZE - xlen);
6026 		}
6027 
6028 		bp = pageio_setup(cpp, cur_len, ip->i_devvp, flags);
6029 		ASSERT(bp != NULL);
6030 
6031 		bp->b_edev = ip->i_dev;
6032 		bp->b_dev = cmpdev(ip->i_dev);
6033 		bp->b_blkno = bn;
6034 		bp->b_un.b_addr = (caddr_t)0;
6035 		bp->b_file = ip->i_vnode;
6036 
6037 		ufsvfsp->vfs_iotstamp = lbolt;
6038 		ub.ub_pageios.value.ul++;
6039 		if (ufsvfsp->vfs_snapshot)
6040 			fssnap_strategy(&(ufsvfsp->vfs_snapshot), bp);
6041 		else
6042 			(void) bdev_strategy(bp);
6043 
6044 		if (flags & B_READ)
6045 			ufs_pageio_reads++;
6046 		else
6047 			ufs_pageio_writes++;
6048 		if (flags & B_READ)
6049 			lwp_stat_update(LWP_STAT_INBLK, 1);
6050 		else
6051 			lwp_stat_update(LWP_STAT_OUBLK, 1);
6052 		/*
6053 		 * If the request is not B_ASYNC, wait for i/o to complete
6054 		 * and re-assemble the page list to return to the caller.
6055 		 * If it is B_ASYNC we leave the page list in pieces and
6056 		 * cleanup() will dispose of them.
6057 		 */
6058 		if ((flags & B_ASYNC) == 0) {
6059 			err = biowait(bp);
6060 			pageio_done(bp);
6061 			if (err)
6062 				break;
6063 			page_list_concat(&opp, &cpp);
6064 		}
6065 		cpp = npp;
6066 		npp = NULL;
6067 		if (flags & B_READ)
6068 			cur_len = P2ROUNDUP_TYPED(cur_len, PAGESIZE, size_t);
6069 		done_len += cur_len;
6070 	}
6071 	ASSERT(err || (cpp == NULL && npp == NULL && done_len == io_len));
6072 	if (err) {
6073 		if (flags & B_ASYNC) {
6074 			/* Cleanup unprocessed parts of list */
6075 			page_list_concat(&cpp, &npp);
6076 			if (flags & B_READ)
6077 				pvn_read_done(cpp, B_ERROR);
6078 			else
6079 				pvn_write_done(cpp, B_ERROR);
6080 		} else {
6081 			/* Re-assemble list and let caller clean up */
6082 			page_list_concat(&opp, &cpp);
6083 			page_list_concat(&opp, &npp);
6084 		}
6085 	}
6086 
6087 	if (vmpss && !(ip->i_flag & IACC) && !ULOCKFS_IS_NOIACC(ulp) &&
6088 	    ufsvfsp->vfs_fs->fs_ronly == 0 && !ufsvfsp->vfs_noatime) {
6089 		mutex_enter(&ip->i_tlock);
6090 		ip->i_flag |= IACC;
6091 		ITIMES_NOLOCK(ip);
6092 		mutex_exit(&ip->i_tlock);
6093 	}
6094 
6095 	if (dolock)
6096 		rw_exit(&ip->i_contents);
6097 	if (vmpss && !atomic_add_long_nv(&ulp->ul_vnops_cnt, -1))
6098 		cv_broadcast(&ulp->ul_cv);
6099 	return (err);
6100 }
6101 
6102 /*
6103  * Called when the kernel is in a frozen state to dump data
6104  * directly to the device. It uses a private dump data structure,
6105  * set up by dump_ctl, to locate the correct disk block to which to dump.
6106  */
6107 /*ARGSUSED*/
6108 static int
6109 ufs_dump(vnode_t *vp, caddr_t addr, offset_t ldbn, offset_t dblks,
6110     caller_context_t *ct)
6111 {
6112 	u_offset_t	file_size;
6113 	struct inode    *ip = VTOI(vp);
6114 	struct fs	*fs = ip->i_fs;
6115 	daddr_t		dbn, lfsbn;
6116 	int		disk_blks = fs->fs_bsize >> DEV_BSHIFT;
6117 	int		error = 0;
6118 	int		ndbs, nfsbs;
6119 
6120 	/*
6121 	 * forced unmount case
6122 	 */
6123 	if (ip->i_ufsvfs == NULL)
6124 		return (EIO);
6125 	/*
6126 	 * Validate the inode that it has not been modified since
6127 	 * the dump structure is allocated.
6128 	 */
6129 	mutex_enter(&ip->i_tlock);
6130 	if ((dump_info == NULL) ||
6131 	    (dump_info->ip != ip) ||
6132 	    (dump_info->time.tv_sec != ip->i_mtime.tv_sec) ||
6133 	    (dump_info->time.tv_usec != ip->i_mtime.tv_usec)) {
6134 		mutex_exit(&ip->i_tlock);
6135 		return (-1);
6136 	}
6137 	mutex_exit(&ip->i_tlock);
6138 
6139 	/*
6140 	 * See that the file has room for this write
6141 	 */
6142 	UFS_GET_ISIZE(&file_size, ip);
6143 
6144 	if (ldbtob(ldbn + dblks) > file_size)
6145 		return (ENOSPC);
6146 
6147 	/*
6148 	 * Find the physical disk block numbers from the dump
6149 	 * private data structure directly and write out the data
6150 	 * in contiguous block lumps
6151 	 */
6152 	while (dblks > 0 && !error) {
6153 		lfsbn = (daddr_t)lblkno(fs, ldbtob(ldbn));
6154 		dbn = fsbtodb(fs, dump_info->dblk[lfsbn]) + ldbn % disk_blks;
6155 		nfsbs = 1;
6156 		ndbs = disk_blks - ldbn % disk_blks;
6157 		while (ndbs < dblks && fsbtodb(fs, dump_info->dblk[lfsbn +
6158 		    nfsbs]) == dbn + ndbs) {
6159 			nfsbs++;
6160 			ndbs += disk_blks;
6161 		}
6162 		if (ndbs > dblks)
6163 			ndbs = dblks;
6164 		error = bdev_dump(ip->i_dev, addr, dbn, ndbs);
6165 		addr += ldbtob((offset_t)ndbs);
6166 		dblks -= ndbs;
6167 		ldbn += ndbs;
6168 	}
6169 	return (error);
6170 
6171 }
6172 
6173 /*
6174  * Prepare the file system before and after the dump operation.
6175  *
6176  * action = DUMP_ALLOC:
6177  * Preparation before dump, allocate dump private data structure
6178  * to hold all the direct and indirect block info for dump.
6179  *
6180  * action = DUMP_FREE:
6181  * Clean up after dump, deallocate the dump private data structure.
6182  *
6183  * action = DUMP_SCAN:
6184  * Scan dump_info for *blkp DEV_BSIZE blocks of contig fs space;
6185  * if found, the starting file-relative DEV_BSIZE lbn is written
6186  * to *bklp; that lbn is intended for use with VOP_DUMP()
6187  */
6188 /*ARGSUSED*/
6189 static int
6190 ufs_dumpctl(vnode_t *vp, int action, offset_t *blkp, caller_context_t *ct)
6191 {
6192 	struct inode	*ip = VTOI(vp);
6193 	ufsvfs_t	*ufsvfsp = ip->i_ufsvfs;
6194 	struct fs	*fs;
6195 	daddr32_t	*dblk, *storeblk;
6196 	daddr32_t	*nextblk, *endblk;
6197 	struct buf	*bp;
6198 	int		i, entry, entries;
6199 	int		n, ncontig;
6200 
6201 	/*
6202 	 * check for forced unmount
6203 	 */
6204 	if (ufsvfsp == NULL)
6205 		return (EIO);
6206 
6207 	if (action == DUMP_ALLOC) {
6208 		/*
6209 		 * alloc and record dump_info
6210 		 */
6211 		if (dump_info != NULL)
6212 			return (EINVAL);
6213 
6214 		ASSERT(vp->v_type == VREG);
6215 		fs = ufsvfsp->vfs_fs;
6216 
6217 		rw_enter(&ip->i_contents, RW_READER);
6218 
6219 		if (bmap_has_holes(ip)) {
6220 			rw_exit(&ip->i_contents);
6221 			return (EFAULT);
6222 		}
6223 
6224 		/*
6225 		 * calculate and allocate space needed according to i_size
6226 		 */
6227 		entries = (int)lblkno(fs, blkroundup(fs, ip->i_size));
6228 		dump_info = kmem_alloc(sizeof (struct dump) +
6229 		    (entries - 1) * sizeof (daddr32_t), KM_NOSLEEP);
6230 		if (dump_info == NULL) {
6231 			rw_exit(&ip->i_contents);
6232 			return (ENOMEM);
6233 		}
6234 
6235 		/* Start saving the info */
6236 		dump_info->fsbs = entries;
6237 		dump_info->ip = ip;
6238 		storeblk = &dump_info->dblk[0];
6239 
6240 		/* Direct Blocks */
6241 		for (entry = 0; entry < NDADDR && entry < entries; entry++)
6242 			*storeblk++ = ip->i_db[entry];
6243 
6244 		/* Indirect Blocks */
6245 		for (i = 0; i < NIADDR; i++) {
6246 			int error = 0;
6247 
6248 			bp = UFS_BREAD(ufsvfsp,
6249 			    ip->i_dev, fsbtodb(fs, ip->i_ib[i]), fs->fs_bsize);
6250 			if (bp->b_flags & B_ERROR)
6251 				error = EIO;
6252 			else {
6253 				dblk = bp->b_un.b_daddr;
6254 				if ((storeblk = save_dblks(ip, ufsvfsp,
6255 				    storeblk, dblk, i, entries)) == NULL)
6256 					error = EIO;
6257 			}
6258 
6259 			brelse(bp);
6260 
6261 			if (error != 0) {
6262 				kmem_free(dump_info, sizeof (struct dump) +
6263 				    (entries - 1) * sizeof (daddr32_t));
6264 				rw_exit(&ip->i_contents);
6265 				dump_info = NULL;
6266 				return (error);
6267 			}
6268 		}
6269 		/* and time stamp the information */
6270 		mutex_enter(&ip->i_tlock);
6271 		dump_info->time = ip->i_mtime;
6272 		mutex_exit(&ip->i_tlock);
6273 
6274 		rw_exit(&ip->i_contents);
6275 	} else if (action == DUMP_FREE) {
6276 		/*
6277 		 * free dump_info
6278 		 */
6279 		if (dump_info == NULL)
6280 			return (EINVAL);
6281 		entries = dump_info->fsbs - 1;
6282 		kmem_free(dump_info, sizeof (struct dump) +
6283 		    entries * sizeof (daddr32_t));
6284 		dump_info = NULL;
6285 	} else if (action == DUMP_SCAN) {
6286 		/*
6287 		 * scan dump_info
6288 		 */
6289 		if (dump_info == NULL)
6290 			return (EINVAL);
6291 
6292 		dblk = dump_info->dblk;
6293 		nextblk = dblk + 1;
6294 		endblk = dblk + dump_info->fsbs - 1;
6295 		fs = ufsvfsp->vfs_fs;
6296 		ncontig = *blkp >> (fs->fs_bshift - DEV_BSHIFT);
6297 
6298 		/*
6299 		 * scan dblk[] entries; contig fs space is found when:
6300 		 * ((current blkno + frags per block) == next blkno)
6301 		 */
6302 		n = 0;
6303 		while (n < ncontig && dblk < endblk) {
6304 			if ((*dblk + fs->fs_frag) == *nextblk)
6305 				n++;
6306 			else
6307 				n = 0;
6308 			dblk++;
6309 			nextblk++;
6310 		}
6311 
6312 		/*
6313 		 * index is where size bytes of contig space begins;
6314 		 * conversion from index to the file's DEV_BSIZE lbn
6315 		 * is equivalent to:  (index * fs_bsize) / DEV_BSIZE
6316 		 */
6317 		if (n == ncontig) {
6318 			i = (dblk - dump_info->dblk) - ncontig;
6319 			*blkp = i << (fs->fs_bshift - DEV_BSHIFT);
6320 		} else
6321 			return (EFAULT);
6322 	}
6323 	return (0);
6324 }
6325 
6326 /*
6327  * Recursive helper function for ufs_dumpctl().  It follows the indirect file
6328  * system  blocks until it reaches the the disk block addresses, which are
6329  * then stored into the given buffer, storeblk.
6330  */
6331 static daddr32_t *
6332 save_dblks(struct inode *ip, struct ufsvfs *ufsvfsp,  daddr32_t *storeblk,
6333     daddr32_t *dblk, int level, int entries)
6334 {
6335 	struct fs	*fs = ufsvfsp->vfs_fs;
6336 	struct buf	*bp;
6337 	int		i;
6338 
6339 	if (level == 0) {
6340 		for (i = 0; i < NINDIR(fs); i++) {
6341 			if (storeblk - dump_info->dblk >= entries)
6342 				break;
6343 			*storeblk++ = dblk[i];
6344 		}
6345 		return (storeblk);
6346 	}
6347 	for (i = 0; i < NINDIR(fs); i++) {
6348 		if (storeblk - dump_info->dblk >= entries)
6349 			break;
6350 		bp = UFS_BREAD(ufsvfsp,
6351 		    ip->i_dev, fsbtodb(fs, dblk[i]), fs->fs_bsize);
6352 		if (bp->b_flags & B_ERROR) {
6353 			brelse(bp);
6354 			return (NULL);
6355 		}
6356 		storeblk = save_dblks(ip, ufsvfsp, storeblk, bp->b_un.b_daddr,
6357 		    level - 1, entries);
6358 		brelse(bp);
6359 
6360 		if (storeblk == NULL)
6361 			return (NULL);
6362 	}
6363 	return (storeblk);
6364 }
6365 
6366 /* ARGSUSED */
6367 static int
6368 ufs_getsecattr(struct vnode *vp, vsecattr_t *vsap, int flag,
6369 	struct cred *cr, caller_context_t *ct)
6370 {
6371 	struct inode	*ip = VTOI(vp);
6372 	struct ulockfs	*ulp;
6373 	struct ufsvfs	*ufsvfsp = ip->i_ufsvfs;
6374 	ulong_t		vsa_mask = vsap->vsa_mask;
6375 	int		err = EINVAL;
6376 
6377 	vsa_mask &= (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT);
6378 
6379 	/*
6380 	 * Only grab locks if needed - they're not needed to check vsa_mask
6381 	 * or if the mask contains no acl flags.
6382 	 */
6383 	if (vsa_mask != 0) {
6384 		if (err = ufs_lockfs_begin(ufsvfsp, &ulp,
6385 		    ULOCKFS_GETATTR_MASK))
6386 			return (err);
6387 
6388 		rw_enter(&ip->i_contents, RW_READER);
6389 		err = ufs_acl_get(ip, vsap, flag, cr);
6390 		rw_exit(&ip->i_contents);
6391 
6392 		if (ulp)
6393 			ufs_lockfs_end(ulp);
6394 	}
6395 	return (err);
6396 }
6397 
6398 /* ARGSUSED */
6399 static int
6400 ufs_setsecattr(struct vnode *vp, vsecattr_t *vsap, int flag, struct cred *cr,
6401 	caller_context_t *ct)
6402 {
6403 	struct inode	*ip = VTOI(vp);
6404 	struct ulockfs	*ulp = NULL;
6405 	struct ufsvfs	*ufsvfsp = VTOI(vp)->i_ufsvfs;
6406 	ulong_t		vsa_mask = vsap->vsa_mask;
6407 	int		err;
6408 	int		haverwlock = 1;
6409 	int		trans_size;
6410 	int		donetrans = 0;
6411 	int		retry = 1;
6412 
6413 	ASSERT(RW_LOCK_HELD(&ip->i_rwlock));
6414 
6415 	/* Abort now if the request is either empty or invalid. */
6416 	vsa_mask &= (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT);
6417 	if ((vsa_mask == 0) ||
6418 	    ((vsap->vsa_aclentp == NULL) &&
6419 	    (vsap->vsa_dfaclentp == NULL))) {
6420 		err = EINVAL;
6421 		goto out;
6422 	}
6423 
6424 	/*
6425 	 * Following convention, if this is a directory then we acquire the
6426 	 * inode's i_rwlock after starting a UFS logging transaction;
6427 	 * otherwise, we acquire it beforehand. Since we were called (and
6428 	 * must therefore return) with the lock held, we will have to drop it,
6429 	 * and later reacquire it, if operating on a directory.
6430 	 */
6431 	if (vp->v_type == VDIR) {
6432 		rw_exit(&ip->i_rwlock);
6433 		haverwlock = 0;
6434 	} else {
6435 		/* Upgrade the lock if required. */
6436 		if (!rw_write_held(&ip->i_rwlock)) {
6437 			rw_exit(&ip->i_rwlock);
6438 			rw_enter(&ip->i_rwlock, RW_WRITER);
6439 		}
6440 	}
6441 
6442 again:
6443 	ASSERT(!(vp->v_type == VDIR && haverwlock));
6444 	if (err = ufs_lockfs_begin(ufsvfsp, &ulp, ULOCKFS_SETATTR_MASK)) {
6445 		ulp = NULL;
6446 		retry = 0;
6447 		goto out;
6448 	}
6449 
6450 	/*
6451 	 * Check that the file system supports this operation. Note that
6452 	 * ufs_lockfs_begin() will have checked that the file system had
6453 	 * not been forcibly unmounted.
6454 	 */
6455 	if (ufsvfsp->vfs_fs->fs_ronly) {
6456 		err = EROFS;
6457 		goto out;
6458 	}
6459 	if (ufsvfsp->vfs_nosetsec) {
6460 		err = ENOSYS;
6461 		goto out;
6462 	}
6463 
6464 	if (ulp) {
6465 		TRANS_BEGIN_ASYNC(ufsvfsp, TOP_SETSECATTR,
6466 		    trans_size = TOP_SETSECATTR_SIZE(VTOI(vp)));
6467 		donetrans = 1;
6468 	}
6469 
6470 	if (vp->v_type == VDIR) {
6471 		rw_enter(&ip->i_rwlock, RW_WRITER);
6472 		haverwlock = 1;
6473 	}
6474 
6475 	ASSERT(haverwlock);
6476 
6477 	/* Do the actual work. */
6478 	rw_enter(&ip->i_contents, RW_WRITER);
6479 	/*
6480 	 * Suppress out of inodes messages if we will retry.
6481 	 */
6482 	if (retry)
6483 		ip->i_flag |= IQUIET;
6484 	err = ufs_acl_set(ip, vsap, flag, cr);
6485 	ip->i_flag &= ~IQUIET;
6486 	rw_exit(&ip->i_contents);
6487 
6488 out:
6489 	if (ulp) {
6490 		if (donetrans) {
6491 			/*
6492 			 * top_end_async() can eventually call
6493 			 * top_end_sync(), which can block. We must
6494 			 * therefore observe the lock-ordering protocol
6495 			 * here as well.
6496 			 */
6497 			if (vp->v_type == VDIR) {
6498 				rw_exit(&ip->i_rwlock);
6499 				haverwlock = 0;
6500 			}
6501 			TRANS_END_ASYNC(ufsvfsp, TOP_SETSECATTR, trans_size);
6502 		}
6503 		ufs_lockfs_end(ulp);
6504 	}
6505 	/*
6506 	 * If no inodes available, try scaring a logically-
6507 	 * free one out of the delete queue to someplace
6508 	 * that we can find it.
6509 	 */
6510 	if ((err == ENOSPC) && retry && TRANS_ISTRANS(ufsvfsp)) {
6511 		ufs_delete_drain_wait(ufsvfsp, 1);
6512 		retry = 0;
6513 		if (vp->v_type == VDIR && haverwlock) {
6514 			rw_exit(&ip->i_rwlock);
6515 			haverwlock = 0;
6516 		}
6517 		goto again;
6518 	}
6519 	/*
6520 	 * If we need to reacquire the lock then it is safe to do so
6521 	 * as a reader. This is because ufs_rwunlock(), which will be
6522 	 * called by our caller after we return, does not differentiate
6523 	 * between shared and exclusive locks.
6524 	 */
6525 	if (!haverwlock) {
6526 		ASSERT(vp->v_type == VDIR);
6527 		rw_enter(&ip->i_rwlock, RW_READER);
6528 	}
6529 
6530 	return (err);
6531 }
6532