xref: /illumos-gate/usr/src/uts/common/fs/hsfs/hsfs_vnops.c (revision da6c28aaf62fa55f0fdb8004aa40f88f23bf53f0)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*
29  * Vnode operations for the High Sierra filesystem
30  */
31 
32 #include <sys/types.h>
33 #include <sys/t_lock.h>
34 #include <sys/param.h>
35 #include <sys/time.h>
36 #include <sys/systm.h>
37 #include <sys/sysmacros.h>
38 #include <sys/resource.h>
39 #include <sys/signal.h>
40 #include <sys/cred.h>
41 #include <sys/user.h>
42 #include <sys/buf.h>
43 #include <sys/vfs.h>
44 #include <sys/vfs_opreg.h>
45 #include <sys/stat.h>
46 #include <sys/vnode.h>
47 #include <sys/mode.h>
48 #include <sys/proc.h>
49 #include <sys/disp.h>
50 #include <sys/file.h>
51 #include <sys/fcntl.h>
52 #include <sys/flock.h>
53 #include <sys/kmem.h>
54 #include <sys/uio.h>
55 #include <sys/conf.h>
56 #include <sys/errno.h>
57 #include <sys/mman.h>
58 #include <sys/pathname.h>
59 #include <sys/debug.h>
60 #include <sys/vmsystm.h>
61 #include <sys/cmn_err.h>
62 #include <sys/fbuf.h>
63 #include <sys/dirent.h>
64 #include <sys/errno.h>
65 #include <sys/dkio.h>
66 #include <sys/cmn_err.h>
67 #include <sys/atomic.h>
68 
69 #include <vm/hat.h>
70 #include <vm/page.h>
71 #include <vm/pvn.h>
72 #include <vm/as.h>
73 #include <vm/seg.h>
74 #include <vm/seg_map.h>
75 #include <vm/seg_kmem.h>
76 #include <vm/seg_vn.h>
77 #include <vm/rm.h>
78 #include <vm/page.h>
79 #include <sys/swap.h>
80 #include <sys/avl.h>
81 #include <sys/sunldi.h>
82 #include <sys/ddi.h>
83 #include <sys/sunddi.h>
84 #include <sys/sdt.h>
85 
86 /*
87  * For struct modlinkage
88  */
89 #include <sys/modctl.h>
90 
91 #include <sys/fs/hsfs_spec.h>
92 #include <sys/fs/hsfs_node.h>
93 #include <sys/fs/hsfs_impl.h>
94 #include <sys/fs/hsfs_susp.h>
95 #include <sys/fs/hsfs_rrip.h>
96 
97 #include <fs/fs_subr.h>
98 
99 /* # of contiguous requests to detect sequential access pattern */
100 static int seq_contig_requests = 2;
101 
102 /*
103  * This is the max number os taskq threads that will be created
104  * if required. Since we are using a Dynamic TaskQ by default only
105  * one thread is created initially.
106  *
107  * NOTE: In the usual hsfs use case this per fs instance number
108  * of taskq threads should not place any undue load on a system.
109  * Even on an unusual system with say 100 CDROM drives, 800 threads
110  * will not be created unless all the drives are loaded and all
111  * of them are saturated with I/O at the same time! If there is at
112  * all a complaint of system load due to such an unusual case it
113  * should be easy enough to change to one per-machine Dynamic TaskQ
114  * for all hsfs mounts with a nthreads of say 32.
115  */
116 static int hsfs_taskq_nthreads = 8;	/* # of taskq threads per fs */
117 
118 /* Min count of adjacent bufs that will avoid buf coalescing */
119 static int hsched_coalesce_min = 2;
120 
121 /*
122  * Kmem caches for heavily used small allocations. Using these kmem
123  * caches provides a factor of 3 reduction in system time and greatly
124  * aids overall throughput esp. on SPARC.
125  */
126 struct kmem_cache *hio_cache;
127 struct kmem_cache *hio_info_cache;
128 
129 /*
130  * This tunable allows us to ignore inode numbers from rrip-1.12.
131  * In this case, we fall back to our default inode algorithm.
132  */
133 extern int use_rrip_inodes;
134 
135 /*
136  * Free behind logic from UFS to tame our thirst for
137  * the page cache.
138  * See usr/src/uts/common/fs/ufs/ufs_vnops.c for more
139  * explanation.
140  */
141 static int	freebehind = 1;
142 static int	smallfile = 0;
143 static int	cache_read_ahead = 0;
144 static u_offset_t smallfile64 = 32 * 1024;
145 #define	SMALLFILE1_D 1000
146 #define	SMALLFILE2_D 10
147 static u_offset_t smallfile1 = 32 * 1024;
148 static u_offset_t smallfile2 = 32 * 1024;
149 static clock_t smallfile_update = 0; /* when to recompute */
150 static uint_t smallfile1_d = SMALLFILE1_D;
151 static uint_t smallfile2_d = SMALLFILE2_D;
152 
153 static int hsched_deadline_compare(const void *x1, const void *x2);
154 static int hsched_offset_compare(const void *x1, const void *x2);
155 static void hsched_enqueue_io(struct hsfs *fsp, struct hio *hsio, int ra);
156 int hsched_invoke_strategy(struct hsfs *fsp);
157 
158 /* ARGSUSED */
159 static int
160 hsfs_fsync(vnode_t *cp,
161 	int syncflag,
162 	cred_t *cred,
163 	caller_context_t *ct)
164 {
165 	return (0);
166 }
167 
168 
169 /*ARGSUSED*/
170 static int
171 hsfs_read(struct vnode *vp,
172 	struct uio *uiop,
173 	int ioflag,
174 	struct cred *cred,
175 	struct caller_context *ct)
176 {
177 	caddr_t base;
178 	offset_t diff;
179 	int error;
180 	struct hsnode *hp;
181 	uint_t filesize;
182 	int dofree;
183 
184 	hp = VTOH(vp);
185 	/*
186 	 * if vp is of type VDIR, make sure dirent
187 	 * is filled up with all info (because of ptbl)
188 	 */
189 	if (vp->v_type == VDIR) {
190 		if (hp->hs_dirent.ext_size == 0)
191 			hs_filldirent(vp, &hp->hs_dirent);
192 	}
193 	filesize = hp->hs_dirent.ext_size;
194 
195 	/* Sanity checks. */
196 	if (uiop->uio_resid == 0 ||		/* No data wanted. */
197 	    uiop->uio_loffset > HS_MAXFILEOFF ||	/* Offset too big. */
198 	    uiop->uio_loffset >= filesize)	/* Past EOF. */
199 		return (0);
200 
201 	do {
202 		/*
203 		 * We want to ask for only the "right" amount of data.
204 		 * In this case that means:-
205 		 *
206 		 * We can't get data from beyond our EOF. If asked,
207 		 * we will give a short read.
208 		 *
209 		 * segmap_getmapflt returns buffers of MAXBSIZE bytes.
210 		 * These buffers are always MAXBSIZE aligned.
211 		 * If our starting offset is not MAXBSIZE aligned,
212 		 * we can only ask for less than MAXBSIZE bytes.
213 		 *
214 		 * If our requested offset and length are such that
215 		 * they belong in different MAXBSIZE aligned slots
216 		 * then we'll be making more than one call on
217 		 * segmap_getmapflt.
218 		 *
219 		 * This diagram shows the variables we use and their
220 		 * relationships.
221 		 *
222 		 * |<-----MAXBSIZE----->|
223 		 * +--------------------------...+
224 		 * |.....mapon->|<--n-->|....*...|EOF
225 		 * +--------------------------...+
226 		 * uio_loffset->|
227 		 * uio_resid....|<---------->|
228 		 * diff.........|<-------------->|
229 		 *
230 		 * So, in this case our offset is not aligned
231 		 * and our request takes us outside of the
232 		 * MAXBSIZE window. We will break this up into
233 		 * two segmap_getmapflt calls.
234 		 */
235 		size_t nbytes;
236 		offset_t mapon;
237 		size_t n;
238 		uint_t flags;
239 
240 		mapon = uiop->uio_loffset & MAXBOFFSET;
241 		diff = filesize - uiop->uio_loffset;
242 		nbytes = (size_t)MIN(MAXBSIZE - mapon, uiop->uio_resid);
243 		n = MIN(diff, nbytes);
244 		if (n <= 0) {
245 			/* EOF or request satisfied. */
246 			return (0);
247 		}
248 
249 		/*
250 		 * Freebehind computation taken from:
251 		 * usr/src/uts/common/fs/ufs/ufs_vnops.c
252 		 */
253 		if (drv_hztousec(ddi_get_lbolt()) >= smallfile_update) {
254 			uint64_t percpufreeb;
255 			if (smallfile1_d == 0) smallfile1_d = SMALLFILE1_D;
256 			if (smallfile2_d == 0) smallfile2_d = SMALLFILE2_D;
257 			percpufreeb = ptob((uint64_t)freemem) / ncpus_online;
258 			smallfile1 = percpufreeb / smallfile1_d;
259 			smallfile2 = percpufreeb / smallfile2_d;
260 			smallfile1 = MAX(smallfile1, smallfile);
261 			smallfile1 = MAX(smallfile1, smallfile64);
262 			smallfile2 = MAX(smallfile1, smallfile2);
263 			smallfile_update = drv_hztousec(ddi_get_lbolt())
264 			    + 1000000;
265 		}
266 
267 		dofree = freebehind &&
268 		    hp->hs_prev_offset == uiop->uio_loffset &&
269 		    hp->hs_ra_bytes > 0;
270 
271 		base = segmap_getmapflt(segkmap, vp,
272 		    (u_offset_t)uiop->uio_loffset, n, 1, S_READ);
273 
274 		error = uiomove(base + mapon, n, UIO_READ, uiop);
275 
276 		if (error == 0) {
277 			/*
278 			 * if read a whole block, or read to eof,
279 			 *  won't need this buffer again soon.
280 			 */
281 			if (n + mapon == MAXBSIZE ||
282 			    uiop->uio_loffset == filesize)
283 				flags = SM_DONTNEED;
284 			else
285 				flags = 0;
286 
287 			if (dofree) {
288 				flags = SM_FREE | SM_ASYNC;
289 				if ((cache_read_ahead == 0) &&
290 				    uiop->uio_loffset > smallfile2)
291 					flags |=  SM_DONTNEED;
292 			}
293 
294 			error = segmap_release(segkmap, base, flags);
295 		} else
296 			(void) segmap_release(segkmap, base, 0);
297 	} while (error == 0 && uiop->uio_resid > 0);
298 
299 	return (error);
300 }
301 
302 /*ARGSUSED2*/
303 static int
304 hsfs_getattr(
305 	struct vnode *vp,
306 	struct vattr *vap,
307 	int flags,
308 	struct cred *cred,
309 	caller_context_t *ct)
310 {
311 	struct hsnode *hp;
312 	struct vfs *vfsp;
313 	struct hsfs *fsp;
314 
315 	hp = VTOH(vp);
316 	fsp = VFS_TO_HSFS(vp->v_vfsp);
317 	vfsp = vp->v_vfsp;
318 
319 	if ((hp->hs_dirent.ext_size == 0) && (vp->v_type == VDIR)) {
320 		hs_filldirent(vp, &hp->hs_dirent);
321 	}
322 	vap->va_type = IFTOVT(hp->hs_dirent.mode);
323 	vap->va_mode = hp->hs_dirent.mode;
324 	vap->va_uid = hp->hs_dirent.uid;
325 	vap->va_gid = hp->hs_dirent.gid;
326 
327 	vap->va_fsid = vfsp->vfs_dev;
328 	vap->va_nodeid = (ino64_t)hp->hs_nodeid;
329 	vap->va_nlink = hp->hs_dirent.nlink;
330 	vap->va_size =	(offset_t)hp->hs_dirent.ext_size;
331 
332 	vap->va_atime.tv_sec = hp->hs_dirent.adate.tv_sec;
333 	vap->va_atime.tv_nsec = hp->hs_dirent.adate.tv_usec*1000;
334 	vap->va_mtime.tv_sec = hp->hs_dirent.mdate.tv_sec;
335 	vap->va_mtime.tv_nsec = hp->hs_dirent.mdate.tv_usec*1000;
336 	vap->va_ctime.tv_sec = hp->hs_dirent.cdate.tv_sec;
337 	vap->va_ctime.tv_nsec = hp->hs_dirent.cdate.tv_usec*1000;
338 	if (vp->v_type == VCHR || vp->v_type == VBLK)
339 		vap->va_rdev = hp->hs_dirent.r_dev;
340 	else
341 		vap->va_rdev = 0;
342 	vap->va_blksize = vfsp->vfs_bsize;
343 	/* no. of blocks = no. of data blocks + no. of xar blocks */
344 	vap->va_nblocks = (fsblkcnt64_t)howmany(vap->va_size + (u_longlong_t)
345 	    (hp->hs_dirent.xar_len << fsp->hsfs_vol.lbn_shift), DEV_BSIZE);
346 	vap->va_seq = hp->hs_seq;
347 	return (0);
348 }
349 
350 /*ARGSUSED*/
351 static int
352 hsfs_readlink(struct vnode *vp,
353 	struct uio *uiop,
354 	struct cred *cred,
355 	caller_context_t *ct)
356 {
357 	struct hsnode *hp;
358 
359 	if (vp->v_type != VLNK)
360 		return (EINVAL);
361 
362 	hp = VTOH(vp);
363 
364 	if (hp->hs_dirent.sym_link == (char *)NULL)
365 		return (ENOENT);
366 
367 	return (uiomove(hp->hs_dirent.sym_link,
368 	    (size_t)MIN(hp->hs_dirent.ext_size,
369 	    uiop->uio_resid), UIO_READ, uiop));
370 }
371 
372 /*ARGSUSED*/
373 static void
374 hsfs_inactive(struct vnode *vp,
375 	struct cred *cred,
376 	caller_context_t *ct)
377 {
378 	struct hsnode *hp;
379 	struct hsfs *fsp;
380 
381 	int nopage;
382 
383 	hp = VTOH(vp);
384 	fsp = VFS_TO_HSFS(vp->v_vfsp);
385 	/*
386 	 * Note: acquiring and holding v_lock for quite a while
387 	 * here serializes on the vnode; this is unfortunate, but
388 	 * likely not to overly impact performance, as the underlying
389 	 * device (CDROM drive) is quite slow.
390 	 */
391 	rw_enter(&fsp->hsfs_hash_lock, RW_WRITER);
392 	mutex_enter(&hp->hs_contents_lock);
393 	mutex_enter(&vp->v_lock);
394 
395 	if (vp->v_count < 1) {
396 		panic("hsfs_inactive: v_count < 1");
397 		/*NOTREACHED*/
398 	}
399 
400 	if (vp->v_count > 1 || (hp->hs_flags & HREF) == 0) {
401 		vp->v_count--;	/* release hold from vn_rele */
402 		mutex_exit(&vp->v_lock);
403 		mutex_exit(&hp->hs_contents_lock);
404 		rw_exit(&fsp->hsfs_hash_lock);
405 		return;
406 	}
407 	vp->v_count--;	/* release hold from vn_rele */
408 	if (vp->v_count == 0) {
409 		/*
410 		 * Free the hsnode.
411 		 * If there are no pages associated with the
412 		 * hsnode, give it back to the kmem_cache,
413 		 * else put at the end of this file system's
414 		 * internal free list.
415 		 */
416 		nopage = !vn_has_cached_data(vp);
417 		hp->hs_flags = 0;
418 		/*
419 		 * exit these locks now, since hs_freenode may
420 		 * kmem_free the hsnode and embedded vnode
421 		 */
422 		mutex_exit(&vp->v_lock);
423 		mutex_exit(&hp->hs_contents_lock);
424 		hs_freenode(vp, fsp, nopage);
425 	} else {
426 		mutex_exit(&vp->v_lock);
427 		mutex_exit(&hp->hs_contents_lock);
428 	}
429 	rw_exit(&fsp->hsfs_hash_lock);
430 }
431 
432 
433 /*ARGSUSED*/
434 static int
435 hsfs_lookup(
436 	struct vnode *dvp,
437 	char *nm,
438 	struct vnode **vpp,
439 	struct pathname *pnp,
440 	int flags,
441 	struct vnode *rdir,
442 	struct cred *cred,
443 	caller_context_t *ct,
444 	int *direntflags,
445 	pathname_t *realpnp)
446 {
447 	int error;
448 	int namelen = (int)strlen(nm);
449 
450 	if (*nm == '\0') {
451 		VN_HOLD(dvp);
452 		*vpp = dvp;
453 		return (0);
454 	}
455 
456 	/*
457 	 * If we're looking for ourself, life is simple.
458 	 */
459 	if (namelen == 1 && *nm == '.') {
460 		if (error = hs_access(dvp, (mode_t)VEXEC, cred))
461 			return (error);
462 		VN_HOLD(dvp);
463 		*vpp = dvp;
464 		return (0);
465 	}
466 
467 	return (hs_dirlook(dvp, nm, namelen, vpp, cred));
468 }
469 
470 
471 /*ARGSUSED*/
472 static int
473 hsfs_readdir(
474 	struct vnode		*vp,
475 	struct uio		*uiop,
476 	struct cred		*cred,
477 	int			*eofp,
478 	caller_context_t	*ct,
479 	int			flags)
480 {
481 	struct hsnode	*dhp;
482 	struct hsfs	*fsp;
483 	struct hs_direntry hd;
484 	struct dirent64	*nd;
485 	int		error;
486 	uint_t		offset;		/* real offset in directory */
487 	uint_t		dirsiz;		/* real size of directory */
488 	uchar_t		*blkp;
489 	int		hdlen;		/* length of hs directory entry */
490 	long		ndlen;		/* length of dirent entry */
491 	int		bytes_wanted;
492 	size_t		bufsize;	/* size of dirent buffer */
493 	char		*outbuf;	/* ptr to dirent buffer */
494 	char		*dname;
495 	int		dnamelen;
496 	size_t		dname_size;
497 	struct fbuf	*fbp;
498 	uint_t		last_offset;	/* last index into current dir block */
499 	ino64_t		dirino;	/* temporary storage before storing in dirent */
500 	off_t		diroff;
501 
502 	dhp = VTOH(vp);
503 	fsp = VFS_TO_HSFS(vp->v_vfsp);
504 	if (dhp->hs_dirent.ext_size == 0)
505 		hs_filldirent(vp, &dhp->hs_dirent);
506 	dirsiz = dhp->hs_dirent.ext_size;
507 	if (uiop->uio_loffset >= dirsiz) {	/* at or beyond EOF */
508 		if (eofp)
509 			*eofp = 1;
510 		return (0);
511 	}
512 	ASSERT(uiop->uio_loffset <= HS_MAXFILEOFF);
513 	offset = uiop->uio_loffset;
514 
515 	dname_size = fsp->hsfs_namemax + 1;	/* 1 for the ending NUL */
516 	dname = kmem_alloc(dname_size, KM_SLEEP);
517 	bufsize = uiop->uio_resid + sizeof (struct dirent64);
518 
519 	outbuf = kmem_alloc(bufsize, KM_SLEEP);
520 	nd = (struct dirent64 *)outbuf;
521 
522 	while (offset < dirsiz) {
523 		bytes_wanted = MIN(MAXBSIZE, dirsiz - (offset & MAXBMASK));
524 
525 		error = fbread(vp, (offset_t)(offset & MAXBMASK),
526 		    (unsigned int)bytes_wanted, S_READ, &fbp);
527 		if (error)
528 			goto done;
529 
530 		blkp = (uchar_t *)fbp->fb_addr;
531 		last_offset = (offset & MAXBMASK) + fbp->fb_count;
532 
533 #define	rel_offset(offset) ((offset) & MAXBOFFSET)	/* index into blkp */
534 
535 		while (offset < last_offset) {
536 			/*
537 			 * Very similar validation code is found in
538 			 * process_dirblock(), hsfs_node.c.
539 			 * For an explanation, see there.
540 			 * It may make sense for the future to
541 			 * "consolidate" the code in hs_parsedir(),
542 			 * process_dirblock() and hsfs_readdir() into
543 			 * a single utility function.
544 			 */
545 			hdlen = (int)((uchar_t)
546 			    HDE_DIR_LEN(&blkp[rel_offset(offset)]));
547 			if (hdlen < HDE_ROOT_DIR_REC_SIZE ||
548 			    offset + hdlen > last_offset) {
549 				/*
550 				 * advance to next sector boundary
551 				 */
552 				offset = roundup(offset + 1, HS_SECTOR_SIZE);
553 				if (hdlen)
554 					hs_log_bogus_disk_warning(fsp,
555 					    HSFS_ERR_TRAILING_JUNK, 0);
556 
557 				continue;
558 			}
559 
560 			bzero(&hd, sizeof (hd));
561 
562 			/*
563 			 * Just ignore invalid directory entries.
564 			 * XXX - maybe hs_parsedir() will detect EXISTENCE bit
565 			 */
566 			if (!hs_parsedir(fsp, &blkp[rel_offset(offset)],
567 			    &hd, dname, &dnamelen, last_offset - offset)) {
568 				/*
569 				 * Determine if there is enough room
570 				 */
571 				ndlen = (long)DIRENT64_RECLEN((dnamelen));
572 
573 				if ((ndlen + ((char *)nd - outbuf)) >
574 				    uiop->uio_resid) {
575 					fbrelse(fbp, S_READ);
576 					goto done; /* output buffer full */
577 				}
578 
579 				diroff = offset + hdlen;
580 				/*
581 				 * If the media carries rrip-v1.12 or newer,
582 				 * and we trust the inodes from the rrip data
583 				 * (use_rrip_inodes != 0), use that data. If the
584 				 * media has been created by a recent mkisofs
585 				 * version, we may trust all numbers in the
586 				 * starting extent number; otherwise, we cannot
587 				 * do this for zero sized files and symlinks,
588 				 * because if we did we'd end up mapping all of
589 				 * them to the same node. We use HS_DUMMY_INO
590 				 * in this case and make sure that we will not
591 				 * map all files to the same meta data.
592 				 */
593 				if (hd.inode != 0 && use_rrip_inodes) {
594 					dirino = hd.inode;
595 				} else if ((hd.ext_size == 0 ||
596 				    hd.sym_link != (char *)NULL) &&
597 				    (fsp->hsfs_flags & HSFSMNT_INODE) == 0) {
598 					dirino = HS_DUMMY_INO;
599 				} else {
600 					dirino = hd.ext_lbn;
601 				}
602 
603 				/* strncpy(9f) will zero uninitialized bytes */
604 
605 				ASSERT(strlen(dname) + 1 <=
606 				    DIRENT64_NAMELEN(ndlen));
607 				(void) strncpy(nd->d_name, dname,
608 				    DIRENT64_NAMELEN(ndlen));
609 				nd->d_reclen = (ushort_t)ndlen;
610 				nd->d_off = (offset_t)diroff;
611 				nd->d_ino = dirino;
612 				nd = (struct dirent64 *)((char *)nd + ndlen);
613 
614 				/*
615 				 * free up space allocated for symlink
616 				 */
617 				if (hd.sym_link != (char *)NULL) {
618 					kmem_free(hd.sym_link,
619 					    (size_t)(hd.ext_size+1));
620 					hd.sym_link = (char *)NULL;
621 				}
622 			}
623 			offset += hdlen;
624 		}
625 		fbrelse(fbp, S_READ);
626 	}
627 
628 	/*
629 	 * Got here for one of the following reasons:
630 	 *	1) outbuf is full (error == 0)
631 	 *	2) end of directory reached (error == 0)
632 	 *	3) error reading directory sector (error != 0)
633 	 *	4) directory entry crosses sector boundary (error == 0)
634 	 *
635 	 * If any directory entries have been copied, don't report
636 	 * case 4.  Instead, return the valid directory entries.
637 	 *
638 	 * If no entries have been copied, report the error.
639 	 * If case 4, this will be indistiguishable from EOF.
640 	 */
641 done:
642 	ndlen = ((char *)nd - outbuf);
643 	if (ndlen != 0) {
644 		error = uiomove(outbuf, (size_t)ndlen, UIO_READ, uiop);
645 		uiop->uio_loffset = offset;
646 	}
647 	kmem_free(dname, dname_size);
648 	kmem_free(outbuf, bufsize);
649 	if (eofp && error == 0)
650 		*eofp = (uiop->uio_loffset >= dirsiz);
651 	return (error);
652 }
653 
654 /*ARGSUSED2*/
655 static int
656 hsfs_fid(struct vnode *vp, struct fid *fidp, caller_context_t *ct)
657 {
658 	struct hsnode *hp;
659 	struct hsfid *fid;
660 
661 	if (fidp->fid_len < (sizeof (*fid) - sizeof (fid->hf_len))) {
662 		fidp->fid_len = sizeof (*fid) - sizeof (fid->hf_len);
663 		return (ENOSPC);
664 	}
665 
666 	fid = (struct hsfid *)fidp;
667 	fid->hf_len = sizeof (*fid) - sizeof (fid->hf_len);
668 	hp = VTOH(vp);
669 	mutex_enter(&hp->hs_contents_lock);
670 	fid->hf_dir_lbn = hp->hs_dir_lbn;
671 	fid->hf_dir_off = (ushort_t)hp->hs_dir_off;
672 	fid->hf_ino = hp->hs_nodeid;
673 	mutex_exit(&hp->hs_contents_lock);
674 	return (0);
675 }
676 
677 /*ARGSUSED*/
678 static int
679 hsfs_open(struct vnode **vpp,
680 	int flag,
681 	struct cred *cred,
682 	caller_context_t *ct)
683 {
684 	return (0);
685 }
686 
687 /*ARGSUSED*/
688 static int
689 hsfs_close(
690 	struct vnode *vp,
691 	int flag,
692 	int count,
693 	offset_t offset,
694 	struct cred *cred,
695 	caller_context_t *ct)
696 {
697 	(void) cleanlocks(vp, ttoproc(curthread)->p_pid, 0);
698 	cleanshares(vp, ttoproc(curthread)->p_pid);
699 	return (0);
700 }
701 
702 /*ARGSUSED2*/
703 static int
704 hsfs_access(struct vnode *vp,
705 	int mode,
706 	int flags,
707 	cred_t *cred,
708 	caller_context_t *ct)
709 {
710 	return (hs_access(vp, (mode_t)mode, cred));
711 }
712 
713 /*
714  * the seek time of a CD-ROM is very slow, and data transfer
715  * rate is even worse (max. 150K per sec).  The design
716  * decision is to reduce access to cd-rom as much as possible,
717  * and to transfer a sizable block (read-ahead) of data at a time.
718  * UFS style of read ahead one block at a time is not appropriate,
719  * and is not supported
720  */
721 
722 /*
723  * KLUSTSIZE should be a multiple of PAGESIZE and <= MAXPHYS.
724  */
725 #define	KLUSTSIZE	(56 * 1024)
726 /* we don't support read ahead */
727 int hsfs_lostpage;	/* no. of times we lost original page */
728 
729 /*
730  * Used to prevent biodone() from releasing buf resources that
731  * we didn't allocate in quite the usual way.
732  */
733 /*ARGSUSED*/
734 int
735 hsfs_iodone(struct buf *bp)
736 {
737 	sema_v(&bp->b_io);
738 	return (0);
739 }
740 
741 /*
742  * The taskq thread that invokes the scheduling function to ensure
743  * that all readaheads are complete and cleans up the associated
744  * memory and releases the page lock.
745  */
746 void
747 hsfs_ra_task(void *arg)
748 {
749 	struct hio_info *info = arg;
750 	uint_t count;
751 	struct buf *wbuf;
752 
753 	ASSERT(info->pp != NULL);
754 
755 	for (count = 0; count < info->bufsused; count++) {
756 		wbuf = &(info->bufs[count]);
757 
758 		DTRACE_PROBE1(hsfs_io_wait_ra, struct buf *, wbuf);
759 		while (sema_tryp(&(info->sema[count])) == 0) {
760 			if (hsched_invoke_strategy(info->fsp)) {
761 				sema_p(&(info->sema[count]));
762 				break;
763 			}
764 		}
765 		sema_destroy(&(info->sema[count]));
766 		DTRACE_PROBE1(hsfs_io_done_ra, struct buf *, wbuf);
767 		biofini(&(info->bufs[count]));
768 	}
769 	for (count = 0; count < info->bufsused; count++) {
770 		if (info->vas[count] != NULL) {
771 			ppmapout(info->vas[count]);
772 		}
773 	}
774 	kmem_free(info->vas, info->bufcnt * sizeof (caddr_t));
775 	kmem_free(info->bufs, info->bufcnt * sizeof (struct buf));
776 	kmem_free(info->sema, info->bufcnt * sizeof (ksema_t));
777 
778 	pvn_read_done(info->pp, 0);
779 	kmem_cache_free(hio_info_cache, info);
780 }
781 
782 /*
783  * Submit asynchronous readahead requests to the I/O scheduler
784  * depending on the number of pages to read ahead. These requests
785  * are asynchronous to the calling thread but I/O requests issued
786  * subsequently by other threads with higher LBNs must wait for
787  * these readaheads to complete since we have a single ordered
788  * I/O pipeline. Thus these readaheads are semi-asynchronous.
789  * A TaskQ handles waiting for the readaheads to complete.
790  *
791  * This function is mostly a copy of hsfs_getapage but somewhat
792  * simpler. A readahead request is aborted if page allocation
793  * fails.
794  */
795 /*ARGSUSED*/
796 static int
797 hsfs_getpage_ra(
798 	struct vnode *vp,
799 	u_offset_t off,
800 	struct seg *seg,
801 	caddr_t addr,
802 	struct hsnode *hp,
803 	struct hsfs *fsp,
804 	int	xarsiz,
805 	offset_t	bof,
806 	int	chunk_lbn_count,
807 	int	chunk_data_bytes)
808 {
809 	struct buf *bufs;
810 	caddr_t *vas;
811 	caddr_t va;
812 	struct page *pp, *searchp, *lastp;
813 	struct vnode *devvp;
814 	ulong_t	byte_offset;
815 	size_t	io_len_tmp;
816 	uint_t	io_off, io_len;
817 	uint_t	xlen;
818 	uint_t	filsiz;
819 	uint_t	secsize;
820 	uint_t	bufcnt;
821 	uint_t	bufsused;
822 	uint_t	count;
823 	uint_t	io_end;
824 	uint_t	which_chunk_lbn;
825 	uint_t	offset_lbn;
826 	uint_t	offset_extra;
827 	offset_t	offset_bytes;
828 	uint_t	remaining_bytes;
829 	uint_t	extension;
830 	int	remainder;	/* must be signed */
831 	diskaddr_t driver_block;
832 	u_offset_t io_off_tmp;
833 	ksema_t	*fio_done;
834 	struct hio_info *info;
835 	size_t len;
836 
837 	ASSERT(fsp->hqueue != NULL);
838 
839 	if (addr >= seg->s_base + seg->s_size) {
840 		return (-1);
841 	}
842 
843 	devvp = fsp->hsfs_devvp;
844 	secsize = fsp->hsfs_vol.lbn_size;  /* bytes per logical block */
845 
846 	/* file data size */
847 	filsiz = hp->hs_dirent.ext_size;
848 
849 	if (off >= filsiz)
850 		return (0);
851 
852 	extension = 0;
853 	pp = NULL;
854 
855 	extension += hp->hs_ra_bytes;
856 
857 	/*
858 	 * Some cd writers don't write sectors that aren't used.  Also,
859 	 * there's no point in reading sectors we'll never look at.  So,
860 	 * if we're asked to go beyond the end of a file, truncate to the
861 	 * length of that file.
862 	 *
863 	 * Additionally, this behaviour is required by section 6.4.5 of
864 	 * ISO 9660:1988(E).
865 	 */
866 	len = MIN(extension ? extension : PAGESIZE, filsiz - off);
867 
868 	/* A little paranoia */
869 	if (len <= 0)
870 		return (-1);
871 
872 	/*
873 	 * After all that, make sure we're asking for things in units
874 	 * that bdev_strategy() will understand (see bug 4202551).
875 	 */
876 	len = roundup(len, DEV_BSIZE);
877 
878 	pp = pvn_read_kluster(vp, off, seg, addr, &io_off_tmp,
879 	    &io_len_tmp, off, len, 1);
880 
881 	if (pp == NULL) {
882 		hp->hs_num_contig = 0;
883 		hp->hs_ra_bytes = 0;
884 		hp->hs_prev_offset = 0;
885 		return (-1);
886 	}
887 
888 	io_off = (uint_t)io_off_tmp;
889 	io_len = (uint_t)io_len_tmp;
890 
891 	/* check for truncation */
892 	/*
893 	 * xxx Clean up and return EIO instead?
894 	 * xxx Ought to go to u_offset_t for everything, but we
895 	 * xxx call lots of things that want uint_t arguments.
896 	 */
897 	ASSERT(io_off == io_off_tmp);
898 
899 	/*
900 	 * get enough buffers for worst-case scenario
901 	 * (i.e., no coalescing possible).
902 	 */
903 	bufcnt = (len + secsize - 1) / secsize;
904 	bufs = kmem_alloc(bufcnt * sizeof (struct buf), KM_SLEEP);
905 	vas = kmem_alloc(bufcnt * sizeof (caddr_t), KM_SLEEP);
906 
907 	/*
908 	 * Allocate a array of semaphores since we are doing I/O
909 	 * scheduling.
910 	 */
911 	fio_done = kmem_alloc(bufcnt * sizeof (ksema_t), KM_SLEEP);
912 
913 	/*
914 	 * If our filesize is not an integer multiple of PAGESIZE,
915 	 * we zero that part of the last page that's between EOF and
916 	 * the PAGESIZE boundary.
917 	 */
918 	xlen = io_len & PAGEOFFSET;
919 	if (xlen != 0)
920 		pagezero(pp->p_prev, xlen, PAGESIZE - xlen);
921 
922 	DTRACE_PROBE2(hsfs_readahead, struct vnode *, vp, uint_t, io_len);
923 
924 	va = NULL;
925 	lastp = NULL;
926 	searchp = pp;
927 	io_end = io_off + io_len;
928 	for (count = 0, byte_offset = io_off;
929 	    byte_offset < io_end;
930 	    count++) {
931 		ASSERT(count < bufcnt);
932 
933 		bioinit(&bufs[count]);
934 		bufs[count].b_edev = devvp->v_rdev;
935 		bufs[count].b_dev = cmpdev(devvp->v_rdev);
936 		bufs[count].b_flags = B_NOCACHE|B_BUSY|B_READ;
937 		bufs[count].b_iodone = hsfs_iodone;
938 		bufs[count].b_vp = vp;
939 		bufs[count].b_file = vp;
940 
941 		/* Compute disk address for interleaving. */
942 
943 		/* considered without skips */
944 		which_chunk_lbn = byte_offset / chunk_data_bytes;
945 
946 		/* factor in skips */
947 		offset_lbn = which_chunk_lbn * chunk_lbn_count;
948 
949 		/* convert to physical byte offset for lbn */
950 		offset_bytes = LBN_TO_BYTE(offset_lbn, vp->v_vfsp);
951 
952 		/* don't forget offset into lbn */
953 		offset_extra = byte_offset % chunk_data_bytes;
954 
955 		/* get virtual block number for driver */
956 		driver_block = lbtodb(bof + xarsiz
957 		    + offset_bytes + offset_extra);
958 
959 		if (lastp != searchp) {
960 			/* this branch taken first time through loop */
961 			va = vas[count] = ppmapin(searchp, PROT_WRITE,
962 			    (caddr_t)-1);
963 			/* ppmapin() guarantees not to return NULL */
964 		} else {
965 			vas[count] = NULL;
966 		}
967 
968 		bufs[count].b_un.b_addr = va + byte_offset % PAGESIZE;
969 		bufs[count].b_offset =
970 		    (offset_t)(byte_offset - io_off + off);
971 
972 		/*
973 		 * We specifically use the b_lblkno member here
974 		 * as even in the 32 bit world driver_block can
975 		 * get very large in line with the ISO9660 spec.
976 		 */
977 
978 		bufs[count].b_lblkno = driver_block;
979 
980 		remaining_bytes = ((which_chunk_lbn + 1) * chunk_data_bytes)
981 		    - byte_offset;
982 
983 		/*
984 		 * remaining_bytes can't be zero, as we derived
985 		 * which_chunk_lbn directly from byte_offset.
986 		 */
987 		if ((remaining_bytes + byte_offset) < (off + len)) {
988 			/* coalesce-read the rest of the chunk */
989 			bufs[count].b_bcount = remaining_bytes;
990 		} else {
991 			/* get the final bits */
992 			bufs[count].b_bcount = off + len - byte_offset;
993 		}
994 
995 		remainder = PAGESIZE - (byte_offset % PAGESIZE);
996 		if (bufs[count].b_bcount > remainder) {
997 			bufs[count].b_bcount = remainder;
998 		}
999 
1000 		bufs[count].b_bufsize = bufs[count].b_bcount;
1001 		if (((offset_t)byte_offset + bufs[count].b_bcount) >
1002 		    HS_MAXFILEOFF) {
1003 			break;
1004 		}
1005 		byte_offset += bufs[count].b_bcount;
1006 
1007 		/*
1008 		 * We are scheduling I/O so we need to enqueue
1009 		 * requests rather than calling bdev_strategy
1010 		 * here. A later invocation of the scheduling
1011 		 * function will take care of doing the actual
1012 		 * I/O as it selects requests from the queue as
1013 		 * per the scheduling logic.
1014 		 */
1015 		struct hio *hsio = kmem_cache_alloc(hio_cache,
1016 		    KM_SLEEP);
1017 
1018 		sema_init(&fio_done[count], 0, NULL,
1019 		    SEMA_DEFAULT, NULL);
1020 		hsio->bp = &bufs[count];
1021 		hsio->sema = &fio_done[count];
1022 		hsio->io_lblkno = bufs[count].b_lblkno;
1023 		hsio->nblocks = howmany(hsio->bp->b_bcount,
1024 		    DEV_BSIZE);
1025 
1026 		/* used for deadline */
1027 		hsio->io_timestamp = drv_hztousec(ddi_get_lbolt());
1028 
1029 		/* for I/O coalescing */
1030 		hsio->contig_chain = NULL;
1031 		hsched_enqueue_io(fsp, hsio, 1);
1032 
1033 		lwp_stat_update(LWP_STAT_INBLK, 1);
1034 		lastp = searchp;
1035 		if ((remainder - bufs[count].b_bcount) < 1) {
1036 			searchp = searchp->p_next;
1037 		}
1038 	}
1039 
1040 	bufsused = count;
1041 	info = kmem_cache_alloc(hio_info_cache, KM_SLEEP);
1042 	info->bufs = bufs;
1043 	info->vas = vas;
1044 	info->sema = fio_done;
1045 	info->bufsused = bufsused;
1046 	info->bufcnt = bufcnt;
1047 	info->fsp = fsp;
1048 	info->pp = pp;
1049 
1050 	(void) taskq_dispatch(fsp->hqueue->ra_task,
1051 	    hsfs_ra_task, info, KM_SLEEP);
1052 	/*
1053 	 * The I/O locked pages are unlocked in our taskq thread.
1054 	 */
1055 	return (0);
1056 }
1057 
1058 /*
1059  * Each file may have a different interleaving on disk.  This makes
1060  * things somewhat interesting.  The gist is that there are some
1061  * number of contiguous data sectors, followed by some other number
1062  * of contiguous skip sectors.  The sum of those two sets of sectors
1063  * defines the interleave size.  Unfortunately, it means that we generally
1064  * can't simply read N sectors starting at a given offset to satisfy
1065  * any given request.
1066  *
1067  * What we do is get the relevant memory pages via pvn_read_kluster(),
1068  * then stride through the interleaves, setting up a buf for each
1069  * sector that needs to be brought in.  Instead of kmem_alloc'ing
1070  * space for the sectors, though, we just point at the appropriate
1071  * spot in the relevant page for each of them.  This saves us a bunch
1072  * of copying.
1073  *
1074  * NOTICE: The code below in hsfs_getapage is mostly same as the code
1075  *         in hsfs_getpage_ra above (with some omissions). If you are
1076  *         making any change to this function, please also look at
1077  *         hsfs_getpage_ra.
1078  */
1079 /*ARGSUSED*/
1080 static int
1081 hsfs_getapage(
1082 	struct vnode *vp,
1083 	u_offset_t off,
1084 	size_t len,
1085 	uint_t *protp,
1086 	struct page *pl[],
1087 	size_t plsz,
1088 	struct seg *seg,
1089 	caddr_t addr,
1090 	enum seg_rw rw,
1091 	struct cred *cred)
1092 {
1093 	struct hsnode *hp;
1094 	struct hsfs *fsp;
1095 	int	err;
1096 	struct buf *bufs;
1097 	caddr_t *vas;
1098 	caddr_t va;
1099 	struct page *pp, *searchp, *lastp;
1100 	page_t	*pagefound;
1101 	offset_t	bof;
1102 	struct vnode *devvp;
1103 	ulong_t	byte_offset;
1104 	size_t	io_len_tmp;
1105 	uint_t	io_off, io_len;
1106 	uint_t	xlen;
1107 	uint_t	filsiz;
1108 	uint_t	secsize;
1109 	uint_t	bufcnt;
1110 	uint_t	bufsused;
1111 	uint_t	count;
1112 	uint_t	io_end;
1113 	uint_t	which_chunk_lbn;
1114 	uint_t	offset_lbn;
1115 	uint_t	offset_extra;
1116 	offset_t	offset_bytes;
1117 	uint_t	remaining_bytes;
1118 	uint_t	extension;
1119 	int	remainder;	/* must be signed */
1120 	int	chunk_lbn_count;
1121 	int	chunk_data_bytes;
1122 	int	xarsiz;
1123 	diskaddr_t driver_block;
1124 	u_offset_t io_off_tmp;
1125 	ksema_t *fio_done;
1126 	int	calcdone;
1127 
1128 	/*
1129 	 * We don't support asynchronous operation at the moment, so
1130 	 * just pretend we did it.  If the pages are ever actually
1131 	 * needed, they'll get brought in then.
1132 	 */
1133 	if (pl == NULL)
1134 		return (0);
1135 
1136 	hp = VTOH(vp);
1137 	fsp = VFS_TO_HSFS(vp->v_vfsp);
1138 	devvp = fsp->hsfs_devvp;
1139 	secsize = fsp->hsfs_vol.lbn_size;  /* bytes per logical block */
1140 
1141 	/* file data size */
1142 	filsiz = hp->hs_dirent.ext_size;
1143 
1144 	/* disk addr for start of file */
1145 	bof = LBN_TO_BYTE((offset_t)hp->hs_dirent.ext_lbn, vp->v_vfsp);
1146 
1147 	/* xarsiz byte must be skipped for data */
1148 	xarsiz = hp->hs_dirent.xar_len << fsp->hsfs_vol.lbn_shift;
1149 
1150 	/* how many logical blocks in an interleave (data+skip) */
1151 	chunk_lbn_count = hp->hs_dirent.intlf_sz + hp->hs_dirent.intlf_sk;
1152 
1153 	if (chunk_lbn_count == 0) {
1154 		chunk_lbn_count = 1;
1155 	}
1156 
1157 	/*
1158 	 * Convert interleaving size into bytes.  The zero case
1159 	 * (no interleaving) optimization is handled as a side-
1160 	 * effect of the read-ahead logic.
1161 	 */
1162 	if (hp->hs_dirent.intlf_sz == 0) {
1163 		chunk_data_bytes = LBN_TO_BYTE(1, vp->v_vfsp);
1164 		/*
1165 		 * Optimization: If our pagesize is a multiple of LBN
1166 		 * bytes, we can avoid breaking up a page into individual
1167 		 * lbn-sized requests.
1168 		 */
1169 		if (PAGESIZE % chunk_data_bytes == 0) {
1170 			chunk_lbn_count = BYTE_TO_LBN(PAGESIZE, vp->v_vfsp);
1171 			chunk_data_bytes = PAGESIZE;
1172 		}
1173 	} else {
1174 		chunk_data_bytes =
1175 		    LBN_TO_BYTE(hp->hs_dirent.intlf_sz, vp->v_vfsp);
1176 	}
1177 
1178 reread:
1179 	err = 0;
1180 	pagefound = 0;
1181 	calcdone = 0;
1182 
1183 	/*
1184 	 * Do some read-ahead.  This mostly saves us a bit of
1185 	 * system cpu time more than anything else when doing
1186 	 * sequential reads.  At some point, could do the
1187 	 * read-ahead asynchronously which might gain us something
1188 	 * on wall time, but it seems unlikely....
1189 	 *
1190 	 * We do the easy case here, which is to read through
1191 	 * the end of the chunk, minus whatever's at the end that
1192 	 * won't exactly fill a page.
1193 	 */
1194 	if (hp->hs_ra_bytes > 0 && chunk_data_bytes != PAGESIZE) {
1195 		which_chunk_lbn = (off + len) / chunk_data_bytes;
1196 		extension = ((which_chunk_lbn + 1) * chunk_data_bytes) - off;
1197 		extension -= (extension % PAGESIZE);
1198 	} else {
1199 		extension = roundup(len, PAGESIZE);
1200 	}
1201 
1202 	atomic_inc_64(&fsp->total_pages_requested);
1203 
1204 	pp = NULL;
1205 again:
1206 	/* search for page in buffer */
1207 	if ((pagefound = page_exists(vp, off)) == 0) {
1208 		/*
1209 		 * Need to really do disk IO to get the page.
1210 		 */
1211 		if (!calcdone) {
1212 			extension += hp->hs_ra_bytes;
1213 
1214 			/*
1215 			 * Some cd writers don't write sectors that aren't
1216 			 * used. Also, there's no point in reading sectors
1217 			 * we'll never look at.  So, if we're asked to go
1218 			 * beyond the end of a file, truncate to the length
1219 			 * of that file.
1220 			 *
1221 			 * Additionally, this behaviour is required by section
1222 			 * 6.4.5 of ISO 9660:1988(E).
1223 			 */
1224 			len = MIN(extension ? extension : PAGESIZE,
1225 			    filsiz - off);
1226 
1227 			/* A little paranoia. */
1228 			ASSERT(len > 0);
1229 
1230 			/*
1231 			 * After all that, make sure we're asking for things
1232 			 * in units that bdev_strategy() will understand
1233 			 * (see bug 4202551).
1234 			 */
1235 			len = roundup(len, DEV_BSIZE);
1236 			calcdone = 1;
1237 		}
1238 
1239 		pp = pvn_read_kluster(vp, off, seg, addr, &io_off_tmp,
1240 		    &io_len_tmp, off, len, 0);
1241 
1242 		if (pp == NULL) {
1243 			/*
1244 			 * Pressure on memory, roll back readahead
1245 			 */
1246 			hp->hs_num_contig = 0;
1247 			hp->hs_ra_bytes = 0;
1248 			hp->hs_prev_offset = 0;
1249 			goto again;
1250 		}
1251 
1252 		io_off = (uint_t)io_off_tmp;
1253 		io_len = (uint_t)io_len_tmp;
1254 
1255 		/* check for truncation */
1256 		/*
1257 		 * xxx Clean up and return EIO instead?
1258 		 * xxx Ought to go to u_offset_t for everything, but we
1259 		 * xxx call lots of things that want uint_t arguments.
1260 		 */
1261 		ASSERT(io_off == io_off_tmp);
1262 
1263 		/*
1264 		 * get enough buffers for worst-case scenario
1265 		 * (i.e., no coalescing possible).
1266 		 */
1267 		bufcnt = (len + secsize - 1) / secsize;
1268 		bufs = kmem_zalloc(bufcnt * sizeof (struct buf), KM_SLEEP);
1269 		vas = kmem_alloc(bufcnt * sizeof (caddr_t), KM_SLEEP);
1270 
1271 		/*
1272 		 * Allocate a array of semaphores if we are doing I/O
1273 		 * scheduling.
1274 		 */
1275 		if (fsp->hqueue != NULL)
1276 			fio_done = kmem_alloc(bufcnt * sizeof (ksema_t),
1277 			    KM_SLEEP);
1278 		for (count = 0; count < bufcnt; count++) {
1279 			bioinit(&bufs[count]);
1280 			bufs[count].b_edev = devvp->v_rdev;
1281 			bufs[count].b_dev = cmpdev(devvp->v_rdev);
1282 			bufs[count].b_flags = B_NOCACHE|B_BUSY|B_READ;
1283 			bufs[count].b_iodone = hsfs_iodone;
1284 			bufs[count].b_vp = vp;
1285 			bufs[count].b_file = vp;
1286 		}
1287 
1288 		/*
1289 		 * If our filesize is not an integer multiple of PAGESIZE,
1290 		 * we zero that part of the last page that's between EOF and
1291 		 * the PAGESIZE boundary.
1292 		 */
1293 		xlen = io_len & PAGEOFFSET;
1294 		if (xlen != 0)
1295 			pagezero(pp->p_prev, xlen, PAGESIZE - xlen);
1296 
1297 		va = NULL;
1298 		lastp = NULL;
1299 		searchp = pp;
1300 		io_end = io_off + io_len;
1301 		for (count = 0, byte_offset = io_off;
1302 		    byte_offset < io_end; count++) {
1303 			ASSERT(count < bufcnt);
1304 
1305 			/* Compute disk address for interleaving. */
1306 
1307 			/* considered without skips */
1308 			which_chunk_lbn = byte_offset / chunk_data_bytes;
1309 
1310 			/* factor in skips */
1311 			offset_lbn = which_chunk_lbn * chunk_lbn_count;
1312 
1313 			/* convert to physical byte offset for lbn */
1314 			offset_bytes = LBN_TO_BYTE(offset_lbn, vp->v_vfsp);
1315 
1316 			/* don't forget offset into lbn */
1317 			offset_extra = byte_offset % chunk_data_bytes;
1318 
1319 			/* get virtual block number for driver */
1320 			driver_block =
1321 			    lbtodb(bof + xarsiz + offset_bytes + offset_extra);
1322 
1323 			if (lastp != searchp) {
1324 				/* this branch taken first time through loop */
1325 				va = vas[count] =
1326 				    ppmapin(searchp, PROT_WRITE, (caddr_t)-1);
1327 				/* ppmapin() guarantees not to return NULL */
1328 			} else {
1329 				vas[count] = NULL;
1330 			}
1331 
1332 			bufs[count].b_un.b_addr = va + byte_offset % PAGESIZE;
1333 			bufs[count].b_offset =
1334 			    (offset_t)(byte_offset - io_off + off);
1335 
1336 			/*
1337 			 * We specifically use the b_lblkno member here
1338 			 * as even in the 32 bit world driver_block can
1339 			 * get very large in line with the ISO9660 spec.
1340 			 */
1341 
1342 			bufs[count].b_lblkno = driver_block;
1343 
1344 			remaining_bytes =
1345 			    ((which_chunk_lbn + 1) * chunk_data_bytes)
1346 			    - byte_offset;
1347 
1348 			/*
1349 			 * remaining_bytes can't be zero, as we derived
1350 			 * which_chunk_lbn directly from byte_offset.
1351 			 */
1352 			if ((remaining_bytes + byte_offset) < (off + len)) {
1353 				/* coalesce-read the rest of the chunk */
1354 				bufs[count].b_bcount = remaining_bytes;
1355 			} else {
1356 				/* get the final bits */
1357 				bufs[count].b_bcount = off + len - byte_offset;
1358 			}
1359 
1360 			/*
1361 			 * It would be nice to do multiple pages'
1362 			 * worth at once here when the opportunity
1363 			 * arises, as that has been shown to improve
1364 			 * our wall time.  However, to do that
1365 			 * requires that we use the pageio subsystem,
1366 			 * which doesn't mix well with what we're
1367 			 * already using here.  We can't use pageio
1368 			 * all the time, because that subsystem
1369 			 * assumes that a page is stored in N
1370 			 * contiguous blocks on the device.
1371 			 * Interleaving violates that assumption.
1372 			 *
1373 			 * Update: This is now not so big a problem
1374 			 * because of the I/O scheduler sitting below
1375 			 * that can re-order and coalesce I/O requests.
1376 			 */
1377 
1378 			remainder = PAGESIZE - (byte_offset % PAGESIZE);
1379 			if (bufs[count].b_bcount > remainder) {
1380 				bufs[count].b_bcount = remainder;
1381 			}
1382 
1383 			bufs[count].b_bufsize = bufs[count].b_bcount;
1384 			if (((offset_t)byte_offset + bufs[count].b_bcount) >
1385 			    HS_MAXFILEOFF) {
1386 				break;
1387 			}
1388 			byte_offset += bufs[count].b_bcount;
1389 
1390 			if (fsp->hqueue == NULL) {
1391 				(void) bdev_strategy(&bufs[count]);
1392 
1393 			} else {
1394 				/*
1395 				 * We are scheduling I/O so we need to enqueue
1396 				 * requests rather than calling bdev_strategy
1397 				 * here. A later invocation of the scheduling
1398 				 * function will take care of doing the actual
1399 				 * I/O as it selects requests from the queue as
1400 				 * per the scheduling logic.
1401 				 */
1402 				struct hio *hsio = kmem_cache_alloc(hio_cache,
1403 				    KM_SLEEP);
1404 
1405 				sema_init(&fio_done[count], 0, NULL,
1406 				    SEMA_DEFAULT, NULL);
1407 				hsio->bp = &bufs[count];
1408 				hsio->sema = &fio_done[count];
1409 				hsio->io_lblkno = bufs[count].b_lblkno;
1410 				hsio->nblocks = howmany(hsio->bp->b_bcount,
1411 				    DEV_BSIZE);
1412 
1413 				/* used for deadline */
1414 				hsio->io_timestamp =
1415 				    drv_hztousec(ddi_get_lbolt());
1416 
1417 				/* for I/O coalescing */
1418 				hsio->contig_chain = NULL;
1419 				hsched_enqueue_io(fsp, hsio, 0);
1420 			}
1421 
1422 			lwp_stat_update(LWP_STAT_INBLK, 1);
1423 			lastp = searchp;
1424 			if ((remainder - bufs[count].b_bcount) < 1) {
1425 				searchp = searchp->p_next;
1426 			}
1427 		}
1428 
1429 		bufsused = count;
1430 		/* Now wait for everything to come in */
1431 		if (fsp->hqueue == NULL) {
1432 			for (count = 0; count < bufsused; count++) {
1433 				if (err == 0) {
1434 					err = biowait(&bufs[count]);
1435 				} else
1436 					(void) biowait(&bufs[count]);
1437 			}
1438 		} else {
1439 			for (count = 0; count < bufsused; count++) {
1440 				struct buf *wbuf;
1441 
1442 				/*
1443 				 * Invoke scheduling function till our buf
1444 				 * is processed. In doing this it might
1445 				 * process bufs enqueued by other threads
1446 				 * which is good.
1447 				 */
1448 				wbuf = &bufs[count];
1449 				DTRACE_PROBE1(hsfs_io_wait, struct buf *, wbuf);
1450 				while (sema_tryp(&fio_done[count]) == 0) {
1451 					/*
1452 					 * hsched_invoke_strategy will return 1
1453 					 * if the I/O queue is empty. This means
1454 					 * that there is another thread who has
1455 					 * issued our buf and is waiting. So we
1456 					 * just block instead of spinning.
1457 					 */
1458 					if (hsched_invoke_strategy(fsp)) {
1459 						sema_p(&fio_done[count]);
1460 						break;
1461 					}
1462 				}
1463 				sema_destroy(&fio_done[count]);
1464 				DTRACE_PROBE1(hsfs_io_done, struct buf *, wbuf);
1465 
1466 				if (err == 0) {
1467 					err = geterror(wbuf);
1468 				}
1469 			}
1470 			kmem_free(fio_done, bufcnt * sizeof (ksema_t));
1471 		}
1472 
1473 		/* Don't leak resources */
1474 		for (count = 0; count < bufcnt; count++) {
1475 			biofini(&bufs[count]);
1476 			if (count < bufsused && vas[count] != NULL) {
1477 				ppmapout(vas[count]);
1478 			}
1479 		}
1480 
1481 		kmem_free(vas, bufcnt * sizeof (caddr_t));
1482 		kmem_free(bufs, bufcnt * sizeof (struct buf));
1483 	}
1484 
1485 	if (err) {
1486 		pvn_read_done(pp, B_ERROR);
1487 		return (err);
1488 	}
1489 
1490 	/*
1491 	 * Lock the requested page, and the one after it if possible.
1492 	 * Don't bother if our caller hasn't given us a place to stash
1493 	 * the page pointers, since otherwise we'd lock pages that would
1494 	 * never get unlocked.
1495 	 */
1496 	if (pagefound) {
1497 		int index;
1498 		ulong_t soff;
1499 
1500 		/*
1501 		 * Make sure it's in memory before we say it's here.
1502 		 */
1503 		if ((pp = page_lookup(vp, off, SE_SHARED)) == NULL) {
1504 			hsfs_lostpage++;
1505 			goto reread;
1506 		}
1507 
1508 		pl[0] = pp;
1509 		index = 1;
1510 		atomic_inc_64(&fsp->cache_read_pages);
1511 
1512 		/*
1513 		 * Try to lock the next page, if it exists, without
1514 		 * blocking.
1515 		 */
1516 		plsz -= PAGESIZE;
1517 		/* LINTED (plsz is unsigned) */
1518 		for (soff = off + PAGESIZE; plsz > 0;
1519 		    soff += PAGESIZE, plsz -= PAGESIZE) {
1520 			pp = page_lookup_nowait(vp, (u_offset_t)soff,
1521 			    SE_SHARED);
1522 			if (pp == NULL)
1523 				break;
1524 			pl[index++] = pp;
1525 		}
1526 		pl[index] = NULL;
1527 
1528 		/*
1529 		 * Schedule a semi-asynchronous readahead if we are
1530 		 * accessing the last cached page for the current
1531 		 * file.
1532 		 *
1533 		 * Doing this here means that readaheads will be
1534 		 * issued only if cache-hits occur. This is an advantage
1535 		 * since cache-hits would mean that readahead is giving
1536 		 * the desired benefit. If cache-hits do not occur there
1537 		 * is no point in reading ahead of time - the system
1538 		 * is loaded anyway.
1539 		 */
1540 		if (fsp->hqueue != NULL &&
1541 		    hp->hs_prev_offset - off == PAGESIZE &&
1542 		    hp->hs_prev_offset < filsiz &&
1543 		    hp->hs_ra_bytes > 0 &&
1544 		    !page_exists(vp, hp->hs_prev_offset)) {
1545 			(void) hsfs_getpage_ra(vp, hp->hs_prev_offset, seg,
1546 			    addr + PAGESIZE, hp, fsp, xarsiz, bof,
1547 			    chunk_lbn_count, chunk_data_bytes);
1548 		}
1549 
1550 		return (0);
1551 	}
1552 
1553 	if (pp != NULL) {
1554 		pvn_plist_init(pp, pl, plsz, off, io_len, rw);
1555 	}
1556 
1557 	return (err);
1558 }
1559 
1560 /*ARGSUSED*/
1561 static int
1562 hsfs_getpage(
1563 	struct vnode *vp,
1564 	offset_t off,
1565 	size_t len,
1566 	uint_t *protp,
1567 	struct page *pl[],
1568 	size_t plsz,
1569 	struct seg *seg,
1570 	caddr_t addr,
1571 	enum seg_rw rw,
1572 	struct cred *cred,
1573 	caller_context_t *ct)
1574 {
1575 	int err;
1576 	uint_t filsiz;
1577 	struct hsfs *fsp;
1578 	struct hsnode *hp;
1579 
1580 	fsp = VFS_TO_HSFS(vp->v_vfsp);
1581 	hp = VTOH(vp);
1582 
1583 	/* does not support write */
1584 	if (rw == S_WRITE) {
1585 		panic("write attempt on READ ONLY HSFS");
1586 		/*NOTREACHED*/
1587 	}
1588 
1589 	if (vp->v_flag & VNOMAP) {
1590 		return (ENOSYS);
1591 	}
1592 
1593 	ASSERT(off <= HS_MAXFILEOFF);
1594 
1595 	/*
1596 	 * Determine file data size for EOF check.
1597 	 */
1598 	filsiz = hp->hs_dirent.ext_size;
1599 	if ((off + len) > (offset_t)(filsiz + PAGEOFFSET) && seg != segkmap)
1600 		return (EFAULT);	/* beyond EOF */
1601 
1602 	/*
1603 	 * Async Read-ahead computation.
1604 	 * This attempts to detect sequential access pattern and
1605 	 * enables reading extra pages ahead of time.
1606 	 */
1607 	if (fsp->hqueue != NULL) {
1608 		/*
1609 		 * This check for sequential access also takes into
1610 		 * account segmap weirdness when reading in chunks
1611 		 * less than the segmap size of 8K.
1612 		 */
1613 		if (hp->hs_prev_offset == off || (off <
1614 		    hp->hs_prev_offset && off + MAX(len, PAGESIZE)
1615 		    >= hp->hs_prev_offset)) {
1616 			if (hp->hs_num_contig <
1617 			    (seq_contig_requests - 1)) {
1618 				hp->hs_num_contig++;
1619 
1620 			} else {
1621 				/*
1622 				 * We increase readahead quantum till
1623 				 * a predefined max. max_readahead_bytes
1624 				 * is a multiple of PAGESIZE.
1625 				 */
1626 				if (hp->hs_ra_bytes <
1627 				    fsp->hqueue->max_ra_bytes) {
1628 					hp->hs_ra_bytes += PAGESIZE;
1629 				}
1630 			}
1631 		} else {
1632 			/*
1633 			 * Not contiguous so reduce read ahead counters.
1634 			 */
1635 			if (hp->hs_ra_bytes > 0)
1636 				hp->hs_ra_bytes -= PAGESIZE;
1637 
1638 			if (hp->hs_ra_bytes <= 0) {
1639 				hp->hs_ra_bytes = 0;
1640 				if (hp->hs_num_contig > 0)
1641 					hp->hs_num_contig--;
1642 			}
1643 		}
1644 		/*
1645 		 * Length must be rounded up to page boundary.
1646 		 * since we read in units of pages.
1647 		 */
1648 		hp->hs_prev_offset = off + roundup(len, PAGESIZE);
1649 		DTRACE_PROBE1(hsfs_compute_ra, struct hsnode *, hp);
1650 	}
1651 	if (protp != NULL)
1652 		*protp = PROT_ALL;
1653 
1654 	if (len <= PAGESIZE)
1655 		err = hsfs_getapage(vp, (u_offset_t)off, len, protp, pl, plsz,
1656 		    seg, addr, rw, cred);
1657 	else
1658 		err = pvn_getpages(hsfs_getapage, vp, off, len, protp,
1659 		    pl, plsz, seg, addr, rw, cred);
1660 
1661 	return (err);
1662 }
1663 
1664 
1665 
1666 /*
1667  * This function should never be called. We need to have it to pass
1668  * it as an argument to other functions.
1669  */
1670 /*ARGSUSED*/
1671 int
1672 hsfs_putapage(
1673 	vnode_t		*vp,
1674 	page_t		*pp,
1675 	u_offset_t	*offp,
1676 	size_t		*lenp,
1677 	int		flags,
1678 	cred_t		*cr)
1679 {
1680 	/* should never happen - just destroy it */
1681 	cmn_err(CE_NOTE, "hsfs_putapage: dirty HSFS page");
1682 	pvn_write_done(pp, B_ERROR | B_WRITE | B_INVAL | B_FORCE | flags);
1683 	return (0);
1684 }
1685 
1686 
1687 /*
1688  * The only flags we support are B_INVAL, B_FREE and B_DONTNEED.
1689  * B_INVAL is set by:
1690  *
1691  *	1) the MC_SYNC command of memcntl(2) to support the MS_INVALIDATE flag.
1692  *	2) the MC_ADVISE command of memcntl(2) with the MADV_DONTNEED advice
1693  *	   which translates to an MC_SYNC with the MS_INVALIDATE flag.
1694  *
1695  * The B_FREE (as well as the B_DONTNEED) flag is set when the
1696  * MADV_SEQUENTIAL advice has been used. VOP_PUTPAGE is invoked
1697  * from SEGVN to release pages behind a pagefault.
1698  */
1699 /*ARGSUSED*/
1700 static int
1701 hsfs_putpage(
1702 	struct vnode		*vp,
1703 	offset_t		off,
1704 	size_t			len,
1705 	int			flags,
1706 	struct cred		*cr,
1707 	caller_context_t	*ct)
1708 {
1709 	int error = 0;
1710 
1711 	if (vp->v_count == 0) {
1712 		panic("hsfs_putpage: bad v_count");
1713 		/*NOTREACHED*/
1714 	}
1715 
1716 	if (vp->v_flag & VNOMAP)
1717 		return (ENOSYS);
1718 
1719 	ASSERT(off <= HS_MAXFILEOFF);
1720 
1721 	if (!vn_has_cached_data(vp))	/* no pages mapped */
1722 		return (0);
1723 
1724 	if (len == 0) {		/* from 'off' to EOF */
1725 		error = pvn_vplist_dirty(vp, off, hsfs_putapage, flags, cr);
1726 	} else {
1727 		offset_t end_off = off + len;
1728 		offset_t file_size = VTOH(vp)->hs_dirent.ext_size;
1729 		offset_t io_off;
1730 
1731 		file_size = (file_size + PAGESIZE - 1) & PAGEMASK;
1732 		if (end_off > file_size)
1733 			end_off = file_size;
1734 
1735 		for (io_off = off; io_off < end_off; io_off += PAGESIZE) {
1736 			page_t *pp;
1737 
1738 			/*
1739 			 * We insist on getting the page only if we are
1740 			 * about to invalidate, free or write it and
1741 			 * the B_ASYNC flag is not set.
1742 			 */
1743 			if ((flags & B_INVAL) || ((flags & B_ASYNC) == 0)) {
1744 				pp = page_lookup(vp, io_off,
1745 				    (flags & (B_INVAL | B_FREE)) ?
1746 				    SE_EXCL : SE_SHARED);
1747 			} else {
1748 				pp = page_lookup_nowait(vp, io_off,
1749 				    (flags & B_FREE) ? SE_EXCL : SE_SHARED);
1750 			}
1751 
1752 			if (pp == NULL)
1753 				continue;
1754 
1755 			/*
1756 			 * Normally pvn_getdirty() should return 0, which
1757 			 * impies that it has done the job for us.
1758 			 * The shouldn't-happen scenario is when it returns 1.
1759 			 * This means that the page has been modified and
1760 			 * needs to be put back.
1761 			 * Since we can't write on a CD, we fake a failed
1762 			 * I/O and force pvn_write_done() to destroy the page.
1763 			 */
1764 			if (pvn_getdirty(pp, flags) == 1) {
1765 				cmn_err(CE_NOTE,
1766 				    "hsfs_putpage: dirty HSFS page");
1767 				pvn_write_done(pp, flags |
1768 				    B_ERROR | B_WRITE | B_INVAL | B_FORCE);
1769 			}
1770 		}
1771 	}
1772 	return (error);
1773 }
1774 
1775 
1776 /*ARGSUSED*/
1777 static int
1778 hsfs_map(
1779 	struct vnode *vp,
1780 	offset_t off,
1781 	struct as *as,
1782 	caddr_t *addrp,
1783 	size_t len,
1784 	uchar_t prot,
1785 	uchar_t maxprot,
1786 	uint_t flags,
1787 	struct cred *cred,
1788 	caller_context_t *ct)
1789 {
1790 	struct segvn_crargs vn_a;
1791 	int error;
1792 
1793 	/* VFS_RECORD(vp->v_vfsp, VS_MAP, VS_CALL); */
1794 
1795 	if (vp->v_flag & VNOMAP)
1796 		return (ENOSYS);
1797 
1798 	if (off > HS_MAXFILEOFF || off < 0 ||
1799 	    (off + len) < 0 || (off + len) > HS_MAXFILEOFF)
1800 		return (ENXIO);
1801 
1802 	if (vp->v_type != VREG) {
1803 		return (ENODEV);
1804 	}
1805 
1806 	/*
1807 	 * If file is being locked, disallow mapping.
1808 	 */
1809 	if (vn_has_mandatory_locks(vp, VTOH(vp)->hs_dirent.mode))
1810 		return (EAGAIN);
1811 
1812 	as_rangelock(as);
1813 
1814 	if ((flags & MAP_FIXED) == 0) {
1815 		map_addr(addrp, len, off, 1, flags);
1816 		if (*addrp == NULL) {
1817 			as_rangeunlock(as);
1818 			return (ENOMEM);
1819 		}
1820 	} else {
1821 		/*
1822 		 * User specified address - blow away any previous mappings
1823 		 */
1824 		(void) as_unmap(as, *addrp, len);
1825 	}
1826 
1827 	vn_a.vp = vp;
1828 	vn_a.offset = off;
1829 	vn_a.type = flags & MAP_TYPE;
1830 	vn_a.prot = prot;
1831 	vn_a.maxprot = maxprot;
1832 	vn_a.flags = flags & ~MAP_TYPE;
1833 	vn_a.cred = cred;
1834 	vn_a.amp = NULL;
1835 	vn_a.szc = 0;
1836 	vn_a.lgrp_mem_policy_flags = 0;
1837 
1838 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
1839 	as_rangeunlock(as);
1840 	return (error);
1841 }
1842 
1843 /* ARGSUSED */
1844 static int
1845 hsfs_addmap(
1846 	struct vnode *vp,
1847 	offset_t off,
1848 	struct as *as,
1849 	caddr_t addr,
1850 	size_t len,
1851 	uchar_t prot,
1852 	uchar_t maxprot,
1853 	uint_t flags,
1854 	struct cred *cr,
1855 	caller_context_t *ct)
1856 {
1857 	struct hsnode *hp;
1858 
1859 	if (vp->v_flag & VNOMAP)
1860 		return (ENOSYS);
1861 
1862 	hp = VTOH(vp);
1863 	mutex_enter(&hp->hs_contents_lock);
1864 	hp->hs_mapcnt += btopr(len);
1865 	mutex_exit(&hp->hs_contents_lock);
1866 	return (0);
1867 }
1868 
1869 /*ARGSUSED*/
1870 static int
1871 hsfs_delmap(
1872 	struct vnode *vp,
1873 	offset_t off,
1874 	struct as *as,
1875 	caddr_t addr,
1876 	size_t len,
1877 	uint_t prot,
1878 	uint_t maxprot,
1879 	uint_t flags,
1880 	struct cred *cr,
1881 	caller_context_t *ct)
1882 {
1883 	struct hsnode *hp;
1884 
1885 	if (vp->v_flag & VNOMAP)
1886 		return (ENOSYS);
1887 
1888 	hp = VTOH(vp);
1889 	mutex_enter(&hp->hs_contents_lock);
1890 	hp->hs_mapcnt -= btopr(len);	/* Count released mappings */
1891 	ASSERT(hp->hs_mapcnt >= 0);
1892 	mutex_exit(&hp->hs_contents_lock);
1893 	return (0);
1894 }
1895 
1896 /* ARGSUSED */
1897 static int
1898 hsfs_seek(
1899 	struct vnode *vp,
1900 	offset_t ooff,
1901 	offset_t *noffp,
1902 	caller_context_t *ct)
1903 {
1904 	return ((*noffp < 0 || *noffp > MAXOFFSET_T) ? EINVAL : 0);
1905 }
1906 
1907 /* ARGSUSED */
1908 static int
1909 hsfs_frlock(
1910 	struct vnode *vp,
1911 	int cmd,
1912 	struct flock64 *bfp,
1913 	int flag,
1914 	offset_t offset,
1915 	struct flk_callback *flk_cbp,
1916 	cred_t *cr,
1917 	caller_context_t *ct)
1918 {
1919 	struct hsnode *hp = VTOH(vp);
1920 
1921 	/*
1922 	 * If the file is being mapped, disallow fs_frlock.
1923 	 * We are not holding the hs_contents_lock while checking
1924 	 * hs_mapcnt because the current locking strategy drops all
1925 	 * locks before calling fs_frlock.
1926 	 * So, hs_mapcnt could change before we enter fs_frlock making
1927 	 * it meaningless to have held hs_contents_lock in the first place.
1928 	 */
1929 	if (hp->hs_mapcnt > 0 && MANDLOCK(vp, hp->hs_dirent.mode))
1930 		return (EAGAIN);
1931 
1932 	return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct));
1933 }
1934 
1935 static int
1936 hsched_deadline_compare(const void *x1, const void *x2)
1937 {
1938 	const struct hio *h1 = x1;
1939 	const struct hio *h2 = x2;
1940 
1941 	if (h1->io_timestamp < h2->io_timestamp)
1942 		return (-1);
1943 	if (h1->io_timestamp > h2->io_timestamp)
1944 		return (1);
1945 
1946 	if (h1->io_lblkno < h2->io_lblkno)
1947 		return (-1);
1948 	if (h1->io_lblkno > h2->io_lblkno)
1949 		return (1);
1950 
1951 	if (h1 < h2)
1952 		return (-1);
1953 	if (h1 > h2)
1954 		return (1);
1955 
1956 	return (0);
1957 }
1958 
1959 static int
1960 hsched_offset_compare(const void *x1, const void *x2)
1961 {
1962 	const struct hio *h1 = x1;
1963 	const struct hio *h2 = x2;
1964 
1965 	if (h1->io_lblkno < h2->io_lblkno)
1966 		return (-1);
1967 	if (h1->io_lblkno > h2->io_lblkno)
1968 		return (1);
1969 
1970 	if (h1 < h2)
1971 		return (-1);
1972 	if (h1 > h2)
1973 		return (1);
1974 
1975 	return (0);
1976 }
1977 
1978 void
1979 hsched_init_caches(void)
1980 {
1981 	hio_cache = kmem_cache_create("hsfs_hio_cache",
1982 	    sizeof (struct hio), 0, NULL,
1983 	    NULL, NULL, NULL, NULL, 0);
1984 
1985 	hio_info_cache = kmem_cache_create("hsfs_hio_info_cache",
1986 	    sizeof (struct hio_info), 0, NULL,
1987 	    NULL, NULL, NULL, NULL, 0);
1988 }
1989 
1990 void
1991 hsched_fini_caches(void)
1992 {
1993 	kmem_cache_destroy(hio_cache);
1994 	kmem_cache_destroy(hio_info_cache);
1995 }
1996 
1997 /*
1998  * Initialize I/O scheduling structures. This is called via hsfs_mount
1999  */
2000 void
2001 hsched_init(struct hsfs *fsp, int fsid, struct modlinkage *modlinkage)
2002 {
2003 	struct hsfs_queue *hqueue = fsp->hqueue;
2004 	struct vnode *vp = fsp->hsfs_devvp;
2005 
2006 	/* TaskQ name of the form: hsched_task_ + stringof(int) */
2007 	char namebuf[23];
2008 	int error, err;
2009 	struct dk_cinfo info;
2010 	ldi_handle_t lh;
2011 	ldi_ident_t li;
2012 
2013 	/*
2014 	 * Default maxtransfer = 16k chunk
2015 	 */
2016 	hqueue->dev_maxtransfer = 16384;
2017 
2018 	/*
2019 	 * Try to fetch the maximum device transfer size. This is used to
2020 	 * ensure that a coalesced block does not exceed the maxtransfer.
2021 	 */
2022 	err  = ldi_ident_from_mod(modlinkage, &li);
2023 	if (err) {
2024 		cmn_err(CE_NOTE, "hsched_init: Querying device failed");
2025 		cmn_err(CE_NOTE, "hsched_init: ldi_ident_from_mod err=%d\n",
2026 		    err);
2027 		goto set_ra;
2028 	}
2029 
2030 	err = ldi_open_by_dev(&(vp->v_rdev), OTYP_CHR, FREAD, CRED(), &lh, li);
2031 	ldi_ident_release(li);
2032 	if (err) {
2033 		cmn_err(CE_NOTE, "hsched_init: Querying device failed");
2034 		cmn_err(CE_NOTE, "hsched_init: ldi_open err=%d\n", err);
2035 		goto set_ra;
2036 	}
2037 
2038 	error = ldi_ioctl(lh, DKIOCINFO, (intptr_t)&info, FKIOCTL,
2039 	    CRED(), &err);
2040 	err = ldi_close(lh, FREAD, CRED());
2041 	if (err) {
2042 		cmn_err(CE_NOTE, "hsched_init: Querying device failed");
2043 		cmn_err(CE_NOTE, "hsched_init: ldi_close err=%d\n", err);
2044 	}
2045 
2046 	if (error == 0) {
2047 		hqueue->dev_maxtransfer = ldbtob(info.dki_maxtransfer);
2048 	}
2049 
2050 set_ra:
2051 	/*
2052 	 * Max size of data to read ahead for sequential access pattern.
2053 	 * Conservative to avoid letting the underlying CD drive to spin
2054 	 * down, in case the application is reading slowly.
2055 	 * We read ahead upto a max of 4 pages.
2056 	 */
2057 	hqueue->max_ra_bytes = PAGESIZE * 8;
2058 
2059 	mutex_init(&(hqueue->hsfs_queue_lock), NULL, MUTEX_DEFAULT, NULL);
2060 	mutex_init(&(hqueue->strategy_lock), NULL, MUTEX_DEFAULT, NULL);
2061 	avl_create(&(hqueue->read_tree), hsched_offset_compare,
2062 	    sizeof (struct hio), offsetof(struct hio, io_offset_node));
2063 	avl_create(&(hqueue->deadline_tree), hsched_deadline_compare,
2064 	    sizeof (struct hio), offsetof(struct hio, io_deadline_node));
2065 
2066 	(void) snprintf(namebuf, sizeof (namebuf), "hsched_task_%d", fsid);
2067 	hqueue->ra_task = taskq_create(namebuf, hsfs_taskq_nthreads,
2068 	    minclsyspri + 2, 1, 104857600 / PAGESIZE, TASKQ_DYNAMIC);
2069 
2070 	hqueue->next = NULL;
2071 	hqueue->nbuf = kmem_zalloc(sizeof (struct buf), KM_SLEEP);
2072 }
2073 
2074 void
2075 hsched_fini(struct hsfs_queue *hqueue)
2076 {
2077 	if (hqueue != NULL) {
2078 		avl_destroy(&(hqueue->read_tree));
2079 		avl_destroy(&(hqueue->deadline_tree));
2080 		mutex_destroy(&(hqueue->hsfs_queue_lock));
2081 		mutex_destroy(&(hqueue->strategy_lock));
2082 
2083 		/*
2084 		 * If there are any existing readahead threads running
2085 		 * taskq_destroy will wait for them to finish.
2086 		 */
2087 		taskq_destroy(hqueue->ra_task);
2088 		if (hqueue->next != NULL) {
2089 			kmem_cache_free(hio_cache, hqueue->next);
2090 		}
2091 		kmem_free(hqueue->nbuf, sizeof (struct buf));
2092 	}
2093 }
2094 
2095 /*
2096  * Determine if two I/O requests are adjacent to each other so
2097  * that they can coalesced.
2098  */
2099 #define	IS_ADJACENT(io, nio) \
2100 	(((io)->io_lblkno + (io)->nblocks == (nio)->io_lblkno) && \
2101 	(io)->bp->b_edev == (nio)->bp->b_edev)
2102 
2103 /*
2104  * This performs the actual I/O scheduling logic. We use the Circular
2105  * Look algorithm here. Sort the I/O requests in ascending order of
2106  * logical block number and process them starting with the lowest
2107  * numbered block and progressing towards higher block numbers in the
2108  * queue. Once there are no more higher numbered blocks, start again
2109  * with the lowest one. This is good for CD/DVD as you keep moving
2110  * the head in one direction along the outward spiral track and avoid
2111  * too many seeks as much as possible. The re-ordering also allows
2112  * us to coalesce adjacent requests into one larger request.
2113  * This is thus essentially a 1-way Elevator with front merging.
2114  *
2115  * In addition each read request here has a deadline and will be
2116  * processed out of turn if the deadline (500ms) expires.
2117  *
2118  * This function is necessarily serialized via hqueue->strategy_lock.
2119  * This function sits just below hsfs_getapage and processes all read
2120  * requests orginating from that function.
2121  */
2122 int
2123 hsched_invoke_strategy(struct hsfs *fsp)
2124 {
2125 	struct hsfs_queue *hqueue;
2126 	struct buf *nbuf;
2127 	struct hio *fio, *nio, *tio, *prev, *last;
2128 	size_t bsize, soffset, offset, data;
2129 	int bioret, bufcount;
2130 	struct vnode *fvp;
2131 	ksema_t *io_done;
2132 	caddr_t iodata;
2133 
2134 	hqueue = fsp->hqueue;
2135 	mutex_enter(&hqueue->strategy_lock);
2136 	mutex_enter(&hqueue->hsfs_queue_lock);
2137 
2138 	/*
2139 	 * Check for Deadline expiration first
2140 	 */
2141 	fio = avl_first(&hqueue->deadline_tree);
2142 
2143 	/*
2144 	 * Paranoid check for empty I/O queue. Both deadline
2145 	 * and read trees contain same data sorted in different
2146 	 * ways. So empty deadline tree = empty read tree.
2147 	 */
2148 	if (fio == NULL) {
2149 		/*
2150 		 * Remove the sentinel if there was one.
2151 		 */
2152 		if (hqueue->next != NULL) {
2153 			avl_remove(&hqueue->read_tree, hqueue->next);
2154 			kmem_cache_free(hio_cache, hqueue->next);
2155 			hqueue->next = NULL;
2156 		}
2157 		mutex_exit(&hqueue->hsfs_queue_lock);
2158 		mutex_exit(&hqueue->strategy_lock);
2159 		return (1);
2160 	}
2161 
2162 	if (drv_hztousec(ddi_get_lbolt()) - fio->io_timestamp
2163 	    < HSFS_READ_DEADLINE) {
2164 		/*
2165 		 * Apply standard scheduling logic. This uses the
2166 		 * C-LOOK approach. Process I/O requests in ascending
2167 		 * order of logical block address till no subsequent
2168 		 * higher numbered block request remains. Then start
2169 		 * again from the lowest numbered block in the queue.
2170 		 *
2171 		 * We do this cheaply here by means of a sentinel.
2172 		 * The last processed I/O structure from the previous
2173 		 * invocation of this func, is left dangling in the
2174 		 * read_tree so that we can easily scan to the next
2175 		 * higher numbered request and remove the sentinel.
2176 		 */
2177 		fio = NULL;
2178 		if (hqueue->next != NULL) {
2179 			fio = AVL_NEXT(&hqueue->read_tree, hqueue->next);
2180 			avl_remove(&hqueue->read_tree, hqueue->next);
2181 			kmem_cache_free(hio_cache, hqueue->next);
2182 			hqueue->next = NULL;
2183 		}
2184 		if (fio == NULL) {
2185 			fio = avl_first(&hqueue->read_tree);
2186 		}
2187 	} else if (hqueue->next != NULL) {
2188 		DTRACE_PROBE1(hsfs_deadline_expiry, struct hio *, fio);
2189 
2190 		avl_remove(&hqueue->read_tree, hqueue->next);
2191 		kmem_cache_free(hio_cache, hqueue->next);
2192 		hqueue->next = NULL;
2193 	}
2194 
2195 	/*
2196 	 * In addition we try to coalesce contiguous
2197 	 * requests into one bigger request.
2198 	 */
2199 	bufcount = 1;
2200 	bsize = ldbtob(fio->nblocks);
2201 	fvp = fio->bp->b_file;
2202 	nio = AVL_NEXT(&hqueue->read_tree, fio);
2203 	tio = fio;
2204 	while (nio != NULL && IS_ADJACENT(tio, nio) &&
2205 	    bsize < hqueue->dev_maxtransfer) {
2206 		avl_remove(&hqueue->deadline_tree, tio);
2207 		avl_remove(&hqueue->read_tree, tio);
2208 		tio->contig_chain = nio;
2209 		bsize += ldbtob(nio->nblocks);
2210 		prev = tio;
2211 		tio = nio;
2212 
2213 		/*
2214 		 * This check is required to detect the case where
2215 		 * we are merging adjacent buffers belonging to
2216 		 * different files. fvp is used to set the b_file
2217 		 * parameter in the coalesced buf. b_file is used
2218 		 * by DTrace so we do not want DTrace to accrue
2219 		 * requests to two different files to any one file.
2220 		 */
2221 		if (fvp && tio->bp->b_file != fvp) {
2222 			fvp = NULL;
2223 		}
2224 
2225 		nio = AVL_NEXT(&hqueue->read_tree, nio);
2226 		bufcount++;
2227 	}
2228 
2229 	/*
2230 	 * tio is not removed from the read_tree as it serves as a sentinel
2231 	 * to cheaply allow us to scan to the next higher numbered I/O
2232 	 * request.
2233 	 */
2234 	hqueue->next = tio;
2235 	avl_remove(&hqueue->deadline_tree, tio);
2236 	mutex_exit(&hqueue->hsfs_queue_lock);
2237 	DTRACE_PROBE3(hsfs_io_dequeued, struct hio *, fio, int, bufcount,
2238 	    size_t, bsize);
2239 
2240 	/*
2241 	 * The benefit of coalescing occurs if the the savings in I/O outweighs
2242 	 * the cost of doing the additional work below.
2243 	 * It was observed that coalescing 2 buffers results in diminishing
2244 	 * returns, so we do coalescing if we have >2 adjacent bufs.
2245 	 */
2246 	if (bufcount > hsched_coalesce_min) {
2247 		/*
2248 		 * We have coalesced blocks. First allocate mem and buf for
2249 		 * the entire coalesced chunk.
2250 		 * Since we are guaranteed single-threaded here we pre-allocate
2251 		 * one buf at mount time and that is re-used every time. This
2252 		 * is a synthesized buf structure that uses kmem_alloced chunk.
2253 		 * Not quite a normal buf attached to pages.
2254 		 */
2255 		fsp->coalesced_bytes += bsize;
2256 		nbuf = hqueue->nbuf;
2257 		bioinit(nbuf);
2258 		nbuf->b_edev = fio->bp->b_edev;
2259 		nbuf->b_dev = fio->bp->b_dev;
2260 		nbuf->b_flags = fio->bp->b_flags;
2261 		nbuf->b_iodone = fio->bp->b_iodone;
2262 		iodata = kmem_alloc(bsize, KM_SLEEP);
2263 		nbuf->b_un.b_addr = iodata;
2264 		nbuf->b_lblkno = fio->bp->b_lblkno;
2265 		nbuf->b_vp = fvp;
2266 		nbuf->b_file = fvp;
2267 		nbuf->b_bcount = bsize;
2268 		nbuf->b_bufsize = bsize;
2269 		nbuf->b_resid = bsize;
2270 
2271 		DTRACE_PROBE3(hsfs_coalesced_io_start, struct hio *, fio, int,
2272 		    bufcount, size_t, bsize);
2273 
2274 		/*
2275 		 * Perform I/O for the coalesced block.
2276 		 */
2277 		(void) bdev_strategy(nbuf);
2278 
2279 		/*
2280 		 * Duplicate the last IO node to leave the sentinel alone.
2281 		 * The sentinel is freed in the next invocation of this
2282 		 * function.
2283 		 */
2284 		prev->contig_chain = kmem_cache_alloc(hio_cache, KM_SLEEP);
2285 		prev->contig_chain->bp = tio->bp;
2286 		prev->contig_chain->sema = tio->sema;
2287 		tio = prev->contig_chain;
2288 		tio->contig_chain = NULL;
2289 		soffset = ldbtob(fio->bp->b_lblkno);
2290 		nio = fio;
2291 
2292 		bioret = biowait(nbuf);
2293 		data = bsize - nbuf->b_resid;
2294 		biofini(nbuf);
2295 		mutex_exit(&hqueue->strategy_lock);
2296 
2297 		/*
2298 		 * We use the b_resid parameter to detect how much
2299 		 * data was succesfully transferred. We will signal
2300 		 * a success to all the fully retrieved actual bufs
2301 		 * before coalescing, rest is signaled as error,
2302 		 * if any.
2303 		 */
2304 		tio = nio;
2305 		DTRACE_PROBE3(hsfs_coalesced_io_done, struct hio *, nio,
2306 		    int, bioret, size_t, data);
2307 
2308 		/*
2309 		 * Copy data and signal success to all the bufs
2310 		 * which can be fully satisfied from b_resid.
2311 		 */
2312 		while (nio != NULL && data >= nio->bp->b_bcount) {
2313 			offset = ldbtob(nio->bp->b_lblkno) - soffset;
2314 			bcopy(iodata + offset, nio->bp->b_un.b_addr,
2315 			    nio->bp->b_bcount);
2316 			data -= nio->bp->b_bcount;
2317 			bioerror(nio->bp, 0);
2318 			biodone(nio->bp);
2319 			sema_v(nio->sema);
2320 			tio = nio;
2321 			nio = nio->contig_chain;
2322 			kmem_cache_free(hio_cache, tio);
2323 		}
2324 
2325 		/*
2326 		 * Signal error to all the leftover bufs (if any)
2327 		 * after b_resid data is exhausted.
2328 		 */
2329 		while (nio != NULL) {
2330 			nio->bp->b_resid = nio->bp->b_bcount - data;
2331 			bzero(nio->bp->b_un.b_addr + data, nio->bp->b_resid);
2332 			bioerror(nio->bp, bioret);
2333 			biodone(nio->bp);
2334 			sema_v(nio->sema);
2335 			tio = nio;
2336 			nio = nio->contig_chain;
2337 			kmem_cache_free(hio_cache, tio);
2338 			data = 0;
2339 		}
2340 		kmem_free(iodata, bsize);
2341 	} else {
2342 
2343 		nbuf = tio->bp;
2344 		io_done = tio->sema;
2345 		nio = fio;
2346 		last = tio;
2347 
2348 		while (nio != NULL) {
2349 			(void) bdev_strategy(nio->bp);
2350 			nio = nio->contig_chain;
2351 		}
2352 		nio = fio;
2353 		mutex_exit(&hqueue->strategy_lock);
2354 
2355 		while (nio != NULL) {
2356 			if (nio == last) {
2357 				(void) biowait(nbuf);
2358 				sema_v(io_done);
2359 				break;
2360 				/* sentinel last not freed. See above. */
2361 			} else {
2362 				(void) biowait(nio->bp);
2363 				sema_v(nio->sema);
2364 			}
2365 			tio = nio;
2366 			nio = nio->contig_chain;
2367 			kmem_cache_free(hio_cache, tio);
2368 		}
2369 	}
2370 	return (0);
2371 }
2372 
2373 /*
2374  * Insert an I/O request in the I/O scheduler's pipeline
2375  * Using AVL tree makes it easy to reorder the I/O request
2376  * based on logical block number.
2377  */
2378 static void
2379 hsched_enqueue_io(struct hsfs *fsp, struct hio *hsio, int ra)
2380 {
2381 	struct hsfs_queue *hqueue = fsp->hqueue;
2382 
2383 	mutex_enter(&hqueue->hsfs_queue_lock);
2384 
2385 	fsp->physical_read_bytes += hsio->bp->b_bcount;
2386 	if (ra)
2387 		fsp->readahead_bytes += hsio->bp->b_bcount;
2388 
2389 	avl_add(&hqueue->deadline_tree, hsio);
2390 	avl_add(&hqueue->read_tree, hsio);
2391 
2392 	DTRACE_PROBE3(hsfs_io_enqueued, struct hio *, hsio,
2393 	    struct hsfs_queue *, hqueue, int, ra);
2394 
2395 	mutex_exit(&hqueue->hsfs_queue_lock);
2396 }
2397 
2398 /* ARGSUSED */
2399 static int
2400 hsfs_pathconf(struct vnode *vp,
2401 	int cmd,
2402 	ulong_t *valp,
2403 	struct cred *cr,
2404 	caller_context_t *ct)
2405 {
2406 	struct hsfs	*fsp;
2407 
2408 	int		error = 0;
2409 
2410 	switch (cmd) {
2411 
2412 	case _PC_NAME_MAX:
2413 		fsp = VFS_TO_HSFS(vp->v_vfsp);
2414 		*valp = fsp->hsfs_namemax;
2415 		break;
2416 
2417 	case _PC_FILESIZEBITS:
2418 		*valp = 33;	/* Without multi extent support: 4 GB - 2k */
2419 		break;
2420 
2421 	default:
2422 		error = fs_pathconf(vp, cmd, valp, cr, ct);
2423 	}
2424 
2425 	return (error);
2426 }
2427 
2428 
2429 
2430 const fs_operation_def_t hsfs_vnodeops_template[] = {
2431 	VOPNAME_OPEN,		{ .vop_open = hsfs_open },
2432 	VOPNAME_CLOSE,		{ .vop_close = hsfs_close },
2433 	VOPNAME_READ,		{ .vop_read = hsfs_read },
2434 	VOPNAME_GETATTR,	{ .vop_getattr = hsfs_getattr },
2435 	VOPNAME_ACCESS,		{ .vop_access = hsfs_access },
2436 	VOPNAME_LOOKUP,		{ .vop_lookup = hsfs_lookup },
2437 	VOPNAME_READDIR,	{ .vop_readdir = hsfs_readdir },
2438 	VOPNAME_READLINK,	{ .vop_readlink = hsfs_readlink },
2439 	VOPNAME_FSYNC,		{ .vop_fsync = hsfs_fsync },
2440 	VOPNAME_INACTIVE,	{ .vop_inactive = hsfs_inactive },
2441 	VOPNAME_FID,		{ .vop_fid = hsfs_fid },
2442 	VOPNAME_SEEK,		{ .vop_seek = hsfs_seek },
2443 	VOPNAME_FRLOCK,		{ .vop_frlock = hsfs_frlock },
2444 	VOPNAME_GETPAGE,	{ .vop_getpage = hsfs_getpage },
2445 	VOPNAME_PUTPAGE,	{ .vop_putpage = hsfs_putpage },
2446 	VOPNAME_MAP,		{ .vop_map = hsfs_map },
2447 	VOPNAME_ADDMAP,		{ .vop_addmap = hsfs_addmap },
2448 	VOPNAME_DELMAP,		{ .vop_delmap = hsfs_delmap },
2449 	VOPNAME_PATHCONF,	{ .vop_pathconf = hsfs_pathconf },
2450 	NULL,			NULL
2451 };
2452 
2453 struct vnodeops *hsfs_vnodeops;
2454