xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/st.c (revision 0dcef4d4)
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  */
123 extern struct scsi_key_strings scsi_cmds[];
124 extern uchar_t	scsi_cdb_size[];
125 
126 /*
127  * Local Static Data
128  */
129 static void *st_state;
130 static char *const st_label = "st";
131 static volatile int st_recov_sz = sizeof (recov_info);
132 static 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  */
142 static 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 
157 static 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 */
164 static 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  */
199 static int st_selection_retry_count = ST_SEL_RETRY_COUNT;
200 static int st_retry_count	= ST_RETRY_COUNT;
201 
202 static int st_io_time		= ST_IO_TIME;
203 static int st_long_timeout_x	= ST_LONG_TIMEOUT_X;
204 
205 static int st_space_time	= ST_SPACE_TIME;
206 static int st_long_space_time_x	= ST_LONG_SPACE_TIME_X;
207 
208 static int st_error_level	= SCSI_ERR_RETRYABLE;
209 static int st_check_media_time	= 3000000;	/* 3 Second State Check */
210 
211 static int st_max_throttle	= ST_MAX_THROTTLE;
212 
213 static clock_t st_wait_cmds_complete = ST_WAIT_CMDS_COMPLETE;
214 
215 static int st_allow_large_xfer = 1;
216 static 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 
246 extern const int st_ndrivetypes;	/* defined in st_conf.c */
247 extern const struct st_drivetype st_drivetypes[];
248 extern const char st_conf_version[];
249 
250 #ifdef STDEBUG
251 static int st_soft_error_report_debug = 0;
252 volatile int st_debug = 0;
253 static volatile dev_info_t *st_lastdev;
254 static kmutex_t st_debug_mutex;
255 #endif
256 
257 #define	ST_MT02_NAME	"Emulex  MT02 QIC-11/24  "
258 
259 static 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 
269 static 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 */
304 static const char wr_str[]  = "write";
305 static const char rd_str[]  = "read";
306 static const char wrg_str[] = "writing";
307 static const char rdg_str[] = "reading";
308 static const char *space_strs[] = {
309 	"records",
310 	"filemarks",
311 	"sequential filemarks",
312 	"eod",
313 	"setmarks",
314 	"sequential setmarks",
315 	"Reserved",
316 	"Reserved"
317 };
318 static 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 
331 static 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 
348 const 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 
358 static 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 
373 static 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)
388 static 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)
403 static 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 };
417 uint64_t st_max_phys_addr = 0xFFFFFFFFull;
418 int st_sgl_size = 0xF;
419 
420 #endif
421 
422 /*
423  * Configuration Data:
424  *
425  * Device driver ops vector
426  */
427 static int st_aread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
428 static int st_awrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
429 static int st_read(dev_t  dev,  struct   uio   *uio_p,   cred_t *cred_p);
430 static int st_write(dev_t  dev,  struct  uio   *uio_p,   cred_t *cred_p);
431 static int st_open(dev_t  *devp,  int  flag,  int  otyp,  cred_t *cred_p);
432 static int st_close(dev_t  dev,  int  flag,  int  otyp,  cred_t *cred_p);
433 static int st_strategy(struct buf *bp);
434 static int st_queued_strategy(buf_t *bp);
435 static int st_ioctl(dev_t dev, int cmd, intptr_t arg, int  flag,
436 	cred_t *cred_p, int *rval_p);
437 extern int nulldev(), nodev();
438 
439 static 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 
462 static int st_info(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
463 		void **result);
464 static int st_probe(dev_info_t *dev);
465 static int st_attach(dev_info_t *dev, ddi_attach_cmd_t cmd);
466 static int st_detach(dev_info_t *dev, ddi_detach_cmd_t cmd);
467 
468 static 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  */
486 static char *st_print_scsi_cmd(char cmd);
487 static void st_print_cdb(dev_info_t *dip, char *label, uint_t level,
488     char *title, char *cdb);
489 static void st_clean_print(dev_info_t *dev, char *label, uint_t level,
490     char *title, char *data, int len);
491 static int st_doattach(struct scsi_device *devp, int (*canwait)());
492 static void st_known_tape_type(struct scsi_tape *un);
493 static int st_get_conf_from_st_dot_conf(struct scsi_tape *, char *,
494     struct st_drivetype *);
495 static int st_get_conf_from_st_conf_dot_c(struct scsi_tape *, char *,
496     struct st_drivetype *);
497 static int st_get_conf_from_tape_drive(struct scsi_tape *, char *,
498     struct st_drivetype *);
499 static int st_get_densities_from_tape_drive(struct scsi_tape *,
500     struct st_drivetype *);
501 static int st_get_timeout_values_from_tape_drive(struct scsi_tape *,
502     struct st_drivetype *);
503 static int st_get_timeouts_value(struct scsi_tape *, uchar_t, ushort_t *,
504     ushort_t);
505 static int st_get_default_conf(struct scsi_tape *, char *,
506     struct st_drivetype *);
507 static int st_rw(dev_t dev, struct uio *uio, int flag);
508 static int st_arw(dev_t dev, struct aio_req *aio, int flag);
509 static int st_find_eod(struct scsi_tape *un);
510 static int st_check_density_or_wfm(dev_t dev, int wfm, int mode, int stepflag);
511 static int st_uscsi_cmd(struct scsi_tape *un, struct uscsi_cmd *, int flag);
512 static int st_mtioctop(struct scsi_tape *un, intptr_t arg, int flag);
513 static int st_mtiocltop(struct scsi_tape *un, intptr_t arg, int flag);
514 static int st_do_mtioctop(struct scsi_tape *un, struct mtlop *mtop);
515 static void st_start(struct scsi_tape *un);
516 static int st_handle_start_busy(struct scsi_tape *un, struct buf *bp,
517     clock_t timeout_interval, int queued);
518 static int st_handle_intr_busy(struct scsi_tape *un, struct buf *bp,
519     clock_t timeout_interval);
520 static int st_handle_intr_retry_lcmd(struct scsi_tape *un, struct buf *bp);
521 static void st_done_and_mutex_exit(struct scsi_tape *un, struct buf *bp);
522 static void st_init(struct scsi_tape *un);
523 static void st_make_cmd(struct scsi_tape *un, struct buf *bp,
524     int (*func)(caddr_t));
525 static void st_make_uscsi_cmd(struct scsi_tape *, struct uscsi_cmd *,
526     struct buf *bp, int (*func)(caddr_t));
527 static void st_intr(struct scsi_pkt *pkt);
528 static void st_set_state(struct scsi_tape *un, buf_t *bp);
529 static void st_test_append(struct buf *bp);
530 static int st_runout(caddr_t);
531 static int st_cmd(struct scsi_tape *un, int com, int64_t count, int wait);
532 static int st_setup_cmd(struct scsi_tape *un, buf_t *bp, int com,
533     int64_t count);
534 static int st_set_compression(struct scsi_tape *un);
535 static int st_write_fm(dev_t dev, int wfm);
536 static int st_determine_generic(struct scsi_tape *un);
537 static int st_determine_density(struct scsi_tape *un, int rw);
538 static int st_get_density(struct scsi_tape *un);
539 static int st_set_density(struct scsi_tape *un);
540 static int st_loadtape(struct scsi_tape *un);
541 static int st_modesense(struct scsi_tape *un);
542 static int st_modeselect(struct scsi_tape *un);
543 static errstate st_handle_incomplete(struct scsi_tape *un, struct buf *bp);
544 static int st_wrongtapetype(struct scsi_tape *un);
545 static errstate st_check_error(struct scsi_tape *un, struct scsi_pkt *pkt);
546 static errstate st_handle_sense(struct scsi_tape *un, struct buf *bp,
547     tapepos_t *);
548 static errstate st_handle_autosense(struct scsi_tape *un, struct buf *bp,
549     tapepos_t *);
550 static int st_get_error_entry(struct scsi_tape *un, intptr_t arg, int flag);
551 static void st_update_error_stack(struct scsi_tape *un, struct scsi_pkt *pkt,
552     struct scsi_arq_status *cmd);
553 static void st_empty_error_stack(struct scsi_tape *un);
554 static errstate st_decode_sense(struct scsi_tape *un, struct buf *bp, int amt,
555     struct scsi_arq_status *, tapepos_t *);
556 static int st_report_soft_errors(dev_t dev, int flag);
557 static void st_delayed_cv_broadcast(void *arg);
558 static int st_check_media(dev_t dev, enum mtio_state state);
559 static int st_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
560 static void st_intr_restart(void *arg);
561 static void st_start_restart(void *arg);
562 static int st_gen_mode_sense(struct scsi_tape *un, ubufunc_t ubf, int page,
563     struct seq_mode *page_data, int page_size);
564 static int st_change_block_size(struct scsi_tape *un, uint32_t nblksz);
565 static int st_gen_mode_select(struct scsi_tape *un, ubufunc_t ubf,
566     struct seq_mode *page_data, int page_size);
567 static int st_read_block_limits(struct scsi_tape *un,
568     struct read_blklim *read_blk);
569 static int st_report_density_support(struct scsi_tape *un,
570     uchar_t *density_data, size_t buflen);
571 static int st_report_supported_operation(struct scsi_tape *un,
572     uchar_t *oper_data, uchar_t option_code, ushort_t service_action);
573 static int st_tape_init(struct scsi_tape *un);
574 static void st_flush(struct scsi_tape *un);
575 static void st_set_pe_errno(struct scsi_tape *un);
576 static void st_hba_unflush(struct scsi_tape *un);
577 static void st_turn_pe_on(struct scsi_tape *un);
578 static void st_turn_pe_off(struct scsi_tape *un);
579 static void st_set_pe_flag(struct scsi_tape *un);
580 static void st_clear_pe(struct scsi_tape *un);
581 static void st_wait_for_io(struct scsi_tape *un);
582 static int st_set_devconfig_page(struct scsi_tape *un, int compression_on);
583 static int st_set_datacomp_page(struct scsi_tape *un, int compression_on);
584 static int st_reserve_release(struct scsi_tape *un, int command, ubufunc_t ubf);
585 static int st_check_cdb_for_need_to_reserve(struct scsi_tape *un, uchar_t *cdb);
586 static int st_check_cmd_for_need_to_reserve(struct scsi_tape *un, uchar_t cmd,
587     int count);
588 static int st_take_ownership(struct scsi_tape *un, ubufunc_t ubf);
589 static int st_check_asc_ascq(struct scsi_tape *un);
590 static int st_check_clean_bit(struct scsi_tape *un);
591 static int st_check_alert_flags(struct scsi_tape *un);
592 static int st_check_sequential_clean_bit(struct scsi_tape *un);
593 static int st_check_sense_clean_bit(struct scsi_tape *un);
594 static int st_clear_unit_attentions(dev_t dev_instance, int max_trys);
595 static void st_calculate_timeouts(struct scsi_tape *un);
596 static writablity st_is_drive_worm(struct scsi_tape *un);
597 static int st_read_attributes(struct scsi_tape *un, uint16_t attribute,
598     void *buf, size_t size, ubufunc_t bufunc);
599 static int st_get_special_inquiry(struct scsi_tape *un, uchar_t size,
600     caddr_t dest, uchar_t page);
601 static int st_update_block_pos(struct scsi_tape *un, bufunc_t bf,
602     int post_space);
603 static 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);
605 static int st_get_read_pos(struct scsi_tape *un, buf_t *bp);
606 static int st_logical_block_locate(struct scsi_tape *un, ubufunc_t ubf,
607     tapepos_t *pos, uint64_t lblk, uchar_t partition);
608 static int st_mtfsf_ioctl(struct scsi_tape *un, int64_t files);
609 static int st_mtfsr_ioctl(struct scsi_tape *un, int64_t count);
610 static int st_mtbsf_ioctl(struct scsi_tape *un, int64_t files);
611 static int st_mtnbsf_ioctl(struct scsi_tape *un, int64_t count);
612 static int st_mtbsr_ioctl(struct scsi_tape *un, int64_t num);
613 static int st_mtfsfm_ioctl(struct scsi_tape *un, int64_t cnt);
614 static int st_mtbsfm_ioctl(struct scsi_tape *un, int64_t cnt);
615 static int st_backward_space_files(struct scsi_tape *un, int64_t count,
616     int infront);
617 static int st_forward_space_files(struct scsi_tape *un, int64_t files);
618 static int st_scenic_route_to_begining_of_file(struct scsi_tape *un,
619     int32_t fileno);
620 static int st_space_to_begining_of_file(struct scsi_tape *un);
621 static int st_space_records(struct scsi_tape *un, int64_t records);
622 static int st_get_media_identification(struct scsi_tape *un, ubufunc_t bufunc);
623 static errstate st_command_recovery(struct scsi_tape *un, struct scsi_pkt *pkt,
624     errstate onentry);
625 static void st_recover(void *arg);
626 static void st_recov_cb(struct scsi_pkt *pkt);
627 static int st_rcmd(struct scsi_tape *un, int com, int64_t count, int wait);
628 static int st_uscsi_rcmd(struct scsi_tape *un, struct uscsi_cmd *ucmd,
629     int flag);
630 static void st_add_recovery_info_to_pkt(struct scsi_tape *un, buf_t *bp,
631     struct scsi_pkt *cmd);
632 static int st_check_mode_for_change(struct scsi_tape *un, ubufunc_t ubf);
633 static int st_test_path_to_device(struct scsi_tape *un);
634 static int st_recovery_read_pos(struct scsi_tape *un, read_p_types type,
635     read_pos_data_t *raw);
636 static int st_recovery_get_position(struct scsi_tape *un, tapepos_t *read,
637     read_pos_data_t *raw);
638 static int st_compare_expected_position(struct scsi_tape *un, st_err_info *ei,
639     cmd_attribute const * cmd_att, tapepos_t *read);
640 static errstate st_recover_reissue_pkt(struct scsi_tape *us,
641     struct scsi_pkt *pkt);
642 static int st_transport(struct scsi_tape *un, struct scsi_pkt *pkt);
643 static buf_t *st_remove_from_queue(buf_t **head, buf_t **tail, buf_t *bp);
644 static void st_add_to_queue(buf_t **head, buf_t **tail, buf_t *end, buf_t *bp);
645 static int st_reset(struct scsi_tape *un, int reset_type);
646 static void st_reset_notification(caddr_t arg);
647 static const cmd_attribute *st_lookup_cmd_attribute(unsigned char cmd);
648 
649 static int st_set_target_TLR_mode(struct scsi_tape *un, ubufunc_t ubf);
650 static 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  */
657 static void st_release_contig_mem(struct scsi_tape *un, struct contig_mem *cp);
658 static struct contig_mem *st_get_contig_mem(struct scsi_tape *un, size_t len,
659     int alloc_flags);
660 static int st_bigblk_xfer_done(struct buf *bp);
661 static struct buf *st_get_bigblk_bp(struct buf *bp);
662 #endif
663 static 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  */
669 static int st_create_errstats(struct scsi_tape *, int);
670 static int st_validate_tapemarks(struct scsi_tape *un, ubufunc_t ubf,
671     tapepos_t *pos);
672 
673 #ifdef STDEBUG
674 static void st_debug_cmds(struct scsi_tape *un, int com, int count, int wait);
675 #endif /* STDEBUG */
676 static 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 
691 static 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 
697 static 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 
729 int
_init(void)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 
763 int
_fini(void)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 
781 int
_info(struct modinfo * modinfop)782 _info(struct modinfo *modinfop)
783 {
784 	return (mod_info(&modlinkage, modinfop));
785 }
786 
787 
788 static int
st_probe(dev_info_t * devi)789 st_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 
863 static int
st_attach(dev_info_t * devi,ddi_attach_cmd_t cmd)864 st_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*/
1216 static int
st_detach(dev_info_t * devi,ddi_detach_cmd_t cmd)1217 st_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 */
1570 static int
st_info(dev_info_t * dip,ddi_info_cmd_t infocmd,void * arg,void ** result)1571 st_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 
1600 static int
st_doattach(struct scsi_device * devp,int (* canwait)())1601 st_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 
1787 error:
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 
1830 typedef int
1831 (*cfg_functp)(struct scsi_tape *, char *vidpid, struct st_drivetype *);
1832 
1833 static 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  */
1845 static void
st_known_tape_type(struct scsi_tape * un)1846 st_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 
1958 typedef struct {
1959 	int mask;
1960 	int bottom;
1961 	int top;
1962 	char *name;
1963 } conf_limit;
1964 
1965 static 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 
1983 static int
st_validate_conf_data(struct scsi_tape * un,int * list,int list_len,const char * conf_name)1984 st_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 
2072 static int
st_get_conf_from_st_dot_conf(struct scsi_tape * un,char * vidpid,struct st_drivetype * dp)2073 st_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 
2241 static int
st_get_conf_from_st_conf_dot_c(struct scsi_tape * un,char * vidpid,struct st_drivetype * dp)2242 st_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 
2270 static int
st_get_conf_from_tape_drive(struct scsi_tape * un,char * vidpid,struct st_drivetype * dp)2271 st_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 
2431 exit:
2432 	un->un_status = KEY_NO_SENSE;
2433 	kmem_free(tem_dp, sizeof (struct st_drivetype));
2434 	return (rval);
2435 }
2436 
2437 static int
st_get_densities_from_tape_drive(struct scsi_tape * un,struct st_drivetype * dp)2438 st_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 
2590 static int
st_get_timeout_values_from_tape_drive(struct scsi_tape * un,struct st_drivetype * dp)2591 st_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 
2680 static int
st_get_timeouts_value(struct scsi_tape * un,uchar_t option_code,ushort_t * timeout_value,ushort_t service_action)2681 st_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 
2746 static int
st_get_default_conf(struct scsi_tape * un,char * vidpid,struct st_drivetype * dp)2747 st_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 */
2788 static int
st_open(dev_t * dev_p,int flag,int otyp,cred_t * cred_p)2789 st_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 
2930 exit:
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 	}
2943 busy:
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 
2951 static int
st_tape_init(struct scsi_tape * un)2952 st_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 
3362 exit:
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 */
3376 static int
st_close(dev_t dev,int flag,int otyp,cred_t * cred_p)3377 st_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 	/