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