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