xref: /titanic_44/usr/src/uts/common/io/scsi/targets/st.c (revision 6e16840296a75e42faa7d22cc93f56e4e8e2d301)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * SCSI	 SCSA-compliant and not-so-DDI-compliant Tape Driver
31  */
32 
33 #if defined(lint) && !defined(DEBUG)
34 #define	DEBUG	1
35 #endif
36 
37 #include <sys/modctl.h>
38 #include <sys/scsi/scsi.h>
39 #include <sys/mtio.h>
40 #include <sys/scsi/targets/stdef.h>
41 #include <sys/file.h>
42 #include <sys/stat.h>
43 #include <sys/kstat.h>
44 #include <sys/ddidmareq.h>
45 #include <sys/ddi.h>
46 #include <sys/sunddi.h>
47 
48 #define	IOSP	KSTAT_IO_PTR(un->un_stats)
49 /*
50  * stats maintained only for reads/writes as commands
51  * like rewind etc skew the wait/busy times
52  */
53 #define	IS_RW(bp) 	((bp)->b_bcount > 0)
54 #define	ST_DO_KSTATS(bp, kstat_function) \
55 	if ((bp != un->un_sbufp) && un->un_stats && IS_RW(bp)) { \
56 		kstat_function(IOSP); \
57 	}
58 
59 #define	ST_DO_ERRSTATS(un, x)  \
60 	if (un->un_errstats) { \
61 		struct st_errstats *stp; \
62 		stp = (struct st_errstats *)un->un_errstats->ks_data; \
63 		stp->x.value.ul++; \
64 	}
65 
66 #define	FILL_SCSI1_LUN(devp, pkt) 					\
67 	if ((devp)->sd_inq->inq_ansi == 0x1) {				\
68 		int _lun;						\
69 		_lun = ddi_prop_get_int(DDI_DEV_T_ANY, (devp)->sd_dev,	\
70 		    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);		\
71 		if (_lun > 0) {						\
72 			((union scsi_cdb *)(pkt)->pkt_cdbp)->scc_lun =	\
73 			    _lun;					\
74 		}							\
75 	}
76 
77 #define	ST_NUM_MEMBERS(array)	(sizeof (array) / sizeof (array[0]))
78 
79 /*
80  * Global External Data Definitions
81  */
82 extern struct scsi_key_strings scsi_cmds[];
83 
84 /*
85  * Local Static Data
86  */
87 static void *st_state;
88 static char *st_label = "st";
89 
90 #if defined(__i386) || defined(__amd64)
91 /*
92  * We need to use below DMA attr to alloc physically contiguous
93  * memory to do I/O in big block size
94  */
95 static ddi_dma_attr_t st_contig_mem_dma_attr = {
96 	DMA_ATTR_V0,    /* version number */
97 	0x0,		/* lowest usable address */
98 	0xFFFFFFFFull,  /* high DMA address range */
99 	0xFFFFFFFFull,  /* DMA counter register */
100 	1,		/* DMA address alignment */
101 	1,		/* DMA burstsizes */
102 	1,		/* min effective DMA size */
103 	0xFFFFFFFFull,  /* max DMA xfer size */
104 	0xFFFFFFFFull,  /* segment boundary */
105 	1,		/* s/g list length */
106 	1,		/* granularity of device */
107 	0		/* DMA transfer flags */
108 };
109 
110 static ddi_device_acc_attr_t st_acc_attr = {
111 	DDI_DEVICE_ATTR_V0,
112 	DDI_NEVERSWAP_ACC,
113 	DDI_STRICTORDER_ACC
114 };
115 
116 /* set limitation for the number of contig_mem */
117 static int st_max_contig_mem_num = ST_MAX_CONTIG_MEM_NUM;
118 #endif
119 
120 /*
121  * Tunable parameters
122  *
123  * DISCLAIMER
124  * ----------
125  * These parameters are intended for use only in system testing; if you use
126  * them in production systems, you do so at your own risk. Altering any
127  * variable not listed below may cause unpredictable system behavior.
128  *
129  * st_check_media_time
130  *
131  *   Three second state check
132  *
133  * st_allow_large_xfer
134  *
135  *   Gated with ST_NO_RECSIZE_LIMIT
136  *
137  *   0 - Transfers larger than 64KB will not be allowed
138  *       regardless of the setting of ST_NO_RECSIZE_LIMIT
139  *   1 - Transfers larger than 64KB will be allowed
140  *       if ST_NO_RECSIZE_LIMIT is TRUE for the drive
141  *
142  * st_report_soft_errors_on_close
143  *
144  *  Gated with ST_SOFT_ERROR_REPORTING
145  *
146  *  0 - Errors will not be reported on close regardless
147  *      of the setting of ST_SOFT_ERROR_REPORTING
148  *
149  *  1 - Errors will be reported on close if
150  *      ST_SOFT_ERROR_REPORTING is TRUE for the drive
151  */
152 static int st_selection_retry_count = ST_SEL_RETRY_COUNT;
153 static int st_retry_count	= ST_RETRY_COUNT;
154 
155 static int st_io_time		= ST_IO_TIME;
156 static int st_long_timeout_x	= ST_LONG_TIMEOUT_X;
157 
158 static int st_space_time	= ST_SPACE_TIME;
159 static int st_long_space_time_x	= ST_LONG_SPACE_TIME_X;
160 
161 static int st_error_level	= SCSI_ERR_RETRYABLE;
162 static int st_check_media_time	= 3000000;	/* 3 Second State Check */
163 
164 static int st_max_throttle	= ST_MAX_THROTTLE;
165 
166 static clock_t st_wait_cmds_complete = ST_WAIT_CMDS_COMPLETE;
167 
168 static int st_allow_large_xfer = 1;
169 static int st_report_soft_errors_on_close = 1;
170 
171 /*
172  * End of tunable parameters list
173  */
174 
175 
176 
177 /*
178  * Asynchronous I/O and persistent errors, refer to PSARC/1995/228
179  *
180  * Asynchronous I/O's main offering is that it is a non-blocking way to do
181  * reads and writes.  The driver will queue up all the requests it gets and
182  * have them ready to transport to the HBA.  Unfortunately, we cannot always
183  * just ship the I/O requests to the HBA, as there errors and exceptions
184  * that may happen when we don't want the HBA to continue.  Therein comes
185  * the flush-on-errors capability.  If the HBA supports it, then st will
186  * send in st_max_throttle I/O requests at the same time.
187  *
188  * Persistent errors : This was also reasonably simple.  In the interrupt
189  * routines, if there was an error or exception (FM, LEOT, media error,
190  * transport error), the persistent error bits are set and shuts everything
191  * down, but setting the throttle to zero.  If we hit and exception in the
192  * HBA, and flush-on-errors were set, we wait for all outstanding I/O's to
193  * come back (with CMD_ABORTED), then flush all bp's in the wait queue with
194  * the appropriate error, and this will preserve order. Of course, depending
195  * on the exception we have to show a zero read or write before we show
196  * errors back to the application.
197  */
198 
199 extern const int st_ndrivetypes;	/* defined in st_conf.c */
200 extern const struct st_drivetype st_drivetypes[];
201 
202 static kmutex_t st_attach_mutex;
203 
204 #ifdef STDEBUG
205 static int st_soft_error_report_debug = 0;
206 static int st_debug = 0;
207 #endif
208 
209 #define	ST_MT02_NAME	"Emulex  MT02 QIC-11/24  "
210 
211 static const struct driver_minor_data {
212 	char	*name;
213 	int	minor;
214 } st_minor_data[] = {
215 	/*
216 	 * The top 4 entries are for the default densities,
217 	 * don't alter their position.
218 	 */
219 	{"",	0},
220 	{"n",	MT_NOREWIND},
221 	{"b",	MT_BSD},
222 	{"bn",	MT_NOREWIND | MT_BSD},
223 	{"l",	MT_DENSITY1},
224 	{"m",	MT_DENSITY2},
225 	{"h",	MT_DENSITY3},
226 	{"c",	MT_DENSITY4},
227 	{"u",	MT_DENSITY4},
228 	{"ln",	MT_DENSITY1 | MT_NOREWIND},
229 	{"mn",	MT_DENSITY2 | MT_NOREWIND},
230 	{"hn",	MT_DENSITY3 | MT_NOREWIND},
231 	{"cn",	MT_DENSITY4 | MT_NOREWIND},
232 	{"un",	MT_DENSITY4 | MT_NOREWIND},
233 	{"lb",	MT_DENSITY1 | MT_BSD},
234 	{"mb",	MT_DENSITY2 | MT_BSD},
235 	{"hb",	MT_DENSITY3 | MT_BSD},
236 	{"cb",	MT_DENSITY4 | MT_BSD},
237 	{"ub",	MT_DENSITY4 | MT_BSD},
238 	{"lbn",	MT_DENSITY1 | MT_NOREWIND | MT_BSD},
239 	{"mbn",	MT_DENSITY2 | MT_NOREWIND | MT_BSD},
240 	{"hbn",	MT_DENSITY3 | MT_NOREWIND | MT_BSD},
241 	{"cbn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD},
242 	{"ubn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD}
243 };
244 
245 /* strings used in many debug and warning messages */
246 static const char wr_str[]  = "write";
247 static const char rd_str[]  = "read";
248 static const char wrg_str[] = "writing";
249 static const char rdg_str[] = "reading";
250 
251 /* default density offsets in the table above */
252 #define	DEF_BLANK	0
253 #define	DEF_NOREWIND	1
254 #define	DEF_BSD		2
255 #define	DEF_BSD_NR	3
256 
257 /* Sense Key, ASC/ASCQ for which tape ejection is needed */
258 
259 static struct tape_failure_code {
260 	uchar_t key;
261 	uchar_t add_code;
262 	uchar_t qual_code;
263 } st_tape_failure_code[] = {
264 	{ KEY_HARDWARE_ERROR, 0x15, 0x01},
265 	{ KEY_HARDWARE_ERROR, 0x44, 0x00},
266 	{ KEY_HARDWARE_ERROR, 0x53, 0x00},
267 	{ KEY_HARDWARE_ERROR, 0x53, 0x01},
268 	{ KEY_NOT_READY, 0x53, 0x00},
269 	{ 0xff}
270 };
271 
272 /*  clean bit position and mask */
273 
274 static struct cln_bit_position {
275 	ushort_t cln_bit_byte;
276 	uchar_t cln_bit_mask;
277 } st_cln_bit_position[] = {
278 	{ 21, 0x08},
279 	{ 70, 0xc0},
280 	{ 18, 0x81}  /* 80 bit indicates in bit mode, 1 bit clean light is on */
281 };
282 
283 /*
284  * Configuration Data:
285  *
286  * Device driver ops vector
287  */
288 static int st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
289 static int st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
290 static int st_read(dev_t  dev,  struct   uio   *uio_p,   cred_t *cred_p);
291 static int st_write(dev_t  dev,  struct  uio   *uio_p,   cred_t *cred_p);
292 static int st_open(dev_t  *devp,  int  flag,  int  otyp,  cred_t *cred_p);
293 static int st_close(dev_t  dev,  int  flag,  int  otyp,  cred_t *cred_p);
294 static int st_strategy(struct buf *bp);
295 static int st_ioctl(dev_t dev, int cmd, intptr_t arg, int  flag,
296 	cred_t *cred_p, int *rval_p);
297 extern int nulldev(), nodev();
298 
299 static struct cb_ops st_cb_ops = {
300 	st_open,			/* open */
301 	st_close,		/* close */
302 	st_strategy,		/* strategy */
303 	nodev,			/* print */
304 	nodev,			/* dump */
305 	st_read,		/* read */
306 	st_write,		/* write */
307 	st_ioctl,		/* ioctl */
308 	nodev,			/* devmap */
309 	nodev,			/* mmap */
310 	nodev,			/* segmap */
311 	nochpoll,		/* poll */
312 	ddi_prop_op,		/* cb_prop_op */
313 	0,			/* streamtab  */
314 	D_64BIT | D_MP | D_NEW | D_HOTPLUG,	/* Driver compatibility flag */
315 	CB_REV,			/* cb_rev */
316 	st_aread, 		/* async I/O read entry point */
317 	st_awrite		/* async I/O write entry point */
318 
319 };
320 
321 static int stinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
322 		void **result);
323 static int st_probe(dev_info_t *dev);
324 static int st_attach(dev_info_t *dev, ddi_attach_cmd_t cmd);
325 static int st_detach(dev_info_t *dev, ddi_detach_cmd_t cmd);
326 
327 static struct dev_ops st_ops = {
328 	DEVO_REV,		/* devo_rev, */
329 	0,			/* refcnt  */
330 	stinfo,			/* info */
331 	nulldev,		/* identify */
332 	st_probe,		/* probe */
333 	st_attach,		/* attach */
334 	st_detach,		/* detach */
335 	nodev,			/* reset */
336 	&st_cb_ops,		/* driver operations */
337 	(struct bus_ops *)0,	/* bus operations */
338 	nulldev			/* power */
339 };
340 
341 /*
342  * Local Function Declarations
343  */
344 static void st_clean_print(dev_info_t *dev, char *label, uint_t level,
345 	char *title, char *data, int len);
346 static int st_doattach(struct scsi_device *devp, int (*canwait)());
347 static void st_known_tape_type(struct scsi_tape *un);
348 static int st_get_conf_from_st_dot_conf(struct scsi_tape *, char *,
349     struct st_drivetype *);
350 static int st_get_conf_from_st_conf_dot_c(struct scsi_tape *, char *,
351     struct st_drivetype *);
352 static int st_get_default_conf(struct scsi_tape *, char *,
353     struct st_drivetype *);
354 static int st_rw(dev_t dev, struct uio *uio, int flag);
355 static int st_arw(dev_t dev, struct aio_req *aio, int flag);
356 static int st_find_eom(dev_t dev);
357 static int st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag);
358 static int st_ioctl_cmd(dev_t dev, struct uscsi_cmd *,
359 	enum uio_seg, enum uio_seg, enum uio_seg);
360 static int st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag);
361 static void st_start(struct scsi_tape *un);
362 static int st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
363     clock_t timeout_interval);
364 static int st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
365     clock_t timeout_interval);
366 static int st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp);
367 static void st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp);
368 static void st_init(struct scsi_tape *un);
369 static void st_make_cmd(struct scsi_tape *un, struct buf *bp,
370     int (*func)(caddr_t));
371 static void st_make_uscsi_cmd(struct scsi_tape *, struct uscsi_cmd *,
372     struct buf *bp, int (*func)(caddr_t));
373 static void st_intr(struct scsi_pkt *pkt);
374 static void st_set_state(struct scsi_tape *un);
375 static void st_test_append(struct buf *bp);
376 static int st_runout(caddr_t);
377 static int st_cmd(dev_t dev, int com, int count, int wait);
378 static int st_set_compression(struct scsi_tape *un);
379 static int st_write_fm(dev_t dev, int wfm);
380 static int st_determine_generic(dev_t dev);
381 static int st_determine_density(dev_t dev, int rw);
382 static int st_get_density(dev_t dev);
383 static int st_set_density(dev_t dev);
384 static int st_loadtape(dev_t dev);
385 static int st_modesense(struct scsi_tape *un);
386 static int st_modeselect(struct scsi_tape *un);
387 static int st_handle_incomplete(struct scsi_tape *un, struct buf *bp);
388 static int st_wrongtapetype(struct scsi_tape *un);
389 static int st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt);
390 static int st_handle_sense(struct scsi_tape *un, struct buf *bp);
391 static int st_handle_autosense(struct scsi_tape *un, struct buf *bp);
392 static int st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
393 	struct scsi_status *);
394 static int st_report_soft_errors(dev_t dev, int flag);
395 static void st_delayed_cv_broadcast(void *arg);
396 static int st_check_media(dev_t dev, enum mtio_state state);
397 static int st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
398 static void st_intr_restart(void *arg);
399 static void st_start_restart(void *arg);
400 static int st_gen_mode_sense(struct scsi_tape *un, int page,
401     struct seq_mode *page_data, int page_size);
402 static int st_change_block_size(dev_t dev, uint32_t nblksz);
403 static int st_gen_mode_select(struct scsi_tape *un, struct seq_mode *page_data,
404     int page_size);
405 static int st_tape_init(dev_t dev);
406 static void st_flush(struct scsi_tape *un);
407 static void st_set_pe_errno(struct scsi_tape *un);
408 static void st_hba_unflush(struct scsi_tape *un);
409 static void st_turn_pe_on(struct scsi_tape *un);
410 static void st_turn_pe_off(struct scsi_tape *un);
411 static void st_set_pe_flag(struct scsi_tape *un);
412 static void st_clear_pe(struct scsi_tape *un);
413 static void st_wait_for_io(struct scsi_tape *un);
414 static int st_set_devconfig_page(struct scsi_tape *un, int compression_on);
415 static int st_set_datacomp_page(struct scsi_tape *un, int compression_on);
416 static int st_tape_reservation_init(dev_t dev);
417 static int st_reserve_release(dev_t dev, int command);
418 static int st_take_ownership(dev_t dev);
419 static int st_check_asc_ascq(struct scsi_tape *un);
420 static int st_check_clean_bit(dev_t dev);
421 static int st_check_alert_clean_bit(dev_t dev);
422 static int st_check_sequential_clean_bit(dev_t dev);
423 static int st_check_sense_clean_bit(dev_t dev);
424 static int st_clear_unit_attentions(dev_t dev_instance, int max_trys);
425 static void st_calculate_timeouts(struct scsi_tape *un);
426 
427 #if defined(__i386) || defined(__amd64)
428 /*
429  * routines for I/O in big block size
430  */
431 static void st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp);
432 static struct contig_mem *st_get_contig_mem(struct scsi_tape *un, size_t len,
433     int alloc_flags);
434 static int st_bigblk_xfer_done(struct buf *bp);
435 static struct buf *st_get_bigblk_bp(struct buf *bp);
436 #endif
437 
438 /*
439  * error statistics create/update functions
440  */
441 static int st_create_errstats(struct scsi_tape *, int);
442 static void st_uscsi_minphys(struct buf *bp);
443 static int st_validate_tapemarks(struct scsi_tape *un, int fileno, daddr_t bn);
444 
445 #ifdef STDEBUG
446 static void st_debug_cmds(struct scsi_tape *un, int com, int count, int wait);
447 static char *st_dev_name(dev_t dev);
448 #endif /* STDEBUG */
449 
450 #if !defined(lint)
451 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_pkt buf uio scsi_cdb))
452 _NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_extended_sense scsi_status))
453 _NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device))
454 _NOTE(DATA_READABLE_WITHOUT_LOCK(st_drivetype scsi_address))
455 #endif
456 
457 /*
458  * autoconfiguration routines.
459  */
460 char _depends_on[] = "misc/scsi";
461 
462 static struct modldrv modldrv = {
463 	&mod_driverops,		/* Type of module. This one is a driver */
464 	"SCSI tape Driver %I%", /* Name of the module. */
465 	&st_ops			/* driver ops */
466 };
467 
468 static struct modlinkage modlinkage = {
469 	MODREV_1, &modldrv, NULL
470 };
471 
472 /*
473  * Notes on Post Reset Behavior in the tape driver:
474  *
475  * When the tape drive is opened, the driver  attempts  to make sure that
476  * the tape head is positioned exactly where it was left when it was last
477  * closed  provided  the  medium  is not  changed.  If the tape  drive is
478  * opened in O_NDELAY mode, the repositioning  (if necessary for any loss
479  * of position due to reset) will happen when the first tape operation or
480  * I/O occurs.  The repositioning (if required) may not be possible under
481  * certain situations such as when the device firmware not able to report
482  * the medium  change in the REQUEST  SENSE data  because of a reset or a
483  * misbehaving  bus  not  allowing  the  reposition  to  happen.  In such
484  * extraordinary  situations, where the driver fails to position the head
485  * at its  original  position,  it will fail the open the first  time, to
486  * save the applications from overwriting the data.  All further attempts
487  * to open the tape device will result in the driver  attempting  to load
488  * the  tape at BOT  (beginning  of  tape).  Also a  warning  message  to
489  * indicate  that further  attempts to open the tape device may result in
490  * the tape being  loaded at BOT will be printed on the  console.  If the
491  * tape  device is opened  in  O_NDELAY  mode,  failure  to  restore  the
492  * original tape head  position,  will result in the failure of the first
493  * tape  operation  or I/O,  Further,  the  driver  will  invalidate  its
494  * internal tape position  which will  necessitate  the  applications  to
495  * validate the position by using either a tape  positioning  ioctl (such
496  * as MTREW) or closing and reopening the tape device.
497  *
498  */
499 
500 int
501 _init(void)
502 {
503 	int e;
504 
505 	if (((e = ddi_soft_state_init(&st_state,
506 	    sizeof (struct scsi_tape), ST_MAXUNIT)) != 0)) {
507 		return (e);
508 	}
509 
510 	mutex_init(&st_attach_mutex, NULL, MUTEX_DRIVER, NULL);
511 	if ((e = mod_install(&modlinkage)) != 0) {
512 		mutex_destroy(&st_attach_mutex);
513 		ddi_soft_state_fini(&st_state);
514 	}
515 
516 	return (e);
517 }
518 
519 int
520 _fini(void)
521 {
522 	int e;
523 
524 	if ((e = mod_remove(&modlinkage)) != 0) {
525 		return (e);
526 	}
527 
528 	mutex_destroy(&st_attach_mutex);
529 	ddi_soft_state_fini(&st_state);
530 
531 	return (e);
532 }
533 
534 int
535 _info(struct modinfo *modinfop)
536 {
537 	return (mod_info(&modlinkage, modinfop));
538 }
539 
540 
541 static int
542 st_probe(dev_info_t *devi)
543 {
544 	int instance;
545 	struct scsi_device *devp;
546 	int rval;
547 
548 #if !defined(__sparc)
549 	char    *tape_prop;
550 	int	tape_prop_len;
551 #endif
552 
553 	/* If self identifying device */
554 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
555 		return (DDI_PROBE_DONTCARE);
556 	}
557 
558 #if !defined(__sparc)
559 	/*
560 	 * Since some x86 HBAs have devnodes that look like SCSI as
561 	 * far as we can tell but aren't really SCSI (DADK, like mlx)
562 	 * we check for the presence of the "tape" property.
563 	 */
564 	if (ddi_prop_op(DDI_DEV_T_NONE, devi, PROP_LEN_AND_VAL_ALLOC,
565 	    DDI_PROP_CANSLEEP, "tape",
566 	    (caddr_t)&tape_prop, &tape_prop_len) != DDI_PROP_SUCCESS) {
567 		return (DDI_PROBE_FAILURE);
568 	}
569 	if (strncmp(tape_prop, "sctp", tape_prop_len) != 0) {
570 		kmem_free(tape_prop, tape_prop_len);
571 		return (DDI_PROBE_FAILURE);
572 	}
573 	kmem_free(tape_prop, tape_prop_len);
574 #endif
575 
576 	devp = ddi_get_driver_private(devi);
577 	instance = ddi_get_instance(devi);
578 
579 	if (ddi_get_soft_state(st_state, instance) != NULL) {
580 		return (DDI_PROBE_PARTIAL);
581 	}
582 
583 
584 	/*
585 	 * Turn around and call probe routine to see whether
586 	 * we actually have a tape at this SCSI nexus.
587 	 */
588 	if (scsi_probe(devp, NULL_FUNC) == SCSIPROBE_EXISTS) {
589 
590 		/*
591 		 * In checking the whole inq_dtype byte we are looking at both
592 		 * the Peripheral Qualifier and the Peripheral Device Type.
593 		 * For this driver we are only interested in sequential devices
594 		 * that are connected or capable if connecting to this logical
595 		 * unit.
596 		 */
597 		if (devp->sd_inq->inq_dtype ==
598 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
599 			ST_DEBUG6(devi, st_label, SCSI_DEBUG,
600 			    "probe exists\n");
601 			rval = DDI_PROBE_SUCCESS;
602 		} else {
603 			rval = DDI_PROBE_FAILURE;
604 		}
605 	} else {
606 		ST_DEBUG6(devi, st_label, SCSI_DEBUG,
607 		    "probe failure: nothing there\n");
608 		rval = DDI_PROBE_FAILURE;
609 	}
610 	scsi_unprobe(devp);
611 	return (rval);
612 }
613 
614 static int
615 st_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
616 {
617 	int 	instance;
618 	int	wide;
619 	int 	dev_instance;
620 	int	ret_status;
621 	struct	scsi_device *devp;
622 	int	node_ix;
623 	struct	scsi_tape *un;
624 
625 	devp = ddi_get_driver_private(devi);
626 	instance = ddi_get_instance(devi);
627 
628 	switch (cmd) {
629 		case DDI_ATTACH:
630 			if (st_doattach(devp, SLEEP_FUNC) == DDI_FAILURE) {
631 				return (DDI_FAILURE);
632 			}
633 			break;
634 		case DDI_RESUME:
635 			/*
636 			 * Suspend/Resume
637 			 *
638 			 * When the driver suspended, there might be
639 			 * outstanding cmds and therefore we need to
640 			 * reset the suspended flag and resume the scsi
641 			 * watch thread and restart commands and timeouts
642 			 */
643 
644 			if (!(un = ddi_get_soft_state(st_state, instance))) {
645 				return (DDI_FAILURE);
646 			}
647 			dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
648 			    un->un_dev);
649 
650 			mutex_enter(ST_MUTEX);
651 
652 			un->un_throttle = un->un_max_throttle;
653 			un->un_tids_at_suspend = 0;
654 			un->un_pwr_mgmt = ST_PWR_NORMAL;
655 
656 			if (un->un_swr_token) {
657 				scsi_watch_resume(un->un_swr_token);
658 			}
659 
660 			/*
661 			 * Restart timeouts
662 			 */
663 			if ((un->un_tids_at_suspend & ST_DELAY_TID) != 0) {
664 				mutex_exit(ST_MUTEX);
665 				un->un_delay_tid =
666 				    timeout(st_delayed_cv_broadcast, un,
667 					drv_usectohz((clock_t)
668 					MEDIA_ACCESS_DELAY));
669 				mutex_enter(ST_MUTEX);
670 			}
671 
672 			if (un->un_tids_at_suspend & ST_HIB_TID) {
673 				mutex_exit(ST_MUTEX);
674 				un->un_hib_tid = timeout(st_intr_restart, un,
675 				    ST_STATUS_BUSY_TIMEOUT);
676 				mutex_enter(ST_MUTEX);
677 			}
678 
679 			ret_status = st_clear_unit_attentions(dev_instance, 5);
680 
681 			/*
682 			 * now check if we need to restore the tape position
683 			 */
684 			if ((un->un_suspend_fileno > 0) ||
685 			    (un->un_suspend_blkno > 0)) {
686 				if (ret_status != 0) {
687 					/*
688 					 * tape didn't get good TUR
689 					 * just print out error messages
690 					 */
691 					scsi_log(ST_DEVINFO, st_label, CE_WARN,
692 					    "st_attach-RESUME: tape failure "
693 					    " tape position will be lost");
694 				} else {
695 					/* this prints errors */
696 					(void) st_validate_tapemarks(un,
697 					    un->un_suspend_fileno,
698 					    un->un_suspend_blkno);
699 				}
700 				/*
701 				 * there are no retries, if there is an error
702 				 * we don't know if the tape has changed
703 				 */
704 				un->un_suspend_fileno = 0;
705 				un->un_suspend_blkno = 0;
706 			}
707 
708 			/* now we are ready to start up any queued I/Os */
709 			if (un->un_ncmds || un->un_quef) {
710 				st_start(un);
711 			}
712 
713 			cv_broadcast(&un->un_suspend_cv);
714 			mutex_exit(ST_MUTEX);
715 			return (DDI_SUCCESS);
716 
717 		default:
718 			return (DDI_FAILURE);
719 	}
720 
721 	un = ddi_get_soft_state(st_state, instance);
722 
723 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
724 	    "st_attach: instance=%x\n", instance);
725 
726 	/*
727 	 * find the drive type for this target
728 	 */
729 	st_known_tape_type(un);
730 
731 	for (node_ix = 0; node_ix < ST_NUM_MEMBERS(st_minor_data); node_ix++) {
732 		int minor;
733 		char *name;
734 
735 		name  = st_minor_data[node_ix].name;
736 		minor = st_minor_data[node_ix].minor;
737 
738 		/*
739 		 * For default devices set the density to the
740 		 * preferred default density for this device.
741 		 */
742 		if (node_ix <= DEF_BSD_NR) {
743 			minor |= un->un_dp->default_density;
744 		}
745 		minor |= MTMINOR(instance);
746 
747 		if (ddi_create_minor_node(devi, name, S_IFCHR, minor,
748 		    DDI_NT_TAPE, NULL) == DDI_SUCCESS) {
749 			continue;
750 		}
751 
752 		ddi_remove_minor_node(devi, NULL);
753 		if (un) {
754 			cv_destroy(&un->un_clscv);
755 			cv_destroy(&un->un_sbuf_cv);
756 			cv_destroy(&un->un_queue_cv);
757 			cv_destroy(&un->un_state_cv);
758 			cv_destroy(&un->un_suspend_cv);
759 			cv_destroy(&un->un_tape_busy_cv);
760 
761 			if (un->un_sbufp) {
762 				freerbuf(un->un_sbufp);
763 			}
764 			if (un->un_uscsi_rqs_buf) {
765 				kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
766 			}
767 			if (un->un_mspl) {
768 				ddi_iopb_free((caddr_t)un->un_mspl);
769 			}
770 			scsi_destroy_pkt(un->un_rqs);
771 			scsi_free_consistent_buf(un->un_rqs_bp);
772 			ddi_soft_state_free(st_state, instance);
773 			devp->sd_private = NULL;
774 			devp->sd_sense = NULL;
775 
776 		}
777 		ddi_prop_remove_all(devi);
778 		return (DDI_FAILURE);
779 	}
780 
781 	/*
782 	 * Add a zero-length attribute to tell the world we support
783 	 * kernel ioctls (for layered drivers)
784 	 */
785 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
786 	    DDI_KERNEL_IOCTL, NULL, 0);
787 
788 	ddi_report_dev((dev_info_t *)devi);
789 
790 	/*
791 	 * If it's a SCSI-2 tape drive which supports wide,
792 	 * tell the host adapter to use wide.
793 	 */
794 	wide = ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
795 	    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) ?
796 		1 : 0;
797 
798 	if (scsi_ifsetcap(ROUTE, "wide-xfer", wide, 1) == 1) {
799 		ST_DEBUG(devi, st_label, SCSI_DEBUG,
800 		    "Wide Transfer %s\n", wide ? "enabled" : "disabled");
801 	}
802 
803 	/*
804 	 * enable autorequest sense; keep the rq packet around in case
805 	 * the autorequest sense fails because of a busy condition
806 	 * do a getcap first in case the capability is not variable
807 	 */
808 	if (scsi_ifgetcap(ROUTE, "auto-rqsense", 1) == 1) {
809 		un->un_arq_enabled = 1;
810 	} else {
811 		un->un_arq_enabled =
812 		    ((scsi_ifsetcap(ROUTE, "auto-rqsense", 1, 1) == 1) ? 1 : 0);
813 	}
814 
815 
816 	ST_DEBUG(devi, st_label, SCSI_DEBUG, "auto request sense %s\n",
817 		(un->un_arq_enabled ? "enabled" : "disabled"));
818 
819 	un->un_untagged_qing =
820 	    (scsi_ifgetcap(ROUTE, "untagged-qing", 0) == 1);
821 
822 	/*
823 	 * XXX - This is just for 2.6.  to tell users that write buffering
824 	 *	has gone away.
825 	 */
826 	if (un->un_arq_enabled && un->un_untagged_qing) {
827 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
828 		    "tape-driver-buffering", 0) != 0) {
829 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
830 			    "Write Data Buffering has been depricated. Your "
831 			    "applications should continue to work normally.\n"
832 			    " But, they should  ported to use Asynchronous "
833 			    " I/O\n"
834 			    " For more information, read about "
835 			    " tape-driver-buffering "
836 			    "property in the st(7d) man page\n");
837 		}
838 	}
839 
840 	un->un_max_throttle = un->un_throttle = un->un_last_throttle = 1;
841 	un->un_flush_on_errors = 0;
842 	un->un_mkr_pkt = (struct scsi_pkt *)NULL;
843 
844 	ST_DEBUG(devi, st_label, SCSI_DEBUG,
845 	    "throttle=%x, max_throttle = %x\n",
846 	    un->un_throttle, un->un_max_throttle);
847 
848 	/* initialize persistent errors to nil */
849 	un->un_persistence = 0;
850 	un->un_persist_errors = 0;
851 
852 	/*
853 	 * Get dma-max from HBA driver. If it is not defined, use 64k
854 	 */
855 	un->un_maxdma	= scsi_ifgetcap(&devp->sd_address, "dma-max", 1);
856 	if (un->un_maxdma == -1) {
857 		un->un_maxdma = (64 * 1024);
858 	}
859 
860 	un->un_maxbsize = MAXBSIZE_UNKNOWN;
861 
862 	un->un_mediastate = MTIO_NONE;
863 	un->un_HeadClean  = TAPE_ALERT_SUPPORT_UNKNOWN;
864 
865 	/*
866 	 * initialize kstats
867 	 */
868 	un->un_stats = kstat_create("st", instance, NULL, "tape",
869 			KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
870 	if (un->un_stats) {
871 		un->un_stats->ks_lock = ST_MUTEX;
872 		kstat_install(un->un_stats);
873 	}
874 	(void) st_create_errstats(un, instance);
875 
876 	return (DDI_SUCCESS);
877 }
878 
879 /*
880  * st_detach:
881  *
882  * we allow a detach if and only if:
883  *	- no tape is currently inserted
884  *	- tape position is at BOT or unknown
885  *		(if it is not at BOT then a no rewind
886  *		device was opened and we have to preserve state)
887  *	- it must be in a closed state : no timeouts or scsi_watch requests
888  *		will exist if it is closed, so we don't need to check for
889  *		them here.
890  */
891 /*ARGSUSED*/
892 static int
893 st_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
894 {
895 	int 	instance;
896 	int 	dev_instance;
897 	struct scsi_device *devp;
898 	struct scsi_tape *un;
899 	clock_t wait_cmds_complete;
900 
901 	instance = ddi_get_instance(devi);
902 
903 	if (!(un = ddi_get_soft_state(st_state, instance))) {
904 		return (DDI_FAILURE);
905 	}
906 
907 	switch (cmd) {
908 
909 	case DDI_DETACH:
910 		/*
911 		 * Undo what we did in st_attach & st_doattach,
912 		 * freeing resources and removing things we installed.
913 		 * The system framework guarantees we are not active
914 		 * with this devinfo node in any other entry points at
915 		 * this time.
916 		 */
917 
918 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
919 		    "st_detach: instance=%x, un=%p\n", instance,
920 		    (void *)un);
921 
922 		if (((un->un_dp->options & ST_UNLOADABLE) == 0) ||
923 		    (un->un_ncmds != 0) || (un->un_quef != NULL) ||
924 		    (un->un_state != ST_STATE_CLOSED)) {
925 			/*
926 			 * we cannot unload some targets because the
927 			 * inquiry returns junk unless immediately
928 			 * after a reset
929 			 */
930 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
931 			    "cannot unload instance %x\n", instance);
932 			return (DDI_FAILURE);
933 		}
934 
935 		/*
936 		 * if the tape has been removed then we may unload;
937 		 * do a test unit ready and if it returns NOT READY
938 		 * then we assume that it is safe to unload.
939 		 * as a side effect, fileno may be set to -1 if the
940 		 * the test unit ready fails;
941 		 * also un_state may be set to non-closed, so reset it
942 		 */
943 		if ((un->un_dev) &&		/* Been opened since attach */
944 		    ((un->un_fileno > 0) ||	/* Known position not rewound */
945 		    (un->un_blkno != 0))) {	/* Or within first file */
946 			mutex_enter(ST_MUTEX);
947 			/*
948 			 * Send Test Unit Ready in the hopes that if
949 			 * the drive is not in the state we think it is.
950 			 * And the state will be changed so it can be detached.
951 			 * If the command fails to reach the device and
952 			 * the drive was not rewound or unloaded we want
953 			 * to fail the detach till a user command fails
954 			 * where after the detach will succead.
955 			 */
956 			(void) st_cmd(un->un_dev, SCMD_TEST_UNIT_READY,
957 			    0, SYNC_CMD);
958 			/*
959 			 * After TUR un_state may be set to non-closed,
960 			 * so reset it back.
961 			 */
962 			un->un_state = ST_STATE_CLOSED;
963 			mutex_exit(ST_MUTEX);
964 		}
965 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
966 		    "un_status=%x, fileno=%x, blkno=%lx\n",
967 		    un->un_status, un->un_fileno, un->un_blkno);
968 
969 		/*
970 		 * check again:
971 		 * if we are not at BOT then it is not safe to unload
972 		 */
973 		if ((un->un_dev) &&		/* Been opened since attach */
974 		    ((un->un_fileno > 0) ||	/* Known position not rewound */
975 		    (un->un_blkno != 0))) {	/* Or within first file */
976 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
977 			    "cannot detach: fileno=%x, blkno=%lx\n",
978 			    un->un_fileno, un->un_blkno);
979 			return (DDI_FAILURE);
980 		}
981 
982 		/*
983 		 * Just To make sure that we have released the
984 		 * tape unit .
985 		 */
986 		if (un->un_dev && (un->un_rsvd_status & ST_RESERVE) &&
987 		    !DEVI_IS_DEVICE_REMOVED(devi)) {
988 			mutex_enter(ST_MUTEX);
989 			(void) st_cmd(un->un_dev, SCMD_RELEASE, 0, SYNC_CMD);
990 			mutex_exit(ST_MUTEX);
991 		}
992 
993 		/*
994 		 * now remove other data structures allocated in st_doattach()
995 		 */
996 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
997 		    "destroying/freeing\n");
998 		cv_destroy(&un->un_clscv);
999 		cv_destroy(&un->un_sbuf_cv);
1000 		cv_destroy(&un->un_queue_cv);
1001 		cv_destroy(&un->un_suspend_cv);
1002 		cv_destroy(&un->un_tape_busy_cv);
1003 
1004 		if (un->un_hib_tid) {
1005 			(void) untimeout(un->un_hib_tid);
1006 			un->un_hib_tid = 0;
1007 		}
1008 
1009 		if (un->un_delay_tid) {
1010 			(void) untimeout(un->un_delay_tid);
1011 			un->un_delay_tid = 0;
1012 		}
1013 		cv_destroy(&un->un_state_cv);
1014 
1015 #if defined(__i386) || defined(__amd64)
1016 		if (un->un_contig_mem_hdl != NULL) {
1017 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1018 		}
1019 #endif
1020 		if (un->un_sbufp) {
1021 			freerbuf(un->un_sbufp);
1022 		}
1023 		if (un->un_uscsi_rqs_buf) {
1024 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1025 		}
1026 		if (un->un_mspl) {
1027 			ddi_iopb_free((caddr_t)un->un_mspl);
1028 		}
1029 		if (un->un_rqs) {
1030 			scsi_destroy_pkt(un->un_rqs);
1031 			scsi_free_consistent_buf(un->un_rqs_bp);
1032 		}
1033 		if (un->un_mkr_pkt) {
1034 			scsi_destroy_pkt(un->un_mkr_pkt);
1035 		}
1036 		if (un->un_arq_enabled) {
1037 			(void) scsi_ifsetcap(ROUTE, "auto-rqsense", 0, 1);
1038 		}
1039 		if (un->un_dp_size) {
1040 			kmem_free(un->un_dp, un->un_dp_size);
1041 		}
1042 		if (un->un_stats) {
1043 			kstat_delete(un->un_stats);
1044 			un->un_stats = (kstat_t *)0;
1045 		}
1046 		if (un->un_errstats) {
1047 			kstat_delete(un->un_errstats);
1048 			un->un_errstats = (kstat_t *)0;
1049 		}
1050 		devp = ST_SCSI_DEVP;
1051 		ddi_soft_state_free(st_state, instance);
1052 		devp->sd_private = NULL;
1053 		devp->sd_sense = NULL;
1054 		scsi_unprobe(devp);
1055 		ddi_prop_remove_all(devi);
1056 		ddi_remove_minor_node(devi, NULL);
1057 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach done\n");
1058 		return (DDI_SUCCESS);
1059 
1060 	case DDI_SUSPEND:
1061 
1062 		/*
1063 		 * Suspend/Resume
1064 		 *
1065 		 * To process DDI_SUSPEND, we must do the following:
1066 		 *
1067 		 *  - check ddi_removing_power to see if power will be turned
1068 		 *    off. if so, return DDI_FAILURE
1069 		 *  - check if we are already suspended,
1070 		 *    if so, return DDI_FAILURE
1071 		 *  - check if device state is CLOSED,
1072 		 *    if not, return DDI_FAILURE.
1073 		 *  - wait until outstanding operations complete
1074 		 *  - save tape state
1075 		 *  - block new operations
1076 		 *  - cancel pending timeouts
1077 		 *
1078 		 */
1079 
1080 		if (ddi_removing_power(devi))
1081 			return (DDI_FAILURE);
1082 
1083 		mutex_enter(ST_MUTEX);
1084 
1085 		/*
1086 		 * Shouldn't already be suspended, if so return failure
1087 		 */
1088 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
1089 			mutex_exit(ST_MUTEX);
1090 			return (DDI_FAILURE);
1091 		}
1092 		if (un->un_state != ST_STATE_CLOSED) {
1093 			mutex_exit(ST_MUTEX);
1094 			return (DDI_FAILURE);
1095 		}
1096 
1097 		/*
1098 		 * Wait for all outstanding I/O's to complete
1099 		 *
1100 		 * we wait on both ncmds and the wait queue for times
1101 		 * when we are flushing after persistent errors are
1102 		 * flagged, which is when ncmds can be 0, and the
1103 		 * queue can still have I/O's.  This way we preserve
1104 		 * order of biodone's.
1105 		 */
1106 		wait_cmds_complete = ddi_get_lbolt();
1107 		wait_cmds_complete +=
1108 		    st_wait_cmds_complete * drv_usectohz(1000000);
1109 		while (un->un_ncmds || un->un_quef ||
1110 		    (un->un_state == ST_STATE_RESOURCE_WAIT)) {
1111 
1112 			if (cv_timedwait(&un->un_tape_busy_cv, ST_MUTEX,
1113 			    wait_cmds_complete) == -1) {
1114 				/*
1115 				 * Time expired then cancel the command
1116 				 */
1117 				mutex_exit(ST_MUTEX);
1118 				if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
1119 					mutex_enter(ST_MUTEX);
1120 					if (un->un_last_throttle) {
1121 						un->un_throttle =
1122 						    un->un_last_throttle;
1123 					}
1124 					mutex_exit(ST_MUTEX);
1125 					return (DDI_FAILURE);
1126 				} else {
1127 					mutex_enter(ST_MUTEX);
1128 					break;
1129 				}
1130 			}
1131 		}
1132 
1133 		/*
1134 		 * DDI_SUSPEND says that the system "may" power down, we
1135 		 * remember the file and block number before rewinding.
1136 		 * we also need to save state before issuing
1137 		 * any WRITE_FILE_MARK command.
1138 		 */
1139 		if (un->un_fileno < 0) {
1140 			un->un_suspend_fileno = 0;
1141 			un->un_suspend_blkno  = 0;
1142 		} else {
1143 			un->un_suspend_fileno = un->un_fileno;
1144 			un->un_suspend_blkno = un->un_blkno;
1145 		}
1146 		dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
1147 		    un->un_dev);
1148 
1149 		/*
1150 		 * Issue a zero write file fmk command to tell the drive to
1151 		 * flush any buffered tape marks
1152 		 */
1153 		(void) st_cmd(dev_instance, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
1154 
1155 		/*
1156 		 * Because not all tape drives correctly implement buffer
1157 		 * flushing with the zero write file fmk command, issue a
1158 		 * synchronous rewind command to force data flushing.
1159 		 * st_validate_tapemarks() will do a rewind during DDI_RESUME
1160 		 * anyway.
1161 		 */
1162 		(void) st_cmd(dev_instance, SCMD_REWIND, 0, SYNC_CMD);
1163 
1164 		/* stop any new operations */
1165 		un->un_pwr_mgmt = ST_PWR_SUSPENDED;
1166 		un->un_throttle = 0;
1167 
1168 		/*
1169 		 * cancel any outstanding timeouts
1170 		 */
1171 		if (un->un_delay_tid) {
1172 			timeout_id_t temp_id = un->un_delay_tid;
1173 			un->un_delay_tid = 0;
1174 			un->un_tids_at_suspend |= ST_DELAY_TID;
1175 			mutex_exit(ST_MUTEX);
1176 			(void) untimeout(temp_id);
1177 			mutex_enter(ST_MUTEX);
1178 		}
1179 
1180 		if (un->un_hib_tid) {
1181 			timeout_id_t temp_id = un->un_hib_tid;
1182 			un->un_hib_tid = 0;
1183 			un->un_tids_at_suspend |= ST_HIB_TID;
1184 			mutex_exit(ST_MUTEX);
1185 			(void) untimeout(temp_id);
1186 			mutex_enter(ST_MUTEX);
1187 		}
1188 
1189 		/*
1190 		 * Suspend the scsi_watch_thread
1191 		 */
1192 		if (un->un_swr_token) {
1193 			opaque_t temp_token = un->un_swr_token;
1194 			mutex_exit(ST_MUTEX);
1195 			scsi_watch_suspend(temp_token);
1196 		} else {
1197 			mutex_exit(ST_MUTEX);
1198 		}
1199 
1200 		return (DDI_SUCCESS);
1201 
1202 	default:
1203 		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach failed\n");
1204 		return (DDI_FAILURE);
1205 	}
1206 }
1207 
1208 
1209 /* ARGSUSED */
1210 static int
1211 stinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1212 {
1213 	dev_t dev;
1214 	struct scsi_tape *un;
1215 	int instance, error;
1216 	switch (infocmd) {
1217 	case DDI_INFO_DEVT2DEVINFO:
1218 		dev = (dev_t)arg;
1219 		instance = MTUNIT(dev);
1220 		if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
1221 			return (DDI_FAILURE);
1222 		*result = (void *) ST_DEVINFO;
1223 		error = DDI_SUCCESS;
1224 		break;
1225 	case DDI_INFO_DEVT2INSTANCE:
1226 		dev = (dev_t)arg;
1227 		instance = MTUNIT(dev);
1228 		*result = (void *)(uintptr_t)instance;
1229 		error = DDI_SUCCESS;
1230 		break;
1231 	default:
1232 		error = DDI_FAILURE;
1233 	}
1234 	return (error);
1235 }
1236 
1237 static int
1238 st_doattach(struct scsi_device *devp, int (*canwait)())
1239 {
1240 	struct scsi_pkt *rqpkt = NULL;
1241 	struct scsi_tape *un = NULL;
1242 	int km_flags = (canwait != NULL_FUNC) ? KM_SLEEP : KM_NOSLEEP;
1243 	int instance;
1244 	struct buf *bp;
1245 
1246 	/*
1247 	 * Call the routine scsi_probe to do some of the dirty work.
1248 	 * If the INQUIRY command succeeds, the field sd_inq in the
1249 	 * device structure will be filled in.
1250 	 */
1251 	ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1252 		"st_doattach(): probing\n");
1253 
1254 	if (scsi_probe(devp, canwait) == SCSIPROBE_EXISTS) {
1255 
1256 		/*
1257 		 * In checking the whole inq_dtype byte we are looking at both
1258 		 * the Peripheral Qualifier and the Peripheral Device Type.
1259 		 * For this driver we are only interested in sequential devices
1260 		 * that are connected or capable if connecting to this logical
1261 		 * unit.
1262 		 */
1263 		if (devp->sd_inq->inq_dtype ==
1264 		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
1265 			ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1266 			    "probe exists\n");
1267 		} else {
1268 			/* Something there but not a tape device */
1269 			scsi_unprobe(devp);
1270 			return (DDI_FAILURE);
1271 		}
1272 	} else {
1273 		/* Nothing there */
1274 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1275 		    "probe failure: nothing there\n");
1276 		scsi_unprobe(devp);
1277 		return (DDI_FAILURE);
1278 	}
1279 
1280 	bp = scsi_alloc_consistent_buf(&devp->sd_address, (struct buf *)NULL,
1281 	    SENSE_LENGTH, B_READ, canwait, NULL);
1282 	if (!bp) {
1283 		goto error;
1284 	}
1285 	rqpkt = scsi_init_pkt(&devp->sd_address,
1286 	    (struct scsi_pkt *)NULL, bp, CDB_GROUP0, 1, 0,
1287 	    PKT_CONSISTENT, canwait, NULL);
1288 	if (!rqpkt) {
1289 		goto error;
1290 	}
1291 	devp->sd_sense = (struct scsi_extended_sense *)bp->b_un.b_addr;
1292 	ASSERT(geterror(bp) == NULL);
1293 
1294 	(void) scsi_setup_cdb((union scsi_cdb *)rqpkt->pkt_cdbp,
1295 	    SCMD_REQUEST_SENSE, 0, SENSE_LENGTH, 0);
1296 	FILL_SCSI1_LUN(devp, rqpkt);
1297 
1298 	/*
1299 	 * The actual unit is present.
1300 	 * Now is the time to fill in the rest of our info..
1301 	 */
1302 	instance = ddi_get_instance(devp->sd_dev);
1303 
1304 	if (ddi_soft_state_zalloc(st_state, instance) != DDI_SUCCESS) {
1305 		goto error;
1306 	}
1307 	un = ddi_get_soft_state(st_state, instance);
1308 
1309 	un->un_sbufp = getrbuf(km_flags);
1310 
1311 	un->un_uscsi_rqs_buf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
1312 
1313 	(void) ddi_iopb_alloc(devp->sd_dev, (ddi_dma_lim_t *)0,
1314 		sizeof (struct seq_mode), (caddr_t *)&un->un_mspl);
1315 
1316 	if (!un->un_sbufp || !un->un_mspl) {
1317 		if (un->un_mspl) {
1318 			ddi_iopb_free((caddr_t)un->un_mspl);
1319 		}
1320 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1321 		    "probe partial failure: no space\n");
1322 		goto error;
1323 	}
1324 
1325 	bzero(un->un_mspl, sizeof (struct seq_mode));
1326 
1327 	cv_init(&un->un_sbuf_cv, NULL, CV_DRIVER, NULL);
1328 	cv_init(&un->un_queue_cv, NULL, CV_DRIVER, NULL);
1329 	cv_init(&un->un_clscv, NULL, CV_DRIVER, NULL);
1330 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
1331 #if defined(__i386) || defined(__amd64)
1332 	cv_init(&un->un_contig_mem_cv, NULL, CV_DRIVER, NULL);
1333 #endif
1334 
1335 	/* Initialize power managemnet condition variable */
1336 	cv_init(&un->un_suspend_cv, NULL, CV_DRIVER, NULL);
1337 	cv_init(&un->un_tape_busy_cv, NULL, CV_DRIVER, NULL);
1338 
1339 	rqpkt->pkt_flags |= (FLAG_SENSING | FLAG_HEAD | FLAG_NODISCON);
1340 
1341 	un->un_fileno	= -1;
1342 	rqpkt->pkt_time = st_io_time;
1343 	rqpkt->pkt_comp = st_intr;
1344 	un->un_rqs	= rqpkt;
1345 	un->un_sd	= devp;
1346 	un->un_rqs_bp	= bp;
1347 	un->un_swr_token = (opaque_t)NULL;
1348 	un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
1349 
1350 	un->un_suspend_fileno 	= 0;
1351 	un->un_suspend_blkno 	= 0;
1352 
1353 #if defined(__i386) || defined(__amd64)
1354 	if (ddi_dma_alloc_handle(ST_DEVINFO, &st_contig_mem_dma_attr,
1355 		DDI_DMA_SLEEP, NULL, &un->un_contig_mem_hdl) != DDI_SUCCESS) {
1356 		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1357 		    "allocation of contiguous memory dma handle failed!");
1358 		un->un_contig_mem_hdl = NULL;
1359 		goto error;
1360 	}
1361 #endif
1362 
1363 	/*
1364 	 * Since this driver manages devices with "remote" hardware,
1365 	 * i.e. the devices themselves have no "reg" properties,
1366 	 * the SUSPEND/RESUME commands in detach/attach will not be
1367 	 * called by the power management framework unless we request
1368 	 * it by creating a "pm-hardware-state" property and setting it
1369 	 * to value "needs-suspend-resume".
1370 	 */
1371 	if (ddi_prop_update_string(DDI_DEV_T_NONE, devp->sd_dev,
1372 	    "pm-hardware-state", "needs-suspend-resume") !=
1373 	    DDI_PROP_SUCCESS) {
1374 
1375 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1376 		    "ddi_prop_update(\"pm-hardware-state\") failed\n");
1377 		goto error;
1378 	}
1379 
1380 	if (ddi_prop_create(DDI_DEV_T_NONE, devp->sd_dev, DDI_PROP_CANSLEEP,
1381 	    "no-involuntary-power-cycles", NULL, 0) != DDI_PROP_SUCCESS) {
1382 
1383 		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1384 		    "ddi_prop_create(\"no-involuntary-power-cycles\") "
1385 		    "failed\n");
1386 		goto error;
1387 	}
1388 
1389 	ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG, "probe success\n");
1390 	return (DDI_SUCCESS);
1391 
1392 error:
1393 	devp->sd_sense = NULL;
1394 
1395 	ddi_remove_minor_node(devp->sd_dev, NULL);
1396 	if (un) {
1397 		if (un->un_mspl) {
1398 			ddi_iopb_free((caddr_t)un->un_mspl);
1399 		}
1400 		if (un->un_sbufp) {
1401 			freerbuf(un->un_sbufp);
1402 		}
1403 		if (un->un_uscsi_rqs_buf) {
1404 			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1405 		}
1406 #if defined(__i386) || defined(__amd64)
1407 		if (un->un_contig_mem_hdl != NULL) {
1408 			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1409 		}
1410 #endif
1411 		ddi_soft_state_free(st_state, instance);
1412 		devp->sd_private = NULL;
1413 	}
1414 
1415 	if (rqpkt) {
1416 		scsi_destroy_pkt(rqpkt);
1417 	}
1418 
1419 	if (bp) {
1420 		scsi_free_consistent_buf(bp);
1421 	}
1422 
1423 	if (devp->sd_inq) {
1424 		scsi_unprobe(devp);
1425 	}
1426 	return (DDI_FAILURE);
1427 }
1428 
1429 typedef int
1430 (*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1431 
1432 static cfg_functp config_functs[] = {
1433 	st_get_conf_from_st_dot_conf,
1434 	st_get_conf_from_st_conf_dot_c,
1435 	st_get_default_conf
1436 };
1437 
1438 
1439 /*
1440  * determine tape type, using tape-config-list or built-in table or
1441  * use a generic tape config entry
1442  */
1443 static void
1444 st_known_tape_type(struct scsi_tape *un)
1445 {
1446 	struct st_drivetype *dp;
1447 	cfg_functp *config_funct;
1448 
1449 	/*
1450 	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1451 	 *	 no vid & pid inquiry data.  So, we provide one.
1452 	 */
1453 	if (ST_INQUIRY->inq_len == 0 ||
1454 		(bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1455 		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1456 	}
1457 
1458 	un->un_dp_size = sizeof (struct st_drivetype);
1459 	dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1460 	un->un_dp = dp;
1461 
1462 	/*
1463 	 * Loop through the configuration methods till one works.
1464 	 */
1465 	for (config_funct = &config_functs[0]; ; config_funct++) {
1466 		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1467 			break;
1468 		}
1469 	}
1470 
1471 	/*
1472 	 * If we didn't just make up this configuration and
1473 	 * all the density codes are the same..
1474 	 * Set Auto Density over ride.
1475 	 */
1476 	if (*config_funct != st_get_default_conf) {
1477 		/*
1478 		 * If this device is one that is configured and all
1479 		 * densities are the same, This saves doing gets and set
1480 		 * that yield nothing.
1481 		 */
1482 		if ((dp->densities[0]) == (dp->densities[1]) &&
1483 		    (dp->densities[0]) == (dp->densities[2]) &&
1484 		    (dp->densities[0]) == (dp->densities[3])) {
1485 
1486 			dp->options |= ST_AUTODEN_OVERRIDE;
1487 		}
1488 	}
1489 
1490 
1491 	/*
1492 	 * Store tape drive characteristics.
1493 	 */
1494 	un->un_status = 0;
1495 	un->un_attached = 1;
1496 	un->un_init_options = dp->options;
1497 
1498 	/* setup operation time-outs based on options */
1499 	st_calculate_timeouts(un);
1500 
1501 	/* make sure if we are supposed to be variable, make it variable */
1502 	if (dp->options & ST_VARIABLE) {
1503 		dp->bsize = 0;
1504 	}
1505 
1506 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1507 }
1508 
1509 
1510 typedef struct {
1511 	int mask;
1512 	int bottom;
1513 	int top;
1514 	char *name;
1515 } conf_limit;
1516 
1517 static const conf_limit conf_limits[] = {
1518 
1519 	-1,		1,		2,		"conf version",
1520 	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1521 	-1,		0,		0xffffff,	"block size",
1522 	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1523 	-1,		0,		4,		"number of densities",
1524 	-1,		0,		UINT8_MAX,	"density code",
1525 	-1,		0,		3,		"default density",
1526 	-1,		0,		UINT16_MAX,	"non motion timeout",
1527 	-1,		0,		UINT16_MAX,	"I/O timeout",
1528 	-1,		0,		UINT16_MAX,	"space timeout",
1529 	-1,		0,		UINT16_MAX,	"load timeout",
1530 	-1,		0,		UINT16_MAX,	"unload timeout",
1531 	-1,		0,		UINT16_MAX,	"erase timeout",
1532 	0,		0,		0,		NULL
1533 };
1534 
1535 static int
1536 st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1537     const char *conf_name)
1538 {
1539 	int dens;
1540 	int ndens;
1541 	int value;
1542 	int type;
1543 	int count;
1544 	const conf_limit *limit = &conf_limits[0];
1545 
1546 	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
1547 	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
1548 
1549 	count = list_len;
1550 	type = *list;
1551 	for (;  count && limit->name; count--, list++, limit++) {
1552 
1553 		value = *list;
1554 		if (value & ~limit->mask) {
1555 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1556 			    "%s %s value invalid bits set: 0x%X\n",
1557 			    conf_name, limit->name, value & ~limit->mask);
1558 			*list &= limit->mask;
1559 		} else if (value < limit->bottom) {
1560 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1561 			    "%s %s value too low: value = %d limit %d\n",
1562 			    conf_name, limit->name, value, limit->bottom);
1563 		} else if (value > limit->top) {
1564 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1565 			    "%s %s value too high: value = %d limit %d\n",
1566 			    conf_name, limit->name, value, limit->top);
1567 		} else {
1568 			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1569 			    "%s %s value = 0x%X\n",
1570 			    conf_name, limit->name, value);
1571 		}
1572 
1573 		/* If not the number of densities continue */
1574 		if (limit != &conf_limits[4]) {
1575 			continue;
1576 		}
1577 
1578 		/* If number of densities is not in range can't use config */
1579 		if (value < limit->bottom || value > limit->top) {
1580 			return (-1);
1581 		}
1582 
1583 		ndens = min(value, NDENSITIES);
1584 		if ((type == 1) && (list_len - ndens) != 6) {
1585 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1586 			    "%s conf version 1 with %d densities has %d items"
1587 			    " should have %d",
1588 			    conf_name, ndens, list_len, 6 + ndens);
1589 		} else if ((type == 2) && (list_len - ndens) != 13) {
1590 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1591 			    "%s conf version 2 with %d densities has %d items"
1592 			    " should have %d",
1593 			    conf_name, ndens, list_len, 13 + ndens);
1594 		}
1595 
1596 		limit++;
1597 		for (dens = 0; dens < ndens && count; dens++) {
1598 			count--;
1599 			list++;
1600 			value = *list;
1601 			if (value < limit->bottom) {
1602 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1603 				    "%s density[%d] value too low: value ="
1604 				    " 0x%X limit 0x%X\n",
1605 				    conf_name, dens, value, limit->bottom);
1606 			} else if (value > limit->top) {
1607 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1608 				    "%s density[%d] value too high: value ="
1609 				    " 0x%X limit 0x%X\n",
1610 				    conf_name, dens, value, limit->top);
1611 			} else {
1612 				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
1613 				    "%s density[%d] value = 0x%X\n",
1614 				    conf_name, dens, value);
1615 			}
1616 		}
1617 	}
1618 
1619 	return (0);
1620 }
1621 
1622 static int
1623 st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
1624     struct st_drivetype *dp)
1625 {
1626 	caddr_t config_list = NULL;
1627 	caddr_t data_list = NULL;
1628 	int	*data_ptr;
1629 	caddr_t vidptr, prettyptr, datanameptr;
1630 	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
1631 	int config_list_len, data_list_len, len, i;
1632 	int version;
1633 	int found = 0;
1634 
1635 
1636 	/*
1637 	 * Determine type of tape controller. Type is determined by
1638 	 * checking the vendor ids of the earlier inquiry command and
1639 	 * comparing those with vids in tape-config-list defined in st.conf
1640 	 */
1641 	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
1642 	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
1643 	    != DDI_PROP_SUCCESS) {
1644 		return (found);
1645 	}
1646 
1647 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
1648 	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
1649 
1650 	/*
1651 	 * Compare vids in each triplet - if it matches, get value for
1652 	 * data_name and contruct a st_drivetype struct
1653 	 * tripletlen is not set yet!
1654 	 */
1655 	for (len = config_list_len, vidptr = config_list;
1656 	    len > 0;
1657 	    vidptr += tripletlen, len -= tripletlen) {
1658 
1659 		vidlen = strlen(vidptr);
1660 		prettyptr = vidptr + vidlen + 1;
1661 		prettylen = strlen(prettyptr);
1662 		datanameptr = prettyptr + prettylen + 1;
1663 		datanamelen = strlen(datanameptr);
1664 		tripletlen = vidlen + prettylen + datanamelen + 3;
1665 
1666 		if (vidlen == 0) {
1667 			continue;
1668 		}
1669 
1670 		/*
1671 		 * If inquiry vid dosen't match this triplets vid,
1672 		 * try the next.
1673 		 */
1674 		if (strncasecmp(vidpid, vidptr, vidlen)) {
1675 			continue;
1676 		}
1677 
1678 		/*
1679 		 * if prettylen is zero then use the vid string
1680 		 */
1681 		if (prettylen == 0) {
1682 			prettyptr = vidptr;
1683 			prettylen = vidlen;
1684 		}
1685 
1686 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1687 		    "vid = %s, pretty=%s, dataname = %s\n",
1688 		    vidptr, prettyptr, datanameptr);
1689 
1690 		/*
1691 		 * get the data list
1692 		 */
1693 		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
1694 		    datanameptr, (caddr_t)&data_list,
1695 		    &data_list_len) != DDI_PROP_SUCCESS) {
1696 			/*
1697 			 * Error in getting property value
1698 			 * print warning!
1699 			 */
1700 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1701 			    "data property (%s) has no value\n",
1702 			    datanameptr);
1703 			continue;
1704 		}
1705 
1706 		/*
1707 		 * now initialize the st_drivetype struct
1708 		 */
1709 		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
1710 		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
1711 		(void) strncpy(dp->vid, vidptr, dp->length);
1712 		data_ptr = (int *)data_list;
1713 		/*
1714 		 * check if data is enough for version, type,
1715 		 * bsize, options, # of densities, density1,
1716 		 * density2, ..., default_density
1717 		 */
1718 		if ((data_list_len < 5 * sizeof (int)) ||
1719 		    (data_list_len < 6 * sizeof (int) +
1720 		    *(data_ptr + 4) * sizeof (int))) {
1721 			/*
1722 			 * print warning and skip to next triplet.
1723 			 */
1724 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1725 			    "data property (%s) incomplete\n",
1726 			    datanameptr);
1727 			kmem_free(data_list, data_list_len);
1728 			continue;
1729 		}
1730 
1731 		if (st_validate_conf_data(un, data_ptr,
1732 		    data_list_len / sizeof (int), datanameptr)) {
1733 			kmem_free(data_list, data_list_len);
1734 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1735 			    "data property (%s) rejected\n",
1736 			    datanameptr);
1737 			continue;
1738 		}
1739 
1740 		/*
1741 		 * check version
1742 		 */
1743 		version = *data_ptr++;
1744 		if (version != 1 && version != 2) {
1745 			/* print warning but accept it */
1746 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
1747 			    "Version # for data property (%s) "
1748 			    "not set to 1 or 2\n", datanameptr);
1749 		}
1750 
1751 		dp->type    = *data_ptr++;
1752 		dp->bsize   = *data_ptr++;
1753 		dp->options = *data_ptr++;
1754 		dp->options |= ST_DYNAMIC;
1755 		len = *data_ptr++;
1756 		for (i = 0; i < NDENSITIES; i++) {
1757 			if (i < len) {
1758 				dp->densities[i] = *data_ptr++;
1759 			}
1760 		}
1761 		dp->default_density = *data_ptr << 3;
1762 		if (version == 2 &&
1763 		    data_list_len >= (13 + len) * sizeof (int)) {
1764 			data_ptr++;
1765 			dp->non_motion_timeout	= *data_ptr++;
1766 			dp->io_timeout		= *data_ptr++;
1767 			dp->rewind_timeout	= *data_ptr++;
1768 			dp->space_timeout	= *data_ptr++;
1769 			dp->load_timeout	= *data_ptr++;
1770 			dp->unload_timeout	= *data_ptr++;
1771 			dp->erase_timeout	= *data_ptr++;
1772 		}
1773 		kmem_free(data_list, data_list_len);
1774 		found = 1;
1775 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1776 		    "found in st.conf: vid = %s, pretty=%s\n",
1777 		    dp->vid, dp->name);
1778 		break;
1779 	}
1780 
1781 	/*
1782 	 * free up the memory allocated by ddi_getlongprop
1783 	 */
1784 	if (config_list) {
1785 		kmem_free(config_list, config_list_len);
1786 	}
1787 	return (found);
1788 }
1789 
1790 static int
1791 st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
1792     struct st_drivetype *dp)
1793 {
1794 	int i;
1795 
1796 	/*
1797 	 * Determine type of tape controller.  Type is determined by
1798 	 * checking the result of the earlier inquiry command and
1799 	 * comparing vendor ids with strings in a table declared in st_conf.c.
1800 	 */
1801 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1802 	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
1803 
1804 	for (i = 0; i < st_ndrivetypes; i++) {
1805 		if (st_drivetypes[i].length == 0) {
1806 			continue;
1807 		}
1808 		if (strncasecmp(vidpid, st_drivetypes[i].vid,
1809 		    st_drivetypes[i].length)) {
1810 			continue;
1811 		}
1812 		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
1813 		return (1);
1814 	}
1815 	return (0);
1816 }
1817 
1818 static int
1819 st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
1820 {
1821 	int i;
1822 
1823 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
1824 	    "st_get_default_conf(): making drivetype from INQ cmd\n");
1825 
1826 
1827 	/*
1828 	 * Make up a name
1829 	 */
1830 	bcopy("Vendor '", dp->name, 8);
1831 	bcopy(vidpid, &dp->name[8], VIDLEN);
1832 	bcopy("' Product '", &dp->name[16], 11);
1833 	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
1834 	dp->name[ST_NAMESIZE - 2] = '\'';
1835 	dp->name[ST_NAMESIZE - 1] = '\0';
1836 	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
1837 	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
1838 	/*
1839 	 * 'clean' vendor and product strings of non-printing chars
1840 	 */
1841 	for (i = 0; i < ST_NAMESIZE - 2; i++) {
1842 		if (dp->name[i] < ' ' || dp->name[i] > '~') {
1843 			dp->name[i] = '.';
1844 		}
1845 	}
1846 	dp->type = ST_TYPE_INVALID;
1847 	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
1848 
1849 	return (1); /* Can Not Fail */
1850 }
1851 
1852 /*
1853  * Regular Unix Entry points
1854  */
1855 
1856 
1857 
1858 /* ARGSUSED */
1859 static int
1860 st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
1861 {
1862 	dev_t dev = *dev_p;
1863 	int rval = 0;
1864 
1865 	GET_SOFT_STATE(dev);
1866 
1867 	/*
1868 	 * validate that we are addressing a sensible unit
1869 	 */
1870 	mutex_enter(ST_MUTEX);
1871 
1872 #ifdef	STDEBUG
1873 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
1874 	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
1875 	    st_dev_name(dev), *dev_p, flag, otyp);
1876 #endif
1877 
1878 	/*
1879 	 * All device accesss go thru st_strategy() where we check
1880 	 * suspend status
1881 	 */
1882 
1883 	if (!un->un_attached) {
1884 		st_known_tape_type(un);
1885 		if (!un->un_attached) {
1886 			rval = ENXIO;
1887 			goto exit;
1888 		}
1889 
1890 	}
1891 
1892 	/*
1893 	 * Check for the case of the tape in the middle of closing.
1894 	 * This isn't simply a check of the current state, because
1895 	 * we could be in state of sensing with the previous state
1896 	 * that of closing.
1897 	 *
1898 	 * And don't allow multiple opens.
1899 	 */
1900 	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
1901 		un->un_laststate = un->un_state;
1902 		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
1903 		while (IS_CLOSING(un) ||
1904 		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
1905 			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
1906 				rval = EINTR;
1907 				un->un_state = un->un_laststate;
1908 				goto exit;
1909 			}
1910 		}
1911 	} else if (un->un_state != ST_STATE_CLOSED) {
1912 		rval = EBUSY;
1913 		goto busy;
1914 	}
1915 
1916 	/*
1917 	 * record current dev
1918 	 */
1919 	un->un_dev = dev;
1920 	un->un_oflags = flag;	/* save for use in st_tape_init() */
1921 	un->un_errno = 0;	/* no errors yet */
1922 	un->un_restore_pos = 0;
1923 	un->un_rqs_state = 0;
1924 
1925 	/*
1926 	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
1927 	 * anything, leave internal states alone, if fileno >= 0
1928 	 */
1929 	if (flag & (FNDELAY | FNONBLOCK)) {
1930 		if (un->un_fileno < 0 || (un->un_fileno == 0 &&
1931 			un->un_blkno == 0)) {
1932 			un->un_state = ST_STATE_OFFLINE;
1933 		} else {
1934 			/*
1935 			 * set un_read_only/write-protect status.
1936 			 *
1937 			 * If the tape is not bot we can assume
1938 			 * that mspl->wp_status is set properly.
1939 			 * else
1940 			 * we need to do a mode sense/Tur once
1941 			 * again to get the actual tape status.(since
1942 			 * user might have replaced the tape)
1943 			 * Hence make the st state OFFLINE so that
1944 			 * we re-intialize the tape once again.
1945 			 */
1946 			if (un->un_fileno > 0 ||
1947 			    (un->un_fileno == 0 && un->un_blkno != 0)) {
1948 				un->un_read_only =
1949 				    (un->un_oflags & FWRITE) ? 0 : 1;
1950 				un->un_state = ST_STATE_OPEN_PENDING_IO;
1951 			} else {
1952 				un->un_state = ST_STATE_OFFLINE;
1953 			}
1954 		}
1955 		rval = 0;
1956 	} else {
1957 		/*
1958 		 * If reserve/release is supported on this drive.
1959 		 * then call st_tape_reservation_init().
1960 		 */
1961 		un->un_state = ST_STATE_OPENING;
1962 
1963 		if (ST_RESERVE_SUPPORTED(un)) {
1964 			rval = st_tape_reservation_init(dev);
1965 			if (rval) {
1966 				goto exit;
1967 			}
1968 		}
1969 		rval = st_tape_init(dev);
1970 		if (rval) {
1971 			/*
1972 			 * Release the tape unit, if no preserve reserve
1973 			 */
1974 			if ((ST_RESERVE_SUPPORTED(un)) &&
1975 			    !(un->un_rsvd_status & ST_PRESERVE_RESERVE)) {
1976 				(void) st_reserve_release(dev, ST_RELEASE);
1977 			}
1978 		} else {
1979 			un->un_state = ST_STATE_OPEN_PENDING_IO;
1980 		}
1981 	}
1982 
1983 exit:
1984 	/*
1985 	 * we don't want any uninvited guests scrogging our data when we're
1986 	 * busy with something, so for successful opens or failed opens
1987 	 * (except for EBUSY), reset these counters and state appropriately.
1988 	 */
1989 	if (rval != EBUSY) {
1990 		if (rval) {
1991 			un->un_state = ST_STATE_CLOSED;
1992 		}
1993 		un->un_err_resid = 0;
1994 		un->un_retry_ct = 0;
1995 		un->un_tran_retry_ct = 0;
1996 	}
1997 busy:
1998 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
1999 	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2000 	mutex_exit(ST_MUTEX);
2001 	return (rval);
2002 
2003 }
2004 
2005 #define	ST_LOST_RESERVE_BETWEEN_OPENS  \
2006 		(ST_RESERVE | ST_LOST_RESERVE | ST_PRESERVE_RESERVE)
2007 
2008 int
2009 st_tape_reservation_init(dev_t dev)
2010 {
2011 	int rval = 0;
2012 
2013 	GET_SOFT_STATE(dev);
2014 
2015 	ASSERT(mutex_owned(ST_MUTEX));
2016 
2017 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2018 	    "st_tape_reservation_init(dev = 0x%lx)\n", dev);
2019 
2020 	/*
2021 	 * Issue a Throw-Away reserve command to clear the
2022 	 * check condition.
2023 	 * If the current behaviour of reserve/release is to
2024 	 * hold reservation across opens , and if a Bus reset
2025 	 * has been issued between opens then this command
2026 	 * would set the ST_LOST_RESERVE flags in rsvd_status.
2027 	 * In this case return an EACCES so that user knows that
2028 	 * reservation has been lost in between opens.
2029 	 * If this error is not returned and we continue with
2030 	 * successful open , then user may think position of the
2031 	 * tape is still the same but inreality we would rewind the
2032 	 * tape and continue from BOT.
2033 	 */
2034 	rval = st_reserve_release(dev, ST_RESERVE);
2035 
2036 	if (rval) {
2037 		if ((un->un_rsvd_status & ST_LOST_RESERVE_BETWEEN_OPENS) ==
2038 			ST_LOST_RESERVE_BETWEEN_OPENS) {
2039 				un->un_rsvd_status &=
2040 					~(ST_LOST_RESERVE | ST_RESERVE);
2041 				un->un_errno = EACCES;
2042 				return (EACCES);
2043 		}
2044 		rval = st_reserve_release(dev, ST_RESERVE);
2045 	}
2046 	if (rval == 0)
2047 		un->un_rsvd_status |= ST_INIT_RESERVE;
2048 
2049 	return (rval);
2050 }
2051 
2052 static int
2053 st_tape_init(dev_t dev)
2054 {
2055 	int err;
2056 	int rval = 0;
2057 
2058 	GET_SOFT_STATE(dev);
2059 
2060 	ASSERT(mutex_owned(ST_MUTEX));
2061 
2062 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2063 	    "st_tape_init(dev = 0x%lx, oflags = %d)\n", dev, un->un_oflags);
2064 
2065 	/*
2066 	 * Clean up after any errors left by 'last' close.
2067 	 * This also handles the case of the initial open.
2068 	 */
2069 	if (un->un_state != ST_STATE_INITIALIZING) {
2070 		un->un_laststate = un->un_state;
2071 		un->un_state = ST_STATE_OPENING;
2072 	}
2073 
2074 	un->un_kbytes_xferred = 0;
2075 
2076 	/*
2077 	 * do a throw away TUR to clear check condition
2078 	 */
2079 	err = st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2080 
2081 	/*
2082 	 * If test unit ready fails because the drive is reserved
2083 	 * by another host fail the open for no access.
2084 	 */
2085 	if (err) {
2086 		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2087 			un->un_state = ST_STATE_CLOSED;
2088 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2089 				"st_tape_init: RESERVATION CONFLICT\n");
2090 			rval = EACCES;
2091 			goto exit;
2092 		}
2093 	}
2094 
2095 	/*
2096 	 * See whether this is a generic device that we haven't figured
2097 	 * anything out about yet.
2098 	 */
2099 	if (un->un_dp->type == ST_TYPE_INVALID) {
2100 		if (st_determine_generic(dev)) {
2101 			un->un_state = ST_STATE_CLOSED;
2102 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2103 			    "st_open: EIO invalid type\n");
2104 			rval = EIO;
2105 			goto exit;
2106 		}
2107 		/*
2108 		 * If this is a Unknown Type drive,
2109 		 * Use the READ BLOCK LIMITS to determine if
2110 		 * allow large xfer is approprate if not globally
2111 		 * disabled with st_allow_large_xfer.
2112 		 */
2113 		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
2114 	} else {
2115 
2116 		/*
2117 		 * If we allow_large_xfer (ie >64k) and have not yet found out
2118 		 * the max block size supported by the drive,
2119 		 * find it by issueing a READ_BLKLIM command.
2120 		 * if READ_BLKLIM cmd fails, assume drive doesn't
2121 		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
2122 		 */
2123 		un->un_allow_large_xfer = st_allow_large_xfer &&
2124 		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
2125 	}
2126 	/*
2127 	 * if maxbsize is unknown, set the maximum block size.
2128 	 */
2129 	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
2130 
2131 		/*
2132 		 * Get the Block limits of the tape drive.
2133 		 * if un->un_allow_large_xfer = 0 , then make sure
2134 		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
2135 		 */
2136 		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
2137 
2138 		err = st_cmd(dev, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2139 		if (err) {
2140 			/* Retry */
2141 			err = st_cmd(dev, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
2142 		}
2143 		if (!err) {
2144 
2145 			/*
2146 			 * if cmd successful, use limit returned
2147 			 */
2148 			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
2149 					(un->un_rbl->max_mid << 8) +
2150 					un->un_rbl->max_lo;
2151 			un->un_minbsize = (un->un_rbl->min_hi << 8) +
2152 					un->un_rbl->min_lo;
2153 			un->un_data_mod = 1 << un->un_rbl->granularity;
2154 			if ((un->un_maxbsize == 0) ||
2155 			    (un->un_allow_large_xfer == 0 &&
2156 			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
2157 				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
2158 
2159 			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
2160 				/*
2161 				 * Drive is not one that is configured, But the
2162 				 * READ BLOCK LIMITS tells us it can do large
2163 				 * xfers.
2164 				 */
2165 				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
2166 					un->un_dp->options |=
2167 					    ST_NO_RECSIZE_LIMIT;
2168 				}
2169 				/*
2170 				 * If max and mimimum block limits are the
2171 				 * same this is a fixed block size device.
2172 				 */
2173 				if (un->un_maxbsize == un->un_minbsize) {
2174 					un->un_dp->options &= ~ST_VARIABLE;
2175 				}
2176 			}
2177 
2178 			if (un->un_minbsize == 0) {
2179 				un->un_minbsize = 1;
2180 			}
2181 
2182 		} else { /* error on read block limits */
2183 
2184 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2185 				"!st_tape_init: Error on READ BLOCK LIMITS,"
2186 				" errno = %d un_rsvd_status = 0x%X\n",
2187 				err, un->un_rsvd_status);
2188 
2189 			/*
2190 			 * since read block limits cmd failed,
2191 			 * do not allow large xfers.
2192 			 * use old values in st_minphys
2193 			 */
2194 			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2195 				rval = EACCES;
2196 			} else {
2197 				un->un_allow_large_xfer = 0;
2198 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2199 					"!Disabling large transfers\n");
2200 
2201 				/*
2202 				 * we guess maxbsize and minbsize
2203 				 */
2204 				if (un->un_bsize) {
2205 					un->un_maxbsize = un->un_minbsize =
2206 						un->un_bsize;
2207 				} else {
2208 					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
2209 					un->un_minbsize = 1;
2210 				}
2211 				/*
2212 				 * Data Mod must be set,
2213 				 * Even if read block limits fails.
2214 				 * Prevents Divide By Zero in st_rw().
2215 				 */
2216 				un->un_data_mod = 1;
2217 			}
2218 		}
2219 		if (un->un_rbl) {
2220 			kmem_free(un->un_rbl, RBLSIZE);
2221 			un->un_rbl = NULL;
2222 		}
2223 
2224 		if (rval) {
2225 			goto exit;
2226 		}
2227 	}
2228 
2229 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
2230 	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
2231 	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
2232 	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
2233 
2234 	err = st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2235 
2236 	if (err != 0) {
2237 		if (err == EINTR) {
2238 			un->un_laststate = un->un_state;
2239 			un->un_state = ST_STATE_CLOSED;
2240 			rval = EINTR;
2241 			goto exit;
2242 		}
2243 		/*
2244 		 * Make sure the tape is ready
2245 		 */
2246 		un->un_fileno = -1;
2247 		if (un->un_status != KEY_UNIT_ATTENTION) {
2248 			/*
2249 			 * allow open no media.  Subsequent MTIOCSTATE
2250 			 * with media present will complete the open
2251 			 * logic.
2252 			 */
2253 			un->un_laststate = un->un_state;
2254 			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
2255 				un->un_mediastate = MTIO_EJECTED;
2256 				un->un_state = ST_STATE_OFFLINE;
2257 				rval = 0;
2258 				goto exit;
2259 			} else {
2260 				un->un_state = ST_STATE_CLOSED;
2261 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2262 		    "st_open EIO no media, not opened O_NONBLOCK|O_EXCL\n");
2263 				rval = EIO;
2264 				goto exit;
2265 			}
2266 		}
2267 	}
2268 
2269 	/*
2270 	 * On each open, initialize block size from drivetype struct,
2271 	 * as it could have been changed by MTSRSZ ioctl.
2272 	 * Now, ST_VARIABLE simply means drive is capable of variable
2273 	 * mode. All drives are assumed to support fixed records.
2274 	 * Hence, un_bsize tells what mode the drive is in.
2275 	 *	un_bsize	= 0	- variable record length
2276 	 *			= x	- fixed record length is x
2277 	 */
2278 	un->un_bsize = un->un_dp->bsize;
2279 
2280 	if (un->un_restore_pos) {
2281 		if (st_validate_tapemarks(un, un->un_save_fileno,
2282 		    un->un_save_blkno) != 0) {
2283 			un->un_restore_pos = 0;
2284 			un->un_laststate = un->un_state;
2285 			un->un_state = ST_STATE_CLOSED;
2286 			rval = EIO;
2287 			goto exit;
2288 		}
2289 		un->un_restore_pos = 0;
2290 	}
2291 
2292 	if ((un->un_fileno < 0) && st_loadtape(dev)) {
2293 		un->un_laststate = un->un_state;
2294 		un->un_state = ST_STATE_CLOSED;
2295 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2296 		    "st_open : EIO can't open tape\n");
2297 		rval = EIO;
2298 		goto exit;
2299 	}
2300 
2301 	/*
2302 	 * do a mode sense to pick up state of current write-protect,
2303 	 */
2304 	(void) st_modesense(un);
2305 
2306 	/*
2307 	 * If we are opening the tape for writing, check
2308 	 * to make sure that the tape can be written.
2309 	 */
2310 	if (un->un_oflags & FWRITE) {
2311 		err = 0;
2312 		if (un->un_mspl->wp)  {
2313 			un->un_status = KEY_WRITE_PROTECT;
2314 			un->un_laststate = un->un_state;
2315 			un->un_state = ST_STATE_CLOSED;
2316 			rval = EACCES;
2317 			goto exit;
2318 		} else {
2319 			un->un_read_only = 0;
2320 		}
2321 	} else {
2322 		un->un_read_only = 1;
2323 	}
2324 
2325 	/*
2326 	 * If we're opening the tape write-only, we need to
2327 	 * write 2 filemarks on the HP 1/2 inch drive, to
2328 	 * create a null file.
2329 	 */
2330 	if ((un->un_oflags == FWRITE) && (un->un_dp->options & ST_REEL)) {
2331 		un->un_fmneeded = 2;
2332 	} else if (un->un_oflags == FWRITE) {
2333 		un->un_fmneeded = 1;
2334 	} else {
2335 		un->un_fmneeded = 0;
2336 	}
2337 
2338 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
2339 	    "fmneeded = %x\n", un->un_fmneeded);
2340 
2341 	/*
2342 	 * Make sure the density can be selected correctly.
2343 	 */
2344 	if (st_determine_density(dev, B_WRITE)) {
2345 		un->un_status = KEY_ILLEGAL_REQUEST;
2346 		un->un_laststate = un->un_state;
2347 		un->un_state = ST_STATE_CLOSED;
2348 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2349 		    "st_open: EIO can't determine density\n");
2350 		rval = EIO;
2351 		goto exit;
2352 	}
2353 
2354 	/*
2355 	 * Destroy the knowledge that we have 'determined'
2356 	 * density so that a later read at BOT comes along
2357 	 * does the right density determination.
2358 	 */
2359 
2360 	un->un_density_known = 0;
2361 
2362 
2363 	/*
2364 	 * Okay, the tape is loaded and either at BOT or somewhere past.
2365 	 * Mark the state such that any I/O or tape space operations
2366 	 * will get/set the right density, etc..
2367 	 */
2368 	un->un_laststate = un->un_state;
2369 	un->un_lastop = ST_OP_NIL;
2370 	un->un_mediastate = MTIO_INSERTED;
2371 	cv_broadcast(&un->un_state_cv);
2372 
2373 	/*
2374 	 *  Set test append flag if writing.
2375 	 *  First write must check that tape is positioned correctly.
2376 	 */
2377 	un->un_test_append = (un->un_oflags & FWRITE);
2378 
2379 exit:
2380 	un->un_err_resid = 0;
2381 	un->un_last_resid = 0;
2382 	un->un_last_count = 0;
2383 
2384 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2385 	    "st_tape_init: return val = %x\n", rval);
2386 	return (rval);
2387 
2388 }
2389 
2390 
2391 
2392 /* ARGSUSED */
2393 static int
2394 st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
2395 {
2396 	int err = 0;
2397 	int norew, count, last_state;
2398 #if defined(__i386) || defined(__amd64)
2399 	struct contig_mem *cp, *cp_temp;
2400 #endif
2401 
2402 	GET_SOFT_STATE(dev);
2403 
2404 	/*
2405 	 * wait till all cmds in the pipeline have been completed
2406 	 */
2407 	mutex_enter(ST_MUTEX);
2408 
2409 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2410 	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
2411 
2412 	st_wait_for_io(un);
2413 
2414 	/* turn off persistent errors on close, as we want close to succeed */
2415 	TURN_PE_OFF(un);
2416 
2417 	/*
2418 	 * set state to indicate that we are in process of closing
2419 	 */
2420 	last_state = un->un_laststate = un->un_state;
2421 	un->un_state = ST_STATE_CLOSING;
2422 
2423 	/*
2424 	 * BSD behavior:
2425 	 * a close always causes a silent span to the next file if we've hit
2426 	 * an EOF (but not yet read across it).
2427 	 */
2428 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2429 	    "st_close1: fileno=%x, blkno=%lx, un_eof=%x\n", un->un_fileno,
2430 	    un->un_blkno, un->un_eof);
2431 
2432 
2433 	if (BSD_BEHAVIOR && (un->un_eof == ST_EOF)) {
2434 		if (un->un_fileno >= 0) {
2435 			un->un_fileno++;
2436 			un->un_blkno = 0;
2437 		}
2438 		un->un_eof = ST_NO_EOF;
2439 	}
2440 
2441 	/*
2442 	 * rewinding?
2443 	 */
2444 	norew = (getminor(dev) & MT_NOREWIND);
2445 
2446 	/*
2447 	 * SVR4 behavior for skipping to next file:
2448 	 *
2449 	 * If we have not seen a filemark, space to the next file
2450 	 *
2451 	 * If we have already seen the filemark we are physically in the next
2452 	 * file and we only increment the filenumber
2453 	 */
2454 
2455 	if (norew && SVR4_BEHAVIOR && (flag & FREAD) && (un->un_blkno != 0) &&
2456 	    (un->un_lastop != ST_OP_WRITE)) {
2457 		switch (un->un_eof) {
2458 		case ST_NO_EOF:
2459 			/*
2460 			 * if we were reading and did not read the complete file
2461 			 * skip to the next file, leaving the tape correctly
2462 			 * positioned to read the first record of the next file
2463 			 * Check first for REEL if we are at EOT by trying to
2464 			 * read a block
2465 			 */
2466 			if ((un->un_dp->options & ST_REEL) &&
2467 				(!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
2468 			    (un->un_blkno == 0)) {
2469 				if (st_cmd(dev, SCMD_SPACE, Blk(1), SYNC_CMD)) {
2470 					ST_DEBUG2(ST_DEVINFO, st_label,
2471 					    SCSI_DEBUG,
2472 					    "st_close : EIO can't space\n");
2473 					err = EIO;
2474 					break;
2475 				}
2476 				if (un->un_eof >= ST_EOF_PENDING) {
2477 					un->un_eof = ST_EOT_PENDING;
2478 					un->un_fileno += 1;
2479 					un->un_blkno   = 0;
2480 					break;
2481 				}
2482 			}
2483 			if (st_cmd(dev, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
2484 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2485 				    "st_close: EIO can't space #2\n");
2486 				err = EIO;
2487 			} else {
2488 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2489 				    "st_close2: fileno=%x,blkno=%lx,"
2490 				    "un_eof=%x\n",
2491 				    un->un_fileno, un->un_blkno, un->un_eof);
2492 				un->un_eof = ST_NO_EOF;
2493 			}
2494 			break;
2495 
2496 		case ST_EOF_PENDING:
2497 		case ST_EOF:
2498 			un->un_fileno += 1;
2499 			un->un_blkno   = 0;
2500 			un->un_eof = ST_NO_EOF;
2501 			break;
2502 
2503 		case ST_EOT:
2504 		case ST_EOT_PENDING:
2505 			/* nothing to do */
2506 			break;
2507 		}
2508 	}
2509 
2510 
2511 	/*
2512 	 * For performance reasons (HP 88780), the driver should
2513 	 * postpone writing the second tape mark until just before a file
2514 	 * positioning ioctl is issued (e.g., rewind).	This means that
2515 	 * the user must not manually rewind the tape because the tape will
2516 	 * be missing the second tape mark which marks EOM.
2517 	 * However, this small performance improvement is not worth the risk.
2518 	 */
2519 
2520 	/*
2521 	 * We need to back up over the filemark we inadvertently popped
2522 	 * over doing a read in between the two filemarks that constitute
2523 	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
2524 	 * set while reading.
2525 	 *
2526 	 * If we happen to be at physical eot (ST_EOM) (writing case),
2527 	 * the writing of filemark(s) will clear the ST_EOM state, which
2528 	 * we don't want, so we save this state and restore it later.
2529 	 */
2530 
2531 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2532 	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
2533 		flag, un->un_fmneeded, un->un_lastop, un->un_eof);
2534 
2535 	if (un->un_eof == ST_EOT_PENDING) {
2536 		if (norew) {
2537 			if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
2538 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2539 				    "st_close: EIO can't space #3\n");
2540 				err = EIO;
2541 			} else {
2542 				un->un_blkno = 0;
2543 				un->un_eof = ST_EOT;
2544 			}
2545 		} else {
2546 			un->un_eof = ST_NO_EOF;
2547 		}
2548 
2549 	/*
2550 	 * Do we need to write a file mark?
2551 	 *
2552 	 * only write filemarks if there are fmks to be written and
2553 	 *   - open for write (possibly read/write)
2554 	 *   - the last operation was a write
2555 	 * or:
2556 	 *   -	opened for wronly
2557 	 *   -	no data was written
2558 	 */
2559 	} else if ((un->un_fileno >= 0) && (un->un_fmneeded > 0) &&
2560 	    (((flag & FWRITE) && (un->un_lastop == ST_OP_WRITE)) ||
2561 	    ((flag & FWRITE) && (un->un_lastop == ST_OP_WEOF)) ||
2562 	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
2563 
2564 		/* save ST_EOM state */
2565 		int was_at_eom = (un->un_eof == ST_EOM) ? 1 : 0;
2566 
2567 		/*
2568 		 * Note that we will write a filemark if we had opened
2569 		 * the tape write only and no data was written, thus
2570 		 * creating a null file.
2571 		 *
2572 		 * If the user already wrote one, we only have to write 1 more.
2573 		 * If they wrote two, we don't have to write any.
2574 		 */
2575 
2576 		count = un->un_fmneeded;
2577 		if (count > 0) {
2578 			if (st_cmd(dev, SCMD_WRITE_FILE_MARK,
2579 			    count, SYNC_CMD)) {
2580 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2581 				    "st_close : EIO can't wfm\n");
2582 				err = EIO;
2583 			}
2584 			if ((un->un_dp->options & ST_REEL) && norew) {
2585 				if (st_cmd(dev, SCMD_SPACE, Fmk((-1)),
2586 				    SYNC_CMD)) {
2587 					ST_DEBUG2(ST_DEVINFO, st_label,
2588 					    SCSI_DEBUG,
2589 					    "st_close : EIO space fmk(-1)\n");
2590 					err = EIO;
2591 				}
2592 				un->un_eof = ST_NO_EOF;
2593 				/* fix up block number */
2594 				un->un_blkno = 0;
2595 			}
2596 		}
2597 
2598 		/*
2599 		 * If we aren't going to be rewinding, and we were at
2600 		 * physical eot, restore the state that indicates we
2601 		 * are at physical eot. Once you have reached physical
2602 		 * eot, and you close the tape, the only thing you can
2603 		 * do on the next open is to rewind. Access to trailer
2604 		 * records is only allowed without closing the device.
2605 		 */
2606 		if (norew == 0 && was_at_eom)
2607 			un->un_eof = ST_EOM;
2608 	}
2609 
2610 	/*
2611 	 * report soft errors if enabled and available, if we never accessed
2612 	 * the drive, don't get errors. This will prevent some DAT error
2613 	 * messages upon LOG SENSE.
2614 	 */
2615 	if (st_report_soft_errors_on_close &&
2616 	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
2617 	    (last_state != ST_STATE_OFFLINE)) {
2618 		/*
2619 		 * Make sure we have reserve the tape unit.
2620 		 * This is the case when we do a O_NDELAY open and
2621 		 * then do a close without any I/O.
2622 		 */
2623 		if (!(un->un_rsvd_status & ST_INIT_RESERVE) &&
2624 			ST_RESERVE_SUPPORTED(un)) {
2625 			if ((err = st_tape_reservation_init(dev))) {
2626 				goto error;
2627 			}
2628 		}
2629 		(void) st_report_soft_errors(dev, flag);
2630 	}
2631 
2632 
2633 	/*
2634 	 * Do we need to rewind? Can we rewind?
2635 	 */
2636 	if (norew == 0 && un->un_fileno >= 0 && err == 0) {
2637 		/*
2638 		 * We'd like to rewind with the
2639 		 * 'immediate' bit set, but this
2640 		 * causes problems on some drives
2641 		 * where subsequent opens get a
2642 		 * 'NOT READY' error condition
2643 		 * back while the tape is rewinding,
2644 		 * which is impossible to distinguish
2645 		 * from the condition of 'no tape loaded'.
2646 		 *
2647 		 * Also, for some targets, if you disconnect
2648 		 * with the 'immediate' bit set, you don't
2649 		 * actually return right away, i.e., the
2650 		 * target ignores your request for immediate
2651 		 * return.
2652 		 *
2653 		 * Instead, we'll fire off an async rewind
2654 		 * command. We'll mark the device as closed,
2655 		 * and any subsequent open will stall on
2656 		 * the first TEST_UNIT_READY until the rewind
2657 		 * completes.
2658 		 *
2659 		 */
2660 		if (!(un->un_rsvd_status & ST_INIT_RESERVE) &&
2661 			ST_RESERVE_SUPPORTED(un)) {
2662 			if ((err = st_tape_reservation_init(dev))) {
2663 				goto error;
2664 			}
2665 		}
2666 		if (ST_RESERVE_SUPPORTED(un)) {
2667 			(void) st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
2668 		} else {
2669 			(void) st_cmd(dev, SCMD_REWIND, 0, ASYNC_CMD);
2670 		}
2671 	}
2672 
2673 	/*
2674 	 * eject tape if necessary
2675 	 */
2676 	if (un->un_eject_tape_on_failure) {
2677 		un->un_eject_tape_on_failure = 0;
2678 		if (st_cmd(dev, SCMD_LOAD, 0, SYNC_CMD)) {
2679 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2680 			    "st_close : can't unload tape\n");
2681 		} else {
2682 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2683 			    "st_close : tape unloaded \n");
2684 			un->un_eof = ST_NO_EOF;
2685 			un->un_mediastate = MTIO_EJECTED;
2686 		}
2687 	}
2688 	/*
2689 	 * Release the tape unit, if default reserve/release
2690 	 * behaviour.
2691 	 */
2692 	if (ST_RESERVE_SUPPORTED(un) &&
2693 		!(un->un_rsvd_status & ST_PRESERVE_RESERVE) &&
2694 		    (un->un_rsvd_status & ST_INIT_RESERVE)) {
2695 		(void) st_reserve_release(dev, ST_RELEASE);
2696 	}
2697 
2698 error:
2699 	/*
2700 	 * clear up state
2701 	 */
2702 	un->un_laststate = un->un_state;
2703 	un->un_state = ST_STATE_CLOSED;
2704 	un->un_lastop = ST_OP_NIL;
2705 	un->un_throttle = 1;	/* assume one request at time, for now */
2706 	un->un_retry_ct = 0;
2707 	un->un_tran_retry_ct = 0;
2708 	un->un_errno = 0;
2709 	un->un_swr_token = (opaque_t)NULL;
2710 	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
2711 
2712 	/* Restore the options to the init time settings */
2713 	if (un->un_init_options & ST_READ_IGNORE_ILI) {
2714 		un->un_dp->options |= ST_READ_IGNORE_ILI;
2715 	} else {
2716 		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
2717 	}
2718 
2719 	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
2720 		un->un_dp->options |= ST_READ_IGNORE_EOFS;
2721 	} else {
2722 		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
2723 	}
2724 
2725 	if (un->un_init_options & ST_SHORT_FILEMARKS) {
2726 		un->un_dp->options |= ST_SHORT_FILEMARKS;
2727 	} else {
2728 		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
2729 	}
2730 
2731 	ASSERT(mutex_owned(ST_MUTEX));
2732 
2733 	/*
2734 	 * Signal anyone awaiting a close operation to complete.
2735 	 */
2736 	cv_signal(&un->un_clscv);
2737 
2738 	/*
2739 	 * any kind of error on closing causes all state to be tossed
2740 	 */
2741 	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
2742 		un->un_density_known = 0;
2743 		/*
2744 		 * note that st_intr has already set un_fileno to -1
2745 		 */
2746 	}
2747 
2748 #if defined(__i386) || defined(__amd64)
2749 	/*
2750 	 * free any contiguous mem alloc'ed for big block I/O
2751 	 */
2752 	cp = un->un_contig_mem;
2753 	while (cp) {
2754 		if (cp->cm_addr) {
2755 			ddi_dma_mem_free(&cp->cm_acc_hdl);
2756 		}
2757 		if (cp->cm_bp) {
2758 			freerbuf(cp->cm_bp);
2759 		}
2760 		cp_temp = cp;
2761 		cp = cp->cm_next;
2762 		kmem_free(cp_temp, sizeof (struct contig_mem));
2763 	}
2764 	un->un_contig_mem_total_num = 0;
2765 	un->un_contig_mem_available_num = 0;
2766 	un->un_contig_mem = NULL;
2767 #endif
2768 
2769 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2770 	    "st_close3: return val = %x, fileno=%x, blkno=%lx, un_eof=%x\n",
2771 			    err, un->un_fileno, un->un_blkno, un->un_eof);
2772 
2773 	mutex_exit(ST_MUTEX);
2774 	return (err);
2775 }
2776 
2777 /*
2778  * These routines perform raw i/o operations.
2779  */
2780 
2781 /* ARGSUSED2 */
2782 static int
2783 st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
2784 {
2785 	return (st_arw(dev, aio, B_READ));
2786 }
2787 
2788 
2789 /* ARGSUSED2 */
2790 static int
2791 st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
2792 {
2793 	return (st_arw(dev, aio, B_WRITE));
2794 }
2795 
2796 
2797 
2798 /* ARGSUSED */
2799 static int
2800 st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
2801 {
2802 	return (st_rw(dev, uiop, B_READ));
2803 }
2804 
2805 /* ARGSUSED */
2806 static int
2807 st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
2808 {
2809 	return (st_rw(dev, uiop, B_WRITE));
2810 }
2811 
2812 /*
2813  * Due to historical reasons, old limits are: For variable-length devices:
2814  * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
2815  * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
2816  * (let it through unmodified. For fixed-length record devices:
2817  * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
2818  *
2819  * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
2820  * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
2821  * command to the drive).
2822  *
2823  */
2824 static void
2825 st_minphys(struct buf *bp)
2826 {
2827 	struct scsi_tape *un;
2828 
2829 #if !defined(lint)
2830 	_NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_tape::un_sd));
2831 #endif
2832 
2833 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
2834 
2835 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2836 	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
2837 	    bp->b_bcount);
2838 
2839 	if (un->un_allow_large_xfer) {
2840 
2841 		/*
2842 		 * check un_maxbsize for variable length devices only
2843 		 */
2844 		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
2845 			bp->b_bcount = un->un_maxbsize;
2846 		}
2847 		/*
2848 		 * can't go more that HBA maxdma limit in either fixed-length
2849 		 * or variable-length tape drives.
2850 		 */
2851 		if (bp->b_bcount > un->un_maxdma) {
2852 			bp->b_bcount = un->un_maxdma;
2853 		}
2854 	} else {
2855 
2856 		/*
2857 		 *  use old fixed limits
2858 		 */
2859 		if (un->un_bsize == 0) {
2860 			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
2861 				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
2862 			}
2863 		} else {
2864 			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
2865 				bp->b_bcount = ST_MAXRECSIZE_FIXED;
2866 			}
2867 		}
2868 	}
2869 
2870 #if !defined(lint)
2871 _NOTE(DATA_READABLE_WITHOUT_LOCK(scsi_tape::un_sbufp));
2872 #endif /* lint */
2873 	/*
2874 	 * For regular raw I/O and Fixed Block length devices, make sure
2875 	 * the adjusted block count is a whole multiple of the device
2876 	 * block size.
2877 	 */
2878 	if (bp != un->un_sbufp && un->un_bsize) {
2879 		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
2880 	}
2881 }
2882 
2883 /*ARGSUSED*/
2884 static void
2885 st_uscsi_minphys(struct buf *bp)
2886 {
2887 	/*
2888 	 * do not break up because the CDB count would then be
2889 	 * incorrect and create spurious data underrun errors.
2890 	 */
2891 }
2892 
2893 static int
2894 st_rw(dev_t dev, struct uio *uio, int flag)
2895 {
2896 	int rval = 0;
2897 	long len;
2898 
2899 	GET_SOFT_STATE(dev);
2900 
2901 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2902 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
2903 	    (flag == B_READ ? rd_str: wr_str));
2904 
2905 	/* get local copy of transfer length */
2906 	len = uio->uio_iov->iov_len;
2907 
2908 	mutex_enter(ST_MUTEX);
2909 
2910 	/*
2911 	 * If in fixed block size mode and requested read or write
2912 	 * is not an even multiple of that block size.
2913 	 */
2914 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
2915 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
2916 		    "%s: not modulo %d block size\n",
2917 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
2918 		rval = EINVAL;
2919 	}
2920 
2921 	/* If device has set granularity in the READ_BLKLIM we honor it. */
2922 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
2923 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
2924 		    "%s: not modulo %d device granularity\n",
2925 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
2926 		rval = EINVAL;
2927 	}
2928 
2929 	if (rval != 0) {
2930 		un->un_errno = rval;
2931 		mutex_exit(ST_MUTEX);
2932 		return (rval);
2933 	}
2934 
2935 	un->un_silent_skip = 0;
2936 	mutex_exit(ST_MUTEX);
2937 
2938 	len = uio->uio_resid;
2939 
2940 	rval = physio(st_strategy, (struct buf *)NULL,
2941 		dev, flag, st_minphys, uio);
2942 	/*
2943 	 * if we have hit logical EOT during this xfer and there is not a
2944 	 * full residue, then set un_eof back  to ST_EOM to make sure that
2945 	 * the user will see at least one zero write
2946 	 * after this short write
2947 	 */
2948 	mutex_enter(ST_MUTEX);
2949 	if (un->un_eof > ST_NO_EOF) {
2950 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2951 		"un_eof=%d resid=%lx\n", un->un_eof, uio->uio_resid);
2952 	}
2953 	if (un->un_eof >= ST_EOM && (flag == B_WRITE)) {
2954 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
2955 			un->un_eof = ST_EOM;
2956 		} else if (uio->uio_resid == len) {
2957 			un->un_eof = ST_NO_EOF;
2958 		}
2959 	}
2960 
2961 	if (un->un_silent_skip && uio->uio_resid != len) {
2962 		un->un_eof = ST_EOF;
2963 		un->un_blkno = un->un_save_blkno;
2964 		un->un_fileno--;
2965 	}
2966 
2967 	un->un_errno = rval;
2968 
2969 	mutex_exit(ST_MUTEX);
2970 
2971 	return (rval);
2972 }
2973 
2974 static int
2975 st_arw(dev_t dev, struct aio_req *aio, int flag)
2976 {
2977 	struct uio *uio = aio->aio_uio;
2978 	int rval = 0;
2979 	long len;
2980 
2981 	GET_SOFT_STATE(dev);
2982 
2983 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2984 	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
2985 	    (flag == B_READ ? rd_str: wr_str));
2986 
2987 	/* get local copy of transfer length */
2988 	len = uio->uio_iov->iov_len;
2989 
2990 	mutex_enter(ST_MUTEX);
2991 
2992 	/*
2993 	 * If in fixed block size mode and requested read or write
2994 	 * is not an even multiple of that block size.
2995 	 */
2996 	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
2997 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
2998 		    "%s: not modulo %d block size\n",
2999 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3000 		rval = EINVAL;
3001 	}
3002 
3003 	/* If device has set granularity in the READ_BLKLIM we honor it. */
3004 	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3005 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3006 		    "%s: not modulo %d device granularity\n",
3007 		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3008 		rval = EINVAL;
3009 	}
3010 
3011 	if (rval != 0) {
3012 		un->un_errno = rval;
3013 		mutex_exit(ST_MUTEX);
3014 		return (rval);
3015 	}
3016 
3017 	mutex_exit(ST_MUTEX);
3018 
3019 	len = uio->uio_resid;
3020 
3021 	rval = aphysio(st_strategy, anocancel, dev, flag, st_minphys, aio);
3022 
3023 	/*
3024 	 * if we have hit logical EOT during this xfer and there is not a
3025 	 * full residue, then set un_eof back  to ST_EOM to make sure that
3026 	 * the user will see at least one zero write
3027 	 * after this short write
3028 	 *
3029 	 * we keep this here just in case the application is not using
3030 	 * persistent errors
3031 	 */
3032 	mutex_enter(ST_MUTEX);
3033 	if (un->un_eof > ST_NO_EOF) {
3034 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3035 		    "un_eof=%d resid=%lx\n", un->un_eof, uio->uio_resid);
3036 	}
3037 	if (un->un_eof >= ST_EOM && (flag == B_WRITE)) {
3038 		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3039 			un->un_eof = ST_EOM;
3040 		} else if (uio->uio_resid == len && !IS_PE_FLAG_SET(un)) {
3041 			un->un_eof = ST_NO_EOF;
3042 		}
3043 	}
3044 	un->un_errno = rval;
3045 	mutex_exit(ST_MUTEX);
3046 
3047 	return (rval);
3048 }
3049 
3050 
3051 
3052 static int
3053 st_strategy(struct buf *bp)
3054 {
3055 	struct scsi_tape *un;
3056 	dev_t dev = bp->b_edev;
3057 
3058 	/*
3059 	 * validate arguments
3060 	 */
3061 	if ((un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev))) == NULL) {
3062 		bp->b_resid = bp->b_bcount;
3063 		mutex_enter(ST_MUTEX);
3064 		st_bioerror(bp, ENXIO);
3065 		mutex_exit(ST_MUTEX);
3066 		goto error;
3067 	}
3068 
3069 	mutex_enter(ST_MUTEX);
3070 
3071 	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
3072 		cv_wait(&un->un_suspend_cv, ST_MUTEX);
3073 	}
3074 
3075 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3076 	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%lx, eof=%d\n",
3077 	    bp->b_bcount, un->un_fileno, un->un_blkno, un->un_eof);
3078 
3079 	/*
3080 	 * If persistent errors have been flagged, just nix this one. We wait
3081 	 * for any outstanding I/O's below, so we will be in order.
3082 	 */
3083 	if (IS_PE_FLAG_SET(un))
3084 		goto exit;
3085 
3086 	if (bp != un->un_sbufp) {
3087 		char reading = bp->b_flags & B_READ;
3088 		int wasopening = 0;
3089 
3090 		/*
3091 		 * If we haven't done/checked reservation on the tape unit
3092 		 * do it now.
3093 		 */
3094 		if (!(un->un_rsvd_status & ST_INIT_RESERVE)) {
3095 		    if (ST_RESERVE_SUPPORTED(un)) {
3096 				if (st_tape_reservation_init(dev)) {
3097 					st_bioerror(bp, un->un_errno);
3098 					goto exit;
3099 				}
3100 		    } else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3101 				/*
3102 				 * Enter here to restore position for possible
3103 				 * resets when the device was closed and opened
3104 				 * in O_NDELAY mode subsequently
3105 				 */
3106 				un->un_state = ST_STATE_INITIALIZING;
3107 				(void) st_cmd(dev, SCMD_TEST_UNIT_READY,
3108 				    0, SYNC_CMD);
3109 				un->un_state = ST_STATE_OPEN_PENDING_IO;
3110 			}
3111 		    un->un_rsvd_status |= ST_INIT_RESERVE;
3112 		}
3113 
3114 		/*
3115 		 * If we are offline, we have to initialize everything first.
3116 		 * This is to handle either when opened with O_NDELAY, or
3117 		 * we just got a new tape in the drive, after an offline.
3118 		 * We don't observe O_NDELAY past the open,
3119 		 * as it will not make sense for tapes.
3120 		 */
3121 		if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
3122 			/* reset state to avoid recursion */
3123 			un->un_state = ST_STATE_INITIALIZING;
3124 			if (st_tape_init(dev)) {
3125 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3126 					"stioctl : OFFLINE init failure ");
3127 				un->un_state = ST_STATE_OFFLINE;
3128 				un->un_fileno = -1;
3129 				goto b_done_err;
3130 			}
3131 			un->un_state = ST_STATE_OPEN_PENDING_IO;
3132 		}
3133 		/*
3134 		 * Check for legal operations
3135 		 */
3136 		if (un->un_fileno < 0) {
3137 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3138 			    "strategy with un->un_fileno < 0\n");
3139 			goto b_done_err;
3140 		}
3141 
3142 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3143 		    "st_strategy(): regular io\n");
3144 
3145 		/*
3146 		 * Process this first. If we were reading, and we're pending
3147 		 * logical eot, that means we've bumped one file mark too far.
3148 		 */
3149 
3150 		/*
3151 		 * Recursion warning: st_cmd will route back through here.
3152 		 */
3153 		if (un->un_eof == ST_EOT_PENDING) {
3154 			if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
3155 				un->un_fileno = -1;
3156 				un->un_density_known = 0;
3157 				goto b_done_err;
3158 			}
3159 			un->un_blkno = 0; /* fix up block number.. */
3160 			un->un_eof = ST_EOT;
3161 		}
3162 
3163 		/*
3164 		 * If we are in the process of opening, we may have to
3165 		 * determine/set the correct density. We also may have
3166 		 * to do a test_append (if QIC) to see whether we are
3167 		 * in a position to append to the end of the tape.
3168 		 *
3169 		 * If we're already at logical eot, we transition
3170 		 * to ST_NO_EOF. If we're at physical eot, we punt
3171 		 * to the switch statement below to handle.
3172 		 */
3173 		if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
3174 		    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
3175 
3176 			if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3177 				if (st_determine_density(dev, (int)reading)) {
3178 					goto b_done_err;
3179 				}
3180 			}
3181 
3182 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3183 			    "pending_io@fileno %d rw %d qic %d eof %d\n",
3184 			    un->un_fileno, (int)reading,
3185 			    (un->un_dp->options & ST_QIC) ? 1 : 0,
3186 			    un->un_eof);
3187 
3188 			if (!reading && un->un_eof != ST_EOM) {
3189 				if (un->un_eof == ST_EOT) {
3190 					un->un_eof = ST_NO_EOF;
3191 				} else if (un->un_fileno > 0 &&
3192 				    (un->un_dp->options & ST_QIC)) {
3193 					/*
3194 					 * st_test_append() will do it all
3195 					 */
3196 					st_test_append(bp);
3197 					goto done;
3198 				}
3199 			}
3200 			if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3201 				wasopening = 1;
3202 			}
3203 			un->un_laststate = un->un_state;
3204 			un->un_state = ST_STATE_OPEN;
3205 		}
3206 
3207 
3208 		/*
3209 		 * Process rest of END OF FILE and END OF TAPE conditions
3210 		 */
3211 
3212 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3213 		    "un_eof=%x, wasopening=%x\n",
3214 		    un->un_eof, wasopening);
3215 
3216 		switch (un->un_eof) {
3217 		case ST_EOM:
3218 			/*
3219 			 * This allows writes to proceed past physical
3220 			 * eot. We'll *really* be in trouble if the
3221 			 * user continues blindly writing data too
3222 			 * much past this point (unwind the tape).
3223 			 * Physical eot really means 'early warning
3224 			 * eot' in this context.
3225 			 *
3226 			 * Every other write from now on will succeed
3227 			 * (if sufficient  tape left).
3228 			 * This write will return with resid == count
3229 			 * but the next one should be successful
3230 			 *
3231 			 * Note that we only transition to logical EOT
3232 			 * if the last state wasn't the OPENING state.
3233 			 * We explicitly prohibit running up to physical
3234 			 * eot, closing the device, and then re-opening
3235 			 * to proceed. Trailer records may only be gotten
3236 			 * at by keeping the tape open after hitting eot.
3237 			 *
3238 			 * Also note that ST_EOM cannot be set by reading-
3239 			 * this can only be set during writing. Reading
3240 			 * up to the end of the tape gets a blank check
3241 			 * or a double-filemark indication (ST_EOT_PENDING),
3242 			 * and we prohibit reading after that point.
3243 			 *
3244 			 */
3245 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
3246 			if (wasopening == 0) {
3247 				/*
3248 				 * this allows st_rw() to reset it back to
3249 				 * ST_EOM to make sure that the application
3250 				 * will see a zero write
3251 				 */
3252 				un->un_eof = ST_WRITE_AFTER_EOM;
3253 			}
3254 			un->un_status = SUN_KEY_EOT;
3255 			goto b_done;
3256 
3257 		case ST_WRITE_AFTER_EOM:
3258 		case ST_EOT:
3259 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
3260 			un->un_status = SUN_KEY_EOT;
3261 			if (SVR4_BEHAVIOR && reading) {
3262 				goto b_done_err;
3263 			}
3264 
3265 			if (reading) {
3266 				goto b_done;
3267 			}
3268 			un->un_eof = ST_NO_EOF;
3269 			break;
3270 
3271 		case ST_EOF_PENDING:
3272 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3273 			    "EOF PENDING\n");
3274 			un->un_status = SUN_KEY_EOF;
3275 			if (SVR4_BEHAVIOR) {
3276 				un->un_eof = ST_EOF;
3277 				goto b_done;
3278 			}
3279 			/* FALLTHROUGH */
3280 		case ST_EOF:
3281 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
3282 			un->un_status = SUN_KEY_EOF;
3283 			if (SVR4_BEHAVIOR) {
3284 				goto b_done_err;
3285 			}
3286 
3287 			if (BSD_BEHAVIOR) {
3288 				un->un_eof = ST_NO_EOF;
3289 				un->un_fileno += 1;
3290 				un->un_blkno   = 0;
3291 			}
3292 
3293 			if (reading) {
3294 				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3295 				    "now file %d (read)\n",
3296 				    un->un_fileno);
3297 				goto b_done;
3298 			}
3299 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3300 			    "now file %d (write)\n", un->un_fileno);
3301 			break;
3302 		default:
3303 			un->un_status = 0;
3304 			break;
3305 		}
3306 	}
3307 
3308 	bp->b_flags &= ~(B_DONE);
3309 	st_bioerror(bp, 0);
3310 	bp->av_forw = NULL;
3311 	bp->b_resid = 0;
3312 	SET_BP_PKT(bp, 0);
3313 
3314 
3315 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3316 	    "st_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
3317 	    " pkt=0x%p\n",
3318 	    (void *)bp->b_forw, bp->b_bcount,
3319 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
3320 
3321 #if defined(__i386) || defined(__amd64)
3322 	/*
3323 	 * We will replace bp with a new bp that can do big blk xfer
3324 	 * if the requested xfer size is bigger than ST_BIGBLK_XFER
3325 	 */
3326 	if (bp->b_bcount > ST_BIGBLK_XFER) {
3327 		mutex_exit(ST_MUTEX);
3328 		bp = st_get_bigblk_bp(bp);
3329 		mutex_enter(ST_MUTEX);
3330 	}
3331 #endif
3332 
3333 	/* put on wait queue */
3334 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3335 	    "st_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
3336 	    (void *)un->un_quef, (void *)bp);
3337 
3338 	if (un->un_quef) {
3339 		un->un_quel->b_actf = bp;
3340 	} else {
3341 		un->un_quef = bp;
3342 	}
3343 	un->un_quel = bp;
3344 
3345 	ST_DO_KSTATS(bp, kstat_waitq_enter);
3346 
3347 	st_start(un);
3348 
3349 done:
3350 	mutex_exit(ST_MUTEX);
3351 	return (0);
3352 
3353 
3354 error:
3355 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3356 	    "st_strategy: error exit\n");
3357 
3358 	biodone(bp);
3359 	return (0);
3360 
3361 b_done_err:
3362 	st_bioerror(bp, EIO);
3363 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3364 	    "st_strategy : EIO b_done_err\n");
3365 
3366 b_done:
3367 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3368 	    "st_strategy: b_done\n");
3369 
3370 exit:
3371 	/*
3372 	 * make sure no commands are outstanding or waiting before closing,
3373 	 * so we can guarantee order
3374 	 */
3375 	st_wait_for_io(un);
3376 	un->un_err_resid = bp->b_resid = bp->b_bcount;
3377 
3378 	/* override errno here, if persistent errors were flagged */
3379 	if (IS_PE_FLAG_SET(un))
3380 		bioerror(bp, un->un_errno);
3381 
3382 	mutex_exit(ST_MUTEX);
3383 
3384 	biodone(bp);
3385 	ASSERT(mutex_owned(ST_MUTEX) == 0);
3386 	return (0);
3387 }
3388 
3389 
3390 
3391 /*
3392  * this routine spaces forward over filemarks
3393  */
3394 static int
3395 st_space_fmks(dev_t dev, int count)
3396 {
3397 	int rval = 0;
3398 
3399 	GET_SOFT_STATE(dev);
3400 
3401 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3402 	    "st_space_fmks(dev = 0x%lx, count = %d)\n", dev, count);
3403 
3404 	ASSERT(mutex_owned(ST_MUTEX));
3405 
3406 	/*
3407 	 * the risk with doing only one space operation is that we
3408 	 * may accidentily jump in old data
3409 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
3410 	 * because the 8200 does not append a marker; in order not to
3411 	 * sacrifice the fast file skip, we do a slow skip if the low
3412 	 * density device has been opened
3413 	 */
3414 
3415 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
3416 	    !((un->un_dp->type == ST_TYPE_EXB8500 && MT_DENSITY(dev) == 0))) {
3417 		if (st_cmd(dev, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
3418 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3419 			    "space_fmks : EIO can't do space cmd #1\n");
3420 			rval = EIO;
3421 		}
3422 	} else {
3423 		while (count > 0) {
3424 			if (st_cmd(dev, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3425 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3426 				    "space_fmks : EIO can't do space cmd #2\n");
3427 				rval = EIO;
3428 				break;
3429 			}
3430 			count -= 1;
3431 			/*
3432 			 * read a block to see if we have reached
3433 			 * end of medium (double filemark for reel or
3434 			 * medium error for others)
3435 			 */
3436 			if (count > 0) {
3437 				if (st_cmd(dev, SCMD_SPACE, Blk(1),
3438 				    SYNC_CMD)) {
3439 					ST_DEBUG2(ST_DEVINFO, st_label,
3440 					    SCSI_DEBUG,
3441 					    "space_fmks : EIO can't do "
3442 					    "space cmd #3\n");
3443 					rval = EIO;
3444 					break;
3445 				}
3446 				if ((un->un_eof >= ST_EOF_PENDING) &&
3447 				    (un->un_dp->options & ST_REEL)) {
3448 					un->un_status = SUN_KEY_EOT;
3449 					ST_DEBUG2(ST_DEVINFO, st_label,
3450 					    SCSI_DEBUG,
3451 					    "space_fmks : EIO ST_REEL\n");
3452 					rval = EIO;
3453 					break;
3454 				} else if (IN_EOF(un)) {
3455 					un->un_eof = ST_NO_EOF;
3456 					un->un_fileno++;
3457 					un->un_blkno = 0;
3458 					count--;
3459 				} else if (un->un_eof > ST_EOF) {
3460 					ST_DEBUG2(ST_DEVINFO, st_label,
3461 					    SCSI_DEBUG,
3462 					    "space_fmks, EIO > ST_EOF\n");
3463 					rval = EIO;
3464 					break;
3465 				}
3466 
3467 			}
3468 		}
3469 		un->un_err_resid = count;
3470 		un->un_err_fileno = un->un_fileno;
3471 		un->un_err_blkno = un->un_blkno;
3472 	}
3473 	ASSERT(mutex_owned(ST_MUTEX));
3474 	return (rval);
3475 }
3476 
3477 /*
3478  * this routine spaces to EOM
3479  *
3480  * it keeps track of the current filenumber and returns the filenumber after
3481  * the last successful space operation, we keep the number high because as
3482  * tapes are getting larger, the possibility of more and more files exist,
3483  * 0x100000 (1 Meg of files) probably will never have to be changed any time
3484  * soon
3485  */
3486 #define	MAX_SKIP	0x100000 /* somewhat arbitrary */
3487 
3488 static int
3489 st_find_eom(dev_t dev)
3490 {
3491 	int count, savefile;
3492 	struct scsi_tape *un;
3493 	int instance;
3494 
3495 	instance = MTUNIT(dev);
3496 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
3497 		return (-1);
3498 
3499 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3500 	    "st_find_eom(dev = 0x%lx): fileno = %d\n", dev, un->un_fileno);
3501 
3502 	ASSERT(mutex_owned(ST_MUTEX));
3503 
3504 	savefile = un->un_fileno;
3505 
3506 	/*
3507 	 * see if the drive is smart enough to do the skips in
3508 	 * one operation; 1/2" use two filemarks
3509 	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
3510 	 * because the 8200 does not append a marker; in order not to
3511 	 * sacrifice the fast file skip, we do a slow skip if the low
3512 	 * density device has been opened
3513 	 */
3514 	if ((un->un_dp->options & ST_KNOWS_EOD) &&
3515 	    !((un->un_dp->type == ST_TYPE_EXB8500 && MT_DENSITY(dev) == 0))) {
3516 		count = MAX_SKIP;
3517 	} else {
3518 		count = 1;
3519 	}
3520 
3521 	while (st_cmd(dev, SCMD_SPACE, Fmk(count), SYNC_CMD) == 0) {
3522 
3523 		savefile = un->un_fileno;
3524 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3525 			"count=%x, eof=%x, status=%x\n", count,  un->un_eof,
3526 			un->un_status);
3527 
3528 		/*
3529 		 * If we're not EOM smart,  space a record
3530 		 * to see whether we're now in the slot between
3531 		 * the two sequential filemarks that logical
3532 		 * EOM consists of (REEL) or hit nowhere land
3533 		 * (8mm).
3534 		 */
3535 		if (count == 1) {
3536 			/*
3537 			 * no fast skipping, check a record
3538 			 */
3539 			if (st_cmd(dev, SCMD_SPACE, Blk((1)), SYNC_CMD))
3540 				break;
3541 			else if ((un->un_eof >= ST_EOF_PENDING) &&
3542 			    (un->un_dp->options & ST_REEL)) {
3543 				un->un_status = KEY_BLANK_CHECK;
3544 				un->un_fileno++;
3545 				un->un_blkno = 0;
3546 				break;
3547 			} else if (IN_EOF(un)) {
3548 				un->un_eof = ST_NO_EOF;
3549 				un->un_fileno++;
3550 				un->un_blkno = 0;
3551 			} else if (un->un_eof > ST_EOF) {
3552 				break;
3553 			}
3554 		} else {
3555 			if (un->un_eof >  ST_EOF) {
3556 				break;
3557 			}
3558 		}
3559 	}
3560 
3561 	if (un->un_dp->options & ST_KNOWS_EOD) {
3562 		savefile = un->un_fileno;
3563 	}
3564 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3565 	    "st_find_eom: %x\n", savefile);
3566 	ASSERT(mutex_owned(ST_MUTEX));
3567 	return (savefile);
3568 }
3569 
3570 
3571 /*
3572  * this routine is frequently used in ioctls below;
3573  * it determines whether we know the density and if not will
3574  * determine it
3575  * if we have written the tape before, one or more filemarks are written
3576  *
3577  * depending on the stepflag, the head is repositioned to where it was before
3578  * the filemarks were written in order not to confuse step counts
3579  */
3580 #define	STEPBACK    0
3581 #define	NO_STEPBACK 1
3582 
3583 static int
3584 st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
3585 {
3586 
3587 	GET_SOFT_STATE(dev);
3588 
3589 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3590 	"st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)\n",
3591 	dev, wfm, mode, stepflag);
3592 
3593 	ASSERT(mutex_owned(ST_MUTEX));
3594 
3595 	/*
3596 	 * If we don't yet know the density of the tape we have inserted,
3597 	 * we have to either unconditionally set it (if we're 'writing'),
3598 	 * or we have to determine it. As side effects, check for any
3599 	 * write-protect errors, and for the need to put out any file-marks
3600 	 * before positioning a tape.
3601 	 *
3602 	 * If we are going to be spacing forward, and we haven't determined
3603 	 * the tape density yet, we have to do so now...
3604 	 */
3605 	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
3606 		if (st_determine_density(dev, mode)) {
3607 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3608 			    "check_density_or_wfm : EIO can't determine "
3609 			    "density\n");
3610 			un->un_errno = EIO;
3611 			return (EIO);
3612 		}
3613 		/*
3614 		 * Presumably we are at BOT. If we attempt to write, it will
3615 		 * either work okay, or bomb. We don't do a st_test_append
3616 		 * unless we're past BOT.
3617 		 */
3618 		un->un_laststate = un->un_state;
3619 		un->un_state = ST_STATE_OPEN;
3620 
3621 	} else if (un->un_fileno >= 0 && un->un_fmneeded > 0 &&
3622 	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
3623 	    (un->un_lastop == ST_OP_WRITE && wfm))) {
3624 
3625 		daddr_t blkno = un->un_blkno;
3626 		int fileno = un->un_fileno;
3627 
3628 		/*
3629 		 * We need to write one or two filemarks.
3630 		 * In the case of the HP, we need to
3631 		 * position the head between the two
3632 		 * marks.
3633 		 */
3634 		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
3635 			wfm = un->un_fmneeded;
3636 			un->un_fmneeded = 0;
3637 		}
3638 
3639 		if (st_write_fm(dev, wfm)) {
3640 			un->un_fileno = -1;
3641 			un->un_density_known = 0;
3642 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3643 			    "check_density_or_wfm : EIO can't write fm\n");
3644 			un->un_errno = EIO;
3645 			return (EIO);
3646 		}
3647 
3648 		if (stepflag == STEPBACK) {
3649 			if (st_cmd(dev, SCMD_SPACE, Fmk((-wfm)), SYNC_CMD)) {
3650 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3651 				    "check_density_or_wfm : EIO can't space "
3652 				    "(-wfm)\n");
3653 				un->un_errno = EIO;
3654 				return (EIO);
3655 			}
3656 			un->un_blkno = blkno;
3657 			un->un_fileno = fileno;
3658 		}
3659 	}
3660 
3661 	/*
3662 	 * Whatever we do at this point clears the state of the eof flag.
3663 	 */
3664 
3665 	un->un_eof = ST_NO_EOF;
3666 
3667 	/*
3668 	 * If writing, let's check that we're positioned correctly
3669 	 * at the end of tape before issuing the next write.
3670 	 */
3671 	if (!un->un_read_only) {
3672 		un->un_test_append = 1;
3673 	}
3674 
3675 	ASSERT(mutex_owned(ST_MUTEX));
3676 	return (0);
3677 }
3678 
3679 
3680 /*
3681  * Wait for all outstaning I/O's to complete
3682  *
3683  * we wait on both ncmds and the wait queue for times when we are flushing
3684  * after persistent errors are flagged, which is when ncmds can be 0, and the
3685  * queue can still have I/O's.  This way we preserve order of biodone's.
3686  */
3687 static void
3688 st_wait_for_io(struct scsi_tape *un)
3689 {
3690 	ASSERT(mutex_owned(ST_MUTEX));
3691 	while (un->un_ncmds || un->un_quef) {
3692 		cv_wait(&un->un_queue_cv, ST_MUTEX);
3693 	}
3694 }
3695 
3696 /*
3697  * This routine implements the ioctl calls.  It is called
3698  * from the device switch at normal priority.
3699  */
3700 /*ARGSUSED*/
3701 static int
3702 st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
3703     int *rval_p)
3704 {
3705 	int tmp, rval = 0;
3706 
3707 	GET_SOFT_STATE(dev);
3708 
3709 	mutex_enter(ST_MUTEX);
3710 
3711 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3712 	    "st_ioctl(): fileno=%x, blkno=%lx, un_eof=%x, state = %d, "
3713 	    "pe_flag = %d\n",
3714 	    un->un_fileno, un->un_blkno, un->un_eof, un->un_state,
3715 	    IS_PE_FLAG_SET(un));
3716 
3717 	/*
3718 	 * We don't want to block on these, so let them through
3719 	 * and we don't care about setting driver states here.
3720 	 */
3721 	if ((cmd == MTIOCGETDRIVETYPE) ||
3722 	    (cmd == MTIOCGUARANTEEDORDER) ||
3723 	    (cmd == MTIOCPERSISTENTSTATUS)) {
3724 		goto check_commands;
3725 	}
3726 
3727 	/*
3728 	 * wait for all outstanding commands to complete, or be dequeued.
3729 	 * And because ioctl's are synchronous commands, any return value
3730 	 * after this,  will be in order
3731 	 */
3732 	st_wait_for_io(un);
3733 
3734 	/*
3735 	 * allow only a through clear errors and persistent status, and
3736 	 * status
3737 	 */
3738 	if (IS_PE_FLAG_SET(un)) {
3739 		if ((cmd == MTIOCLRERR) ||
3740 		    (cmd == MTIOCPERSISTENT) ||
3741 		    (cmd == MTIOCGET) ||
3742 		    (cmd == USCSIGETRQS)) {
3743 			goto check_commands;
3744 		} else {
3745 			rval = un->un_errno;
3746 			goto exit;
3747 		}
3748 	}
3749 
3750 	un->un_throttle = 1;	/* > 1 will never happen here */
3751 	un->un_errno = 0;	/* start clean from here */
3752 
3753 	/*
3754 	 * first and foremost, handle any ST_EOT_PENDING cases.
3755 	 * That is, if a logical eot is pending notice, notice it.
3756 	 */
3757 	if (un->un_eof == ST_EOT_PENDING) {
3758 		int resid = un->un_err_resid;
3759 		uchar_t status = un->un_status;
3760 		uchar_t lastop = un->un_lastop;
3761 
3762 		if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)) {
3763 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3764 			    "stioctl : EIO can't space fmk(-1)\n");
3765 			rval = EIO;
3766 			goto exit;
3767 		}
3768 		un->un_lastop = lastop; /* restore last operation */
3769 		if (status == SUN_KEY_EOF) {
3770 			un->un_status = SUN_KEY_EOT;
3771 		} else {
3772 			un->un_status = status;
3773 		}
3774 		un->un_err_resid  = resid;
3775 		un->un_err_blkno = un->un_blkno = 0; /* fix up block number */
3776 		un->un_eof = ST_EOT;	/* now we're at logical eot */
3777 	}
3778 
3779 	/*
3780 	 * now, handle the rest of the situations
3781 	 */
3782 check_commands:
3783 	switch (cmd) {
3784 	case MTIOCGET:
3785 		{
3786 #ifdef _MULTI_DATAMODEL
3787 			/*
3788 			 * For use when a 32 bit app makes a call into a
3789 			 * 64 bit ioctl
3790 			 */
3791 			struct mtget32		mtg_local32;
3792 			struct mtget32 		*mtget_32 = &mtg_local32;
3793 #endif /* _MULTI_DATAMODEL */
3794 
3795 			/* Get tape status */
3796 			struct mtget mtg_local;
3797 			struct mtget *mtget = &mtg_local;
3798 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3799 				"st_ioctl: MTIOCGET\n");
3800 
3801 			bzero(mtget, sizeof (struct mtget));
3802 			mtget->mt_erreg = un->un_status;
3803 			mtget->mt_resid = un->un_err_resid;
3804 			mtget->mt_dsreg = un->un_retry_ct;
3805 			mtget->mt_fileno = un->un_err_fileno;
3806 			mtget->mt_blkno = un->un_err_blkno;
3807 			mtget->mt_type = un->un_dp->type;
3808 			mtget->mt_flags = MTF_SCSI | MTF_ASF;
3809 			if (un->un_dp->options & ST_REEL) {
3810 				mtget->mt_flags |= MTF_REEL;
3811 				mtget->mt_bf = 20;
3812 			} else {		/* 1/4" cartridges */
3813 				switch (mtget->mt_type) {
3814 				/* Emulex cartridge tape */
3815 				case MT_ISMT02:
3816 					mtget->mt_bf = 40;
3817 					break;
3818 				default:
3819 					mtget->mt_bf = 126;
3820 					break;
3821 				}
3822 			}
3823 
3824 			/*
3825 			 * If large transfers are allowed and drive options
3826 			 * has no record size limit set. Calculate blocking
3827 			 * factor from the lesser of maxbsize and maxdma.
3828 			 */
3829 			if ((un->un_allow_large_xfer) &&
3830 			    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
3831 				mtget->mt_bf = min(un->un_maxbsize,
3832 				    un->un_maxdma) / SECSIZE;
3833 			}
3834 
3835 			rval = st_check_clean_bit(dev);
3836 			if (rval == -1) {
3837 				rval = EIO;
3838 				goto exit;
3839 			} else {
3840 				mtget->mt_flags |= (ushort_t)rval;
3841 				rval = 0;
3842 			}
3843 
3844 			un->un_status = 0;		/* Reset status */
3845 			un->un_err_resid = 0;
3846 			tmp = sizeof (struct mtget);
3847 
3848 #ifdef _MULTI_DATAMODEL
3849 
3850 		switch (ddi_model_convert_from(flag & FMODELS)) {
3851 		case DDI_MODEL_ILP32:
3852 			/*
3853 			 * Convert 64 bit back to 32 bit before doing
3854 			 * copyout. This is what the ILP32 app expects.
3855 			 */
3856 			mtget_32->mt_erreg = 	mtget->mt_erreg;
3857 			mtget_32->mt_resid = 	mtget->mt_resid;
3858 			mtget_32->mt_dsreg = 	mtget->mt_dsreg;
3859 			mtget_32->mt_fileno = 	(daddr32_t)mtget->mt_fileno;
3860 			mtget_32->mt_blkno = 	(daddr32_t)mtget->mt_blkno;
3861 			mtget_32->mt_type =  	mtget->mt_type;
3862 			mtget_32->mt_flags = 	mtget->mt_flags;
3863 			mtget_32->mt_bf = 	mtget->mt_bf;
3864 
3865 			if (ddi_copyout(mtget_32, (void *)arg,
3866 			    sizeof (struct mtget32), flag)) {
3867 				rval = EFAULT;
3868 			}
3869 			break;
3870 
3871 		case DDI_MODEL_NONE:
3872 			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
3873 				rval = EFAULT;
3874 			}
3875 			break;
3876 		}
3877 #else /* ! _MULTI_DATAMODE */
3878 		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
3879 			rval = EFAULT;
3880 		}
3881 #endif /* _MULTI_DATAMODE */
3882 
3883 			break;
3884 		}
3885 	case MTIOCSTATE:
3886 		{
3887 			/*
3888 			 * return when media presence matches state
3889 			 */
3890 			enum mtio_state state;
3891 
3892 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3893 				"st_ioctl: MTIOCSTATE\n");
3894 
3895 			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
3896 				rval = EFAULT;
3897 
3898 			mutex_exit(ST_MUTEX);
3899 
3900 			rval = st_check_media(dev, state);
3901 
3902 			mutex_enter(ST_MUTEX);
3903 
3904 			if (rval != 0) {
3905 				break;
3906 			}
3907 
3908 			if (ddi_copyout(&un->un_mediastate, (void *)arg,
3909 			    sizeof (int), flag))
3910 				rval = EFAULT;
3911 			break;
3912 
3913 		}
3914 
3915 	case MTIOCGETDRIVETYPE:
3916 		{
3917 #ifdef _MULTI_DATAMODEL
3918 		/*
3919 		 * For use when a 32 bit app makes a call into a
3920 		 * 64 bit ioctl
3921 		 */
3922 		struct mtdrivetype_request32	mtdtrq32;
3923 #endif /* _MULTI_DATAMODEL */
3924 
3925 			/*
3926 			 * return mtdrivetype
3927 			 */
3928 			struct mtdrivetype_request mtdtrq;
3929 			struct mtdrivetype mtdrtyp;
3930 			struct mtdrivetype *mtdt = &mtdrtyp;
3931 			struct st_drivetype *stdt = un->un_dp;
3932 
3933 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3934 				"st_ioctl: MTIOCGETDRIVETYPE\n");
3935 
3936 #ifdef _MULTI_DATAMODEL
3937 		switch (ddi_model_convert_from(flag & FMODELS)) {
3938 		case DDI_MODEL_ILP32:
3939 		{
3940 			if (ddi_copyin((void *)arg, &mtdtrq32,
3941 			    sizeof (struct mtdrivetype_request32), flag)) {
3942 				rval = EFAULT;
3943 				break;
3944 			}
3945 			mtdtrq.size = mtdtrq32.size;
3946 			mtdtrq.mtdtp =
3947 			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
3948 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3949 				"st_ioctl: size 0x%x\n", mtdtrq.size);
3950 			break;
3951 		}
3952 		case DDI_MODEL_NONE:
3953 			if (ddi_copyin((void *)arg, &mtdtrq,
3954 			    sizeof (struct mtdrivetype_request), flag)) {
3955 				rval = EFAULT;
3956 				break;
3957 			}
3958 			break;
3959 		}
3960 
3961 #else /* ! _MULTI_DATAMODEL */
3962 		if (ddi_copyin((void *)arg, &mtdtrq,
3963 		    sizeof (struct mtdrivetype_request), flag)) {
3964 			rval = EFAULT;
3965 			break;
3966 		}
3967 #endif /* _MULTI_DATAMODEL */
3968 
3969 			/*
3970 			 * if requested size is < 0 then return
3971 			 * error.
3972 			 */
3973 			if (mtdtrq.size < 0) {
3974 				rval = EINVAL;
3975 				break;
3976 			}
3977 			bzero(mtdt, sizeof (struct mtdrivetype));
3978 			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
3979 			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
3980 			mtdt->type = stdt->type;
3981 			mtdt->bsize = stdt->bsize;
3982 			mtdt->options = stdt->options;
3983 			mtdt->max_rretries = stdt->max_rretries;
3984 			mtdt->max_wretries = stdt->max_wretries;
3985 			for (tmp = 0; tmp < NDENSITIES; tmp++)
3986 				mtdt->densities[tmp] = stdt->densities[tmp];
3987 			mtdt->default_density = stdt->default_density;
3988 			/*
3989 			 * Speed hasn't been used since the hayday of reel tape.
3990 			 * For all drives not setting the option ST_KNOWS_MEDIA
3991 			 * the speed member renamed to mediatype are zeros.
3992 			 * Those drives that have ST_KNOWS_MEDIA set use the
3993 			 * new mediatype member which is used to figure the
3994 			 * type of media loaded.
3995 			 *
3996 			 * So as to not break applications speed in the
3997 			 * mtdrivetype structure is not renamed.
3998 			 */
3999 			for (tmp = 0; tmp < NDENSITIES; tmp++) {
4000 				mtdt->speeds[tmp] = stdt->mediatype[tmp];
4001 			}
4002 			mtdt->non_motion_timeout = stdt->non_motion_timeout;
4003 			mtdt->io_timeout = stdt->io_timeout;
4004 			mtdt->rewind_timeout = stdt->rewind_timeout;
4005 			mtdt->space_timeout = stdt->space_timeout;
4006 			mtdt->load_timeout = stdt->load_timeout;
4007 			mtdt->unload_timeout = stdt->unload_timeout;
4008 			mtdt->erase_timeout = stdt->erase_timeout;
4009 
4010 			/*
4011 			 * Limit the maximum length of the result to
4012 			 * sizeof (struct mtdrivetype).
4013 			 */
4014 			tmp = sizeof (struct mtdrivetype);
4015 			if (mtdtrq.size < tmp)
4016 				tmp = mtdtrq.size;
4017 			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
4018 				rval = EFAULT;
4019 			}
4020 			break;
4021 		}
4022 	case MTIOCPERSISTENT:
4023 		{
4024 			int persistence = 0;
4025 
4026 			if (ddi_copyin((void *)arg, &persistence,
4027 			    sizeof (int), flag)) {
4028 				rval = EFAULT;
4029 				break;
4030 			}
4031 
4032 			/* non zero sets it, only 0 turns it off */
4033 			un->un_persistence = (uchar_t)persistence ? 1 : 0;
4034 
4035 			if (un->un_persistence)
4036 				TURN_PE_ON(un);
4037 			else
4038 				TURN_PE_OFF(un);
4039 
4040 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4041 			    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
4042 			    un->un_persistence);
4043 
4044 			break;
4045 		}
4046 	case MTIOCPERSISTENTSTATUS:
4047 		{
4048 			int persistence = (int)un->un_persistence;
4049 
4050 			if (ddi_copyout(&persistence, (void *)arg,
4051 			    sizeof (int), flag)) {
4052 				rval = EFAULT;
4053 			}
4054 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4055 			    "st_ioctl: MTIOCPERSISTENTSTATUS:persistece = %d\n",
4056 			    un->un_persistence);
4057 
4058 			break;
4059 		}
4060 
4061 
4062 	case MTIOCLRERR:
4063 		{
4064 			/* clear persistent errors */
4065 
4066 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4067 			    "st_ioctl: MTIOCLRERR\n");
4068 
4069 			CLEAR_PE(un);
4070 
4071 			break;
4072 		}
4073 
4074 	case MTIOCGUARANTEEDORDER:
4075 		{
4076 			/*
4077 			 * this is just a holder to make a valid ioctl and
4078 			 * it won't be in any earlier release
4079 			 */
4080 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4081 			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
4082 
4083 			break;
4084 		}
4085 
4086 	case MTIOCRESERVE:
4087 		{
4088 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4089 			    "st_ioctl: MTIOCRESERVE\n");
4090 
4091 			/*
4092 			 * Check if Reserve/Release is supported.
4093 			 */
4094 			if (!(ST_RESERVE_SUPPORTED(un))) {
4095 				rval = ENOTTY;
4096 				break;
4097 			}
4098 
4099 			rval = st_reserve_release(dev, ST_RESERVE);
4100 
4101 			if (rval == 0) {
4102 				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
4103 			}
4104 			break;
4105 		}
4106 
4107 	case MTIOCRELEASE:
4108 		{
4109 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4110 			    "st_ioctl: MTIOCRELEASE\n");
4111 
4112 			/*
4113 			 * Check if Reserve/Release is supported.
4114 			 */
4115 			if (!(ST_RESERVE_SUPPORTED(un))) {
4116 				rval = ENOTTY;
4117 				break;
4118 			}
4119 
4120 			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
4121 
4122 			break;
4123 		}
4124 
4125 	case MTIOCFORCERESERVE:
4126 		{
4127 			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4128 			    "st_ioctl: MTIOCFORCERESERVE\n");
4129 
4130 			/*
4131 			 * Check if Reserve/Release is supported.
4132 			 */
4133 			if (!(ST_RESERVE_SUPPORTED(un))) {
4134 				rval = ENOTTY;
4135 				break;
4136 			}
4137 			/*
4138 			 * allow only super user to run this.
4139 			 */
4140 			if (drv_priv(cred_p) != 0) {
4141 				rval = EPERM;
4142 				break;
4143 			}
4144 			/*
4145 			 * Throw away reserve,
4146 			 * not using test-unit-ready
4147 			 * since reserve can succeed without tape being
4148 			 * present in the drive.
4149 			 */
4150 			(void) st_reserve_release(dev, ST_RESERVE);
4151 
4152 			rval = st_take_ownership(dev);
4153 
4154 			break;
4155 		}
4156 	case USCSIGETRQS:
4157 		{
4158 #ifdef _MULTI_DATAMODEL
4159 		/*
4160 		 * For use when a 32 bit app makes a call into a
4161 		 * 64 bit ioctl
4162 		 */
4163 		struct uscsi_rqs32	urqs_32;
4164 		struct uscsi_rqs32	*urqs_32_ptr = &urqs_32;
4165 #endif /* _MULTI_DATAMODEL */
4166 			struct uscsi_rqs	urqs;
4167 			struct uscsi_rqs	*urqs_ptr = &urqs;
4168 			ushort_t		len;
4169 #ifdef _MULTI_DATAMODEL
4170 		switch (ddi_model_convert_from(flag & FMODELS)) {
4171 		case DDI_MODEL_ILP32:
4172 		{
4173 			if (ddi_copyin((void *)arg, urqs_32_ptr,
4174 			    sizeof (struct uscsi_rqs32), flag)) {
4175 				rval = EFAULT;
4176 				break;
4177 			}
4178 			urqs_ptr->rqs_buflen = urqs_32_ptr->rqs_buflen;
4179 			urqs_ptr->rqs_bufaddr =
4180 			    (caddr_t)(uintptr_t)urqs_32_ptr->rqs_bufaddr;
4181 			break;
4182 		}
4183 		case DDI_MODEL_NONE:
4184 			if (ddi_copyin((void *)arg, urqs_ptr,
4185 			    sizeof (struct uscsi_rqs), flag)) {
4186 				rval = EFAULT;
4187 				break;
4188 			}
4189 		}
4190 #else /* ! _MULTI_DATAMODEL */
4191 		if (ddi_copyin((void *)arg, urqs_ptr, sizeof (urqs), flag)) {
4192 			rval = EFAULT;
4193 			break;
4194 		}
4195 #endif /* _MULTI_DATAMODEL */
4196 
4197 			urqs_ptr->rqs_flags = (int)un->un_rqs_state &
4198 			    (ST_RQS_OVR | ST_RQS_VALID);
4199 			if (urqs_ptr->rqs_buflen <= SENSE_LENGTH) {
4200 			    len = urqs_ptr->rqs_buflen;
4201 			    urqs_ptr->rqs_resid = 0;
4202 			} else {
4203 			    len = SENSE_LENGTH;
4204 			    urqs_ptr->rqs_resid = urqs_ptr->rqs_buflen
4205 				    - SENSE_LENGTH;
4206 			}
4207 			if (!(un->un_rqs_state & ST_RQS_VALID)) {
4208 			    urqs_ptr->rqs_resid = urqs_ptr->rqs_buflen;
4209 			}
4210 			un->un_rqs_state |= ST_RQS_READ;
4211 			un->un_rqs_state &= ~(ST_RQS_OVR);
4212 
4213 #ifdef _MULTI_DATAMODEL
4214 		switch (ddi_model_convert_from(flag & FMODELS)) {
4215 		case DDI_MODEL_ILP32:
4216 			urqs_32_ptr->rqs_flags = urqs_ptr->rqs_flags;
4217 			urqs_32_ptr->rqs_resid = urqs_ptr->rqs_resid;
4218 			if (ddi_copyout(&urqs_32, (void *)arg,
4219 			    sizeof (urqs_32), flag)) {
4220 				rval = EFAULT;
4221 			}
4222 			break;
4223 		case DDI_MODEL_NONE:
4224 			if (ddi_copyout(&urqs, (void *)arg, sizeof (urqs),
4225 			    flag)) {
4226 				rval = EFAULT;
4227 			}
4228 			break;
4229 		}
4230 
4231 		if (un->un_rqs_state & ST_RQS_VALID) {
4232 			if (ddi_copyout(un->un_uscsi_rqs_buf,
4233 			    urqs_ptr->rqs_bufaddr, len, flag)) {
4234 				rval = EFAULT;
4235 		    }
4236 		}
4237 #else /* ! _MULTI_DATAMODEL */
4238 		if (ddi_copyout(&urqs, (void *)arg, sizeof (urqs), flag)) {
4239 			rval = EFAULT;
4240 		}
4241 		if (un->un_rqs_state & ST_RQS_VALID) {
4242 			if (ddi_copyout(un->un_uscsi_rqs_buf,
4243 			    urqs_ptr->rqs_bufaddr, len, flag)) {
4244 				rval = EFAULT;
4245 		    }
4246 		}
4247 #endif /* _MULTI_DATAMODEL */
4248 			break;
4249 		}
4250 
4251 	case USCSICMD:
4252 		{
4253 		cred_t	*cr;
4254 #ifdef _MULTI_DATAMODEL
4255 		/*
4256 		 * For use when a 32 bit app makes a call into a
4257 		 * 64 bit ioctl
4258 		 */
4259 		struct uscsi_cmd32	ucmd_32;
4260 		struct uscsi_cmd32	*ucmd_32_ptr = &ucmd_32;
4261 #endif /* _MULTI_DATAMODEL */
4262 
4263 			/*
4264 			 * Run a generic USCSI command
4265 			 */
4266 			struct uscsi_cmd ucmd;
4267 			struct uscsi_cmd *ucmd_ptr = &ucmd;
4268 			enum uio_seg uioseg;
4269 
4270 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4271 				"st_ioctl: USCSICMD\n");
4272 
4273 			cr = ddi_get_cred();
4274 			if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
4275 				rval = EPERM;
4276 				break;
4277 			}
4278 
4279 #ifdef _MULTI_DATAMODEL
4280 		switch (ddi_model_convert_from(flag & FMODELS)) {
4281 		case DDI_MODEL_ILP32:
4282 		{
4283 			if (ddi_copyin((void *)arg, ucmd_32_ptr,
4284 			    sizeof (struct uscsi_cmd32), flag)) {
4285 				rval = EFAULT;
4286 				break;
4287 			}
4288 			uscsi_cmd32touscsi_cmd(ucmd_32_ptr, ucmd_ptr);
4289 			break;
4290 		}
4291 		case DDI_MODEL_NONE:
4292 			if (ddi_copyin((void *)arg, ucmd_ptr, sizeof (ucmd),
4293 			    flag)) {
4294 				rval = EFAULT;
4295 				break;
4296 			}
4297 		}
4298 
4299 #else /* ! _MULTI_DATAMODEL */
4300 		if (ddi_copyin((void *)arg, ucmd_ptr, sizeof (ucmd), flag)) {
4301 			rval = EFAULT;
4302 			break;
4303 		}
4304 #endif /* _MULTI_DATAMODEL */
4305 
4306 
4307 			/*
4308 			 * If we haven't done/checked reservation on the
4309 			 * tape unit do it now.
4310 			 */
4311 			if (ST_RESERVE_SUPPORTED(un) &&
4312 				!(un->un_rsvd_status & ST_INIT_RESERVE)) {
4313 				if (rval = st_tape_reservation_init(dev))
4314 					goto exit;
4315 			}
4316 
4317 			/*
4318 			 * although st_ioctl_cmd() never makes use of these
4319 			 * now, we are just being safe and consistent
4320 			 */
4321 			ucmd.uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
4322 			    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
4323 
4324 
4325 			uioseg = (flag & FKIOCTL) ?
4326 			    UIO_SYSSPACE : UIO_USERSPACE;
4327 
4328 			rval = st_ioctl_cmd(dev, &ucmd, uioseg, uioseg, uioseg);
4329 
4330 
4331 #ifdef _MULTI_DATAMODEL
4332 		switch (ddi_model_convert_from(flag & FMODELS)) {
4333 		case DDI_MODEL_ILP32:
4334 			/*
4335 			 * Convert 64 bit back to 32 bit before doing
4336 			 * copyout. This is what the ILP32 app expects.
4337 			 */
4338 			uscsi_cmdtouscsi_cmd32(ucmd_ptr, ucmd_32_ptr);
4339 
4340 			if (ddi_copyout(&ucmd_32, (void *)arg,
4341 			    sizeof (ucmd_32), flag)) {
4342 				if (rval != 0)
4343 					rval = EFAULT;
4344 				}
4345 			break;
4346 
4347 		case DDI_MODEL_NONE:
4348 			if (ddi_copyout(&ucmd, (void *)arg,
4349 			    sizeof (ucmd), flag)) {
4350 				if (rval != 0)
4351 					rval = EFAULT;
4352 				}
4353 			break;
4354 		}
4355 #else /* ! _MULTI_DATAMODEL */
4356 		if (ddi_copyout(&ucmd, (void *)arg, sizeof (ucmd), flag)) {
4357 			if (rval != 0)
4358 				rval = EFAULT;
4359 		}
4360 #endif /* _MULTI_DATAMODEL */
4361 
4362 			break;
4363 		}
4364 
4365 	case MTIOCTOP:
4366 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4367 			"st_ioctl: MTIOCTOP\n");
4368 		rval = st_mtioctop(un, arg, flag);
4369 		break;
4370 
4371 	case MTIOCREADIGNOREILI:
4372 		{
4373 			int set_ili;
4374 
4375 			if (ddi_copyin((void *)arg, &set_ili,
4376 			    sizeof (set_ili), flag)) {
4377 				rval = EFAULT;
4378 				break;
4379 			}
4380 
4381 			if (un->un_bsize) {
4382 				rval = ENOTTY;
4383 				break;
4384 			}
4385 
4386 			switch (set_ili) {
4387 			case 0:
4388 				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
4389 				break;
4390 
4391 			case 1:
4392 				un->un_dp->options |= ST_READ_IGNORE_ILI;
4393 				break;
4394 
4395 			default:
4396 				rval = EINVAL;
4397 				break;
4398 			}
4399 			break;
4400 		}
4401 
4402 	case MTIOCREADIGNOREEOFS:
4403 		{
4404 			int ignore_eof;
4405 
4406 			if (ddi_copyin((void *)arg, &ignore_eof,
4407 			    sizeof (ignore_eof), flag)) {
4408 				rval = EFAULT;
4409 				break;
4410 			}
4411 
4412 			if (!(un->un_dp->options & ST_REEL)) {
4413 				rval = ENOTTY;
4414 				break;
4415 			}
4416 
4417 			switch (ignore_eof) {
4418 			case 0:
4419 				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
4420 				break;
4421 
4422 			case 1:
4423 				un->un_dp->options |= ST_READ_IGNORE_EOFS;
4424 				break;
4425 
4426 			default:
4427 				rval = EINVAL;
4428 				break;
4429 			}
4430 			break;
4431 		}
4432 
4433 	case MTIOCSHORTFMK:
4434 		{
4435 			int short_fmk;
4436 
4437 			if (ddi_copyin((void *)arg, &short_fmk,
4438 			    sizeof (short_fmk), flag)) {
4439 				rval = EFAULT;
4440 				break;
4441 			}
4442 
4443 			switch (un->un_dp->type) {
4444 			case ST_TYPE_EXB8500:
4445 			case ST_TYPE_EXABYTE:
4446 				if (!short_fmk) {
4447 					un->un_dp->options &=
4448 						~ST_SHORT_FILEMARKS;
4449 				} else if (short_fmk == 1) {
4450 					un->un_dp->options |=
4451 						ST_SHORT_FILEMARKS;
4452 				} else {
4453 					rval = EINVAL;
4454 				}
4455 				break;
4456 
4457 			default:
4458 				rval = ENOTTY;
4459 				break;
4460 			}
4461 			break;
4462 		}
4463 
4464 	default:
4465 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4466 			"st_ioctl: unknown ioctl\n");
4467 		rval = ENOTTY;
4468 	}
4469 
4470 exit:
4471 	if (!IS_PE_FLAG_SET(un))
4472 		un->un_errno = rval;
4473 
4474 	mutex_exit(ST_MUTEX);
4475 
4476 	return (rval);
4477 }
4478 
4479 
4480 /*
4481  * do some MTIOCTOP tape operations
4482  */
4483 static int
4484 st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
4485 {
4486 	struct mtop *mtop, local;
4487 	int savefile, tmp, rval = 0;
4488 	dev_t dev = un->un_dev;
4489 #ifdef _MULTI_DATAMODEL
4490 	/*
4491 	 * For use when a 32 bit app makes a call into a
4492 	 * 64 bit ioctl
4493 	 */
4494 	struct mtop32	mtop_32_for_64;
4495 #endif /* _MULTI_DATAMODEL */
4496 
4497 
4498 	ASSERT(mutex_owned(ST_MUTEX));
4499 
4500 	mtop = &local;
4501 #ifdef _MULTI_DATAMODEL
4502 		switch (ddi_model_convert_from(flag & FMODELS)) {
4503 		case DDI_MODEL_ILP32:
4504 		{
4505 			if (ddi_copyin((void *)arg, &mtop_32_for_64,
4506 			    sizeof (struct mtop32), flag)) {
4507 				return (EFAULT);
4508 			}
4509 			mtop->mt_op = mtop_32_for_64.mt_op;
4510 			mtop->mt_count =  (daddr_t)mtop_32_for_64.mt_count;
4511 			break;
4512 		}
4513 		case DDI_MODEL_NONE:
4514 			if (ddi_copyin((void *)arg, mtop,
4515 			    sizeof (struct mtop), flag)) {
4516 				return (EFAULT);
4517 			}
4518 			break;
4519 		}
4520 
4521 #else /* ! _MULTI_DATAMODEL */
4522 		if (ddi_copyin((void *)arg, mtop, sizeof (struct mtop), flag)) {
4523 			return (EFAULT);
4524 		}
4525 #endif /* _MULTI_DATAMODEL */
4526 
4527 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4528 	    "st_mtioctop(): mt_op=%x\n", mtop->mt_op);
4529 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4530 	    "fileno=%x, blkno=%lx, un_eof=%x\n", un->un_fileno, un->un_blkno,
4531 	    un->un_eof);
4532 
4533 	rval = 0;
4534 	un->un_status = 0;
4535 
4536 	/*
4537 	 * If we haven't done/checked reservation on the tape unit
4538 	 * do it now.
4539 	 */
4540 	if (ST_RESERVE_SUPPORTED(un) &&
4541 		!(un->un_rsvd_status & ST_INIT_RESERVE)) {
4542 		if (rval = st_tape_reservation_init(dev))
4543 			return (rval);
4544 	}
4545 	/*
4546 	 * if we are going to mess with a tape, we have to make sure we have
4547 	 * one and are not offline (i.e. no tape is initialized).  We let
4548 	 * commands pass here that don't actually touch the tape, except for
4549 	 * loading and initialization (rewinding).
4550 	 */
4551 	if (un->un_state == ST_STATE_OFFLINE) {
4552 		switch (mtop->mt_op) {
4553 		case MTLOAD:
4554 		case MTNOP:
4555 			/*
4556 			 * We don't want strategy calling st_tape_init here,
4557 			 * so, change state
4558 			 */
4559 			un->un_state = ST_STATE_INITIALIZING;
4560 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4561 			    "st_mtioctop : OFFLINE state = %d\n",
4562 			    un->un_state);
4563 			break;
4564 		default:
4565 			/*
4566 			 * reinitialize by normal means
4567 			 */
4568 			if (st_tape_init(dev)) {
4569 				un->un_state = ST_STATE_INITIALIZING;
4570 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4571 				    "st_mtioctop : OFFLINE init failure ");
4572 				un->un_state = ST_STATE_OFFLINE;
4573 				un->un_fileno = -1;
4574 				return (EIO);
4575 			}
4576 			un->un_state = ST_STATE_OPEN_PENDING_IO;
4577 			break;
4578 		}
4579 	}
4580 
4581 	/*
4582 	 * If the file position is invalid, allow only those
4583 	 * commands that properly position the tape and fail
4584 	 * the rest with EIO
4585 	 */
4586 	if (un->un_fileno < 0) {
4587 		switch (mtop->mt_op) {
4588 		case MTWEOF:
4589 		case MTRETEN:
4590 		case MTERASE:
4591 		case MTEOM:
4592 		case MTFSF:
4593 		case MTFSR:
4594 		case MTBSF:
4595 		case MTNBSF:
4596 		case MTBSR:
4597 		case MTSRSZ:
4598 		case MTGRSZ:
4599 			return (EIO);
4600 			/* NOTREACHED */
4601 		case MTREW:
4602 		case MTLOAD:
4603 		case MTOFFL:
4604 		case MTNOP:
4605 			break;
4606 
4607 		default:
4608 			return (ENOTTY);
4609 			/* NOTREACHED */
4610 		}
4611 	}
4612 
4613 	switch (mtop->mt_op) {
4614 	case MTERASE:
4615 		/*
4616 		 * MTERASE rewinds the tape, erase it completely, and returns
4617 		 * to the beginning of the tape
4618 		 */
4619 		if (un->un_dp->options & ST_REEL)
4620 			un->un_fmneeded = 2;
4621 
4622 		if (un->un_mspl->wp || un->un_read_only) {
4623 			un->un_status = KEY_WRITE_PROTECT;
4624 			un->un_err_resid = mtop->mt_count;
4625 			un->un_err_fileno = un->un_fileno;
4626 			un->un_err_blkno = un->un_blkno;
4627 			return (EACCES);
4628 		}
4629 		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
4630 		    st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD) ||
4631 		    st_cmd(dev, SCMD_ERASE, 0, SYNC_CMD)) {
4632 			un->un_fileno = -1;
4633 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4634 			    "st_mtioctop : EIO space or erase or check den)\n");
4635 			rval = EIO;
4636 		} else {
4637 			/* QIC and helical scan rewind after erase */
4638 			if (un->un_dp->options & ST_REEL) {
4639 				(void) st_cmd(dev, SCMD_REWIND, 0, ASYNC_CMD);
4640 			}
4641 		}
4642 		break;
4643 
4644 	case MTWEOF:
4645 		/*
4646 		 * write an end-of-file record
4647 		 */
4648 		if (un->un_mspl->wp || un->un_read_only) {
4649 			un->un_status = KEY_WRITE_PROTECT;
4650 			un->un_err_resid = mtop->mt_count;
4651 			un->un_err_fileno = un->un_fileno;
4652 			un->un_err_blkno = un->un_blkno;
4653 			return (EACCES);
4654 		}
4655 
4656 		/*
4657 		 * zero count means just flush buffers
4658 		 * negative count is not permitted
4659 		 */
4660 		if (mtop->mt_count < 0)
4661 			return (EINVAL);
4662 
4663 		if (!un->un_read_only) {
4664 			un->un_test_append = 1;
4665 		}
4666 
4667 		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4668 			if (st_determine_density(dev, B_WRITE)) {
4669 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4670 				    "st_mtioctop : EIO : MTWEOF can't determine"
4671 				    "density");
4672 				return (EIO);
4673 			}
4674 		}
4675 
4676 		if (st_write_fm(dev, (int)mtop->mt_count)) {
4677 			/*
4678 			 * Failure due to something other than illegal
4679 			 * request results in loss of state (st_intr).
4680 			 */
4681 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4682 			    "st_mtioctop : EIO : MTWEOF can't write file mark");
4683 			rval = EIO;
4684 		}
4685 		break;
4686 
4687 	case MTRETEN:
4688 		/*
4689 		 * retension the tape
4690 		 */
4691 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
4692 		    st_cmd(dev, SCMD_LOAD, 3, SYNC_CMD)) {
4693 			un->un_fileno = -1;
4694 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4695 			    "st_mtioctop : EIO : MTRETEN ");
4696 			rval = EIO;
4697 		}
4698 		break;
4699 
4700 	case MTREW:
4701 		/*
4702 		 * rewind  the tape
4703 		 */
4704 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
4705 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4706 			    "st_mtioctop : EIO:MTREW check density/wfm failed");
4707 			return (EIO);
4708 		}
4709 		if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD)) {
4710 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4711 			    "st_mtioctop : EIO : MTREW ");
4712 			rval = EIO;
4713 		}
4714 		break;
4715 
4716 	case MTOFFL:
4717 		/*
4718 		 * rewinds, and, if appropriate, takes the device offline by
4719 		 * unloading the tape
4720 		 */
4721 		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
4722 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4723 			    "st_mtioctop :EIO:MTOFFL check density/wfm failed");
4724 			return (EIO);
4725 		}
4726 		(void) st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
4727 		if (st_cmd(dev, SCMD_LOAD, 0, SYNC_CMD)) {
4728 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4729 			    "st_mtioctop : EIO : MTOFFL");
4730 			return (EIO);
4731 		}
4732 		un->un_eof = ST_NO_EOF;
4733 		un->un_laststate = un->un_state;
4734 		un->un_state = ST_STATE_OFFLINE;
4735 		un->un_mediastate = MTIO_EJECTED;
4736 		break;
4737 
4738 	case MTLOAD:
4739 		/*
4740 		 * This is to load a tape into the drive
4741 		 * Note that if the tape is not loaded, the device will have
4742 		 * to be opened via O_NDELAY or O_NONBLOCK.
4743 		 */
4744 		/*
4745 		 * Let's try and clean things up, if we are not
4746 		 * initializing, and then send in the load command, no
4747 		 * matter what.
4748 		 *
4749 		 * we try the load twice because some drives fail the first
4750 		 * load after a media change by the user.
4751 		 */
4752 
4753 		if (un->un_state > ST_STATE_INITIALIZING)
4754 			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
4755 
4756 		if (st_cmd(dev, SCMD_LOAD, 1, SYNC_CMD) &&
4757 		    st_cmd(dev, SCMD_LOAD, 1, SYNC_CMD)) {
4758 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4759 			    "st_mtioctop : EIO : MTLOAD\n");
4760 			rval = EIO;
4761 
4762 			/*
4763 			 * If load tape fails, who knows what happened...
4764 			 */
4765 			un->un_fileno = -1;
4766 			rval = EIO;
4767 			break;
4768 		}
4769 
4770 		/*
4771 		 * reset all counters appropriately using rewind, as if LOAD
4772 		 * succeeds, we are at BOT
4773 		 */
4774 		un->un_state = ST_STATE_INITIALIZING;
4775 
4776 		if (st_tape_init(dev)) {
4777 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4778 			    "st_mtioctop : EIO : MTLOAD calls st_tape_init\n");
4779 			rval = EIO;
4780 			un->un_state = ST_STATE_OFFLINE;
4781 		}
4782 
4783 		break;
4784 
4785 	case MTNOP:
4786 		un->un_status = 0;		/* Reset status */
4787 		un->un_err_resid = 0;
4788 		break;
4789 
4790 	case MTEOM:
4791 		/*
4792 		 * positions the tape at a location just after the last file
4793 		 * written on the tape. For cartridge and 8 mm, this after
4794 		 * the last file mark; for reel, this is inbetween the two
4795 		 * last 2 file marks
4796 		 */
4797 		if ((un->un_eof >= ST_EOT) ||
4798 		    (un->un_lastop == ST_OP_WRITE) ||
4799 		    (un->un_lastop == ST_OP_WEOF)) {
4800 			/*
4801 			 * If the command wants to move to logical end
4802 			 * of media, and we're already there, we're done.
4803 			 * If we were at logical eot, we reset the state
4804 			 * to be *not* at logical eot.
4805 			 *
4806 			 * If we're at physical or logical eot, we prohibit
4807 			 * forward space operations (unconditionally).
4808 			 *
4809 			 * Also if the last operation was a write of any
4810 			 * kind the tape is at EOD.
4811 			 */
4812 			return (0);
4813 		}
4814 		/*
4815 		 * physical tape position may not be what we've been
4816 		 * telling the user; adjust the request accordingly
4817 		 */
4818 		if (IN_EOF(un)) {
4819 			un->un_fileno++;
4820 			un->un_blkno = 0;
4821 		}
4822 
4823 		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
4824 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4825 			    "st_mtioctop : EIO:MTEOM check density/wfm failed");
4826 			return (EIO);
4827 		}
4828 
4829 		/*
4830 		 * st_find_eom() returns the last fileno we knew about;
4831 		 */
4832 		savefile = st_find_eom(dev);
4833 
4834 		if ((un->un_status != KEY_BLANK_CHECK) &&
4835 		    (un->un_status != SUN_KEY_EOT)) {
4836 			un->un_fileno = -1;
4837 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4838 			    "st_mtioctop : EIO : MTEOM status check failed");
4839 			rval = EIO;
4840 		} else {
4841 			/*
4842 			 * For 1/2" reel tapes assume logical EOT marked
4843 			 * by two file marks or we don't care that we may
4844 			 * be extending the last file on the tape.
4845 			 */
4846 			if (un->un_dp->options & ST_REEL) {
4847 				if (st_cmd(dev, SCMD_SPACE, Fmk((-1)),
4848 				    SYNC_CMD)) {
4849 					un->un_fileno = -1;
4850 					ST_DEBUG2(ST_DEVINFO, st_label,
4851 					    SCSI_DEBUG,
4852 					    "st_mtioctop : EIO : MTEOM space "
4853 					    "cmd failed");
4854 					rval = EIO;
4855 					break;
4856 				}
4857 				/*
4858 				 * Fix up the block number.
4859 				 */
4860 				un->un_blkno = 0;
4861 				un->un_err_blkno = 0;
4862 			}
4863 			un->un_err_resid = 0;
4864 			un->un_fileno = savefile;
4865 			un->un_eof = ST_EOT;
4866 		}
4867 		un->un_status = 0;
4868 		break;
4869 
4870 	case MTFSF:
4871 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4872 		    "fsf: count=%lx, eof=%x\n", mtop->mt_count,
4873 			un->un_eof);
4874 		/*
4875 		 * forward space over filemark
4876 		 *
4877 		 * For ASF we allow a count of 0 on fsf which means
4878 		 * we just want to go to beginning of current file.
4879 		 * Equivalent to "nbsf(0)" or "bsf(1) + fsf".
4880 		 * Allow stepping over double fmk with reel
4881 		 */
4882 		if ((un->un_eof >= ST_EOT) && (mtop->mt_count > 0) &&
4883 		    ((un->un_dp->options & ST_REEL) == 0)) {
4884 			/* we're at EOM */
4885 			un->un_err_resid = mtop->mt_count;
4886 			un->un_status = KEY_BLANK_CHECK;
4887 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4888 			    "st_mtioctop : EIO : MTFSF at EOM");
4889 			return (EIO);
4890 		}
4891 
4892 		/*
4893 		 * physical tape position may not be what we've been
4894 		 * telling the user; adjust the request accordingly
4895 		 */
4896 		if (IN_EOF(un)) {
4897 			un->un_fileno++;
4898 			un->un_blkno = 0;
4899 			/*
4900 			 * For positive direction case, we're now covered.
4901 			 * For zero or negative direction, we're covered
4902 			 * (almost)
4903 			 */
4904 			mtop->mt_count--;
4905 		}
4906 
4907 		if (st_check_density_or_wfm(dev, 1, B_READ, STEPBACK)) {
4908 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4909 			    "st_mtioctop : EIO : MTFSF density/wfm failed");
4910 			return (EIO);
4911 		}
4912 
4913 
4914 		/*
4915 		 * Forward space file marks.
4916 		 * We leave ourselves at block zero
4917 		 * of the target file number.
4918 		 */
4919 		if (mtop->mt_count < 0) {
4920 			mtop->mt_count = -mtop->mt_count;
4921 			mtop->mt_op = MTNBSF;
4922 			goto bspace;
4923 		}
4924 fspace:
4925 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4926 		    "fspace: count=%lx, eof=%x\n", mtop->mt_count,
4927 			un->un_eof);
4928 		if ((tmp = mtop->mt_count) == 0) {
4929 			if (un->un_blkno == 0) {
4930 				un->un_err_resid = 0;
4931 				un->un_err_fileno = un->un_fileno;
4932 				un->un_err_blkno = un->un_blkno;
4933 				break;
4934 			} else if (un->un_fileno == 0) {
4935 				rval = st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD);
4936 			} else if (un->un_dp->options & ST_BSF) {
4937 				rval = (st_cmd(dev, SCMD_SPACE, Fmk((-1)),
4938 				    SYNC_CMD) ||
4939 				    st_cmd(dev, SCMD_SPACE, Fmk(1), SYNC_CMD));
4940 			} else {
4941 				tmp = un->un_fileno;
4942 				rval = (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD) ||
4943 				    st_cmd(dev, SCMD_SPACE, (int)Fmk(tmp),
4944 				    SYNC_CMD));
4945 			}
4946 			if (rval != 0) {
4947 				un->un_fileno = -1;
4948 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4949 				    "st_mtioctop : EIO : fspace fileno = -1");
4950 
4951 				rval = EIO;
4952 			}
4953 		} else {
4954 			rval = st_space_fmks(dev, tmp);
4955 		}
4956 
4957 		if (mtop->mt_op == MTBSF && rval != EIO) {
4958 			/*
4959 			 * we came here with a count < 0; we now need
4960 			 * to skip back to end up before the filemark
4961 			 */
4962 			mtop->mt_count = 1;
4963 			goto bspace;
4964 		}
4965 		break;
4966 
4967 
4968 	case MTFSR:
4969 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4970 		    "fsr: count=%lx, eof=%x\n", mtop->mt_count,
4971 			un->un_eof);
4972 		/*
4973 		 * forward space to inter-record gap
4974 		 *
4975 		 */
4976 		if ((un->un_eof >= ST_EOT) && (mtop->mt_count > 0)) {
4977 			/* we're at EOM */
4978 			un->un_err_resid = mtop->mt_count;
4979 			un->un_status = KEY_BLANK_CHECK;
4980 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4981 			    "st_mtioctop : EIO : MTFSR un_eof > ST_EOT");
4982 			return (EIO);
4983 		}
4984 
4985 		if (mtop->mt_count == 0) {
4986 			un->un_err_fileno = un->un_fileno;
4987 			un->un_err_blkno = un->un_blkno;
4988 			un->un_err_resid = 0;
4989 			if (IN_EOF(un) && SVR4_BEHAVIOR) {
4990 				un->un_status = SUN_KEY_EOF;
4991 			}
4992 			return (0);
4993 		}
4994 
4995 		/*
4996 		 * physical tape position may not be what we've been
4997 		 * telling the user; adjust the position accordingly
4998 		 */
4999 		if (IN_EOF(un)) {
5000 			daddr_t blkno = un->un_blkno;
5001 			int fileno = un->un_fileno;
5002 			uchar_t lastop = un->un_lastop;
5003 			if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)
5004 			    == -1) {
5005 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5006 				    "st_mtioctop : EIO :MTFSR count && IN_EOF");
5007 				return (EIO);
5008 			}
5009 
5010 			un->un_blkno = blkno;
5011 			un->un_fileno = fileno;
5012 			un->un_lastop = lastop;
5013 		}
5014 
5015 		if (st_check_density_or_wfm(dev, 1, B_READ, STEPBACK)) {
5016 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5017 			    "st_mtioctop : EIO : MTFSR st_check_den");
5018 			return (EIO);
5019 		}
5020 
5021 space_records:
5022 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5023 		    "space_records: count=%lx, eof=%x\n", mtop->mt_count,
5024 			un->un_eof);
5025 		tmp = un->un_blkno + mtop->mt_count;
5026 		if (tmp == un->un_blkno) {
5027 			un->un_err_resid = 0;
5028 			un->un_err_fileno = un->un_fileno;
5029 			un->un_err_blkno = un->un_blkno;
5030 			break;
5031 		} else if (un->un_blkno < tmp ||
5032 		    (un->un_dp->options & ST_BSR)) {
5033 			/*
5034 			 * If we're spacing forward, or the device can
5035 			 * backspace records, we can just use the SPACE
5036 			 * command.
5037 			 */
5038 			tmp = tmp - un->un_blkno;
5039 			if (st_cmd(dev, SCMD_SPACE, Blk(tmp), SYNC_CMD)) {
5040 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5041 				    "st_mtioctop :EIO:space_records can't spc");
5042 				rval = EIO;
5043 			} else if (un->un_eof >= ST_EOF_PENDING) {
5044 				/*
5045 				 * check if we hit BOT/EOT
5046 				 */
5047 				if (tmp < 0 && un->un_eof == ST_EOM) {
5048 					un->un_status = SUN_KEY_BOT;
5049 					un->un_eof = ST_NO_EOF;
5050 				} else if (tmp < 0 && un->un_eof ==
5051 				    ST_EOF_PENDING) {
5052 					int residue = un->un_err_resid;
5053 					/*
5054 					 * we skipped over a filemark
5055 					 * and need to go forward again
5056 					 */
5057 					if (st_cmd(dev, SCMD_SPACE, Fmk(1),
5058 					    SYNC_CMD)) {
5059 						ST_DEBUG2(ST_DEVINFO,
5060 						    st_label, SCSI_DEBUG,
5061 						    "st_mtioctop : EIO : "
5062 						    "space_records can't "
5063 						    "space #2");
5064 						rval = EIO;
5065 					}
5066 					un->un_err_resid = residue;
5067 				}
5068 				if (rval == 0) {
5069 					ST_DEBUG2(ST_DEVINFO, st_label,
5070 					    SCSI_DEBUG,
5071 					    "st_mtioctop : EIO : space_rec rval"
5072 					    " == 0");
5073 					rval = EIO;
5074 				}
5075 			}
5076 		} else {
5077 			/*
5078 			 * else we rewind, space forward across filemarks to
5079 			 * the desired file, and then space records to the
5080 			 * desired block.
5081 			 */
5082 
5083 			int t = un->un_fileno;	/* save current file */
5084 
5085 			if (tmp < 0) {
5086 				/*
5087 				 * Wups - we're backing up over a filemark
5088 				 */
5089 				if (un->un_blkno != 0 &&
5090 				    (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD) ||
5091 				    st_cmd(dev, SCMD_SPACE, Fmk(t), SYNC_CMD)))
5092 					un->un_fileno = -1;
5093 				un->un_err_resid = -tmp;
5094 				if (un->un_fileno == 0 && un->un_blkno == 0) {
5095 					un->un_status = SUN_KEY_BOT;
5096 					un->un_eof = ST_NO_EOF;
5097 				} else if (un->un_fileno > 0) {
5098 					un->un_status = SUN_KEY_EOF;
5099 					un->un_eof = ST_NO_EOF;
5100 				}
5101 				un->un_err_fileno = un->un_fileno;
5102 				un->un_err_blkno = un->un_blkno;
5103 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5104 				    "st_mtioctop :EIO:space_records : tmp < 0");
5105 				rval = EIO;
5106 			} else if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD) ||
5107 				    st_cmd(dev, SCMD_SPACE, Fmk(t), SYNC_CMD) ||
5108 				    st_cmd(dev, SCMD_SPACE, Blk(tmp),
5109 					SYNC_CMD)) {
5110 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5111 				    "st_mtioctop : EIO :space_records : rewind "
5112 				    "and space failed");
5113 				un->un_fileno = -1;
5114 				rval = EIO;
5115 			}
5116 		}
5117 		break;
5118 
5119 
5120 	case MTBSF:
5121 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5122 		    "bsf: count=%lx, eof=%x\n", mtop->mt_count,
5123 			un->un_eof);
5124 		/*
5125 		 * backward space of file filemark (1/2" and 8mm)
5126 		 * tape position will end on the beginning of tape side
5127 		 * of the desired file mark
5128 		 */
5129 		if ((un->un_dp->options & ST_BSF) == 0) {
5130 			return (ENOTTY);
5131 		}
5132 
5133 		/*
5134 		 * If a negative count (which implies a forward space op)
5135 		 * is specified, and we're at logical or physical eot,
5136 		 * bounce the request.
5137 		 */
5138 
5139 		if (un->un_eof >= ST_EOT && mtop->mt_count < 0) {
5140 			un->un_err_resid = mtop->mt_count;
5141 			un->un_status = SUN_KEY_EOT;
5142 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5143 			    "st_ioctl : EIO : MTBSF : un_eof > ST_EOF");
5144 			return (EIO);
5145 		}
5146 		/*
5147 		 * physical tape position may not be what we've been
5148 		 * telling the user; adjust the request accordingly
5149 		 */
5150 		if (IN_EOF(un)) {
5151 			un->un_fileno++;
5152 			un->un_blkno = 0;
5153 			mtop->mt_count++;
5154 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5155 			"bsf in eof: count=%ld, op=%x\n",
5156 			mtop->mt_count, mtop->mt_op);
5157 
5158 		}
5159 
5160 		if (st_check_density_or_wfm(dev, 1, 0, STEPBACK)) {
5161 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5162 			    "st_ioctl : EIO : MTBSF : check den wfm");
5163 			return (EIO);
5164 		}
5165 
5166 		if (mtop->mt_count <= 0) {
5167 			/*
5168 			 * for a negative count, we need to step forward
5169 			 * first and then step back again
5170 			 */
5171 			mtop->mt_count = -mtop->mt_count+1;
5172 			goto fspace;
5173 		}
5174 
5175 bspace:
5176 	{
5177 		int skip_cnt, end_at_eof;
5178 
5179 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5180 		    "bspace: count=%lx, eof=%x\n", mtop->mt_count,
5181 			un->un_eof);
5182 		/*
5183 		 * Backspace files (MTNBSF):
5184 		 *
5185 		 *	For tapes that can backspace, backspace
5186 		 *	count+1 filemarks and then run forward over
5187 		 *	a filemark
5188 		 *
5189 		 *	For tapes that can't backspace,
5190 		 *		calculate desired filenumber
5191 		 *		(un->un_fileno - count), rewind,
5192 		 *		and then space forward this amount
5193 		 *
5194 		 * Backspace filemarks (MTBSF)
5195 		 *
5196 		 *	For tapes that can backspace, backspace count
5197 		 *	filemarks
5198 		 *
5199 		 *	For tapes that can't backspace, calculate
5200 		 *	desired filenumber (un->un_fileno - count),
5201 		 *	add 1, rewind, space forward this amount,
5202 		 *	and mark state as ST_EOF_PENDING appropriately.
5203 		 */
5204 
5205 		if (mtop->mt_op == MTBSF) {
5206 			end_at_eof = 1;
5207 		} else {
5208 			end_at_eof = 0;
5209 		}
5210 
5211 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5212 		    "bspace: mt_op=%x, count=%lx, fileno=%x, blkno=%lx\n",
5213 		    mtop->mt_op, mtop->mt_count, un->un_fileno, un->un_blkno);
5214 
5215 		/*
5216 		 * Handle the simple case of BOT
5217 		 * playing a role in these cmds.
5218 		 * We do this by calculating the
5219 		 * ending file number. If the ending
5220 		 * file is < BOT, rewind and set an
5221 		 * error and mark resid appropriately.
5222 		 * If we're backspacing a file (not a
5223 		 * filemark) and the target file is
5224 		 * the first file on the tape, just
5225 		 * rewind.
5226 		 */
5227 
5228 		tmp = un->un_fileno - mtop->mt_count;
5229 		if ((end_at_eof && tmp < 0) || (end_at_eof == 0 && tmp <= 0)) {
5230 			if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD)) {
5231 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5232 				    "st_ioctl : EIO : bspace : end_at_eof && "
5233 				    "tmp < 0");
5234 				rval = EIO;
5235 			}
5236 			if (tmp < 0) {
5237 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5238 				    "st_ioctl : EIO : bspace : tmp < 0");
5239 				rval = EIO;
5240 				un->un_err_resid = -tmp;
5241 				un->un_status = SUN_KEY_BOT;
5242 			}
5243 			break;
5244 		}
5245 
5246 		if (un->un_dp->options & ST_BSF) {
5247 			skip_cnt = 1 - end_at_eof;
5248 			/*
5249 			 * If we are going to end up at the beginning
5250 			 * of the file, we have to space one extra file
5251 			 * first, and then space forward later.
5252 			 */
5253 			tmp = -(mtop->mt_count + skip_cnt);
5254 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5255 			    "skip_cnt=%x, tmp=%x\n", skip_cnt, tmp);
5256 			if (st_cmd(dev, SCMD_SPACE, Fmk(tmp), SYNC_CMD)) {
5257 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5258 				    "st_ioctl : EIO : bspace : can't space "
5259 				    "tmp");
5260 				rval = EIO;
5261 			}
5262 		} else {
5263 			if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD)) {
5264 				rval = EIO;
5265 			} else {
5266 				skip_cnt = tmp + end_at_eof;
5267 			}
5268 		}
5269 
5270 		/*
5271 		 * If we have to space forward, do so...
5272 		 */
5273 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5274 		    "space forward skip_cnt=%x, rval=%x\n", skip_cnt, rval);
5275 		if (rval == 0 && skip_cnt) {
5276 			if (st_cmd(dev, SCMD_SPACE, Fmk(skip_cnt), SYNC_CMD)) {
5277 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5278 				    "st_ioctl : EIO : bspace : can't space "
5279 				    "skip_cnt");
5280 				rval = EIO;
5281 			} else if (end_at_eof) {
5282 				/*
5283 				 * If we had to space forward, and we're
5284 				 * not a tape that can backspace, mark state
5285 				 * as if we'd just seen a filemark during a
5286 				 * a read.
5287 				 */
5288 				if ((un->un_dp->options & ST_BSF) == 0) {
5289 					un->un_eof = ST_EOF_PENDING;
5290 					un->un_fileno -= 1;
5291 					un->un_blkno = INF;
5292 				}
5293 			}
5294 		}
5295 
5296 		if (rval != 0) {
5297 			un->un_fileno = -1;
5298 		}
5299 		break;
5300 	}
5301 
5302 	case MTNBSF:
5303 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5304 		    "nbsf: count=%lx, eof=%x\n", mtop->mt_count,
5305 			un->un_eof);
5306 		/*
5307 		 * backward space file to beginning of file
5308 		 *
5309 		 * If a negative count (which implies a forward space op)
5310 		 * is specified, and we're at logical or physical eot,
5311 		 * bounce the request.
5312 		 */
5313 
5314 		if (un->un_eof >= ST_EOT && mtop->mt_count < 0) {
5315 			un->un_err_resid = mtop->mt_count;
5316 			un->un_status = SUN_KEY_EOT;
5317 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5318 			    "st_ioctl : EIO : > EOT and count < 0");
5319 			return (EIO);
5320 		}
5321 		/*
5322 		 * physical tape position may not be what we've been
5323 		 * telling the user; adjust the request accordingly
5324 		 */
5325 		if (IN_EOF(un)) {
5326 			un->un_fileno++;
5327 			un->un_blkno = 0;
5328 			mtop->mt_count++;
5329 		}
5330 
5331 		if (st_check_density_or_wfm(dev, 1, 0, STEPBACK)) {
5332 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5333 			    "st_ioctl : EIO : MTNBSF check den and wfm");
5334 			return (EIO);
5335 		}
5336 
5337 mtnbsf:
5338 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5339 		    "mtnbsf: count=%lx, eof=%x\n", mtop->mt_count,
5340 			un->un_eof);
5341 		if (mtop->mt_count <= 0) {
5342 			mtop->mt_op = MTFSF;
5343 			mtop->mt_count = -mtop->mt_count;
5344 			goto fspace;
5345 		}
5346 		goto bspace;
5347 
5348 	case MTBSR:
5349 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5350 		    "bsr: count=%lx, eof=%x\n", mtop->mt_count,
5351 			un->un_eof);
5352 		/*
5353 		 * backward space into inter-record gap
5354 		 *
5355 		 * If a negative count (which implies a forward space op)
5356 		 * is specified, and we're at logical or physical eot,
5357 		 * bounce the request.
5358 		 */
5359 		if (un->un_eof >= ST_EOT && mtop->mt_count < 0) {
5360 			un->un_err_resid = mtop->mt_count;
5361 			un->un_status = SUN_KEY_EOT;
5362 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5363 			    "st_ioctl : EIO : MTBSR > EOT");
5364 			return (EIO);
5365 		}
5366 
5367 		if (mtop->mt_count == 0) {
5368 			un->un_err_fileno = un->un_fileno;
5369 			un->un_err_blkno = un->un_blkno;
5370 			un->un_err_resid = 0;
5371 			if (IN_EOF(un) && SVR4_BEHAVIOR) {
5372 				un->un_status = SUN_KEY_EOF;
5373 			}
5374 			return (0);
5375 		}
5376 
5377 		/*
5378 		 * physical tape position may not be what we've been
5379 		 * telling the user; adjust the position accordingly.
5380 		 * bsr can not skip filemarks and continue to skip records
5381 		 * therefore if we are logically before the filemark but
5382 		 * physically at the EOT side of the filemark, we need to step
5383 		 * back; this allows fsr N where N > number of blocks in file
5384 		 * followed by bsr 1 to position at the beginning of last block
5385 		 */
5386 		if (IN_EOF(un)) {
5387 			int blkno = un->un_blkno;
5388 			int fileno = un->un_fileno;
5389 			uchar_t lastop = un->un_lastop;
5390 			if (st_cmd(dev, SCMD_SPACE, Fmk((-1)), SYNC_CMD)
5391 			    == -1) {
5392 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5393 				    "st_write_fm : EIO : MTBSR can't space");
5394 				return (EIO);
5395 			}
5396 
5397 			un->un_blkno = blkno;
5398 			un->un_fileno = fileno;
5399 			un->un_lastop = lastop;
5400 		}
5401 
5402 		un->un_eof = ST_NO_EOF;
5403 
5404 		if (st_check_density_or_wfm(dev, 1, 0, STEPBACK)) {
5405 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5406 			    "st_ioctl : EIO : MTBSR : can't set density or "
5407 			    "wfm");
5408 			return (EIO);
5409 		}
5410 
5411 		mtop->mt_count = -mtop->mt_count;
5412 		goto space_records;
5413 
5414 	case MTSRSZ:
5415 
5416 		/*
5417 		 * Set record-size to that sent by user
5418 		 * Check to see if there is reason that the requested
5419 		 * block size should not be set.
5420 		 */
5421 
5422 		/* If requesting variable block size is it ok? */
5423 		if ((mtop->mt_count == 0) &&
5424 		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
5425 			return (ENOTTY);
5426 		}
5427 
5428 		/*
5429 		 * If requested block size is not variable "0",
5430 		 * is it less then minimum.
5431 		 */
5432 		if ((mtop->mt_count != 0) &&
5433 		    (mtop->mt_count < un->un_minbsize)) {
5434 			return (EINVAL);
5435 		}
5436 
5437 		/* Is the requested block size more then maximum */
5438 		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
5439 		    (un->un_maxbsize != 0)) {
5440 			return (EINVAL);
5441 		}
5442 
5443 		/* Is requested block size a modulus the device likes */
5444 		if ((mtop->mt_count % un->un_data_mod) != 0) {
5445 			return (EINVAL);
5446 		}
5447 
5448 		if (st_change_block_size(dev, (uint32_t)mtop->mt_count) != 0) {
5449 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5450 			    "st_ioctl : MTSRSZ : EIO : cant set block size");
5451 			return (EIO);
5452 		}
5453 
5454 		return (0);
5455 
5456 	case MTGRSZ:
5457 	{
5458 #ifdef _MULTI_DATAMODEL
5459 	/*
5460 	 * For use when a 32 bit app makes a call into a
5461 	 * 64 bit ioctl
5462 	 */
5463 	struct mtop32	mtop_32_for_64;
5464 #endif /* _MULTI_DATAMODEL */
5465 
5466 
5467 		/*
5468 		 * Get record-size to the user
5469 		 */
5470 		mtop->mt_count = un->un_bsize;
5471 
5472 #ifdef _MULTI_DATAMODEL
5473 		switch (ddi_model_convert_from(flag & FMODELS)) {
5474 		case DDI_MODEL_ILP32:
5475 			/*
5476 			 * Convert 64 bit back to 32 bit before doing
5477 			 * copyout. This is what the ILP32 app expects.
5478 			 */
5479 			mtop_32_for_64.mt_op = mtop->mt_op;
5480 			mtop_32_for_64.mt_count = mtop->mt_count;
5481 
5482 			if (ddi_copyout(&mtop_32_for_64, (void *)arg,
5483 			    sizeof (struct mtop32), flag)) {
5484 				return (EFAULT);
5485 			}
5486 			break;
5487 
5488 		case DDI_MODEL_NONE:
5489 			if (ddi_copyout(mtop, (void *)arg,
5490 			    sizeof (struct mtop), flag)) {
5491 				return (EFAULT);
5492 			}
5493 			break;
5494 		}
5495 #else /* ! _MULTI_DATAMODE */
5496 		if (ddi_copyout(mtop, (void *)arg, sizeof (struct mtop), flag))
5497 			return (EFAULT);
5498 
5499 #endif /* _MULTI_DATAMODE */
5500 
5501 		return (0);
5502 	}
5503 	default:
5504 		rval = ENOTTY;
5505 	}
5506 
5507 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5508 	    "st_ioctl: fileno=%x, blkno=%lx, un_eof=%x\n", un->un_fileno,
5509 	    un->un_blkno, un->un_eof);
5510 
5511 	if (un->un_fileno < 0) {
5512 		un->un_density_known = 0;
5513 	}
5514 
5515 	ASSERT(mutex_owned(ST_MUTEX));
5516 	return (rval);
5517 }
5518 
5519 
5520 /*
5521  * Run a command for uscsi ioctl.
5522  * cdbspace is address space of cdb.
5523  * dataspace is address space of the uscsi data buffer.
5524  */
5525 static int
5526 st_ioctl_cmd(dev_t dev, struct uscsi_cmd *ucmd,
5527 	enum uio_seg cdbspace, enum uio_seg dataspace,
5528 	enum uio_seg rqbufspace)
5529 {
5530 	struct buf *bp;
5531 	struct uscsi_cmd *kcmd;
5532 	caddr_t kcdb;
5533 	int flag;
5534 	int err;
5535 	int rqlen;
5536 	int offline_state = 0;
5537 	char *krqbuf = NULL;
5538 
5539 	GET_SOFT_STATE(dev);
5540 
5541 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5542 	    "st_ioctl_cmd(dev = 0x%lx)\n", dev);
5543 
5544 	ASSERT(mutex_owned(ST_MUTEX));
5545 
5546 	/*
5547 	 * We really don't know what commands are coming in here and
5548 	 * we don't want to limit the commands coming in.
5549 	 *
5550 	 * If st_tape_init() gets called from st_strategy(), then we
5551 	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
5552 	 * which it never will, as we set it below.  To prevent
5553 	 * st_tape_init() from getting called, we have to set state to other
5554 	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
5555 	 * achieves this purpose already
5556 	 *
5557 	 * We use offline_state to preserve the OFFLINE state, if it exists,
5558 	 * so other entry points to the driver might have the chance to call
5559 	 * st_tape_init().
5560 	 */
5561 	if (un->un_state == ST_STATE_OFFLINE) {
5562 		un->un_laststate = ST_STATE_OFFLINE;
5563 		un->un_state = ST_STATE_INITIALIZING;
5564 		offline_state = 1;
5565 	}
5566 	/*
5567 	 * Is this a request to reset the bus?
5568 	 * If so, we need go no further.
5569 	 */
5570 	if (ucmd->uscsi_flags & (USCSI_RESET|USCSI_RESET_ALL)) {
5571 		flag = ((ucmd->uscsi_flags & USCSI_RESET_ALL)) ?
5572 			RESET_ALL : RESET_TARGET;
5573 
5574 		mutex_exit(ST_MUTEX);
5575 		err = (scsi_reset(ROUTE, flag)) ? 0 : EIO;
5576 		mutex_enter(ST_MUTEX);
5577 
5578 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5579 			"reset %s %s\n",
5580 			(flag == RESET_ALL) ? "all" : "target",
5581 			(err == 0) ? "ok" : "failed");
5582 		/*
5583 		 * If scsi reset successful, don't write any filemarks.
5584 		 */
5585 		if (err == 0) {
5586 			un->un_fmneeded = 0;
5587 		} else {
5588 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5589 			    "st_ioctl_cmd : EIO : scsi_reset failed");
5590 		}
5591 		goto exit;
5592 	}
5593 
5594 	/*
5595 	 * First do some sanity checks for USCSI commands.
5596 	 */
5597 	if (ucmd->uscsi_cdblen <= 0) {
5598 		return (EINVAL);
5599 	}
5600 
5601 	/*
5602 	 * In order to not worry about where the uscsi structure
5603 	 * or cdb it points to came from, we kmem_alloc copies
5604 	 * of them here.  This will allow reference to the data
5605 	 * they contain long after this process has gone to
5606 	 * sleep and its kernel stack has been unmapped, etc.
5607 	 */
5608 
5609 	kcdb = kmem_alloc((size_t)ucmd->uscsi_cdblen, KM_SLEEP);
5610 	if (cdbspace == UIO_SYSSPACE) {
5611 		bcopy(ucmd->uscsi_cdb, kcdb, ucmd->uscsi_cdblen);
5612 	} else {
5613 		if (ddi_copyin(ucmd->uscsi_cdb, kcdb,
5614 		    (size_t)ucmd->uscsi_cdblen, 0)) {
5615 			kmem_free(kcdb, (size_t)ucmd->uscsi_cdblen);
5616 			err = EFAULT;
5617 			goto exit;
5618 		}
5619 	}
5620 
5621 	kcmd = kmem_alloc(sizeof (struct uscsi_cmd), KM_SLEEP);
5622 	bcopy(ucmd, kcmd, sizeof (struct uscsi_cmd));
5623 	kcmd->uscsi_cdb = kcdb;
5624 
5625 	flag = (kcmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
5626 
5627 #ifdef STDEBUG
5628 	if (st_debug > 6) {
5629 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
5630 		    "uscsi cdb", kcdb, kcmd->uscsi_cdblen);
5631 		if (kcmd->uscsi_buflen) {
5632 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5633 			"uscsi %s of %ld bytes %s %s space\n",
5634 			(flag == B_READ) ? rd_str : wr_str,
5635 			kcmd->uscsi_buflen,
5636 			(flag == B_READ) ? "to" : "from",
5637 			(dataspace == UIO_SYSSPACE) ? "system" : "user");
5638 		}
5639 	}
5640 #endif /* ST_DEBUG */
5641 
5642 	/*
5643 	 * Initialize Request Sense buffering, if requested.
5644 	 * For user processes, allocate a kernel copy of the sense buffer
5645 	 */
5646 	if ((kcmd->uscsi_flags & USCSI_RQENABLE) &&
5647 			kcmd->uscsi_rqlen && kcmd->uscsi_rqbuf) {
5648 		if (rqbufspace == UIO_USERSPACE) {
5649 			krqbuf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
5650 		}
5651 		kcmd->uscsi_rqlen = SENSE_LENGTH;
5652 		kcmd->uscsi_rqresid = SENSE_LENGTH;
5653 	} else {
5654 		kcmd->uscsi_rqlen = 0;
5655 		kcmd->uscsi_rqresid = 0;
5656 	}
5657 
5658 	/*
5659 	 * Get buffer resources...
5660 	 */
5661 	while (un->un_sbuf_busy)
5662 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
5663 	un->un_sbuf_busy = 1;
5664 
5665 	un->un_srqbufp = krqbuf;
5666 	bp = un->un_sbufp;
5667 	bzero(bp, sizeof (buf_t));
5668 
5669 	/*
5670 	 * Force asynchronous mode, if necessary.
5671 	 */
5672 	if (ucmd->uscsi_flags & USCSI_ASYNC) {
5673 		mutex_exit(ST_MUTEX);
5674 		if (scsi_ifgetcap(ROUTE, "synchronous", 1) == 1) {
5675 			if (scsi_ifsetcap(ROUTE, "synchronous", 0, 1) == 1) {
5676 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
5677 				    "forced async ok\n");
5678 			} else {
5679 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
5680 				    "forced async failed\n");
5681 				err = EINVAL;
5682 				mutex_enter(ST_MUTEX);
5683 				goto done;
5684 			}
5685 		}
5686 		mutex_enter(ST_MUTEX);
5687 	}
5688 
5689 	/*
5690 	 * Re-enable synchronous mode, if requested
5691 	 */
5692 	if (ucmd->uscsi_flags & USCSI_SYNC) {
5693 		mutex_exit(ST_MUTEX);
5694 		if (scsi_ifgetcap(ROUTE, "synchronous", 1) == 0) {
5695 			int i = scsi_ifsetcap(ROUTE, "synchronous", 1, 1);
5696 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
5697 				"re-enabled sync %s\n",
5698 				(i == 1) ? "ok" : "failed");
5699 		}
5700 		mutex_enter(ST_MUTEX);
5701 	}
5702 
5703 	if (kcmd->uscsi_buflen) {
5704 		/*
5705 		 * We're going to do actual I/O.
5706 		 * Set things up for physio.
5707 		 */
5708 		struct iovec aiov;
5709 		struct uio auio;
5710 		struct uio *uio = &auio;
5711 
5712 		bzero(&auio, sizeof (struct uio));
5713 		bzero(&aiov, sizeof (struct iovec));
5714 		aiov.iov_base = kcmd->uscsi_bufaddr;
5715 		aiov.iov_len = kcmd->uscsi_buflen;
5716 
5717 		uio->uio_iov = &aiov;
5718 		uio->uio_iovcnt = 1;
5719 		uio->uio_resid = aiov.iov_len;
5720 		uio->uio_segflg = dataspace;
5721 
5722 		/*
5723 		 * Let physio do the rest...
5724 		 */
5725 		bp->b_forw = (struct buf *)(uintptr_t)kcdb[0];
5726 		bp->b_back = (struct buf *)kcmd;
5727 
5728 		mutex_exit(ST_MUTEX);
5729 		err = physio(st_strategy, bp, dev, flag, st_uscsi_minphys, uio);
5730 		mutex_enter(ST_MUTEX);
5731 	} else {
5732 		/*
5733 		 * Mimic physio
5734 		 */
5735 		bp->b_forw = (struct buf *)(uintptr_t)kcdb[0];
5736 		bp->b_back = (struct buf *)kcmd;
5737 		bp->b_flags = B_BUSY | flag;
5738 		bp->b_edev = dev;
5739 		bp->b_dev = cmpdev(dev);
5740 		bp->b_bcount = 0;
5741 		bp->b_blkno = 0;
5742 		bp->b_resid = 0;
5743 		mutex_exit(ST_MUTEX);
5744 		(void) st_strategy(bp);
5745 
5746 		/*
5747 		 * BugTraq #4260046
5748 		 * ----------------
5749 		 * See comments in st_cmd.
5750 		 */
5751 
5752 		err = biowait(bp);
5753 		mutex_enter(ST_MUTEX);
5754 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5755 		    "st_ioctl_cmd: biowait returns %d\n", err);
5756 	}
5757 
5758 	/*
5759 	 * Copy status from kernel copy of uscsi_cmd to user copy
5760 	 * of uscsi_cmd - this was saved in st_done_and_mutex_exit()
5761 	 */
5762 	ucmd->uscsi_status = kcmd->uscsi_status;
5763 
5764 done:
5765 	ucmd->uscsi_resid = bp->b_resid;
5766 
5767 	/*
5768 	 * Update the Request Sense status and resid
5769 	 */
5770 	rqlen = kcmd->uscsi_rqlen - kcmd->uscsi_rqresid;
5771 	rqlen = min(((int)ucmd->uscsi_rqlen), rqlen);
5772 	ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
5773 	ucmd->uscsi_rqstatus = kcmd->uscsi_rqstatus;
5774 	/*
5775 	 * Copy out the sense data for user processes
5776 	 */
5777 	if (ucmd->uscsi_rqbuf && rqlen && rqbufspace == UIO_USERSPACE) {
5778 		if (copyout(krqbuf, ucmd->uscsi_rqbuf, rqlen)) {
5779 			err = EFAULT;
5780 		}
5781 	}
5782 
5783 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5784 	    "st_ioctl_cmd status is 0x%x, resid is 0x%lx\n",
5785 	    ucmd->uscsi_status, ucmd->uscsi_resid);
5786 	if (DEBUGGING && (rqlen != 0)) {
5787 		int i, n, len;
5788 		char *data = krqbuf;
5789 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5790 			"rqstatus=0x%x	rqlen=0x%x  rqresid=0x%x\n",
5791 			ucmd->uscsi_rqstatus, ucmd->uscsi_rqlen,
5792 			ucmd->uscsi_rqresid);
5793 		len = (int)ucmd->uscsi_rqlen - ucmd->uscsi_rqresid;
5794 		for (i = 0; i < len; i += 16) {
5795 			n = min(16, len-1);
5796 			st_clean_print(ST_DEVINFO, st_label, CE_NOTE,
5797 				"  ", &data[i], n);
5798 		}
5799 	}
5800 
5801 exit_free:
5802 	/*
5803 	 * Free resources
5804 	 */
5805 	un->un_sbuf_busy = 0;
5806 	un->un_srqbufp = NULL;
5807 	cv_signal(&un->un_sbuf_cv);
5808 
5809 	if (krqbuf) {
5810 		kmem_free(krqbuf, SENSE_LENGTH);
5811 	}
5812 	kmem_free(kcdb, kcmd->uscsi_cdblen);
5813 	kmem_free(kcmd, sizeof (struct uscsi_cmd));
5814 
5815 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5816 	    "st_ioctl_cmd returns 0x%x\n", err);
5817 
5818 
5819 exit:
5820 	/* don't lose offline state */
5821 	if (offline_state)
5822 		un->un_state = ST_STATE_OFFLINE;
5823 
5824 	ASSERT(mutex_owned(ST_MUTEX));
5825 	return (err);
5826 }
5827 
5828 static int
5829 st_write_fm(dev_t dev, int wfm)
5830 {
5831 	int i;
5832 
5833 	GET_SOFT_STATE(dev);
5834 
5835 	ASSERT(mutex_owned(ST_MUTEX));
5836 
5837 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5838 	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
5839 
5840 	/*
5841 	 * write one filemark at the time after EOT
5842 	 */
5843 	if (un->un_eof >= ST_EOT) {
5844 		for (i = 0; i < wfm; i++) {
5845 			if (st_cmd(dev, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD)) {
5846 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5847 				    "st_write_fm : EIO : write EOT file mark");
5848 				return (EIO);
5849 			}
5850 		}
5851 	} else if (st_cmd(dev, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD)) {
5852 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5853 		    "st_write_fm : EIO : write file mark");
5854 		return (EIO);
5855 	}
5856 
5857 	ASSERT(mutex_owned(ST_MUTEX));
5858 	return (0);
5859 }
5860 
5861 #ifdef STDEBUG
5862 static void
5863 start_dump(struct scsi_tape *un, struct buf *bp)
5864 {
5865 	struct scsi_pkt *pkt = BP_PKT(bp);
5866 	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
5867 
5868 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5869 	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
5870 	    (void *)bp->b_forw, bp->b_bcount,
5871 	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
5872 
5873 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5874 	    "st_start: cdb %x %x %x %x %x %x, fileno=%d, blk=%ld\n",
5875 	    cdbp[0], cdbp[1], cdbp[2],
5876 	    cdbp[3], cdbp[4], cdbp[5], un->un_fileno,
5877 	    un->un_blkno);
5878 }
5879 #endif
5880 
5881 
5882 /*
5883  * Command start && done functions
5884  */
5885 
5886 /*
5887  * st_start()
5888  *
5889  * Called from:
5890  *  st_strategy() to start a command.
5891  *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
5892  *  st_attach() when resuming from power down state.
5893  *  st_start_restart() to retry transport when device was previously busy.
5894  *  st_done_and_mutex_exit() to start the next command when previous is done.
5895  *
5896  * On entry:
5897  *  scsi_pkt may or may not be allocated.
5898  *
5899  */
5900 static void
5901 st_start(struct scsi_tape *un)
5902 {
5903 	struct buf *bp;
5904 	int status;
5905 
5906 	ASSERT(mutex_owned(ST_MUTEX));
5907 
5908 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5909 	    "st_start(): dev = 0x%lx\n", un->un_dev);
5910 
5911 	if ((bp = un->un_quef) == NULL) {
5912 		return;
5913 	}
5914 
5915 	ASSERT((bp->b_flags & B_DONE) == 0);
5916 
5917 	/*
5918 	 * Don't send more than un_throttle commands to the HBA
5919 	 */
5920 	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
5921 		return;
5922 	}
5923 
5924 	/*
5925 	 * If the buf has no scsi_pkt call st_make_cmd() to get one and
5926 	 * build the command.
5927 	 */
5928 	if (BP_PKT(bp) == NULL) {
5929 		ASSERT((bp->b_flags & B_DONE) == 0);
5930 		st_make_cmd(un, bp, st_runout);
5931 		ASSERT((bp->b_flags & B_DONE) == 0);
5932 		status = geterror(bp);
5933 
5934 		/*
5935 		 * Some HBA's don't call bioerror() to set an error.
5936 		 * And geterror() returns zero if B_ERROR is not set.
5937 		 * So if we get zero we must check b_error.
5938 		 */
5939 		if (status == 0 && bp->b_error != 0) {
5940 			status = bp->b_error;
5941 			bioerror(bp, status);
5942 		}
5943 
5944 		/*
5945 		 * Some HBA's convert DDI_DMA_NORESOURCES into ENOMEM.
5946 		 * In tape ENOMEM has special meaning so we'll change it.
5947 		 */
5948 		if (status == ENOMEM) {
5949 			status = 0;
5950 			bioerror(bp, status);
5951 		}
5952 
5953 		/*
5954 		 * Did it fail and is it retryable?
5955 		 * If so return and wait for the callback through st_runout.
5956 		 * Also looks like scsi_init_pkt() will setup a callback even
5957 		 * if it isn't retryable.
5958 		 */
5959 		if (BP_PKT(bp) == NULL) {
5960 			if (status == 0) {
5961 				/*
5962 				 * If first attempt save state.
5963 				 */
5964 				if (un->un_state != ST_STATE_RESOURCE_WAIT) {
5965 					un->un_laststate = un->un_state;
5966 					un->un_state = ST_STATE_RESOURCE_WAIT;
5967 				}
5968 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5969 				    "temp no resources for pkt\n");
5970 			} else {
5971 				/*
5972 				 * Unlikely that it would be retryable then not.
5973 				 */
5974 				if (un->un_state == ST_STATE_RESOURCE_WAIT) {
5975 					un->un_state = un->un_laststate;
5976 				}
5977 				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5978 				    "perm no resources for pkt errno = 0x%x\n",
5979 				    status);
5980 			}
5981 			return;
5982 		}
5983 		/*
5984 		 * Worked this time set the state back.
5985 		 */
5986 		if (un->un_state == ST_STATE_RESOURCE_WAIT) {
5987 			un->un_state = un->un_laststate;
5988 		}
5989 	}
5990 
5991 	/*
5992 	 * move from waitq to runq
5993 	 */
5994 	un->un_quef = bp->b_actf;
5995 	if (un->un_quel == bp) {
5996 		/*
5997 		 *  For the case of queue having one
5998 		 *  element, set the tail pointer to
5999 		 *  point to the element.
6000 		 */
6001 		un->un_quel = bp->b_actf;
6002 	}
6003 
6004 	bp->b_actf = NULL;
6005 
6006 	if (un->un_runqf) {
6007 		un->un_runql->b_actf = bp;
6008 	} else {
6009 		un->un_runqf = bp;
6010 	}
6011 	un->un_runql = bp;
6012 
6013 
6014 #ifdef STDEBUG
6015 	start_dump(un, bp);
6016 #endif
6017 
6018 	/* could not get here if throttle was zero */
6019 	un->un_last_throttle = un->un_throttle;
6020 	un->un_throttle = 0;	/* so nothing else will come in here */
6021 	un->un_ncmds++;
6022 
6023 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
6024 
6025 	mutex_exit(ST_MUTEX);
6026 
6027 	status = scsi_transport(BP_PKT(bp));
6028 
6029 	mutex_enter(ST_MUTEX);
6030 
6031 	if (un->un_last_throttle) {
6032 		un->un_throttle = un->un_last_throttle;
6033 	}
6034 
6035 	if (status != TRAN_ACCEPT) {
6036 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
6037 		mutex_exit(ST_MUTEX);
6038 
6039 		if (status == TRAN_BUSY) {
6040 			/* if too many retries, fail the transport */
6041 			if (st_handle_start_busy(un, bp,
6042 			    ST_TRAN_BUSY_TIMEOUT) == 0)
6043 				goto done;
6044 		}
6045 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6046 		    "transport rejected\n");
6047 		bp->b_resid = bp->b_bcount;
6048 
6049 
6050 #ifndef __lock_lint
6051 		/*
6052 		 * warlock doesn't understand this potential
6053 		 * recursion?
6054 		 */
6055 		mutex_enter(ST_MUTEX);
6056 		ST_DO_KSTATS(bp, kstat_waitq_exit);
6057 		ST_DO_ERRSTATS(un, st_transerrs);
6058 		st_bioerror(bp, EIO);
6059 		SET_PE_FLAG(un);
6060 		st_done_and_mutex_exit(un, bp);
6061 #endif
6062 	} else {
6063 		un->un_tran_retry_ct = 0;
6064 		mutex_exit(ST_MUTEX);
6065 	}
6066 
6067 done:
6068 
6069 	mutex_enter(ST_MUTEX);
6070 }
6071 
6072 /*
6073  * if the transport is busy, then put this bp back on the waitq
6074  */
6075 static int
6076 st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
6077     clock_t timeout_interval)
6078 {
6079 	struct buf *last_quef, *runq_bp;
6080 	int rval = 0;
6081 
6082 	mutex_enter(ST_MUTEX);
6083 
6084 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6085 	    "st_handle_start_busy()\n");
6086 
6087 	/*
6088 	 * Check to see if we hit the retry timeout and one last check for
6089 	 * making sure this is the last on the runq, if it is not, we have
6090 	 * to fail
6091 	 */
6092 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
6093 	    (un->un_runql != bp)) {
6094 		rval = -1;
6095 		goto exit;
6096 	}
6097 
6098 	/* put the bp back on the waitq */
6099 	if (un->un_quef) {
6100 		last_quef = un->un_quef;
6101 		un->un_quef = bp;
6102 		bp->b_actf = last_quef;
6103 	} else  {
6104 		bp->b_actf = NULL;
6105 		un->un_quef = bp;
6106 		un->un_quel = bp;
6107 	}
6108 
6109 	/*
6110 	 * Decrement un_ncmds so that this
6111 	 * gets thru' st_start() again.
6112 	 */
6113 	un->un_ncmds--;
6114 
6115 	/*
6116 	 * since this is an error case, we won't have to do
6117 	 * this list walking much.  We've already made sure this bp was the
6118 	 * last on the runq
6119 	 */
6120 	runq_bp = un->un_runqf;
6121 
6122 	if (un->un_runqf == bp) {
6123 		un->un_runqf = NULL;
6124 		un->un_runql = NULL;
6125 	} else {
6126 		while (runq_bp) {
6127 			if (runq_bp->b_actf == bp) {
6128 				runq_bp->b_actf = NULL;
6129 				un->un_runql = runq_bp;
6130 				break;
6131 			}
6132 			runq_bp = runq_bp->b_actf;
6133 		}
6134 	}
6135 
6136 
6137 	/*
6138 	 * send a marker pkt, if appropriate
6139 	 */
6140 	st_hba_unflush(un);
6141 
6142 	/*
6143 	 * all queues are aligned, we are just waiting to
6144 	 * transport, don't alloc any more buf p's, when
6145 	 * st_start is reentered.
6146 	 */
6147 	(void) timeout(st_start_restart, un, timeout_interval);
6148 
6149 exit:
6150 	mutex_exit(ST_MUTEX);
6151 	return (rval);
6152 }
6153 
6154 
6155 
6156 /*
6157  * st_runout a callback that is called what a resource allocatation failed
6158  */
6159 static int
6160 st_runout(caddr_t arg)
6161 {
6162 	struct scsi_tape *un = (struct scsi_tape *)arg;
6163 	struct buf *bp;
6164 
6165 	ASSERT(un != NULL);
6166 
6167 	mutex_enter(ST_MUTEX);
6168 
6169 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_runout()\n");
6170 
6171 	bp = un->un_quef;
6172 
6173 	/*
6174 	 * failed scsi_init_pkt(). If errno is zero its retryable.
6175 	 */
6176 	if ((bp != NULL) && (geterror(bp) != 0)) {
6177 
6178 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
6179 		    "errors after pkt alloc (b_flags=0x%x, b_error=0x%x)\n",
6180 		    bp->b_flags, geterror(bp));
6181 		ASSERT((bp->b_flags & B_DONE) == 0);
6182 
6183 		un->un_quef = bp->b_actf;
6184 		if (un->un_quel == bp) {
6185 			/*
6186 			 *  For the case of queue having one
6187 			 *  element, set the tail pointer to
6188 			 *  point to the element.
6189 			 */
6190 			un->un_quel = bp->b_actf;
6191 		}
6192 		bp->b_actf = NULL;
6193 
6194 		ASSERT((bp->b_flags & B_DONE) == 0);
6195 
6196 		/*
6197 		 * Set resid, Error already set, then unblock calling thread.
6198 		 */
6199 		bp->b_resid = bp->b_bcount;
6200 		biodone(bp);
6201 	} else {
6202 		/*
6203 		 * Try Again
6204 		 */
6205 		st_start(un);
6206 	}
6207 
6208 	mutex_exit(ST_MUTEX);
6209 
6210 	/*
6211 	 * Comments courtesy of sd.c
6212 	 * The scsi_init_pkt routine allows for the callback function to
6213 	 * return a 0 indicating the callback should be rescheduled or a 1
6214 	 * indicating not to reschedule. This routine always returns 1
6215 	 * because the driver always provides a callback function to
6216 	 * scsi_init_pkt. This results in a callback always being scheduled
6217 	 * (via the scsi_init_pkt callback implementation) if a resource
6218 	 * failure occurs.
6219 	 */
6220 
6221 	return (1);
6222 }
6223 
6224 /*
6225  * st_done_and_mutex_exit()
6226  *	- remove bp from runq
6227  *	- start up the next request
6228  *	- if this was an asynch bp, clean up
6229  *	- exit with released mutex
6230  */
6231 static void
6232 st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp)
6233 {
6234 	struct buf *runqbp, *prevbp;
6235 	int	pe_flagged = 0;
6236 
6237 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
6238 #if !defined(lint)
6239 	_NOTE(LOCK_RELEASED_AS_SIDE_EFFECT(&un->un_sd->sd_mutex))
6240 #endif
6241 	ASSERT(mutex_owned(ST_MUTEX));
6242 
6243 	/*
6244 	 * if bp is still on the runq (anywhere), then remove it
6245 	 */
6246 	prevbp = NULL;
6247 	for (runqbp = un->un_runqf; runqbp != 0; runqbp = runqbp->b_actf) {
6248 		if (runqbp == bp) {
6249 			if (runqbp == un->un_runqf) {
6250 				un->un_runqf = bp->b_actf;
6251 			} else {
6252 				prevbp->b_actf = bp->b_actf;
6253 			}
6254 			if (un->un_runql == bp) {
6255 				un->un_runql = prevbp;
6256 			}
6257 			break;
6258 		}
6259 		prevbp = runqbp;
6260 	}
6261 	bp->b_actf = NULL;
6262 
6263 	un->un_ncmds--;
6264 	cv_signal(&un->un_queue_cv);
6265 
6266 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6267 	"st_done_and_mutex_exit(): cmd=0x%x count=%ld resid=%ld  flags=0x%x\n",
6268 		(int)*((caddr_t)(BP_PKT(bp))->pkt_cdbp),
6269 		bp->b_bcount, bp->b_resid, bp->b_flags);
6270 
6271 
6272 	/*
6273 	 * update kstats with transfer count info
6274 	 */
6275 	if (un->un_stats && (bp != un->un_sbufp) && IS_RW(bp)) {
6276 		uint32_t n_done =  bp->b_bcount - bp->b_resid;
6277 		if (bp->b_flags & B_READ) {
6278 			IOSP->reads++;
6279 			IOSP->nread += n_done;
6280 		} else {
6281 			IOSP->writes++;
6282 			IOSP->nwritten += n_done;
6283 		}
6284 	}
6285 
6286 	/*
6287 	 * Start the next one before releasing resources on this one, if
6288 	 * there is something on the queue and persistent errors has not been
6289 	 * flagged
6290 	 */
6291 
6292 	if ((pe_flagged = IS_PE_FLAG_SET(un)) != 0) {
6293 		un->un_last_resid = bp->b_resid;
6294 		un->un_last_count = bp->b_bcount;
6295 	}
6296 
6297 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
6298 		cv_broadcast(&un->un_tape_busy_cv);
6299 	} else if (un->un_quef && un->un_throttle && !pe_flagged) {
6300 		st_start(un);
6301 	}
6302 
6303 	if (bp == un->un_sbufp && (bp->b_flags & B_ASYNC)) {
6304 		/*
6305 		 * Since we marked this ourselves as ASYNC,
6306 		 * there isn't anybody around waiting for
6307 		 * completion any more.
6308 		 */
6309 		uchar_t com = (uchar_t)(uintptr_t)bp->b_forw;
6310 		if (com == SCMD_READ || com == SCMD_WRITE) {
6311 			bp->b_un.b_addr = (caddr_t)0;
6312 		}
6313 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6314 		    "st_done_and_mutex_exit(async): freeing pkt\n");
6315 		scsi_destroy_pkt(BP_PKT(bp));
6316 		un->un_sbuf_busy = 0;
6317 		cv_signal(&un->un_sbuf_cv);
6318 		mutex_exit(ST_MUTEX);
6319 		return;
6320 	}
6321 
6322 	if (bp == un->un_sbufp && BP_UCMD(bp)) {
6323 		/*
6324 		 * Copy status from scsi_pkt to uscsi_cmd
6325 		 * since st_ioctl_cmd needs it
6326 		 */
6327 		BP_UCMD(bp)->uscsi_status = SCBP_C(BP_PKT(bp));
6328 	}
6329 
6330 
6331 #ifdef STDEBUG
6332 	if ((st_debug >= 4) &&
6333 	    (((un->un_blkno % 100) == 0) || IS_PE_FLAG_SET(un))) {
6334 
6335 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6336 		    "st_d_a_m_exit(): ncmds = %d, thr = %d, "
6337 		    "un_errno = %d, un_pe = %d\n",
6338 		    un->un_ncmds, un->un_throttle, un->un_errno,
6339 		    un->un_persist_errors);
6340 	}
6341 
6342 #endif
6343 
6344 	mutex_exit(ST_MUTEX);
6345 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6346 	    "st_done_and_mutex_exit: freeing pkt\n");
6347 
6348 	scsi_destroy_pkt(BP_PKT(bp));
6349 
6350 	biodone(bp);
6351 
6352 	/*
6353 	 * now that we biodoned that command, if persistent errors have been
6354 	 * flagged, flush the waitq
6355 	 */
6356 	if (pe_flagged)
6357 		st_flush(un);
6358 }
6359 
6360 
6361 /*
6362  * Tape error, flush tape driver queue.
6363  */
6364 static void
6365 st_flush(struct scsi_tape *un)
6366 {
6367 	struct buf *bp;
6368 
6369 	mutex_enter(ST_MUTEX);
6370 
6371 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6372 	    "st_flush(), ncmds = %d, quef = 0x%p\n",
6373 	    un->un_ncmds, (void *)un->un_quef);
6374 
6375 	/*
6376 	 * if we still have commands outstanding, wait for them to come in
6377 	 * before flushing the queue, and make sure there is a queue
6378 	 */
6379 	if (un->un_ncmds || !un->un_quef)
6380 		goto exit;
6381 
6382 	/*
6383 	 * we have no more commands outstanding, so let's deal with special
6384 	 * cases in the queue for EOM and FM. If we are here, and un_errno
6385 	 * is 0, then we know there was no error and we return a 0 read or
6386 	 * write before showing errors
6387 	 */
6388 
6389 	/* Flush the wait queue. */
6390 	while ((bp = un->un_quef) != NULL) {
6391 		un->un_quef = bp->b_actf;
6392 
6393 		bp->b_resid = bp->b_bcount;
6394 
6395 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
6396 		    "st_flush() : blkno=%ld, err=%d, b_bcount=%ld\n",
6397 		    un->un_blkno, un->un_errno, bp->b_bcount);
6398 
6399 		st_set_pe_errno(un);
6400 
6401 		bioerror(bp, un->un_errno);
6402 
6403 		mutex_exit(ST_MUTEX);
6404 		/* it should have one, but check anyway */
6405 		if (BP_PKT(bp)) {
6406 			scsi_destroy_pkt(BP_PKT(bp));
6407 		}
6408 		biodone(bp);
6409 		mutex_enter(ST_MUTEX);
6410 	}
6411 
6412 	/*
6413 	 * It's not a bad practice to reset the
6414 	 * waitq tail pointer to NULL.
6415 	 */
6416 	un->un_quel = NULL;
6417 
6418 exit:
6419 	/* we mucked with the queue, so let others know about it */
6420 	cv_signal(&un->un_queue_cv);
6421 	mutex_exit(ST_MUTEX);
6422 }
6423 
6424 
6425 /*
6426  * Utility functions
6427  */
6428 static int
6429 st_determine_generic(dev_t dev)
6430 {
6431 	int bsize;
6432 	static char *cart = "0.25 inch cartridge";
6433 	char *sizestr;
6434 
6435 	GET_SOFT_STATE(dev);
6436 
6437 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6438 	    "st_determine_generic(dev = 0x%lx)\n", dev);
6439 
6440 	ASSERT(mutex_owned(ST_MUTEX));
6441 
6442 	if (st_modesense(un)) {
6443 		return (-1);
6444 	}
6445 
6446 	bsize = (un->un_mspl->high_bl << 16)	|
6447 		(un->un_mspl->mid_bl << 8)	|
6448 		(un->un_mspl->low_bl);
6449 
6450 	if (bsize == 0) {
6451 		un->un_dp->options |= ST_VARIABLE;
6452 		un->un_dp->bsize = 0;
6453 		un->un_bsize = 0;
6454 	} else if (bsize > ST_MAXRECSIZE_FIXED) {
6455 		/*
6456 		 * record size of this device too big.
6457 		 * try and convert it to variable record length.
6458 		 *
6459 		 */
6460 		un->un_dp->options |= ST_VARIABLE;
6461 		if (st_change_block_size(dev, 0) != 0) {
6462 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6463 			    "Fixed Record Size %d is too large\n", bsize);
6464 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
6465 			    "Cannot switch to variable record size\n");
6466 			un->un_dp->options &= ~ST_VARIABLE;
6467 			return (-1);
6468 		}
6469 	} else if (st_change_block_size(dev, 0) == 0) {
6470 		/*
6471 		 * If the drive was set to a non zero block size,
6472 		 * See if it can be set to a zero block size.
6473 		 * If it works, ST_VARIABLE so user can set it as they want.
6474 		 */
6475 		un->un_dp->options |= ST_VARIABLE;
6476 		un->un_dp->bsize = 0;
6477 		un->un_bsize = 0;
6478 	} else {
6479 		un->un_dp->bsize = bsize;
6480 		un->un_bsize = bsize;
6481 	}
6482 
6483 
6484 	switch (un->un_mspl->density) {
6485 	default:
6486 	case 0x0:
6487 		/*
6488 		 * default density, cannot determine any other
6489 		 * information.
6490 		 */
6491 		sizestr = "Unknown type- assuming 0.25 inch cartridge";
6492 		un->un_dp->type = ST_TYPE_DEFAULT;
6493 		un->un_dp->options |= (ST_AUTODEN_OVERRIDE|ST_QIC);
6494 		break;
6495 	case 0x1:
6496 	case 0x2:
6497 	case 0x3:
6498 	case 0x6:
6499 		/*
6500 		 * 1/2" reel
6501 		 */
6502 		sizestr = "0.50 inch reel";
6503 		un->un_dp->type = ST_TYPE_REEL;
6504 		un->un_dp->options |= ST_REEL;
6505 		un->un_dp->densities[0] = 0x1;
6506 		un->un_dp->densities[1] = 0x2;
6507 		un->un_dp->densities[2] = 0x6;
6508 		un->un_dp->densities[3] = 0x3;
6509 		break;
6510 	case 0x4:
6511 	case 0x5:
6512 	case 0x7:
6513 	case 0x0b:
6514 
6515 		/*
6516 		 * Quarter inch.
6517 		 */
6518 		sizestr = cart;
6519 		un->un_dp->type = ST_TYPE_DEFAULT;
6520 		un->un_dp->options |= ST_QIC;
6521 
6522 		un->un_dp->densities[1] = 0x4;
6523 		un->un_dp->densities[2] = 0x5;
6524 		un->un_dp->densities[3] = 0x7;
6525 		un->un_dp->densities[0] = 0x0b;
6526 		break;
6527 
6528 	case 0x0f:
6529 	case 0x10:
6530 	case 0x11:
6531 	case 0x12:
6532 		/*
6533 		 * QIC-120, QIC-150, QIC-320, QIC-600
6534 		 */
6535 		sizestr = cart;
6536 		un->un_dp->type = ST_TYPE_DEFAULT;
6537 		un->un_dp->options |= ST_QIC;
6538 		un->un_dp->densities[0] = 0x0f;
6539 		un->un_dp->densities[1] = 0x10;
6540 		un->un_dp->densities[2] = 0x11;
6541 		un->un_dp->densities[3] = 0x12;
6542 		break;
6543 
6544 	case 0x09:
6545 	case 0x0a:
6546 	case 0x0c:
6547 	case 0x0d:
6548 		/*
6549 		 * 1/2" cartridge tapes. Include HI-TC.
6550 		 */
6551 		sizestr = cart;
6552 		sizestr[2] = '5';
6553 		sizestr[3] = '0';
6554 		un->un_dp->type = ST_TYPE_HIC;
6555 		un->un_dp->densities[0] = 0x09;
6556 		un->un_dp->densities[1] = 0x0a;
6557 		un->un_dp->densities[2] = 0x0c;
6558 		un->un_dp->densities[3] = 0x0d;
6559 		break;
6560 
6561 	case 0x13:
6562 			/* DDS-2/DDS-3 scsi spec densities */
6563 	case 0x24:
6564 	case 0x25:
6565 	case 0x26:
6566 		sizestr = "DAT Data Storage (DDS)";
6567 		un->un_dp->type = ST_TYPE_DAT;
6568 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6569 		break;
6570 
6571 	case 0x14:
6572 		/*
6573 		 * Helical Scan (Exabyte) devices
6574 		 */
6575 		sizestr = "8mm helical scan cartridge";
6576 		un->un_dp->type = ST_TYPE_EXABYTE;
6577 		un->un_dp->options |= ST_AUTODEN_OVERRIDE;
6578 		break;
6579 	}
6580 
6581 	/*
6582 	 * Assume LONG ERASE, BSF and BSR
6583 	 */
6584 
6585 	un->un_dp->options |= (ST_LONG_ERASE|ST_UNLOADABLE|ST_BSF|
6586 				ST_BSR|ST_KNOWS_EOD);
6587 
6588 	/*
6589 	 * Only if mode sense data says no buffered write, set NOBUF
6590 	 */
6591 	if (un->un_mspl->bufm == 0)
6592 		un->un_dp->options |= ST_NOBUF;
6593 
6594 	/*
6595 	 * set up large read and write retry counts
6596 	 */
6597 
6598 	un->un_dp->max_rretries = un->un_dp->max_wretries = 1000;
6599 
6600 	/*
6601 	 * If this is a 0.50 inch reel tape, and
6602 	 * it is *not* variable mode, try and
6603 	 * set it to variable record length
6604 	 * mode.
6605 	 */
6606 	if ((un->un_dp->options & ST_REEL) && un->un_bsize != 0 &&
6607 	    (un->un_dp->options & ST_VARIABLE)) {
6608 		if (st_change_block_size(dev, 0) == 0) {
6609 			un->un_dp->bsize = 0;
6610 			un->un_mspl->high_bl = un->un_mspl->mid_bl =
6611 			    un->un_mspl->low_bl = 0;
6612 		}
6613 	}
6614 
6615 	/*
6616 	 * Write to console about type of device found
6617 	 */
6618 	ST_DEBUG6(ST_DEVINFO, st_label, CE_NOTE,
6619 	    "Generic Drive, Vendor=%s\n\t%s", un->un_dp->name,
6620 	    sizestr);
6621 	if (un->un_dp->options & ST_VARIABLE) {
6622 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6623 		    "!Variable record length I/O\n");
6624 	} else {
6625 		scsi_log(ST_DEVINFO, st_label, CE_NOTE,
6626 		    "!Fixed record length (%d byte blocks) I/O\n",
6627 		    un->un_dp->bsize);
6628 	}
6629 	ASSERT(mutex_owned(ST_MUTEX));
6630 	return (0);
6631 }
6632 
6633 static int
6634 st_determine_density(dev_t dev, int rw)
6635 {
6636 	int rval = 0;
6637 
6638 	GET_SOFT_STATE(dev);
6639 
6640 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6641 	    "st_determine_density(dev = 0x%lx, rw = %s)\n",
6642 	    dev, (rw == B_WRITE ? wr_str: rd_str));
6643 
6644 	ASSERT(mutex_owned(ST_MUTEX));
6645 
6646 	/*
6647 	 * If we're past BOT, density is determined already.
6648 	 */
6649 	if (un->un_fileno > 0 || (un->un_fileno == 0 && un->un_blkno != 0)) {
6650 		/*
6651 		 * XXX: put in a bitch message about attempting to
6652 		 * XXX: change density past BOT.
6653 		 */
6654 		goto exit;
6655 	}
6656 
6657 	/*
6658 	 * If we're going to be writing, we set the density
6659 	 */
6660 	if (rw == 0 || rw == B_WRITE) {
6661 		/* un_curdens is used as an index into densities table */
6662 		un->un_curdens = MT_DENSITY(un->un_dev);
6663 		if (st_set_density(dev)) {
6664 			rval = -1;
6665 		}
6666 		goto exit;
6667 	}
6668 
6669 	/*
6670 	 * If density is known already,
6671 	 * we don't have to get it again.(?)
6672 	 */
6673 	if (!un->un_density_known) {
6674 		if (st_get_density(dev)) {
6675 			rval = -1;
6676 		}
6677 	}
6678 
6679 exit:
6680 	ASSERT(mutex_owned(ST_MUTEX));
6681 	return (rval);
6682 }
6683 
6684 
6685 /*
6686  * Try to determine density. We do this by attempting to read the
6687  * first record off the tape, cycling through the available density
6688  * codes as we go.
6689  */
6690 
6691 static int
6692 st_get_density(dev_t dev)
6693 {
6694 	int succes = 0, rval = -1, i;
6695 	uint_t size;
6696 	uchar_t dens, olddens;
6697 
6698 	GET_SOFT_STATE(dev);
6699 
6700 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6701 	    "st_get_density(dev = 0x%lx)\n", dev);
6702 
6703 	ASSERT(mutex_owned(ST_MUTEX));
6704 
6705 	/*
6706 	 * If Auto Density override is enabled The drive has
6707 	 * only one density and there is no point in attempting
6708 	 * find the correct one.
6709 	 *
6710 	 * Since most modern drives auto detect the density
6711 	 * and format of the recorded media before they come
6712 	 * ready. What this function does is a legacy behavior
6713 	 * and modern drives not only don't need it, The backup
6714 	 * utilities that do positioning via uscsi find the un-
6715 	 * expected rewinds problematic.
6716 	 *
6717 	 * The drives that need this are old reel to reel devices.
6718 	 * I took a swag and said they must be scsi-1 or older.
6719 	 * I don't beleave there will any of the newer devices
6720 	 * that need this. There will be some scsi-1 devices that
6721 	 * don't need this but I don't think they will be using the
6722 	 * BIG aftermarket backup and restore utilitys.
6723 	 */
6724 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) ||
6725 	    (un->un_sd->sd_inq->inq_ansi > 1)) {
6726 		un->un_density_known = 1;
6727 		rval = 0;
6728 		goto exit;
6729 	}
6730 
6731 	/*
6732 	 * This will only work on variable record length tapes
6733 	 * if and only if all variable record length tapes autodensity
6734 	 * select.
6735 	 */
6736 	size = (unsigned)(un->un_dp->bsize ? un->un_dp->bsize : SECSIZE);
6737 	un->un_tmpbuf = kmem_alloc(size, KM_SLEEP);
6738 
6739 	/*
6740 	 * Start at the specified density
6741 	 */
6742 
6743 	dens = olddens = un->un_curdens = MT_DENSITY(un->un_dev);
6744 
6745 	for (i = 0; i < NDENSITIES; i++, ((un->un_curdens == NDENSITIES - 1) ?
6746 					(un->un_curdens = 0) :
6747 					(un->un_curdens += 1))) {
6748 		/*
6749 		 * If we've done this density before,
6750 		 * don't bother to do it again.
6751 		 */
6752 		dens = un->un_dp->densities[un->un_curdens];
6753 		if (i > 0 && dens == olddens)
6754 			continue;
6755 		olddens = dens;
6756 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6757 		    "trying density 0x%x\n", dens);
6758 		if (st_set_density(dev)) {
6759 			continue;
6760 		}
6761 
6762 		/*
6763 		 * XXX - the creates lots of headaches and slowdowns - must
6764 		 * fix.
6765 		 */
6766 		succes = (st_cmd(dev, SCMD_READ, (int)size, SYNC_CMD) == 0);
6767 		if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD)) {
6768 			break;
6769 		}
6770 		if (succes) {
6771 			st_init(un);
6772 			rval = 0;
6773 			un->un_density_known = 1;
6774 			break;
6775 		}
6776 	}
6777 	kmem_free(un->un_tmpbuf, size);
6778 	un->un_tmpbuf = 0;
6779 
6780 exit:
6781 	ASSERT(mutex_owned(ST_MUTEX));
6782 	return (rval);
6783 }
6784 
6785 static int
6786 st_set_density(dev_t dev)
6787 {
6788 	int rval = 0;
6789 
6790 	GET_SOFT_STATE(dev);
6791 
6792 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6793 	    "st_set_density(dev = 0x%lx): density = 0x%x\n", dev,
6794 	    un->un_dp->densities[un->un_curdens]);
6795 
6796 	ASSERT(mutex_owned(ST_MUTEX));
6797 
6798 	un->un_mspl->density = un->un_dp->densities[un->un_curdens];
6799 
6800 	if ((un->un_dp->options & ST_AUTODEN_OVERRIDE) == 0) {
6801 		/*
6802 		 * If auto density override is not set, Use mode select
6803 		 * to set density and compression.
6804 		 */
6805 		if (st_modeselect(un)) {
6806 			rval = -1;
6807 		}
6808 	} else if ((un->un_dp->options & ST_MODE_SEL_COMP) != 0) {
6809 		/*
6810 		 * If auto density and mode select compression are set,
6811 		 * This is a drive with one density code but compression
6812 		 * can be enabled or disabled.
6813 		 * Set compression but no need to set density.
6814 		 */
6815 		rval = st_set_compression(un);
6816 		if ((rval != 0) && (rval != EALREADY)) {
6817 			rval = -1;
6818 		} else {
6819 			rval = 0;
6820 		}
6821 	}
6822 
6823 	/* If sucessful set density and/or compression, mark density known */
6824 	if (rval == 0) {
6825 		un->un_density_known = 1;
6826 	}
6827 
6828 	ASSERT(mutex_owned(ST_MUTEX));
6829 	return (rval);
6830 }
6831 
6832 static int
6833 st_loadtape(dev_t dev)
6834 {
6835 	int rval = 0;
6836 
6837 	GET_SOFT_STATE(dev);
6838 
6839 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6840 	    "st_loadtape(dev = 0x%lx)\n", dev);
6841 
6842 	ASSERT(mutex_owned(ST_MUTEX));
6843 
6844 	/*
6845 	 * 'LOAD' the tape to BOT by rewinding
6846 	 */
6847 	if (st_cmd(dev, SCMD_REWIND, 1, SYNC_CMD)) {
6848 		rval = -1;
6849 	} else {
6850 		st_init(un);
6851 		un->un_density_known = 0;
6852 	}
6853 
6854 	ASSERT(mutex_owned(ST_MUTEX));
6855 	return (rval);
6856 }
6857 
6858 
6859 /*
6860  * Note: QIC devices aren't so smart.  If you try to append
6861  * after EOM, the write can fail because the device doesn't know
6862  * it's at EOM.	 In that case, issue a read.  The read should fail
6863  * because there's no data, but the device knows it's at EOM,
6864  * so a subsequent write should succeed.  To further confuse matters,
6865  * the target returns the same error if the tape is positioned
6866  * such that a write would overwrite existing data.  That's why
6867  * we have to do the append test.  A read in the middle of
6868  * recorded data would succeed, thus indicating we're attempting
6869  * something illegal.
6870  */
6871 
6872 void bp_mapin(struct buf *bp);
6873 
6874 static void
6875 st_test_append(struct buf *bp)
6876 {
6877 	dev_t dev = bp->b_edev;
6878 	struct scsi_tape *un;
6879 	uchar_t status;
6880 	unsigned bcount;
6881 
6882 	un = ddi_get_soft_state(st_state, MTUNIT(dev));
6883 
6884 	ASSERT(mutex_owned(ST_MUTEX));
6885 
6886 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6887 	    "st_test_append(): fileno %d\n", un->un_fileno);
6888 
6889 	un->un_laststate = un->un_state;
6890 	un->un_state = ST_STATE_APPEND_TESTING;
6891 	un->un_test_append = 0;
6892 
6893 	/*
6894 	 * first, map in the buffer, because we're doing a double write --
6895 	 * first into the kernel, then onto the tape.
6896 	 */
6897 	bp_mapin(bp);
6898 
6899 	/*
6900 	 * get a copy of the data....
6901 	 */
6902 	un->un_tmpbuf = kmem_alloc((unsigned)bp->b_bcount, KM_SLEEP);
6903 	bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
6904 
6905 	/*
6906 	 * attempt the write..
6907 	 */
6908 
6909 	if (st_cmd(dev, (int)SCMD_WRITE, (int)bp->b_bcount, SYNC_CMD) == 0) {
6910 success:
6911 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6912 		    "append write succeeded\n");
6913 		bp->b_resid = un->un_sbufp->b_resid;
6914 		mutex_exit(ST_MUTEX);
6915 		bcount = (unsigned)bp->b_bcount;
6916 		biodone(bp);
6917 		mutex_enter(ST_MUTEX);
6918 		un->un_laststate = un->un_state;
6919 		un->un_state = ST_STATE_OPEN;
6920 		kmem_free(un->un_tmpbuf, bcount);
6921 		un->un_tmpbuf = NULL;
6922 		return;
6923 	}
6924 
6925 	/*
6926 	 * The append failed. Do a short read. If that fails,  we are at EOM
6927 	 * so we can retry the write command. If that succeeds, than we're
6928 	 * all screwed up (the controller reported a real error).
6929 	 *
6930 	 * XXX: should the dummy read be > SECSIZE? should it be the device's
6931 	 * XXX: block size?
6932 	 *
6933 	 */
6934 	status = un->un_status;
6935 	un->un_status = 0;
6936 	(void) st_cmd(dev, SCMD_READ, SECSIZE, SYNC_CMD);
6937 	if (un->un_status == KEY_BLANK_CHECK) {
6938 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6939 		    "append at EOM\n");
6940 		/*
6941 		 * Okay- the read failed. We should actually have confused
6942 		 * the controller enough to allow writing. In any case, the
6943 		 * i/o is on its own from here on out.
6944 		 */
6945 		un->un_laststate = un->un_state;
6946 		un->un_state = ST_STATE_OPEN;
6947 		bcopy(bp->b_un.b_addr, un->un_tmpbuf, (uint_t)bp->b_bcount);
6948 		if (st_cmd(dev, (int)SCMD_WRITE, (int)bp->b_bcount,
6949 		    SYNC_CMD) == 0) {
6950 			goto success;
6951 		}
6952 	}
6953 
6954 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6955 	    "append write failed- not at EOM\n");
6956 	bp->b_resid = bp->b_bcount;
6957 	st_bioerror(bp, EIO);
6958 
6959 	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6960 	    "st_test_append : EIO : append write failed - not at EOM");
6961 
6962 	/*
6963 	 * backspace one record to get back to where we were
6964 	 */
6965 	if (st_cmd(dev, SCMD_SPACE, Blk(-1), SYNC_CMD)) {
6966 		un->un_fileno = -1;
6967 	}
6968 
6969 	un->un_err_resid = bp->b_resid;
6970 	un->un_status = status;
6971 
6972 	/*
6973 	 * Note: biodone will do a bp_mapout()
6974 	 */
6975 	mutex_exit(ST_MUTEX);
6976 	bcount = (unsigned)bp->b_bcount;
6977 	biodone(bp);
6978 	mutex_enter(ST_MUTEX);
6979 	un->un_laststate = un->un_state;
6980 	un->un_state = ST_STATE_OPEN_PENDING_IO;
6981 	kmem_free(un->un_tmpbuf, bcount);
6982 	un->un_tmpbuf = NULL;
6983 }
6984 
6985 /*
6986  * Special command handler
6987  */
6988 
6989 /*
6990  * common st_cmd code. The fourth parameter states
6991  * whether the caller wishes to await the results
6992  * Note the release of the mutex during most of the function
6993  */
6994 static int
6995 st_cmd(dev_t dev, int com, int count, int wait)
6996 {
6997 	struct buf *bp;
6998 	int err;
6999 
7000 	GET_SOFT_STATE(dev);
7001 
7002 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7003 	    "st_cmd(dev = 0x%lx, com = 0x%x, count = %x, wait = %d)\n",
7004 	    dev, com, count, wait);
7005 
7006 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
7007 	ASSERT(mutex_owned(ST_MUTEX));
7008 
7009 #ifdef STDEBUG
7010 	if (st_debug)
7011 		st_debug_cmds(un, com, count, wait);
7012 #endif
7013 
7014 	while (un->un_sbuf_busy)
7015 		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
7016 	un->un_sbuf_busy = 1;
7017 
7018 	bp = un->un_sbufp;
7019 	bzero(bp, sizeof (buf_t));
7020 
7021 	bp->b_flags = (wait) ? B_BUSY : B_BUSY|B_ASYNC;
7022 
7023 	/*
7024 	 * Set count to the actual size of the data tranfer.
7025 	 * For commands with no data transfer, set bp->b_bcount
7026 	 * to the value to be used when constructing the
7027 	 * cdb in st_make_cmd().
7028 	 */
7029 	switch (com) {
7030 	case SCMD_READ:
7031 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7032 		    "special read %d\n", count);
7033 		bp->b_flags |= B_READ;
7034 		bp->b_un.b_addr = un->un_tmpbuf;
7035 		break;
7036 
7037 	case SCMD_WRITE:
7038 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7039 		    "special write %d\n", count);
7040 		bp->b_un.b_addr = un->un_tmpbuf;
7041 		break;
7042 
7043 	case SCMD_WRITE_FILE_MARK:
7044 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7045 		    "write %d file marks\n", count);
7046 		bp->b_bcount = count;
7047 		count = 0;
7048 		break;
7049 
7050 	case SCMD_REWIND:
7051 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "rewind\n");
7052 		bp->b_bcount = 0;
7053 		count = 0;
7054 		break;
7055 
7056 	case SCMD_SPACE:
7057 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "space\n");
7058 		bp->b_bcount = count;
7059 		count = 0;
7060 		break;
7061 
7062 	case SCMD_RESERVE:
7063 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "reserve");
7064 		bp->b_bcount = 0;
7065 		count = 0;
7066 		break;
7067 
7068 	case SCMD_RELEASE:
7069 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "release");
7070 		bp->b_bcount = 0;
7071 		count = 0;
7072 		break;
7073 
7074 	case SCMD_LOAD:
7075 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7076 		    "%s tape\n", (count) ? "load" : "unload");
7077 		bp->b_bcount = count;
7078 		count = 0;
7079 		break;
7080 
7081 	case SCMD_ERASE:
7082 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7083 		    "erase tape\n");
7084 		bp->b_bcount = 0;
7085 		count = 0;
7086 		break;
7087 
7088 	case SCMD_MODE_SENSE:
7089 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7090 		    "mode sense\n");
7091 		bp->b_flags |= B_READ;
7092 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7093 		break;
7094 
7095 	case SCMD_MODE_SELECT:
7096 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7097 		    "mode select\n");
7098 		bp->b_un.b_addr = (caddr_t)(un->un_mspl);
7099 		break;
7100 
7101 	case SCMD_READ_BLKLIM:
7102 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7103 		    "read block limits\n");
7104 		bp->b_flags |= B_READ;
7105 		bp->b_un.b_addr = (caddr_t)(un->un_rbl);
7106 		break;
7107 
7108 	case SCMD_TEST_UNIT_READY:
7109 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7110 		    "test unit ready\n");
7111 		bp->b_bcount = 0;
7112 		count = 0;
7113 		break;
7114 	default:
7115 		ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7116 		    "Unhandled scsi command 0x%x in st_cmd()\n", com);
7117 	}
7118 
7119 	mutex_exit(ST_MUTEX);
7120 
7121 	if (count > 0) {
7122 		/*
7123 		 * We're going to do actual I/O.
7124 		 * Set things up for physio.
7125 		 */
7126 		struct iovec aiov;
7127 		struct uio auio;
7128 		struct uio *uio = &auio;
7129 
7130 		bzero(&auio, sizeof (struct uio));
7131 		bzero(&aiov, sizeof (struct iovec));
7132 		aiov.iov_base = bp->b_un.b_addr;
7133 		aiov.iov_len = count;
7134 
7135 		uio->uio_iov = &aiov;
7136 		uio->uio_iovcnt = 1;
7137 		uio->uio_resid = aiov.iov_len;
7138 		uio->uio_segflg = UIO_SYSSPACE;
7139 
7140 		/*
7141 		 * Let physio do the rest...
7142 		 */
7143 		bp->b_forw = (struct buf *)(uintptr_t)com;
7144 		bp->b_back = NULL;
7145 		err = physio(st_strategy, bp, dev,
7146 			(bp->b_flags & B_READ) ? B_READ : B_WRITE,
7147 			st_minphys, uio);
7148 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7149 		    "st_cmd: physio returns %d\n", err);
7150 	} else {
7151 		/*
7152 		 * Mimic physio
7153 		 */
7154 		bp->b_forw = (struct buf *)(uintptr_t)com;
7155 		bp->b_back = NULL;
7156 		bp->b_edev = dev;
7157 		bp->b_dev = cmpdev(dev);
7158 		bp->b_blkno = 0;
7159 		bp->b_resid = 0;
7160 		(void) st_strategy(bp);
7161 		if (!wait) {
7162 			/*
7163 			 * This is an async command- the caller won't wait
7164 			 * and doesn't care about errors.
7165 			 */
7166 			mutex_enter(ST_MUTEX);
7167 			return (0);
7168 		}
7169 
7170 		/*
7171 		 * BugTraq #4260046
7172 		 * ----------------
7173 		 * Restore Solaris 2.5.1 behavior, namely call biowait
7174 		 * unconditionally. The old comment said...
7175 		 *
7176 		 * "if strategy was flagged with  persistent errors, we would
7177 		 *  have an error here, and the bp would never be sent, so we
7178 		 *  don't want to wait on a bp that was never sent...or hang"
7179 		 *
7180 		 * The new rationale, courtesy of Chitrank...
7181 		 *
7182 		 * "we should unconditionally biowait() here because
7183 		 *  st_strategy() will do a biodone() in the persistent error
7184 		 *  case and the following biowait() will return immediately.
7185 		 *  If not, in the case of "errors after pkt alloc" in
7186 		 *  st_start(), we will not biowait here which will cause the
7187 		 *  next biowait() to return immediately which will cause
7188 		 *  us to send out the next command. In the case where both of
7189 		 *  these use the sbuf, when the first command completes we'll
7190 		 *  free the packet attached to sbuf and the same pkt will
7191 		 *  get freed again when we complete the second command.
7192 		 *  see esc 518987.  BTW, it is necessary to do biodone() in
7193 		 *  st_start() for the pkt alloc failure case because physio()
7194 		 *  does biowait() and will hang if we don't do biodone()"
7195 		 */
7196 
7197 		err = biowait(bp);
7198 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7199 		    "st_cmd: biowait returns %d\n", err);
7200 	}
7201 	mutex_enter(ST_MUTEX);
7202 
7203 	un->un_sbuf_busy = 0;
7204 	cv_signal(&un->un_sbuf_cv);
7205 	return (err);
7206 }
7207 
7208 static int
7209 st_set_compression(struct scsi_tape *un)
7210 {
7211 	int rval;
7212 	int turn_compression_on;
7213 	minor_t minor;
7214 
7215 	/*
7216 	 * Drive either dosn't have compression or it is controlled with
7217 	 * special density codes. Return ENOTTY so caller
7218 	 * knows nothing was done.
7219 	 */
7220 	if ((un->un_dp->options & ST_MODE_SEL_COMP) == 0) {
7221 		un->un_comp_page = 0;
7222 		return (ENOTTY);
7223 	}
7224 
7225 	/* set compression based on minor node opened */
7226 	minor = MT_DENSITY(un->un_dev);
7227 
7228 	/*
7229 	 * If this the compression density or
7230 	 * the drive has two densities and uses mode select for
7231 	 * control of compression turn on compression for MT_DENSITY2
7232 	 * as well.
7233 	 */
7234 	if ((minor == ST_COMPRESSION_DENSITY) ||
7235 	    (minor == MT_DENSITY(MT_DENSITY2)) &&
7236 	    (un->un_dp->densities[0] == un->un_dp->densities[1]) &&
7237 	    (un->un_dp->densities[2] == un->un_dp->densities[3]) &&
7238 	    (un->un_dp->densities[0] != un->un_dp->densities[2])) {
7239 
7240 		turn_compression_on = 1;
7241 	} else {
7242 		turn_compression_on = 0;
7243 	}
7244 
7245 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7246 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7247 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7248 
7249 	/*
7250 	 * Need to determine which page does the device use for compression.
7251 	 * First try the data compression page. If this fails try the device
7252 	 * configuration page
7253 	 */
7254 
7255 	if ((un->un_comp_page & ST_DEV_DATACOMP_PAGE) == ST_DEV_DATACOMP_PAGE) {
7256 		rval = st_set_datacomp_page(un, turn_compression_on);
7257 		if (rval == EALREADY) {
7258 			return (rval);
7259 		}
7260 		if (rval != 0) {
7261 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7262 				/*
7263 				 * This device does not support data
7264 				 * compression page
7265 				 */
7266 				un->un_comp_page = ST_DEV_CONFIG_PAGE;
7267 			} else if (un->un_state >= ST_STATE_OPEN) {
7268 				un->un_fileno = -1;
7269 				rval = EIO;
7270 			} else {
7271 				rval = -1;
7272 			}
7273 		} else {
7274 			un->un_comp_page = ST_DEV_DATACOMP_PAGE;
7275 		}
7276 	}
7277 
7278 	if ((un->un_comp_page & ST_DEV_CONFIG_PAGE) == ST_DEV_CONFIG_PAGE) {
7279 		rval = st_set_devconfig_page(un, turn_compression_on);
7280 		if (rval == EALREADY) {
7281 			return (rval);
7282 		}
7283 		if (rval != 0) {
7284 			if (un->un_status == KEY_ILLEGAL_REQUEST) {
7285 				/*
7286 				 * This device does not support
7287 				 * compression at all advice the
7288 				 * user and unset ST_MODE_SEL_COMP
7289 				 */
7290 				un->un_dp->options &= ~ST_MODE_SEL_COMP;
7291 				un->un_comp_page = 0;
7292 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
7293 				    "Device Does Not Support Compression\n");
7294 			} else if (un->un_state >= ST_STATE_OPEN) {
7295 				un->un_fileno = -1;
7296 				rval = EIO;
7297 			} else {
7298 				rval = -1;
7299 			}
7300 		}
7301 	}
7302 
7303 	return (rval);
7304 }
7305 
7306 /*
7307  * set or unset compression thru device configuration page.
7308  */
7309 static int
7310 st_set_devconfig_page(struct scsi_tape *un, int compression_on)
7311 {
7312 	unsigned char cflag;
7313 	int rval = 0;
7314 
7315 	ASSERT(mutex_owned(ST_MUTEX));
7316 
7317 	/*
7318 	 * Figure what to set compression flag to.
7319 	 */
7320 	if (compression_on) {
7321 		/* They have selected a compression node */
7322 		if (un->un_dp->type == ST_TYPE_FUJI) {
7323 			cflag = 0x84;   /* use EDRC */
7324 		} else {
7325 			cflag = ST_DEV_CONFIG_DEF_COMP;
7326 		}
7327 	} else {
7328 		cflag = ST_DEV_CONFIG_NO_COMP;
7329 	}
7330 
7331 	/*
7332 	 * If compression is already set the way it was requested.
7333 	 * And if this not the first time we has tried.
7334 	 */
7335 	if ((cflag == un->un_mspl->page.dev.comp_alg) &&
7336 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7337 		return (EALREADY);
7338 	}
7339 
7340 	un->un_mspl->page.dev.comp_alg = cflag;
7341 	/*
7342 	 * need to send mode select even if correct compression is
7343 	 * already set since need to set density code
7344 	 */
7345 
7346 #ifdef STDEBUG
7347 	if (st_debug >= 6) {
7348 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7349 		    "st_set_devconfig_page: sense data for mode select",
7350 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7351 	}
7352 #endif
7353 	rval = st_gen_mode_select(un, un->un_mspl, sizeof (struct seq_mode));
7354 
7355 	return (rval);
7356 }
7357 
7358 /*
7359  * set/reset compression bit thru data compression page
7360  */
7361 static int
7362 st_set_datacomp_page(struct scsi_tape *un, int compression_on)
7363 {
7364 	int compression_on_already;
7365 	int rval = 0;
7366 
7367 	ASSERT(mutex_owned(ST_MUTEX));
7368 
7369 	/*
7370 	 * If drive is not capable of compression (at this time)
7371 	 * return EALREADY so caller doesn't think that this page
7372 	 * is not supported. This check is for drives that can
7373 	 * disable compression from the front panel or configuration.
7374 	 * I doubt that a drive that supports this page is not really
7375 	 * capable of compression.
7376 	 */
7377 	if (un->un_mspl->page.comp.dcc == 0) {
7378 		return (EALREADY);
7379 	}
7380 
7381 	/* See if compression currently turned on */
7382 	if (un->un_mspl->page.comp.dce) {
7383 		compression_on_already = 1;
7384 	} else {
7385 		compression_on_already = 0;
7386 	}
7387 
7388 	/*
7389 	 * If compression is already set the way it was requested.
7390 	 * And if this not the first time we has tried.
7391 	 */
7392 	if ((compression_on == compression_on_already) &&
7393 	    (un->un_comp_page == ST_DEV_DATACOMP_PAGE)) {
7394 		return (EALREADY);
7395 	}
7396 
7397 	/*
7398 	 * if we are already set to the appropriate compression
7399 	 * mode, don't set it again
7400 	 */
7401 	if (compression_on) {
7402 		/* compression selected */
7403 		un->un_mspl->page.comp.dce = 1;
7404 	} else {
7405 		un->un_mspl->page.comp.dce = 0;
7406 	}
7407 
7408 
7409 #ifdef STDEBUG
7410 	if (st_debug >= 6) {
7411 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
7412 		    "st_set_datacomp_page: sense data for mode select",
7413 		    (char *)un->un_mspl, sizeof (struct seq_mode));
7414 	}
7415 #endif
7416 	rval = st_gen_mode_select(un, un->un_mspl, sizeof (struct seq_mode));
7417 
7418 	return (rval);
7419 }
7420 
7421 static int
7422 st_modesense(struct scsi_tape *un)
7423 {
7424 	int rval;
7425 	uchar_t page;
7426 
7427 	page = un->un_comp_page;
7428 
7429 	switch (page) {
7430 	case ST_DEV_DATACOMP_PAGE:
7431 	case ST_DEV_CONFIG_PAGE: /* fall through */
7432 		rval = st_gen_mode_sense(un, page, un->un_mspl,
7433 		    sizeof (struct seq_mode));
7434 		break;
7435 
7436 	case ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE:
7437 		if (un->un_dp->options & ST_MODE_SEL_COMP) {
7438 			page = ST_DEV_DATACOMP_PAGE;
7439 			rval = st_gen_mode_sense(un, page, un->un_mspl,
7440 			    sizeof (struct seq_mode));
7441 			if (rval == 0 && un->un_mspl->page_code == page) {
7442 				un->un_comp_page = page;
7443 				break;
7444 			}
7445 			page = ST_DEV_CONFIG_PAGE;
7446 			rval = st_gen_mode_sense(un, page, un->un_mspl,
7447 			    sizeof (struct seq_mode));
7448 			if (rval == 0 && un->un_mspl->page_code == page) {
7449 				un->un_comp_page = page;
7450 				break;
7451 			}
7452 			un->un_dp->options &= ~ST_MODE_SEL_COMP;
7453 			un->un_comp_page = 0;
7454 		} else {
7455 			un->un_comp_page = 0;
7456 		}
7457 
7458 	default:	/* fall through */
7459 		rval = st_cmd(un->un_dev, SCMD_MODE_SENSE, MSIZE, SYNC_CMD);
7460 	}
7461 	return (rval);
7462 }
7463 
7464 static int
7465 st_modeselect(struct scsi_tape *un)
7466 {
7467 	int rval = 0;
7468 	int ix;
7469 
7470 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7471 	    "st_modeselect(dev = 0x%lx): density = 0x%x\n",
7472 	    un->un_dev, un->un_mspl->density);
7473 
7474 	ASSERT(mutex_owned(ST_MUTEX));
7475 
7476 	/*
7477 	 * The parameter list should be the same for all of the
7478 	 * cases that follow so set them here
7479 	 *
7480 	 * Try mode select first if if fails set fields manually
7481 	 */
7482 	rval = st_modesense(un);
7483 	if (rval != 0) {
7484 		ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
7485 		    "st_modeselect: First mode sense failed\n");
7486 		un->un_mspl->bd_len  = 8;
7487 		un->un_mspl->high_nb = 0;
7488 		un->un_mspl->mid_nb  = 0;
7489 		un->un_mspl->low_nb  = 0;
7490 	}
7491 	un->un_mspl->high_bl = (uchar_t)(un->un_bsize >> 16);
7492 	un->un_mspl->mid_bl  = (uchar_t)(un->un_bsize >> 8);
7493 	un->un_mspl->low_bl  = (uchar_t)(un->un_bsize);
7494 
7495 
7496 	/*
7497 	 * If configured to use a specific density code for a media type.
7498 	 * curdens is previously set by the minor node opened.
7499 	 * If the media type doesn't match the minor node we change it so it
7500 	 * looks like the correct one was opened.
7501 	 */
7502 	if (un->un_dp->options & ST_KNOWS_MEDIA) {
7503 		uchar_t best;
7504 
7505 		for (best = 0xff, ix = 0; ix < NDENSITIES; ix++) {
7506 			if (un->un_mspl->media_type ==
7507 			    un->un_dp->mediatype[ix]) {
7508 				best = ix;
7509 				/*
7510 				 * It matches but it might not be the only one.
7511 				 * Use the highest matching media type but not
7512 				 * to exceed the density selected by the open.
7513 				 */
7514 				if (ix < un->un_curdens) {
7515 					continue;
7516 				}
7517 				un->un_curdens = ix;
7518 				break;
7519 			}
7520 		}
7521 		/* If a match was found best will not be 0xff any more */
7522 		if (best < NDENSITIES) {
7523 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
7524 			    "found media 0x%X using density 0x%X\n",
7525 			    un->un_mspl->media_type,
7526 			    un->un_dp->densities[best]);
7527 		}
7528 
7529 		un->un_mspl->density = un->un_dp->densities[best];
7530 
7531 	} else {
7532 		/* Otherwise set density based on minor node opened */
7533 		un->un_mspl->density = un->un_dp->densities[un->un_curdens];
7534 	}
7535 
7536 	if (un->un_dp->options & ST_NOBUF) {
7537 		un->un_mspl->bufm = 0;
7538 	} else {
7539 		un->un_mspl->bufm = 1;
7540 	}
7541 
7542 	rval = st_set_compression(un);
7543 
7544 	/*
7545 	 * If st_set_compression returned invalid or already it
7546 	 * found no need to do the mode select.
7547 	 * So do it here.
7548 	 */
7549 	if ((rval == ENOTTY) || (rval == EALREADY)) {
7550 
7551 		/* Zero non-writeable fields */
7552 		un->un_mspl->data_len = 0;
7553 		un->un_mspl->media_type = 0;
7554 		un->un_mspl->wp = 0;
7555 
7556 		/* need to set the density code */
7557 		rval = st_cmd(un->un_dev, SCMD_MODE_SELECT, MSIZE, SYNC_CMD);
7558 		if (rval != 0) {
7559 			if (un->un_state >= ST_STATE_OPEN) {
7560 				ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
7561 				    "unable to set tape mode\n");
7562 				un->un_fileno = -1;
7563 				rval = EIO;
7564 			} else {
7565 				rval = -1;
7566 			}
7567 		}
7568 	}
7569 
7570 	/*
7571 	 * The spec recommends to send a mode sense after a mode select
7572 	 */
7573 	(void) st_modesense(un);
7574 
7575 	ASSERT(mutex_owned(ST_MUTEX));
7576 
7577 	return (rval);
7578 }
7579 
7580 /*
7581  * st_gen_mode_sense
7582  *
7583  * generic mode sense.. it allows for any page
7584  */
7585 static int
7586 st_gen_mode_sense(struct scsi_tape *un, int page, struct seq_mode *page_data,
7587     int page_size)
7588 {
7589 
7590 	int r;
7591 	char	cdb[CDB_GROUP0];
7592 	struct uscsi_cmd *com;
7593 
7594 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
7595 
7596 	bzero(cdb, CDB_GROUP0);
7597 	cdb[0] = SCMD_MODE_SENSE;
7598 	cdb[2] = (char)page;
7599 	cdb[4] = (char)page_size;
7600 
7601 	com->uscsi_cdb = cdb;
7602 	com->uscsi_cdblen = CDB_GROUP0;
7603 	com->uscsi_bufaddr = (caddr_t)page_data;
7604 	com->uscsi_buflen = page_size;
7605 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
7606 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT |
7607 			    USCSI_READ | USCSI_RQENABLE;
7608 
7609 	r = st_ioctl_cmd(un->un_dev, com, UIO_SYSSPACE, UIO_SYSSPACE,
7610 		UIO_SYSSPACE);
7611 	kmem_free(com, sizeof (*com));
7612 	return (r);
7613 }
7614 
7615 /*
7616  * st_gen_mode_select
7617  *
7618  * generic mode select.. it allows for any page
7619  */
7620 static int
7621 st_gen_mode_select(struct scsi_tape *un, struct seq_mode *page_data,
7622     int page_size)
7623 {
7624 
7625 	int r;
7626 	char cdb[CDB_GROUP0];
7627 	struct uscsi_cmd *com;
7628 
7629 	/* Zero non-writeable fields */
7630 	page_data->data_len = 0;
7631 	page_data->media_type = 0;
7632 	page_data->wp = 0;
7633 
7634 	/*
7635 	 * If mode select has any page data, zero the ps (Page Savable) bit.
7636 	 */
7637 	if (page_size > MSIZE) {
7638 		page_data->ps = 0;
7639 	}
7640 
7641 
7642 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
7643 
7644 	/*
7645 	 * then, do a mode select to set what ever info
7646 	 */
7647 	bzero(cdb, CDB_GROUP0);
7648 	cdb[0] = SCMD_MODE_SELECT;
7649 	cdb[1] = 0x10;		/* set PF bit for many third party drives */
7650 	cdb[4] = (char)page_size;
7651 
7652 	com->uscsi_cdb = cdb;
7653 	com->uscsi_cdblen = CDB_GROUP0;
7654 	com->uscsi_bufaddr = (caddr_t)page_data;
7655 	com->uscsi_buflen = page_size;
7656 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
7657 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT
7658 		| USCSI_WRITE | USCSI_RQENABLE;
7659 
7660 	r = st_ioctl_cmd(un->un_dev, com, UIO_SYSSPACE, UIO_SYSSPACE,
7661 		UIO_SYSSPACE);
7662 
7663 	kmem_free(com, sizeof (*com));
7664 	return (r);
7665 }
7666 
7667 /*
7668  * Changes devices blocksize and bsize to requested blocksize nblksz.
7669  * Returns returned value from first failed call or zero on success.
7670  */
7671 static int
7672 st_change_block_size(dev_t dev, uint32_t nblksz)
7673 {
7674 	struct seq_mode *current;
7675 	int rval;
7676 	uint32_t oldblksz;
7677 
7678 	GET_SOFT_STATE(dev);
7679 
7680 	current = kmem_zalloc(MSIZE, KM_SLEEP);
7681 
7682 	/* Read current settings */
7683 	rval = st_gen_mode_sense(un, 0, current, MSIZE);
7684 	if (rval != 0) {
7685 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
7686 		    "mode sense for change block size failed: rval = %d", rval);
7687 		goto finish;
7688 	}
7689 
7690 	/* Figure the current block size */
7691 	oldblksz =
7692 	    (current->high_bl << 16) |
7693 	    (current->mid_bl << 8) |
7694 	    (current->low_bl);
7695 
7696 	/* If current block size is the same as requested were done */
7697 	if (oldblksz == nblksz) {
7698 		un->un_bsize = nblksz;
7699 		rval = 0;
7700 		goto finish;
7701 	}
7702 
7703 	/* Change to requested block size */
7704 	current->high_bl = (uchar_t)(nblksz >> 16);
7705 	current->mid_bl  = (uchar_t)(nblksz >> 8);
7706 	current->low_bl  = (uchar_t)(nblksz);
7707 
7708 	/* Attempt to change block size */
7709 	rval = st_gen_mode_select(un, current, MSIZE);
7710 	if (rval != 0) {
7711 		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
7712 		    "Set new block size failed: rval = %d", rval);
7713 		goto finish;
7714 	}
7715 
7716 	/* Read back and verify setting */
7717 	rval = st_modesense(un);
7718 	if (rval == 0) {
7719 		un->un_bsize =
7720 		    (un->un_mspl->high_bl << 16) |
7721 		    (un->un_mspl->mid_bl << 8) |
7722 		    (un->un_mspl->low_bl);
7723 
7724 		if (un->un_bsize != nblksz) {
7725 			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
7726 			    "Blocksize set does not equal requested blocksize"
7727 			    "(read: %u requested: %u)\n", nblksz, un->un_bsize);
7728 			rval = EIO;
7729 		}
7730 	}
7731 finish:
7732 	kmem_free(current, MSIZE);
7733 	return (rval);
7734 }
7735 
7736 
7737 static void
7738 st_init(struct scsi_tape *un)
7739 {
7740 	ASSERT(mutex_owned(ST_MUTEX));
7741 
7742 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7743 	"st_init(): dev = 0x%lx, will reset fileno, blkno, eof\n", un->un_dev);
7744 
7745 	un->un_blkno = 0;
7746 	un->un_fileno = 0;
7747 	un->un_lastop = ST_OP_NIL;
7748 	un->un_eof = ST_NO_EOF;
7749 	un->un_pwr_mgmt = ST_PWR_NORMAL;
7750 	if (st_error_level != SCSI_ERR_ALL) {
7751 		if (DEBUGGING) {
7752 			st_error_level = SCSI_ERR_ALL;
7753 		} else {
7754 			st_error_level = SCSI_ERR_RETRYABLE;
7755 		}
7756 	}
7757 }
7758 
7759 
7760 static void
7761 st_make_cmd(struct scsi_tape *un, struct buf *bp, int (*func)(caddr_t))
7762 {
7763 	struct scsi_pkt *pkt;
7764 	struct uscsi_cmd *ucmd;
7765 	int count, tval = 0;
7766 	int flags = 0;
7767 	uchar_t com;
7768 	char fixbit;
7769 
7770 	ASSERT(mutex_owned(ST_MUTEX));
7771 
7772 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
7773 	    "st_make_cmd(): dev = 0x%lx\n", un->un_dev);
7774 
7775 
7776 	/*
7777 	 * fixbit is for setting the Fixed Mode and Suppress Incorrect
7778 	 * Length Indicator bits on read/write commands, for setting
7779 	 * the Long bit on erase commands, and for setting the Code
7780 	 * Field bits on space commands.
7781 	 * XXX why do we set lastop here?
7782 	 */
7783 
7784 	if (bp != un->un_sbufp) {		/* regular raw I/O */
7785 		int stat_size = (un->un_arq_enabled ?
7786 			sizeof (struct scsi_arq_status) : 1);
7787 		pkt = scsi_init_pkt(ROUTE, NULL, bp,
7788 		    CDB_GROUP0, stat_size, 0, 0, func, (caddr_t)un);
7789 		if (pkt == NULL) {
7790 			goto exit;
7791 		}
7792 		SET_BP_PKT(bp, pkt);
7793 		if (un->un_bsize == 0) {
7794 			count = bp->b_bcount;
7795 			fixbit = 0;
7796 		} else {
7797 			count = bp->b_bcount / un->un_bsize;
7798 			fixbit = 1;
7799 		}
7800 		if (bp->b_flags & B_READ) {
7801 			com = SCMD_READ;
7802 			un->un_lastop = ST_OP_READ;
7803 			if ((un->un_bsize == 0) && /* Not Fixed Block */
7804 			    (un->un_dp->options & ST_READ_IGNORE_ILI)) {
7805 				fixbit = 2;
7806 			}
7807 		} else {
7808 			com = SCMD_WRITE;
7809 			un->un_lastop = ST_OP_WRITE;
7810 		}
7811 
7812 		tval = un->un_dp->io_timeout;
7813 
7814 		/*
7815 		 * For really large xfers, increase timeout
7816 		 */
7817 		if (bp->b_bcount > (10 * ONE_MEG))
7818 			tval *= bp->b_bcount/(10 * ONE_MEG);
7819 
7820 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7821 		    "%s %ld amt 0x%lx\n", (com == SCMD_WRITE) ?
7822 		    wr_str: rd_str, un->un_blkno, bp->b_bcount);
7823 
7824 	} else if ((ucmd = BP_UCMD(bp)) != NULL) {
7825 		/*
7826 		 * uscsi - build command, allocate scsi resources
7827 		 */
7828 		st_make_uscsi_cmd(un, ucmd, bp, func);
7829 		goto exit;
7830 
7831 	} else {				/* special I/O */
7832 		struct buf *allocbp = NULL;
7833 		int stat_size = (un->un_arq_enabled ?
7834 			sizeof (struct scsi_arq_status) : 1);
7835 
7836 
7837 		com = (uchar_t)(uintptr_t)bp->b_forw;
7838 		count = bp->b_bcount;
7839 
7840 		switch (com) {
7841 		case SCMD_READ:
7842 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7843 			    "special read %d\n", count);
7844 			if (un->un_bsize == 0) {
7845 				fixbit = 2;	/* suppress SILI */
7846 			} else {
7847 				fixbit = 1;	/* Fixed Block Mode */
7848 				count /= un->un_bsize;
7849 			}
7850 			allocbp = bp;
7851 			un->un_lastop = ST_OP_READ;
7852 			tval = un->un_dp->io_timeout;
7853 			break;
7854 
7855 		case SCMD_WRITE:
7856 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7857 			    "special write %d\n", count);
7858 			if (un->un_bsize != 0) {
7859 				fixbit = 1;	/* Fixed Block Mode */
7860 				count /= un->un_bsize;
7861 			} else {
7862 				fixbit = 0;
7863 			}
7864 			allocbp = bp;
7865 			un->un_lastop = ST_OP_WRITE;
7866 			tval = un->un_dp->io_timeout;
7867 			break;
7868 
7869 		case SCMD_WRITE_FILE_MARK:
7870 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7871 			    "write %d file marks\n", count);
7872 			un->un_lastop = ST_OP_WEOF;
7873 			fixbit = 0;
7874 			tval = un->un_dp->io_timeout;
7875 			break;
7876 
7877 		case SCMD_REWIND:
7878 			fixbit = 0;
7879 			count = 0;
7880 			un->un_lastop = ST_OP_CTL;
7881 			tval = un->un_dp->rewind_timeout;
7882 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7883 			    "rewind\n");
7884 			break;
7885 
7886 		case SCMD_SPACE:
7887 			fixbit = Isfmk(count);
7888 			count = (int)space_cnt(count);
7889 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7890 			    "space %d %s from file %d blk %ld\n",
7891 			    count, (fixbit) ? "filemarks" : "records",
7892 			    un->un_fileno, un->un_blkno);
7893 			un->un_lastop = ST_OP_CTL;
7894 			tval = un->un_dp->space_timeout;
7895 			break;
7896 
7897 		case SCMD_LOAD:
7898 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7899 			    "%s tape\n", (count & 1) ? "load" : "unload");
7900 			fixbit = 0;
7901 
7902 			/* Loading or Unloading */
7903 			if (count & 1) {
7904 				tval = un->un_dp->load_timeout;
7905 			} else {
7906 				tval = un->un_dp->unload_timeout;
7907 			}
7908 			/* Is Retension requested */
7909 			if (count & 2) {
7910 				tval += un->un_dp->rewind_timeout;
7911 			}
7912 			un->un_lastop = ST_OP_CTL;
7913 			break;
7914 
7915 		case SCMD_ERASE:
7916 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7917 			    "erase tape\n");
7918 			count = 0;
7919 			/*
7920 			 * We support long erase only
7921 			 */
7922 			fixbit = 1;
7923 			tval = un->un_dp->erase_timeout;
7924 			un->un_lastop = ST_OP_CTL;
7925 			break;
7926 
7927 		case SCMD_MODE_SENSE:
7928 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7929 			    "mode sense\n");
7930 			allocbp = bp;
7931 			fixbit = 0;
7932 			tval = un->un_dp->non_motion_timeout;
7933 			break;
7934 
7935 		case SCMD_MODE_SELECT:
7936 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7937 			    "mode select\n");
7938 			allocbp = bp;
7939 			fixbit = 0;
7940 			tval = un->un_dp->non_motion_timeout;
7941 			break;
7942 
7943 		case SCMD_RESERVE:
7944 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7945 			    "reserve\n");
7946 			fixbit = 0;
7947 			tval = un->un_dp->non_motion_timeout;
7948 			break;
7949 
7950 		case SCMD_RELEASE:
7951 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7952 			    "release\n");
7953 			fixbit = 0;
7954 			tval = un->un_dp->non_motion_timeout;
7955 			break;
7956 
7957 		case SCMD_READ_BLKLIM:
7958 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7959 			    "read block limits\n");
7960 			allocbp = bp;
7961 			fixbit = count = 0;
7962 			tval = un->un_dp->non_motion_timeout;
7963 			break;
7964 
7965 		case SCMD_TEST_UNIT_READY:
7966 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
7967 			    "test unit ready\n");
7968 			fixbit = 0;
7969 			tval = un->un_dp->non_motion_timeout;
7970 			break;
7971 		default:
7972 			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
7973 			    "Unhandled scsi command 0x%x in st_make_cmd()\n",
7974 			    com);
7975 		}
7976 		pkt = scsi_init_pkt(ROUTE, NULL, allocbp,
7977 			CDB_GROUP0, stat_size, 0, 0, func, (caddr_t)un);
7978 		if (pkt == NULL) {
7979 			goto exit;
7980 		}
7981 		if (allocbp)
7982 			ASSERT(geterror(allocbp) == 0);
7983 
7984 	}
7985 
7986 	(void) scsi_setup_cdb((union scsi_cdb *)pkt->pkt_cdbp,
7987 	    com, 0, (uint_t)count, 0);
7988 	FILL_SCSI1_LUN(un->un_sd, pkt);
7989 	/*
7990 	 * Initialize the SILI/Fixed bits of the byte 1 of cdb.
7991 	 */
7992 	((union scsi_cdb *)(pkt->pkt_cdbp))->t_code = fixbit;
7993 	pkt->pkt_flags = flags;
7994 
7995 	/*
7996 	 * If ST_SHORT_FILEMARKS bit is ON for EXABYTE
7997 	 * device, set the Vendor Unique bit to
7998 	 * write Short File Mark.
7999 	 */
8000 	if (com == SCMD_WRITE_FILE_MARK &&
8001 		un->un_dp->options & ST_SHORT_FILEMARKS) {
8002 		switch (un->un_dp->type) {
8003 		case ST_TYPE_EXB8500:
8004 		case ST_TYPE_EXABYTE:
8005 			/*
8006 			 * Now the Vendor Unique bit 7 in Byte 5 of CDB
8007 			 * is set to to write Short File Mark
8008 			 */
8009 			((union scsi_cdb *)pkt->pkt_cdbp)->g0_vu_1 = 1;
8010 			break;
8011 
8012 		default:
8013 			/*
8014 			 * Well, if ST_SHORT_FILEMARKS is set for other
8015 			 * tape drives, it is just ignored
8016 			 */
8017 			break;
8018 		}
8019 	}
8020 	ASSERT(tval);
8021 	pkt->pkt_time = tval;
8022 	pkt->pkt_comp = st_intr;
8023 	pkt->pkt_private = (opaque_t)bp;
8024 	SET_BP_PKT(bp, pkt);
8025 
8026 exit:
8027 	ASSERT(mutex_owned(ST_MUTEX));
8028 }
8029 
8030 
8031 /*
8032  * Build a command based on a uscsi command;
8033  */
8034 static void
8035 st_make_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
8036     struct buf *bp, int (*func)(caddr_t))
8037 {
8038 	struct scsi_pkt *pkt;
8039 	caddr_t cdb;
8040 	int	cdblen;
8041 	int stat_size;
8042 
8043 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8044 	    "st_make_uscsi_cmd(): dev = 0x%lx\n", un->un_dev);
8045 
8046 	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
8047 		stat_size = (un->un_arq_enabled ?
8048 		    sizeof (struct scsi_arq_status) : 1);
8049 	} else {
8050 		stat_size = 1;
8051 	}
8052 
8053 	ASSERT(mutex_owned(ST_MUTEX));
8054 
8055 	un->un_lastop = ST_OP_CTL;	/* usual */
8056 
8057 	cdb = ucmd->uscsi_cdb;
8058 	cdblen = ucmd->uscsi_cdblen;
8059 
8060 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8061 	    "st_make_uscsi_cmd: buflen=%ld bcount=%ld\n",
8062 		ucmd->uscsi_buflen, bp->b_bcount);
8063 	pkt = scsi_init_pkt(ROUTE, NULL,
8064 		(bp->b_bcount > 0) ? bp : NULL,
8065 		cdblen, stat_size, 0, 0, func, (caddr_t)un);
8066 	if (pkt == NULL) {
8067 		goto exit;
8068 	}
8069 
8070 	bcopy(cdb, pkt->pkt_cdbp, (uint_t)cdblen);
8071 
8072 #ifdef STDEBUG
8073 	if (st_debug >= 6) {
8074 		st_clean_print(ST_DEVINFO, st_label, SCSI_DEBUG,
8075 		    "pkt_cdbp", (char *)cdb, cdblen);
8076 	}
8077 #endif
8078 
8079 	if (ucmd->uscsi_flags & USCSI_SILENT) {
8080 		pkt->pkt_flags |= FLAG_SILENT;
8081 	}
8082 
8083 	pkt->pkt_time = ucmd->uscsi_timeout;
8084 	pkt->pkt_comp = st_intr;
8085 	pkt->pkt_private = (opaque_t)bp;
8086 	SET_BP_PKT(bp, pkt);
8087 exit:
8088 	ASSERT(mutex_owned(ST_MUTEX));
8089 }
8090 
8091 
8092 /*
8093  * restart cmd currently at the head of the runq
8094  *
8095  * If scsi_transport() succeeds or the retries
8096  * count exhausted, restore the throttle that was
8097  * zeroed out in st_handle_intr_busy().
8098  *
8099  */
8100 static void
8101 st_intr_restart(void *arg)
8102 {
8103 	struct scsi_tape *un = arg;
8104 	struct buf *bp;
8105 	int status = TRAN_ACCEPT;
8106 
8107 	mutex_enter(ST_MUTEX);
8108 
8109 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8110 		"st_intr_restart(), un = 0x%p\n", (void *)un);
8111 
8112 	un->un_hib_tid = 0;
8113 
8114 	/*
8115 	 * move from waitq to runq, if there is anything on the waitq
8116 	 */
8117 	if ((bp = un->un_quef) == NULL) {
8118 		mutex_exit(ST_MUTEX);
8119 		return;
8120 	}
8121 
8122 	/*
8123 	 * Here we know :
8124 	 *	throttle = 0, via st_handle_intr_busy
8125 	 */
8126 
8127 	if (un->un_quel == bp) {
8128 		un->un_quel = NULL;
8129 		un->un_quef = NULL;	/* we know it's the first one */
8130 	} else {
8131 		un->un_quef = bp->b_actf;
8132 	}
8133 	bp->b_actf = NULL;
8134 
8135 	if (un->un_runqf) {
8136 		/*
8137 		 * not good, we don't want to requeue something after
8138 		 * another.
8139 		 */
8140 		mutex_exit(ST_MUTEX);
8141 		goto done_error;
8142 	} else {
8143 		un->un_runqf = bp;
8144 		un->un_runql = bp;
8145 	}
8146 
8147 	ST_DO_KSTATS(bp, kstat_waitq_to_runq);
8148 
8149 	mutex_exit(ST_MUTEX);
8150 
8151 	status = scsi_transport(BP_PKT(bp));
8152 
8153 	mutex_enter(ST_MUTEX);
8154 
8155 	if (status != TRAN_ACCEPT) {
8156 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
8157 		mutex_exit(ST_MUTEX);
8158 
8159 		if (status == TRAN_BUSY) {
8160 			if (st_handle_intr_busy(un, bp,
8161 			    ST_TRAN_BUSY_TIMEOUT) == 0)
8162 				return;	/* timeout is setup again */
8163 		}
8164 
8165 	} else {
8166 		un->un_tran_retry_ct = 0;
8167 		if (un->un_last_throttle) {
8168 			un->un_throttle = un->un_last_throttle;
8169 		}
8170 		mutex_exit(ST_MUTEX);
8171 		return;
8172 	}
8173 
8174 done_error:
8175 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8176 	    "restart transport rejected\n");
8177 	bp->b_resid = bp->b_bcount;
8178 
8179 #ifndef __lock_lint
8180 	/*
8181 	 * warlock doesn't understand this potential
8182 	 * recursion?
8183 	 */
8184 	mutex_enter(ST_MUTEX);
8185 	if (un->un_last_throttle) {
8186 		un->un_throttle = un->un_last_throttle;
8187 	}
8188 	if (status != TRAN_ACCEPT)
8189 		ST_DO_ERRSTATS(un, st_transerrs);
8190 	ST_DO_KSTATS(bp, kstat_waitq_exit);
8191 	SET_PE_FLAG(un);
8192 	st_bioerror(bp, EIO);
8193 	st_done_and_mutex_exit(un, bp);
8194 #endif
8195 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8196 	    "busy restart aborted\n");
8197 }
8198 
8199 /*
8200  * st_check_media():
8201  * Periodically check the media state using scsi_watch service;
8202  * this service calls back after TUR and possibly request sense
8203  * the callback handler (st_media_watch_cb()) decodes the request sense
8204  * data (if any)
8205  */
8206 
8207 static int
8208 st_check_media(dev_t dev, enum mtio_state state)
8209 {
8210 	int rval = 0;
8211 	enum mtio_state	prev_state;
8212 	opaque_t token = NULL;
8213 
8214 	GET_SOFT_STATE(dev);
8215 
8216 	mutex_enter(ST_MUTEX);
8217 
8218 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8219 		"st_check_media:state=%x, mediastate=%x\n",
8220 		state, un->un_mediastate);
8221 
8222 	prev_state = un->un_mediastate;
8223 
8224 	/*
8225 	 * is there anything to do?
8226 	 */
8227 retry:
8228 	if (state == un->un_mediastate || un->un_mediastate == MTIO_NONE) {
8229 		/*
8230 		 * submit the request to the scsi_watch service;
8231 		 * scsi_media_watch_cb() does the real work
8232 		 */
8233 		mutex_exit(ST_MUTEX);
8234 		token = scsi_watch_request_submit(ST_SCSI_DEVP,
8235 			st_check_media_time, SENSE_LENGTH,
8236 			st_media_watch_cb, (caddr_t)dev);
8237 		if (token == NULL) {
8238 			rval = EAGAIN;
8239 			goto done;
8240 		}
8241 		mutex_enter(ST_MUTEX);
8242 
8243 		un->un_swr_token = token;
8244 		un->un_specified_mediastate = state;
8245 
8246 		/*
8247 		 * now wait for media change
8248 		 * we will not be signalled unless mediastate == state but it
8249 		 * still better to test for this condition, since there
8250 		 * is a 5 sec cv_broadcast delay when
8251 		 *  mediastate == MTIO_INSERTED
8252 		 */
8253 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8254 			"st_check_media:waiting for media state change\n");
8255 		while (un->un_mediastate == state) {
8256 			if (cv_wait_sig(&un->un_state_cv, ST_MUTEX) == 0) {
8257 				mutex_exit(ST_MUTEX);
8258 				ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8259 				    "st_check_media:waiting for media state "
8260 				    "was interrupted\n");
8261 				rval = EINTR;
8262 				goto done;
8263 			}
8264 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8265 			    "st_check_media:received signal, state=%x\n",
8266 			    un->un_mediastate);
8267 		}
8268 	}
8269 
8270 	/*
8271 	 * if we transitioned to MTIO_INSERTED, media has really been
8272 	 * inserted.  If TUR fails, it is probably a exabyte slow spin up.
8273 	 * Reset and retry the state change.  If everything is ok, replay
8274 	 * the open() logic.
8275 	 */
8276 	if ((un->un_mediastate == MTIO_INSERTED) &&
8277 	    (un->un_state == ST_STATE_OFFLINE)) {
8278 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8279 		    "st_check_media: calling st_cmd to confirm inserted\n");
8280 
8281 		/*
8282 		 * set this early so that TUR will make it through strategy
8283 		 * without triggering a st_tape_init().  We needed it set
8284 		 * before calling st_tape_init() ourselves anyway.  If TUR
8285 		 * fails, set it back
8286 		 */
8287 		un->un_state = ST_STATE_INITIALIZING;
8288 		/*
8289 		 * If we haven't done/checked reservation on the
8290 		 * tape unit do it now.
8291 		 */
8292 		if (ST_RESERVE_SUPPORTED(un) &&
8293 			!(un->un_rsvd_status & ST_INIT_RESERVE)) {
8294 				if (rval = st_tape_reservation_init(dev)) {
8295 					mutex_exit(ST_MUTEX);
8296 					goto done;
8297 				}
8298 		}
8299 
8300 		if (st_cmd(dev, SCMD_TEST_UNIT_READY, 0, SYNC_CMD)) {
8301 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8302 			    "st_check_media: TUR failed, going to retry\n");
8303 			un->un_mediastate = prev_state;
8304 			un->un_state = ST_STATE_OFFLINE;
8305 			goto retry;
8306 		}
8307 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8308 		    "st_check_media: media inserted\n");
8309 
8310 		/* this also rewinds the tape */
8311 		rval = st_tape_init(dev);
8312 		if (rval != 0) {
8313 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8314 			    "st_check_media : OFFLINE init failure ");
8315 			un->un_state = ST_STATE_OFFLINE;
8316 			un->un_fileno = -1;
8317 		} else {
8318 			un->un_state = ST_STATE_OPEN_PENDING_IO;
8319 			un->un_fileno = 0;
8320 			un->un_blkno = 0;
8321 		}
8322 	} else if ((un->un_mediastate == MTIO_EJECTED) &&
8323 		(un->un_state != ST_STATE_OFFLINE)) {
8324 		/*
8325 		 * supported devices must be rewound before ejection
8326 		 * rewind resets fileno & blkno
8327 		 */
8328 		un->un_laststate = un->un_state;
8329 		un->un_state = ST_STATE_OFFLINE;
8330 	}
8331 	mutex_exit(ST_MUTEX);
8332 done:
8333 	if (token) {
8334 		(void) scsi_watch_request_terminate(token,
8335 				SCSI_WATCH_TERMINATE_WAIT);
8336 		mutex_enter(ST_MUTEX);
8337 		un->un_swr_token = (opaque_t)NULL;
8338 		mutex_exit(ST_MUTEX);
8339 	}
8340 
8341 	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_media: done\n");
8342 
8343 	return (rval);
8344 }
8345 
8346 /*
8347  * st_media_watch_cb() is called by scsi_watch_thread for
8348  * verifying the request sense data (if any)
8349  */
8350 static int
8351 st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
8352 {
8353 	struct scsi_status *statusp = resultp->statusp;
8354 	struct scsi_extended_sense *sensep = resultp->sensep;
8355 	uchar_t actual_sense_length = resultp->actual_sense_length;
8356 	struct scsi_tape *un;
8357 	enum mtio_state state = MTIO_NONE;
8358 	int instance;
8359 	dev_t dev = (dev_t)arg;
8360 
8361 	instance = MTUNIT(dev);
8362 	if ((un = ddi_get_soft_state(st_state, instance)) == NULL) {
8363 		return (-1);
8364 	}
8365 
8366 	mutex_enter(ST_MUTEX);
8367 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8368 		"st_media_watch_cb: status=%x, sensep=%p, len=%x\n",
8369 			*((char *)statusp), (void *)sensep,
8370 			actual_sense_length);
8371 
8372 	/*
8373 	 * if there was a check condition then sensep points to valid
8374 	 * sense data
8375 	 * if status was not a check condition but a reservation or busy
8376 	 * status then the new state is MTIO_NONE
8377 	 */
8378 	if (sensep) {
8379 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8380 		    "st_media_watch_cb: KEY=%x, ASC=%x, ASCQ=%x\n",
8381 		    sensep->es_key, sensep->es_add_code, sensep->es_qual_code);
8382 
8383 		switch (un->un_dp->type) {
8384 		default:
8385 			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8386 	    "st_media_watch_cb: unknown drive type %d, default to ST_TYPE_HP\n",
8387 	    un->un_dp->type);
8388 		/* FALLTHROUGH */
8389 
8390 		case ST_TYPE_STC3490:	/* STK 4220 1/2" cartridge */
8391 		case ST_TYPE_FUJI:	/* 1/2" cartridge */
8392 		case ST_TYPE_HP:	/* HP 88780 1/2" reel */
8393 			if (un->un_dp->type == ST_TYPE_FUJI) {
8394 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8395 				    "st_media_watch_cb: ST_TYPE_FUJI\n");
8396 			} else {
8397 				ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8398 				    "st_media_watch_cb: ST_TYPE_HP\n");
8399 			}
8400 			switch (sensep->es_key) {
8401 			case KEY_UNIT_ATTENTION:
8402 				/* not ready to ready transition */
8403 				/* hp/es_qual_code == 80 on>off>on */
8404 				/* hp/es_qual_code == 0 on>off>unld>ld>on */
8405 				if (sensep->es_add_code == 0x28) {
8406 					state = MTIO_INSERTED;
8407 				}
8408 				break;
8409 			case KEY_NOT_READY:
8410 				/* in process, rewinding or loading */
8411 				if ((sensep->es_add_code == 0x04) &&
8412 				    (sensep->es_qual_code == 0x00)) {
8413 					state = MTIO_EJECTED;
8414 				}
8415 				break;
8416 			}
8417 			break;
8418 
8419 		case ST_TYPE_EXB8500:	/* Exabyte 8500 */
8420 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8421 			    "st_media_watch_cb: ST_TYPE_EXB8500\n");
8422 			switch (sensep->es_key) {
8423 			case KEY_UNIT_ATTENTION:
8424 				/* operator medium removal request */
8425 				if ((sensep->es_add_code == 0x5a) &&
8426 				    (sensep->es_qual_code == 0x01)) {
8427 					state = MTIO_EJECTED;
8428 				/* not ready to ready transition */
8429 				} else if ((sensep->es_add_code == 0x28) &&
8430 				    (sensep->es_qual_code == 0x00)) {
8431 					state = MTIO_INSERTED;
8432 				}
8433 				break;
8434 			case KEY_NOT_READY:
8435 				/* medium not present */
8436 				if (sensep->es_add_code == 0x3a) {
8437 					state = MTIO_EJECTED;
8438 				}
8439 				break;
8440 			}
8441 			break;
8442 		case ST_TYPE_EXABYTE:	/* Exabyte 8200 */
8443 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8444 			    "st_media_watch_cb: ST_TYPE_EXABYTE\n");
8445 			switch (sensep->es_key) {
8446 			case KEY_NOT_READY:
8447 				if ((sensep->es_add_code == 0x04) &&
8448 				    (sensep->es_qual_code == 0x00)) {
8449 					/* volume not mounted? */
8450 					state = MTIO_EJECTED;
8451 				} else if (sensep->es_add_code == 0x3a) {
8452 					state = MTIO_EJECTED;
8453 				}
8454 				break;
8455 			case KEY_UNIT_ATTENTION:
8456 				state = MTIO_EJECTED;
8457 				break;
8458 			}
8459 			break;
8460 
8461 		case ST_TYPE_DLT:		/* quantum DLT4xxx */
8462 			switch (sensep->es_key) {
8463 			case KEY_UNIT_ATTENTION:
8464 				if (sensep->es_add_code == 0x28) {
8465 					state = MTIO_INSERTED;
8466 				}
8467 				break;
8468 			case KEY_NOT_READY:
8469 				if (sensep->es_add_code == 0x04) {
8470 					/* in transition but could be either */
8471 					state = un->un_specified_mediastate;
8472 				} else if ((sensep->es_add_code == 0x3a) &&
8473 				    (sensep->es_qual_code == 0x00)) {
8474 					state = MTIO_EJECTED;
8475 				}
8476 				break;
8477 			}
8478 			break;
8479 		}
8480 	} else if (*((char *)statusp) == STATUS_GOOD) {
8481 		state = MTIO_INSERTED;
8482 	}
8483 
8484 	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8485 		"st_media_watch_cb:state=%x, specified=%x\n",
8486 		state, un->un_specified_mediastate);
8487 
8488 	/*
8489 	 * now signal the waiting thread if this is *not* the specified state;
8490 	 * delay the signal if the state is MTIO_INSERTED
8491 	 * to allow the target to recover
8492 	 */
8493 	if (state != un->un_specified_mediastate) {
8494 		un->un_mediastate = state;
8495 		if (state == MTIO_INSERTED) {
8496 			/*
8497 			 * delay the signal to give the drive a chance
8498 			 * to do what it apparently needs to do
8499 			 */
8500 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8501 			    "st_media_watch_cb:delayed cv_broadcast\n");
8502 			un->un_delay_tid = timeout(st_delayed_cv_broadcast,
8503 			    un, drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
8504 		} else {
8505 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
8506 				"st_media_watch_cb:immediate cv_broadcast\n");
8507 			cv_broadcast(&un->un_state_cv);
8508 		}
8509 	}
8510 	mutex_exit(ST_MUTEX);
8511 	return (0);
8512 }
8513 
8514 /*
8515  * delayed cv_broadcast to allow for target to recover
8516  * from media insertion
8517  */
8518 static void
8519 st_delayed_cv_broadcast(void *arg)
8520 {
8521 	struct scsi_tape *un = arg;
8522 
8523 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8524 		"st_delayed_cv_broadcast:delayed cv_broadcast\n");
8525 
8526 	mutex_enter(ST_MUTEX);
8527 	cv_broadcast(&un->un_state_cv);
8528 	mutex_exit(ST_MUTEX);
8529 }
8530 
8531 /*
8532  * restart cmd currently at the start of the waitq
8533  */
8534 static void
8535 st_start_restart(void *arg)
8536 {
8537 	struct scsi_tape *un = arg;
8538 
8539 	ASSERT(un != NULL);
8540 
8541 	mutex_enter(ST_MUTEX);
8542 
8543 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8544 		"st_tran_restart()\n");
8545 
8546 	if (un->un_quef) {
8547 		st_start(un);
8548 	}
8549 
8550 	mutex_exit(ST_MUTEX);
8551 }
8552 
8553 
8554 /*
8555  * Command completion processing
8556  *
8557  */
8558 static void
8559 st_intr(struct scsi_pkt *pkt)
8560 {
8561 	struct scsi_tape *un;
8562 	struct buf *last_runqf;
8563 	struct buf *bp;
8564 	int action = COMMAND_DONE;
8565 	clock_t	timout;
8566 	int	status;
8567 
8568 	bp = (struct buf *)pkt->pkt_private;
8569 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
8570 
8571 	mutex_enter(ST_MUTEX);
8572 
8573 	un->un_rqs_state &= ~(ST_RQS_ERROR);
8574 
8575 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_intr()\n");
8576 
8577 	if (pkt->pkt_reason != CMD_CMPLT) {
8578 
8579 		/* If device has gone away not much else to do */
8580 		if (pkt->pkt_reason == CMD_DEV_GONE) {
8581 			action = COMMAND_DONE_ERROR;
8582 		} else if (un->un_state == ST_STATE_SENSING) {
8583 			ST_DO_ERRSTATS(un, st_transerrs);
8584 			action = COMMAND_DONE_ERROR;
8585 		} else {
8586 			action = st_handle_incomplete(un, bp);
8587 		}
8588 	/*
8589 	 * At this point we know that the command was successfully
8590 	 * completed. Now what?
8591 	 */
8592 	} else if (un->un_arq_enabled &&
8593 	    (pkt->pkt_state & STATE_ARQ_DONE)) {
8594 		/*
8595 		 * the transport layer successfully completed an autorqsense
8596 		 */
8597 		action = st_handle_autosense(un, bp);
8598 
8599 	} else if (un->un_state == ST_STATE_SENSING) {
8600 		/*
8601 		 * okay. We were running a REQUEST SENSE. Find
8602 		 * out what to do next.
8603 		 * some actions are based on un_state, hence
8604 		 * restore the state st was in before ST_STATE_SENSING.
8605 		 */
8606 		un->un_state = un->un_laststate;
8607 		action = st_handle_sense(un, bp);
8608 		/*
8609 		 * set pkt back to original packet in case we will have
8610 		 * to requeue it
8611 		 */
8612 		pkt = BP_PKT(bp);
8613 	} else  if ((SCBP(pkt)->sts_busy) || (SCBP(pkt)->sts_chk)) {
8614 		/*
8615 		 * Okay, we weren't running a REQUEST SENSE. Call a routine
8616 		 * to see if the status bits we're okay. If a request sense
8617 		 * is to be run, that will happen.
8618 		 */
8619 		action = st_check_error(un, pkt);
8620 	}
8621 
8622 	if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
8623 		switch (action) {
8624 			case QUE_COMMAND:
8625 				/*
8626 				 * return cmd to head to the queue
8627 				 * since we are suspending so that
8628 				 * it gets restarted during resume
8629 				 */
8630 				if (un->un_runqf) {
8631 					last_runqf = un->un_runqf;
8632 					un->un_runqf = bp;
8633 					bp->b_actf = last_runqf;
8634 				} else {
8635 					bp->b_actf = NULL;
8636 					un->un_runqf = bp;
8637 					un->un_runql = bp;
8638 				}
8639 				action = JUST_RETURN;
8640 				break;
8641 
8642 			case QUE_SENSE:
8643 				action = COMMAND_DONE_ERROR;
8644 				break;
8645 
8646 			default:
8647 				break;
8648 		}
8649 	}
8650 
8651 	/*
8652 	 * Restore old state if we were sensing.
8653 	 */
8654 	if (un->un_state == ST_STATE_SENSING && action != QUE_SENSE) {
8655 		un->un_state = un->un_laststate;
8656 	}
8657 
8658 	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
8659 	    "st_intr: pkt=%p, bp=%p, action=%x, status=%x\n",
8660 	    (void *)pkt, (void *)bp, action, SCBP_C(pkt));
8661 
8662 
8663 	switch (action) {
8664 	case COMMAND_DONE_EACCES:
8665 		/* this is to report a reservation conflict */
8666 		st_bioerror(bp, EACCES);
8667 		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
8668 			"Reservation Conflict \n");
8669 
8670 		/*FALLTHROUGH*/
8671 	case COMMAND_DONE_ERROR:
8672 		if (un->un_eof < ST_EOT_PENDING &&
8673 		    un->un_state >= ST_STATE_OPEN) {
8674 			/*
8675 			 * all errors set state of the tape to 'unknown'
8676 			 * unless we're at EOT or are doing append testing.
8677 			 * If sense key was illegal request, preserve state.
8678 			 */
8679 			if (un->un_status != KEY_ILLEGAL_REQUEST) {
8680 				un->un_fileno = -1;
8681 			}
8682 		}
8683 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8684 		/*
8685 		 * since we have an error (COMMAND_DONE_ERROR), we want to
8686 		 * make sure an error ocurrs, so make sure at least EIO is
8687 		 * returned
8688 		 */
8689 		if (geterror(bp) == 0)
8690 			st_bioerror(bp, EIO);
8691 
8692 		SET_PE_FLAG(un);
8693 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
8694 		    (un->un_errno == EIO)) {
8695 			un->un_rqs_state &= ~(ST_RQS_VALID);
8696 		}
8697 		goto done;
8698 
8699 	case COMMAND_DONE_ERROR_RECOVERED:
8700 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8701 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
8702 		    "st_intr(): COMMAND_DONE_ERROR_RECOVERED");
8703 		if (geterror(bp) == 0)
8704 			st_bioerror(bp, EIO);
8705 		SET_PE_FLAG(un);
8706 		if (!(un->un_rqs_state & ST_RQS_ERROR) &&
8707 		    (un->un_errno == EIO)) {
8708 			un->un_rqs_state &= ~(ST_RQS_VALID);
8709 		}
8710 		/*FALLTHROUGH*/
8711 	case COMMAND_DONE:
8712 		st_set_state(un);
8713 done:
8714 		ST_DO_KSTATS(bp, kstat_runq_exit);
8715 		st_done_and_mutex_exit(un, bp);
8716 		return;
8717 
8718 	case QUE_SENSE:
8719 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors)
8720 			goto sense_error;
8721 
8722 		if (un->un_state != ST_STATE_SENSING) {
8723 			un->un_laststate = un->un_state;
8724 			un->un_state = ST_STATE_SENSING;
8725 		}
8726 
8727 		un->un_rqs->pkt_private = (opaque_t)bp;
8728 		bzero(ST_RQSENSE, SENSE_LENGTH);
8729 
8730 		if (un->un_throttle) {
8731 			un->un_last_throttle = un->un_throttle;
8732 			un->un_throttle = 0;
8733 		}
8734 
8735 		mutex_exit(ST_MUTEX);
8736 
8737 		/*
8738 		 * never retry this, some other command will have nuked the
8739 		 * sense, anyway
8740 		 */
8741 		status = scsi_transport(un->un_rqs);
8742 
8743 		mutex_enter(ST_MUTEX);
8744 
8745 		if (un->un_last_throttle) {
8746 			un->un_throttle = un->un_last_throttle;
8747 		}
8748 
8749 		if (status == TRAN_ACCEPT) {
8750 			mutex_exit(ST_MUTEX);
8751 			return;
8752 		}
8753 		if (status != TRAN_BUSY)
8754 			ST_DO_ERRSTATS(un, st_transerrs);
8755 sense_error:
8756 		un->un_fileno = -1;
8757 		st_bioerror(bp, EIO);
8758 		SET_PE_FLAG(un);
8759 		goto done;
8760 
8761 	case QUE_BUSY_COMMAND:
8762 		/* longish timeout */
8763 		timout = ST_STATUS_BUSY_TIMEOUT;
8764 		goto que_it_up;
8765 
8766 	case QUE_COMMAND:
8767 		/* short timeout */
8768 		timout = ST_TRAN_BUSY_TIMEOUT;
8769 que_it_up:
8770 		/*
8771 		 * let st_handle_intr_busy put this bp back on waitq and make
8772 		 * checks to see if it is ok to requeue the command.
8773 		 */
8774 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
8775 
8776 		/*
8777 		 * Save the throttle before setting up the timeout
8778 		 */
8779 		if (un->un_throttle) {
8780 			un->un_last_throttle = un->un_throttle;
8781 		}
8782 		mutex_exit(ST_MUTEX);
8783 		if (st_handle_intr_busy(un, bp, timout) == 0)
8784 			return;		/* timeout is setup again */
8785 
8786 		mutex_enter(ST_MUTEX);
8787 		un->un_fileno = -1;
8788 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8789 		st_bioerror(bp, EIO);
8790 		SET_PE_FLAG(un);
8791 		goto done;
8792 
8793 	case QUE_LAST_COMMAND:
8794 
8795 		if ((un->un_ncmds > 1) && !un->un_flush_on_errors) {
8796 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
8797 			    "un_ncmds: %d can't retry cmd \n", un->un_ncmds);
8798 			goto last_command_error;
8799 		}
8800 		mutex_exit(ST_MUTEX);
8801 		if (st_handle_intr_retry_lcmd(un, bp) == 0)
8802 			return;
8803 		mutex_enter(ST_MUTEX);
8804 last_command_error:
8805 		un->un_err_resid = bp->b_resid = bp->b_bcount;
8806 		un->un_fileno = -1;
8807 		st_bioerror(bp, EIO);
8808 		SET_PE_FLAG(un);
8809 		goto done;
8810 
8811 	case JUST_RETURN:
8812 	default:
8813 		ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
8814 		mutex_exit(ST_MUTEX);
8815 		return;
8816 	}
8817 	/*NOTREACHED*/
8818 }
8819 
8820 static int
8821 st_handle_incomplete(struct scsi_tape *un, struct buf *bp)
8822 {
8823 	static char *fail = "SCSI transport failed: reason '%s': %s\n";
8824 	int rval = COMMAND_DONE_ERROR;
8825 	struct scsi_pkt *pkt = (un->un_state == ST_STATE_SENSING) ?
8826 			un->un_rqs : BP_PKT(bp);
8827 	int result;
8828 
8829 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8830 		"st_handle_incomplete(): dev = 0x%lx\n", un->un_dev);
8831 
8832 	ASSERT(mutex_owned(ST_MUTEX));
8833 
8834 	switch (pkt->pkt_reason) {
8835 	case CMD_INCOMPLETE:	/* tran stopped with not normal state */
8836 		/*
8837 		 * this occurs when accessing a powered down drive, no
8838 		 * need to complain; just fail the open
8839 		 */
8840 #ifdef STDEBUG
8841 		if (st_debug >= 1) {
8842 			st_clean_print(ST_DEVINFO, st_label, CE_WARN,
8843 			    "Failed CDB", (char *)pkt->pkt_cdbp, CDB_SIZE);
8844 		}
8845 
8846 #endif
8847 		/*
8848 		 * if we have commands outstanding in HBA, and a command
8849 		 * comes back incomplete, we're hosed, so reset target
8850 		 * If we have the bus, but cmd_incomplete, we probably just
8851 		 * have a failed selection, so don't reset the target, just
8852 		 * requeue the command and try again
8853 		 */
8854 		if ((un->un_ncmds > 1) || (pkt->pkt_state != STATE_GOT_BUS)) {
8855 			goto reset_target;
8856 		}
8857 
8858 		/*
8859 		 * Retry selection a couple more times if we're
8860 		 * open.  If opening, we only try just once to
8861 		 * reduce probe time for nonexistant devices.
8862 		 */
8863 		if ((un->un_laststate > ST_STATE_OPENING) &&
8864 		    ((int)un->un_retry_ct < st_selection_retry_count)) {
8865 			rval = QUE_COMMAND;
8866 		}
8867 		ST_DO_ERRSTATS(un, st_transerrs);
8868 		break;
8869 
8870 	case CMD_ABORTED:
8871 		/*
8872 		 * most likely this is caused by flush-on-error support. If
8873 		 * it was not there, the we're in trouble.
8874 		 */
8875 		if (!un->un_flush_on_errors) {
8876 			un->un_status = SUN_KEY_FATAL;
8877 			goto reset_target;
8878 		}
8879 
8880 		st_set_pe_errno(un);
8881 		bioerror(bp, un->un_errno);
8882 		if (un->un_errno)
8883 			return (COMMAND_DONE_ERROR);
8884 		else
8885 			return (COMMAND_DONE);
8886 
8887 	case CMD_TIMEOUT:	/* Command timed out */
8888 		un->un_status = SUN_KEY_TIMEOUT;
8889 
8890 		/*FALLTHROUGH*/
8891 	default:
8892 reset_target:
8893 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
8894 		    "transport completed with %s\n",
8895 		    scsi_rname(pkt->pkt_reason));
8896 		ST_DO_ERRSTATS(un, st_transerrs);
8897 		if ((pkt->pkt_state & STATE_GOT_TARGET) &&
8898 		    ((pkt->pkt_statistics & (STAT_BUS_RESET | STAT_DEV_RESET |
8899 			STAT_ABORTED)) == 0)) {
8900 
8901 			mutex_exit(ST_MUTEX);
8902 
8903 			result = scsi_reset(ROUTE, RESET_TARGET);
8904 			/*
8905 			 * if target reset fails, then pull the chain
8906 			 */
8907 			if (result == 0) {
8908 				result = scsi_reset(ROUTE, RESET_ALL);
8909 			}
8910 			mutex_enter(ST_MUTEX);
8911 
8912 			if ((result == 0) && (un->un_state >= ST_STATE_OPEN)) {
8913 				/* no hope left to recover */
8914 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
8915 				    "recovery by resets failed\n");
8916 				return (rval);
8917 			}
8918 		}
8919 	}
8920 
8921 	if ((pkt->pkt_reason == CMD_RESET) || (pkt->pkt_statistics &
8922 		(STAT_BUS_RESET | STAT_DEV_RESET))) {
8923 		if ((un->un_rsvd_status & ST_RESERVE)) {
8924 			un->un_rsvd_status |= ST_LOST_RESERVE;
8925 			ST_DEBUG3(ST_DEVINFO, st_label, CE_WARN,
8926 				"Lost Reservation\n");
8927 		}
8928 	}
8929 
8930 	if ((int)un->un_retry_ct++ < st_retry_count) {
8931 		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
8932 			rval = QUE_COMMAND;
8933 		} else if (bp == un->un_sbufp) {
8934 			switch ((uchar_t)(uintptr_t)bp->b_forw) {
8935 			case SCMD_MODE_SENSE:
8936 			case SCMD_MODE_SELECT:
8937 			case SCMD_READ_BLKLIM:
8938 			case SCMD_REWIND:
8939 			case SCMD_LOAD:
8940 			case SCMD_TEST_UNIT_READY:
8941 				/*
8942 				 * These commands can be rerun with impunity
8943 				 */
8944 				rval = QUE_COMMAND;
8945 				break;
8946 
8947 			default:
8948 				break;
8949 			}
8950 		}
8951 	} else {
8952 		rval = COMMAND_DONE_ERROR;
8953 	}
8954 
8955 	if (un->un_state >= ST_STATE_OPEN) {
8956 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
8957 		    fail, scsi_rname(pkt->pkt_reason),
8958 		    (rval == COMMAND_DONE_ERROR)?
8959 		    "giving up" : "retrying command");
8960 	}
8961 	return (rval);
8962 }
8963 
8964 /*
8965  * if the device is busy, then put this bp back on the waitq, on the
8966  * interrupt thread, where we want the head of the queue and not the
8967  * end
8968  *
8969  * The callers of this routine should take measures to save the
8970  * un_throttle in un_last_throttle which will be restored in
8971  * st_intr_restart(). The only exception should be st_intr_restart()
8972  * calling this routine for which the saving is already done.
8973  */
8974 static int
8975 st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
8976 	clock_t timeout_interval)
8977 {
8978 	struct buf *last_quef;
8979 	int rval = 0;
8980 
8981 	mutex_enter(ST_MUTEX);
8982 
8983 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
8984 	    "st_handle_intr_busy(), un = 0x%p\n", (void *)un);
8985 
8986 	/*
8987 	 * Check to see if we hit the retry timeout. We check to make sure
8988 	 * this is the first one on the runq and make sure we have not
8989 	 * queued up any more, so this one has to be the last on the list
8990 	 * also. If it is not, we have to fail.  If it is not the first, but
8991 	 * is the last we are in trouble anyway, as we are in the interrupt
8992 	 * context here.
8993 	 */
8994 	if (((int)un->un_tran_retry_ct++ > st_retry_count) ||
8995 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
8996 		rval = -1;
8997 		goto exit;
8998 	}
8999 
9000 	/* put the bp back on the waitq */
9001 	if (un->un_quef) {
9002 		last_quef = un->un_quef;
9003 		un->un_quef = bp;
9004 		bp->b_actf = last_quef;
9005 	} else  {
9006 		bp->b_actf = NULL;
9007 		un->un_quef = bp;
9008 		un->un_quel = bp;
9009 	}
9010 
9011 	/*
9012 	 * We know that this is the first and last on the runq at this time,
9013 	 * so we just nullify those two queues
9014 	 */
9015 	un->un_runqf = NULL;
9016 	un->un_runql = NULL;
9017 
9018 	/*
9019 	 * We don't want any other commands being started in the mean time.
9020 	 * If start had just released mutex after putting something on the
9021 	 * runq, we won't even get here.
9022 	 */
9023 	un->un_throttle = 0;
9024 
9025 	/*
9026 	 * send a marker pkt, if appropriate
9027 	 */
9028 	st_hba_unflush(un);
9029 
9030 	/*
9031 	 * all queues are aligned, we are just waiting to
9032 	 * transport
9033 	 */
9034 	un->un_hib_tid = timeout(st_intr_restart, un, timeout_interval);
9035 
9036 exit:
9037 	mutex_exit(ST_MUTEX);
9038 	return (rval);
9039 }
9040 
9041 static int
9042 st_handle_sense(struct scsi_tape *un, struct buf *bp)
9043 {
9044 	struct scsi_pkt *rqpkt = un->un_rqs;
9045 	int rval = COMMAND_DONE_ERROR;
9046 	int amt;
9047 
9048 	ASSERT(mutex_owned(ST_MUTEX));
9049 
9050 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9051 		"st_handle_sense()\n");
9052 
9053 	if (SCBP(rqpkt)->sts_busy) {
9054 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
9055 		    "busy unit on request sense\n");
9056 		if ((int)un->un_retry_ct++ < st_retry_count) {
9057 			rval = QUE_BUSY_COMMAND;
9058 		}
9059 		return (rval);
9060 	} else if (SCBP(rqpkt)->sts_chk) {
9061 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9062 		    "Check Condition on REQUEST SENSE\n");
9063 		return (rval);
9064 	}
9065 
9066 	/* was there enough data? */
9067 	amt = (int)SENSE_LENGTH - rqpkt->pkt_resid;
9068 	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 ||
9069 	    (amt < SUN_MIN_SENSE_LENGTH)) {
9070 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9071 		    "REQUEST SENSE couldn't get sense data\n");
9072 		return (rval);
9073 	}
9074 	return (st_decode_sense(un, bp, amt, SCBP(rqpkt)));
9075 }
9076 
9077 static int
9078 st_handle_autosense(struct scsi_tape *un, struct buf *bp)
9079 {
9080 	struct scsi_pkt *pkt = BP_PKT(bp);
9081 	struct scsi_arq_status *arqstat =
9082 	    (struct scsi_arq_status *)pkt->pkt_scbp;
9083 	int rval = COMMAND_DONE_ERROR;
9084 	int amt;
9085 
9086 	ASSERT(mutex_owned(ST_MUTEX));
9087 
9088 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9089 		"st_handle_autosense()\n");
9090 
9091 	if (arqstat->sts_rqpkt_status.sts_busy) {
9092 		ST_DEBUG4(ST_DEVINFO, st_label, CE_WARN,
9093 		    "busy unit on request sense\n");
9094 		/*
9095 		 * we return QUE_SENSE so st_intr will setup the SENSE cmd.
9096 		 * the disadvantage is that we do not have any delay for the
9097 		 * second retry of rqsense and we have to keep a packet around
9098 		 */
9099 		return (QUE_SENSE);
9100 
9101 	} else if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
9102 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9103 		    "transport error on REQUEST SENSE\n");
9104 		if ((arqstat->sts_rqpkt_state & STATE_GOT_TARGET) &&
9105 		    ((arqstat->sts_rqpkt_statistics &
9106 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0)) {
9107 			mutex_exit(ST_MUTEX);
9108 			if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
9109 				/*
9110 				 * if target reset fails, then pull the chain
9111 				 */
9112 				if (scsi_reset(ROUTE, RESET_ALL) == 0) {
9113 					ST_DEBUG6(ST_DEVINFO, st_label,
9114 					    CE_WARN,
9115 					    "recovery by resets failed\n");
9116 				}
9117 			}
9118 			mutex_enter(ST_MUTEX);
9119 		}
9120 		return (rval);
9121 
9122 	} else if (arqstat->sts_rqpkt_status.sts_chk) {
9123 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9124 		    "Check Condition on REQUEST SENSE\n");
9125 		return (rval);
9126 	}
9127 
9128 
9129 	/* was there enough data? */
9130 	amt = (int)SENSE_LENGTH - arqstat->sts_rqpkt_resid;
9131 	if ((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0 ||
9132 	    (amt < SUN_MIN_SENSE_LENGTH)) {
9133 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9134 		    "REQUEST SENSE couldn't get sense data\n");
9135 		return (rval);
9136 	}
9137 
9138 	bcopy(&arqstat->sts_sensedata, ST_RQSENSE, SENSE_LENGTH);
9139 
9140 	return (st_decode_sense(un, bp, amt, &arqstat->sts_rqpkt_status));
9141 }
9142 
9143 static int
9144 st_decode_sense(struct scsi_tape *un, struct buf *bp,  int amt,
9145 	struct scsi_status *statusp)
9146 {
9147 	struct scsi_pkt *pkt = BP_PKT(bp);
9148 	int rval = COMMAND_DONE_ERROR;
9149 	long resid;
9150 	struct scsi_extended_sense *sensep = ST_RQSENSE;
9151 	int severity;
9152 	int get_error;
9153 
9154 	ASSERT(mutex_owned(ST_MUTEX));
9155 
9156 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9157 		"st_decode_sense()\n");
9158 
9159 	/*
9160 	 * For uscsi commands, squirrel away a copy of the
9161 	 * results of the Request Sense.
9162 	 */
9163 	if (USCSI_CMD(bp)) {
9164 		struct uscsi_cmd *ucmd = BP_UCMD(bp);
9165 		ucmd->uscsi_rqstatus = *(uchar_t *)statusp;
9166 		if (ucmd->uscsi_rqlen && un->un_srqbufp) {
9167 			uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
9168 			ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
9169 			bcopy(ST_RQSENSE, un->un_srqbufp, rqlen);
9170 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
9171 				"st_decode_sense: stat=0x%x resid=0x%x\n",
9172 				ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
9173 		}
9174 	}
9175 
9176 	/*
9177 	 * If the drive is an MT-02, reposition the
9178 	 * secondary error code into the proper place.
9179 	 *
9180 	 * XXX	MT-02 is non-CCS tape, so secondary error code
9181 	 * is in byte 8.  However, in SCSI-2, tape has CCS definition
9182 	 * so it's in byte 12.
9183 	 */
9184 	if (un->un_dp->type == ST_TYPE_EMULEX) {
9185 		sensep->es_code = sensep->es_add_info[0];
9186 	}
9187 
9188 	/* for normal I/O check extract the resid values. */
9189 	if (bp != un->un_sbufp) {
9190 		if (sensep->es_valid) {
9191 			resid = (sensep->es_info_1 << 24) |
9192 				(sensep->es_info_2 << 16) |
9193 				(sensep->es_info_3 << 8)  |
9194 				(sensep->es_info_4);
9195 			if (un->un_bsize) {
9196 				resid *= un->un_bsize;
9197 			}
9198 		} else if (pkt->pkt_state & STATE_XFERRED_DATA) {
9199 			resid = pkt->pkt_resid;
9200 		} else {
9201 			resid = bp->b_bcount;
9202 		}
9203 		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9204 		    "st_handle_sense (rw): xferred bit = %d, resid=%ld (%d), "
9205 		    "pkt_resid=%ld\n", pkt->pkt_state & STATE_XFERRED_DATA,
9206 		    resid,
9207 		    (sensep->es_info_1 << 24) |
9208 		    (sensep->es_info_2 << 16) |
9209 		    (sensep->es_info_3 << 8)  |
9210 		    (sensep->es_info_4),
9211 		    pkt->pkt_resid);
9212 		/*
9213 		 * The problem is, what should we believe?
9214 		 */
9215 		if (resid && (pkt->pkt_resid == 0)) {
9216 			pkt->pkt_resid = resid;
9217 		}
9218 	} else {
9219 		/*
9220 		 * If the command is SCMD_SPACE, we need to get the
9221 		 * residual as returned in the sense data, to adjust
9222 		 * our idea of current tape position correctly
9223 		 */
9224 		if ((CDBP(pkt)->scc_cmd == SCMD_SPACE ||
9225 		    CDBP(pkt)->scc_cmd == SCMD_WRITE_FILE_MARK) &&
9226 		    (sensep->es_valid)) {
9227 			resid = (sensep->es_info_1 << 24) |
9228 			    (sensep->es_info_2 << 16) |
9229 			    (sensep->es_info_3 << 8)  |
9230 			    (sensep->es_info_4);
9231 			bp->b_resid = resid;
9232 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9233 			    "st_handle_sense(other):	resid=%ld\n",
9234 			    resid);
9235 		} else {
9236 			/*
9237 			 * If the special command is SCMD_READ,
9238 			 * the correct resid will be set later.
9239 			 */
9240 			resid = bp->b_bcount;
9241 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9242 			    "st_handle_sense(special read):  resid=%ld\n",
9243 				resid);
9244 		}
9245 	}
9246 
9247 	if ((un->un_state >= ST_STATE_OPEN) &&
9248 	    (DEBUGGING || st_error_level == SCSI_ERR_ALL)) {
9249 		st_clean_print(ST_DEVINFO, st_label, CE_NOTE,
9250 		    "Failed CDB", (char *)pkt->pkt_cdbp, CDB_SIZE);
9251 		st_clean_print(ST_DEVINFO, st_label, CE_CONT,
9252 		    "sense data", (char *)sensep, amt);
9253 		scsi_log(ST_DEVINFO, st_label, CE_CONT,
9254 		    "count 0x%lx resid 0x%lx pktresid 0x%lx\n",
9255 		    bp->b_bcount, resid, pkt->pkt_resid);
9256 	}
9257 
9258 	switch (un->un_status = sensep->es_key) {
9259 	case KEY_NO_SENSE:
9260 		severity = SCSI_ERR_INFO;
9261 		goto common;
9262 
9263 	case KEY_RECOVERABLE_ERROR:
9264 		severity = SCSI_ERR_RECOVERED;
9265 		if ((sensep->es_class == CLASS_EXTENDED_SENSE) &&
9266 		    (sensep->es_code == ST_DEFERRED_ERROR)) {
9267 		    if (un->un_dp->options &
9268 			ST_RETRY_ON_RECOVERED_DEFERRED_ERROR) {
9269 			    rval = QUE_LAST_COMMAND;
9270 			    scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
9271 				un->un_blkno, un->un_err_blkno, scsi_cmds,
9272 				sensep);
9273 			    scsi_log(ST_DEVINFO, st_label, CE_CONT,
9274 				"Command will be retried\n");
9275 			} else {
9276 			    severity = SCSI_ERR_FATAL;
9277 			    rval = COMMAND_DONE_ERROR_RECOVERED;
9278 			    ST_DO_ERRSTATS(un, st_softerrs);
9279 			    scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
9280 				un->un_blkno, un->un_err_blkno, scsi_cmds,
9281 				sensep);
9282 			}
9283 			break;
9284 		}
9285 common:
9286 		/*
9287 		 * XXX only want reads to be stopped by filemarks.
9288 		 * Don't want them to be stopped by EOT.  EOT matters
9289 		 * only on write.
9290 		 */
9291 		if (sensep->es_filmk && !sensep->es_eom) {
9292 			rval = COMMAND_DONE;
9293 		} else if (sensep->es_eom) {
9294 			rval = COMMAND_DONE;
9295 		} else if (sensep->es_ili) {
9296 			/*
9297 			 * Fun with variable length record devices:
9298 			 * for specifying larger blocks sizes than the
9299 			 * actual physical record size.
9300 			 */
9301 			if (un->un_bsize == 0 && resid > 0) {
9302 				/*
9303 				 * XXX! Ugly.
9304 				 * The requested blocksize is > tape blocksize,
9305 				 * so this is ok, so we just return the
9306 				 * actual size xferred.
9307 				 */
9308 				pkt->pkt_resid = resid;
9309 				rval = COMMAND_DONE;
9310 			} else if (un->un_bsize == 0 && resid < 0) {
9311 				/*
9312 				 * The requested blocksize is < tape blocksize,
9313 				 * so this is not ok, so we err with ENOMEM
9314 				 */
9315 				rval = COMMAND_DONE_ERROR_RECOVERED;
9316 				st_bioerror(bp, ENOMEM);
9317 			} else {
9318 				ST_DO_ERRSTATS(un, st_softerrs);
9319 				severity = SCSI_ERR_FATAL;
9320 				rval = COMMAND_DONE_ERROR;
9321 				st_bioerror(bp, EINVAL);
9322 			}
9323 		} else {
9324 			/*
9325 			 * we hope and pray for this just being
9326 			 * something we can ignore (ie. a
9327 			 * truly recoverable soft error)
9328 			 */
9329 			rval = COMMAND_DONE;
9330 		}
9331 		if (sensep->es_filmk) {
9332 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9333 			    "filemark\n");
9334 			un->un_status = SUN_KEY_EOF;
9335 			un->un_eof = ST_EOF_PENDING;
9336 			SET_PE_FLAG(un);
9337 		}
9338 
9339 		/*
9340 		 * ignore eom when reading, a fmk should terminate reading
9341 		 */
9342 		if ((sensep->es_eom) &&
9343 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
9344 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
9345 			un->un_status = SUN_KEY_EOT;
9346 			un->un_eof = ST_EOM;
9347 			SET_PE_FLAG(un);
9348 		}
9349 
9350 		break;
9351 
9352 	case KEY_ILLEGAL_REQUEST:
9353 
9354 		if (un->un_laststate >= ST_STATE_OPEN) {
9355 			ST_DO_ERRSTATS(un, st_softerrs);
9356 			severity = SCSI_ERR_FATAL;
9357 		} else {
9358 			severity = SCSI_ERR_INFO;
9359 		}
9360 		break;
9361 
9362 	case KEY_MEDIUM_ERROR:
9363 		ST_DO_ERRSTATS(un, st_harderrs);
9364 		severity = SCSI_ERR_FATAL;
9365 
9366 		/*
9367 		 * for (buffered) writes, a medium error must be fatal
9368 		 */
9369 		if (CDBP(pkt)->scc_cmd != SCMD_WRITE) {
9370 			rval = COMMAND_DONE_ERROR_RECOVERED;
9371 		}
9372 
9373 check_keys:
9374 		/*
9375 		 * attempt to process the keys in the presence of
9376 		 * other errors
9377 		 */
9378 		if (sensep->es_ili && rval != COMMAND_DONE_ERROR) {
9379 			/*
9380 			 * Fun with variable length record devices:
9381 			 * for specifying larger blocks sizes than the
9382 			 * actual physical record size.
9383 			 */
9384 			if (un->un_bsize == 0 && resid > 0) {
9385 				/*
9386 				 * XXX! Ugly
9387 				 */
9388 				pkt->pkt_resid = resid;
9389 			} else if (un->un_bsize == 0 && resid < 0) {
9390 				st_bioerror(bp, EINVAL);
9391 			} else {
9392 				severity = SCSI_ERR_FATAL;
9393 				rval = COMMAND_DONE_ERROR;
9394 				st_bioerror(bp, EINVAL);
9395 			}
9396 		}
9397 		if (sensep->es_filmk) {
9398 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9399 			    "filemark\n");
9400 			un->un_status = SUN_KEY_EOF;
9401 			un->un_eof = ST_EOF_PENDING;
9402 			SET_PE_FLAG(un);
9403 		}
9404 
9405 		/*
9406 		 * ignore eom when reading, a fmk should terminate reading
9407 		 */
9408 		if ((sensep->es_eom) &&
9409 		    (CDBP(pkt)->scc_cmd != SCMD_READ)) {
9410 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "eom\n");
9411 			un->un_status = SUN_KEY_EOT;
9412 			un->un_eof = ST_EOM;
9413 			SET_PE_FLAG(un);
9414 		}
9415 
9416 		break;
9417 
9418 	case KEY_VOLUME_OVERFLOW:
9419 		ST_DO_ERRSTATS(un, st_softerrs);
9420 		un->un_eof = ST_EOM;
9421 		severity = SCSI_ERR_FATAL;
9422 		rval = COMMAND_DONE_ERROR;
9423 		goto check_keys;
9424 
9425 	case KEY_HARDWARE_ERROR:
9426 		ST_DO_ERRSTATS(un, st_harderrs);
9427 		severity = SCSI_ERR_FATAL;
9428 		rval = COMMAND_DONE_ERROR;
9429 		if (un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE)
9430 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
9431 		break;
9432 
9433 	case KEY_BLANK_CHECK:
9434 		ST_DO_ERRSTATS(un, st_softerrs);
9435 		severity = SCSI_ERR_INFO;
9436 
9437 		/*
9438 		 * if not a special request and some data was xferred then it
9439 		 * it is not an error yet
9440 		 */
9441 		if (bp != un->un_sbufp && (bp->b_flags & B_READ)) {
9442 			/*
9443 			 * no error for read with or without data xferred
9444 			 */
9445 			un->un_status = SUN_KEY_EOT;
9446 			un->un_eof = ST_EOT;
9447 			rval = COMMAND_DONE_ERROR;
9448 			SET_PE_FLAG(un);
9449 			goto check_keys;
9450 		} else if (bp != un->un_sbufp &&
9451 		    (pkt->pkt_state & STATE_XFERRED_DATA)) {
9452 			rval = COMMAND_DONE;
9453 		} else {
9454 			rval = COMMAND_DONE_ERROR_RECOVERED;
9455 		}
9456 
9457 		if (un->un_laststate >= ST_STATE_OPEN) {
9458 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9459 			    "blank check\n");
9460 			un->un_eof = ST_EOM;
9461 		}
9462 		if ((CDBP(pkt)->scc_cmd == SCMD_SPACE) &&
9463 		    (un->un_dp->options & ST_KNOWS_EOD) &&
9464 		    (severity = SCSI_ERR_INFO)) {
9465 			/*
9466 			 * we were doing a fast forward by skipping
9467 			 * multiple fmk at the time
9468 			 */
9469 			st_bioerror(bp, EIO);
9470 			severity = SCSI_ERR_RECOVERED;
9471 			rval	 = COMMAND_DONE;
9472 		}
9473 		SET_PE_FLAG(un);
9474 		goto check_keys;
9475 
9476 	case KEY_WRITE_PROTECT:
9477 		if (st_wrongtapetype(un)) {
9478 			un->un_status = SUN_KEY_WRONGMEDIA;
9479 			ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9480 		"wrong tape for writing- use DC6150 tape (or equivalent)\n");
9481 			severity = SCSI_ERR_UNKNOWN;
9482 		} else {
9483 			severity = SCSI_ERR_FATAL;
9484 		}
9485 		ST_DO_ERRSTATS(un, st_harderrs);
9486 		rval = COMMAND_DONE_ERROR;
9487 		st_bioerror(bp, EACCES);
9488 		break;
9489 
9490 	case KEY_UNIT_ATTENTION:
9491 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9492 		    "KEY_UNIT_ATTENTION : un_state = %d\n", un->un_state);
9493 
9494 		/*
9495 		 * If we have detected a Bus Reset and the tape
9496 		 * drive has been reserved.
9497 		 */
9498 		if (ST_RQSENSE->es_add_code == 0x29 &&
9499 			(un->un_rsvd_status & ST_RESERVE)) {
9500 			un->un_rsvd_status |= ST_LOST_RESERVE;
9501 			ST_DEBUG(ST_DEVINFO, st_label, CE_WARN,
9502 				"st_decode_sense: Lost Reservation\n");
9503 		}
9504 
9505 		if (un->un_state <= ST_STATE_OPENING) {
9506 			/*
9507 			 * Look, the tape isn't open yet, now determine
9508 			 * if the cause is a BUS RESET, Save the file and
9509 			 * Block positions for the callers to recover from
9510 			 * the loss of position.
9511 			 */
9512 			if ((un->un_fileno >= 0) &&
9513 			(un->un_fileno || un->un_blkno)) {
9514 				if (ST_RQSENSE->es_add_code == 0x29) {
9515 					un->un_save_fileno = un->un_fileno;
9516 					un->un_save_blkno = un->un_blkno;
9517 					un->un_restore_pos = 1;
9518 				}
9519 			}
9520 
9521 			if ((int)un->un_retry_ct++ < st_retry_count) {
9522 				rval = QUE_COMMAND;
9523 			} else {
9524 				rval = COMMAND_DONE_ERROR;
9525 			}
9526 			severity = SCSI_ERR_INFO;
9527 
9528 		} else {
9529 			/*
9530 			 * Check if it is an Unexpected Unit Attention.
9531 			 * If state is >= ST_STATE_OPEN, we have
9532 			 * already done the initialization .
9533 			 * In this case it is Fatal Error
9534 			 * since no further reading/writing
9535 			 * can be done with fileno set to < 0.
9536 			 */
9537 			if (un->un_state >= ST_STATE_OPEN) {
9538 				ST_DO_ERRSTATS(un, st_harderrs);
9539 				severity = SCSI_ERR_FATAL;
9540 			} else {
9541 				severity = SCSI_ERR_INFO;
9542 			}
9543 			rval = COMMAND_DONE_ERROR;
9544 		}
9545 		un->un_fileno = -1;
9546 
9547 		break;
9548 
9549 	case KEY_NOT_READY:
9550 		/*
9551 		 * If in process of getting ready retry.
9552 		 */
9553 		if (sensep->es_add_code  == 0x04 &&
9554 		    sensep->es_qual_code == 0x01 &&
9555 		    un->un_retry_ct++ < st_retry_count) {
9556 			rval = QUE_COMMAND;
9557 			severity = SCSI_ERR_INFO;
9558 		} else {
9559 			/* give up */
9560 			rval = COMMAND_DONE_ERROR;
9561 			severity = SCSI_ERR_FATAL;
9562 		}
9563 
9564 		/*
9565 		 * If this was an error and after device opened
9566 		 * do error stats.
9567 		 */
9568 		if (rval == COMMAND_DONE_ERROR &&
9569 		    un->un_state > ST_STATE_OPENING) {
9570 			ST_DO_ERRSTATS(un, st_harderrs);
9571 		}
9572 
9573 		if (ST_RQSENSE->es_add_code == 0x3a) {
9574 			if (st_error_level >= SCSI_ERR_FATAL)
9575 				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
9576 				    "Tape not inserted in drive\n");
9577 			un->un_mediastate = MTIO_EJECTED;
9578 			cv_broadcast(&un->un_state_cv);
9579 		}
9580 		if ((un->un_dp->options & ST_EJECT_ON_CHANGER_FAILURE) &&
9581 		    (rval != QUE_COMMAND))
9582 			un->un_eject_tape_on_failure = st_check_asc_ascq(un);
9583 		break;
9584 
9585 	case KEY_ABORTED_COMMAND:
9586 
9587 		/*
9588 		 * Probably a parity error...
9589 		 * if we retry here then this may cause data to be
9590 		 * written twice or data skipped during reading
9591 		 */
9592 		ST_DO_ERRSTATS(un, st_harderrs);
9593 		severity = SCSI_ERR_FATAL;
9594 		rval = COMMAND_DONE_ERROR;
9595 		goto check_keys;
9596 
9597 	default:
9598 		/*
9599 		 * Undecoded sense key.	 Try retries and hope
9600 		 * that will fix the problem.  Otherwise, we're
9601 		 * dead.
9602 		 */
9603 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9604 		    "Unhandled Sense Key '%s'\n",
9605 		    sense_keys[un->un_status]);
9606 		ST_DO_ERRSTATS(un, st_harderrs);
9607 		severity = SCSI_ERR_FATAL;
9608 		rval = COMMAND_DONE_ERROR;
9609 		goto check_keys;
9610 	}
9611 
9612 	if ((!(pkt->pkt_flags & FLAG_SILENT) &&
9613 	    un->un_state >= ST_STATE_OPEN) && (DEBUGGING ||
9614 		(un->un_laststate > ST_STATE_OPENING) &&
9615 		(severity >= st_error_level))) {
9616 
9617 		scsi_errmsg(ST_SCSI_DEVP, pkt, st_label, severity,
9618 		    un->un_blkno, un->un_err_blkno, scsi_cmds, sensep);
9619 		if (sensep->es_filmk) {
9620 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9621 			    "File Mark Detected\n");
9622 		}
9623 		if (sensep->es_eom) {
9624 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9625 			    "End-of-Media Detected\n");
9626 		}
9627 		if (sensep->es_ili) {
9628 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
9629 			    "Incorrect Length Indicator Set\n");
9630 		}
9631 	}
9632 	get_error = geterror(bp);
9633 	if (((rval == COMMAND_DONE_ERROR) ||
9634 	    (rval == COMMAND_DONE_ERROR_RECOVERED)) &&
9635 	    ((get_error == EIO) || (get_error == 0))) {
9636 		un->un_rqs_state |= (ST_RQS_ERROR | ST_RQS_VALID);
9637 		bcopy(ST_RQSENSE, un->un_uscsi_rqs_buf, SENSE_LENGTH);
9638 		if (un->un_rqs_state & ST_RQS_READ) {
9639 		    un->un_rqs_state &= ~(ST_RQS_READ);
9640 		} else {
9641 		    un->un_rqs_state |= ST_RQS_OVR;
9642 		}
9643 	}
9644 
9645 	return (rval);
9646 }
9647 
9648 
9649 static int
9650 st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp)
9651 {
9652 	int status = TRAN_ACCEPT;
9653 
9654 	mutex_enter(ST_MUTEX);
9655 
9656 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9657 		"st_handle_intr_rtr_lcmd(), un = 0x%p\n", (void *)un);
9658 
9659 	/*
9660 	 * Check to see if we hit the retry timeout. We check to make sure
9661 	 * this is the first one on the runq and make sure we have not
9662 	 * queued up any more, so this one has to be the last on the list
9663 	 * also. If it is not, we have to fail.  If it is not the first, but
9664 	 * is the last we are in trouble anyway, as we are in the interrupt
9665 	 * context here.
9666 	 */
9667 	if (((int)un->un_retry_ct > st_retry_count) ||
9668 	    ((un->un_runqf != bp) && (un->un_runql != bp))) {
9669 	    goto exit;
9670 	}
9671 
9672 	if (un->un_throttle) {
9673 		un->un_last_throttle = un->un_throttle;
9674 		un->un_throttle = 0;
9675 	}
9676 
9677 	/*
9678 	 * Here we know : bp is the first and last one on the runq
9679 	 * it is not necessary to put it back on the head of the
9680 	 * waitq and then move from waitq to runq. Save this queuing
9681 	 * and call scsi_transport.
9682 	 */
9683 
9684 	mutex_exit(ST_MUTEX);
9685 
9686 	status = scsi_transport(BP_PKT(bp));
9687 
9688 	mutex_enter(ST_MUTEX);
9689 
9690 	if (status == TRAN_ACCEPT) {
9691 		un->un_tran_retry_ct = 0;
9692 		if (un->un_last_throttle) {
9693 			un->un_throttle = un->un_last_throttle;
9694 		}
9695 		mutex_exit(ST_MUTEX);
9696 
9697 		ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9698 		    "restart transport \n");
9699 		return (0);
9700 	}
9701 
9702 	ST_DO_KSTATS(bp, kstat_runq_back_to_waitq);
9703 	mutex_exit(ST_MUTEX);
9704 
9705 	if (status == TRAN_BUSY) {
9706 	    if (st_handle_intr_busy(un, bp,
9707 		ST_TRAN_BUSY_TIMEOUT) == 0)
9708 		return (0);
9709 	}
9710 	ST_DEBUG6(ST_DEVINFO, st_label, CE_WARN,
9711 		"restart transport rejected\n");
9712 	mutex_enter(ST_MUTEX);
9713 	ST_DO_ERRSTATS(un, st_transerrs);
9714 	if (un->un_last_throttle) {
9715 		un->un_throttle = un->un_last_throttle;
9716 	}
9717 exit:
9718 	mutex_exit(ST_MUTEX);
9719 	return (-1);
9720 }
9721 
9722 static int
9723 st_wrongtapetype(struct scsi_tape *un)
9724 {
9725 
9726 	ASSERT(mutex_owned(ST_MUTEX));
9727 
9728 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9729 		"st_wrongtapetype()\n");
9730 
9731 	/*
9732 	 * Hack to handle  600A, 600XTD, 6150 && 660 vs. 300XL tapes...
9733 	 */
9734 	if (un->un_dp && (un->un_dp->options & ST_QIC) && un->un_mspl) {
9735 		switch (un->un_dp->type) {
9736 		case ST_TYPE_WANGTEK:
9737 		case ST_TYPE_ARCHIVE:
9738 			/*
9739 			 * If this really worked, we could go off of
9740 			 * the density codes set in the modesense
9741 			 * page. For this drive, 0x10 == QIC-120,
9742 			 * 0xf == QIC-150, and 0x5 should be for
9743 			 * both QIC-24 and, maybe, QIC-11. However,
9744 			 * the h/w doesn't do what the manual says
9745 			 * that it should, so we'll key off of
9746 			 * getting a WRITE PROTECT error AND wp *not*
9747 			 * set in the mode sense information.
9748 			 */
9749 			/*
9750 			 * XXX but we already know that status is
9751 			 * write protect, so don't check it again.
9752 			 */
9753 
9754 			if (un->un_status == KEY_WRITE_PROTECT &&
9755 			    un->un_mspl->wp == 0) {
9756 				return (1);
9757 			}
9758 			break;
9759 		default:
9760 			break;
9761 		}
9762 	}
9763 	return (0);
9764 }
9765 
9766 static int
9767 st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt)
9768 {
9769 	int action;
9770 
9771 	ASSERT(mutex_owned(ST_MUTEX));
9772 
9773 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_check_error()\n");
9774 
9775 	if (SCBP_C(pkt) == STATUS_RESERVATION_CONFLICT) {
9776 		action = COMMAND_DONE_EACCES;
9777 		un->un_rsvd_status |= ST_RESERVATION_CONFLICT;
9778 	} else if (SCBP(pkt)->sts_busy) {
9779 		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG, "unit busy\n");
9780 		if ((int)un->un_retry_ct++ < st_retry_count) {
9781 			action = QUE_BUSY_COMMAND;
9782 		} else {
9783 			ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
9784 			    "unit busy too long\n");
9785 			mutex_exit(ST_MUTEX);
9786 			if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
9787 				(void) scsi_reset(ROUTE, RESET_ALL);
9788 			}
9789 			mutex_enter(ST_MUTEX);
9790 			action = COMMAND_DONE_ERROR;
9791 		}
9792 	} else if (SCBP(pkt)->sts_chk) {
9793 		/*
9794 		 * we should only get here if the auto rqsense failed
9795 		 * thru a uscsi cmd without autorequest sense
9796 		 * so we just try again
9797 		 */
9798 		action = QUE_SENSE;
9799 	} else {
9800 		action = COMMAND_DONE;
9801 	}
9802 	return (action);
9803 }
9804 
9805 static void
9806 st_calc_bnum(struct scsi_tape *un, struct buf *bp)
9807 {
9808 	int n;
9809 
9810 	ASSERT(mutex_owned(ST_MUTEX));
9811 
9812 	if (un->un_bsize == 0) {
9813 		n = ((bp->b_bcount - bp->b_resid  == 0) ? 0 : 1);
9814 		un->un_kbytes_xferred += (bp->b_bcount - bp->b_resid)/1000;
9815 	} else {
9816 		n = ((bp->b_bcount - bp->b_resid) / un->un_bsize);
9817 	}
9818 	un->un_blkno += n;
9819 }
9820 
9821 static void
9822 st_set_state(struct scsi_tape *un)
9823 {
9824 	struct buf *bp = un->un_runqf;
9825 	struct scsi_pkt *sp = BP_PKT(bp);
9826 	struct uscsi_cmd *ucmd;
9827 
9828 	ASSERT(mutex_owned(ST_MUTEX));
9829 
9830 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
9831 	    "st_set_state(): un_eof=%x	fmneeded=%x  pkt_resid=0x%lx (%ld)\n",
9832 		un->un_eof, un->un_fmneeded, sp->pkt_resid, sp->pkt_resid);
9833 
9834 	if (bp != un->un_sbufp) {
9835 #ifdef STDEBUG
9836 		if (DEBUGGING && sp->pkt_resid) {
9837 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9838 			    "pkt_resid %ld bcount %ld\n",
9839 			    sp->pkt_resid, bp->b_bcount);
9840 		}
9841 #endif
9842 		bp->b_resid = sp->pkt_resid;
9843 		st_calc_bnum(un, bp);
9844 		if (bp->b_flags & B_READ) {
9845 			un->un_lastop = ST_OP_READ;
9846 			un->un_fmneeded = 0;
9847 		} else {
9848 			un->un_lastop = ST_OP_WRITE;
9849 			if (un->un_dp->options & ST_REEL) {
9850 				un->un_fmneeded = 2;
9851 			} else {
9852 				un->un_fmneeded = 1;
9853 			}
9854 		}
9855 		/*
9856 		 * all is honky dory at this point, so let's
9857 		 * readjust the throttle, to increase speed, if we
9858 		 * have not throttled down.
9859 		 */
9860 		if (un->un_throttle)
9861 			un->un_throttle = un->un_max_throttle;
9862 	} else {
9863 		char saved_lastop = un->un_lastop;
9864 		uchar_t cmd = (uchar_t)(intptr_t)bp->b_forw;
9865 
9866 		un->un_lastop = ST_OP_CTL;
9867 
9868 		switch (cmd) {
9869 		case SCMD_WRITE:
9870 			bp->b_resid = sp->pkt_resid;
9871 			un->un_lastop = ST_OP_WRITE;
9872 			st_calc_bnum(un, bp);
9873 			if (un->un_dp->options & ST_REEL) {
9874 				un->un_fmneeded = 2;
9875 			} else {
9876 				un->un_fmneeded = 1;
9877 			}
9878 			break;
9879 		case SCMD_READ:
9880 			bp->b_resid = sp->pkt_resid;
9881 			un->un_lastop = ST_OP_READ;
9882 			st_calc_bnum(un, bp);
9883 			un->un_fmneeded = 0;
9884 			break;
9885 		case SCMD_WRITE_FILE_MARK:
9886 			if (un->un_eof != ST_EOM)
9887 				un->un_eof = ST_NO_EOF;
9888 			un->un_lastop = ST_OP_WEOF;
9889 			un->un_fileno += (bp->b_bcount - bp->b_resid);
9890 			un->un_blkno = 0;
9891 			if (un->un_dp->options & ST_REEL) {
9892 				un->un_fmneeded -=
9893 					(bp->b_bcount - bp->b_resid);
9894 				if (un->un_fmneeded < 0) {
9895 					un->un_fmneeded = 0;
9896 				}
9897 			} else {
9898 				un->un_fmneeded = 0;
9899 			}
9900 
9901 			break;
9902 		case SCMD_REWIND:
9903 			un->un_eof = ST_NO_EOF;
9904 			un->un_fileno = 0;
9905 			un->un_blkno = 0;
9906 			break;
9907 
9908 		case SCMD_SPACE:
9909 		{
9910 			int space_fmk, count;
9911 			long resid;
9912 
9913 			count = (int)space_cnt(bp->b_bcount);
9914 			resid = (long)space_cnt(bp->b_resid);
9915 			space_fmk = ((bp->b_bcount) & (1<<24)) ? 1 : 0;
9916 
9917 
9918 			if (count >= 0) {
9919 				if (space_fmk) {
9920 					if (un->un_eof <= ST_EOF) {
9921 						un->un_eof = ST_NO_EOF;
9922 					}
9923 					un->un_fileno += (count - resid);
9924 					un->un_blkno = 0;
9925 				} else {
9926 					un->un_blkno += count - resid;
9927 				}
9928 			} else if (count < 0) {
9929 				if (space_fmk) {
9930 					un->un_fileno -=
9931 					    ((-count) - resid);
9932 					if (un->un_fileno < 0) {
9933 						un->un_fileno = 0;
9934 						un->un_blkno = 0;
9935 					} else {
9936 						un->un_blkno = INF;
9937 					}
9938 				} else {
9939 					if (un->un_eof >= ST_EOF_PENDING) {
9940 					/*
9941 					 * we stepped back into
9942 					 * a previous file; we are not
9943 					 * making an effort to pretend that
9944 					 * we are still in the current file
9945 					 * ie. logical == physical position
9946 					 * and leave it to st_ioctl to correct
9947 					 */
9948 						if (un->un_fileno > 0) {
9949 							un->un_fileno--;
9950 							un->un_blkno = INF;
9951 						} else {
9952 							un->un_blkno = 0;
9953 						}
9954 					} else {
9955 						un->un_blkno -=
9956 						    (-count) - resid;
9957 					}
9958 				}
9959 			}
9960 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
9961 			    "aft_space rs %ld fil %d blk %ld\n",
9962 			    resid, un->un_fileno, un->un_blkno);
9963 			break;
9964 		}
9965 		case SCMD_LOAD:
9966 			if (bp->b_bcount & 0x1) {
9967 				un->un_fileno = 0;
9968 			} else {
9969 				un->un_state = ST_STATE_OFFLINE;
9970 				un->un_fileno = -1;
9971 			}
9972 			un->un_density_known = 0;
9973 			un->un_eof = ST_NO_EOF;
9974 			un->un_blkno = 0;
9975 			break;
9976 		case SCMD_ERASE:
9977 			un->un_eof = ST_NO_EOF;
9978 			un->un_blkno = 0;
9979 			un->un_fileno = 0;
9980 			break;
9981 		case SCMD_RESERVE:
9982 			un->un_rsvd_status |= ST_RESERVE;
9983 			un->un_rsvd_status &=
9984 				~(ST_RELEASE | ST_LOST_RESERVE |
9985 					ST_RESERVATION_CONFLICT);
9986 			un->un_lastop = saved_lastop;
9987 			break;
9988 		case SCMD_RELEASE:
9989 			un->un_rsvd_status |= ST_RELEASE;
9990 			un->un_rsvd_status &=
9991 				~(ST_RESERVE | ST_LOST_RESERVE |
9992 					ST_RESERVATION_CONFLICT);
9993 			un->un_lastop = saved_lastop;
9994 			break;
9995 		case SCMD_TEST_UNIT_READY:
9996 		case SCMD_READ_BLKLIM:
9997 		case SCMD_REQUEST_SENSE:
9998 		case SCMD_INQUIRY:
9999 		case SCMD_RECOVER_BUF:
10000 		case SCMD_MODE_SELECT:
10001 		case SCMD_MODE_SENSE:
10002 		case SCMD_DOORLOCK:
10003 		case SCMD_READ_POSITION:
10004 		case SCMD_READ_BUFFER:
10005 		case SCMD_REPORT_DENSITIES:
10006 		case SCMD_LOG_SELECT_G1:
10007 		case SCMD_LOG_SENSE_G1:
10008 		case SCMD_REPORT_LUNS:
10009 			un->un_lastop = saved_lastop;
10010 			break;
10011 		case SCMD_LOCATE:	/* Locate makes position unknown */
10012 		default:
10013 			/*
10014 			 * Unknown command, If was USCSI and USCSI_SILENT
10015 			 * flag was not set, set position to unknown.
10016 			 */
10017 			if ((((ucmd = BP_UCMD(bp)) != NULL) &&
10018 			    (ucmd->uscsi_flags & USCSI_SILENT) == 0)) {
10019 				ST_DEBUG2(ST_DEVINFO, st_label, CE_WARN,
10020 				    "unknown cmd 0x%X caused loss of state\n",
10021 				    cmd);
10022 			} else {
10023 				break;
10024 			}
10025 			/* FALLTHROUGH */
10026 		case SCMD_WRITE_BUFFER: /* Writes new firmware to device */
10027 			un->un_fileno = -1;
10028 			break;
10029 		}
10030 	}
10031 
10032 	/*
10033 	 * In the st driver we have a logical and physical file position.
10034 	 * Under BSD behavior, when you get a zero read, the logical position
10035 	 * is before the filemark but after the last record of the file.
10036 	 * The physical position is after the filemark. MTIOCGET should always
10037 	 * return the logical file position.
10038 	 *
10039 	 * The next read gives a silent skip to the next file.
10040 	 * Under SVR4, the logical file position remains before the filemark
10041 	 * until the file is closed or a space operation is performed.
10042 	 * Hence set err_resid and err_file before changing fileno if case
10043 	 * BSD Behaviour.
10044 	 */
10045 	un->un_err_resid = bp->b_resid;
10046 	un->un_err_fileno = un->un_fileno;
10047 	un->un_err_blkno = un->un_blkno;
10048 	un->un_retry_ct = 0;
10049 
10050 
10051 	/*
10052 	 * If we've seen a filemark via the last read operation
10053 	 * advance the file counter, but mark things such that
10054 	 * the next read operation gets a zero count. We have
10055 	 * to put this here to handle the case of sitting right
10056 	 * at the end of a tape file having seen the file mark,
10057 	 * but the tape is closed and then re-opened without
10058 	 * any further i/o. That is, the position information
10059 	 * must be updated before a close.
10060 	 */
10061 
10062 	if (un->un_lastop == ST_OP_READ && un->un_eof == ST_EOF_PENDING) {
10063 		/*
10064 		 * If we're a 1/2" tape, and we get a filemark
10065 		 * right on block 0, *AND* we were not in the
10066 		 * first file on the tape, and we've hit logical EOM.
10067 		 * We'll mark the state so that later we do the
10068 		 * right thing (in st_close(), st_strategy() or
10069 		 * st_ioctl()).
10070 		 *
10071 		 */
10072 		if ((un->un_dp->options & ST_REEL) &&
10073 			!(un->un_dp->options & ST_READ_IGNORE_EOFS) &&
10074 		    un->un_blkno == 0 && un->un_fileno > 0) {
10075 			un->un_eof = ST_EOT_PENDING;
10076 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10077 			    "eot pending\n");
10078 			un->un_fileno++;
10079 			un->un_blkno = 0;
10080 		} else if (BSD_BEHAVIOR) {
10081 			/*
10082 			 * If the read of the filemark was a side effect
10083 			 * of reading some blocks (i.e., data was actually
10084 			 * read), then the EOF mark is pending and the
10085 			 * bump into the next file awaits the next read
10086 			 * operation (which will return a zero count), or
10087 			 * a close or a space operation, else the bump
10088 			 * into the next file occurs now.
10089 			 */
10090 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10091 			    "resid=%lx, bcount=%lx\n",
10092 				bp->b_resid, bp->b_bcount);
10093 			if (bp->b_resid != bp->b_bcount) {
10094 				un->un_eof = ST_EOF;
10095 			} else {
10096 				un->un_silent_skip = 1;
10097 				un->un_eof = ST_NO_EOF;
10098 				un->un_fileno++;
10099 				un->un_save_blkno = un->un_blkno;
10100 				un->un_blkno = 0;
10101 			}
10102 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10103 			    "eof of file %d, un_eof=%d\n",
10104 			    un->un_fileno, un->un_eof);
10105 		} else if (SVR4_BEHAVIOR) {
10106 			/*
10107 			 * If the read of the filemark was a side effect
10108 			 * of reading some blocks (i.e., data was actually
10109 			 * read), then the next read should return 0
10110 			 */
10111 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10112 			    "resid=%lx, bcount=%lx\n",
10113 			    bp->b_resid, bp->b_bcount);
10114 			if (bp->b_resid == bp->b_bcount) {
10115 				un->un_eof = ST_EOF;
10116 			}
10117 			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
10118 			    "eof of file=%d, un_eof=%d\n",
10119 			    un->un_fileno, un->un_eof);
10120 		}
10121 	}
10122 }
10123 
10124 /*
10125  * set the correct un_errno, to take corner cases into consideration
10126  */
10127 static void
10128 st_set_pe_errno(struct scsi_tape *un)
10129 {
10130 	ASSERT(mutex_owned(ST_MUTEX));
10131 
10132 	/* if errno is already set, don't reset it */
10133 	if (un->un_errno)
10134 		return;
10135 
10136 	/* here un_errno == 0 */
10137 	/*
10138 	 * if the last transfer before flushing all the
10139 	 * waiting I/O's, was 0 (resid = count), then we
10140 	 * want to give the user an error on all the rest,
10141 	 * so here.  If there was a transfer, we set the
10142 	 * resid and counts to 0, and let it drop through,
10143 	 * giving a zero return.  the next I/O will then
10144 	 * give an error.
10145 	 */
10146 	if (un->un_last_resid == un->un_last_count) {
10147 		switch (un->un_eof) {
10148 		case ST_EOM:
10149 			un->un_errno = ENOMEM;
10150 			break;
10151 		case ST_EOT:
10152 		case ST_EOF:
10153 			un->un_errno = EIO;
10154 			break;
10155 		}
10156 	} else {
10157 		/*
10158 		 * we know they did not have a zero, so make
10159 		 * sure they get one
10160 		 */
10161 		un->un_last_resid = un->un_last_count = 0;
10162 	}
10163 }
10164 
10165 
10166 /*
10167  * send in a marker pkt to terminate flushing of commands by BBA (via
10168  * flush-on-errors) property.  The HBA will always return TRAN_ACCEPT
10169  */
10170 static void
10171 st_hba_unflush(struct scsi_tape *un)
10172 {
10173 	ASSERT(mutex_owned(ST_MUTEX));
10174 
10175 	if (!un->un_flush_on_errors)
10176 		return;
10177 
10178 #ifdef FLUSH_ON_ERRORS
10179 
10180 	if (!un->un_mkr_pkt) {
10181 		un->un_mkr_pkt = scsi_init_pkt(ROUTE, NULL, (struct buf *)NULL,
10182 		    NULL, 0, 0, 0, SLEEP_FUNC, NULL);
10183 
10184 		/* we slept, so it must be there */
10185 		pkt->pkt_flags |= FLAG_FLUSH_MARKER;
10186 	}
10187 
10188 	mutex_exit(ST_MUTEX);
10189 	scsi_transport(un->un_mkr_pkt);
10190 	mutex_enter(ST_MUTEX);
10191 #endif
10192 }
10193 
10194 static void
10195 st_clean_print(dev_info_t *dev, char *label, uint_t level,
10196 	char *title, char *data, int len)
10197 {
10198 	int	i;
10199 	char	buf[256];
10200 
10201 	(void) sprintf(buf, "%s: ", title);
10202 	for (i = 0; i < len; i++) {
10203 		(void) sprintf(&buf[(int)strlen(buf)], "0x%x ",
10204 			(data[i] & 0xff));
10205 	}
10206 	(void) sprintf(&buf[(int)strlen(buf)], "\n");
10207 
10208 	scsi_log(dev, label, level, "%s", buf);
10209 }
10210 
10211 /*
10212  * Conditionally enabled debugging
10213  */
10214 #ifdef	STDEBUG
10215 static void
10216 st_debug_cmds(struct scsi_tape *un, int com, int count, int wait)
10217 {
10218 	char tmpbuf[64];
10219 
10220 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10221 	    "cmd=%s count=0x%x (%d)	 %ssync\n",
10222 	    scsi_cmd_name(com, scsi_cmds, tmpbuf),
10223 	    count, count,
10224 	    wait == ASYNC_CMD ? "a" : "");
10225 }
10226 
10227 /*
10228  * Returns pointer to name of minor node name of device 'dev'.
10229  */
10230 static char *
10231 st_dev_name(dev_t dev)
10232 {
10233 	const char density[] = { 'l', 'm', 'h', 'c' };
10234 	static char name[4];
10235 	minor_t minor;
10236 	int nprt = 0;
10237 
10238 	minor = getminor(dev);
10239 	name[nprt] = density[(minor & MT_DENSITY_MASK) >> 3];
10240 
10241 	if (minor & MT_BSD) {
10242 		name[++nprt] = 'b';
10243 	}
10244 
10245 	if (minor & MT_NOREWIND) {
10246 		name[++nprt] = 'n';
10247 	}
10248 
10249 	/* NULL terminator */
10250 	name[++nprt] = 0;
10251 
10252 	return (name);
10253 }
10254 #endif	/* STDEBUG */
10255 
10256 /*
10257  * Soft error reporting, so far unique to each drive
10258  *
10259  * Currently supported: exabyte and DAT soft error reporting
10260  */
10261 static int
10262 st_report_exabyte_soft_errors(dev_t dev, int flag)
10263 {
10264 	uchar_t *sensep;
10265 	int amt;
10266 	int rval = 0;
10267 	char cdb[CDB_GROUP0], *c = cdb;
10268 	struct uscsi_cmd *com;
10269 
10270 	GET_SOFT_STATE(dev);
10271 
10272 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10273 	    "st_report_exabyte_soft_errors(dev = 0x%lx, flag = %d)\n",
10274 	    dev, flag);
10275 
10276 	ASSERT(mutex_owned(ST_MUTEX));
10277 
10278 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
10279 	sensep = kmem_zalloc(TAPE_SENSE_LENGTH, KM_SLEEP);
10280 
10281 	*c++ = SCMD_REQUEST_SENSE;
10282 	*c++ = 0;
10283 	*c++ = 0;
10284 	*c++ = 0;
10285 	*c++ = TAPE_SENSE_LENGTH;
10286 	/*
10287 	 * set CLRCNT (byte 5, bit 7 which clears the error counts)
10288 	 */
10289 	*c   = (char)0x80;
10290 
10291 	com->uscsi_cdb = cdb;
10292 	com->uscsi_cdblen = CDB_GROUP0;
10293 	com->uscsi_bufaddr = (caddr_t)sensep;
10294 	com->uscsi_buflen = TAPE_SENSE_LENGTH;
10295 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT
10296 		| USCSI_READ | USCSI_RQENABLE;
10297 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
10298 
10299 	rval = st_ioctl_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE,
10300 		UIO_SYSSPACE);
10301 	if (rval || com->uscsi_status) {
10302 		goto done;
10303 	}
10304 
10305 	/*
10306 	 * was there enough data?
10307 	 */
10308 	amt = (int)TAPE_SENSE_LENGTH - com->uscsi_resid;
10309 
10310 	if ((amt >= 19) && un->un_kbytes_xferred) {
10311 		uint_t count, error_rate;
10312 		uint_t rate;
10313 
10314 		if (sensep[21] & CLN) {
10315 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10316 			    "Periodic head cleaning required");
10317 		}
10318 		if (un->un_kbytes_xferred < (EXABYTE_MIN_TRANSFER/1000))
10319 			goto done;
10320 		/*
10321 		 * check if soft error reporting needs to be done.
10322 		 */
10323 		count = sensep[16] << 16 | sensep[17] << 8 | sensep[18];
10324 		count &= 0xffffff;
10325 		error_rate = (count * 100)/un->un_kbytes_xferred;
10326 
10327 #ifdef	STDEBUG
10328 		if (st_soft_error_report_debug) {
10329 			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
10330 			    "Exabyte Soft Error Report:\n");
10331 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10332 			    "read/write error counter: %d\n", count);
10333 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10334 			    "number of bytes transferred: %dK\n",
10335 				un->un_kbytes_xferred);
10336 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10337 			    "error_rate: %d%%\n", error_rate);
10338 
10339 			if (amt >= 22) {
10340 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10341 				    "unit sense: 0x%b 0x%b 0x%b\n",
10342 				    sensep[19], SENSE_19_BITS,
10343 				    sensep[20], SENSE_20_BITS,
10344 				    sensep[21], SENSE_21_BITS);
10345 			}
10346 			if (amt >= 27) {
10347 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10348 				    "tracking retry counter: %d\n",
10349 				    sensep[26]);
10350 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10351 				    "read/write retry counter: %d\n",
10352 				    sensep[27]);
10353 			}
10354 		}
10355 #endif
10356 
10357 		if (flag & FWRITE) {
10358 			rate = EXABYTE_WRITE_ERROR_THRESHOLD;
10359 		} else {
10360 			rate = EXABYTE_READ_ERROR_THRESHOLD;
10361 		}
10362 		if (error_rate >= rate) {
10363 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10364 			    "Soft error rate (%d%%) during %s was too high",
10365 			    error_rate,
10366 			    ((flag & FWRITE) ? wrg_str : rdg_str));
10367 			scsi_log(ST_DEVINFO, st_label, CE_CONT,
10368 			    "Please, replace tape cartridge\n");
10369 		}
10370 	}
10371 
10372 done:
10373 	kmem_free(com, sizeof (*com));
10374 	kmem_free(sensep, TAPE_SENSE_LENGTH);
10375 
10376 	if (rval != 0) {
10377 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10378 		    "exabyte soft error reporting failed\n");
10379 	}
10380 	return (rval);
10381 }
10382 
10383 /*
10384  * this is very specific to Archive 4mm dat
10385  */
10386 #define	ONEGIG	(1024 * 1024 * 1024)
10387 
10388 static int
10389 st_report_dat_soft_errors(dev_t dev, int flag)
10390 {
10391 	uchar_t *sensep;
10392 	int amt, i;
10393 	int rval = 0;
10394 	char cdb[CDB_GROUP1], *c = cdb;
10395 	struct uscsi_cmd *com;
10396 
10397 	GET_SOFT_STATE(dev);
10398 
10399 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10400 	    "st_report_dat_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
10401 
10402 	ASSERT(mutex_owned(ST_MUTEX));
10403 
10404 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
10405 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
10406 
10407 	*c++ = SCMD_LOG_SENSE_G1;
10408 	*c++ = 0;
10409 	*c++ = (flag & FWRITE) ? 0x42 : 0x43;
10410 	*c++ = 0;
10411 	*c++ = 0;
10412 	*c++ = 0;
10413 	*c++ = 2;
10414 	*c++ = 0;
10415 	*c++ = (char)LOG_SENSE_LENGTH;
10416 	*c   = 0;
10417 	com->uscsi_cdb    = cdb;
10418 	com->uscsi_cdblen  = CDB_GROUP1;
10419 	com->uscsi_bufaddr = (caddr_t)sensep;
10420 	com->uscsi_buflen  = LOG_SENSE_LENGTH;
10421 	com->uscsi_flags   =
10422 	    USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ | USCSI_RQENABLE;
10423 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
10424 	rval =
10425 	    st_ioctl_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE, UIO_SYSSPACE);
10426 	if (rval) {
10427 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10428 		    "DAT soft error reporting failed\n");
10429 	}
10430 	if (rval || com->uscsi_status) {
10431 		goto done;
10432 	}
10433 
10434 	/*
10435 	 * was there enough data?
10436 	 */
10437 	amt = (int)LOG_SENSE_LENGTH - com->uscsi_resid;
10438 
10439 	if ((amt >= MIN_LOG_SENSE_LENGTH) && un->un_kbytes_xferred) {
10440 		int total, retries, param_code;
10441 
10442 		total = -1;
10443 		retries = -1;
10444 		amt = sensep[3] + 4;
10445 
10446 
10447 #ifdef STDEBUG
10448 		if (st_soft_error_report_debug) {
10449 			(void) printf("logsense:");
10450 			for (i = 0; i < MIN_LOG_SENSE_LENGTH; i++) {
10451 				if (i % 16 == 0) {
10452 					(void) printf("\t\n");
10453 				}
10454 				(void) printf(" %x", sensep[i]);
10455 			}
10456 			(void) printf("\n");
10457 		}
10458 #endif
10459 
10460 		/*
10461 		 * parse the param_codes
10462 		 */
10463 		if (sensep[0] == 2 || sensep[0] == 3) {
10464 			for (i = 4; i < amt; i++) {
10465 				param_code = (sensep[i++] << 8);
10466 				param_code += sensep[i++];
10467 				i++; /* skip control byte */
10468 				if (param_code == 5) {
10469 					if (sensep[i++] == 4) {
10470 						total = (sensep[i++] << 24);
10471 						total += (sensep[i++] << 16);
10472 						total += (sensep[i++] << 8);
10473 						total += sensep[i];
10474 					}
10475 				} else if (param_code == 0x8007) {
10476 					if (sensep[i++] == 2) {
10477 						retries = sensep[i++] << 8;
10478 						retries += sensep[i];
10479 					}
10480 				} else {
10481 					i += sensep[i];
10482 				}
10483 			}
10484 		}
10485 
10486 		/*
10487 		 * if the log sense returned valid numbers then determine
10488 		 * the read and write error thresholds based on the amount of
10489 		 * data transferred
10490 		 */
10491 
10492 		if (total > 0 && retries > 0) {
10493 			short normal_retries = 0;
10494 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10495 			"total xferred (%s) =%x, retries=%x\n",
10496 				((flag & FWRITE) ? wrg_str : rdg_str),
10497 				total, retries);
10498 
10499 			if (flag & FWRITE) {
10500 				if (total <=
10501 					WRITE_SOFT_ERROR_WARNING_THRESHOLD) {
10502 					normal_retries =
10503 						DAT_SMALL_WRITE_ERROR_THRESHOLD;
10504 				} else {
10505 					normal_retries =
10506 						DAT_LARGE_WRITE_ERROR_THRESHOLD;
10507 				}
10508 			} else {
10509 				if (total <=
10510 					READ_SOFT_ERROR_WARNING_THRESHOLD) {
10511 					normal_retries =
10512 						DAT_SMALL_READ_ERROR_THRESHOLD;
10513 				} else {
10514 					normal_retries =
10515 						DAT_LARGE_READ_ERROR_THRESHOLD;
10516 				}
10517 			}
10518 
10519 			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
10520 			"normal retries=%d\n", normal_retries);
10521 
10522 			if (retries >= normal_retries) {
10523 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
10524 				    "Soft error rate (retries = %d) during "
10525 				    "%s was too high",  retries,
10526 				    ((flag & FWRITE) ? wrg_str : rdg_str));
10527 				scsi_log(ST_DEVINFO, st_label, CE_CONT,
10528 				    "Periodic head cleaning required "
10529 				    "and/or replace tape cartridge\n");
10530 			}
10531 
10532 		} else if (total == -1 || retries == -1) {
10533 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10534 			    "log sense parameter code does not make sense\n");
10535 		}
10536 	}
10537 
10538 	/*
10539 	 * reset all values
10540 	 */
10541 	c = cdb;
10542 	*c++ = SCMD_LOG_SELECT_G1;
10543 	*c++ = 2;	/* this resets all values */
10544 	*c++ = (char)0xc0;
10545 	*c++ = 0;
10546 	*c++ = 0;
10547 	*c++ = 0;
10548 	*c++ = 0;
10549 	*c++ = 0;
10550 	*c++ = 0;
10551 	*c   = 0;
10552 	com->uscsi_bufaddr = NULL;
10553 	com->uscsi_buflen  = 0;
10554 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_RQENABLE;
10555 	rval =
10556 	    st_ioctl_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE, UIO_SYSSPACE);
10557 	if (rval) {
10558 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10559 		    "DAT soft error reset failed\n");
10560 	}
10561 done:
10562 	kmem_free(com, sizeof (*com));
10563 	kmem_free(sensep, LOG_SENSE_LENGTH);
10564 	return (rval);
10565 }
10566 
10567 static int
10568 st_report_soft_errors(dev_t dev, int flag)
10569 {
10570 	GET_SOFT_STATE(dev);
10571 
10572 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10573 	    "st_report_soft_errors(dev = 0x%lx, flag = %d)\n", dev, flag);
10574 
10575 	ASSERT(mutex_owned(ST_MUTEX));
10576 
10577 	switch (un->un_dp->type) {
10578 	case ST_TYPE_EXB8500:
10579 	case ST_TYPE_EXABYTE:
10580 		return (st_report_exabyte_soft_errors(dev, flag));
10581 		/*NOTREACHED*/
10582 	case ST_TYPE_PYTHON:
10583 		return (st_report_dat_soft_errors(dev, flag));
10584 		/*NOTREACHED*/
10585 	default:
10586 		un->un_dp->options &= ~ST_SOFT_ERROR_REPORTING;
10587 		return (-1);
10588 	}
10589 }
10590 
10591 /*
10592  * persistent error routines
10593  */
10594 
10595 /*
10596  * enable persistent errors, and set the throttle appropriately, checking
10597  * for flush-on-errors capability
10598  */
10599 static void
10600 st_turn_pe_on(struct scsi_tape *un)
10601 {
10602 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_on\n");
10603 	ASSERT(mutex_owned(ST_MUTEX));
10604 
10605 	un->un_persistence = 1;
10606 
10607 	/*
10608 	 * only use flush-on-errors if auto-request-sense and untagged-qing are
10609 	 * enabled.  This will simplify the error handling for request senses
10610 	 */
10611 
10612 	if (un->un_arq_enabled && un->un_untagged_qing) {
10613 		uchar_t f_o_e;
10614 
10615 		mutex_exit(ST_MUTEX);
10616 		f_o_e = (scsi_ifsetcap(ROUTE, "flush-on-errors", 1, 1) == 1) ?
10617 		    1 : 0;
10618 		mutex_enter(ST_MUTEX);
10619 
10620 		un->un_flush_on_errors = f_o_e;
10621 	} else {
10622 		un->un_flush_on_errors = 0;
10623 	}
10624 
10625 	if (un->un_flush_on_errors)
10626 		un->un_max_throttle = (uchar_t)st_max_throttle;
10627 	else
10628 		un->un_max_throttle = 1;
10629 
10630 	if (un->un_dp->options & ST_RETRY_ON_RECOVERED_DEFERRED_ERROR)
10631 		un->un_max_throttle = 1;
10632 
10633 	/* this will send a marker pkt */
10634 	CLEAR_PE(un);
10635 }
10636 
10637 /*
10638  * This turns persistent errors permanently off
10639  */
10640 static void
10641 st_turn_pe_off(struct scsi_tape *un)
10642 {
10643 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_off\n");
10644 	ASSERT(mutex_owned(ST_MUTEX));
10645 
10646 	/* turn it off for good */
10647 	un->un_persistence = 0;
10648 
10649 	/* this will send a marker pkt */
10650 	CLEAR_PE(un);
10651 
10652 	/* turn off flush on error capability, if enabled */
10653 	if (un->un_flush_on_errors) {
10654 		mutex_exit(ST_MUTEX);
10655 		(void) scsi_ifsetcap(ROUTE, "flush-on-errors", 0, 1);
10656 		mutex_enter(ST_MUTEX);
10657 	}
10658 
10659 
10660 	un->un_flush_on_errors = 0;
10661 }
10662 
10663 /*
10664  * This clear persistent errors, allowing more commands through, and also
10665  * sending a marker packet.
10666  */
10667 static void
10668 st_clear_pe(struct scsi_tape *un)
10669 {
10670 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_clear\n");
10671 	ASSERT(mutex_owned(ST_MUTEX));
10672 
10673 	un->un_persist_errors = 0;
10674 	un->un_throttle = un->un_last_throttle = 1;
10675 	un->un_errno = 0;
10676 	st_hba_unflush(un);
10677 }
10678 
10679 /*
10680  * This will flag persistent errors, shutting everything down, if the
10681  * application had enabled persistent errors via MTIOCPERSISTENT
10682  */
10683 static void
10684 st_set_pe_flag(struct scsi_tape *un)
10685 {
10686 	ASSERT(mutex_owned(ST_MUTEX));
10687 
10688 	if (un->un_persistence) {
10689 		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG, "st_pe_flag\n");
10690 		un->un_persist_errors = 1;
10691 		un->un_throttle = un->un_last_throttle = 0;
10692 	}
10693 }
10694 
10695 int
10696 st_reserve_release(dev_t dev, int cmd)
10697 {
10698 	struct uscsi_cmd	uscsi_cmd;
10699 	struct uscsi_cmd	*com = &uscsi_cmd;
10700 	int			rval;
10701 	char			cdb[CDB_GROUP0];
10702 
10703 
10704 	GET_SOFT_STATE(dev);
10705 	ASSERT(mutex_owned(ST_MUTEX));
10706 
10707 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10708 		"st_reserve_release: %s \n", (cmd == ST_RELEASE)?
10709 				"Releasing":"Reserving");
10710 
10711 	bzero(cdb, CDB_GROUP0);
10712 	if (cmd == ST_RELEASE) {
10713 		cdb[0] = SCMD_RELEASE;
10714 	} else {
10715 		cdb[0] = SCMD_RESERVE;
10716 	}
10717 	bzero(com, sizeof (struct uscsi_cmd));
10718 	com->uscsi_flags = USCSI_WRITE;
10719 	com->uscsi_cdb = cdb;
10720 	com->uscsi_cdblen = CDB_GROUP0;
10721 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
10722 
10723 	rval = st_ioctl_cmd(dev, com,
10724 		UIO_SYSSPACE, UIO_SYSSPACE, UIO_SYSSPACE);
10725 
10726 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10727 		"st_reserve_release: rval(1)=%d\n", rval);
10728 
10729 	if (rval) {
10730 		if (com->uscsi_status == STATUS_RESERVATION_CONFLICT)
10731 			rval = EACCES;
10732 		/*
10733 		 * dynamically turn off reserve/release support
10734 		 * in case of drives which do not support
10735 		 * reserve/release command(ATAPI drives).
10736 		 */
10737 		if (un->un_status == KEY_ILLEGAL_REQUEST) {
10738 			if (ST_RESERVE_SUPPORTED(un)) {
10739 				un->un_dp->options |= ST_NO_RESERVE_RELEASE;
10740 				ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10741 					"Tape unit does not support "
10742 					"reserve/release \n");
10743 			}
10744 			rval = 0;
10745 		}
10746 	}
10747 	return (rval);
10748 }
10749 
10750 static int
10751 st_take_ownership(dev_t dev)
10752 {
10753 	int rval;
10754 
10755 	GET_SOFT_STATE(dev);
10756 	ASSERT(mutex_owned(ST_MUTEX));
10757 
10758 	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
10759 		"st_take_ownership: Entering ...\n");
10760 
10761 
10762 	rval = st_reserve_release(dev, ST_RESERVE);
10763 	/*
10764 	 * XXX -> Should reset be done only if we get EACCES.
10765 	 * .
10766 	 */
10767 	if (rval) {
10768 		mutex_exit(ST_MUTEX);
10769 		if (scsi_reset(ROUTE, RESET_TARGET) == 0) {
10770 			if (scsi_reset(ROUTE, RESET_ALL) == 0) {
10771 				mutex_enter(ST_MUTEX);
10772 				return (EIO);
10773 			}
10774 		}
10775 		mutex_enter(ST_MUTEX);
10776 		un->un_rsvd_status &=
10777 			~(ST_LOST_RESERVE | ST_RESERVATION_CONFLICT);
10778 
10779 		mutex_exit(ST_MUTEX);
10780 		delay(drv_usectohz(ST_RESERVATION_DELAY));
10781 		mutex_enter(ST_MUTEX);
10782 		/*
10783 		 * remove the check condition.
10784 		 */
10785 		(void) st_reserve_release(dev, ST_RESERVE);
10786 		if ((rval = st_reserve_release(dev, ST_RESERVE)) != 0) {
10787 			if ((st_reserve_release(dev, ST_RESERVE)) != 0) {
10788 				rval = (un->un_rsvd_status &
10789 					ST_RESERVATION_CONFLICT) ? EACCES : EIO;
10790 				return (rval);
10791 			}
10792 		}
10793 		/*
10794 		 * Set tape state to ST_STATE_OFFLINE , in case if
10795 		 * the user wants to continue and start using
10796 		 * the tape.
10797 		 */
10798 		un->un_state = ST_STATE_OFFLINE;
10799 		un->un_rsvd_status |= ST_INIT_RESERVE;
10800 	}
10801 	return (rval);
10802 }
10803 
10804 static int
10805 st_create_errstats(struct scsi_tape *un, int instance)
10806 {
10807 	char	kstatname[KSTAT_STRLEN];
10808 
10809 	/*
10810 	 * Create device error kstats
10811 	 */
10812 
10813 	if (un->un_errstats == (kstat_t *)0) {
10814 		(void) sprintf(kstatname, "st%d,err", instance);
10815 		un->un_errstats = kstat_create("sterr", instance, kstatname,
10816 			"device_error", KSTAT_TYPE_NAMED,
10817 			sizeof (struct st_errstats) / sizeof (kstat_named_t),
10818 			KSTAT_FLAG_PERSISTENT);
10819 
10820 		if (un->un_errstats) {
10821 			struct st_errstats	*stp;
10822 
10823 			stp = (struct st_errstats *)un->un_errstats->ks_data;
10824 			kstat_named_init(&stp->st_softerrs, "Soft Errors",
10825 				KSTAT_DATA_ULONG);
10826 			kstat_named_init(&stp->st_harderrs, "Hard Errors",
10827 				KSTAT_DATA_ULONG);
10828 			kstat_named_init(&stp->st_transerrs, "Transport Errors",
10829 				KSTAT_DATA_ULONG);
10830 			kstat_named_init(&stp->st_vid, "Vendor",
10831 				KSTAT_DATA_CHAR);
10832 			kstat_named_init(&stp->st_pid, "Product",
10833 				KSTAT_DATA_CHAR);
10834 			kstat_named_init(&stp->st_revision, "Revision",
10835 				KSTAT_DATA_CHAR);
10836 			kstat_named_init(&stp->st_serial, "Serial No",
10837 				KSTAT_DATA_CHAR);
10838 			un->un_errstats->ks_private = un;
10839 			un->un_errstats->ks_update = nulldev;
10840 			kstat_install(un->un_errstats);
10841 			/*
10842 			 * Fill in the static data
10843 			 */
10844 			(void) strncpy(&stp->st_vid.value.c[0],
10845 					ST_INQUIRY->inq_vid, 8);
10846 			/*
10847 			 * XXX:  Emulex MT-02 (and emulators) predates
10848 			 *	 SCSI-1 and has no vid & pid inquiry data.
10849 			 */
10850 			if (ST_INQUIRY->inq_len != 0) {
10851 				(void) strncpy(&stp->st_pid.value.c[0],
10852 					ST_INQUIRY->inq_pid, 16);
10853 				(void) strncpy(&stp->st_revision.value.c[0],
10854 					ST_INQUIRY->inq_revision, 4);
10855 				(void) strncpy(&stp->st_serial.value.c[0],
10856 					ST_INQUIRY->inq_serial, 12);
10857 			}
10858 		}
10859 	}
10860 	return (0);
10861 }
10862 
10863 static int
10864 st_validate_tapemarks(struct scsi_tape *un, int fileno, daddr_t blkno)
10865 {
10866 	dev_t 	dev;
10867 
10868 	ASSERT(MUTEX_HELD(&un->un_sd->sd_mutex));
10869 	ASSERT(mutex_owned(ST_MUTEX));
10870 
10871 	dev = un->un_dev;
10872 
10873 	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "Restoring tape"
10874 	" position at fileno=%x, blkno=%lx....", fileno, blkno);
10875 
10876 	/*
10877 	 * Rewind ? Oh yeah, Fidelity has got the STK F/W changed
10878 	 * so as not to rewind tape on RESETS: Gee, Has life ever
10879 	 * been simple in tape land ?
10880 	 */
10881 	if (st_cmd(dev, SCMD_REWIND, 0, SYNC_CMD)) {
10882 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
10883 		"Failed to restore the last file and block position: In"
10884 		" this state, Tape will be loaded at BOT during next open");
10885 		un->un_fileno = -1;
10886 		return (1);
10887 	}
10888 
10889 	if (fileno) {
10890 		if (st_cmd(dev, SCMD_SPACE, Fmk(fileno), SYNC_CMD)) {
10891 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10892 			"Failed to restore the last file position: In this "
10893 			" state, Tape will be loaded at BOT during next open");
10894 			un->un_fileno = -1;
10895 			return (2);
10896 		}
10897 	}
10898 
10899 	if (blkno) {
10900 		if (st_cmd(dev, SCMD_SPACE, Blk(blkno), SYNC_CMD)) {
10901 			scsi_log(ST_DEVINFO, st_label, CE_WARN,
10902 			"Failed to restore the last block position: In this"
10903 			" state, tape will be loaded at BOT during next open");
10904 			un->un_fileno = -1;
10905 			return (3);
10906 		}
10907 	}
10908 
10909 	return (0);
10910 }
10911 
10912 /*
10913  * check sense key, ASC, ASCQ in order to determine if the tape needs
10914  * to be ejected
10915  */
10916 
10917 static int
10918 st_check_asc_ascq(struct scsi_tape *un)
10919 {
10920 	struct scsi_extended_sense *sensep = ST_RQSENSE;
10921 	struct tape_failure_code   *code;
10922 
10923 	for (code = st_tape_failure_code; code->key != 0xff; code++) {
10924 		if ((code->key  == sensep->es_key) &&
10925 		    (code->add_code  == sensep->es_add_code) &&
10926 		    (code->qual_code == sensep->es_qual_code))
10927 			return (1);
10928 	}
10929 	return (0);
10930 }
10931 
10932 /*
10933  * st_logpage_supported() sends a Log Sense command with
10934  * page code = 0 = Supported Log Pages Page to the device,
10935  * to see whether the page 'page' is supported.
10936  * Return values are:
10937  * -1 if the Log Sense command fails
10938  * 0 if page is not supported
10939  * 1 if page is supported
10940  */
10941 
10942 static int
10943 st_logpage_supported(dev_t dev, uchar_t page)
10944 {
10945 	uchar_t *sp, *sensep;
10946 	unsigned length;
10947 	struct uscsi_cmd *com;
10948 	int rval;
10949 	char cdb[CDB_GROUP1] = {
10950 		SCMD_LOG_SENSE_G1,
10951 		0,
10952 		SUPPORTED_LOG_PAGES_PAGE,
10953 		0,
10954 		0,
10955 		0,
10956 		0,
10957 		0,
10958 		(char)LOG_SENSE_LENGTH,
10959 		0
10960 	};
10961 
10962 	GET_SOFT_STATE(dev);
10963 	ASSERT(mutex_owned(ST_MUTEX));
10964 
10965 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
10966 	sensep = kmem_zalloc(LOG_SENSE_LENGTH, KM_SLEEP);
10967 
10968 	com->uscsi_cdb = cdb;
10969 	com->uscsi_cdblen = CDB_GROUP1;
10970 	com->uscsi_bufaddr = (caddr_t)sensep;
10971 	com->uscsi_buflen = LOG_SENSE_LENGTH;
10972 	com->uscsi_flags =
10973 		USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ | USCSI_RQENABLE;
10974 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
10975 	rval = st_ioctl_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE, UIO_SYSSPACE);
10976 	if (rval || com->uscsi_status) {
10977 		/* uscsi-command failed */
10978 		rval = -1;
10979 	} else {
10980 
10981 		sp = sensep + 3;
10982 
10983 		for (length = *sp++; length > 0; length--, sp++) {
10984 
10985 			if (*sp == page) {
10986 				rval = 1;
10987 				break;
10988 			}
10989 		}
10990 	}
10991 	kmem_free(com, sizeof (struct uscsi_cmd));
10992 	kmem_free(sensep, LOG_SENSE_LENGTH);
10993 	return (rval);
10994 }
10995 
10996 
10997 /*
10998  * st_check_clean_bit() gets the status of the tape's cleaning bit.
10999  *
11000  * If the device does support the TapeAlert log page, then the cleaning bit
11001  * information will be read from this page. Otherwise we will see if one of
11002  * ST_CLN_TYPE_1, ST_CLN_TYPE_2 or ST_CLN_TYPE_3 is set in the properties of
11003  * the device, which means, that we can get the cleaning bit information via
11004  * a RequestSense command.
11005  * If both methods of getting cleaning bit information are not supported
11006  * st_check_clean_bit() will return with 0. Otherwise st_check_clean_bit()
11007  * returns with
11008  * - MTF_TAPE_CLN_SUPPORTED if cleaning bit is not set or
11009  * - MTF_TAPE_CLN_SUPPORTED | MTF_TAPE_HEAD_DIRTY if cleaning bit is set.
11010  * If the call to st_ioctl_cmd() to do the Log Sense or the Request Sense
11011  * command fails, or if the amount of Request Sense data is not enough, then
11012  *  st_check_clean_bit() returns with -1.
11013  */
11014 
11015 static int
11016 st_check_clean_bit(dev_t dev)
11017 {
11018 	int rval = 0;
11019 
11020 	GET_SOFT_STATE(dev);
11021 
11022 	ASSERT(mutex_owned(ST_MUTEX));
11023 
11024 	if (un->un_HeadClean & TAPE_ALERT_NOT_SUPPORTED) {
11025 		return (rval);
11026 	}
11027 
11028 	if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
11029 
11030 		rval = st_logpage_supported(dev, TAPE_SEQUENTIAL_PAGE);
11031 		if (rval == 1) {
11032 
11033 			un->un_HeadClean |= TAPE_SEQUENTIAL_SUPPORTED;
11034 		}
11035 
11036 		rval = st_logpage_supported(dev, TAPE_ALERT_PAGE);
11037 		if (rval == 1) {
11038 
11039 			un->un_HeadClean |= TAPE_ALERT_SUPPORTED;
11040 		}
11041 
11042 		if (un->un_HeadClean == TAPE_ALERT_SUPPORT_UNKNOWN) {
11043 
11044 			un->un_HeadClean = TAPE_ALERT_NOT_SUPPORTED;
11045 		}
11046 	}
11047 
11048 	rval = 0;
11049 
11050 	if (un->un_HeadClean & TAPE_SEQUENTIAL_SUPPORTED) {
11051 
11052 		rval = st_check_sequential_clean_bit(dev);
11053 	}
11054 
11055 	if ((rval <= 0) && (un->un_HeadClean & TAPE_ALERT_SUPPORTED)) {
11056 
11057 		rval = st_check_alert_clean_bit(dev);
11058 	}
11059 
11060 	if ((rval <= 0) && (un->un_dp->options & ST_CLN_MASK)) {
11061 
11062 		rval = st_check_sense_clean_bit(dev);
11063 	}
11064 
11065 	if (rval < 0) {
11066 		return (rval);
11067 	}
11068 
11069 	/*
11070 	 * If found a supported means to check need to clean.
11071 	 */
11072 	if (rval & MTF_TAPE_CLN_SUPPORTED) {
11073 
11074 		/*
11075 		 * head needs to be cleaned.
11076 		 */
11077 		if (rval & MTF_TAPE_HEAD_DIRTY) {
11078 
11079 			/*
11080 			 * Print log message only first time
11081 			 * found needing cleaned.
11082 			 */
11083 			if ((un->un_HeadClean & TAPE_PREVIOUSLY_DIRTY) == 0) {
11084 
11085 				scsi_log(ST_DEVINFO, st_label, CE_WARN,
11086 				    "Periodic head cleaning required");
11087 
11088 				un->un_HeadClean |= TAPE_PREVIOUSLY_DIRTY;
11089 			}
11090 
11091 		} else {
11092 
11093 			un->un_HeadClean &= ~TAPE_PREVIOUSLY_DIRTY;
11094 		}
11095 	}
11096 
11097 	return (rval);
11098 }
11099 
11100 
11101 static int
11102 st_check_sequential_clean_bit(dev_t dev)
11103 {
11104 	int rval;
11105 	int ix;
11106 	ushort_t parameter;
11107 	struct uscsi_cmd *cmd;
11108 	struct log_sequential_page *sp;
11109 	struct log_sequential_page_parameter *prm;
11110 	char cdb[CDB_GROUP1] = {
11111 		SCMD_LOG_SENSE_G1,
11112 		0,
11113 		TAPE_SEQUENTIAL_PAGE | CURRENT_CUMULATIVE_VALUES,
11114 		0,
11115 		0,
11116 		0,
11117 		0,
11118 		(char)(sizeof (struct log_sequential_page) >> 8),
11119 		(char)(sizeof (struct log_sequential_page)),
11120 		0
11121 	};
11122 
11123 	GET_SOFT_STATE(dev);
11124 
11125 	cmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11126 	sp  = kmem_zalloc(sizeof (struct log_sequential_page), KM_SLEEP);
11127 
11128 	cmd->uscsi_flags   =
11129 		USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ | USCSI_RQENABLE;
11130 	cmd->uscsi_timeout = un->un_dp->non_motion_timeout;
11131 	cmd->uscsi_cdb	   = cdb;
11132 	cmd->uscsi_cdblen  = CDB_GROUP1;
11133 	cmd->uscsi_bufaddr = (caddr_t)sp;
11134 	cmd->uscsi_buflen  = sizeof (struct log_sequential_page);
11135 
11136 	rval = st_ioctl_cmd(dev, cmd, UIO_SYSSPACE, UIO_SYSSPACE, UIO_SYSSPACE);
11137 
11138 	if (rval || cmd->uscsi_status || cmd->uscsi_resid) {
11139 
11140 		rval = -1;
11141 
11142 	} else if (sp->log_page.code != TAPE_SEQUENTIAL_PAGE) {
11143 
11144 		rval = -1;
11145 	}
11146 
11147 	prm = &sp->param[0];
11148 
11149 	for (ix = 0; rval == 0 && ix < TAPE_SEQUENTIAL_PAGE_PARA; ix++) {
11150 
11151 		if (prm->log_param.length == 0) {
11152 			break;
11153 		}
11154 
11155 		parameter = (((prm->log_param.pc_hi << 8) & 0xff00) +
11156 			(prm->log_param.pc_lo & 0xff));
11157 
11158 		if (parameter == SEQUENTIAL_NEED_CLN) {
11159 
11160 			rval = MTF_TAPE_CLN_SUPPORTED;
11161 			if (prm->param_value[prm->log_param.length - 1]) {
11162 
11163 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11164 					    "sequential log says head dirty\n");
11165 				rval |= MTF_TAPE_HEAD_DIRTY;
11166 			}
11167 		}
11168 		prm = (struct log_sequential_page_parameter *)
11169 			&prm->param_value[prm->log_param.length];
11170 	}
11171 
11172 	kmem_free(cmd, sizeof (struct uscsi_cmd));
11173 	kmem_free(sp,  sizeof (struct log_sequential_page));
11174 
11175 	return (rval);
11176 }
11177 
11178 
11179 static int
11180 st_check_alert_clean_bit(dev_t dev)
11181 {
11182 	struct st_tape_alert *ta;
11183 	struct uscsi_cmd *com;
11184 	unsigned ix, length;
11185 	int rval;
11186 	ushort_t parameter;
11187 	char cdb[CDB_GROUP1] = {
11188 		SCMD_LOG_SENSE_G1,
11189 		0,
11190 		TAPE_ALERT_PAGE | CURRENT_THRESHOLD_VALUES,
11191 		0,
11192 		0,
11193 		0,
11194 		0,
11195 		(char)(sizeof (struct st_tape_alert) >> 8),
11196 		(char)(sizeof (struct st_tape_alert)),
11197 		0
11198 	};
11199 
11200 	GET_SOFT_STATE(dev);
11201 
11202 	com = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11203 	ta  = kmem_zalloc(sizeof (struct st_tape_alert), KM_SLEEP);
11204 
11205 	com->uscsi_cdb = cdb;
11206 	com->uscsi_cdblen = CDB_GROUP1;
11207 	com->uscsi_bufaddr = (caddr_t)ta;
11208 	com->uscsi_buflen = sizeof (struct st_tape_alert);
11209 	com->uscsi_flags =
11210 		USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ | USCSI_RQENABLE;
11211 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11212 
11213 	rval = st_ioctl_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE, UIO_SYSSPACE);
11214 
11215 	if (rval || com->uscsi_status || com->uscsi_resid) {
11216 
11217 		rval = -1; /* uscsi-command failed */
11218 
11219 	} else if (ta->log_page.code != TAPE_ALERT_PAGE) {
11220 
11221 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11222 		"Not Alert Log Page returned 0x%X\n", ta->log_page.code);
11223 		rval = -1;
11224 	}
11225 
11226 	length = (ta->log_page.length_hi << 8) + ta->log_page.length_lo;
11227 
11228 
11229 	if (length != TAPE_ALERT_PARAMETER_LENGTH) {
11230 
11231 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11232 		    "TapeAlert length %d\n", length);
11233 	}
11234 
11235 
11236 	for (ix = 0; ix < TAPE_ALERT_MAX_PARA; ix++) {
11237 
11238 		/*
11239 		 * if rval is bad before the first pass don't bother
11240 		 */
11241 		if (ix == 0 && rval != 0) {
11242 
11243 			break;
11244 		}
11245 
11246 		parameter = ((ta->param[ix].log_param.pc_hi << 8) +
11247 			ta->param[ix].log_param.pc_lo);
11248 
11249 		/*
11250 		 * check to see if current parameter is of interest.
11251 		 * CLEAN_FOR_ERRORS is vendor specific to 9840 9940 stk's.
11252 		 */
11253 		if ((parameter == CLEAN_NOW) ||
11254 		    (parameter == CLEAN_PERIODIC) ||
11255 		    ((parameter == CLEAN_FOR_ERRORS) &&
11256 		    (un->un_dp->type == ST_TYPE_STK9840))) {
11257 
11258 			rval = MTF_TAPE_CLN_SUPPORTED;
11259 
11260 			if (ta->param[ix].param_value & 1) {
11261 
11262 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11263 					    "alert_page drive needs clean %d\n",
11264 					    parameter);
11265 				un->un_HeadClean |= TAPE_ALERT_STILL_DIRTY;
11266 				rval |= MTF_TAPE_HEAD_DIRTY;
11267 			}
11268 
11269 		} else if (parameter == CLEANING_MEDIA) {
11270 
11271 			if (ta->param[ix].param_value & 1) {
11272 
11273 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11274 					    "alert_page drive was cleaned\n");
11275 				un->un_HeadClean &= ~TAPE_ALERT_STILL_DIRTY;
11276 			}
11277 		}
11278 
11279 	}
11280 
11281 	/*
11282 	 * Report it as dirty till we see it cleaned
11283 	 */
11284 	if (un->un_HeadClean & TAPE_ALERT_STILL_DIRTY) {
11285 
11286 		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11287 			    "alert_page still dirty\n");
11288 		rval |= MTF_TAPE_HEAD_DIRTY;
11289 	}
11290 
11291 	kmem_free(com, sizeof (struct uscsi_cmd));
11292 	kmem_free(ta,  sizeof (struct st_tape_alert));
11293 
11294 	return (rval);
11295 }
11296 
11297 
11298 static int
11299 st_check_sense_clean_bit(dev_t dev)
11300 {
11301 	uchar_t *sensep;
11302 	char cdb[CDB_GROUP0];
11303 	struct uscsi_cmd *com;
11304 	ushort_t byte_pos;
11305 	uchar_t bit_mask;
11306 	unsigned length;
11307 	int index;
11308 	int rval;
11309 
11310 	GET_SOFT_STATE(dev);
11311 
11312 	/*
11313 	 * Since this tape does not support Tape Alert,
11314 	 * we now try to get the cleanbit status via
11315 	 * Request Sense.
11316 	 */
11317 
11318 	if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_1) {
11319 
11320 		index = 0;
11321 
11322 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_2) {
11323 
11324 		index = 1;
11325 
11326 	} else if ((un->un_dp->options & ST_CLN_MASK) == ST_CLN_TYPE_3) {
11327 
11328 		index = 2;
11329 
11330 	} else {
11331 
11332 		return (-1);
11333 	}
11334 
11335 	byte_pos  = st_cln_bit_position[index].cln_bit_byte;
11336 	bit_mask  = st_cln_bit_position[index].cln_bit_mask;
11337 	length = byte_pos + 1;
11338 
11339 	com    = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
11340 	sensep = kmem_zalloc(length, KM_SLEEP);
11341 
11342 	cdb[0] = SCMD_REQUEST_SENSE;
11343 	cdb[1] = 0;
11344 	cdb[2] = 0;
11345 	cdb[3] = 0;
11346 	cdb[4] = (char)length;
11347 	cdb[5] = 0;
11348 
11349 	com->uscsi_cdb = cdb;
11350 	com->uscsi_cdblen = CDB_GROUP0;
11351 	com->uscsi_bufaddr = (caddr_t)sensep;
11352 	com->uscsi_buflen = length;
11353 	com->uscsi_flags =
11354 		USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ | USCSI_RQENABLE;
11355 	com->uscsi_timeout = un->un_dp->non_motion_timeout;
11356 
11357 	rval = st_ioctl_cmd(dev, com, UIO_SYSSPACE, UIO_SYSSPACE,
11358 			UIO_SYSSPACE);
11359 
11360 	if (rval || com->uscsi_status || com->uscsi_resid) {
11361 
11362 		rval = -1;
11363 
11364 	} else {
11365 
11366 		rval = MTF_TAPE_CLN_SUPPORTED;
11367 		if ((sensep[byte_pos] & bit_mask) == bit_mask) {
11368 
11369 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11370 				    "sense data says head dirty\n");
11371 			rval |= MTF_TAPE_HEAD_DIRTY;
11372 		}
11373 	}
11374 
11375 	kmem_free(com, sizeof (struct uscsi_cmd));
11376 	kmem_free(sensep, length);
11377 	return (rval);
11378 }
11379 
11380 /*
11381  * st_clear_unit_attention
11382  *
11383  *  	run test unit ready's to clear out outstanding
11384  * 	unit attentions.
11385  * 	returns zero for SUCCESS or the errno from st_cmd call
11386  */
11387 static int
11388 st_clear_unit_attentions(dev_t dev_instance, int max_trys)
11389 {
11390 	int	i    = 0;
11391 	int	rval;
11392 
11393 	do {
11394 		rval = st_cmd(dev_instance, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
11395 	} while ((rval != 0) && (rval != ENXIO) && (++i < max_trys));
11396 	return (rval);
11397 }
11398 
11399 static void
11400 st_calculate_timeouts(struct scsi_tape *un)
11401 {
11402 	if (un->un_dp->non_motion_timeout == 0) {
11403 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11404 			un->un_dp->non_motion_timeout =
11405 				st_io_time * st_long_timeout_x;
11406 		} else {
11407 			un->un_dp->non_motion_timeout = (ushort_t)st_io_time;
11408 		}
11409 	}
11410 
11411 	if (un->un_dp->io_timeout == 0) {
11412 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11413 			un->un_dp->io_timeout = st_io_time * st_long_timeout_x;
11414 		} else {
11415 			un->un_dp->io_timeout = (ushort_t)st_io_time;
11416 		}
11417 	}
11418 
11419 	if (un->un_dp->rewind_timeout == 0) {
11420 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11421 			un->un_dp->rewind_timeout =
11422 				st_space_time * st_long_timeout_x;
11423 		} else {
11424 			un->un_dp->rewind_timeout = (ushort_t)st_space_time;
11425 		}
11426 	}
11427 
11428 	if (un->un_dp->space_timeout == 0) {
11429 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11430 			un->un_dp->space_timeout =
11431 				st_space_time * st_long_timeout_x;
11432 		} else {
11433 			un->un_dp->space_timeout = (ushort_t)st_space_time;
11434 		}
11435 	}
11436 
11437 	if (un->un_dp->load_timeout == 0) {
11438 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11439 			un->un_dp->load_timeout =
11440 				st_space_time * st_long_timeout_x;
11441 		} else {
11442 			un->un_dp->load_timeout = (ushort_t)st_space_time;
11443 		}
11444 	}
11445 
11446 	if (un->un_dp->unload_timeout == 0) {
11447 		if (un->un_dp->options & ST_LONG_TIMEOUTS) {
11448 			un->un_dp->unload_timeout =
11449 				st_space_time * st_long_timeout_x;
11450 		} else {
11451 			un->un_dp->unload_timeout = (ushort_t)st_space_time;
11452 		}
11453 	}
11454 
11455 	if (un->un_dp->erase_timeout == 0) {
11456 		if (un->un_dp->options & ST_LONG_ERASE) {
11457 			un->un_dp->erase_timeout =
11458 				st_space_time * st_long_space_time_x;
11459 		} else {
11460 			un->un_dp->erase_timeout = (ushort_t)st_space_time;
11461 		}
11462 	}
11463 }
11464 
11465 #if defined(__i386) || defined(__amd64)
11466 
11467 /*
11468  * release contig_mem and wake up waiting thread, if any
11469  */
11470 static void
11471 st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp)
11472 {
11473 	mutex_enter(ST_MUTEX);
11474 
11475 	cp->cm_next = un->un_contig_mem;
11476 	un->un_contig_mem = cp;
11477 	un->un_contig_mem_available_num++;
11478 	cv_broadcast(&un->un_contig_mem_cv);
11479 
11480 	mutex_exit(ST_MUTEX);
11481 }
11482 
11483 /*
11484  * St_get_contig_mem will return a contig_mem if there is one available
11485  * in current system. Otherwise, it will try to alloc one, if the total
11486  * number of contig_mem is within st_max_contig_mem_num.
11487  * It will sleep, if allowed by caller or return NULL, if no contig_mem
11488  * is available for now.
11489  */
11490 static struct contig_mem *
11491 st_get_contig_mem(struct scsi_tape *un, size_t len, int alloc_flags)
11492 {
11493 	size_t rlen;
11494 	struct contig_mem *cp = NULL;
11495 	ddi_acc_handle_t acc_hdl;
11496 	caddr_t addr;
11497 	int (*dma_alloc_cb)() = (alloc_flags == KM_SLEEP) ?
11498 		DDI_DMA_SLEEP : DDI_DMA_DONTWAIT;
11499 
11500 	/* Try to get one available contig_mem */
11501 	mutex_enter(ST_MUTEX);
11502 	if (un->un_contig_mem_available_num > 0) {
11503 		cp = un->un_contig_mem;
11504 		un->un_contig_mem = cp->cm_next;
11505 		cp->cm_next = NULL;
11506 		un->un_contig_mem_available_num--;
11507 	} else if (un->un_contig_mem_total_num < st_max_contig_mem_num) {
11508 		/*
11509 		 * we failed to get one. we're going to
11510 		 * alloc one more contig_mem for this I/O
11511 		 */
11512 		mutex_exit(ST_MUTEX);
11513 		cp = (struct contig_mem *)
11514 		    kmem_zalloc(sizeof (struct contig_mem), alloc_flags);
11515 		if (cp == NULL) {
11516 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11517 			    "alloc contig_mem failure\n");
11518 			return (NULL); /* cannot get one */
11519 		}
11520 		mutex_enter(ST_MUTEX);
11521 		un->un_contig_mem_total_num++; /* one more available */
11522 	} else {
11523 		/*
11524 		 * we failed to get one and we're NOT allowed to
11525 		 * alloc more contig_mem
11526 		 */
11527 		if (alloc_flags == KM_SLEEP) {
11528 			while (un->un_contig_mem_available_num <= 0) {
11529 				cv_wait(&un->un_contig_mem_cv,
11530 				    ST_MUTEX);
11531 			}
11532 			cp = un->un_contig_mem;
11533 			un->un_contig_mem = cp->cm_next;
11534 			cp->cm_next = NULL;
11535 			un->un_contig_mem_available_num--;
11536 		} else {
11537 			mutex_exit(ST_MUTEX);
11538 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11539 			    "alloc contig_mem failure\n");
11540 			return (NULL); /* cannot get one */
11541 		}
11542 	}
11543 	mutex_exit(ST_MUTEX);
11544 
11545 	/* We need to check if this block of mem is big enough for this I/O */
11546 	if (cp->cm_len < len) {
11547 		/* not big enough, need to alloc a new one */
11548 		if (ddi_dma_mem_alloc(un->un_contig_mem_hdl, len, &st_acc_attr,
11549 			DDI_DMA_RDWR, dma_alloc_cb, NULL,
11550 			&addr, &rlen, &acc_hdl) != DDI_SUCCESS) {
11551 			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11552 			    "alloc contig_mem failure: not enough mem\n");
11553 			st_release_contig_mem(un, cp);
11554 			return (NULL);
11555 		}
11556 		if (cp->cm_addr) {
11557 			/* release previous one before we attach new one */
11558 			ddi_dma_mem_free(&cp->cm_acc_hdl);
11559 		}
11560 		/* attach new mem to this cp */
11561 		cp->cm_addr = addr;
11562 		cp->cm_acc_hdl = acc_hdl;
11563 		cp->cm_len = len;
11564 
11565 		if (cp->cm_bp == NULL) {
11566 			cp->cm_bp = getrbuf(alloc_flags);
11567 			if (cp->cm_bp == NULL) {
11568 				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
11569 				    "alloc contig_mem failure:"
11570 				    "no enough mem for bp\n");
11571 				st_release_contig_mem(un, cp);
11572 				return (NULL);
11573 			}
11574 		}
11575 	}
11576 
11577 	/* init bp attached to this cp */
11578 	bioinit(cp->cm_bp);
11579 	cp->cm_bp->b_un.b_addr = cp->cm_addr;
11580 	cp->cm_bp->b_private = (void *)cp;
11581 	return (cp);
11582 }
11583 
11584 /*
11585  * this is the biodone func for the bp used in big block I/O
11586  */
11587 static int
11588 st_bigblk_xfer_done(struct buf *bp)
11589 {
11590 	struct contig_mem *cp;
11591 	struct buf *orig_bp;
11592 	int remapped = 0;
11593 	int ioerr;
11594 	struct scsi_tape *un;
11595 
11596 	/* sanity check */
11597 	if (bp == NULL) {
11598 		return (DDI_FAILURE);
11599 	}
11600 
11601 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
11602 	if (un == NULL) {
11603 		return (DDI_FAILURE);
11604 	}
11605 
11606 	cp = (struct contig_mem *)bp->b_private;
11607 	orig_bp = cp->cm_bp; /* get back the bp we have replaced */
11608 	cp->cm_bp = bp;
11609 
11610 	/* special handling for special I/O */
11611 	if (cp->cm_use_sbuf) {
11612 		ASSERT(un->un_sbuf_busy);
11613 		un->un_sbufp = orig_bp;
11614 		cp->cm_use_sbuf = 0;
11615 	}
11616 
11617 	orig_bp->b_resid = bp->b_resid;
11618 	ioerr = geterror(bp);
11619 	if (ioerr != 0) {
11620 		bioerror(orig_bp, ioerr);
11621 	} else if (orig_bp->b_flags & B_READ) {
11622 		/* copy data back to original bp */
11623 		if (orig_bp->b_flags & (B_PHYS | B_PAGEIO)) {
11624 			bp_mapin(orig_bp);
11625 			remapped = 1;
11626 		}
11627 		bcopy(bp->b_un.b_addr, orig_bp->b_un.b_addr,
11628 			bp->b_bcount - bp->b_resid);
11629 		if (remapped)
11630 			bp_mapout(orig_bp);
11631 	}
11632 
11633 	st_release_contig_mem(un, cp);
11634 
11635 	biodone(orig_bp);
11636 
11637 	return (DDI_SUCCESS);
11638 }
11639 
11640 /*
11641  * We use this func to replace original bp that may not be able to do I/O
11642  * in big block size with one that can
11643  */
11644 static struct buf *
11645 st_get_bigblk_bp(struct buf *bp)
11646 {
11647 	struct contig_mem *cp;
11648 	struct scsi_tape *un;
11649 	struct buf *cont_bp;
11650 	int remapped = 0;
11651 
11652 	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
11653 	if (un == NULL) {
11654 		return (bp);
11655 	}
11656 
11657 	/* try to get one contig_mem */
11658 	cp = st_get_contig_mem(un, bp->b_bcount, KM_SLEEP);
11659 	if (!cp) {
11660 		scsi_log(ST_DEVINFO, st_label, CE_WARN,
11661 			"Cannot alloc contig buf for I/O for %lu blk size",
11662 			bp->b_bcount);
11663 		return (bp);
11664 	}
11665 	cont_bp = cp->cm_bp;
11666 	cp->cm_bp = bp;
11667 
11668 	/* make sure that we "are" using un_sbufp for special I/O */
11669 	if (bp == un->un_sbufp) {
11670 		ASSERT(un->un_sbuf_busy);
11671 		un->un_sbufp = cont_bp;
11672 		cp->cm_use_sbuf = 1;
11673 	}
11674 
11675 	/* clone bp */
11676 	cont_bp->b_bcount = bp->b_bcount;
11677 	cont_bp->b_resid = bp->b_resid;
11678 	cont_bp->b_iodone = st_bigblk_xfer_done;
11679 	cont_bp->b_file = bp->b_file;
11680 	cont_bp->b_offset = bp->b_offset;
11681 	cont_bp->b_dip = bp->b_dip;
11682 	cont_bp->b_error = 0;
11683 	cont_bp->b_proc = NULL;
11684 	cont_bp->b_flags = bp->b_flags & ~(B_PAGEIO | B_PHYS | B_SHADOW);
11685 	cont_bp->b_shadow = NULL;
11686 	cont_bp->b_pages = NULL;
11687 	cont_bp->b_edev = bp->b_edev;
11688 	cont_bp->b_dev = bp->b_dev;
11689 	cont_bp->b_lblkno = bp->b_lblkno;
11690 	cont_bp->b_forw = bp->b_forw;
11691 	cont_bp->b_back = bp->b_back;
11692 	cont_bp->av_forw = bp->av_forw;
11693 	cont_bp->av_back = bp->av_back;
11694 	cont_bp->b_bufsize = bp->b_bufsize;
11695 
11696 	/* get data in original bp */
11697 	if (bp->b_flags & B_WRITE) {
11698 		if (bp->b_flags & (B_PHYS | B_PAGEIO)) {
11699 			bp_mapin(bp);
11700 			remapped = 1;
11701 		}
11702 		bcopy(bp->b_un.b_addr, cont_bp->b_un.b_addr, bp->b_bcount);
11703 		if (remapped)
11704 			bp_mapout(bp);
11705 	}
11706 
11707 	return (cont_bp);
11708 }
11709 #endif
11710