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