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