1/*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21
22/*
23 *  Copyright (c) 1990, 2010, Oracle and/or its affiliates. All rights reserved.
24 *  Copyright (c) 2011 Bayard G. Bell. All rights reserved.
25 */
26
27/*
28 * SCSI	 SCSA-compliant and not-so-DDI-compliant Tape Driver
29 */
30
31#if defined(lint) && !defined(DEBUG)
32#define	DEBUG	1
33#endif
34
35#include <sys/modctl.h>
36#include <sys/scsi/scsi.h>
37#include <sys/mtio.h>
38#include <sys/scsi/targets/stdef.h>
39#include <sys/file.h>
40#include <sys/kstat.h>
41#include <sys/ddidmareq.h>
42#include <sys/ddi.h>
43#include <sys/sunddi.h>
44#include <sys/byteorder.h>
45
46#define	IOSP	KSTAT_IO_PTR(un->un_stats)
47/*
48 * stats maintained only for reads/writes as commands
49 * like rewind etc skew the wait/busy times
50 */
51#define	IS_RW(bp)	((bp)->b_bcount > 0)
52#define	ST_DO_KSTATS(bp, kstat_function) \
53	if ((bp != un->un_sbufp) && un->un_stats && IS_RW(bp)) { \
54		kstat_function(IOSP); \
55	}
56
57#define	ST_DO_ERRSTATS(un, x)  \
58	if (un->un_errstats) { \
59		struct st_errstats *stp; \
60		stp = (struct st_errstats *)un->un_errstats->ks_data; \
61		stp->x.value.ul++; \
62	}
63
64#define	FILL_SCSI1_LUN(devp, pkt)					\
65	if ((devp)->sd_inq->inq_ansi == 0x1) {				\
66		int _lun;						\
67		_lun = ddi_prop_get_int(DDI_DEV_T_ANY, (devp)->sd_dev,	\
68		    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);		\
69		if (_lun > 0) {						\
70			((union scsi_cdb *)(pkt)->pkt_cdbp)->scc_lun =	\
71			    _lun;					\
72		}							\
73	}
74
75/*
76 * get an available contig mem header, cp.
77 * when big_enough is true, we will return NULL, if no big enough
78 * contig mem is found.
79 * when big_enough is false, we will try to find cp containing big
80 * enough contig mem. if not found, we will ruturn the last cp available.
81 *
82 * used by st_get_contig_mem()
83 */
84#define	ST_GET_CONTIG_MEM_HEAD(un, cp, len, big_enough) {		\
85	struct contig_mem *tmp_cp = NULL;				\
86	for ((cp) = (un)->un_contig_mem;				\
87	    (cp) != NULL;						\
88	    tmp_cp = (cp), (cp) = (cp)->cm_next) {			\
89		if (((cp)->cm_len >= (len)) ||				\
90		    (!(big_enough) && ((cp)->cm_next == NULL))) {	\
91			if (tmp_cp == NULL) {				\
92				(un)->un_contig_mem = (cp)->cm_next;	\
93			} else {					\
94				tmp_cp->cm_next = (cp)->cm_next;	\
95			}						\
96			(cp)->cm_next = NULL;				\
97			(un)->un_contig_mem_available_num--;		\
98			break;						\
99		}							\
100	}								\
101}
102
103#define	ST_NUM_MEMBERS(array)	(sizeof (array) / sizeof (array[0]))
104#define	COPY_POS(dest, source) bcopy(source, dest, sizeof (tapepos_t))
105#define	ISALNUM(byte) \
106	(((byte) >= 'a' && (byte) <= 'z') || \
107	((byte) >= 'A' && (byte) <= 'Z') || \
108	((byte) >= '0' && (byte) <= '9'))
109
110#define	ONE_K	1024
111
112#define	MAX_SPACE_CNT(cnt) if (cnt >= 0) { \
113		if (cnt > MIN(SP_CNT_MASK, INT32_MAX)) \
114			return (EINVAL); \
115	} else { \
116		if (-(cnt) > MIN(SP_CNT_MASK, INT32_MAX)) \
117			return (EINVAL); \
118	} \
119
120/*
121 * Global External Data Definitions
122 */
123extern struct scsi_key_strings scsi_cmds[];
124extern uchar_t	scsi_cdb_size[];
125
126/*
127 * Local Static Data
128 */
129static void *st_state;
130static char *const st_label = "st";
131static volatile int st_recov_sz = sizeof (recov_info);
132static const char mp_misconf[] = {
133	"St Tape is misconfigured, MPxIO enabled and "
134	"tape-command-recovery-disable set in st.conf\n"
135};
136
137#ifdef	__x86
138/*
139 * We need to use below DMA attr to alloc physically contiguous
140 * memory to do I/O in big block size
141 */
142static ddi_dma_attr_t st_contig_mem_dma_attr = {
143	DMA_ATTR_V0,    /* version number */
144	0x0,		/* lowest usable address */
145	0xFFFFFFFFull,  /* high DMA address range */
146	0xFFFFFFFFull,  /* DMA counter register */
147	1,		/* DMA address alignment */
148	1,		/* DMA burstsizes */
149	1,		/* min effective DMA size */
150	0xFFFFFFFFull,  /* max DMA xfer size */
151	0xFFFFFFFFull,  /* segment boundary */
152	1,		/* s/g list length */
153	1,		/* granularity of device */
154	0		/* DMA transfer flags */
155};
156
157static ddi_device_acc_attr_t st_acc_attr = {
158	DDI_DEVICE_ATTR_V0,
159	DDI_NEVERSWAP_ACC,
160	DDI_STRICTORDER_ACC
161};
162
163/* set limitation for the number of contig_mem */
164static int st_max_contig_mem_num = ST_MAX_CONTIG_MEM_NUM;
165#endif
166
167/*
168 * Tunable parameters
169 *
170 * DISCLAIMER
171 * ----------
172 * These parameters are intended for use only in system testing; if you use
173 * them in production systems, you do so at your own risk. Altering any
174 * variable not listed below may cause unpredictable system behavior.
175 *
176 * st_check_media_time
177 *
178 *   Three second state check
179 *
180 * st_allow_large_xfer
181 *
182 *   Gated with ST_NO_RECSIZE_LIMIT
183 *
184 *   0 - Transfers larger than 64KB will not be allowed
185 *       regardless of the setting of ST_NO_RECSIZE_LIMIT
186 *   1 - Transfers larger than 64KB will be allowed
187 *       if ST_NO_RECSIZE_LIMIT is TRUE for the drive
188 *
189 * st_report_soft_errors_on_close
190 *
191 *  Gated with ST_SOFT_ERROR_REPORTING
192 *
193 *  0 - Errors will not be reported on close regardless
194 *      of the setting of ST_SOFT_ERROR_REPORTING
195 *
196 *  1 - Errors will be reported on close if
197 *      ST_SOFT_ERROR_REPORTING is TRUE for the drive
198 */
199static int st_selection_retry_count = ST_SEL_RETRY_COUNT;
200static int st_retry_count	= ST_RETRY_COUNT;
201
202static int st_io_time		= ST_IO_TIME;
203static int st_long_timeout_x	= ST_LONG_TIMEOUT_X;
204
205static int st_space_time	= ST_SPACE_TIME;
206static int st_long_space_time_x	= ST_LONG_SPACE_TIME_X;
207
208static int st_error_level	= SCSI_ERR_RETRYABLE;
209static int st_check_media_time	= 3000000;	/* 3 Second State Check */
210
211static int st_max_throttle	= ST_MAX_THROTTLE;
212
213static clock_t st_wait_cmds_complete = ST_WAIT_CMDS_COMPLETE;
214
215static int st_allow_large_xfer = 1;
216static int st_report_soft_errors_on_close = 1;
217
218/*
219 * End of tunable parameters list
220 */
221
222
223
224/*
225 * Asynchronous I/O and persistent errors, refer to PSARC/1995/228
226 *
227 * Asynchronous I/O's main offering is that it is a non-blocking way to do
228 * reads and writes.  The driver will queue up all the requests it gets and
229 * have them ready to transport to the HBA.  Unfortunately, we cannot always
230 * just ship the I/O requests to the HBA, as there errors and exceptions
231 * that may happen when we don't want the HBA to continue.  Therein comes
232 * the flush-on-errors capability.  If the HBA supports it, then st will
233 * send in st_max_throttle I/O requests at the same time.
234 *
235 * Persistent errors : This was also reasonably simple.  In the interrupt
236 * routines, if there was an error or exception (FM, LEOT, media error,
237 * transport error), the persistent error bits are set and shuts everything
238 * down, but setting the throttle to zero.  If we hit and exception in the
239 * HBA, and flush-on-errors were set, we wait for all outstanding I/O's to
240 * come back (with CMD_ABORTED), then flush all bp's in the wait queue with
241 * the appropriate error, and this will preserve order. Of course, depending
242 * on the exception we have to show a zero read or write before we show
243 * errors back to the application.
244 */
245
246extern const int st_ndrivetypes;	/* defined in st_conf.c */
247extern const struct st_drivetype st_drivetypes[];
248extern const char st_conf_version[];
249
250#ifdef STDEBUG
251static int st_soft_error_report_debug = 0;
252volatile int st_debug = 0;
253static volatile dev_info_t *st_lastdev;
254static kmutex_t st_debug_mutex;
255#endif
256
257#define	ST_MT02_NAME	"Emulex  MT02 QIC-11/24  "
258
259static const struct vid_drivetype {
260	char	*vid;
261	char	type;
262} st_vid_dt[] = {
263	{"LTO-CVE ",	MT_LTO},
264	{"QUANTUM ",    MT_ISDLT},
265	{"SONY    ",    MT_ISAIT},
266	{"STK     ",	MT_ISSTK9840}
267};
268
269static const struct driver_minor_data {
270	char	*name;
271	int	minor;
272} st_minor_data[] = {
273	/*
274	 * The top 4 entries are for the default densities,
275	 * don't alter their position.
276	 */
277	{"",	0},
278	{"n",	MT_NOREWIND},
279	{"b",	MT_BSD},
280	{"bn",	MT_NOREWIND | MT_BSD},
281	{"l",	MT_DENSITY1},
282	{"m",	MT_DENSITY2},
283	{"h",	MT_DENSITY3},
284	{"c",	MT_DENSITY4},
285	{"u",	MT_DENSITY4},
286	{"ln",	MT_DENSITY1 | MT_NOREWIND},
287	{"mn",	MT_DENSITY2 | MT_NOREWIND},
288	{"hn",	MT_DENSITY3 | MT_NOREWIND},
289	{"cn",	MT_DENSITY4 | MT_NOREWIND},
290	{"un",	MT_DENSITY4 | MT_NOREWIND},
291	{"lb",	MT_DENSITY1 | MT_BSD},
292	{"mb",	MT_DENSITY2 | MT_BSD},
293	{"hb",	MT_DENSITY3 | MT_BSD},
294	{"cb",	MT_DENSITY4 | MT_BSD},
295	{"ub",	MT_DENSITY4 | MT_BSD},
296	{"lbn",	MT_DENSITY1 | MT_NOREWIND | MT_BSD},
297	{"mbn",	MT_DENSITY2 | MT_NOREWIND | MT_BSD},
298	{"hbn",	MT_DENSITY3 | MT_NOREWIND | MT_BSD},
299	{"cbn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD},
300	{"ubn",	MT_DENSITY4 | MT_NOREWIND | MT_BSD}
301};
302
303/* strings used in many debug and warning messages */
304static const char wr_str[]  = "write";
305static const char rd_str[]  = "read";
306static const char wrg_str[] = "writing";
307static const char rdg_str[] = "reading";
308static const char *space_strs[] = {
309	"records",
310	"filemarks",
311	"sequential filemarks",
312	"eod",
313	"setmarks",
314	"sequential setmarks",
315	"Reserved",
316	"Reserved"
317};
318static const char *load_strs[] = {
319	"unload",		/* LD_UNLOAD		0 */
320	"load",			/* LD_LOAD		1 */
321	"retension",		/* LD_RETEN		2 */
322	"load reten",		/* LD_LOAD | LD_RETEN	3 */
323	"eod",			/* LD_EOT		4 */
324	"load EOD",		/* LD_LOAD | LD_EOT	5 */
325	"reten EOD",		/* LD_RETEN | LD_EOT	6 */
326	"load reten EOD"	/* LD_LOAD|LD_RETEN|LD_EOT 7 */
327	"hold",			/* LD_HOLD		8 */
328	"load and hold"		/* LD_LOAD | LD_HOLD	9 */
329};
330
331static const char *errstatenames[] = {
332	"COMMAND_DONE",
333	"COMMAND_DONE_ERROR",
334	"COMMAND_DONE_ERROR_RECOVERED",
335	"QUE_COMMAND",
336	"QUE_BUSY_COMMAND",
337	"QUE_SENSE",
338	"JUST_RETURN",
339	"COMMAND_DONE_EACCES",
340	"QUE_LAST_COMMAND",
341	"COMMAND_TIMEOUT",
342	"PATH_FAILED",
343	"DEVICE_RESET",
344	"DEVICE_TAMPER",
345	"ATTEMPT_RETRY"
346};
347
348const char *bogusID = "Unknown Media ID";
349
350/* default density offsets in the table above */
351#define	DEF_BLANK	0
352#define	DEF_NOREWIND	1
353#define	DEF_BSD		2
354#define	DEF_BSD_NR	3
355
356/* Sense Key, ASC/ASCQ for which tape ejection is needed */
357
358static struct tape_failure_code {
359	uchar_t key;
360	uchar_t add_code;
361	uchar_t qual_code;
362} st_tape_failure_code[] = {
363	{ KEY_HARDWARE_ERROR, 0x15, 0x01},
364	{ KEY_HARDWARE_ERROR, 0x44, 0x00},
365	{ KEY_HARDWARE_ERROR, 0x53, 0x00},
366	{ KEY_HARDWARE_ERROR, 0x53, 0x01},
367	{ KEY_NOT_READY, 0x53, 0x00},
368	{ 0xff}
369};
370
371/*  clean bit position and mask */
372
373static struct cln_bit_position {
374	ushort_t cln_bit_byte;
375	uchar_t cln_bit_mask;
376} st_cln_bit_position[] = {
377	{ 21, 0x08},
378	{ 70, 0xc0},
379	{ 18, 0x81}  /* 80 bit indicates in bit mode, 1 bit clean light is on */
380};
381
382/*
383 * architecture dependent allocation restrictions. For x86, we'll set
384 * dma_attr_addr_hi to st_max_phys_addr and dma_attr_sgllen to
385 * st_sgl_size during _init().
386 */
387#if defined(__sparc)
388static ddi_dma_attr_t st_alloc_attr = {
389	DMA_ATTR_V0,	/* version number */
390	0x0,		/* lowest usable address */
391	0xFFFFFFFFull,	/* high DMA address range */
392	0xFFFFFFFFull,	/* DMA counter register */
393	1,		/* DMA address alignment */
394	1,		/* DMA burstsizes */
395	1,		/* min effective DMA size */
396	0xFFFFFFFFull,	/* max DMA xfer size */
397	0xFFFFFFFFull,	/* segment boundary */
398	1,		/* s/g list length */
399	512,		/* granularity of device */
400	0		/* DMA transfer flags */
401};
402#elif defined(__x86)
403static ddi_dma_attr_t st_alloc_attr = {
404	DMA_ATTR_V0,	/* version number */
405	0x0,		/* lowest usable address */
406	0x0,		/* high DMA address range [set in _init()] */
407	0xFFFFull,	/* DMA counter register */
408	512,		/* DMA address alignment */
409	1,		/* DMA burstsizes */
410	1,		/* min effective DMA size */
411	0xFFFFFFFFull,	/* max DMA xfer size */
412	0xFFFFFFFFull,  /* segment boundary */
413	0,		/* s/g list length */
414	512,		/* granularity of device [set in _init()] */
415	0		/* DMA transfer flags */
416};
417uint64_t st_max_phys_addr = 0xFFFFFFFFull;
418int st_sgl_size = 0xF;
419
420#endif
421
422/*
423 * Configuration Data:
424 *
425 * Device driver ops vector
426 */
427static int st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
428static int st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
429static int st_read(dev_t  dev,  struct   uio   *uio_p,   cred_t *cred_p);
430static int st_write(dev_t  dev,  struct  uio   *uio_p,   cred_t *cred_p);
431static int st_open(dev_t  *devp,  int  flag,  int  otyp,  cred_t *cred_p);
432static int st_close(dev_t  dev,  int  flag,  int  otyp,  cred_t *cred_p);
433static int st_strategy(struct buf *bp);
434static int st_queued_strategy(buf_t *bp);
435static int st_ioctl(dev_t dev, int cmd, intptr_t arg, int  flag,
436	cred_t *cred_p, int *rval_p);
437extern int nulldev(), nodev();
438
439static struct cb_ops st_cb_ops = {
440	st_open,		/* open */
441	st_close,		/* close */
442	st_queued_strategy,	/* strategy Not Block device but async checks */
443	nodev,			/* print */
444	nodev,			/* dump */
445	st_read,		/* read */
446	st_write,		/* write */
447	st_ioctl,		/* ioctl */
448	nodev,			/* devmap */
449	nodev,			/* mmap */
450	nodev,			/* segmap */
451	nochpoll,		/* poll */
452	ddi_prop_op,		/* cb_prop_op */
453	0,			/* streamtab  */
454	D_64BIT | D_MP | D_NEW | D_HOTPLUG |
455	D_OPEN_RETURNS_EINTR,	/* cb_flag */
456	CB_REV,			/* cb_rev */
457	st_aread,		/* async I/O read entry point */
458	st_awrite		/* async I/O write entry point */
459
460};
461
462static int st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
463		void **result);
464static int st_probe(dev_info_t *dev);
465static int st_attach(dev_info_t *dev, ddi_attach_cmd_t cmd);
466static int st_detach(dev_info_t *dev, ddi_detach_cmd_t cmd);
467
468static struct dev_ops st_ops = {
469	DEVO_REV,		/* devo_rev, */
470	0,			/* refcnt  */
471	st_info,		/* info */
472	nulldev,		/* identify */
473	st_probe,		/* probe */
474	st_attach,		/* attach */
475	st_detach,		/* detach */
476	nodev,			/* reset */
477	&st_cb_ops,		/* driver operations */
478	(struct bus_ops *)0,	/* bus operations */
479	nulldev,		/* power */
480	ddi_quiesce_not_needed,	/* devo_quiesce */
481};
482
483/*
484 * Local Function Declarations
485 */
486static char *st_print_scsi_cmd(char cmd);
487static void st_print_cdb(dev_info_t *dip, char *label, uint_t level,
488    char *title, char *cdb);
489static void st_clean_print(dev_info_t *dev, char *label, uint_t level,
490    char *title, char *data, int len);
491static int st_doattach(struct scsi_device *devp, int (*canwait)());
492static void st_known_tape_type(struct scsi_tape *un);
493static int st_get_conf_from_st_dot_conf(struct scsi_tape *, char *,
494    struct st_drivetype *);
495static int st_get_conf_from_st_conf_dot_c(struct scsi_tape *, char *,
496    struct st_drivetype *);
497static int st_get_conf_from_tape_drive(struct scsi_tape *, char *,
498    struct st_drivetype *);
499static int st_get_densities_from_tape_drive(struct scsi_tape *,
500    struct st_drivetype *);
501static int st_get_timeout_values_from_tape_drive(struct scsi_tape *,
502    struct st_drivetype *);
503static int st_get_timeouts_value(struct scsi_tape *, uchar_t, ushort_t *,
504    ushort_t);
505static int st_get_default_conf(struct scsi_tape *, char *,
506    struct st_drivetype *);
507static int st_rw(dev_t dev, struct uio *uio, int flag);
508static int st_arw(dev_t dev, struct aio_req *aio, int flag);
509static int st_find_eod(struct scsi_tape *un);
510static int st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag);
511static int st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *, int flag);
512static int st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag);
513static int st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag);
514static int st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop);
515static void st_start(struct scsi_tape *un);
516static int st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
517    clock_t timeout_interval, int queued);
518static int st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
519    clock_t timeout_interval);
520static int st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp);
521static void st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp);
522static void st_init(struct scsi_tape *un);
523static void st_make_cmd(struct scsi_tape *un, struct buf *bp,
524    int (*func)(caddr_t));
525static void st_make_uscsi_cmd(struct scsi_tape *, struct uscsi_cmd *,
526    struct buf *bp, int (*func)(caddr_t));
527static void st_intr(struct scsi_pkt *pkt);
528static void st_set_state(struct scsi_tape *un, buf_t *bp);
529static void st_test_append(struct buf *bp);
530static int st_runout(caddr_t);
531static int st_cmd(struct scsi_tape *un, int com, int64_t count, int wait);
532static int st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com,
533    int64_t count);
534static int st_set_compression(struct scsi_tape *un);
535static int st_write_fm(dev_t dev, int wfm);
536static int st_determine_generic(struct scsi_tape *un);
537static int st_determine_density(struct scsi_tape *un, int rw);
538static int st_get_density(struct scsi_tape *un);
539static int st_set_density(struct scsi_tape *un);
540static int st_loadtape(struct scsi_tape *un);
541static int st_modesense(struct scsi_tape *un);
542static int st_modeselect(struct scsi_tape *un);
543static errstate st_handle_incomplete(struct scsi_tape *un, struct buf *bp);
544static int st_wrongtapetype(struct scsi_tape *un);
545static errstate st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt);
546static errstate st_handle_sense(struct scsi_tape *un, struct buf *bp,
547    tapepos_t *);
548static errstate st_handle_autosense(struct scsi_tape *un, struct buf *bp,
549    tapepos_t *);
550static int st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag);
551static void st_update_error_stack(struct scsi_tape *un, struct scsi_pkt *pkt,
552    struct scsi_arq_status *cmd);
553static void st_empty_error_stack(struct scsi_tape *un);
554static errstate st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
555    struct scsi_arq_status *, tapepos_t *);
556static int st_report_soft_errors(dev_t dev, int flag);
557static void st_delayed_cv_broadcast(void *arg);
558static int st_check_media(dev_t dev, enum mtio_state state);
559static int st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
560static void st_intr_restart(void *arg);
561static void st_start_restart(void *arg);
562static int st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
563    struct seq_mode *page_data, int page_size);
564static int st_change_block_size(struct scsi_tape *un, uint32_t nblksz);
565static int st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
566    struct seq_mode *page_data, int page_size);
567static int st_read_block_limits(struct scsi_tape *un,
568    struct read_blklim *read_blk);
569static int st_report_density_support(struct scsi_tape *un,
570    uchar_t *density_data, size_t buflen);
571static int st_report_supported_operation(struct scsi_tape *un,
572    uchar_t *oper_data, uchar_t option_code, ushort_t service_action);
573static int st_tape_init(struct scsi_tape *un);
574static void st_flush(struct scsi_tape *un);
575static void st_set_pe_errno(struct scsi_tape *un);
576static void st_hba_unflush(struct scsi_tape *un);
577static void st_turn_pe_on(struct scsi_tape *un);
578static void st_turn_pe_off(struct scsi_tape *un);
579static void st_set_pe_flag(struct scsi_tape *un);
580static void st_clear_pe(struct scsi_tape *un);
581static void st_wait_for_io(struct scsi_tape *un);
582static int st_set_devconfig_page(struct scsi_tape *un, int compression_on);
583static int st_set_datacomp_page(struct scsi_tape *un, int compression_on);
584static int st_reserve_release(struct scsi_tape *un, int command, ubufunc_t ubf);
585static int st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb);
586static int st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd,
587    int count);
588static int st_take_ownership(struct scsi_tape *un, ubufunc_t ubf);
589static int st_check_asc_ascq(struct scsi_tape *un);
590static int st_check_clean_bit(struct scsi_tape *un);
591static int st_check_alert_flags(struct scsi_tape *un);
592static int st_check_sequential_clean_bit(struct scsi_tape *un);
593static int st_check_sense_clean_bit(struct scsi_tape *un);
594static int st_clear_unit_attentions(dev_t dev_instance, int max_trys);
595static void st_calculate_timeouts(struct scsi_tape *un);
596static writablity st_is_drive_worm(struct scsi_tape *un);
597static int st_read_attributes(struct scsi_tape *un, uint16_t attribute,
598    void *buf, size_t size, ubufunc_t bufunc);
599static int st_get_special_inquiry(struct scsi_tape *un, uchar_t size,
600    caddr_t dest, uchar_t page);
601static int st_update_block_pos(struct scsi_tape *un, bufunc_t bf,
602    int post_space);
603static int st_interpret_read_pos(struct scsi_tape const *un, tapepos_t *dest,
604    read_p_types type, size_t data_sz, const caddr_t responce, int post_space);
605static int st_get_read_pos(struct scsi_tape *un, buf_t *bp);
606static int st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf,
607    tapepos_t *pos, uint64_t lblk, uchar_t partition);
608static int st_mtfsf_ioctl(struct scsi_tape *un, int64_t files);
609static int st_mtfsr_ioctl(struct scsi_tape *un, int64_t count);
610static int st_mtbsf_ioctl(struct scsi_tape *un, int64_t files);
611static int st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count);
612static int st_mtbsr_ioctl(struct scsi_tape *un, int64_t num);
613static int st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt);
614static int st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt);
615static int st_backward_space_files(struct scsi_tape *un, int64_t count,
616    int infront);
617static int st_forward_space_files(struct scsi_tape *un, int64_t files);
618static int st_scenic_route_to_begining_of_file(struct scsi_tape *un,
619    int32_t fileno);
620static int st_space_to_begining_of_file(struct scsi_tape *un);
621static int st_space_records(struct scsi_tape *un, int64_t records);
622static int st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc);
623static errstate st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
624    errstate onentry);
625static void st_recover(void *arg);
626static void st_recov_cb(struct scsi_pkt *pkt);
627static int st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait);
628static int st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
629    int flag);
630static void st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
631    struct scsi_pkt *cmd);
632static int st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf);
633static int st_test_path_to_device(struct scsi_tape *un);
634static int st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
635    read_pos_data_t *raw);
636static int st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
637    read_pos_data_t *raw);
638static int st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
639    cmd_attribute const * cmd_att, tapepos_t *read);
640static errstate st_recover_reissue_pkt(struct scsi_tape *us,
641    struct scsi_pkt *pkt);
642static int st_transport(struct scsi_tape *un, struct scsi_pkt *pkt);
643static buf_t *st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp);
644static void st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp);
645static int st_reset(struct scsi_tape *un, int reset_type);
646static void st_reset_notification(caddr_t arg);
647static const cmd_attribute *st_lookup_cmd_attribute(unsigned char cmd);
648
649static int st_set_target_TLR_mode(struct scsi_tape *un, ubufunc_t ubf);
650static int st_make_sure_mode_data_is_correct(struct scsi_tape *un,
651    ubufunc_t ubf);
652
653#ifdef	__x86
654/*
655 * routines for I/O in big block size
656 */
657static void st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp);
658static struct contig_mem *st_get_contig_mem(struct scsi_tape *un, size_t len,
659    int alloc_flags);
660static int st_bigblk_xfer_done(struct buf *bp);
661static struct buf *st_get_bigblk_bp(struct buf *bp);
662#endif
663static void st_print_position(dev_info_t *dev, char *label, uint_t level,
664    const char *comment, tapepos_t *pos);
665
666/*
667 * error statistics create/update functions
668 */
669static int st_create_errstats(struct scsi_tape *, int);
670static int st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf,
671    tapepos_t *pos);
672
673#ifdef STDEBUG
674static void st_debug_cmds(struct scsi_tape *un, int com, int count, int wait);
675#endif /* STDEBUG */
676static char *st_dev_name(dev_t dev);
677
678#if !defined(lint)
679_NOTE(SCHEME_PROTECTS_DATA("unique per pkt",
680    scsi_pkt buf uio scsi_cdb uscsi_cmd))
681_NOTE(SCHEME_PROTECTS_DATA("unique per pkt", scsi_extended_sense scsi_status))
682_NOTE(SCHEME_PROTECTS_DATA("unique per pkt", recov_info))
683_NOTE(SCHEME_PROTECTS_DATA("stable data", scsi_device))
684_NOTE(DATA_READABLE_WITHOUT_LOCK(st_drivetype scsi_address))
685#endif
686
687/*
688 * autoconfiguration routines.
689 */
690
691static struct modldrv modldrv = {
692	&mod_driverops,		/* Type of module. This one is a driver */
693	"SCSI tape Driver",	/* Name of the module. */
694	&st_ops			/* driver ops */
695};
696
697static struct modlinkage modlinkage = {
698	MODREV_1, &modldrv, NULL
699};
700
701/*
702 * Notes on Post Reset Behavior in the tape driver:
703 *
704 * When the tape drive is opened, the driver  attempts  to make sure that
705 * the tape head is positioned exactly where it was left when it was last
706 * closed  provided  the  medium  is not  changed.  If the tape  drive is
707 * opened in O_NDELAY mode, the repositioning  (if necessary for any loss
708 * of position due to reset) will happen when the first tape operation or
709 * I/O occurs.  The repositioning (if required) may not be possible under
710 * certain situations such as when the device firmware not able to report
711 * the medium  change in the REQUEST  SENSE data  because of a reset or a
712 * misbehaving  bus  not  allowing  the  reposition  to  happen.  In such
713 * extraordinary  situations, where the driver fails to position the head
714 * at its  original  position,  it will fail the open the first  time, to
715 * save the applications from overwriting the data.  All further attempts
716 * to open the tape device will result in the driver  attempting  to load
717 * the  tape at BOT  (beginning  of  tape).  Also a  warning  message  to
718 * indicate  that further  attempts to open the tape device may result in
719 * the tape being  loaded at BOT will be printed on the  console.  If the
720 * tape  device is opened  in  O_NDELAY  mode,  failure  to  restore  the
721 * original tape head  position,  will result in the failure of the first
722 * tape  operation  or I/O,  Further,  the  driver  will  invalidate  its
723 * internal tape position  which will  necessitate  the  applications  to
724 * validate the position by using either a tape  positioning  ioctl (such
725 * as MTREW) or closing and reopening the tape device.
726 *
727 */
728
729int
730_init(void)
731{
732	int e;
733
734	if (((e = ddi_soft_state_init(&st_state,
735	    sizeof (struct scsi_tape), ST_MAXUNIT)) != 0)) {
736		return (e);
737	}
738
739	if ((e = mod_install(&modlinkage)) != 0) {
740		ddi_soft_state_fini(&st_state);
741	} else {
742#ifdef STDEBUG
743		mutex_init(&st_debug_mutex, NULL, MUTEX_DRIVER, NULL);
744#endif
745
746#if defined(__x86)
747		/* set the max physical address for iob allocs on x86 */
748		st_alloc_attr.dma_attr_addr_hi = st_max_phys_addr;
749
750		/*
751		 * set the sgllen for iob allocs on x86. If this is set less
752		 * than the number of pages the buffer will take
753		 * (taking into account alignment), it would force the
754		 * allocator to try and allocate contiguous pages.
755		 */
756		st_alloc_attr.dma_attr_sgllen = st_sgl_size;
757#endif
758	}
759
760	return (e);
761}
762
763int
764_fini(void)
765{
766	int e;
767
768	if ((e = mod_remove(&modlinkage)) != 0) {
769		return (e);
770	}
771
772#ifdef STDEBUG
773	mutex_destroy(&st_debug_mutex);
774#endif
775
776	ddi_soft_state_fini(&st_state);
777
778	return (e);
779}
780
781int
782_info(struct modinfo *modinfop)
783{
784	return (mod_info(&modlinkage, modinfop));
785}
786
787
788static int
789st_probe(dev_info_t *devi)
790{
791	int instance;
792	struct scsi_device *devp;
793	int rval;
794
795#if !defined(__sparc)
796	char    *tape_prop;
797	int	tape_prop_len;
798#endif
799
800	ST_ENTR(devi, st_probe);
801
802	/* If self identifying device */
803	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
804		return (DDI_PROBE_DONTCARE);
805	}
806
807#if !defined(__sparc)
808	/*
809	 * Since some x86 HBAs have devnodes that look like SCSI as
810	 * far as we can tell but aren't really SCSI (DADK, like mlx)
811	 * we check for the presence of the "tape" property.
812	 */
813	if (ddi_prop_op(DDI_DEV_T_NONE, devi, PROP_LEN_AND_VAL_ALLOC,
814	    DDI_PROP_CANSLEEP, "tape",
815	    (caddr_t)&tape_prop, &tape_prop_len) != DDI_PROP_SUCCESS) {
816		return (DDI_PROBE_FAILURE);
817	}
818	if (strncmp(tape_prop, "sctp", tape_prop_len) != 0) {
819		kmem_free(tape_prop, tape_prop_len);
820		return (DDI_PROBE_FAILURE);
821	}
822	kmem_free(tape_prop, tape_prop_len);
823#endif
824
825	devp = ddi_get_driver_private(devi);
826	instance = ddi_get_instance(devi);
827
828	if (ddi_get_soft_state(st_state, instance) != NULL) {
829		return (DDI_PROBE_PARTIAL);
830	}
831
832
833	/*
834	 * Turn around and call probe routine to see whether
835	 * we actually have a tape at this SCSI nexus.
836	 */
837	if (scsi_probe(devp, NULL_FUNC) == SCSIPROBE_EXISTS) {
838
839		/*
840		 * In checking the whole inq_dtype byte we are looking at both
841		 * the Peripheral Qualifier and the Peripheral Device Type.
842		 * For this driver we are only interested in sequential devices
843		 * that are connected or capable if connecting to this logical
844		 * unit.
845		 */
846		if (devp->sd_inq->inq_dtype ==
847		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
848			ST_DEBUG6(devi, st_label, SCSI_DEBUG,
849			    "probe exists\n");
850			rval = DDI_PROBE_SUCCESS;
851		} else {
852			rval = DDI_PROBE_FAILURE;
853		}
854	} else {
855		ST_DEBUG6(devi, st_label, SCSI_DEBUG,
856		    "probe failure: nothing there\n");
857		rval = DDI_PROBE_FAILURE;
858	}
859	scsi_unprobe(devp);
860	return (rval);
861}
862
863static int
864st_attach(dev_info_t *devi, ddi_attach_cmd_t cmd)
865{
866	int	instance;
867	int	wide;
868	int	dev_instance;
869	int	ret_status;
870	struct	scsi_device *devp;
871	int	node_ix;
872	struct	scsi_tape *un;
873
874	ST_ENTR(devi, st_attach);
875
876	devp = ddi_get_driver_private(devi);
877	instance = ddi_get_instance(devi);
878
879	switch (cmd) {
880		case DDI_ATTACH:
881			if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
882			    "tape-command-recovery-disable", 0) != 0) {
883				st_recov_sz = sizeof (pkt_info);
884			}
885			if (st_doattach(devp, SLEEP_FUNC) == DDI_FAILURE) {
886				return (DDI_FAILURE);
887			}
888			break;
889		case DDI_RESUME:
890			/*
891			 * Suspend/Resume
892			 *
893			 * When the driver suspended, there might be
894			 * outstanding cmds and therefore we need to
895			 * reset the suspended flag and resume the scsi
896			 * watch thread and restart commands and timeouts
897			 */
898
899			if (!(un = ddi_get_soft_state(st_state, instance))) {
900				return (DDI_FAILURE);
901			}
902			dev_instance = ((un->un_dev == 0) ? MTMINOR(instance) :
903			    un->un_dev);
904
905			mutex_enter(ST_MUTEX);
906
907			un->un_throttle = un->un_max_throttle;
908			un->un_tids_at_suspend = 0;
909			un->un_pwr_mgmt = ST_PWR_NORMAL;
910
911			if (un->un_swr_token) {
912				scsi_watch_resume(un->un_swr_token);
913			}
914
915			/*
916			 * Restart timeouts
917			 */
918			if ((un->un_tids_at_suspend & ST_DELAY_TID) != 0) {
919				mutex_exit(ST_MUTEX);
920				un->un_delay_tid = timeout(
921				    st_delayed_cv_broadcast, un,
922				    drv_usectohz((clock_t)
923				    MEDIA_ACCESS_DELAY));
924				mutex_enter(ST_MUTEX);
925			}
926
927			if (un->un_tids_at_suspend & ST_HIB_TID) {
928				mutex_exit(ST_MUTEX);
929				un->un_hib_tid = timeout(st_intr_restart, un,
930				    ST_STATUS_BUSY_TIMEOUT);
931				mutex_enter(ST_MUTEX);
932			}
933
934			ret_status = st_clear_unit_attentions(dev_instance, 5);
935
936			/*
937			 * now check if we need to restore the tape position
938			 */
939			if ((un->un_suspend_pos.pmode != invalid) &&
940			    ((un->un_suspend_pos.fileno > 0) ||
941			    (un->un_suspend_pos.blkno > 0)) ||
942			    (un->un_suspend_pos.lgclblkno > 0)) {
943				if (ret_status != 0) {
944					/*
945					 * tape didn't get good TUR
946					 * just print out error messages
947					 */
948					scsi_log(ST_DEVINFO, st_label, CE_WARN,
949					    "st_attach-RESUME: tape failure "
950					    " tape position will be lost");
951				} else {
952					/* this prints errors */
953					(void) st_validate_tapemarks(un,
954					    st_uscsi_cmd, &un->un_suspend_pos);
955				}
956				/*
957				 * there are no retries, if there is an error
958				 * we don't know if the tape has changed
959				 */
960				un->un_suspend_pos.pmode = invalid;
961			}
962
963			/* now we are ready to start up any queued I/Os */
964			if (un->un_ncmds || un->un_quef) {
965				st_start(un);
966			}
967
968			cv_broadcast(&un->un_suspend_cv);
969			mutex_exit(ST_MUTEX);
970			return (DDI_SUCCESS);
971
972		default:
973			return (DDI_FAILURE);
974	}
975
976	un = ddi_get_soft_state(st_state, instance);
977
978	ST_DEBUG(devi, st_label, SCSI_DEBUG,
979	    "st_attach: instance=%x\n", instance);
980
981	/*
982	 * Add a zero-length attribute to tell the world we support
983	 * kernel ioctls (for layered drivers)
984	 */
985	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
986	    DDI_KERNEL_IOCTL, NULL, 0);
987
988	ddi_report_dev((dev_info_t *)devi);
989
990	/*
991	 * If it's a SCSI-2 tape drive which supports wide,
992	 * tell the host adapter to use wide.
993	 */
994	wide = ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
995	    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) ?  1 : 0;
996
997	if (scsi_ifsetcap(ROUTE, "wide-xfer", wide, 1) == 1) {
998		ST_DEBUG(devi, st_label, SCSI_DEBUG,
999		    "Wide Transfer %s\n", wide ? "enabled" : "disabled");
1000	}
1001
1002	/*
1003	 * enable autorequest sense; keep the rq packet around in case
1004	 * the autorequest sense fails because of a busy condition
1005	 * do a getcap first in case the capability is not variable
1006	 */
1007	if (scsi_ifgetcap(ROUTE, "auto-rqsense", 1) == 1) {
1008		un->un_arq_enabled = 1;
1009	} else {
1010		un->un_arq_enabled =
1011		    ((scsi_ifsetcap(ROUTE, "auto-rqsense", 1, 1) == 1) ? 1 : 0);
1012	}
1013
1014	ST_DEBUG(devi, st_label, SCSI_DEBUG, "auto request sense %s\n",
1015	    (un->un_arq_enabled ? "enabled" : "disabled"));
1016
1017	un->un_untagged_qing =
1018	    (scsi_ifgetcap(ROUTE, "untagged-qing", 0) == 1);
1019
1020	/*
1021	 * XXX - This is just for 2.6.  to tell users that write buffering
1022	 *	has gone away.
1023	 */
1024	if (un->un_arq_enabled && un->un_untagged_qing) {
1025		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
1026		    "tape-driver-buffering", 0) != 0) {
1027			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
1028			    "Write Data Buffering has been depricated. Your "
1029			    "applications should continue to work normally.\n"
1030			    " But, they should  ported to use Asynchronous "
1031			    " I/O\n"
1032			    " For more information, read about "
1033			    " tape-driver-buffering "
1034			    "property in the st(7d) man page\n");
1035		}
1036	}
1037
1038	un->un_max_throttle = un->un_throttle = un->un_last_throttle = 1;
1039	un->un_flush_on_errors = 0;
1040	un->un_mkr_pkt = (struct scsi_pkt *)NULL;
1041
1042	ST_DEBUG(devi, st_label, SCSI_DEBUG,
1043	    "throttle=%x, max_throttle = %x\n",
1044	    un->un_throttle, un->un_max_throttle);
1045
1046	/* initialize persistent errors to nil */
1047	un->un_persistence = 0;
1048	un->un_persist_errors = 0;
1049
1050	/*
1051	 * Get dma-max from HBA driver. If it is not defined, use 64k
1052	 */
1053	un->un_maxdma	= scsi_ifgetcap(&devp->sd_address, "dma-max", 1);
1054	if (un->un_maxdma == -1) {
1055		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1056		    "Received a value that looked like -1. Using 64k maxdma");
1057		un->un_maxdma = (64 * ONE_K);
1058	}
1059
1060#ifdef	__x86
1061	/*
1062	 * for x86, the device may be able to DMA more than the system will
1063	 * allow under some circumstances. We need account for both the HBA's
1064	 * and system's contraints.
1065	 *
1066	 * Get the maximum DMA under worse case conditions. e.g. looking at the
1067	 * device constraints, the max copy buffer size, and the worse case
1068	 * fragmentation. NOTE: this may differ from dma-max since dma-max
1069	 * doesn't take the worse case framentation into account.
1070	 *
1071	 * e.g. a device may be able to DMA 16MBytes, but can only DMA 1MByte
1072	 * if none of the pages are contiguous. Keeping track of both of these
1073	 * values allows us to support larger tape block sizes on some devices.
1074	 */
1075	un->un_maxdma_arch = scsi_ifgetcap(&devp->sd_address, "dma-max-arch",
1076	    1);
1077
1078	/*
1079	 * If the dma-max-arch capability is not implemented, or the value
1080	 * comes back higher than what was reported in dma-max, use dma-max.
1081	 */
1082	if ((un->un_maxdma_arch == -1) ||
1083	    ((uint_t)un->un_maxdma < (uint_t)un->un_maxdma_arch)) {
1084		un->un_maxdma_arch = un->un_maxdma;
1085	}
1086#endif
1087
1088	/*
1089	 * Get the max allowable cdb size
1090	 */
1091	un->un_max_cdb_sz =
1092	    scsi_ifgetcap(&devp->sd_address, "max-cdb-length", 1);
1093	if (un->un_max_cdb_sz < CDB_GROUP0) {
1094		ST_DEBUG(devi, st_label, SCSI_DEBUG,
1095		    "HBA reported max-cdb-length as %d\n", un->un_max_cdb_sz);
1096		un->un_max_cdb_sz = CDB_GROUP4; /* optimistic default */
1097	}
1098
1099	if (strcmp(ddi_driver_name(ddi_get_parent(ST_DEVINFO)), "scsi_vhci")) {
1100		un->un_multipath = 0;
1101	} else {
1102		un->un_multipath = 1;
1103	}
1104
1105	un->un_maxbsize = MAXBSIZE_UNKNOWN;
1106
1107	un->un_mediastate = MTIO_NONE;
1108	un->un_HeadClean  = TAPE_ALERT_SUPPORT_UNKNOWN;
1109
1110	/*
1111	 * initialize kstats
1112	 */
1113	un->un_stats = kstat_create("st", instance, NULL, "tape",
1114	    KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
1115	if (un->un_stats) {
1116		un->un_stats->ks_lock = ST_MUTEX;
1117		kstat_install(un->un_stats);
1118	}
1119	(void) st_create_errstats(un, instance);
1120
1121	/*
1122	 * find the drive type for this target
1123	 */
1124	mutex_enter(ST_MUTEX);
1125	un->un_dev = MTMINOR(instance);
1126	st_known_tape_type(un);
1127	un->un_dev = 0;
1128	mutex_exit(ST_MUTEX);
1129
1130	for (node_ix = 0; node_ix < ST_NUM_MEMBERS(st_minor_data); node_ix++) {
1131		int minor;
1132		char *name;
1133
1134		name  = st_minor_data[node_ix].name;
1135		minor = st_minor_data[node_ix].minor;
1136
1137		/*
1138		 * For default devices set the density to the
1139		 * preferred default density for this device.
1140		 */
1141		if (node_ix <= DEF_BSD_NR) {
1142			minor |= un->un_dp->default_density;
1143		}
1144		minor |= MTMINOR(instance);
1145
1146		if (ddi_create_minor_node(devi, name, S_IFCHR, minor,
1147		    DDI_NT_TAPE, 0) == DDI_SUCCESS) {
1148			continue;
1149		}
1150
1151		ddi_remove_minor_node(devi, NULL);
1152
1153		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1154		    st_reset_notification, (caddr_t)un);
1155		cv_destroy(&un->un_clscv);
1156		cv_destroy(&un->un_sbuf_cv);
1157		cv_destroy(&un->un_queue_cv);
1158		cv_destroy(&un->un_state_cv);
1159#ifdef	__x86
1160		cv_destroy(&un->un_contig_mem_cv);
1161#endif
1162		cv_destroy(&un->un_suspend_cv);
1163		cv_destroy(&un->un_tape_busy_cv);
1164		cv_destroy(&un->un_recov_buf_cv);
1165		if (un->un_recov_taskq) {
1166			ddi_taskq_destroy(un->un_recov_taskq);
1167		}
1168		if (un->un_sbufp) {
1169			freerbuf(un->un_sbufp);
1170		}
1171		if (un->un_recov_buf) {
1172			freerbuf(un->un_recov_buf);
1173		}
1174		if (un->un_uscsi_rqs_buf) {
1175			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1176		}
1177		if (un->un_mspl) {
1178			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1179		}
1180		if (un->un_dp_size) {
1181			kmem_free(un->un_dp, un->un_dp_size);
1182		}
1183		if (un->un_state) {
1184			kstat_delete(un->un_stats);
1185		}
1186		if (un->un_errstats) {
1187			kstat_delete(un->un_errstats);
1188		}
1189
1190		scsi_destroy_pkt(un->un_rqs);
1191		scsi_free_consistent_buf(un->un_rqs_bp);
1192		ddi_soft_state_free(st_state, instance);
1193		devp->sd_private = NULL;
1194		devp->sd_sense = NULL;
1195
1196		ddi_prop_remove_all(devi);
1197		return (DDI_FAILURE);
1198	}
1199
1200	return (DDI_SUCCESS);
1201}
1202
1203/*
1204 * st_detach:
1205 *
1206 * we allow a detach if and only if:
1207 *	- no tape is currently inserted
1208 *	- tape position is at BOT or unknown
1209 *		(if it is not at BOT then a no rewind
1210 *		device was opened and we have to preserve state)
1211 *	- it must be in a closed state : no timeouts or scsi_watch requests
1212 *		will exist if it is closed, so we don't need to check for
1213 *		them here.
1214 */
1215/*ARGSUSED*/
1216static int
1217st_detach(dev_info_t *devi, ddi_detach_cmd_t cmd)
1218{
1219	int instance;
1220	int result;
1221	struct scsi_device *devp;
1222	struct scsi_tape *un;
1223	clock_t wait_cmds_complete;
1224
1225	ST_ENTR(devi, st_detach);
1226
1227	instance = ddi_get_instance(devi);
1228
1229	if (!(un = ddi_get_soft_state(st_state, instance))) {
1230		return (DDI_FAILURE);
1231	}
1232
1233	mutex_enter(ST_MUTEX);
1234
1235	/*
1236	 * Clear error entry stack
1237	 */
1238	st_empty_error_stack(un);
1239
1240	mutex_exit(ST_MUTEX);
1241
1242	switch (cmd) {
1243
1244	case DDI_DETACH:
1245		/*
1246		 * Undo what we did in st_attach & st_doattach,
1247		 * freeing resources and removing things we installed.
1248		 * The system framework guarantees we are not active
1249		 * with this devinfo node in any other entry points at
1250		 * this time.
1251		 */
1252
1253		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1254		    "st_detach: instance=%x, un=%p\n", instance,
1255		    (void *)un);
1256
1257		if (((un->un_dp->options & ST_UNLOADABLE) == 0) ||
1258		    ((un->un_rsvd_status & ST_APPLICATION_RESERVATIONS) != 0) ||
1259		    (un->un_ncmds != 0) || (un->un_quef != NULL) ||
1260		    (un->un_state != ST_STATE_CLOSED)) {
1261			/*
1262			 * we cannot unload some targets because the
1263			 * inquiry returns junk unless immediately
1264			 * after a reset
1265			 */
1266			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
1267			    "cannot unload instance %x\n", instance);
1268			un->un_unit_attention_flags |= 4;
1269			return (DDI_FAILURE);
1270		}
1271
1272		/*
1273		 * if the tape has been removed then we may unload;
1274		 * do a test unit ready and if it returns NOT READY
1275		 * then we assume that it is safe to unload.
1276		 * as a side effect, pmode may be set to invalid if the
1277		 * the test unit ready fails;
1278		 * also un_state may be set to non-closed, so reset it
1279		 */
1280		if ((un->un_dev) &&		/* Been opened since attach */
1281		    ((un->un_pos.pmode == legacy) &&
1282		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1283		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1284		    ((un->un_pos.pmode == logical) &&
1285		    (un->un_pos.lgclblkno > 0))) {
1286			mutex_enter(ST_MUTEX);
1287			/*
1288			 * Send Test Unit Ready in the hopes that if
1289			 * the drive is not in the state we think it is.
1290			 * And the state will be changed so it can be detached.
1291			 * If the command fails to reach the device and
1292			 * the drive was not rewound or unloaded we want
1293			 * to fail the detach till a user command fails
1294			 * where after the detach will succead.
1295			 */
1296			result = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
1297			/*
1298			 * After TUR un_state may be set to non-closed,
1299			 * so reset it back.
1300			 */
1301			un->un_state = ST_STATE_CLOSED;
1302			mutex_exit(ST_MUTEX);
1303		}
1304		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1305		    "un_status=%x, fileno=%x, blkno=%x\n",
1306		    un->un_status, un->un_pos.fileno, un->un_pos.blkno);
1307
1308		/*
1309		 * check again:
1310		 * if we are not at BOT then it is not safe to unload
1311		 */
1312		if ((un->un_dev) &&		/* Been opened since attach */
1313		    (result != EACCES) &&	/* drive is use by somebody */
1314		    ((((un->un_pos.pmode == legacy) &&
1315		    (un->un_pos.fileno > 0) ||	/* Known position not rewound */
1316		    (un->un_pos.blkno != 0)) ||	/* Or within first file */
1317		    ((un->un_pos.pmode == logical) &&
1318		    (un->un_pos.lgclblkno > 0))) &&
1319		    ((un->un_state == ST_STATE_CLOSED) &&
1320		    (un->un_laststate == ST_STATE_CLOSING)))) {
1321
1322			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1323			    "cannot detach: pmode=%d fileno=0x%x, blkno=0x%x"
1324			    " lgclblkno=0x%"PRIx64"\n", un->un_pos.pmode,
1325			    un->un_pos.fileno, un->un_pos.blkno,
1326			    un->un_pos.lgclblkno);
1327			un->un_unit_attention_flags |= 4;
1328			return (DDI_FAILURE);
1329		}
1330
1331		/*
1332		 * Just To make sure that we have released the
1333		 * tape unit .
1334		 */
1335		if (un->un_dev && (un->un_rsvd_status & ST_RESERVE) &&
1336		    !DEVI_IS_DEVICE_REMOVED(devi)) {
1337			mutex_enter(ST_MUTEX);
1338			(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
1339			mutex_exit(ST_MUTEX);
1340		}
1341
1342		/*
1343		 * now remove other data structures allocated in st_doattach()
1344		 */
1345		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
1346		    "destroying/freeing\n");
1347
1348		(void) scsi_reset_notify(ROUTE, SCSI_RESET_CANCEL,
1349		    st_reset_notification, (caddr_t)un);
1350		cv_destroy(&un->un_clscv);
1351		cv_destroy(&un->un_sbuf_cv);
1352		cv_destroy(&un->un_queue_cv);
1353		cv_destroy(&un->un_suspend_cv);
1354		cv_destroy(&un->un_tape_busy_cv);
1355		cv_destroy(&un->un_recov_buf_cv);
1356
1357		if (un->un_recov_taskq) {
1358			ddi_taskq_destroy(un->un_recov_taskq);
1359		}
1360
1361		if (un->un_hib_tid) {
1362			(void) untimeout(un->un_hib_tid);
1363			un->un_hib_tid = 0;
1364		}
1365
1366		if (un->un_delay_tid) {
1367			(void) untimeout(un->un_delay_tid);
1368			un->un_delay_tid = 0;
1369		}
1370		cv_destroy(&un->un_state_cv);
1371
1372#ifdef	__x86
1373		cv_destroy(&un->un_contig_mem_cv);
1374
1375		if (un->un_contig_mem_hdl != NULL) {
1376			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1377		}
1378#endif
1379		if (un->un_sbufp) {
1380			freerbuf(un->un_sbufp);
1381		}
1382		if (un->un_recov_buf) {
1383			freerbuf(un->un_recov_buf);
1384		}
1385		if (un->un_uscsi_rqs_buf) {
1386			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1387		}
1388		if (un->un_mspl) {
1389			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1390		}
1391		if (un->un_rqs) {
1392			scsi_destroy_pkt(un->un_rqs);
1393			scsi_free_consistent_buf(un->un_rqs_bp);
1394		}
1395		if (un->un_mkr_pkt) {
1396			scsi_destroy_pkt(un->un_mkr_pkt);
1397		}
1398		if (un->un_arq_enabled) {
1399			(void) scsi_ifsetcap(ROUTE, "auto-rqsense", 0, 1);
1400		}
1401		if (un->un_dp_size) {
1402			kmem_free(un->un_dp, un->un_dp_size);
1403		}
1404		if (un->un_stats) {
1405			kstat_delete(un->un_stats);
1406			un->un_stats = (kstat_t *)0;
1407		}
1408		if (un->un_errstats) {
1409			kstat_delete(un->un_errstats);
1410			un->un_errstats = (kstat_t *)0;
1411		}
1412		if (un->un_media_id_len) {
1413			kmem_free(un->un_media_id, un->un_media_id_len);
1414		}
1415		devp = ST_SCSI_DEVP;
1416		ddi_soft_state_free(st_state, instance);
1417		devp->sd_private = NULL;
1418		devp->sd_sense = NULL;
1419		scsi_unprobe(devp);
1420		ddi_prop_remove_all(devi);
1421		ddi_remove_minor_node(devi, NULL);
1422		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach done\n");
1423		return (DDI_SUCCESS);
1424
1425	case DDI_SUSPEND:
1426
1427		/*
1428		 * Suspend/Resume
1429		 *
1430		 * To process DDI_SUSPEND, we must do the following:
1431		 *
1432		 *  - check ddi_removing_power to see if power will be turned
1433		 *    off. if so, return DDI_FAILURE
1434		 *  - check if we are already suspended,
1435		 *    if so, return DDI_FAILURE
1436		 *  - check if device state is CLOSED,
1437		 *    if not, return DDI_FAILURE.
1438		 *  - wait until outstanding operations complete
1439		 *  - save tape state
1440		 *  - block new operations
1441		 *  - cancel pending timeouts
1442		 *
1443		 */
1444
1445		if (ddi_removing_power(devi)) {
1446			return (DDI_FAILURE);
1447		}
1448
1449		if (un->un_dev == 0)
1450			un->un_dev = MTMINOR(instance);
1451
1452		mutex_enter(ST_MUTEX);
1453
1454		/*
1455		 * Shouldn't already be suspended, if so return failure
1456		 */
1457		if (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
1458			mutex_exit(ST_MUTEX);
1459			return (DDI_FAILURE);
1460		}
1461		if (un->un_state != ST_STATE_CLOSED) {
1462			mutex_exit(ST_MUTEX);
1463			return (DDI_FAILURE);
1464		}
1465
1466		/*
1467		 * Wait for all outstanding I/O's to complete
1468		 *
1469		 * we wait on both ncmds and the wait queue for times
1470		 * when we are flushing after persistent errors are
1471		 * flagged, which is when ncmds can be 0, and the
1472		 * queue can still have I/O's.  This way we preserve
1473		 * order of biodone's.
1474		 */
1475		wait_cmds_complete = ddi_get_lbolt();
1476		wait_cmds_complete +=
1477		    st_wait_cmds_complete * drv_usectohz(1000000);
1478		while (un->un_ncmds || un->un_quef ||
1479		    (un->un_state == ST_STATE_RESOURCE_WAIT)) {
1480
1481			if (cv_timedwait(&un->un_tape_busy_cv, ST_MUTEX,
1482			    wait_cmds_complete) == -1) {
1483				/*
1484				 * Time expired then cancel the command
1485				 */
1486				if (st_reset(un, RESET_LUN) == 0) {
1487					if (un->un_last_throttle) {
1488						un->un_throttle =
1489						    un->un_last_throttle;
1490					}
1491					mutex_exit(ST_MUTEX);
1492					return (DDI_FAILURE);
1493				} else {
1494					break;
1495				}
1496			}
1497		}
1498
1499		/*
1500		 * DDI_SUSPEND says that the system "may" power down, we
1501		 * remember the file and block number before rewinding.
1502		 * we also need to save state before issuing
1503		 * any WRITE_FILE_MARK command.
1504		 */
1505		(void) st_update_block_pos(un, st_cmd, 0);
1506		COPY_POS(&un->un_suspend_pos, &un->un_pos);
1507
1508
1509		/*
1510		 * Issue a zero write file fmk command to tell the drive to
1511		 * flush any buffered tape marks
1512		 */
1513		(void) st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD);
1514
1515		/*
1516		 * Because not all tape drives correctly implement buffer
1517		 * flushing with the zero write file fmk command, issue a
1518		 * synchronous rewind command to force data flushing.
1519		 * st_validate_tapemarks() will do a rewind during DDI_RESUME
1520		 * anyway.
1521		 */
1522		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
1523
1524		/* stop any new operations */
1525		un->un_pwr_mgmt = ST_PWR_SUSPENDED;
1526		un->un_throttle = 0;
1527
1528		/*
1529		 * cancel any outstanding timeouts
1530		 */
1531		if (un->un_delay_tid) {
1532			timeout_id_t temp_id = un->un_delay_tid;
1533			un->un_delay_tid = 0;
1534			un->un_tids_at_suspend |= ST_DELAY_TID;
1535			mutex_exit(ST_MUTEX);
1536			(void) untimeout(temp_id);
1537			mutex_enter(ST_MUTEX);
1538		}
1539
1540		if (un->un_hib_tid) {
1541			timeout_id_t temp_id = un->un_hib_tid;
1542			un->un_hib_tid = 0;
1543			un->un_tids_at_suspend |= ST_HIB_TID;
1544			mutex_exit(ST_MUTEX);
1545			(void) untimeout(temp_id);
1546			mutex_enter(ST_MUTEX);
1547		}
1548
1549		/*
1550		 * Suspend the scsi_watch_thread
1551		 */
1552		if (un->un_swr_token) {
1553			opaque_t temp_token = un->un_swr_token;
1554			mutex_exit(ST_MUTEX);
1555			scsi_watch_suspend(temp_token);
1556		} else {
1557			mutex_exit(ST_MUTEX);
1558		}
1559
1560		return (DDI_SUCCESS);
1561
1562	default:
1563		ST_DEBUG(0, st_label, SCSI_DEBUG, "st_detach failed\n");
1564		return (DDI_FAILURE);
1565	}
1566}
1567
1568
1569/* ARGSUSED */
1570static int
1571st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
1572{
1573	dev_t dev;
1574	struct scsi_tape *un;
1575	int instance, error;
1576
1577	ST_ENTR(dip, st_info);
1578
1579	switch (infocmd) {
1580	case DDI_INFO_DEVT2DEVINFO:
1581		dev = (dev_t)arg;
1582		instance = MTUNIT(dev);
1583		if ((un = ddi_get_soft_state(st_state, instance)) == NULL)
1584			return (DDI_FAILURE);
1585		*result = (void *) ST_DEVINFO;
1586		error = DDI_SUCCESS;
1587		break;
1588	case DDI_INFO_DEVT2INSTANCE:
1589		dev = (dev_t)arg;
1590		instance = MTUNIT(dev);
1591		*result = (void *)(uintptr_t)instance;
1592		error = DDI_SUCCESS;
1593		break;
1594	default:
1595		error = DDI_FAILURE;
1596	}
1597	return (error);
1598}
1599
1600static int
1601st_doattach(struct scsi_device *devp, int (*canwait)())
1602{
1603	struct scsi_tape *un = NULL;
1604	recov_info *ri;
1605	int km_flags = (canwait != NULL_FUNC) ? KM_SLEEP : KM_NOSLEEP;
1606	int instance;
1607	size_t rlen;
1608
1609	ST_FUNC(devp->sd_dev, st_doattach);
1610	/*
1611	 * Call the routine scsi_probe to do some of the dirty work.
1612	 * If the INQUIRY command succeeds, the field sd_inq in the
1613	 * device structure will be filled in.
1614	 */
1615	ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1616	    "st_doattach(): probing\n");
1617
1618	if (scsi_probe(devp, canwait) == SCSIPROBE_EXISTS) {
1619
1620		/*
1621		 * In checking the whole inq_dtype byte we are looking at both
1622		 * the Peripheral Qualifier and the Peripheral Device Type.
1623		 * For this driver we are only interested in sequential devices
1624		 * that are connected or capable if connecting to this logical
1625		 * unit.
1626		 */
1627		if (devp->sd_inq->inq_dtype ==
1628		    (DTYPE_SEQUENTIAL | DPQ_POSSIBLE)) {
1629			ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1630			    "probe exists\n");
1631		} else {
1632			/* Something there but not a tape device */
1633			scsi_unprobe(devp);
1634			return (DDI_FAILURE);
1635		}
1636	} else {
1637		/* Nothing there */
1638		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1639		    "probe failure: nothing there\n");
1640		scsi_unprobe(devp);
1641		return (DDI_FAILURE);
1642	}
1643
1644
1645	/*
1646	 * The actual unit is present.
1647	 * Now is the time to fill in the rest of our info..
1648	 */
1649	instance = ddi_get_instance(devp->sd_dev);
1650
1651	if (ddi_soft_state_zalloc(st_state, instance) != DDI_SUCCESS) {
1652		goto error;
1653	}
1654	un = ddi_get_soft_state(st_state, instance);
1655
1656	ASSERT(un != NULL);
1657
1658	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
1659	    MAX_SENSE_LENGTH, B_READ, canwait, NULL);
1660	if (un->un_rqs_bp == NULL) {
1661		goto error;
1662	}
1663	un->un_rqs = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
1664	    CDB_GROUP0, 1, st_recov_sz, PKT_CONSISTENT, canwait, NULL);
1665	if (!un->un_rqs) {
1666		goto error;
1667	}
1668	ASSERT(un->un_rqs->pkt_resid == 0);
1669	devp->sd_sense =
1670	    (struct scsi_extended_sense *)un->un_rqs_bp->b_un.b_addr;
1671	ASSERT(geterror(un->un_rqs_bp) == 0);
1672
1673	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs->pkt_cdbp,
1674	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
1675	FILL_SCSI1_LUN(devp, un->un_rqs);
1676	un->un_rqs->pkt_flags |= (FLAG_SENSING | FLAG_HEAD | FLAG_NODISCON);
1677	un->un_rqs->pkt_time = st_io_time;
1678	un->un_rqs->pkt_comp = st_intr;
1679	ri = (recov_info *)un->un_rqs->pkt_private;
1680	if (st_recov_sz == sizeof (recov_info)) {
1681		ri->privatelen = sizeof (recov_info);
1682	} else {
1683		ri->privatelen = sizeof (pkt_info);
1684	}
1685
1686	un->un_sbufp = getrbuf(km_flags);
1687	un->un_recov_buf = getrbuf(km_flags);
1688
1689	un->un_uscsi_rqs_buf = kmem_alloc(SENSE_LENGTH, KM_SLEEP);
1690
1691	/*
1692	 * use i_ddi_mem_alloc() for now until we have an interface to allocate
1693	 * memory for DMA which doesn't require a DMA handle.
1694	 */
1695	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1696	    sizeof (struct seq_mode), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1697	    NULL, (caddr_t *)&un->un_mspl, &rlen, NULL);
1698
1699	(void) i_ddi_mem_alloc(devp->sd_dev, &st_alloc_attr,
1700	    sizeof (read_pos_data_t), ((km_flags == KM_SLEEP) ? 1 : 0), 0,
1701	    NULL, (caddr_t *)&un->un_read_pos_data, &rlen, NULL);
1702
1703	if (!un->un_sbufp || !un->un_mspl || !un->un_read_pos_data) {
1704		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1705		    "probe partial failure: no space\n");
1706		goto error;
1707	}
1708
1709	bzero(un->un_mspl, sizeof (struct seq_mode));
1710
1711	cv_init(&un->un_sbuf_cv, NULL, CV_DRIVER, NULL);
1712	cv_init(&un->un_queue_cv, NULL, CV_DRIVER, NULL);
1713	cv_init(&un->un_clscv, NULL, CV_DRIVER, NULL);
1714	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
1715#ifdef	__x86
1716	cv_init(&un->un_contig_mem_cv, NULL, CV_DRIVER, NULL);
1717#endif
1718
1719	/* Initialize power managemnet condition variable */
1720	cv_init(&un->un_suspend_cv, NULL, CV_DRIVER, NULL);
1721	cv_init(&un->un_tape_busy_cv, NULL, CV_DRIVER, NULL);
1722	cv_init(&un->un_recov_buf_cv, NULL, CV_DRIVER, NULL);
1723
1724	un->un_recov_taskq = ddi_taskq_create(devp->sd_dev,
1725	    "un_recov_taskq", 1, TASKQ_DEFAULTPRI, km_flags);
1726
1727	ASSERT(un->un_recov_taskq != NULL);
1728
1729	un->un_pos.pmode = invalid;
1730	un->un_sd	= devp;
1731	un->un_swr_token = (opaque_t)NULL;
1732	un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
1733	un->un_wormable = st_is_drive_worm;
1734	un->un_media_id_method = st_get_media_identification;
1735	/*
1736	 * setting long a initial as it contains logical file info.
1737	 * support for long format is mandatory but many drive don't do it.
1738	 */
1739	un->un_read_pos_type = LONG_POS;
1740
1741	un->un_suspend_pos.pmode = invalid;
1742
1743	st_add_recovery_info_to_pkt(un, un->un_rqs_bp, un->un_rqs);
1744
1745#ifdef	__x86
1746	if (ddi_dma_alloc_handle(ST_DEVINFO, &st_contig_mem_dma_attr,
1747	    DDI_DMA_SLEEP, NULL, &un->un_contig_mem_hdl) != DDI_SUCCESS) {
1748		ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG,
1749		    "allocation of contiguous memory dma handle failed!");
1750		un->un_contig_mem_hdl = NULL;
1751		goto error;
1752	}
1753#endif
1754
1755	/*
1756	 * Since this driver manages devices with "remote" hardware,
1757	 * i.e. the devices themselves have no "reg" properties,
1758	 * the SUSPEND/RESUME commands in detach/attach will not be
1759	 * called by the power management framework unless we request
1760	 * it by creating a "pm-hardware-state" property and setting it
1761	 * to value "needs-suspend-resume".
1762	 */
1763	if (ddi_prop_update_string(DDI_DEV_T_NONE, devp->sd_dev,
1764	    "pm-hardware-state", "needs-suspend-resume") !=
1765	    DDI_PROP_SUCCESS) {
1766
1767		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1768		    "ddi_prop_update(\"pm-hardware-state\") failed\n");
1769		goto error;
1770	}
1771
1772	if (ddi_prop_create(DDI_DEV_T_NONE, devp->sd_dev, DDI_PROP_CANSLEEP,
1773	    "no-involuntary-power-cycles", NULL, 0) != DDI_PROP_SUCCESS) {
1774
1775		ST_DEBUG(devp->sd_dev, st_label, SCSI_DEBUG,
1776		    "ddi_prop_create(\"no-involuntary-power-cycles\") "
1777		    "failed\n");
1778		goto error;
1779	}
1780
1781	(void) scsi_reset_notify(ROUTE, SCSI_RESET_NOTIFY,
1782	    st_reset_notification, (caddr_t)un);
1783
1784	ST_DEBUG6(devp->sd_dev, st_label, SCSI_DEBUG, "attach success\n");
1785	return (DDI_SUCCESS);
1786
1787error:
1788	devp->sd_sense = NULL;
1789
1790	ddi_remove_minor_node(devp->sd_dev, NULL);
1791	if (un) {
1792		if (un->un_mspl) {
1793			i_ddi_mem_free((caddr_t)un->un_mspl, NULL);
1794		}
1795		if (un->un_read_pos_data) {
1796			i_ddi_mem_free((caddr_t)un->un_read_pos_data, 0);
1797		}
1798		if (un->un_sbufp) {
1799			freerbuf(un->un_sbufp);
1800		}
1801		if (un->un_recov_buf) {
1802			freerbuf(un->un_recov_buf);
1803		}
1804		if (un->un_uscsi_rqs_buf) {
1805			kmem_free(un->un_uscsi_rqs_buf, SENSE_LENGTH);
1806		}
1807#ifdef	__x86
1808		if (un->un_contig_mem_hdl != NULL) {
1809			ddi_dma_free_handle(&un->un_contig_mem_hdl);
1810		}
1811#endif
1812		if (un->un_rqs) {
1813			scsi_destroy_pkt(un->un_rqs);
1814		}
1815
1816		if (un->un_rqs_bp) {
1817			scsi_free_consistent_buf(un->un_rqs_bp);
1818		}
1819
1820		ddi_soft_state_free(st_state, instance);
1821		devp->sd_private = NULL;
1822	}
1823
1824	if (devp->sd_inq) {
1825		scsi_unprobe(devp);
1826	}
1827	return (DDI_FAILURE);
1828}
1829
1830typedef int
1831(*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1832
1833static cfg_functp config_functs[] = {
1834	st_get_conf_from_st_dot_conf,
1835	st_get_conf_from_st_conf_dot_c,
1836	st_get_conf_from_tape_drive,
1837	st_get_default_conf
1838};
1839
1840
1841/*
1842 * determine tape type, using tape-config-list or built-in table or
1843 * use a generic tape config entry
1844 */
1845static void
1846st_known_tape_type(struct scsi_tape *un)
1847{
1848	struct st_drivetype *dp;
1849	cfg_functp *config_funct;
1850	uchar_t reserved;
1851
1852	ST_FUNC(ST_DEVINFO, st_known_tape_type);
1853
1854	reserved = (un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1855	    : ST_RELEASE;
1856
1857	/*
1858	 * XXX:  Emulex MT-02 (and emulators) predates SCSI-1 and has
1859	 *	 no vid & pid inquiry data.  So, we provide one.
1860	 */
1861	if (ST_INQUIRY->inq_len == 0 ||
1862	    (bcmp("\0\0\0\0\0\0\0\0", ST_INQUIRY->inq_vid, 8) == 0)) {
1863		(void) strcpy((char *)ST_INQUIRY->inq_vid, ST_MT02_NAME);
1864	}
1865
1866	if (un->un_dp_size == 0) {
1867		un->un_dp_size = sizeof (struct st_drivetype);
1868		dp = kmem_zalloc((size_t)un->un_dp_size, KM_SLEEP);
1869		un->un_dp = dp;
1870	} else {
1871		dp = un->un_dp;
1872	}
1873
1874	un->un_dp->non_motion_timeout = st_io_time;
1875	/*
1876	 * Loop through the configuration methods till one works.
1877	 */
1878	for (config_funct = &config_functs[0]; ; config_funct++) {
1879		if ((*config_funct)(un, ST_INQUIRY->inq_vid, dp)) {
1880			break;
1881		}
1882	}
1883
1884	/*
1885	 * If we didn't just make up this configuration and
1886	 * all the density codes are the same..
1887	 * Set Auto Density over ride.
1888	 */
1889	if (*config_funct != st_get_default_conf) {
1890		/*
1891		 * If this device is one that is configured and all
1892		 * densities are the same, This saves doing gets and set
1893		 * that yield nothing.
1894		 */
1895		if ((dp->densities[0]) == (dp->densities[1]) &&
1896		    (dp->densities[0]) == (dp->densities[2]) &&
1897		    (dp->densities[0]) == (dp->densities[3])) {
1898
1899			dp->options |= ST_AUTODEN_OVERRIDE;
1900		}
1901	}
1902
1903
1904	/*
1905	 * Store tape drive characteristics.
1906	 */
1907	un->un_status = 0;
1908	un->un_attached = 1;
1909	un->un_init_options = dp->options;
1910
1911	/* setup operation time-outs based on options */
1912	st_calculate_timeouts(un);
1913
1914	/* TLR support */
1915	if (un->un_dp->type != ST_TYPE_INVALID) {
1916		int result;
1917
1918		/* try and enable TLR */
1919		un->un_tlr_flag = TLR_SAS_ONE_DEVICE;
1920		result = st_set_target_TLR_mode(un, st_uscsi_cmd);
1921		if (result == EACCES) {
1922			/*
1923			 * From attach command failed.
1924			 * Set dp type so is run again on open.
1925			 */
1926			un->un_dp->type = ST_TYPE_INVALID;
1927			un->un_tlr_flag = TLR_NOT_KNOWN;
1928		} else if (result == 0) {
1929			if (scsi_ifgetcap(&un->un_sd->sd_address,
1930			    "tran-layer-retries", 1) == -1) {
1931				un->un_tlr_flag = TLR_NOT_SUPPORTED;
1932				(void) st_set_target_TLR_mode(un, st_uscsi_cmd);
1933			} else {
1934				un->un_tlr_flag = TLR_SAS_ONE_DEVICE;
1935			}
1936		} else {
1937			un->un_tlr_flag = TLR_NOT_SUPPORTED;
1938		}
1939	}
1940
1941	/* make sure if we are supposed to be variable, make it variable */
1942	if (dp->options & ST_VARIABLE) {
1943		dp->bsize = 0;
1944	}
1945
1946	if (reserved != ((un->un_rsvd_status & ST_RESERVE) ? ST_RESERVE
1947	    : ST_RELEASE)) {
1948		(void) st_reserve_release(un, reserved, st_uscsi_cmd);
1949	}
1950
1951	un->un_unit_attention_flags |= 1;
1952
1953	scsi_log(ST_DEVINFO, st_label, CE_NOTE, "?<%s>\n", dp->name);
1954
1955}
1956
1957
1958typedef struct {
1959	int mask;
1960	int bottom;
1961	int top;
1962	char *name;
1963} conf_limit;
1964
1965static const conf_limit conf_limits[] = {
1966
1967	-1,		1,		2,		"conf version",
1968	-1,		MT_ISTS,	ST_LAST_TYPE,	"drive type",
1969	-1,		0,		0xffffff,	"block size",
1970	ST_VALID_OPTS,	0,		ST_VALID_OPTS,	"options",
1971	-1,		0,		4,		"number of densities",
1972	-1,		0,		UINT8_MAX,	"density code",
1973	-1,		0,		3,		"default density",
1974	-1,		0,		UINT16_MAX,	"non motion timeout",
1975	-1,		0,		UINT16_MAX,	"I/O timeout",
1976	-1,		0,		UINT16_MAX,	"space timeout",
1977	-1,		0,		UINT16_MAX,	"load timeout",
1978	-1,		0,		UINT16_MAX,	"unload timeout",
1979	-1,		0,		UINT16_MAX,	"erase timeout",
1980	0,		0,		0,		NULL
1981};
1982
1983static int
1984st_validate_conf_data(struct scsi_tape *un, int *list, int list_len,
1985    const char *conf_name)
1986{
1987	int dens;
1988	int ndens;
1989	int value;
1990	int type;
1991	int count;
1992	const conf_limit *limit = &conf_limits[0];
1993
1994	ST_FUNC(ST_DEVINFO, st_validate_conf_data);
1995
1996	ST_DEBUG3(ST_DEVINFO, st_label, CE_NOTE,
1997	    "Checking %d entrys total with %d densities\n", list_len, list[4]);
1998
1999	count = list_len;
2000	type = *list;
2001	for (;  count && limit->name; count--, list++, limit++) {
2002
2003		value = *list;
2004		if (value & ~limit->mask) {
2005			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2006			    "%s %s value invalid bits set: 0x%X\n",
2007			    conf_name, limit->name, value & ~limit->mask);
2008			*list &= limit->mask;
2009		} else if (value < limit->bottom) {
2010			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2011			    "%s %s value too low: value = %d limit %d\n",
2012			    conf_name, limit->name, value, limit->bottom);
2013		} else if (value > limit->top) {
2014			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2015			    "%s %s value too high: value = %d limit %d\n",
2016			    conf_name, limit->name, value, limit->top);
2017		} else {
2018			ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
2019			    "%s %s value = 0x%X\n",
2020			    conf_name, limit->name, value);
2021		}
2022
2023		/* If not the number of densities continue */
2024		if (limit != &conf_limits[4]) {
2025			continue;
2026		}
2027
2028		/* If number of densities is not in range can't use config */
2029		if (value < limit->bottom || value > limit->top) {
2030			return (-1);
2031		}
2032
2033		ndens = min(value, NDENSITIES);
2034		if ((type == 1) && (list_len - ndens) != 6) {
2035			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2036			    "%s conf version 1 with %d densities has %d items"
2037			    " should have %d",
2038			    conf_name, ndens, list_len, 6 + ndens);
2039		} else if ((type == 2) && (list_len - ndens) != 13) {
2040			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2041			    "%s conf version 2 with %d densities has %d items"
2042			    " should have %d",
2043			    conf_name, ndens, list_len, 13 + ndens);
2044		}
2045
2046		limit++;
2047		for (dens = 0; dens < ndens && count; dens++) {
2048			count--;
2049			list++;
2050			value = *list;
2051			if (value < limit->bottom) {
2052				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2053				    "%s density[%d] value too low: value ="
2054				    " 0x%X limit 0x%X\n",
2055				    conf_name, dens, value, limit->bottom);
2056			} else if (value > limit->top) {
2057				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
2058				    "%s density[%d] value too high: value ="
2059				    " 0x%X limit 0x%X\n",
2060				    conf_name, dens, value, limit->top);
2061			} else {
2062				ST_DEBUG3(ST_DEVINFO, st_label, CE_CONT,
2063				    "%s density[%d] value = 0x%X\n",
2064				    conf_name, dens, value);
2065			}
2066		}
2067	}
2068
2069	return (0);
2070}
2071
2072static int
2073st_get_conf_from_st_dot_conf(struct scsi_tape *un, char *vidpid,
2074    struct st_drivetype *dp)
2075{
2076	caddr_t config_list = NULL;
2077	caddr_t data_list = NULL;
2078	int	*data_ptr;
2079	caddr_t vidptr, prettyptr, datanameptr;
2080	size_t	vidlen, prettylen, datanamelen, tripletlen = 0;
2081	int config_list_len, data_list_len, len, i;
2082	int version;
2083	int found = 0;
2084
2085	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_dot_conf);
2086
2087	/*
2088	 * Determine type of tape controller. Type is determined by
2089	 * checking the vendor ids of the earlier inquiry command and
2090	 * comparing those with vids in tape-config-list defined in st.conf
2091	 */
2092	if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, DDI_PROP_DONTPASS,
2093	    "tape-config-list", (caddr_t)&config_list, &config_list_len)
2094	    != DDI_PROP_SUCCESS) {
2095		return (found);
2096	}
2097
2098	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2099	    "st_get_conf_from_st_dot_conf(): st.conf has tape-config-list\n");
2100
2101	/*
2102	 * Compare vids in each triplet - if it matches, get value for
2103	 * data_name and contruct a st_drivetype struct
2104	 * tripletlen is not set yet!
2105	 */
2106	for (len = config_list_len, vidptr = config_list;
2107	    len > 0;
2108	    vidptr += tripletlen, len -= tripletlen) {
2109
2110		vidlen = strlen(vidptr);
2111		prettyptr = vidptr + vidlen + 1;
2112		prettylen = strlen(prettyptr);
2113		datanameptr = prettyptr + prettylen + 1;
2114		datanamelen = strlen(datanameptr);
2115		tripletlen = vidlen + prettylen + datanamelen + 3;
2116
2117		if (vidlen == 0) {
2118			continue;
2119		}
2120
2121		/*
2122		 * If inquiry vid dosen't match this triplets vid,
2123		 * try the next.
2124		 */
2125		if (strncasecmp(vidpid, vidptr, vidlen)) {
2126			continue;
2127		}
2128
2129		/*
2130		 * if prettylen is zero then use the vid string
2131		 */
2132		if (prettylen == 0) {
2133			prettyptr = vidptr;
2134			prettylen = vidlen;
2135		}
2136
2137		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2138		    "vid = %s, pretty=%s, dataname = %s\n",
2139		    vidptr, prettyptr, datanameptr);
2140
2141		/*
2142		 * get the data list
2143		 */
2144		if (ddi_getlongprop(DDI_DEV_T_ANY, ST_DEVINFO, 0,
2145		    datanameptr, (caddr_t)&data_list,
2146		    &data_list_len) != DDI_PROP_SUCCESS) {
2147			/*
2148			 * Error in getting property value
2149			 * print warning!
2150			 */
2151			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2152			    "data property (%s) has no value\n",
2153			    datanameptr);
2154			continue;
2155		}
2156
2157		/*
2158		 * now initialize the st_drivetype struct
2159		 */
2160		(void) strncpy(dp->name, prettyptr, ST_NAMESIZE - 1);
2161		dp->length = (int)min(vidlen, (VIDPIDLEN - 1));
2162		(void) strncpy(dp->vid, vidptr, dp->length);
2163		data_ptr = (int *)data_list;
2164		/*
2165		 * check if data is enough for version, type,
2166		 * bsize, options, # of densities, density1,
2167		 * density2, ..., default_density
2168		 */
2169		if ((data_list_len < 5 * sizeof (int)) ||
2170		    (data_list_len < 6 * sizeof (int) +
2171		    *(data_ptr + 4) * sizeof (int))) {
2172			/*
2173			 * print warning and skip to next triplet.
2174			 */
2175			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2176			    "data property (%s) incomplete\n",
2177			    datanameptr);
2178			kmem_free(data_list, data_list_len);
2179			continue;
2180		}
2181
2182		if (st_validate_conf_data(un, data_ptr,
2183		    data_list_len / sizeof (int), datanameptr)) {
2184			kmem_free(data_list, data_list_len);
2185			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2186			    "data property (%s) rejected\n",
2187			    datanameptr);
2188			continue;
2189		}
2190
2191		/*
2192		 * check version
2193		 */
2194		version = *data_ptr++;
2195		if (version != 1 && version != 2) {
2196			/* print warning but accept it */
2197			scsi_log(ST_DEVINFO, st_label, CE_WARN,
2198			    "Version # for data property (%s) "
2199			    "not set to 1 or 2\n", datanameptr);
2200		}
2201
2202		dp->type    = *data_ptr++;
2203		dp->bsize   = *data_ptr++;
2204		dp->options = *data_ptr++;
2205		dp->options |= ST_DYNAMIC;
2206		len = *data_ptr++;
2207		for (i = 0; i < NDENSITIES; i++) {
2208			if (i < len) {
2209				dp->densities[i] = *data_ptr++;
2210			}
2211		}
2212		dp->default_density = *data_ptr << 3;
2213		if (version == 2 &&
2214		    data_list_len >= (13 + len) * sizeof (int)) {
2215			data_ptr++;
2216			dp->non_motion_timeout	= *data_ptr++;
2217			dp->io_timeout		= *data_ptr++;
2218			dp->rewind_timeout	= *data_ptr++;
2219			dp->space_timeout	= *data_ptr++;
2220			dp->load_timeout	= *data_ptr++;
2221			dp->unload_timeout	= *data_ptr++;
2222			dp->erase_timeout	= *data_ptr++;
2223		}
2224		kmem_free(data_list, data_list_len);
2225		found = 1;
2226		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2227		    "found in st.conf: vid = %s, pretty=%s\n",
2228		    dp->vid, dp->name);
2229		break;
2230	}
2231
2232	/*
2233	 * free up the memory allocated by ddi_getlongprop
2234	 */
2235	if (config_list) {
2236		kmem_free(config_list, config_list_len);
2237	}
2238	return (found);
2239}
2240
2241static int
2242st_get_conf_from_st_conf_dot_c(struct scsi_tape *un, char *vidpid,
2243    struct st_drivetype *dp)
2244{
2245	int i;
2246
2247	ST_FUNC(ST_DEVINFO, st_get_conf_from_st_conf_dot_c);
2248	/*
2249	 * Determine type of tape controller.  Type is determined by
2250	 * checking the result of the earlier inquiry command and
2251	 * comparing vendor ids with strings in a table declared in st_conf.c.
2252	 */
2253	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2254	    "st_get_conf_from_st_conf_dot_c(): looking at st_drivetypes\n");
2255
2256	for (i = 0; i < st_ndrivetypes; i++) {
2257		if (st_drivetypes[i].length == 0) {
2258			continue;
2259		}
2260		if (strncasecmp(vidpid, st_drivetypes[i].vid,
2261		    st_drivetypes[i].length)) {
2262			continue;
2263		}
2264		bcopy(&st_drivetypes[i], dp, sizeof (st_drivetypes[i]));
2265		return (1);
2266	}
2267	return (0);
2268}
2269
2270static int
2271st_get_conf_from_tape_drive(struct scsi_tape *un, char *vidpid,
2272    struct st_drivetype *dp)
2273{
2274	int bsize;
2275	ulong_t maxbsize;
2276	caddr_t buf;
2277	struct st_drivetype *tem_dp;
2278	struct read_blklim *blklim;
2279	int rval;
2280	int i;
2281
2282	ST_FUNC(ST_DEVINFO, st_get_conf_from_tape_drive);
2283
2284	/*
2285	 * Determine the type of tape controller. Type is determined by
2286	 * sending SCSI commands to tape drive and deriving the type from
2287	 * the returned data.
2288	 */
2289	ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2290	    "st_get_conf_from_tape_drive(): asking tape drive\n");
2291
2292	tem_dp = kmem_zalloc(sizeof (struct st_drivetype), KM_SLEEP);
2293
2294	/*
2295	 * Make up a name
2296	 */
2297	bcopy(vidpid, tem_dp->name, VIDPIDLEN);
2298	tem_dp->name[VIDPIDLEN] = '\0';
2299	tem_dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2300	(void) strncpy(tem_dp->vid, ST_INQUIRY->inq_vid, tem_dp->length);
2301	/*
2302	 * 'clean' vendor and product strings of non-printing chars
2303	 */
2304	for (i = 0; i < VIDPIDLEN - 1; i ++) {
2305		if (tem_dp->name[i] < ' ' || tem_dp->name[i] > '~') {
2306			tem_dp->name[i] = '.';
2307		}
2308	}
2309
2310	/*
2311	 * MODE SENSE to determine block size.
2312	 */
2313	un->un_dp->options |= ST_MODE_SEL_COMP | ST_UNLOADABLE;
2314	rval = st_modesense(un);
2315	if (rval) {
2316		if (rval == EACCES) {
2317			un->un_dp->type = ST_TYPE_INVALID;
2318			rval = 1;
2319		} else {
2320			un->un_dp->options &= ~ST_MODE_SEL_COMP;
2321			rval = 0;
2322		}
2323		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2324		    "st_get_conf_from_tape_drive(): fail to mode sense\n");
2325		goto exit;
2326	}
2327
2328	/* Can mode sense page 0x10 or 0xf */
2329	tem_dp->options |= ST_MODE_SEL_COMP;
2330	bsize = (un->un_mspl->high_bl << 16)	|
2331	    (un->un_mspl->mid_bl << 8)		|
2332	    (un->un_mspl->low_bl);
2333
2334	if (bsize == 0) {
2335		tem_dp->options |= ST_VARIABLE;
2336		tem_dp->bsize = 0;
2337	} else if (bsize > ST_MAXRECSIZE_FIXED) {
2338		rval = st_change_block_size(un, 0);
2339		if (rval) {
2340			if (rval == EACCES) {
2341				un->un_dp->type = ST_TYPE_INVALID;
2342				rval = 1;
2343			} else {
2344				rval = 0;
2345				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2346				    "st_get_conf_from_tape_drive(): "
2347				    "Fixed record size is too large and"
2348				    "cannot switch to variable record size");
2349			}
2350			goto exit;
2351		}
2352		tem_dp->options |= ST_VARIABLE;
2353	} else {
2354		rval = st_change_block_size(un, 0);
2355		if (rval == 0) {
2356			tem_dp->options |= ST_VARIABLE;
2357			tem_dp->bsize = 0;
2358		} else if (rval != EACCES) {
2359			tem_dp->bsize = bsize;
2360		} else {
2361			un->un_dp->type = ST_TYPE_INVALID;
2362			rval = 1;
2363			goto exit;
2364		}
2365	}
2366
2367	/*
2368	 * If READ BLOCk LIMITS works and upper block size limit is
2369	 * more than 64K, ST_NO_RECSIZE_LIMIT is supported.
2370	 */
2371	blklim = kmem_zalloc(sizeof (struct read_blklim), KM_SLEEP);
2372	rval = st_read_block_limits(un, blklim);
2373	if (rval) {
2374		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2375		    "st_get_conf_from_tape_drive(): "
2376		    "fail to read block limits.\n");
2377		rval = 0;
2378		kmem_free(blklim, sizeof (struct read_blklim));
2379		goto exit;
2380	}
2381	maxbsize = (blklim->max_hi << 16) +
2382	    (blklim->max_mid << 8) + blklim->max_lo;
2383	if (maxbsize > ST_MAXRECSIZE_VARIABLE) {
2384		tem_dp->options |= ST_NO_RECSIZE_LIMIT;
2385	}
2386	kmem_free(blklim, sizeof (struct read_blklim));
2387
2388	/*
2389	 * Inquiry VPD page 0xb0 to see if the tape drive supports WORM
2390	 */
2391	buf = kmem_zalloc(6, KM_SLEEP);
2392	rval = st_get_special_inquiry(un, 6, buf, 0xb0);
2393	if (rval) {
2394		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2395		    "st_get_conf_from_tape_drive(): "
2396		    "fail to read vitial inquiry.\n");
2397		rval = 0;
2398		kmem_free(buf, 6);
2399		goto exit;
2400	}
2401	if (buf[4] & 1) {
2402		tem_dp->options |= ST_WORMABLE;
2403	}
2404	kmem_free(buf, 6);
2405
2406	/* Assume BSD BSR KNOWS_EOD */
2407	tem_dp->options |= ST_BSF | ST_BSR | ST_KNOWS_EOD | ST_UNLOADABLE;
2408	tem_dp->max_rretries = -1;
2409	tem_dp->max_wretries = -1;
2410
2411	/*
2412	 * Decide the densities supported by tape drive by sending
2413	 * REPORT DENSITY SUPPORT command.
2414	 */
2415	if (st_get_densities_from_tape_drive(un, tem_dp) == 0) {
2416		goto exit;
2417	}
2418
2419	/*
2420	 * Decide the timeout values for several commands by sending
2421	 * REPORT SUPPORTED OPERATION CODES command.
2422	 */
2423	rval = st_get_timeout_values_from_tape_drive(un, tem_dp);
2424	if (rval == 0 || ((rval == 1) && (tem_dp->type == ST_TYPE_INVALID))) {
2425		goto exit;
2426	}
2427
2428	bcopy(tem_dp, dp, sizeof (struct st_drivetype));
2429	rval = 1;
2430
2431exit:
2432	un->un_status = KEY_NO_SENSE;
2433	kmem_free(tem_dp, sizeof (struct st_drivetype));
2434	return (rval);
2435}
2436
2437static int
2438st_get_densities_from_tape_drive(struct scsi_tape *un,
2439    struct st_drivetype *dp)
2440{
2441	int i, p;
2442	size_t buflen;
2443	ushort_t des_len;
2444	uchar_t *den_header;
2445	uchar_t num_den;
2446	uchar_t den[NDENSITIES];
2447	uchar_t deflt[NDENSITIES];
2448	struct report_density_desc *den_desc;
2449
2450	ST_FUNC(ST_DEVINFO, st_get_densities_from_type_drive);
2451
2452	/*
2453	 * Since we have no idea how many densitiy support entries
2454	 * will be returned, we send the command firstly assuming
2455	 * there is only one. Then we can decide the number of
2456	 * entries by available density support length. If multiple
2457	 * entries exist, we will resend the command with enough
2458	 * buffer size.
2459	 */
2460	buflen = sizeof (struct report_density_header) +
2461	    sizeof (struct report_density_desc);
2462	den_header = kmem_zalloc(buflen, KM_SLEEP);
2463	if (st_report_density_support(un, den_header, buflen) != 0) {
2464		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2465		    "st_get_conf_from_tape_drive(): fail to report density.\n");
2466		kmem_free(den_header, buflen);
2467		return (0);
2468	}
2469	des_len =
2470	    BE_16(((struct report_density_header *)den_header)->ava_dens_len);
2471	num_den = (des_len - 2) / sizeof (struct report_density_desc);
2472
2473	if (num_den > 1) {
2474		kmem_free(den_header, buflen);
2475		buflen = sizeof (struct report_density_header) +
2476		    sizeof (struct report_density_desc) * num_den;
2477		den_header = kmem_zalloc(buflen, KM_SLEEP);
2478		if (st_report_density_support(un, den_header, buflen) != 0) {
2479			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2480			    "st_get_conf_from_tape_drive(): "
2481			    "fail to report density.\n");
2482			kmem_free(den_header, buflen);
2483			return (0);
2484		}
2485	}
2486
2487	den_desc = (struct report_density_desc *)(den_header
2488	    + sizeof (struct report_density_header));
2489
2490	/*
2491	 * Decide the drive type by assigning organization
2492	 */
2493	for (i = 0; i < ST_NUM_MEMBERS(st_vid_dt); i ++) {
2494		if (strncmp(st_vid_dt[i].vid, (char *)(den_desc->ass_org),
2495		    8) == 0) {
2496			dp->type = st_vid_dt[i].type;
2497			break;
2498		}
2499	}
2500	if (i == ST_NUM_MEMBERS(st_vid_dt)) {
2501		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2502		    "st_get_conf_from_tape_drive(): "
2503		    "can't find match of assigned ort.\n");
2504		kmem_free(den_header, buflen);
2505		return (0);
2506	}
2507
2508	/*
2509	 * The tape drive may support many tape formats, but the st driver
2510	 * supports only the four highest densities. Since density code
2511	 * values are returned by ascending sequence, we start from the
2512	 * last entry of density support data block descriptor.
2513	 */
2514	p = 0;
2515	den_desc += num_den - 1;
2516	for (i = 0; i < num_den && p < NDENSITIES; i ++, den_desc --) {
2517		if ((den_desc->pri_den != 0) && (den_desc->wrtok)) {
2518			if (p != 0) {
2519				if (den_desc->pri_den >= den[p - 1]) {
2520					continue;
2521				}
2522			}
2523			den[p] = den_desc->pri_den;
2524			deflt[p] = den_desc->deflt;
2525			p ++;
2526		}
2527	}
2528
2529	switch (p) {
2530	case 0:
2531		bzero(dp->densities, NDENSITIES);
2532		dp->options |= ST_AUTODEN_OVERRIDE;
2533		dp->default_density = MT_DENSITY4;
2534		break;
2535
2536	case 1:
2537		(void) memset(dp->densities, den[0], NDENSITIES);
2538		dp->options |= ST_AUTODEN_OVERRIDE;
2539		dp->default_density = MT_DENSITY4;
2540		break;
2541
2542	case 2:
2543		dp->densities[0] = den[1];
2544		dp->densities[1] = den[1];
2545		dp->densities[2] = den[0];
2546		dp->densities[3] = den[0];
2547		if (deflt[0]) {
2548			dp->default_density = MT_DENSITY4;
2549		} else {
2550			dp->default_density = MT_DENSITY2;
2551		}
2552		break;
2553
2554	case 3:
2555		dp->densities[0] = den[2];
2556		dp->densities[1] = den[1];
2557		dp->densities[2] = den[0];
2558		dp->densities[3] = den[0];
2559		if (deflt[0]) {
2560			dp->default_density = MT_DENSITY4;
2561		} else if (deflt[1]) {
2562			dp->default_density = MT_DENSITY2;
2563		} else {
2564			dp->default_density = MT_DENSITY1;
2565		}
2566		break;
2567
2568	default:
2569		for (i = p; i > p - NDENSITIES; i --) {
2570			dp->densities[i - 1] = den[p - i];
2571		}
2572		if (deflt[0]) {
2573			dp->default_density = MT_DENSITY4;
2574		} else if (deflt[1]) {
2575			dp->default_density = MT_DENSITY3;
2576		} else if (deflt[2]) {
2577			dp->default_density = MT_DENSITY2;
2578		} else {
2579			dp->default_density = MT_DENSITY1;
2580		}
2581		break;
2582	}
2583
2584	bzero(dp->mediatype, NDENSITIES);
2585
2586	kmem_free(den_header, buflen);
2587	return (1);
2588}
2589
2590static int
2591st_get_timeout_values_from_tape_drive(struct scsi_tape *un,
2592    struct st_drivetype *dp)
2593{
2594	ushort_t timeout;
2595	int rval;
2596
2597	ST_FUNC(ST_DEVINFO, st_get_timeout_values_from_type_drive);
2598
2599	rval = st_get_timeouts_value(un, SCMD_ERASE, &timeout, 0);
2600	if (rval) {
2601		if (rval == EACCES) {
2602			un->un_dp->type = ST_TYPE_INVALID;
2603			dp->type = ST_TYPE_INVALID;
2604			return (1);
2605		}
2606		return (0);
2607	}
2608	dp->erase_timeout = timeout;
2609
2610	rval = st_get_timeouts_value(un, SCMD_READ, &timeout, 0);
2611	if (rval) {
2612		if (rval == EACCES) {
2613			un->un_dp->type = ST_TYPE_INVALID;
2614			dp->type = ST_TYPE_INVALID;
2615			return (1);
2616		}
2617		return (0);
2618	}
2619	dp->io_timeout = timeout;
2620
2621	rval = st_get_timeouts_value(un, SCMD_WRITE, &timeout, 0);
2622	if (rval) {
2623		if (rval == EACCES) {
2624			un->un_dp->type = ST_TYPE_INVALID;
2625			dp->type = ST_TYPE_INVALID;
2626			return (1);
2627		}
2628		return (0);
2629	}
2630	dp->io_timeout = max(dp->io_timeout, timeout);
2631
2632	rval = st_get_timeouts_value(un, SCMD_SPACE, &timeout, 0);
2633	if (rval) {
2634		if (rval == EACCES) {
2635			un->un_dp->type = ST_TYPE_INVALID;
2636			dp->type = ST_TYPE_INVALID;
2637			return (1);
2638		}
2639		return (0);
2640	}
2641	dp->space_timeout = timeout;
2642
2643	rval = st_get_timeouts_value(un, SCMD_LOAD, &timeout, 0);
2644	if (rval) {
2645		if (rval == EACCES) {
2646			un->un_dp->type = ST_TYPE_INVALID;
2647			dp->type = ST_TYPE_INVALID;
2648			return (1);
2649		}
2650		return (0);
2651	}
2652	dp->load_timeout = timeout;
2653	dp->unload_timeout = timeout;
2654
2655	rval = st_get_timeouts_value(un, SCMD_REWIND, &timeout, 0);
2656	if (rval) {
2657		if (rval == EACCES) {
2658			un->un_dp->type = ST_TYPE_INVALID;
2659			dp->type = ST_TYPE_INVALID;
2660			return (1);
2661		}
2662		return (0);
2663	}
2664	dp->rewind_timeout = timeout;
2665
2666	rval = st_get_timeouts_value(un, SCMD_INQUIRY, &timeout, 0);
2667	if (rval) {
2668		if (rval == EACCES) {
2669			un->un_dp->type = ST_TYPE_INVALID;
2670			dp->type = ST_TYPE_INVALID;
2671			return (1);
2672		}
2673		return (0);
2674	}
2675	dp->non_motion_timeout = timeout;
2676
2677	return (1);
2678}
2679
2680static int
2681st_get_timeouts_value(struct scsi_tape *un, uchar_t option_code,
2682    ushort_t *timeout_value, ushort_t service_action)
2683{
2684	uchar_t *timeouts;
2685	uchar_t *oper;
2686	uchar_t support;
2687	uchar_t cdbsize;
2688	uchar_t ctdp;
2689	size_t buflen;
2690	int rval;
2691
2692	ST_FUNC(ST_DEVINFO, st_get_timeouts_value);
2693
2694	buflen = sizeof (struct one_com_des) +
2695	    sizeof (struct com_timeout_des);
2696	oper = kmem_zalloc(buflen, KM_SLEEP);
2697	rval = st_report_supported_operation(un, oper, option_code,
2698	    service_action);
2699
2700	if (rval) {
2701		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2702		    "st_get_timeouts_value(): "
2703		    "fail to timeouts value for command %d.\n", option_code);
2704		kmem_free(oper, buflen);
2705		return (rval);
2706	}
2707
2708	support = ((struct one_com_des *)oper)->support;
2709	if ((support != SUPPORT_VALUES_SUPPORT_SCSI) &&
2710	    (support != SUPPORT_VALUES_SUPPORT_VENDOR)) {
2711		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2712		    "st_get_timeouts_value(): "
2713		    "command %d is not supported.\n", option_code);
2714		kmem_free(oper, buflen);
2715		return (ENOTSUP);
2716	}
2717
2718	ctdp = ((struct one_com_des *)oper)->ctdp;
2719	if (!ctdp) {
2720		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
2721		    "st_get_timeouts_value(): "
2722		    "command timeout is not included.\n");
2723		kmem_free(oper, buflen);
2724		return (ENOTSUP);
2725	}
2726
2727	cdbsize = BE_16(((struct one_com_des *)oper)->cdb_size);
2728	timeouts = (uchar_t *)(oper + cdbsize + 4);
2729
2730	/*
2731	 * Timeout value in seconds is 4 bytes, but we only support the lower 2
2732	 * bytes. If the higher 2 bytes are not zero, the timeout value is set
2733	 * to 0xFFFF.
2734	 */
2735	if (*(timeouts + 8) != 0 || *(timeouts + 9) != 0) {
2736		*timeout_value = USHRT_MAX;
2737	} else {
2738		*timeout_value = ((*(timeouts + 10)) << 8) |
2739		    (*(timeouts + 11));
2740	}
2741
2742	kmem_free(oper, buflen);
2743	return (0);
2744}
2745
2746static int
2747st_get_default_conf(struct scsi_tape *un, char *vidpid, struct st_drivetype *dp)
2748{
2749	int i;
2750
2751	ST_FUNC(ST_DEVINFO, st_get_default_conf);
2752
2753	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
2754	    "st_get_default_conf(): making drivetype from INQ cmd\n");
2755
2756	/*
2757	 * Make up a name
2758	 */
2759	bcopy("Vendor '", dp->name, 8);
2760	bcopy(vidpid, &dp->name[8], VIDLEN);
2761	bcopy("' Product '", &dp->name[16], 11);
2762	bcopy(&vidpid[8], &dp->name[27], PIDLEN);
2763	dp->name[ST_NAMESIZE - 2] = '\'';
2764	dp->name[ST_NAMESIZE - 1] = '\0';
2765	dp->length = min(strlen(ST_INQUIRY->inq_vid), (VIDPIDLEN - 1));
2766	(void) strncpy(dp->vid, ST_INQUIRY->inq_vid, dp->length);
2767	/*
2768	 * 'clean' vendor and product strings of non-printing chars
2769	 */
2770	for (i = 0; i < ST_NAMESIZE - 2; i++) {
2771		if (dp->name[i] < ' ' || dp->name[i] > '~') {
2772			dp->name[i] = '.';
2773		}
2774	}
2775	dp->type = ST_TYPE_INVALID;
2776	dp->options |= (ST_DYNAMIC | ST_UNLOADABLE | ST_MODE_SEL_COMP);
2777
2778	return (1); /* Can Not Fail */
2779}
2780
2781/*
2782 * Regular Unix Entry points
2783 */
2784
2785
2786
2787/* ARGSUSED */
2788static int
2789st_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
2790{
2791	dev_t dev = *dev_p;
2792	int rval = 0;
2793
2794	GET_SOFT_STATE(dev);
2795
2796	ST_ENTR(ST_DEVINFO, st_open);
2797
2798	/*
2799	 * validate that we are addressing a sensible unit
2800	 */
2801	mutex_enter(ST_MUTEX);
2802
2803	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2804	    "st_open(node = %s dev = 0x%lx, flag = %d, otyp = %d)\n",
2805	    st_dev_name(dev), *dev_p, flag, otyp);
2806
2807	/*
2808	 * All device accesss go thru st_strategy() where we check
2809	 * suspend status
2810	 */
2811
2812	if (!un->un_attached) {
2813		st_known_tape_type(un);
2814		if (!un->un_attached) {
2815			rval = ENXIO;
2816			goto exit;
2817		}
2818
2819	}
2820
2821	/*
2822	 * Check for the case of the tape in the middle of closing.
2823	 * This isn't simply a check of the current state, because
2824	 * we could be in state of sensing with the previous state
2825	 * that of closing.
2826	 *
2827	 * And don't allow multiple opens.
2828	 */
2829	if (!(flag & (FNDELAY | FNONBLOCK)) && IS_CLOSING(un)) {
2830		un->un_laststate = un->un_state;
2831		un->un_state = ST_STATE_CLOSE_PENDING_OPEN;
2832		while (IS_CLOSING(un) ||
2833		    un->un_state == ST_STATE_CLOSE_PENDING_OPEN) {
2834			if (cv_wait_sig(&un->un_clscv, ST_MUTEX) == 0) {
2835				rval = EINTR;
2836				un->un_state = un->un_laststate;
2837				goto exit;
2838			}
2839		}
2840	} else if (un->un_state != ST_STATE_CLOSED) {
2841		rval = EBUSY;
2842		goto busy;
2843	}
2844
2845	/*
2846	 * record current dev
2847	 */
2848	un->un_dev = dev;
2849	un->un_oflags = flag;	/* save for use in st_tape_init() */
2850	un->un_errno = 0;	/* no errors yet */
2851	un->un_restore_pos = 0;
2852	un->un_rqs_state = 0;
2853
2854	/*
2855	 * If we are opening O_NDELAY, or O_NONBLOCK, we don't check for
2856	 * anything, leave internal states alone, if fileno >= 0
2857	 */
2858	if (flag & (FNDELAY | FNONBLOCK)) {
2859		switch (un->un_pos.pmode) {
2860
2861		case invalid:
2862			un->un_state = ST_STATE_OFFLINE;
2863			break;
2864
2865		case legacy:
2866			/*
2867			 * If position is anything other than rewound.
2868			 */
2869			if (un->un_pos.fileno != 0 || un->un_pos.blkno != 0) {
2870				/*
2871				 * set un_read_only/write-protect status.
2872				 *
2873				 * If the tape is not bot we can assume
2874				 * that mspl->wp_status is set properly.
2875				 * else
2876				 * we need to do a mode sense/Tur once
2877				 * again to get the actual tape status.(since
2878				 * user might have replaced the tape)
2879				 * Hence make the st state OFFLINE so that
2880				 * we re-intialize the tape once again.
2881				 */
2882				un->un_read_only =
2883				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2884				un->un_state = ST_STATE_OPEN_PENDING_IO;
2885			} else {
2886				un->un_state = ST_STATE_OFFLINE;
2887			}
2888			break;
2889		case logical:
2890			if (un->un_pos.lgclblkno == 0) {
2891				un->un_state = ST_STATE_OFFLINE;
2892			} else {
2893				un->un_read_only =
2894				    (un->un_oflags & FWRITE) ? RDWR : RDONLY;
2895				un->un_state = ST_STATE_OPEN_PENDING_IO;
2896			}
2897			break;
2898		}
2899		rval = 0;
2900	} else {
2901		/*
2902		 * Not opening O_NDELAY.
2903		 */
2904		un->un_state = ST_STATE_OPENING;
2905
2906		/*
2907		 * Clear error entry stack
2908		 */
2909		st_empty_error_stack(un);
2910
2911		rval = st_tape_init(un);
2912		if ((rval == EACCES) && (un->un_read_only & WORM)) {
2913			un->un_state = ST_STATE_OPEN_PENDING_IO;
2914			rval = 0; /* so open doesn't fail */
2915		} else if (rval) {
2916			/*
2917			 * Release the tape unit, if reserved and not
2918			 * preserve reserve.
2919			 */
2920			if ((un->un_rsvd_status &
2921			    (ST_RESERVE | ST_PRESERVE_RESERVE)) == ST_RESERVE) {
2922				(void) st_reserve_release(un, ST_RELEASE,
2923				    st_uscsi_cmd);
2924			}
2925		} else {
2926			un->un_state = ST_STATE_OPEN_PENDING_IO;
2927		}
2928	}
2929
2930exit:
2931	/*
2932	 * we don't want any uninvited guests scrogging our data when we're
2933	 * busy with something, so for successful opens or failed opens
2934	 * (except for EBUSY), reset these counters and state appropriately.
2935	 */
2936	if (rval != EBUSY) {
2937		if (rval) {
2938			un->un_state = ST_STATE_CLOSED;
2939		}
2940		un->un_err_resid = 0;
2941		un->un_retry_ct = 0;
2942	}
2943busy:
2944	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2945	    "st_open: return val = %x, state = %d\n", rval, un->un_state);
2946	mutex_exit(ST_MUTEX);
2947	return (rval);
2948
2949}
2950
2951static int
2952st_tape_init(struct scsi_tape *un)
2953{
2954	int err;
2955	int rval = 0;
2956
2957	ST_FUNC(ST_DEVINFO, st_tape_init);
2958
2959	ASSERT(mutex_owned(ST_MUTEX));
2960
2961	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
2962	    "st_tape_init(un = 0x%p, oflags = %d)\n", (void*)un, un->un_oflags);
2963
2964	/*
2965	 * Clean up after any errors left by 'last' close.
2966	 * This also handles the case of the initial open.
2967	 */
2968	if (un->un_state != ST_STATE_INITIALIZING) {
2969		un->un_laststate = un->un_state;
2970		un->un_state = ST_STATE_OPENING;
2971	}
2972
2973	un->un_kbytes_xferred = 0;
2974
2975	/*
2976	 * do a throw away TUR to clear check condition
2977	 */
2978	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
2979
2980	/*
2981	 * If test unit ready fails because the drive is reserved
2982	 * by another host fail the open for no access.
2983	 */
2984	if (err) {
2985		if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
2986			un->un_state = ST_STATE_CLOSED;
2987			ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
2988			    "st_tape_init: RESERVATION CONFLICT\n");
2989			rval = EACCES;
2990			goto exit;
2991		} else if ((un->un_rsvd_status &
2992		    ST_APPLICATION_RESERVATIONS) != 0) {
2993			if ((ST_RQSENSE != NULL) &&
2994			    (ST_RQSENSE->es_add_code == 0x2a &&
2995			    ST_RQSENSE->es_qual_code == 0x03)) {
2996				un->un_state = ST_STATE_CLOSED;
2997				rval = EACCES;
2998				goto exit;
2999			}
3000		}
3001	}
3002
3003	/*
3004	 * Tape self identification could fail if the tape drive is used by
3005	 * another host during attach time. We try to get the tape type
3006	 * again. This is also applied to any posponed configuration methods.
3007	 */
3008	if (un->un_dp->type == ST_TYPE_INVALID) {
3009		un->un_comp_page = ST_DEV_DATACOMP_PAGE | ST_DEV_CONFIG_PAGE;
3010		st_known_tape_type(un);
3011	}
3012
3013	/*
3014	 * If the tape type is still invalid, try to determine the generic
3015	 * configuration.
3016	 */
3017	if (un->un_dp->type == ST_TYPE_INVALID) {
3018		rval = st_determine_generic(un);
3019		if (rval) {
3020			if (rval != EACCES) {
3021				rval = EIO;
3022			}
3023			un->un_state = ST_STATE_CLOSED;
3024			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3025			    "st_tape_init: %s invalid type\n",
3026			    rval == EACCES ? "EACCES" : "EIO");
3027			goto exit;
3028		}
3029		/*
3030		 * If this is a Unknown Type drive,
3031		 * Use the READ BLOCK LIMITS to determine if
3032		 * allow large xfer is approprate if not globally
3033		 * disabled with st_allow_large_xfer.
3034		 */
3035		un->un_allow_large_xfer = (uchar_t)st_allow_large_xfer;
3036	} else {
3037
3038		/*
3039		 * If we allow_large_xfer (ie >64k) and have not yet found out
3040		 * the max block size supported by the drive,
3041		 * find it by issueing a READ_BLKLIM command.
3042		 * if READ_BLKLIM cmd fails, assume drive doesn't
3043		 * allow_large_xfer and min/max block sizes as 1 byte and 63k.
3044		 */
3045		un->un_allow_large_xfer = st_allow_large_xfer &&
3046		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT);
3047	}
3048	/*
3049	 * if maxbsize is unknown, set the maximum block size.
3050	 */
3051	if (un->un_maxbsize == MAXBSIZE_UNKNOWN) {
3052
3053		/*
3054		 * Get the Block limits of the tape drive.
3055		 * if un->un_allow_large_xfer = 0 , then make sure
3056		 * that maxbsize is <= ST_MAXRECSIZE_FIXED.
3057		 */
3058		un->un_rbl = kmem_zalloc(RBLSIZE, KM_SLEEP);
3059
3060		err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3061		if (err) {
3062			/* Retry */
3063			err = st_cmd(un, SCMD_READ_BLKLIM, RBLSIZE, SYNC_CMD);
3064		}
3065		if (!err) {
3066
3067			/*
3068			 * if cmd successful, use limit returned
3069			 */
3070			un->un_maxbsize = (un->un_rbl->max_hi << 16) +
3071			    (un->un_rbl->max_mid << 8) +
3072			    un->un_rbl->max_lo;
3073			un->un_minbsize = (un->un_rbl->min_hi << 8) +
3074			    un->un_rbl->min_lo;
3075			un->un_data_mod = 1 << un->un_rbl->granularity;
3076			if ((un->un_maxbsize == 0) ||
3077			    (un->un_allow_large_xfer == 0 &&
3078			    un->un_maxbsize > ST_MAXRECSIZE_FIXED)) {
3079				un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3080
3081			} else if (un->un_dp->type == ST_TYPE_DEFAULT) {
3082				/*
3083				 * Drive is not one that is configured, But the
3084				 * READ BLOCK LIMITS tells us it can do large
3085				 * xfers.
3086				 */
3087				if (un->un_maxbsize > ST_MAXRECSIZE_FIXED) {
3088					un->un_dp->options |=
3089					    ST_NO_RECSIZE_LIMIT;
3090				}
3091				/*
3092				 * If max and mimimum block limits are the
3093				 * same this is a fixed block size device.
3094				 */
3095				if (un->un_maxbsize == un->un_minbsize) {
3096					un->un_dp->options &= ~ST_VARIABLE;
3097				}
3098			}
3099
3100			if (un->un_minbsize == 0) {
3101				un->un_minbsize = 1;
3102			}
3103
3104		} else { /* error on read block limits */
3105
3106			scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3107			    "!st_tape_init: Error on READ BLOCK LIMITS,"
3108			    " errno = %d un_rsvd_status = 0x%X\n",
3109			    err, un->un_rsvd_status);
3110
3111			/*
3112			 * since read block limits cmd failed,
3113			 * do not allow large xfers.
3114			 * use old values in st_minphys
3115			 */
3116			if (un->un_rsvd_status & ST_RESERVATION_CONFLICT) {
3117				rval = EACCES;
3118			} else {
3119				un->un_allow_large_xfer = 0;
3120				scsi_log(ST_DEVINFO, st_label, CE_NOTE,
3121				    "!Disabling large transfers\n");
3122
3123				/*
3124				 * we guess maxbsize and minbsize
3125				 */
3126				if (un->un_bsize) {
3127					un->un_maxbsize = un->un_minbsize =
3128					    un->un_bsize;
3129				} else {
3130					un->un_maxbsize = ST_MAXRECSIZE_FIXED;
3131					un->un_minbsize = 1;
3132				}
3133				/*
3134				 * Data Mod must be set,
3135				 * Even if read block limits fails.
3136				 * Prevents Divide By Zero in st_rw().
3137				 */
3138				un->un_data_mod = 1;
3139			}
3140		}
3141		if (un->un_rbl) {
3142			kmem_free(un->un_rbl, RBLSIZE);
3143			un->un_rbl = NULL;
3144		}
3145
3146		if (rval) {
3147			goto exit;
3148		}
3149	}
3150
3151	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3152	    "maxdma = %d, maxbsize = %d, minbsize = %d, %s large xfer\n",
3153	    un->un_maxdma, un->un_maxbsize, un->un_minbsize,
3154	    (un->un_allow_large_xfer ? "ALLOW": "DON'T ALLOW"));
3155
3156	err = st_cmd(un, SCMD_TEST_UNIT_READY, 0, SYNC_CMD);
3157
3158	if (err != 0) {
3159		if (err == EINTR) {
3160			un->un_laststate = un->un_state;
3161			un->un_state = ST_STATE_CLOSED;
3162			rval = EINTR;
3163			goto exit;
3164		}
3165		/*
3166		 * Make sure the tape is ready
3167		 */
3168		un->un_pos.pmode = invalid;
3169		if (un->un_status != KEY_UNIT_ATTENTION) {
3170			/*
3171			 * allow open no media.  Subsequent MTIOCSTATE
3172			 * with media present will complete the open
3173			 * logic.
3174			 */
3175			un->un_laststate = un->un_state;
3176			if (un->un_oflags & (FNONBLOCK|FNDELAY)) {
3177				un->un_mediastate = MTIO_EJECTED;
3178				un->un_state = ST_STATE_OFFLINE;
3179				rval = 0;
3180				goto exit;
3181			} else {
3182				un->un_state = ST_STATE_CLOSED;
3183				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3184				    "st_tape_init EIO no media, not opened "
3185				    "O_NONBLOCK|O_EXCL\n");
3186				rval = EIO;
3187				goto exit;
3188			}
3189		}
3190	}
3191
3192	/*
3193	 * On each open, initialize block size from drivetype struct,
3194	 * as it could have been changed by MTSRSZ ioctl.
3195	 * Now, ST_VARIABLE simply means drive is capable of variable
3196	 * mode. All drives are assumed to support fixed records.
3197	 * Hence, un_bsize tells what mode the drive is in.
3198	 *	un_bsize	= 0	- variable record length
3199	 *			= x	- fixed record length is x
3200	 */
3201	un->un_bsize = un->un_dp->bsize;
3202
3203	/*
3204	 * If saved position is valid go there
3205	 */
3206	if (un->un_restore_pos) {
3207		un->un_restore_pos = 0;
3208		un->un_pos.fileno = un->un_save_fileno;
3209		un->un_pos.blkno = un->un_save_blkno;
3210		rval = st_validate_tapemarks(un, st_uscsi_cmd, &un->un_pos);
3211		if (rval != 0) {
3212			if (rval != EACCES) {
3213				rval = EIO;
3214			}
3215			un->un_laststate = un->un_state;
3216			un->un_state = ST_STATE_CLOSED;
3217			goto exit;
3218		}
3219	}
3220
3221	if (un->un_pos.pmode == invalid) {
3222		rval = st_loadtape(un);
3223		if (rval) {
3224			if (rval != EACCES) {
3225				rval = EIO;
3226			}
3227			un->un_laststate = un->un_state;
3228			un->un_state = ST_STATE_CLOSED;
3229			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3230			    "st_tape_init: %s can't open tape\n",
3231			    rval == EACCES ? "EACCES" : "EIO");
3232			goto exit;
3233		}
3234	}
3235
3236	/*
3237	 * do a mode sense to pick up state of current write-protect,
3238	 * Could cause reserve and fail due to conflict.
3239	 */
3240	if (un->un_unit_attention_flags) {
3241		rval = st_modesense(un);
3242		if (rval == EACCES) {
3243			goto exit;
3244		}
3245	}
3246
3247	/*
3248	 * If we are opening the tape for writing, check
3249	 * to make sure that the tape can be written.
3250	 */
3251	if (un->un_oflags & FWRITE) {
3252		err = 0;
3253		if (un->un_mspl->wp) {
3254			un->un_status = KEY_WRITE_PROTECT;
3255			un->un_laststate = un->un_state;
3256			un->un_state = ST_STATE_CLOSED;
3257			rval = EACCES;
3258			/*
3259			 * STK sets the wp bit if volsafe tape is loaded.
3260			 */
3261			if ((un->un_dp->type == MT_ISSTK9840) &&
3262			    (un->un_dp->options & ST_WORMABLE)) {
3263				un->un_read_only = RDONLY;
3264			} else {
3265				goto exit;
3266			}
3267		} else {
3268			un->un_read_only = RDWR;
3269		}
3270	} else {
3271		un->un_read_only = RDONLY;
3272	}
3273
3274	if (un->un_dp->options & ST_WORMABLE &&
3275	    un->un_unit_attention_flags) {
3276		un->un_read_only |= un->un_wormable(un);
3277
3278		if (((un->un_read_only == WORM) ||
3279		    (un->un_read_only == RDWORM)) &&
3280		    ((un->un_oflags & FWRITE) == FWRITE)) {
3281			un->un_status = KEY_DATA_PROTECT;
3282			rval = EACCES;
3283			ST_DEBUG4(ST_DEVINFO, st_label, CE_NOTE,
3284			    "read_only = %d eof = %d oflag = %d\n",
3285			    un->un_read_only, un->un_pos.eof, un->un_oflags);
3286		}
3287	}
3288
3289	/*
3290	 * If we're opening the tape write-only, we need to
3291	 * write 2 filemarks on the HP 1/2 inch drive, to
3292	 * create a null file.
3293	 */
3294	if ((un->un_read_only == RDWR) ||
3295	    (un->un_read_only == WORM) && (un->un_oflags & FWRITE)) {
3296		if (un->un_dp->options & ST_REEL) {
3297			un->un_fmneeded = 2;
3298		} else {
3299			un->un_fmneeded = 1;
3300		}
3301	} else {
3302		un->un_fmneeded = 0;
3303	}
3304
3305	ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
3306	    "fmneeded = %x\n", un->un_fmneeded);
3307
3308	/*
3309	 * Make sure the density can be selected correctly.
3310	 * If WORM can only write at the append point which in most cases
3311	 * isn't BOP. st_determine_density() with a B_WRITE only attempts
3312	 * to set and try densities if a BOP.
3313	 */
3314	if (st_determine_density(un,
3315	    un->un_read_only == RDWR ? B_WRITE : B_READ)) {
3316		un->un_status = KEY_ILLEGAL_REQUEST;
3317		un->un_laststate = un->un_state;
3318		un->un_state = ST_STATE_CLOSED;
3319		ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3320		    "st_tape_init: EIO can't determine density\n");
3321		rval = EIO;
3322		goto exit;
3323	}
3324
3325	/*
3326	 * Destroy the knowledge that we have 'determined'
3327	 * density so that a later read at BOT comes along
3328	 * does the right density determination.
3329	 */
3330
3331	un->un_density_known = 0;
3332
3333
3334	/*
3335	 * Okay, the tape is loaded and either at BOT or somewhere past.
3336	 * Mark the state such that any I/O or tape space operations
3337	 * will get/set the right density, etc..
3338	 */
3339	un->un_laststate = un->un_state;
3340	un->un_lastop = ST_OP_NIL;
3341	un->un_mediastate = MTIO_INSERTED;
3342	cv_broadcast(&un->un_state_cv);
3343
3344	/*
3345	 *  Set test append flag if writing.
3346	 *  First write must check that tape is positioned correctly.
3347	 */
3348	un->un_test_append = (un->un_oflags & FWRITE);
3349
3350	/*
3351	 * if there are pending unit attention flags.
3352	 * Check that the media has not changed.
3353	 */
3354	if (un->un_unit_attention_flags) {
3355		rval = st_get_media_identification(un, st_uscsi_cmd);
3356		if (rval != 0 && rval != EACCES) {
3357			rval = EIO;
3358		}
3359		un->un_unit_attention_flags = 0;
3360	}
3361
3362exit:
3363	un->un_err_resid = 0;
3364	un->un_last_resid = 0;
3365	un->un_last_count = 0;
3366
3367	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3368	    "st_tape_init: return val = %x\n", rval);
3369	return (rval);
3370
3371}
3372
3373
3374
3375/* ARGSUSED */
3376static int
3377st_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
3378{
3379	int err = 0;
3380	int count, last_state;
3381	minor_t minor = getminor(dev);
3382#ifdef	__x86
3383	struct contig_mem *cp, *cp_temp;
3384#endif
3385
3386	GET_SOFT_STATE(dev);
3387
3388	ST_ENTR(ST_DEVINFO, st_close);
3389
3390	/*
3391	 * wait till all cmds in the pipeline have been completed
3392	 */
3393	mutex_enter(ST_MUTEX);
3394
3395	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3396	    "st_close(dev = 0x%lx, flag = %d, otyp = %d)\n", dev, flag, otyp);
3397
3398	st_wait_for_io(un);
3399
3400	/* turn off persistent errors on close, as we want close to succeed */
3401	st_turn_pe_off(un);
3402
3403	/*
3404	 * set state to indicate that we are in process of closing
3405	 */
3406	last_state = un->un_laststate = un->un_state;
3407	un->un_state = ST_STATE_CLOSING;
3408
3409	ST_POS(ST_DEVINFO, "st_close1:", &un->un_pos);
3410
3411	/*
3412	 * BSD behavior:
3413	 * a close always causes a silent span to the next file if we've hit
3414	 * an EOF (but not yet read across it).
3415	 */
3416	if ((minor & MT_BSD) && (un->un_pos.eof == ST_EOF)) {
3417		if (un->un_pos.pmode != invalid) {
3418			un->un_pos.fileno++;
3419			un->un_pos.blkno = 0;
3420		}
3421		un->un_pos.eof = ST_NO_EOF;
3422	}
3423
3424	/*
3425	 * SVR4 behavior for skipping to next file:
3426	 *
3427	 * If we have not seen a filemark, space to the next file
3428	 *
3429	 * If we have already seen the filemark we are physically in the next
3430	 * file and we only increment the filenumber
3431	 */
3432	if (((minor & (MT_BSD | MT_NOREWIND)) == MT_NOREWIND) &&
3433	    (flag & FREAD) &&		/* reading or at least asked to */
3434	    (un->un_mediastate == MTIO_INSERTED) &&	/* tape loaded */
3435	    (un->un_pos.pmode != invalid) &&		/* XXX position known */
3436	    ((un->un_pos.blkno != 0) &&			/* inside a file */
3437	    (un->un_lastop != ST_OP_WRITE) &&		/* Didn't just write */
3438	    (un->un_lastop != ST_OP_WEOF))) {		/* or write filemarks */
3439		switch (un->un_pos.eof) {
3440		case ST_NO_EOF:
3441			/*
3442			 * if we were reading and did not read the complete file
3443			 * skip to the next file, leaving the tape correctly
3444			 * positioned to read the first record of the next file
3445			 * Check first for REEL if we are at EOT by trying to
3446			 * read a block
3447			 */
3448			if ((un->un_dp->options & ST_REEL) &&
3449			    (!(un->un_dp->options & ST_READ_IGNORE_EOFS)) &&
3450			    (un->un_pos.blkno == 0)) {
3451				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
3452					ST_DEBUG2(ST_DEVINFO, st_label,
3453					    SCSI_DEBUG,
3454					    "st_close : EIO can't space\n");
3455					err = EIO;
3456					goto error_out;
3457				}
3458				if (un->un_pos.eof >= ST_EOF_PENDING) {
3459					un->un_pos.eof = ST_EOT_PENDING;
3460					un->un_pos.fileno += 1;
3461					un->un_pos.blkno   = 0;
3462					break;
3463				}
3464			}
3465			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
3466				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3467				    "st_close: EIO can't space #2\n");
3468				err = EIO;
3469				goto error_out;
3470			} else {
3471				ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3472				    "st_close2: fileno=%x,blkno=%x,eof=%x\n",
3473				    un->un_pos.fileno, un->un_pos.blkno,
3474				    un->un_pos.eof);
3475				un->un_pos.eof = ST_NO_EOF;
3476			}
3477			break;
3478
3479		case ST_EOF_PENDING:
3480		case ST_EOF:
3481			un->un_pos.fileno += 1;
3482			un->un_pos.lgclblkno += 1;
3483			un->un_pos.blkno   = 0;
3484			un->un_pos.eof = ST_NO_EOF;
3485			break;
3486
3487		case ST_EOT:
3488		case ST_EOT_PENDING:
3489		case ST_EOM:
3490			/* nothing to do */
3491			break;
3492		default:
3493			ST_DEBUG(ST_DEVINFO, st_label, CE_PANIC,
3494			    "Undefined state 0x%x", un->un_pos.eof);
3495
3496		}
3497	}
3498
3499
3500	/*
3501	 * For performance reasons (HP 88780), the driver should
3502	 * postpone writing the second tape mark until just before a file
3503	 * positioning ioctl is issued (e.g., rewind).	This means that
3504	 * the user must not manually rewind the tape because the tape will
3505	 * be missing the second tape mark which marks EOM.
3506	 * However, this small performance improvement is not worth the risk.
3507	 */
3508
3509	/*
3510	 * We need to back up over the filemark we inadvertently popped
3511	 * over doing a read in between the two filemarks that constitute
3512	 * logical eot for 1/2" tapes. Note that ST_EOT_PENDING is only
3513	 * set while reading.
3514	 *
3515	 * If we happen to be at physical eot (ST_EOM) (writing case),
3516	 * the writing of filemark(s) will clear the ST_EOM state, which
3517	 * we don't want, so we save this state and restore it later.
3518	 */
3519
3520	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3521	    "flag=%x, fmneeded=%x, lastop=%x, eof=%x\n",
3522	    flag, un->un_fmneeded, un->un_lastop, un->un_pos.eof);
3523
3524	if (un->un_pos.eof == ST_EOT_PENDING) {
3525		if (minor & MT_NOREWIND) {
3526			if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3527				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3528				    "st_close: EIO can't space #3\n");
3529				err = EIO;
3530				goto error_out;
3531			} else {
3532				un->un_pos.blkno = 0;
3533				un->un_pos.eof = ST_EOT;
3534			}
3535		} else {
3536			un->un_pos.eof = ST_NO_EOF;
3537		}
3538
3539	/*
3540	 * Do we need to write a file mark?
3541	 *
3542	 * only write filemarks if there are fmks to be written and
3543	 *   - open for write (possibly read/write)
3544	 *   - the last operation was a write
3545	 * or:
3546	 *   -	opened for wronly
3547	 *   -	no data was written
3548	 */
3549	} else if ((un->un_pos.pmode != invalid) &&
3550	    (un->un_fmneeded > 0) &&
3551	    (((flag & FWRITE) &&
3552	    ((un->un_lastop == ST_OP_WRITE)||(un->un_lastop == ST_OP_WEOF))) ||
3553	    ((flag == FWRITE) && (un->un_lastop == ST_OP_NIL)))) {
3554
3555		/* save ST_EOM state */
3556		int was_at_eom = (un->un_pos.eof == ST_EOM) ? 1 : 0;
3557
3558		/*
3559		 * Note that we will write a filemark if we had opened
3560		 * the tape write only and no data was written, thus
3561		 * creating a null file.
3562		 *
3563		 * If the user already wrote one, we only have to write 1 more.
3564		 * If they wrote two, we don't have to write any.
3565		 */
3566
3567		count = un->un_fmneeded;
3568		if (count > 0) {
3569			if (st_cmd(un, SCMD_WRITE_FILE_MARK, count, SYNC_CMD)) {
3570				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3571				    "st_close : EIO can't wfm\n");
3572				err = EIO;
3573				goto error_out;
3574			}
3575			if ((un->un_dp->options & ST_REEL) &&
3576			    (minor & MT_NOREWIND)) {
3577				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
3578					ST_DEBUG2(ST_DEVINFO, st_label,
3579					    SCSI_DEBUG,
3580					    "st_close : EIO space fmk(-1)\n");
3581					err = EIO;
3582					goto error_out;
3583				}
3584				un->un_pos.eof = ST_NO_EOF;
3585				/* fix up block number */
3586				un->un_pos.blkno = 0;
3587			}
3588		}
3589
3590		/*
3591		 * If we aren't going to be rewinding, and we were at
3592		 * physical eot, restore the state that indicates we
3593		 * are at physical eot. Once you have reached physical
3594		 * eot, and you close the tape, the only thing you can
3595		 * do on the next open is to rewind. Access to trailer
3596		 * records is only allowed without closing the device.
3597		 */
3598		if ((minor & MT_NOREWIND) == 0 && was_at_eom) {
3599			un->un_pos.eof = ST_EOM;
3600		}
3601	}
3602
3603	/*
3604	 * report soft errors if enabled and available, if we never accessed
3605	 * the drive, don't get errors. This will prevent some DAT error
3606	 * messages upon LOG SENSE.
3607	 */
3608	if (st_report_soft_errors_on_close &&
3609	    (un->un_dp->options & ST_SOFT_ERROR_REPORTING) &&
3610	    (last_state != ST_STATE_OFFLINE)) {
3611		if (st_report_soft_errors(dev, flag)) {
3612			err = EIO;
3613			goto error_out;
3614		}
3615	}
3616
3617
3618	/*
3619	 * Do we need to rewind? Can we rewind?
3620	 */
3621	if ((minor & MT_NOREWIND) == 0 &&
3622	    un->un_pos.pmode != invalid && err == 0) {
3623		/*
3624		 * We'd like to rewind with the
3625		 * 'immediate' bit set, but this
3626		 * causes problems on some drives
3627		 * where subsequent opens get a
3628		 * 'NOT READY' error condition
3629		 * back while the tape is rewinding,
3630		 * which is impossible to distinguish
3631		 * from the condition of 'no tape loaded'.
3632		 *
3633		 * Also, for some targets, if you disconnect
3634		 * with the 'immediate' bit set, you don't
3635		 * actually return right away, i.e., the
3636		 * target ignores your request for immediate
3637		 * return.
3638		 *
3639		 * Instead, we'll fire off an async rewind
3640		 * command. We'll mark the device as closed,
3641		 * and any subsequent open will stall on
3642		 * the first TEST_UNIT_READY until the rewind
3643		 * completes.
3644		 */
3645
3646		/*
3647		 * Used to be if reserve was not supported we'd send an
3648		 * asynchronious rewind. Comments above may be slightly invalid
3649		 * as the immediate bit was never set. Doing an immedate rewind
3650		 * makes sense, I think fixes to not ready status might handle
3651		 * the problems described above.
3652		 */
3653		if (un->un_sd->sd_inq->inq_ansi < 2) {
3654			if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
3655				err = EIO;
3656			}
3657		} else {
3658			/* flush data for older drives per scsi spec. */
3659			if (st_cmd(un, SCMD_WRITE_FILE_MARK, 0, SYNC_CMD)) {
3660				err = EIO;
3661			} else {
3662				/* release the drive before rewind immediate */
3663				if ((un->un_rsvd_status &
3664				    (ST_RESERVE | ST_PRESERVE_RESERVE)) ==
3665				    ST_RESERVE) {
3666					if (st_reserve_release(un, ST_RELEASE,
3667					    st_uscsi_cmd)) {
3668						err = EIO;
3669					}
3670				}
3671
3672				/* send rewind with immediate bit set */
3673				if (st_cmd(un, SCMD_REWIND, 1, ASYNC_CMD)) {
3674					err = EIO;
3675				}
3676			}
3677		}
3678		/*
3679		 * Setting positions invalid in case the rewind doesn't
3680		 * happen. Drives don't like to rewind if resets happen
3681		 * they will tend to move back to where the rewind was
3682		 * issued if a reset or something happens so that if a
3683		 * write happens the data doesn't get clobbered.
3684		 *
3685		 * Not a big deal if the position is invalid when the
3686		 * open occures it will do a read position.
3687		 */
3688		un->un_pos.pmode = invalid;
3689		un->un_running.pmode = invalid;
3690
3691		if (err == EIO) {
3692			goto error_out;
3693		}
3694	}
3695
3696	/*
3697	 * eject tape if necessary
3698	 */
3699	if (un->un_eject_tape_on_failure) {
3700		un->un_eject_tape_on_failure = 0;
3701		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
3702			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3703			    "st_close : can't unload tape\n");
3704			err = EIO;
3705			goto error_out;
3706		} else {
3707			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
3708			    "st_close : tape unloaded \n");
3709			un->un_pos.eof = ST_NO_EOF;
3710			un->un_mediastate = MTIO_EJECTED;
3711		}
3712	}
3713	/*
3714	 * Release the tape unit, if default reserve/release
3715	 * behaviour.
3716	 */
3717	if ((un->un_rsvd_status &
3718	    (ST_RESERVE | ST_PRESERVE_RESERVE |
3719	    ST_APPLICATION_RESERVATIONS)) == ST_RESERVE) {
3720		(void) st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
3721	}
3722error_out:
3723	/*
3724	 * clear up state
3725	 */
3726	un->un_laststate = un->un_state;
3727	un->un_state = ST_STATE_CLOSED;
3728	un->un_lastop = ST_OP_NIL;
3729	un->un_throttle = 1;	/* assume one request at time, for now */
3730	un->un_retry_ct = 0;
3731	un->un_errno = 0;
3732	un->un_swr_token = (opaque_t)NULL;
3733	un->un_rsvd_status &= ~(ST_INIT_RESERVE);
3734
3735	/* Restore the options to the init time settings */
3736	if (un->un_init_options & ST_READ_IGNORE_ILI) {
3737		un->un_dp->options |= ST_READ_IGNORE_ILI;
3738	} else {
3739		un->un_dp->options &= ~ST_READ_IGNORE_ILI;
3740	}
3741
3742	if (un->un_init_options & ST_READ_IGNORE_EOFS) {
3743		un->un_dp->options |= ST_READ_IGNORE_EOFS;
3744	} else {
3745		un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
3746	}
3747
3748	if (un->un_init_options & ST_SHORT_FILEMARKS) {
3749		un->un_dp->options |= ST_SHORT_FILEMARKS;
3750	} else {
3751		un->un_dp->options &= ~ST_SHORT_FILEMARKS;
3752	}
3753
3754	ASSERT(mutex_owned(ST_MUTEX));
3755
3756	/*
3757	 * Signal anyone awaiting a close operation to complete.
3758	 */
3759	cv_signal(&un->un_clscv);
3760
3761	/*
3762	 * any kind of error on closing causes all state to be tossed
3763	 */
3764	if (err && un->un_status != KEY_ILLEGAL_REQUEST) {
3765		/*
3766		 * note that st_intr has already set
3767		 * un_pos.pmode to invalid.
3768		 */
3769		un->un_density_known = 0;
3770	}
3771
3772#ifdef	__x86
3773	/*
3774	 * free any contiguous mem alloc'ed for big block I/O
3775	 */
3776	cp = un->un_contig_mem;
3777	while (cp) {
3778		if (cp->cm_addr) {
3779			ddi_dma_mem_free(&cp->cm_acc_hdl);
3780		}
3781		cp_temp = cp;
3782		cp = cp->cm_next;
3783		kmem_free(cp_temp,
3784		    sizeof (struct contig_mem) + biosize());
3785	}
3786	un->un_contig_mem_total_num = 0;
3787	un->un_contig_mem_available_num = 0;
3788	un->un_contig_mem = NULL;
3789	un->un_max_contig_mem_len = 0;
3790#endif
3791
3792	ST_DEBUG(ST_DEVINFO, st_label, SCSI_DEBUG,
3793	    "st_close3: return val = %x, fileno=%x, blkno=%x, eof=%x\n",
3794	    err, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
3795
3796	mutex_exit(ST_MUTEX);
3797	return (err);
3798}
3799
3800/*
3801 * These routines perform raw i/o operations.
3802 */
3803
3804/* ARGSUSED2 */
3805static int
3806st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3807{
3808#ifdef STDEBUG
3809	GET_SOFT_STATE(dev);
3810	ST_ENTR(ST_DEVINFO, st_aread);
3811#endif
3812	return (st_arw(dev, aio, B_READ));
3813}
3814
3815
3816/* ARGSUSED2 */
3817static int
3818st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
3819{
3820#ifdef STDEBUG
3821	GET_SOFT_STATE(dev);
3822	ST_ENTR(ST_DEVINFO, st_awrite);
3823#endif
3824	return (st_arw(dev, aio, B_WRITE));
3825}
3826
3827
3828
3829/* ARGSUSED */
3830static int
3831st_read(dev_t dev, struct uio *uiop, cred_t *cred_p)
3832{
3833#ifdef STDEBUG
3834	GET_SOFT_STATE(dev);
3835	ST_ENTR(ST_DEVINFO, st_read);
3836#endif
3837	return (st_rw(dev, uiop, B_READ));
3838}
3839
3840/* ARGSUSED */
3841static int
3842st_write(dev_t dev, struct uio *uiop, cred_t *cred_p)
3843{
3844#ifdef STDEBUG
3845	GET_SOFT_STATE(dev);
3846	ST_ENTR(ST_DEVINFO, st_write);
3847#endif
3848	return (st_rw(dev, uiop, B_WRITE));
3849}
3850
3851/*
3852 * Due to historical reasons, old limits are: For variable-length devices:
3853 * if greater than 64KB - 1 (ST_MAXRECSIZE_VARIABLE), block into 64 KB - 2
3854 * ST_MAXRECSIZE_VARIABLE_LIMIT) requests; otherwise,
3855 * (let it through unmodified. For fixed-length record devices:
3856 * 63K (ST_MAXRECSIZE_FIXED) is max (default minphys).
3857 *
3858 * The new limits used are un_maxdma (retrieved using scsi_ifgetcap()
3859 * from the HBA) and un_maxbsize (retrieved by sending SCMD_READ_BLKLIM
3860 * command to the drive).
3861 *
3862 */
3863static void
3864st_minphys(struct buf *bp)
3865{
3866	struct scsi_tape *un;
3867
3868	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
3869
3870	ST_FUNC(ST_DEVINFO, st_minphys);
3871
3872	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3873	    "st_minphys(bp = 0x%p): b_bcount = 0x%lx\n", (void *)bp,
3874	    bp->b_bcount);
3875
3876	if (un->un_allow_large_xfer) {
3877
3878		/*
3879		 * check un_maxbsize for variable length devices only
3880		 */
3881		if (un->un_bsize == 0 && bp->b_bcount > un->un_maxbsize) {
3882			bp->b_bcount = un->un_maxbsize;
3883		}
3884		/*
3885		 * can't go more that HBA maxdma limit in either fixed-length
3886		 * or variable-length tape drives.
3887		 */
3888		if (bp->b_bcount > un->un_maxdma) {
3889			bp->b_bcount = un->un_maxdma;
3890		}
3891	} else {
3892
3893		/*
3894		 *  use old fixed limits
3895		 */
3896		if (un->un_bsize == 0) {
3897			if (bp->b_bcount > ST_MAXRECSIZE_VARIABLE) {
3898				bp->b_bcount = ST_MAXRECSIZE_VARIABLE_LIMIT;
3899			}
3900		} else {
3901			if (bp->b_bcount > ST_MAXRECSIZE_FIXED) {
3902				bp->b_bcount = ST_MAXRECSIZE_FIXED;
3903			}
3904		}
3905	}
3906
3907	/*
3908	 * For regular raw I/O and Fixed Block length devices, make sure
3909	 * the adjusted block count is a whole multiple of the device
3910	 * block size.
3911	 */
3912	if (bp != un->un_sbufp && un->un_bsize) {
3913		bp->b_bcount -= (bp->b_bcount % un->un_bsize);
3914	}
3915}
3916
3917static int
3918st_rw(dev_t dev, struct uio *uio, int flag)
3919{
3920	int rval = 0;
3921	long len;
3922
3923	GET_SOFT_STATE(dev);
3924
3925	ST_FUNC(ST_DEVINFO, st_rw);
3926
3927	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
3928	    "st_rw(dev = 0x%lx, flag = %s)\n", dev,
3929	    (flag == B_READ ? rd_str: wr_str));
3930
3931	/* get local copy of transfer length */
3932	len = uio->uio_iov->iov_len;
3933
3934	mutex_enter(ST_MUTEX);
3935
3936	/*
3937	 * Clear error entry stack
3938	 */
3939	st_empty_error_stack(un);
3940
3941	/*
3942	 * If in fixed block size mode and requested read or write
3943	 * is not an even multiple of that block size.
3944	 */
3945	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
3946		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3947		    "%s: not modulo %d block size\n",
3948		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
3949		rval = EINVAL;
3950	}
3951
3952	/* If device has set granularity in the READ_BLKLIM we honor it. */
3953	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
3954		scsi_log(ST_DEVINFO, st_label, CE_WARN,
3955		    "%s: not modulo %d device granularity\n",
3956		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
3957		rval = EINVAL;
3958	}
3959
3960	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
3961		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
3962		rval = EFAULT;
3963	}
3964
3965	if (rval != 0) {
3966		un->un_errno = rval;
3967		mutex_exit(ST_MUTEX);
3968		return (rval);
3969	}
3970
3971	/*
3972	 * Reset this so it can be set if Berkeley and read over a filemark.
3973	 */
3974	un->un_silent_skip = 0;
3975	mutex_exit(ST_MUTEX);
3976
3977	len = uio->uio_resid;
3978
3979	rval = physio(st_queued_strategy, (struct buf *)NULL,
3980	    dev, flag, st_minphys, uio);
3981	/*
3982	 * if we have hit logical EOT during this xfer and there is not a
3983	 * full residue, then set eof back  to ST_EOM to make sure that
3984	 * the user will see at least one zero write
3985	 * after this short write
3986	 */
3987	mutex_enter(ST_MUTEX);
3988	if (un->un_pos.eof > ST_NO_EOF) {
3989		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
3990		"eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
3991	}
3992	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
3993		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
3994			un->un_pos.eof = ST_EOM;
3995		} else if (uio->uio_resid == len) {
3996			un->un_pos.eof = ST_NO_EOF;
3997		}
3998	}
3999
4000	if (un->un_silent_skip && uio->uio_resid != len) {
4001		un->un_pos.eof = ST_EOF;
4002		un->un_pos.blkno = un->un_save_blkno;
4003		un->un_pos.fileno--;
4004	}
4005
4006	un->un_errno = rval;
4007
4008	mutex_exit(ST_MUTEX);
4009
4010	return (rval);
4011}
4012
4013static int
4014st_arw(dev_t dev, struct aio_req *aio, int flag)
4015{
4016	struct uio *uio = aio->aio_uio;
4017	int rval = 0;
4018	long len;
4019
4020	GET_SOFT_STATE(dev);
4021
4022	ST_FUNC(ST_DEVINFO, st_arw);
4023
4024	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4025	    "st_arw(dev = 0x%lx, flag = %s)\n", dev,
4026	    (flag == B_READ ? rd_str: wr_str));
4027
4028	/* get local copy of transfer length */
4029	len = uio->uio_iov->iov_len;
4030
4031	mutex_enter(ST_MUTEX);
4032
4033	/*
4034	 * If in fixed block size mode and requested read or write
4035	 * is not an even multiple of that block size.
4036	 */
4037	if ((un->un_bsize != 0) && (len % un->un_bsize != 0)) {
4038		scsi_log(ST_DEVINFO, st_label, CE_WARN,
4039		    "%s: not modulo %d block size\n",
4040		    (flag == B_WRITE) ? wr_str : rd_str, un->un_bsize);
4041		rval = EINVAL;
4042	}
4043
4044	/* If device has set granularity in the READ_BLKLIM we honor it. */
4045	if ((un->un_data_mod != 0) && (len % un->un_data_mod != 0)) {
4046		scsi_log(ST_DEVINFO, st_label, CE_WARN,
4047		    "%s: not modulo %d device granularity\n",
4048		    (flag == B_WRITE) ? wr_str : rd_str, un->un_data_mod);
4049		rval = EINVAL;
4050	}
4051
4052	if (st_recov_sz != sizeof (recov_info) && un->un_multipath) {
4053		scsi_log(ST_DEVINFO, st_label, CE_WARN, mp_misconf);
4054		rval = EFAULT;
4055	}
4056
4057	if (rval != 0) {
4058		un->un_errno = rval;
4059		mutex_exit(ST_MUTEX);
4060		return (rval);
4061	}
4062
4063	mutex_exit(ST_MUTEX);
4064
4065	len = uio->uio_resid;
4066
4067	rval =
4068	    aphysio(st_queued_strategy, anocancel, dev, flag, st_minphys, aio);
4069
4070	/*
4071	 * if we have hit logical EOT during this xfer and there is not a
4072	 * full residue, then set eof back  to ST_EOM to make sure that
4073	 * the user will see at least one zero write
4074	 * after this short write
4075	 *
4076	 * we keep this here just in case the application is not using
4077	 * persistent errors
4078	 */
4079	mutex_enter(ST_MUTEX);
4080	if (un->un_pos.eof > ST_NO_EOF) {
4081		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4082		    "eof=%d resid=%lx\n", un->un_pos.eof, uio->uio_resid);
4083	}
4084	if (un->un_pos.eof >= ST_EOM && (flag == B_WRITE)) {
4085		if ((uio->uio_resid != len) && (uio->uio_resid != 0)) {
4086			un->un_pos.eof = ST_EOM;
4087		} else if (uio->uio_resid == len &&
4088		    !(un->un_persistence && un->un_persist_errors)) {
4089			un->un_pos.eof = ST_NO_EOF;
4090		}
4091	}
4092	un->un_errno = rval;
4093	mutex_exit(ST_MUTEX);
4094
4095	return (rval);
4096}
4097
4098
4099
4100static int
4101st_queued_strategy(buf_t *bp)
4102{
4103	struct scsi_tape *un;
4104	char reading = bp->b_flags & B_READ;
4105	int wasopening = 0;
4106
4107	/*
4108	 * validate arguments
4109	 */
4110	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4111	if (un == NULL) {
4112		bp->b_resid = bp->b_bcount;
4113		bioerror(bp, ENXIO);
4114		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4115		    "st_queued_strategy: ENXIO error exit\n");
4116		biodone(bp);
4117		return (0);
4118	}
4119
4120	ST_ENTR(ST_DEVINFO, st_queued_strategy);
4121
4122	mutex_enter(ST_MUTEX);
4123
4124	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4125		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4126	}
4127
4128	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4129	    "st_queued_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4130	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4131
4132	/*
4133	 * If persistent errors have been flagged, just nix this one. We wait
4134	 * for any outstanding I/O's below, so we will be in order.
4135	 */
4136	if (un->un_persistence && un->un_persist_errors) {
4137		goto exit;
4138	}
4139
4140	/*
4141	 * If last command was non queued, wait till it finishes.
4142	 */
4143	while (un->un_sbuf_busy) {
4144		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
4145		/* woke up because of an error */
4146		if (un->un_persistence && un->un_persist_errors) {
4147			goto exit;
4148		}
4149	}
4150
4151	/*
4152	 * s_buf and recovery commands shouldn't come here.
4153	 */
4154	ASSERT(bp != un->un_recov_buf);
4155	ASSERT(bp != un->un_sbufp);
4156
4157	/*
4158	 * If we haven't done/checked reservation on the tape unit
4159	 * do it now.
4160	 */
4161	if ((un->un_rsvd_status &
4162	    (ST_RESERVE | ST_APPLICATION_RESERVATIONS)) == 0) {
4163		if ((un->un_dp->options & ST_NO_RESERVE_RELEASE) == 0) {
4164			if (st_reserve_release(un, ST_RESERVE, st_uscsi_cmd)) {
4165				st_bioerror(bp, un->un_errno);
4166				goto exit;
4167			}
4168		} else if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4169			/*
4170			 * Enter here to restore position for possible
4171			 * resets when the device was closed and opened
4172			 * in O_NDELAY mode subsequently
4173			 */
4174			un->un_state = ST_STATE_INITIALIZING;
4175			(void) st_cmd(un, SCMD_TEST_UNIT_READY,
4176			    0, SYNC_CMD);
4177			un->un_state = ST_STATE_OPEN_PENDING_IO;
4178		}
4179		un->un_rsvd_status |= ST_INIT_RESERVE;
4180	}
4181
4182	/*
4183	 * If we are offline, we have to initialize everything first.
4184	 * This is to handle either when opened with O_NDELAY, or
4185	 * we just got a new tape in the drive, after an offline.
4186	 * We don't observe O_NDELAY past the open,
4187	 * as it will not make sense for tapes.
4188	 */
4189	if (un->un_state == ST_STATE_OFFLINE || un->un_restore_pos) {
4190		/*
4191		 * reset state to avoid recursion
4192		 */
4193		un->un_laststate = un->un_state;
4194		un->un_state = ST_STATE_INITIALIZING;
4195		if (st_tape_init(un)) {
4196			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4197			    "stioctl : OFFLINE init failure ");
4198			un->un_state = ST_STATE_OFFLINE;
4199			un->un_pos.pmode = invalid;
4200			goto b_done_err;
4201		}
4202		/* un_restore_pos make invalid */
4203		un->un_state = ST_STATE_OPEN_PENDING_IO;
4204		un->un_restore_pos = 0;
4205	}
4206	/*
4207	 * Check for legal operations
4208	 */
4209	if (un->un_pos.pmode == invalid) {
4210		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4211		    "strategy with un->un_pos.pmode invalid\n");
4212		goto b_done_err;
4213	}
4214
4215	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4216	    "st_queued_strategy(): regular io\n");
4217
4218	/*
4219	 * Process this first. If we were reading, and we're pending
4220	 * logical eot, that means we've bumped one file mark too far.
4221	 */
4222
4223	/*
4224	 * Recursion warning: st_cmd will route back through here.
4225	 * Not anymore st_cmd will go through st_strategy()!
4226	 */
4227	if (un->un_pos.eof == ST_EOT_PENDING) {
4228		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4229			un->un_pos.pmode = invalid;
4230			un->un_density_known = 0;
4231			goto b_done_err;
4232		}
4233		un->un_pos.blkno = 0; /* fix up block number.. */
4234		un->un_pos.eof = ST_EOT;
4235	}
4236
4237	/*
4238	 * If we are in the process of opening, we may have to
4239	 * determine/set the correct density. We also may have
4240	 * to do a test_append (if QIC) to see whether we are
4241	 * in a position to append to the end of the tape.
4242	 *
4243	 * If we're already at logical eot, we transition
4244	 * to ST_NO_EOF. If we're at physical eot, we punt
4245	 * to the switch statement below to handle.
4246	 */
4247	if ((un->un_state == ST_STATE_OPEN_PENDING_IO) ||
4248	    (un->un_test_append && (un->un_dp->options & ST_QIC))) {
4249
4250		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4251			if (st_determine_density(un, (int)reading)) {
4252				goto b_done_err;
4253			}
4254		}
4255
4256		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4257		    "pending_io@fileno %d rw %d qic %d eof %d\n",
4258		    un->un_pos.fileno, (int)reading,
4259		    (un->un_dp->options & ST_QIC) ? 1 : 0,
4260		    un->un_pos.eof);
4261
4262		if (!reading && un->un_pos.eof != ST_EOM) {
4263			if (un->un_pos.eof == ST_EOT) {
4264				un->un_pos.eof = ST_NO_EOF;
4265			} else if (un->un_pos.pmode != invalid &&
4266			    (un->un_dp->options & ST_QIC)) {
4267				/*
4268				 * st_test_append() will do it all
4269				 */
4270				st_test_append(bp);
4271				mutex_exit(ST_MUTEX);
4272				return (0);
4273			}
4274		}
4275		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4276			wasopening = 1;
4277		}
4278		un->un_laststate = un->un_state;
4279		un->un_state = ST_STATE_OPEN;
4280	}
4281
4282
4283	/*
4284	 * Process rest of END OF FILE and END OF TAPE conditions
4285	 */
4286
4287	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4288	    "eof=%x, wasopening=%x\n",
4289	    un->un_pos.eof, wasopening);
4290
4291	switch (un->un_pos.eof) {
4292	case ST_EOM:
4293		/*
4294		 * This allows writes to proceed past physical
4295		 * eot. We'll *really* be in trouble if the
4296		 * user continues blindly writing data too
4297		 * much past this point (unwind the tape).
4298		 * Physical eot really means 'early warning
4299		 * eot' in this context.
4300		 *
4301		 * Every other write from now on will succeed
4302		 * (if sufficient  tape left).
4303		 * This write will return with resid == count
4304		 * but the next one should be successful
4305		 *
4306		 * Note that we only transition to logical EOT
4307		 * if the last state wasn't the OPENING state.
4308		 * We explicitly prohibit running up to physical
4309		 * eot, closing the device, and then re-opening
4310		 * to proceed. Trailer records may only be gotten
4311		 * at by keeping the tape open after hitting eot.
4312		 *
4313		 * Also note that ST_EOM cannot be set by reading-
4314		 * this can only be set during writing. Reading
4315		 * up to the end of the tape gets a blank check
4316		 * or a double-filemark indication (ST_EOT_PENDING),
4317		 * and we prohibit reading after that point.
4318		 *
4319		 */
4320		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOM\n");
4321		if (wasopening == 0) {
4322			/*
4323			 * this allows st_rw() to reset it back to
4324			 * will see a zero write
4325			 */
4326			un->un_pos.eof = ST_WRITE_AFTER_EOM;
4327		}
4328		un->un_status = SUN_KEY_EOT;
4329		goto b_done;
4330
4331	case ST_WRITE_AFTER_EOM:
4332	case ST_EOT:
4333		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOT\n");
4334		un->un_status = SUN_KEY_EOT;
4335		if (SVR4_BEHAVIOR && reading) {
4336			goto b_done_err;
4337		}
4338
4339		if (reading) {
4340			goto b_done;
4341		}
4342		un->un_pos.eof = ST_NO_EOF;
4343		break;
4344
4345	case ST_EOF_PENDING:
4346		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4347		    "EOF PENDING\n");
4348		un->un_status = SUN_KEY_EOF;
4349		if (SVR4_BEHAVIOR) {
4350			un->un_pos.eof = ST_EOF;
4351			goto b_done;
4352		}
4353		/* FALLTHROUGH */
4354	case ST_EOF:
4355		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG, "EOF\n");
4356		un->un_status = SUN_KEY_EOF;
4357		if (SVR4_BEHAVIOR) {
4358			goto b_done_err;
4359		}
4360
4361		if (BSD_BEHAVIOR) {
4362			un->un_pos.eof = ST_NO_EOF;
4363			un->un_pos.fileno += 1;
4364			un->un_pos.blkno   = 0;
4365		}
4366
4367		if (reading) {
4368			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4369			    "now file %d (read)\n",
4370			    un->un_pos.fileno);
4371			goto b_done;
4372		}
4373		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4374		    "now file %d (write)\n", un->un_pos.fileno);
4375		break;
4376	default:
4377		un->un_status = 0;
4378		break;
4379	}
4380
4381	bp->b_flags &= ~(B_DONE);
4382	st_bioerror(bp, 0);
4383	bp->av_forw = NULL;
4384	bp->b_resid = 0;
4385	SET_BP_PKT(bp, 0);
4386
4387
4388	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4389	    "st_queued_strategy: cmd=0x%p  count=%ld  resid=%ld flags=0x%x"
4390	    " pkt=0x%p\n",
4391	    (void *)bp->b_forw, bp->b_bcount,
4392	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4393
4394#ifdef	__x86
4395	/*
4396	 * We will replace bp with a new bp that can do big blk xfer
4397	 * if the requested xfer size is bigger than un->un_maxdma_arch
4398	 *
4399	 * Also, we need to make sure that we're handling real I/O
4400	 * by checking group 0/1 SCSI I/O commands, if needed
4401	 */
4402	if (bp->b_bcount > un->un_maxdma_arch &&
4403	    ((uchar_t)(uintptr_t)bp->b_forw == SCMD_READ ||
4404	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_READ_G4 ||
4405	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE ||
4406	    (uchar_t)(uintptr_t)bp->b_forw == SCMD_WRITE_G4)) {
4407		mutex_exit(ST_MUTEX);
4408		bp = st_get_bigblk_bp(bp);
4409		mutex_enter(ST_MUTEX);
4410	}
4411#endif
4412
4413	/* put on wait queue */
4414	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4415	    "st_queued_strategy: un->un_quef = 0x%p, bp = 0x%p\n",
4416	    (void *)un->un_quef, (void *)bp);
4417
4418	st_add_to_queue(&un->un_quef, &un->un_quel, un->un_quel, bp);
4419
4420	ST_DO_KSTATS(bp, kstat_waitq_enter);
4421
4422	st_start(un);
4423
4424	mutex_exit(ST_MUTEX);
4425	return (0);
4426
4427b_done_err:
4428	st_bioerror(bp, EIO);
4429	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4430	    "st_queued_strategy : EIO b_done_err\n");
4431
4432b_done:
4433	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4434	    "st_queued_strategy: b_done\n");
4435
4436exit:
4437	/*
4438	 * make sure no commands are outstanding or waiting before closing,
4439	 * so we can guarantee order
4440	 */
4441	st_wait_for_io(un);
4442	un->un_err_resid = bp->b_resid = bp->b_bcount;
4443
4444	/* override errno here, if persistent errors were flagged */
4445	if (un->un_persistence && un->un_persist_errors)
4446		bioerror(bp, un->un_errno);
4447
4448	mutex_exit(ST_MUTEX);
4449
4450	biodone(bp);
4451	ASSERT(mutex_owned(ST_MUTEX) == 0);
4452	return (0);
4453}
4454
4455
4456static int
4457st_strategy(struct buf *bp)
4458{
4459	struct scsi_tape *un;
4460
4461	/*
4462	 * validate arguments
4463	 */
4464	un = ddi_get_soft_state(st_state, MTUNIT(bp->b_edev));
4465	if (un == NULL) {
4466		bp->b_resid = bp->b_bcount;
4467		bioerror(bp, ENXIO);
4468		ST_DEBUG6(NULL, st_label, SCSI_DEBUG,
4469		    "st_strategy: ENXIO error exit\n");
4470
4471		biodone(bp);
4472		return (0);
4473
4474	}
4475
4476	ST_ENTR(ST_DEVINFO, st_strategy);
4477
4478	mutex_enter(ST_MUTEX);
4479
4480	while (un->un_pwr_mgmt == ST_PWR_SUSPENDED) {
4481		cv_wait(&un->un_suspend_cv, ST_MUTEX);
4482	}
4483
4484	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4485	    "st_strategy(): bcount=0x%lx, fileno=%d, blkno=%x, eof=%d\n",
4486	    bp->b_bcount, un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
4487
4488	ASSERT((bp == un->un_recov_buf) || (bp == un->un_sbufp));
4489
4490	bp->b_flags &= ~(B_DONE);
4491	st_bioerror(bp, 0);
4492	bp->av_forw = NULL;
4493	bp->b_resid = 0;
4494	SET_BP_PKT(bp, 0);
4495
4496
4497	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4498	    "st_strategy: cmd=0x%x  count=%ld  resid=%ld flags=0x%x"
4499	    " pkt=0x%p\n",
4500	    (unsigned char)(uintptr_t)bp->b_forw, bp->b_bcount,
4501	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
4502	ST_DO_KSTATS(bp, kstat_waitq_enter);
4503
4504	st_start(un);
4505
4506	mutex_exit(ST_MUTEX);
4507	return (0);
4508}
4509
4510/*
4511 * this routine spaces forward over filemarks
4512 */
4513static int
4514st_space_fmks(struct scsi_tape *un, int64_t count)
4515{
4516	int rval = 0;
4517
4518	ST_FUNC(ST_DEVINFO, st_space_fmks);
4519
4520	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4521	    "st_space_fmks(dev = 0x%lx, count = %"PRIx64")\n",
4522	    un->un_dev, count);
4523
4524	ASSERT(mutex_owned(ST_MUTEX));
4525
4526	/*
4527	 * the risk with doing only one space operation is that we
4528	 * may accidentily jump in old data
4529	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4530	 * because the 8200 does not append a marker; in order not to
4531	 * sacrifice the fast file skip, we do a slow skip if the low
4532	 * density device has been opened
4533	 */
4534
4535	if ((un->un_dp->options & ST_KNOWS_EOD) &&
4536	    !((un->un_dp->type == ST_TYPE_EXB8500 &&
4537	    MT_DENSITY(un->un_dev) == 0))) {
4538		if (st_cmd(un, SCMD_SPACE, Fmk(count), SYNC_CMD)) {
4539			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4540			    "space_fmks : EIO can't do space cmd #1\n");
4541			rval = EIO;
4542		}
4543	} else {
4544		while (count > 0) {
4545			if (st_cmd(un, SCMD_SPACE, Fmk(1), SYNC_CMD)) {
4546				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4547				    "space_fmks : EIO can't do space cmd #2\n");
4548				rval = EIO;
4549				break;
4550			}
4551			count -= 1;
4552			/*
4553			 * read a block to see if we have reached
4554			 * end of medium (double filemark for reel or
4555			 * medium error for others)
4556			 */
4557			if (count > 0) {
4558				if (st_cmd(un, SCMD_SPACE, Blk(1), SYNC_CMD)) {
4559					ST_DEBUG2(ST_DEVINFO, st_label,
4560					    SCSI_DEBUG,
4561					    "space_fmks : EIO can't do "
4562					    "space cmd #3\n");
4563					rval = EIO;
4564					break;
4565				}
4566				if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4567				    (un->un_dp->options & ST_REEL)) {
4568					un->un_status = SUN_KEY_EOT;
4569					ST_DEBUG2(ST_DEVINFO, st_label,
4570					    SCSI_DEBUG,
4571					    "space_fmks : EIO ST_REEL\n");
4572					rval = EIO;
4573					break;
4574				} else if (IN_EOF(un->un_pos)) {
4575					un->un_pos.eof = ST_NO_EOF;
4576					un->un_pos.fileno++;
4577					un->un_pos.blkno = 0;
4578					count--;
4579				} else if (un->un_pos.eof > ST_EOF) {
4580					ST_DEBUG2(ST_DEVINFO, st_label,
4581					    SCSI_DEBUG,
4582					    "space_fmks, EIO > ST_EOF\n");
4583					rval = EIO;
4584					break;
4585				}
4586
4587			}
4588		}
4589		un->un_err_resid = count;
4590		COPY_POS(&un->un_pos, &un->un_err_pos);
4591	}
4592	ASSERT(mutex_owned(ST_MUTEX));
4593	return (rval);
4594}
4595
4596/*
4597 * this routine spaces to EOD
4598 *
4599 * it keeps track of the current filenumber and returns the filenumber after
4600 * the last successful space operation, we keep the number high because as
4601 * tapes are getting larger, the possibility of more and more files exist,
4602 * 0x100000 (1 Meg of files) probably will never have to be changed any time
4603 * soon
4604 */
4605#define	MAX_SKIP	0x100000 /* somewhat arbitrary */
4606
4607static int
4608st_find_eod(struct scsi_tape *un)
4609{
4610	tapepos_t savepos;
4611	int64_t sp_type;
4612	int result;
4613
4614	if (un == NULL) {
4615		return (-1);
4616	}
4617
4618	ST_FUNC(ST_DEVINFO, st_find_eod);
4619
4620	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4621	    "st_find_eod(dev = 0x%lx): fileno = %d\n", un->un_dev,
4622	    un->un_pos.fileno);
4623
4624	ASSERT(mutex_owned(ST_MUTEX));
4625
4626	COPY_POS(&savepos, &un->un_pos);
4627
4628	/*
4629	 * see if the drive is smart enough to do the skips in
4630	 * one operation; 1/2" use two filemarks
4631	 * the exabyte 8500 reading 8200 tapes cannot use KNOWS_EOD
4632	 * because the 8200 does not append a marker; in order not to
4633	 * sacrifice the fast file skip, we do a slow skip if the low
4634	 * density device has been opened
4635	 */
4636	if ((un->un_dp->options & ST_KNOWS_EOD) != 0) {
4637		if ((un->un_dp->type == ST_TYPE_EXB8500) &&
4638		    (MT_DENSITY(un->un_dev) == 0)) {
4639			sp_type = Fmk(1);
4640		} else if (un->un_pos.pmode == logical) {
4641			sp_type = SPACE(SP_EOD, 0);
4642		} else {
4643			sp_type = Fmk(MAX_SKIP);
4644		}
4645	} else {
4646		sp_type = Fmk(1);
4647	}
4648
4649	for (;;) {
4650		result = st_cmd(un, SCMD_SPACE, sp_type, SYNC_CMD);
4651
4652		if (result == 0) {
4653			COPY_POS(&savepos, &un->un_pos);
4654		}
4655
4656		if (sp_type == SPACE(SP_EOD, 0)) {
4657			if (result != 0) {
4658				sp_type = Fmk(MAX_SKIP);
4659				continue;
4660			}
4661
4662			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4663			    "st_find_eod: 0x%"PRIx64"\n",
4664			    savepos.lgclblkno);
4665			/*
4666			 * What we return will become the current file position.
4667			 * After completing the space command with the position
4668			 * mode that is not invalid a read position command will
4669			 * be automaticly issued. If the drive support the long
4670			 * read position format a valid file position can be
4671			 * returned.
4672			 */
4673			return (un->un_pos.fileno);
4674		}
4675
4676		if (result != 0) {
4677			break;
4678		}
4679
4680		ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4681		    "count=%"PRIx64", eof=%x, status=%x\n",
4682		    SPACE_CNT(sp_type),  un->un_pos.eof, un->un_status);
4683
4684		/*
4685		 * If we're not EOM smart,  space a record
4686		 * to see whether we're now in the slot between
4687		 * the two sequential filemarks that logical
4688		 * EOM consists of (REEL) or hit nowhere land
4689		 * (8mm).
4690		 */
4691		if (sp_type == Fmk(1)) {
4692			/*
4693			 * no fast skipping, check a record
4694			 */
4695			if (st_cmd(un, SCMD_SPACE, Blk((1)), SYNC_CMD)) {
4696				break;
4697			}
4698			if ((un->un_pos.eof >= ST_EOF_PENDING) &&
4699			    (un->un_dp->options & ST_REEL)) {
4700				un->un_status = KEY_BLANK_CHECK;
4701				un->un_pos.fileno++;
4702				un->un_pos.blkno = 0;
4703				break;
4704			}
4705			if (IN_EOF(un->un_pos)) {
4706				un->un_pos.eof = ST_NO_EOF;
4707				un->un_pos.fileno++;
4708				un->un_pos.blkno = 0;
4709			}
4710			if (un->un_pos.eof > ST_EOF) {
4711				break;
4712			}
4713		} else {
4714			if (un->un_pos.eof > ST_EOF) {
4715				break;
4716			}
4717		}
4718	}
4719
4720	if (un->un_dp->options & ST_KNOWS_EOD) {
4721		COPY_POS(&savepos, &un->un_pos);
4722	}
4723
4724	ASSERT(mutex_owned(ST_MUTEX));
4725
4726	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
4727	    "st_find_eod: %x\n", savepos.fileno);
4728	return (savepos.fileno);
4729}
4730
4731
4732/*
4733 * this routine is frequently used in ioctls below;
4734 * it determines whether we know the density and if not will
4735 * determine it
4736 * if we have written the tape before, one or more filemarks are written
4737 *
4738 * depending on the stepflag, the head is repositioned to where it was before
4739 * the filemarks were written in order not to confuse step counts
4740 */
4741#define	STEPBACK    0
4742#define	NO_STEPBACK 1
4743
4744static int
4745st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag)
4746{
4747
4748	GET_SOFT_STATE(dev);
4749
4750	ST_FUNC(ST_DEVINFO, st_check_density_or_wfm);
4751
4752	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4753	    "st_check_density_or_wfm(dev= 0x%lx, wfm= %d, mode= %d, stpflg= %d)"
4754	    "\n", dev, wfm, mode, stepflag);
4755
4756	ASSERT(mutex_owned(ST_MUTEX));
4757
4758	/*
4759	 * If we don't yet know the density of the tape we have inserted,
4760	 * we have to either unconditionally set it (if we're 'writing'),
4761	 * or we have to determine it. As side effects, check for any
4762	 * write-protect errors, and for the need to put out any file-marks
4763	 * before positioning a tape.
4764	 *
4765	 * If we are going to be spacing forward, and we haven't determined
4766	 * the tape density yet, we have to do so now...
4767	 */
4768	if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
4769		if (st_determine_density(un, mode)) {
4770			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4771			    "check_density_or_wfm : EIO can't determine "
4772			    "density\n");
4773			un->un_errno = EIO;
4774			return (EIO);
4775		}
4776		/*
4777		 * Presumably we are at BOT. If we attempt to write, it will
4778		 * either work okay, or bomb. We don't do a st_test_append
4779		 * unless we're past BOT.
4780		 */
4781		un->un_laststate = un->un_state;
4782		un->un_state = ST_STATE_OPEN;
4783
4784	} else if (un->un_pos.pmode != invalid && un->un_fmneeded > 0 &&
4785	    ((un->un_lastop == ST_OP_WEOF && wfm) ||
4786	    (un->un_lastop == ST_OP_WRITE && wfm))) {
4787
4788		tapepos_t spos;
4789
4790		COPY_POS(&spos, &un->un_pos);
4791
4792		/*
4793		 * We need to write one or two filemarks.
4794		 * In the case of the HP, we need to
4795		 * position the head between the two
4796		 * marks.
4797		 */
4798		if ((un->un_fmneeded > 0) || (un->un_lastop == ST_OP_WEOF)) {
4799			wfm = un->un_fmneeded;
4800			un->un_fmneeded = 0;
4801		}
4802
4803		if (st_write_fm(dev, wfm)) {
4804			un->un_pos.pmode = invalid;
4805			un->un_density_known = 0;
4806			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4807			    "check_density_or_wfm : EIO can't write fm\n");
4808			un->un_errno = EIO;
4809			return (EIO);
4810		}
4811
4812		if (stepflag == STEPBACK) {
4813			if (st_cmd(un, SCMD_SPACE, Fmk(-wfm), SYNC_CMD)) {
4814				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4815				    "check_density_or_wfm : EIO can't space "
4816				    "(-wfm)\n");
4817				un->un_errno = EIO;
4818				return (EIO);
4819			}
4820			COPY_POS(&un->un_pos, &spos);
4821		}
4822	}
4823
4824	/*
4825	 * Whatever we do at this point clears the state of the eof flag.
4826	 */
4827
4828	un->un_pos.eof = ST_NO_EOF;
4829
4830	/*
4831	 * If writing, let's check that we're positioned correctly
4832	 * at the end of tape before issuing the next write.
4833	 */
4834	if (un->un_read_only == RDWR) {
4835		un->un_test_append = 1;
4836	}
4837
4838	ASSERT(mutex_owned(ST_MUTEX));
4839	return (0);
4840}
4841
4842
4843/*
4844 * Wait for all outstaning I/O's to complete
4845 *
4846 * we wait on both ncmds and the wait queue for times when we are flushing
4847 * after persistent errors are flagged, which is when ncmds can be 0, and the
4848 * queue can still have I/O's.  This way we preserve order of biodone's.
4849 */
4850static void
4851st_wait_for_io(struct scsi_tape *un)
4852{
4853	ST_FUNC(ST_DEVINFO, st_wait_for_io);
4854	ASSERT(mutex_owned(ST_MUTEX));
4855	while ((un->un_ncmds) || (un->un_quef) || (un->un_runqf)) {
4856		cv_wait(&un->un_queue_cv, ST_MUTEX);
4857	}
4858}
4859
4860/*
4861 * This routine implements the ioctl calls.  It is called
4862 * from the device switch at normal priority.
4863 */
4864/*ARGSUSED*/
4865static int
4866st_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p,
4867    int *rval_p)
4868{
4869	int tmp, rval = 0;
4870
4871	GET_SOFT_STATE(dev);
4872
4873	ST_ENTR(ST_DEVINFO, st_ioctl);
4874
4875	mutex_enter(ST_MUTEX);
4876
4877	ASSERT(un->un_recov_buf_busy == 0);
4878
4879	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
4880	    "st_ioctl(): fileno=%x, blkno=%x, eof=%x, state = %d, "
4881	    "pe_flag = %d\n",
4882	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof, un->un_state,
4883	    un->un_persistence && un->un_persist_errors);
4884
4885	/*
4886	 * We don't want to block on these, so let them through
4887	 * and we don't care about setting driver states here.
4888	 */
4889	if ((cmd == MTIOCGETDRIVETYPE) ||
4890	    (cmd == MTIOCGUARANTEEDORDER) ||
4891	    (cmd == MTIOCPERSISTENTSTATUS)) {
4892		goto check_commands;
4893	}
4894
4895	/*
4896	 * We clear error entry stack except command
4897	 * MTIOCGETERROR and MTIOCGET
4898	 */
4899	if ((cmd != MTIOCGETERROR) &&
4900	    (cmd != MTIOCGET)) {
4901		st_empty_error_stack(un);
4902	}
4903
4904	/*
4905	 * wait for all outstanding commands to complete, or be dequeued.
4906	 * And because ioctl's are synchronous commands, any return value
4907	 * after this,  will be in order
4908	 */
4909	st_wait_for_io(un);
4910
4911	/*
4912	 * allow only a through clear errors and persistent status, and
4913	 * status
4914	 */
4915	if (un->un_persistence && un->un_persist_errors) {
4916		if ((cmd == MTIOCLRERR) ||
4917		    (cmd == MTIOCPERSISTENT) ||
4918		    (cmd == MTIOCGET)) {
4919			goto check_commands;
4920		} else {
4921			rval = un->un_errno;
4922			goto exit;
4923		}
4924	}
4925
4926	ASSERT(un->un_throttle != 0);
4927	un->un_throttle = 1;	/* > 1 will never happen here */
4928	un->un_errno = 0;	/* start clean from here */
4929
4930	/*
4931	 * first and foremost, handle any ST_EOT_PENDING cases.
4932	 * That is, if a logical eot is pending notice, notice it.
4933	 */
4934	if (un->un_pos.eof == ST_EOT_PENDING) {
4935		int resid = un->un_err_resid;
4936		uchar_t status = un->un_status;
4937		uchar_t lastop = un->un_lastop;
4938
4939		if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
4940			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
4941			    "stioctl : EIO can't space fmk(-1)\n");
4942			rval = EIO;
4943			goto exit;
4944		}
4945		un->un_lastop = lastop; /* restore last operation */
4946		if (status == SUN_KEY_EOF) {
4947			un->un_status = SUN_KEY_EOT;
4948		} else {
4949			un->un_status = status;
4950		}
4951		un->un_err_resid  = resid;
4952		/* fix up block number */
4953		un->un_err_pos.blkno = un->un_pos.blkno = 0;
4954		/* now we're at logical eot */
4955		un->un_pos.eof = ST_EOT;
4956	}
4957
4958	/*
4959	 * now, handle the rest of the situations
4960	 */
4961check_commands:
4962	switch (cmd) {
4963	case MTIOCGET:
4964	{
4965#ifdef _MULTI_DATAMODEL
4966		/*
4967		 * For use when a 32 bit app makes a call into a
4968		 * 64 bit ioctl
4969		 */
4970		struct mtget32		mtg_local32;
4971		struct mtget32		*mtget_32 = &mtg_local32;
4972#endif /* _MULTI_DATAMODEL */
4973
4974			/* Get tape status */
4975		struct mtget mtg_local;
4976		struct mtget *mtget = &mtg_local;
4977		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
4978		    "st_ioctl: MTIOCGET\n");
4979
4980		bzero((caddr_t)mtget, sizeof (struct mtget));
4981		mtget->mt_erreg = un->un_status;
4982		mtget->mt_resid = un->un_err_resid;
4983		mtget->mt_dsreg = un->un_retry_ct;
4984		if (un->un_err_pos.pmode == legacy) {
4985			mtget->mt_fileno = un->un_err_pos.fileno;
4986		} else {
4987			mtget->mt_fileno = -1;
4988		}
4989		/*
4990		 * If the value is positive fine.
4991		 * If its negative we need to return a value based on the
4992		 * old way if counting backwards from INF (1,000,000,000).
4993		 */
4994		if (un->un_err_pos.blkno >= 0) {
4995			mtget->mt_blkno = un->un_err_pos.blkno;
4996		} else {
4997			mtget->mt_blkno = INF + 1 - (-un->un_err_pos.blkno);
4998		}
4999		mtget->mt_type = un->un_dp->type;
5000		mtget->mt_flags = MTF_SCSI | MTF_ASF;
5001		if (un->un_read_pos_type != NO_POS) {
5002			mtget->mt_flags |= MTF_LOGICAL_BLOCK;
5003		}
5004		if (un->un_dp->options & ST_REEL) {
5005			mtget->mt_flags |= MTF_REEL;
5006			mtget->mt_bf = 20;
5007		} else {		/* 1/4" cartridges */
5008			switch (mtget->mt_type) {
5009			/* Emulex cartridge tape */
5010			case MT_ISMT02:
5011				mtget->mt_bf = 40;
5012				break;
5013			default:
5014				mtget->mt_bf = 126;
5015				break;
5016			}
5017		}
5018
5019		/*
5020		 * If large transfers are allowed and drive options
5021		 * has no record size limit set. Calculate blocking
5022		 * factor from the lesser of maxbsize and maxdma.
5023		 */
5024		if ((un->un_allow_large_xfer) &&
5025		    (un->un_dp->options & ST_NO_RECSIZE_LIMIT)) {
5026			mtget->mt_bf = min(un->un_maxbsize,
5027			    un->un_maxdma) / SECSIZE;
5028		}
5029
5030		if (un->un_read_only == WORM ||
5031		    un->un_read_only == RDWORM) {
5032			mtget->mt_flags |= MTF_WORM_MEDIA;
5033		}
5034
5035		/*
5036		 * In persistent error mode sending a non-queued can hang
5037		 * because this ioctl gets to be run without turning off
5038		 * persistense. Fake the answer based on previous info.
5039		 */
5040		if (un->un_persistence) {
5041			rval = 0;
5042		} else {
5043			rval = st_check_clean_bit(un);
5044		}
5045		if (rval == 0) {
5046			/*
5047			 * If zero is returned or in persistent mode,
5048			 * use the old data.
5049			 */
5050			if ((un->un_HeadClean & (TAPE_ALERT_SUPPORTED |
5051			    TAPE_SEQUENTIAL_SUPPORTED|TAPE_ALERT_NOT_SUPPORTED))
5052			    != TAPE_ALERT_NOT_SUPPORTED) {
5053				mtget->mt_flags |= MTF_TAPE_CLN_SUPPORTED;
5054			}
5055			if (un->un_HeadClean & (TAPE_PREVIOUSLY_DIRTY |
5056			    TAPE_ALERT_STILL_DIRTY)) {
5057				mtget->mt_flags |= MTF_TAPE_HEAD_DIRTY;
5058			}
5059		} else {
5060			mtget->mt_flags |= (ushort_t)rval;
5061			rval = 0;
5062		}
5063
5064		un->un_status = 0;		/* Reset status */
5065		un->un_err_resid = 0;
5066		tmp = sizeof (struct mtget);
5067
5068#ifdef _MULTI_DATAMODEL
5069
5070		switch (ddi_model_convert_from(flag & FMODELS)) {
5071		case DDI_MODEL_ILP32:
5072			/*
5073			 * Convert 64 bit back to 32 bit before doing
5074			 * copyout. This is what the ILP32 app expects.
5075			 */
5076			mtget_32->mt_erreg = mtget->mt_erreg;
5077			mtget_32->mt_resid = mtget->mt_resid;
5078			mtget_32->mt_dsreg = mtget->mt_dsreg;
5079			mtget_32->mt_fileno = (daddr32_t)mtget->mt_fileno;
5080			mtget_32->mt_blkno = (daddr32_t)mtget->mt_blkno;
5081			mtget_32->mt_type = mtget->mt_type;
5082			mtget_32->mt_flags = mtget->mt_flags;
5083			mtget_32->mt_bf = mtget->mt_bf;
5084
5085			if (ddi_copyout(mtget_32, (void *)arg,
5086			    sizeof (struct mtget32), flag)) {
5087				rval = EFAULT;
5088			}
5089			break;
5090
5091		case DDI_MODEL_NONE:
5092			if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5093				rval = EFAULT;
5094			}
5095			break;
5096		}
5097#else /* ! _MULTI_DATAMODE */
5098		if (ddi_copyout(mtget, (void *)arg, tmp, flag)) {
5099			rval = EFAULT;
5100		}
5101#endif /* _MULTI_DATAMODE */
5102
5103		break;
5104	}
5105	case MTIOCGETERROR:
5106			/*
5107			 * get error entry from error stack
5108			 */
5109			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5110			    "st_ioctl: MTIOCGETERROR\n");
5111
5112			rval = st_get_error_entry(un, arg, flag);
5113
5114			break;
5115
5116	case MTIOCSTATE:
5117		{
5118			/*
5119			 * return when media presence matches state
5120			 */
5121			enum mtio_state state;
5122
5123			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5124			    "st_ioctl: MTIOCSTATE\n");
5125
5126			if (ddi_copyin((void *)arg, &state, sizeof (int), flag))
5127				rval = EFAULT;
5128
5129			mutex_exit(ST_MUTEX);
5130
5131			rval = st_check_media(dev, state);
5132
5133			mutex_enter(ST_MUTEX);
5134
5135			if (rval != 0) {
5136				break;
5137			}
5138
5139			if (ddi_copyout(&un->un_mediastate, (void *)arg,
5140			    sizeof (int), flag))
5141				rval = EFAULT;
5142			break;
5143
5144		}
5145
5146	case MTIOCGETDRIVETYPE:
5147		{
5148#ifdef _MULTI_DATAMODEL
5149		/*
5150		 * For use when a 32 bit app makes a call into a
5151		 * 64 bit ioctl
5152		 */
5153		struct mtdrivetype_request32	mtdtrq32;
5154#endif /* _MULTI_DATAMODEL */
5155
5156			/*
5157			 * return mtdrivetype
5158			 */
5159			struct mtdrivetype_request mtdtrq;
5160			struct mtdrivetype mtdrtyp;
5161			struct mtdrivetype *mtdt = &mtdrtyp;
5162			struct st_drivetype *stdt = un->un_dp;
5163
5164			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5165			    "st_ioctl: MTIOCGETDRIVETYPE\n");
5166
5167#ifdef _MULTI_DATAMODEL
5168		switch (ddi_model_convert_from(flag & FMODELS)) {
5169		case DDI_MODEL_ILP32:
5170		{
5171			if (ddi_copyin((void *)arg, &mtdtrq32,
5172			    sizeof (struct mtdrivetype_request32), flag)) {
5173				rval = EFAULT;
5174				break;
5175			}
5176			mtdtrq.size = mtdtrq32.size;
5177			mtdtrq.mtdtp =
5178			    (struct  mtdrivetype *)(uintptr_t)mtdtrq32.mtdtp;
5179			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5180			    "st_ioctl: size 0x%x\n", mtdtrq.size);
5181			break;
5182		}
5183		case DDI_MODEL_NONE:
5184			if (ddi_copyin((void *)arg, &mtdtrq,
5185			    sizeof (struct mtdrivetype_request), flag)) {
5186				rval = EFAULT;
5187				break;
5188			}
5189			break;
5190		}
5191
5192#else /* ! _MULTI_DATAMODEL */
5193		if (ddi_copyin((void *)arg, &mtdtrq,
5194		    sizeof (struct mtdrivetype_request), flag)) {
5195			rval = EFAULT;
5196			break;
5197		}
5198#endif /* _MULTI_DATAMODEL */
5199
5200			/*
5201			 * if requested size is < 0 then return
5202			 * error.
5203			 */
5204			if (mtdtrq.size < 0) {
5205				rval = EINVAL;
5206				break;
5207			}
5208			bzero(mtdt, sizeof (struct mtdrivetype));
5209			(void) strncpy(mtdt->name, stdt->name, ST_NAMESIZE);
5210			(void) strncpy(mtdt->vid, stdt->vid, VIDPIDLEN - 1);
5211			mtdt->type = stdt->type;
5212			mtdt->bsize = stdt->bsize;
5213			mtdt->options = stdt->options;
5214			mtdt->max_rretries = stdt->max_rretries;
5215			mtdt->max_wretries = stdt->max_wretries;
5216			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5217				mtdt->densities[tmp] = stdt->densities[tmp];
5218			}
5219			mtdt->default_density = stdt->default_density;
5220			/*
5221			 * Speed hasn't been used since the hayday of reel tape.
5222			 * For all drives not setting the option ST_KNOWS_MEDIA
5223			 * the speed member renamed to mediatype are zeros.
5224			 * Those drives that have ST_KNOWS_MEDIA set use the
5225			 * new mediatype member which is used to figure the
5226			 * type of media loaded.
5227			 *
5228			 * So as to not break applications speed in the
5229			 * mtdrivetype structure is not renamed.
5230			 */
5231			for (tmp = 0; tmp < NDENSITIES; tmp++) {
5232				mtdt->speeds[tmp] = stdt->mediatype[tmp];
5233			}
5234			mtdt->non_motion_timeout = stdt->non_motion_timeout;
5235			mtdt->io_timeout = stdt->io_timeout;
5236			mtdt->rewind_timeout = stdt->rewind_timeout;
5237			mtdt->space_timeout = stdt->space_timeout;
5238			mtdt->load_timeout = stdt->load_timeout;
5239			mtdt->unload_timeout = stdt->unload_timeout;
5240			mtdt->erase_timeout = stdt->erase_timeout;
5241
5242			/*
5243			 * Limit the maximum length of the result to
5244			 * sizeof (struct mtdrivetype).
5245			 */
5246			tmp = sizeof (struct mtdrivetype);
5247			if (mtdtrq.size < tmp)
5248				tmp = mtdtrq.size;
5249			if (ddi_copyout(mtdt, mtdtrq.mtdtp, tmp, flag)) {
5250				rval = EFAULT;
5251			}
5252			break;
5253		}
5254	case MTIOCPERSISTENT:
5255
5256		if (ddi_copyin((void *)arg, &tmp, sizeof (tmp), flag)) {
5257			rval = EFAULT;
5258			break;
5259		}
5260
5261		if (tmp) {
5262			st_turn_pe_on(un);
5263		} else {
5264			st_turn_pe_off(un);
5265		}
5266
5267		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5268		    "st_ioctl: MTIOCPERSISTENT : persistence = %d\n",
5269		    un->un_persistence);
5270
5271		break;
5272
5273	case MTIOCPERSISTENTSTATUS:
5274		tmp = (int)un->un_persistence;
5275
5276		if (ddi_copyout(&tmp, (void *)arg, sizeof (tmp), flag)) {
5277			rval = EFAULT;
5278		}
5279		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5280		    "st_ioctl: MTIOCPERSISTENTSTATUS:persistence = %d\n",
5281		    un->un_persistence);
5282
5283		break;
5284
5285	case MTIOCLRERR:
5286		{
5287			/* clear persistent errors */
5288
5289			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5290			    "st_ioctl: MTIOCLRERR\n");
5291
5292			st_clear_pe(un);
5293
5294			break;
5295		}
5296
5297	case MTIOCGUARANTEEDORDER:
5298		{
5299			/*
5300			 * this is just a holder to make a valid ioctl and
5301			 * it won't be in any earlier release
5302			 */
5303			ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5304			    "st_ioctl: MTIOCGUARANTEEDORDER\n");
5305
5306			break;
5307		}
5308
5309	case MTIOCRESERVE:
5310		{
5311			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5312			    "st_ioctl: MTIOCRESERVE\n");
5313
5314			/*
5315			 * Check if Reserve/Release is supported.
5316			 */
5317			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5318				rval = ENOTTY;
5319				break;
5320			}
5321
5322			rval = st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5323
5324			if (rval == 0) {
5325				un->un_rsvd_status |= ST_PRESERVE_RESERVE;
5326			}
5327			break;
5328		}
5329
5330	case MTIOCRELEASE:
5331		{
5332			ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5333			    "st_ioctl: MTIOCRELEASE\n");
5334
5335			/*
5336			 * Check if Reserve/Release is supported.
5337			 */
5338			if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5339				rval = ENOTTY;
5340				break;
5341			}
5342
5343			/*
5344			 * Used to just clear ST_PRESERVE_RESERVE which
5345			 * made the reservation release at next close.
5346			 * As the user may have opened and then done a
5347			 * persistant reservation we now need to drop
5348			 * the reservation without closing if the user
5349			 * attempts to do this.
5350			 */
5351			rval = st_reserve_release(un, ST_RELEASE, st_uscsi_cmd);
5352
5353			un->un_rsvd_status &= ~ST_PRESERVE_RESERVE;
5354
5355			break;
5356		}
5357
5358	case MTIOCFORCERESERVE:
5359	{
5360		ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5361		    "st_ioctl: MTIOCFORCERESERVE\n");
5362
5363		/*
5364		 * Check if Reserve/Release is supported.
5365		 */
5366		if (un->un_dp->options & ST_NO_RESERVE_RELEASE) {
5367			rval = ENOTTY;
5368			break;
5369		}
5370		/*
5371		 * allow only super user to run this.
5372		 */
5373		if (drv_priv(cred_p) != 0) {
5374			rval = EPERM;
5375			break;
5376		}
5377		/*
5378		 * Throw away reserve,
5379		 * not using test-unit-ready
5380		 * since reserve can succeed without tape being
5381		 * present in the drive.
5382		 */
5383		(void) st_reserve_release(un, ST_RESERVE, st_uscsi_cmd);
5384
5385		rval = st_take_ownership(un, st_uscsi_cmd);
5386
5387		break;
5388	}
5389
5390	case USCSICMD:
5391	{
5392		cred_t	*cr;
5393
5394		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5395		    "st_ioctl: USCSICMD\n");
5396
5397		cr = ddi_get_cred();
5398		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
5399			rval = EPERM;
5400		} else {
5401			rval = st_uscsi_cmd(un, (struct uscsi_cmd *)arg, flag);
5402		}
5403		break;
5404	}
5405	case MTIOCTOP:
5406		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5407		    "st_ioctl: MTIOCTOP\n");
5408		rval = st_mtioctop(un, arg, flag);
5409		break;
5410
5411	case MTIOCLTOP:
5412		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5413		    "st_ioctl: MTIOLCTOP\n");
5414		rval = st_mtiocltop(un, arg, flag);
5415		break;
5416
5417	case MTIOCREADIGNOREILI:
5418		{
5419			int set_ili;
5420
5421			if (ddi_copyin((void *)arg, &set_ili,
5422			    sizeof (set_ili), flag)) {
5423				rval = EFAULT;
5424				break;
5425			}
5426
5427			if (un->un_bsize) {
5428				rval = ENOTTY;
5429				break;
5430			}
5431
5432			switch (set_ili) {
5433			case 0:
5434				un->un_dp->options &= ~ST_READ_IGNORE_ILI;
5435				break;
5436
5437			case 1:
5438				un->un_dp->options |= ST_READ_IGNORE_ILI;
5439				break;
5440
5441			default:
5442				rval = EINVAL;
5443				break;
5444			}
5445			break;
5446		}
5447
5448	case MTIOCREADIGNOREEOFS:
5449		{
5450			int ignore_eof;
5451
5452			if (ddi_copyin((void *)arg, &ignore_eof,
5453			    sizeof (ignore_eof), flag)) {
5454				rval = EFAULT;
5455				break;
5456			}
5457
5458			if (!(un->un_dp->options & ST_REEL)) {
5459				rval = ENOTTY;
5460				break;
5461			}
5462
5463			switch (ignore_eof) {
5464			case 0:
5465				un->un_dp->options &= ~ST_READ_IGNORE_EOFS;
5466				break;
5467
5468			case 1:
5469				un->un_dp->options |= ST_READ_IGNORE_EOFS;
5470				break;
5471
5472			default:
5473				rval = EINVAL;
5474				break;
5475			}
5476			break;
5477		}
5478
5479	case MTIOCSHORTFMK:
5480	{
5481		int short_fmk;
5482
5483		if (ddi_copyin((void *)arg, &short_fmk,
5484		    sizeof (short_fmk), flag)) {
5485			rval = EFAULT;
5486			break;
5487		}
5488
5489		switch (un->un_dp->type) {
5490		case ST_TYPE_EXB8500:
5491		case ST_TYPE_EXABYTE:
5492			if (!short_fmk) {
5493				un->un_dp->options &= ~ST_SHORT_FILEMARKS;
5494			} else if (short_fmk == 1) {
5495				un->un_dp->options |= ST_SHORT_FILEMARKS;
5496			} else {
5497				rval = EINVAL;
5498			}
5499			break;
5500
5501		default:
5502			rval = ENOTTY;
5503			break;
5504		}
5505		break;
5506	}
5507
5508	case MTIOCGETPOS:
5509		rval = st_update_block_pos(un, st_cmd, 0);
5510		if (rval == 0) {
5511			if (ddi_copyout((void *)&un->un_pos, (void *)arg,
5512			    sizeof (tapepos_t), flag)) {
5513				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5514				    "MTIOCGETPOS copy out failed\n");
5515				rval = EFAULT;
5516			}
5517		}
5518		break;
5519
5520	case MTIOCRESTPOS:
5521	{
5522		tapepos_t dest;
5523
5524		if (ddi_copyin((void *)arg, &dest, sizeof (tapepos_t),
5525		    flag) != 0) {
5526			scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
5527			    "MTIOCRESTPOS copy in failed\n");
5528			rval = EFAULT;
5529			break;
5530		}
5531		rval = st_validate_tapemarks(un, st_uscsi_cmd, &dest);
5532		if (rval != 0) {
5533			rval = EIO;
5534		}
5535		break;
5536	}
5537	default:
5538		ST_DEBUG4(ST_DEVINFO, st_label, SCSI_DEBUG,
5539		    "st_ioctl: unknown ioctl\n");
5540		rval = ENOTTY;
5541	}
5542
5543exit:
5544	if (!(un->un_persistence && un->un_persist_errors)) {
5545		un->un_errno = rval;
5546	}
5547
5548	mutex_exit(ST_MUTEX);
5549
5550	return (rval);
5551}
5552
5553
5554/*
5555 * do some MTIOCTOP tape operations
5556 */
5557static int
5558st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag)
5559{
5560#ifdef _MULTI_DATAMODEL
5561	/*
5562	 * For use when a 32 bit app makes a call into a
5563	 * 64 bit ioctl
5564	 */
5565	struct mtop32	mtop_32_for_64;
5566#endif /* _MULTI_DATAMODEL */
5567	struct mtop passed;
5568	struct mtlop local;
5569	int rval = 0;
5570
5571	ST_FUNC(ST_DEVINFO, st_mtioctop);
5572
5573	ASSERT(mutex_owned(ST_MUTEX));
5574
5575#ifdef _MULTI_DATAMODEL
5576	switch (ddi_model_convert_from(flag & FMODELS)) {
5577	case DDI_MODEL_ILP32:
5578		if (ddi_copyin((void *)arg, &mtop_32_for_64,
5579		    sizeof (struct mtop32), flag)) {
5580			return (EFAULT);
5581		}
5582		local.mt_op = mtop_32_for_64.mt_op;
5583		local.mt_count =  (int64_t)mtop_32_for_64.mt_count;
5584		break;
5585
5586	case DDI_MODEL_NONE:
5587		if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5588			return (EFAULT);
5589		}
5590		local.mt_op = passed.mt_op;
5591		/* prevent sign extention */
5592		local.mt_count = (UINT32_MAX & passed.mt_count);
5593		break;
5594	}
5595
5596#else /* ! _MULTI_DATAMODEL */
5597	if (ddi_copyin((void *)arg, &passed, sizeof (passed), flag)) {
5598		return (EFAULT);
5599	}
5600	local.mt_op = passed.mt_op;
5601	/* prevent sign extention */
5602	local.mt_count = (UINT32_MAX & passed.mt_count);
5603#endif /* _MULTI_DATAMODEL */
5604
5605	rval = st_do_mtioctop(un, &local);
5606
5607#ifdef _MULTI_DATAMODEL
5608	switch (ddi_model_convert_from(flag & FMODELS)) {
5609	case DDI_MODEL_ILP32:
5610		if (((uint64_t)local.mt_count) > UINT32_MAX) {
5611			rval = ERANGE;
5612			break;
5613		}
5614		/*
5615		 * Convert 64 bit back to 32 bit before doing
5616		 * copyout. This is what the ILP32 app expects.
5617		 */
5618		mtop_32_for_64.mt_op = local.mt_op;
5619		mtop_32_for_64.mt_count = local.mt_count;
5620
5621		if (ddi_copyout(&mtop_32_for_64, (void *)arg,
5622		    sizeof (struct mtop32), flag)) {
5623			rval = EFAULT;
5624		}
5625		break;
5626
5627	case DDI_MODEL_NONE:
5628		passed.mt_count = local.mt_count;
5629		passed.mt_op = local.mt_op;
5630		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5631			rval = EFAULT;
5632		}
5633		break;
5634	}
5635#else /* ! _MULTI_DATAMODE */
5636	if (((uint64_t)local.mt_count) > UINT32_MAX) {
5637		rval = ERANGE;
5638	} else {
5639		passed.mt_op = local.mt_op;
5640		passed.mt_count = local.mt_count;
5641		if (ddi_copyout(&passed, (void *)arg, sizeof (passed), flag)) {
5642			rval = EFAULT;
5643		}
5644	}
5645#endif /* _MULTI_DATAMODE */
5646
5647
5648	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
5649	    "st_ioctl: fileno=%x, blkno=%x, eof=%x\n", un->un_pos.fileno,
5650	    un->un_pos.blkno, un->un_pos.eof);
5651
5652	if (un->un_pos.pmode == invalid) {
5653		un->un_density_known = 0;
5654	}
5655
5656	ASSERT(mutex_owned(ST_MUTEX));
5657	return (rval);
5658}
5659
5660static int
5661st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag)
5662{
5663	struct mtlop local;
5664	int rval;
5665
5666	ST_FUNC(ST_DEVINFO, st_mtiocltop);
5667	if (ddi_copyin((void *)arg, &local, sizeof (local), flag)) {
5668		return (EFAULT);
5669	}
5670
5671	rval = st_do_mtioctop(un, &local);
5672
5673	if (ddi_copyout(&local, (void *)arg, sizeof (local), flag)) {
5674		rval = EFAULT;
5675	}
5676	return (rval);
5677}
5678
5679
5680static int
5681st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop)
5682{
5683	dev_t dev = un->un_dev;
5684	int savefile;
5685	int rval = 0;
5686
5687	ST_FUNC(ST_DEVINFO, st_do_mtioctop);
5688
5689	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5690	    "st_do_mtioctop(): mt_op=%x\n", mtop->mt_op);
5691	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
5692	    "fileno=%x, blkno=%x, eof=%x\n",
5693	    un->un_pos.fileno, un->un_pos.blkno, un->un_pos.eof);
5694
5695	un->un_status = 0;
5696
5697	/*
5698	 * if we are going to mess with a tape, we have to make sure we have
5699	 * one and are not offline (i.e. no tape is initialized).  We let
5700	 * commands pass here that don't actually touch the tape, except for
5701	 * loading and initialization (rewinding).
5702	 */
5703	if (un->un_state == ST_STATE_OFFLINE) {
5704		switch (mtop->mt_op) {
5705		case MTLOAD:
5706		case MTNOP:
5707			/*
5708			 * We don't want strategy calling st_tape_init here,
5709			 * so, change state
5710			 */
5711			un->un_state = ST_STATE_INITIALIZING;
5712			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5713			    "st_do_mtioctop : OFFLINE state = %d\n",
5714			    un->un_state);
5715			break;
5716		default:
5717			/*
5718			 * reinitialize by normal means
5719			 */
5720			rval = st_tape_init(un);
5721			if (rval) {
5722				un->un_state = ST_STATE_INITIALIZING;
5723				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5724				    "st_do_mtioctop : OFFLINE init failure ");
5725				un->un_state = ST_STATE_OFFLINE;
5726				un->un_pos.pmode = invalid;
5727				if (rval != EACCES) {
5728					rval = EIO;
5729				}
5730				return (rval);
5731			}
5732			un->un_state = ST_STATE_OPEN_PENDING_IO;
5733			break;
5734		}
5735	}
5736
5737	/*
5738	 * If the file position is invalid, allow only those
5739	 * commands that properly position the tape and fail
5740	 * the rest with EIO
5741	 */
5742	if (un->un_pos.pmode == invalid) {
5743		switch (mtop->mt_op) {
5744		case MTWEOF:
5745		case MTRETEN:
5746		case MTERASE:
5747		case MTEOM:
5748		case MTFSF:
5749		case MTFSR:
5750		case MTBSF:
5751		case MTNBSF:
5752		case MTBSR:
5753		case MTSRSZ:
5754		case MTGRSZ:
5755		case MTSEEK:
5756		case MTBSSF:
5757		case MTFSSF:
5758			return (EIO);
5759			/* NOTREACHED */
5760		case MTREW:
5761		case MTLOAD:
5762		case MTOFFL:
5763		case MTNOP:
5764		case MTTELL:
5765		case MTLOCK:
5766		case MTUNLOCK:
5767			break;
5768
5769		default:
5770			return (ENOTTY);
5771			/* NOTREACHED */
5772		}
5773	}
5774
5775	switch (mtop->mt_op) {
5776	case MTERASE:
5777		/*
5778		 * MTERASE rewinds the tape, erase it completely, and returns
5779		 * to the beginning of the tape
5780		 */
5781		if (un->un_mspl->wp || un->un_read_only & WORM) {
5782			un->un_status = KEY_WRITE_PROTECT;
5783			un->un_err_resid = mtop->mt_count;
5784			COPY_POS(&un->un_err_pos, &un->un_pos);
5785			return (EACCES);
5786		}
5787		if (un->un_dp->options & ST_REEL) {
5788			un->un_fmneeded = 2;
5789		} else {
5790			un->un_fmneeded = 1;
5791		}
5792		mtop->mt_count = mtop->mt_count ? 1 : 0;
5793		if (st_check_density_or_wfm(dev, 1, B_WRITE, NO_STEPBACK) ||
5794		    st_cmd(un, SCMD_REWIND, 0, SYNC_CMD) ||
5795		    st_cmd(un, SCMD_ERASE, mtop->mt_count, SYNC_CMD)) {
5796			un->un_pos.pmode = invalid;
5797			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5798			    "st_do_mtioctop : EIO space or erase or "
5799			    "check den)\n");
5800			rval = EIO;
5801		} else {
5802			/* QIC and helical scan rewind after erase */
5803			if (un->un_dp->options & ST_REEL) {
5804				(void) st_cmd(un, SCMD_REWIND, 0, ASYNC_CMD);
5805			}
5806		}
5807		break;
5808
5809	case MTWEOF:
5810		/*
5811		 * write an end-of-file record
5812		 */
5813		if (un->un_mspl->wp || un->un_read_only & RDONLY) {
5814			un->un_status = KEY_WRITE_PROTECT;
5815			un->un_err_resid = mtop->mt_count;
5816			COPY_POS(&un->un_err_pos, &un->un_pos);
5817			return (EACCES);
5818		}
5819
5820		/*
5821		 * zero count means just flush buffers
5822		 * negative count is not permitted
5823		 */
5824		if (mtop->mt_count < 0) {
5825			return (EINVAL);
5826		}
5827
5828		/* Not on worm */
5829		if (un->un_read_only == RDWR) {
5830			un->un_test_append = 1;
5831		}
5832
5833		if (un->un_state == ST_STATE_OPEN_PENDING_IO) {
5834			if (st_determine_density(un, B_WRITE)) {
5835				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5836				    "st_do_mtioctop : EIO : MTWEOF can't "
5837				    "determine density");
5838				return (EIO);
5839			}
5840		}
5841
5842		rval = st_write_fm(dev, (int)mtop->mt_count);
5843		if ((rval != 0) && (rval != EACCES)) {
5844			/*
5845			 * Failure due to something other than illegal
5846			 * request results in loss of state (st_intr).
5847			 */
5848			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5849			    "st_do_mtioctop : EIO : MTWEOF can't write "
5850			    "file mark");
5851			rval = EIO;
5852		}
5853		break;
5854
5855	case MTRETEN:
5856		/*
5857		 * retension the tape
5858		 */
5859		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK) ||
5860		    st_cmd(un, SCMD_LOAD, LD_LOAD | LD_RETEN, SYNC_CMD)) {
5861			un->un_pos.pmode = invalid;
5862			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5863			    "st_do_mtioctop : EIO : MTRETEN ");
5864			rval = EIO;
5865		}
5866		break;
5867
5868	case MTREW:
5869		/*
5870		 * rewind  the tape
5871		 */
5872		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5873			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5874			    "st_do_mtioctop : EIO:MTREW check "
5875			    "density/wfm failed");
5876			return (EIO);
5877		}
5878		if (st_cmd(un, SCMD_REWIND, 0, SYNC_CMD)) {
5879			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5880			    "st_do_mtioctop : EIO : MTREW ");
5881			rval = EIO;
5882		}
5883		break;
5884
5885	case MTOFFL:
5886		/*
5887		 * rewinds, and, if appropriate, takes the device offline by
5888		 * unloading the tape
5889		 */
5890		if (st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK)) {
5891			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5892			    "st_do_mtioctop :EIO:MTOFFL check "
5893			    "density/wfm failed");
5894			return (EIO);
5895		}
5896		(void) st_cmd(un, SCMD_REWIND, 0, SYNC_CMD);
5897		if (st_cmd(un, SCMD_LOAD, LD_UNLOAD, SYNC_CMD)) {
5898			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5899			    "st_do_mtioctop : EIO : MTOFFL");
5900			return (EIO);
5901		}
5902		un->un_pos.eof = ST_NO_EOF;
5903		un->un_laststate = un->un_state;
5904		un->un_state = ST_STATE_OFFLINE;
5905		un->un_mediastate = MTIO_EJECTED;
5906		break;
5907
5908	case MTLOAD:
5909		/*
5910		 * This is to load a tape into the drive
5911		 * Note that if the tape is not loaded, the device will have
5912		 * to be opened via O_NDELAY or O_NONBLOCK.
5913		 */
5914		/*
5915		 * Let's try and clean things up, if we are not
5916		 * initializing, and then send in the load command, no
5917		 * matter what.
5918		 *
5919		 * load after a media change by the user.
5920		 */
5921
5922		if (un->un_state > ST_STATE_INITIALIZING) {
5923			(void) st_check_density_or_wfm(dev, 1, 0, NO_STEPBACK);
5924		}
5925		rval = st_cmd(un, SCMD_LOAD, LD_LOAD, SYNC_CMD);
5926		/* Load command to a drive that doesn't support load */
5927		if ((rval == EIO) &&
5928		    ((un->un_status == KEY_NOT_READY) &&
5929			/* Medium not present */
5930		    (un->un_uscsi_rqs_buf->es_add_code == 0x3a) ||
5931		    ((un->un_status == KEY_ILLEGAL_REQUEST) &&
5932		    (un->un_dp->type == MT_ISSTK9840) &&
5933			/* CSL not present */
5934		    (un->un_uscsi_rqs_buf->es_add_code == 0x80)))) {
5935			rval = ENOTTY;
5936			break;
5937		} else if (rval != EACCES && rval != 0) {
5938			rval = EIO;
5939		}
5940		if (rval) {
5941			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5942			    "st_do_mtioctop : %s : MTLOAD\n",
5943			    rval == EACCES ? "EACCES" : "EIO");
5944			/*
5945			 * If load tape fails, who knows what happened...
5946			 */
5947			un->un_pos.pmode = invalid;
5948			break;
5949		}
5950
5951		/*
5952		 * reset all counters appropriately using rewind, as if LOAD
5953		 * succeeds, we are at BOT
5954		 */
5955		un->un_state = ST_STATE_INITIALIZING;
5956
5957		rval = st_tape_init(un);
5958		if ((rval == EACCES) && (un->un_read_only & WORM)) {
5959			rval = 0;
5960			break;
5961		}
5962
5963		if (rval != 0) {
5964			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
5965			    "st_do_mtioctop : EIO : MTLOAD calls "
5966			    "st_tape_init\n");
5967			rval = EIO;
5968			un->un_state = ST_STATE_OFFLINE;
5969		}
5970
5971		break;
5972
5973	case MTNOP:
5974		un->un_status = 0;		/* Reset status */
5975		un->un_err_resid = 0;
5976		mtop->mt_count = MTUNIT(dev);
5977		break;
5978
5979	case MTEOM:
5980		/*
5981		 * positions the tape at a location just after the last file
5982		 * written on the tape. For cartridge and 8 mm, this after
5983		 * the last file mark; for reel, this is inbetween the two
5984		 * last 2 file marks
5985		 */
5986		if ((un->un_pos.pmode == legacy && un->un_pos.eof >= ST_EOT) ||
5987		    (un->un_lastop == ST_OP_WRITE) ||
5988		    (un->un_lastop == ST_OP_WEOF)) {
5989			/*
5990			 * If the command wants to move to logical end
5991			 * of media, and we're already there, we're done.
5992			 * If we were at logical eot, we reset the state
5993			 * to be *not* at logical eot.
5994			 *
5995			 * If we're at physical or logical eot, we prohibit
5996			 * forward space operations (unconditionally).
5997			 *
5998			 * Also if the last operation was a write of any
5999			 * kind the tape is at EOD.
6000			 */
6001			return (0);
6002		}
6003		/*
6004		 * physical tape position may not be what we've been
6005		 * telling the user; adjust the request accordingly
6006		 */
6007		if (IN_EOF(un->un_pos)) {
6008			un->un_pos.fileno++;
6009			un->un_pos.blkno = 0;
6010		}
6011
6012		if (st_check_density_or_wfm(dev, 1, B_READ, NO_STEPBACK)) {
6013			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6014			    "st_do_mtioctop : EIO:MTEOM check density/wfm "
6015			    " failed");
6016			return (EIO);
6017		}
6018
6019		/*
6020		 * st_find_eod() returns the last fileno we knew about;
6021		 */
6022		savefile = st_find_eod(un);
6023
6024		if ((un->un_status != KEY_BLANK_CHECK) &&
6025		    (un->un_status != SUN_KEY_EOT)) {
6026			un->un_pos.pmode = invalid;
6027			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6028			    "st_do_mtioctop : EIO : MTEOM status check failed");
6029			rval = EIO;
6030		} else {
6031			/*
6032			 * For 1/2" reel tapes assume logical EOT marked
6033			 * by two file marks or we don't care that we may
6034			 * be extending the last file on the tape.
6035			 */
6036			if (un->un_dp->options & ST_REEL) {
6037				if (st_cmd(un, SCMD_SPACE, Fmk(-1), SYNC_CMD)) {
6038					un->un_pos.pmode = invalid;
6039					ST_DEBUG2(ST_DEVINFO, st_label,
6040					    SCSI_DEBUG,
6041					    "st_do_mtioctop : EIO : MTEOM space"
6042					    " cmd failed");
6043					rval = EIO;
6044					break;
6045				}
6046				/*
6047				 * Fix up the block number.
6048				 */
6049				un->un_pos.blkno = 0;
6050				un->un_err_pos.blkno = 0;
6051			}
6052			un->un_err_resid = 0;
6053			un->un_pos.fileno = savefile;
6054			un->un_pos.eof = ST_EOT;
6055		}
6056		un->un_status = 0;
6057		break;
6058
6059	case MTFSF:
6060		MAX_SPACE_CNT(mtop->mt_count);
6061		rval = st_mtfsf_ioctl(un, mtop->mt_count);
6062		break;
6063
6064	case MTFSR:
6065		MAX_SPACE_CNT(mtop->mt_count);
6066		rval = st_mtfsr_ioctl(un, mtop->mt_count);
6067		break;
6068
6069	case MTBSF:
6070		MAX_SPACE_CNT(mtop->mt_count);
6071		rval = st_mtbsf_ioctl(un, mtop->mt_count);
6072		break;
6073
6074	case MTNBSF:
6075		MAX_SPACE_CNT(mtop->mt_count);
6076		rval = st_mtnbsf_ioctl(un, mtop->mt_count);
6077		break;
6078
6079	case MTBSR:
6080		MAX_SPACE_CNT(mtop->mt_count);
6081		rval = st_mtbsr_ioctl(un, mtop->mt_count);
6082		break;
6083
6084	case MTBSSF:
6085		MAX_SPACE_CNT(mtop->mt_count);
6086		rval = st_mtbsfm_ioctl(un, mtop->mt_count);
6087		break;
6088
6089	case MTFSSF:
6090		MAX_SPACE_CNT(mtop->mt_count);
6091		rval = st_mtfsfm_ioctl(un, mtop->mt_count);
6092		break;
6093
6094	case MTSRSZ:
6095
6096		/*
6097		 * Set record-size to that sent by user
6098		 * Check to see if there is reason that the requested
6099		 * block size should not be set.
6100		 */
6101
6102		/* If requesting variable block size is it ok? */
6103		if ((mtop->mt_count == 0) &&
6104		    ((un->un_dp->options & ST_VARIABLE) == 0)) {
6105			return (ENOTTY);
6106		}
6107
6108		/*
6109		 * If requested block size is not variable "0",
6110		 * is it less then minimum.
6111		 */
6112		if ((mtop->mt_count != 0) &&
6113		    (mtop->mt_count < un->un_minbsize)) {
6114			return (EINVAL);
6115		}
6116
6117		/* Is the requested block size more then maximum */
6118		if ((mtop->mt_count > min(un->un_maxbsize, un->un_maxdma)) &&
6119		    (un->un_maxbsize != 0)) {
6120			return (EINVAL);
6121		}
6122
6123		/* Is requested block size a modulus the device likes */
6124		if ((mtop->mt_count % un->un_data_mod) != 0) {
6125			return (EINVAL);
6126		}
6127
6128		if (st_change_block_size(un, (uint32_t)mtop->mt_count) != 0) {
6129			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6130			    "st_ioctl : MTSRSZ : EIO : cant set block size");
6131			return (EIO);
6132		}
6133
6134		return (0);
6135
6136	case MTGRSZ:
6137		/*
6138		 * Get record-size to the user
6139		 */
6140		mtop->mt_count = un->un_bsize;
6141		rval = 0;
6142		break;
6143
6144	case MTTELL:
6145		rval = st_update_block_pos(un, st_cmd, 0);
6146		mtop->mt_count = un->un_pos.lgclblkno;
6147		break;
6148
6149	case MTSEEK:
6150		rval = st_logical_block_locate(un, st_uscsi_cmd, &un->un_pos,
6151		    (uint64_t)mtop->mt_count, un->un_pos.partition);
6152		/*
6153		 * This bit of magic make mt print the actual position if
6154		 * the resulting position was not what was asked for.
6155		 */
6156		if (rval == ESPIPE) {
6157			rval = EIO;
6158			if ((uint64_t)mtop->mt_count != un->un_pos.lgclblkno) {
6159				mtop->mt_op = MTTELL;
6160				mtop->mt_count = un->un_pos.lgclblkno;
6161			}
6162		}
6163		break;
6164
6165	case MTLOCK:
6166		if (st_cmd(un, SCMD_DOORLOCK, MR_LOCK, SYNC_CMD)) {
6167			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6168			    "st_do_mtioctop : EIO : MTLOCK");
6169			rval = EIO;
6170		}
6171		break;
6172
6173	case MTUNLOCK:
6174		if (st_cmd(un, SCMD_DOORLOCK, MR_UNLOCK, SYNC_CMD)) {
6175			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6176			    "st_do_mtioctop : EIO : MTUNLOCK");
6177			rval = EIO;
6178		}
6179		break;
6180
6181	default:
6182		rval = ENOTTY;
6183	}
6184
6185	return (rval);
6186}
6187
6188
6189/*
6190 * Run a command for uscsi ioctl.
6191 */
6192static int
6193st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *ucmd, int flag)
6194{
6195	struct uscsi_cmd	*uscmd;
6196	struct buf	*bp;
6197	enum uio_seg	uioseg;
6198	int	offline_state = 0;
6199	int	err = 0;
6200	dev_t dev = un->un_dev;
6201
6202	ST_FUNC(ST_DEVINFO, st_uscsi_cmd);
6203
6204	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6205	    "st_uscsi_cmd(dev = 0x%lx)\n", un->un_dev);
6206
6207	ASSERT(mutex_owned(ST_MUTEX));
6208
6209	/*
6210	 * We really don't know what commands are coming in here and
6211	 * we don't want to limit the commands coming in.
6212	 *
6213	 * If st_tape_init() gets called from st_strategy(), then we
6214	 * will hang the process waiting for un->un_sbuf_busy to be cleared,
6215	 * which it never will, as we set it below.  To prevent
6216	 * st_tape_init() from getting called, we have to set state to other
6217	 * than ST_STATE_OFFLINE, so we choose ST_STATE_INITIALIZING, which
6218	 * achieves this purpose already.
6219	 *
6220	 * We use offline_state to preserve the OFFLINE state, if it exists,
6221	 * so other entry points to the driver might have the chance to call
6222	 * st_tape_init().
6223	 */
6224	if (un->un_state == ST_STATE_OFFLINE) {
6225		un->un_laststate = ST_STATE_OFFLINE;
6226		un->un_state = ST_STATE_INITIALIZING;
6227		offline_state = 1;
6228	}
6229
6230	mutex_exit(ST_MUTEX);
6231	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag, ROUTE, &uscmd);
6232	mutex_enter(ST_MUTEX);
6233	if (err != 0) {
6234		ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6235		    "st_uscsi_cmd: scsi_uscsi_alloc_and_copyin failed\n");
6236		goto exit;
6237	}
6238
6239	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;
6240
6241	/* check to see if this command requires the drive to be reserved */
6242	if (uscmd->uscsi_cdb != NULL) {
6243		err = st_check_cdb_for_need_to_reserve(un,
6244		    (uchar_t *)uscmd->uscsi_cdb);
6245		if (err) {
6246			goto exit_free;
6247		}
6248		/*
6249		 * If this is a space command we need to save the starting
6250		 * point so we can retry from there if the command fails.
6251		 */
6252		if ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6253		    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) {
6254			(void) st_update_block_pos(un, st_cmd, 0);
6255		}
6256	}
6257
6258	/*
6259	 * Forground should not be doing anything while recovery is active.
6260	 */
6261	ASSERT(un->un_recov_buf_busy == 0);
6262
6263	/*
6264	 * Get buffer resources...
6265	 */
6266	while (un->un_sbuf_busy)
6267		cv_wait(&un->un_sbuf_cv, ST_MUTEX);
6268	un->un_sbuf_busy = 1;
6269
6270#ifdef STDEBUG
6271	if ((uscmd->uscsi_cdb != NULL) && (st_debug & 0x7) > 6) {
6272		int rw = (uscmd->uscsi_flags & USCSI_READ) ? B_READ : B_WRITE;
6273		st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6274		    "uscsi cdb", uscmd->uscsi_cdb);
6275		if (uscmd->uscsi_buflen) {
6276			ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6277			    "uscsi %s of %ld bytes %s %s space\n",
6278			    (rw == B_READ) ? rd_str : wr_str,
6279			    uscmd->uscsi_buflen,
6280			    (rw == B_READ) ? "to" : "from",
6281			    (uioseg == UIO_SYSSPACE) ? "system" : "user");
6282		}
6283	}
6284#endif /* STDEBUG */
6285
6286	/*
6287	 * Although st_uscsi_cmd() never makes use of these
6288	 * now, we are just being safe and consistent.
6289	 */
6290	uscmd->uscsi_flags &= ~(USCSI_NOINTR | USCSI_NOPARITY |
6291	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD);
6292
6293	un->un_srqbufp = uscmd->uscsi_rqbuf;
6294	bp = un->un_sbufp;
6295	bzero(bp, sizeof (buf_t));
6296	if (uscmd->uscsi_cdb != NULL) {
6297		bp->b_forw = (struct buf *)(uintptr_t)uscmd->uscsi_cdb[0];
6298	}
6299	bp->b_back = (struct buf *)uscmd;
6300
6301	mutex_exit(ST_MUTEX);
6302	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd, st_strategy, bp, NULL);
6303	mutex_enter(ST_MUTEX);
6304
6305	/*
6306	 * If scsi reset successful, don't write any filemarks.
6307	 */
6308	if ((err == 0) && (uscmd->uscsi_flags &
6309	    (USCSI_RESET_LUN | USCSI_RESET_TARGET | USCSI_RESET_ALL))) {
6310		un->un_fmneeded = 0;
6311	}
6312
6313exit_free:
6314	/*
6315	 * Free resources
6316	 */
6317	un->un_sbuf_busy = 0;
6318	un->un_srqbufp = NULL;
6319
6320	/*
6321	 * If was a space command need to update logical block position.
6322	 * If the command failed such that positioning is invalid, Don't
6323	 * update the position as the user must do this to validate the
6324	 * position for data protection.
6325	 */
6326	if ((uscmd->uscsi_cdb != NULL) &&
6327	    ((uscmd->uscsi_cdb[0] == SCMD_SPACE) ||
6328	    (uscmd->uscsi_cdb[0] == (char)SCMD_SPACE_G4)) &&
6329	    (un->un_pos.pmode != invalid)) {
6330		un->un_running.pmode = invalid;
6331		(void) st_update_block_pos(un, st_cmd, 1);
6332		/*
6333		 * Set running position to invalid so it updates on the
6334		 * next command.
6335		 */
6336		un->un_running.pmode = invalid;
6337	}
6338	cv_signal(&un->un_sbuf_cv);
6339	mutex_exit(ST_MUTEX);
6340	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);
6341	mutex_enter(ST_MUTEX);
6342	ST_DEBUG6(ST_DEVINFO, st_label, SCSI_DEBUG,
6343	    "st_uscsi_cmd returns 0x%x\n", err);
6344
6345exit:
6346	/* don't lose offline state */
6347	if (offline_state) {
6348		un->un_state = ST_STATE_OFFLINE;
6349	}
6350
6351	ASSERT(mutex_owned(ST_MUTEX));
6352	return (err);
6353}
6354
6355static int
6356st_write_fm(dev_t dev, int wfm)
6357{
6358	int i;
6359	int rval;
6360
6361	GET_SOFT_STATE(dev);
6362
6363	ST_FUNC(ST_DEVINFO, st_write_fm);
6364
6365	ASSERT(mutex_owned(ST_MUTEX));
6366
6367	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6368	    "st_write_fm(dev = 0x%lx, wfm = %d)\n", dev, wfm);
6369
6370	/*
6371	 * write one filemark at the time after EOT
6372	 */
6373	if (un->un_pos.eof >= ST_EOT) {
6374		for (i = 0; i < wfm; i++) {
6375			rval = st_cmd(un, SCMD_WRITE_FILE_MARK, 1, SYNC_CMD);
6376			if (rval == EACCES) {
6377				return (rval);
6378			}
6379			if (rval != 0) {
6380				ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6381				    "st_write_fm : EIO : write EOT file mark");
6382				return (EIO);
6383			}
6384		}
6385	} else {
6386		rval = st_cmd(un, SCMD_WRITE_FILE_MARK, wfm, SYNC_CMD);
6387		if (rval == EACCES) {
6388			return (rval);
6389		}
6390		if (rval) {
6391			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6392			    "st_write_fm : EIO : write file mark");
6393			return (EIO);
6394		}
6395	}
6396
6397	ASSERT(mutex_owned(ST_MUTEX));
6398	return (0);
6399}
6400
6401#ifdef STDEBUG
6402static void
6403st_start_dump(struct scsi_tape *un, struct buf *bp)
6404{
6405	struct scsi_pkt *pkt = BP_PKT(bp);
6406	uchar_t *cdbp = (uchar_t *)pkt->pkt_cdbp;
6407
6408	ST_FUNC(ST_DEVINFO, st_start_dump);
6409
6410	if ((st_debug & 0x7) < 6)
6411		return;
6412	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6413	    "st_start: cmd=0x%p count=%ld resid=%ld flags=0x%x pkt=0x%p\n",
6414	    (void *)bp->b_forw, bp->b_bcount,
6415	    bp->b_resid, bp->b_flags, (void *)BP_PKT(bp));
6416	st_print_cdb(ST_DEVINFO, st_label, SCSI_DEBUG,
6417	    "st_start: cdb",  (caddr_t)cdbp);
6418	scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6419	    "st_start: fileno=%d, blk=%d\n",
6420	    un->un_pos.fileno, un->un_pos.blkno);
6421}
6422#endif
6423
6424
6425/*
6426 * Command start && done functions
6427 */
6428
6429/*
6430 * st_start()
6431 *
6432 * Called from:
6433 *  st_strategy() to start a command.
6434 *  st_runout() to retry when scsi_pkt allocation fails on previous attempt(s).
6435 *  st_attach() when resuming from power down state.
6436 *  st_start_restart() to retry transport when device was previously busy.
6437 *  st_done_and_mutex_exit() to start the next command when previous is done.
6438 *
6439 * On entry:
6440 *  scsi_pkt may or may not be allocated.
6441 *
6442 */
6443static void
6444st_start(struct scsi_tape *un)
6445{
6446	struct buf *bp;
6447	int status;
6448	int queued;
6449
6450	ST_FUNC(ST_DEVINFO, st_start);
6451	ASSERT(mutex_owned(ST_MUTEX));
6452
6453	ST_DEBUG3(ST_DEVINFO, st_label, SCSI_DEBUG,
6454	    "st_start(): dev = 0x%lx\n", un->un_dev);
6455
6456	if (un->un_recov_buf_busy) {
6457		/* recovery commands can happen anytime */
6458		bp = un->un_recov_buf;
6459		queued = 0;
6460	} else if (un->un_sbuf_busy) {
6461		/* sbuf commands should only happen with an empty queue. */
6462		ASSERT(un->un_quef == NULL);
6463		ASSERT(un->un_runqf == NULL);
6464		bp = un->un_sbufp;
6465		queued = 0;
6466	} else if (un->un_quef != NULL) {
6467		if (un->un_persistence && un->un_persist_errors) {
6468			return;
6469		}
6470		bp = un->un_quef;
6471		queued = 1;
6472	} else {
6473		scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,
6474		    "st_start() returning no buf found\n");
6475		return;
6476	}
6477
6478	ASSERT((bp->b_flags & B_DONE) == 0);
6479
6480	/*
6481	 * Don't send more than un_throttle commands to the HBA
6482	 */
6483	if ((un->un_throttle <= 0) || (un->un_ncmds >= un->un_throttle)) {
6484		/*
6485		 * if doing recovery we know there is outstanding commands.
6486		 */
6487		if (bp != un->un_recov_buf) {
6488			ST_DEBUG2(ST_DEVINFO, st_label, SCSI_DEBUG,
6489			    "st_start returning throttle = %d or ncmds = %d\n",
6490			    un->un_throttle, un->un_ncmds);
6491			if (un->un_ncmds == 0) {
6492				typedef void (*func)();
6493				func fnc = (func)(uintptr_t)st_runout;
6494
6495				scsi_log(ST_DEVINFO, st_label, SCSI_DEBUG,