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