xref: /freebsd-14.2/sys/cam/scsi/scsi_sa.c (revision 55205bea)
1 /*-
2  * Implementation of SCSI Sequential Access Peripheral driver for CAM.
3  *
4  * SPDX-License-Identifier: BSD-2-Clause
5  *
6  * Copyright (c) 1999, 2000 Matthew Jacob
7  * Copyright (c) 2013, 2014, 2015, 2021 Spectra Logic Corporation
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions, and the following disclaimer,
15  *    without modification, immediately at the beginning of the file.
16  * 2. The name of the author may not be used to endorse or promote products
17  *    derived from this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
23  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #include <sys/param.h>
34 #include <sys/queue.h>
35 #ifdef _KERNEL
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
38 #endif
39 #include <sys/types.h>
40 #include <sys/time.h>
41 #include <sys/bio.h>
42 #include <sys/limits.h>
43 #include <sys/malloc.h>
44 #include <sys/mtio.h>
45 #ifdef _KERNEL
46 #include <sys/conf.h>
47 #include <sys/sbuf.h>
48 #include <sys/sysctl.h>
49 #include <sys/taskqueue.h>
50 #endif
51 #include <sys/fcntl.h>
52 #include <sys/devicestat.h>
53 
54 #ifndef _KERNEL
55 #include <stdio.h>
56 #include <string.h>
57 #endif
58 
59 #include <cam/cam.h>
60 #include <cam/cam_ccb.h>
61 #include <cam/cam_periph.h>
62 #include <cam/cam_xpt_periph.h>
63 #include <cam/cam_debug.h>
64 
65 #include <cam/scsi/scsi_all.h>
66 #include <cam/scsi/scsi_message.h>
67 #include <cam/scsi/scsi_sa.h>
68 
69 #ifdef _KERNEL
70 
71 #include "opt_sa.h"
72 
73 #ifndef SA_IO_TIMEOUT
74 #define SA_IO_TIMEOUT		32
75 #endif
76 #ifndef SA_SPACE_TIMEOUT
77 #define SA_SPACE_TIMEOUT	1 * 60
78 #endif
79 #ifndef SA_REWIND_TIMEOUT
80 #define SA_REWIND_TIMEOUT	2 * 60
81 #endif
82 #ifndef SA_ERASE_TIMEOUT
83 #define SA_ERASE_TIMEOUT	4 * 60
84 #endif
85 #ifndef SA_REP_DENSITY_TIMEOUT
86 #define SA_REP_DENSITY_TIMEOUT	1
87 #endif
88 
89 #define	SCSIOP_TIMEOUT		(60 * 1000)	/* not an option */
90 
91 #define	IO_TIMEOUT		(SA_IO_TIMEOUT * 60 * 1000)
92 #define	REWIND_TIMEOUT		(SA_REWIND_TIMEOUT * 60 * 1000)
93 #define	ERASE_TIMEOUT		(SA_ERASE_TIMEOUT * 60 * 1000)
94 #define	SPACE_TIMEOUT		(SA_SPACE_TIMEOUT * 60 * 1000)
95 #define	REP_DENSITY_TIMEOUT	(SA_REP_DENSITY_TIMEOUT * 60 * 1000)
96 
97 /*
98  * Additional options that can be set for config: SA_1FM_AT_EOT
99  */
100 
101 #ifndef	UNUSED_PARAMETER
102 #define	UNUSED_PARAMETER(x)	x = x
103 #endif
104 
105 #define	QFRLS(ccb)	\
106 	if (((ccb)->ccb_h.status & CAM_DEV_QFRZN) != 0)	\
107 		cam_release_devq((ccb)->ccb_h.path, 0, 0, 0, FALSE)
108 
109 /*
110  * Driver states
111  */
112 
113 static MALLOC_DEFINE(M_SCSISA, "SCSI sa", "SCSI sequential access buffers");
114 
115 typedef enum {
116 	SA_STATE_NORMAL, SA_STATE_PROBE, SA_STATE_ABNORMAL
117 } sa_state;
118 
119 #define ccb_pflags	ppriv_field0
120 #define ccb_bp	 	ppriv_ptr1
121 
122 /* bits in ccb_pflags */
123 #define	SA_POSITION_UPDATED	0x1
124 
125 typedef enum {
126 	SA_FLAG_OPEN		= 0x00001,
127 	SA_FLAG_FIXED		= 0x00002,
128 	SA_FLAG_TAPE_LOCKED	= 0x00004,
129 	SA_FLAG_TAPE_MOUNTED	= 0x00008,
130 	SA_FLAG_TAPE_WP		= 0x00010,
131 	SA_FLAG_TAPE_WRITTEN	= 0x00020,
132 	SA_FLAG_EOM_PENDING	= 0x00040,
133 	SA_FLAG_EIO_PENDING	= 0x00080,
134 	SA_FLAG_EOF_PENDING	= 0x00100,
135 	SA_FLAG_ERR_PENDING	= (SA_FLAG_EOM_PENDING|SA_FLAG_EIO_PENDING|
136 				   SA_FLAG_EOF_PENDING),
137 	SA_FLAG_INVALID		= 0x00200,
138 	SA_FLAG_COMP_ENABLED	= 0x00400,
139 	SA_FLAG_COMP_SUPP	= 0x00800,
140 	SA_FLAG_COMP_UNSUPP	= 0x01000,
141 	SA_FLAG_TAPE_FROZEN	= 0x02000,
142 	SA_FLAG_PROTECT_SUPP	= 0x04000,
143 
144 	SA_FLAG_COMPRESSION	= (SA_FLAG_COMP_SUPP|SA_FLAG_COMP_ENABLED|
145 				   SA_FLAG_COMP_UNSUPP),
146 	SA_FLAG_SCTX_INIT	= 0x08000,
147 	SA_FLAG_RSOC_TO_TRY	= 0x10000,
148 } sa_flags;
149 
150 typedef enum {
151 	SA_MODE_REWIND		= 0x00,
152 	SA_MODE_NOREWIND	= 0x01,
153 	SA_MODE_OFFLINE		= 0x02
154 } sa_mode;
155 
156 typedef enum {
157 	SA_TIMEOUT_ERASE,
158 	SA_TIMEOUT_LOAD,
159 	SA_TIMEOUT_LOCATE,
160 	SA_TIMEOUT_MODE_SELECT,
161 	SA_TIMEOUT_MODE_SENSE,
162 	SA_TIMEOUT_PREVENT,
163 	SA_TIMEOUT_READ,
164 	SA_TIMEOUT_READ_BLOCK_LIMITS,
165 	SA_TIMEOUT_READ_POSITION,
166 	SA_TIMEOUT_REP_DENSITY,
167 	SA_TIMEOUT_RESERVE,
168 	SA_TIMEOUT_REWIND,
169 	SA_TIMEOUT_SPACE,
170 	SA_TIMEOUT_TUR,
171 	SA_TIMEOUT_WRITE,
172 	SA_TIMEOUT_WRITE_FILEMARKS,
173 	SA_TIMEOUT_TYPE_MAX
174 } sa_timeout_types;
175 
176 /*
177  * These are the default timeout values that apply to all tape drives.
178  *
179  * We get timeouts from the following places in order of increasing
180  * priority:
181  * 1. Driver default timeouts. (Set in the structure below.)
182  * 2. Timeouts loaded from the drive via REPORT SUPPORTED OPERATION
183  *    CODES.  (If the drive supports it, SPC-4/LTO-5 and newer should.)
184  * 3. Global loader tunables, used for all sa(4) driver instances on
185  *    a machine.
186  * 4. Instance-specific loader tunables, used for say sa5.
187  * 5. On the fly user sysctl changes.
188  *
189  * Each step will overwrite the timeout value set from the one
190  * before, so you go from general to most specific.
191  */
192 static struct sa_timeout_desc {
193 	const char *desc;
194 	int value;
195 } sa_default_timeouts[SA_TIMEOUT_TYPE_MAX] = {
196 	{"erase", 		ERASE_TIMEOUT},
197 	{"load",		REWIND_TIMEOUT},
198 	{"locate",		SPACE_TIMEOUT},
199 	{"mode_select", 	SCSIOP_TIMEOUT},
200 	{"mode_sense",		SCSIOP_TIMEOUT},
201 	{"prevent",		SCSIOP_TIMEOUT},
202 	{"read",		IO_TIMEOUT},
203 	{"read_block_limits",	SCSIOP_TIMEOUT},
204 	{"read_position",	SCSIOP_TIMEOUT},
205 	{"report_density",	REP_DENSITY_TIMEOUT},
206 	{"reserve",		SCSIOP_TIMEOUT},
207 	{"rewind",		REWIND_TIMEOUT},
208 	{"space",		SPACE_TIMEOUT},
209 	{"tur",			SCSIOP_TIMEOUT},
210 	{"write", 		IO_TIMEOUT},
211 	{"write_filemarks",	IO_TIMEOUT},
212 };
213 
214 typedef enum {
215 	SA_PARAM_NONE		= 0x000,
216 	SA_PARAM_BLOCKSIZE	= 0x001,
217 	SA_PARAM_DENSITY	= 0x002,
218 	SA_PARAM_COMPRESSION	= 0x004,
219 	SA_PARAM_BUFF_MODE	= 0x008,
220 	SA_PARAM_NUMBLOCKS	= 0x010,
221 	SA_PARAM_WP		= 0x020,
222 	SA_PARAM_SPEED		= 0x040,
223 	SA_PARAM_DENSITY_EXT	= 0x080,
224 	SA_PARAM_LBP		= 0x100,
225 	SA_PARAM_ALL		= 0x1ff
226 } sa_params;
227 
228 typedef enum {
229 	SA_QUIRK_NONE		= 0x000,
230 	SA_QUIRK_NOCOMP		= 0x001, /* Can't deal with compression at all*/
231 	SA_QUIRK_FIXED		= 0x002, /* Force fixed mode */
232 	SA_QUIRK_VARIABLE	= 0x004, /* Force variable mode */
233 	SA_QUIRK_2FM		= 0x008, /* Needs Two File Marks at EOD */
234 	SA_QUIRK_1FM		= 0x010, /* No more than 1 File Mark at EOD */
235 	SA_QUIRK_NODREAD	= 0x020, /* Don't try and dummy read density */
236 	SA_QUIRK_NO_MODESEL	= 0x040, /* Don't do mode select at all */
237 	SA_QUIRK_NO_CPAGE	= 0x080, /* Don't use DEVICE COMPRESSION page */
238 	SA_QUIRK_NO_LONG_POS	= 0x100  /* No long position information */
239 } sa_quirks;
240 
241 #define SA_QUIRK_BIT_STRING	\
242 	"\020"			\
243 	"\001NOCOMP"		\
244 	"\002FIXED"		\
245 	"\003VARIABLE"		\
246 	"\0042FM"		\
247 	"\0051FM"		\
248 	"\006NODREAD"		\
249 	"\007NO_MODESEL"	\
250 	"\010NO_CPAGE"		\
251 	"\011NO_LONG_POS"
252 
253 #define	SAMODE(z)	(dev2unit(z) & 0x3)
254 #define	SA_IS_CTRL(z)	(dev2unit(z) & (1 << 4))
255 
256 #define SA_NOT_CTLDEV	0
257 #define SA_CTLDEV	1
258 
259 #define SA_ATYPE_R	0
260 #define SA_ATYPE_NR	1
261 #define SA_ATYPE_ER	2
262 #define SA_NUM_ATYPES	3
263 
264 #define	SAMINOR(ctl, access) \
265 	((ctl << 4) | (access & 0x3))
266 
267 struct sa_devs {
268 	struct cdev *ctl_dev;
269 	struct cdev *r_dev;
270 	struct cdev *nr_dev;
271 	struct cdev *er_dev;
272 };
273 
274 #define	SASBADDBASE(sb, indent, data, xfmt, name, type, xsize, desc)	\
275 	sbuf_printf(sb, "%*s<%s type=\"%s\" size=\"%zd\" "		\
276 	    "fmt=\"%s\" desc=\"%s\">" #xfmt "</%s>\n", indent, "", 	\
277 	    #name, #type, xsize, #xfmt, desc ? desc : "", data, #name);
278 
279 #define	SASBADDINT(sb, indent, data, fmt, name)				\
280 	SASBADDBASE(sb, indent, data, fmt, name, int, sizeof(data),	\
281 		    NULL)
282 
283 #define	SASBADDINTDESC(sb, indent, data, fmt, name, desc)		\
284 	SASBADDBASE(sb, indent, data, fmt, name, int, sizeof(data),	\
285 		    desc)
286 
287 #define	SASBADDUINT(sb, indent, data, fmt, name)			\
288 	SASBADDBASE(sb, indent, data, fmt, name, uint, sizeof(data), 	\
289 		    NULL)
290 
291 #define	SASBADDUINTDESC(sb, indent, data, fmt, name, desc)		\
292 	SASBADDBASE(sb, indent, data, fmt, name, uint, sizeof(data), 	\
293 		    desc)
294 
295 #define	SASBADDFIXEDSTR(sb, indent, data, fmt, name)			\
296 	SASBADDBASE(sb, indent, data, fmt, name, str, sizeof(data),	\
297 		    NULL)
298 
299 #define	SASBADDFIXEDSTRDESC(sb, indent, data, fmt, name, desc)		\
300 	SASBADDBASE(sb, indent, data, fmt, name, str, sizeof(data),	\
301 		    desc)
302 
303 #define	SASBADDVARSTR(sb, indent, data, fmt, name, maxlen)		\
304 	SASBADDBASE(sb, indent, data, fmt, name, str, maxlen, NULL)
305 
306 #define	SASBADDVARSTRDESC(sb, indent, data, fmt, name, maxlen, desc)	\
307 	SASBADDBASE(sb, indent, data, fmt, name, str, maxlen, desc)
308 
309 #define	SASBADDNODE(sb, indent, name) {					\
310 	sbuf_printf(sb, "%*s<%s type=\"%s\">\n", indent, "", #name,	\
311 	    "node");							\
312 	indent += 2;							\
313 }
314 
315 #define	SASBADDNODENUM(sb, indent, name, num) {				\
316 	sbuf_printf(sb, "%*s<%s type=\"%s\" num=\"%d\">\n", indent, "",	\
317 	    #name, "node", num);					\
318 	indent += 2;							\
319 }
320 
321 #define	SASBENDNODE(sb, indent, name) {					\
322 	indent -= 2;							\
323 	sbuf_printf(sb, "%*s</%s>\n", indent, "", #name);		\
324 }
325 
326 #define	SA_DENSITY_TYPES	4
327 
328 struct sa_prot_state {
329 	int initialized;
330 	uint32_t prot_method;
331 	uint32_t pi_length;
332 	uint32_t lbp_w;
333 	uint32_t lbp_r;
334 	uint32_t rbdp;
335 };
336 
337 struct sa_prot_info {
338 	struct sa_prot_state cur_prot_state;
339 	struct sa_prot_state pending_prot_state;
340 };
341 
342 /*
343  * A table mapping protection parameters to their types and values.
344  */
345 struct sa_prot_map {
346 	char *name;
347 	mt_param_set_type param_type;
348 	off_t offset;
349 	uint32_t min_val;
350 	uint32_t max_val;
351 	uint32_t *value;
352 } sa_prot_table[] = {
353 	{ "prot_method", MT_PARAM_SET_UNSIGNED,
354 	  __offsetof(struct sa_prot_state, prot_method),
355 	  /*min_val*/ 0, /*max_val*/ 255, NULL },
356 	{ "pi_length", MT_PARAM_SET_UNSIGNED,
357 	  __offsetof(struct sa_prot_state, pi_length),
358 	  /*min_val*/ 0, /*max_val*/ SA_CTRL_DP_PI_LENGTH_MASK, NULL },
359 	{ "lbp_w", MT_PARAM_SET_UNSIGNED,
360 	  __offsetof(struct sa_prot_state, lbp_w),
361 	  /*min_val*/ 0, /*max_val*/ 1, NULL },
362 	{ "lbp_r", MT_PARAM_SET_UNSIGNED,
363 	  __offsetof(struct sa_prot_state, lbp_r),
364 	  /*min_val*/ 0, /*max_val*/ 1, NULL },
365 	{ "rbdp", MT_PARAM_SET_UNSIGNED,
366 	  __offsetof(struct sa_prot_state, rbdp),
367 	  /*min_val*/ 0, /*max_val*/ 1, NULL }
368 };
369 
370 #define	SA_NUM_PROT_ENTS nitems(sa_prot_table)
371 
372 #define	SA_PROT_ENABLED(softc) ((softc->flags & SA_FLAG_PROTECT_SUPP)	\
373 	&& (softc->prot_info.cur_prot_state.initialized != 0)		\
374 	&& (softc->prot_info.cur_prot_state.prot_method != 0))
375 
376 #define	SA_PROT_LEN(softc)	softc->prot_info.cur_prot_state.pi_length
377 
378 struct sa_softc {
379 	sa_state	state;
380 	sa_flags	flags;
381 	sa_quirks	quirks;
382 	u_int		si_flags;
383 	struct cam_periph *periph;
384 	struct		bio_queue_head bio_queue;
385 	int		queue_count;
386 	struct		devstat *device_stats;
387 	struct sa_devs	devs;
388 	int		open_count;
389 	int		num_devs_to_destroy;
390 	int		blk_gran;
391 	int		blk_mask;
392 	int		blk_shift;
393 	uint32_t	max_blk;
394 	uint32_t	min_blk;
395 	uint32_t	maxio;
396 	uint32_t	cpi_maxio;
397 	int		allow_io_split;
398 	int		inject_eom;
399 	int		set_pews_status;
400 	uint32_t	comp_algorithm;
401 	uint32_t	saved_comp_algorithm;
402 	uint32_t	media_blksize;
403 	uint32_t	last_media_blksize;
404 	uint32_t	media_numblks;
405 	uint8_t	media_density;
406 	uint8_t	speed;
407 	uint8_t	scsi_rev;
408 	uint8_t	dsreg;		/* mtio mt_dsreg, redux */
409 	int		buffer_mode;
410 	int		filemarks;
411 	int		last_resid_was_io;
412 	uint8_t		density_type_bits[SA_DENSITY_TYPES];
413 	int		density_info_valid[SA_DENSITY_TYPES];
414 	uint8_t		density_info[SA_DENSITY_TYPES][SRDS_MAX_LENGTH];
415 	int		timeout_info[SA_TIMEOUT_TYPE_MAX];
416 
417 	struct sa_prot_info	prot_info;
418 
419 	int		sili;
420 	int		eot_warn;
421 
422 	/*
423 	 * Current position information.  -1 means that the given value is
424 	 * unknown.  fileno and blkno are always calculated.  blkno is
425 	 * relative to the previous file mark.  rep_fileno and rep_blkno
426 	 * are as reported by the drive, if it supports the long form
427 	 * report for the READ POSITION command.  rep_blkno is relative to
428 	 * the beginning of the partition.
429 	 *
430 	 * bop means that the drive is at the beginning of the partition.
431 	 * eop means that the drive is between early warning and end of
432 	 * partition, inside the current partition.
433 	 * bpew means that the position is in a PEWZ (Programmable Early
434 	 * Warning Zone)
435 	 */
436 	daddr_t		partition;	/* Absolute from BOT */
437 	daddr_t		fileno;		/* Relative to beginning of partition */
438 	daddr_t		blkno;		/* Relative to last file mark */
439 	daddr_t		rep_blkno;	/* Relative to beginning of partition */
440 	daddr_t		rep_fileno;	/* Relative to beginning of partition */
441 	int		bop;		/* Beginning of Partition */
442 	int		eop;		/* End of Partition */
443 	int		bpew;		/* Beyond Programmable Early Warning */
444 
445 	/*
446 	 * Latched Error Info
447 	 */
448 	struct {
449 		struct scsi_sense_data _last_io_sense;
450 		uint64_t _last_io_resid;
451 		uint8_t _last_io_cdb[CAM_MAX_CDBLEN];
452 		struct scsi_sense_data _last_ctl_sense;
453 		uint64_t _last_ctl_resid;
454 		uint8_t _last_ctl_cdb[CAM_MAX_CDBLEN];
455 #define	last_io_sense	errinfo._last_io_sense
456 #define	last_io_resid	errinfo._last_io_resid
457 #define	last_io_cdb	errinfo._last_io_cdb
458 #define	last_ctl_sense	errinfo._last_ctl_sense
459 #define	last_ctl_resid	errinfo._last_ctl_resid
460 #define	last_ctl_cdb	errinfo._last_ctl_cdb
461 	} errinfo;
462 	/*
463 	 * Misc other flags/state
464 	 */
465 	uint32_t
466 					: 29,
467 		open_rdonly		: 1,	/* open read-only */
468 		open_pending_mount	: 1,	/* open pending mount */
469 		ctrl_mode		: 1;	/* control device open */
470 
471 	struct task		sysctl_task;
472 	struct sysctl_ctx_list	sysctl_ctx;
473 	struct sysctl_oid	*sysctl_tree;
474 	struct sysctl_ctx_list	sysctl_timeout_ctx;
475 	struct sysctl_oid	*sysctl_timeout_tree;
476 };
477 
478 struct sa_quirk_entry {
479 	struct scsi_inquiry_pattern inq_pat;	/* matching pattern */
480 	sa_quirks quirks;	/* specific quirk type */
481 	uint32_t prefblk;	/* preferred blocksize when in fixed mode */
482 };
483 
484 static struct sa_quirk_entry sa_quirk_table[] =
485 {
486 	{
487 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "OnStream",
488 		  "ADR*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_NODREAD |
489 		   SA_QUIRK_1FM|SA_QUIRK_NO_MODESEL, 32768
490 	},
491 	{
492 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
493 		  "Python 06408*", "*"}, SA_QUIRK_NODREAD, 0
494 	},
495 	{
496 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
497 		  "Python 25601*", "*"}, SA_QUIRK_NOCOMP|SA_QUIRK_NODREAD, 0
498 	},
499 	{
500 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
501 		  "Python*", "*"}, SA_QUIRK_NODREAD, 0
502 	},
503 	{
504 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
505 		  "VIPER 150*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 512
506 	},
507 	{
508 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
509 		  "VIPER 2525 25462", "-011"},
510 		  SA_QUIRK_NOCOMP|SA_QUIRK_1FM|SA_QUIRK_NODREAD, 0
511 	},
512 	{
513 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
514 		  "VIPER 2525*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 1024
515 	},
516 #if	0
517 	{
518 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "HP",
519 		  "C15*", "*"}, SA_QUIRK_VARIABLE|SA_QUIRK_NO_CPAGE, 0,
520 	},
521 #endif
522  	{
523  		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "HP",
524 		  "C56*", "*"}, SA_QUIRK_VARIABLE|SA_QUIRK_2FM, 0
525 	},
526 	{
527 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "HP",
528 		  "T20*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 512
529 	},
530 	{
531 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "HP",
532 		  "T4000*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 512
533 	},
534 	{
535 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "HP",
536 		  "HP-88780*", "*"}, SA_QUIRK_VARIABLE|SA_QUIRK_2FM, 0
537 	},
538 	{
539 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "KENNEDY",
540 		  "*", "*"}, SA_QUIRK_VARIABLE|SA_QUIRK_2FM, 0
541 	},
542 	{
543 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "M4 DATA",
544 		  "123107 SCSI*", "*"}, SA_QUIRK_VARIABLE|SA_QUIRK_2FM, 0
545 	},
546 	{	/* [email protected] */
547 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "Seagate",
548 		"STT8000N*", "*"}, SA_QUIRK_1FM, 0
549 	},
550 	{	/* [email protected] */
551 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "Seagate",
552 		"STT20000*", "*"}, SA_QUIRK_1FM, 0
553 	},
554 	{
555 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "SEAGATE",
556 		"DAT    06241-XXX", "*"}, SA_QUIRK_VARIABLE|SA_QUIRK_2FM, 0
557 	},
558 	{
559 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
560 		  " TDC 3600", "U07:"}, SA_QUIRK_NOCOMP|SA_QUIRK_1FM, 512
561 	},
562 	{
563 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
564 		  " TDC 3800", "*"}, SA_QUIRK_NOCOMP|SA_QUIRK_1FM, 512
565 	},
566 	{
567 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
568 		  " TDC 4100", "*"}, SA_QUIRK_NOCOMP|SA_QUIRK_1FM, 512
569 	},
570 	{
571 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
572 		  " TDC 4200", "*"}, SA_QUIRK_NOCOMP|SA_QUIRK_1FM, 512
573 	},
574 	{
575 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
576 		  " SLR*", "*"}, SA_QUIRK_1FM, 0
577 	},
578 	{
579 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "WANGTEK",
580 		  "5525ES*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 512
581 	},
582 	{
583 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "WANGTEK",
584 		  "51000*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 1024
585 	}
586 };
587 
588 static	d_open_t	saopen;
589 static	d_close_t	saclose;
590 static	d_strategy_t	sastrategy;
591 static	d_ioctl_t	saioctl;
592 static	periph_init_t	sainit;
593 static	periph_ctor_t	saregister;
594 static	periph_oninv_t	saoninvalidate;
595 static	periph_dtor_t	sacleanup;
596 static	periph_start_t	sastart;
597 static	void		saasync(void *callback_arg, uint32_t code,
598 				struct cam_path *path, void *arg);
599 static	void		sadone(struct cam_periph *periph,
600 			       union ccb *start_ccb);
601 static  int		saerror(union ccb *ccb, uint32_t cam_flags,
602 				uint32_t sense_flags);
603 static int		samarkswanted(struct cam_periph *);
604 static int		sacheckeod(struct cam_periph *periph);
605 static int		sagetparams(struct cam_periph *periph,
606 				    sa_params params_to_get,
607 				    uint32_t *blocksize, uint8_t *density,
608 				    uint32_t *numblocks, int *buff_mode,
609 				    uint8_t *write_protect, uint8_t *speed,
610 				    int *comp_supported, int *comp_enabled,
611 				    uint32_t *comp_algorithm,
612 				    sa_comp_t *comp_page,
613 				    struct scsi_control_data_prot_subpage
614 				    *prot_page, int dp_size,
615 				    int prot_changeable);
616 static int		sasetprot(struct cam_periph *periph,
617 				  struct sa_prot_state *new_prot);
618 static int		sasetparams(struct cam_periph *periph,
619 				    sa_params params_to_set,
620 				    uint32_t blocksize, uint8_t density,
621 				    uint32_t comp_algorithm,
622 				    uint32_t sense_flags);
623 static int		sasetsili(struct cam_periph *periph,
624 				  struct mtparamset *ps, int num_params);
625 static int		saseteotwarn(struct cam_periph *periph,
626 				     struct mtparamset *ps, int num_params);
627 static void		safillprot(struct sa_softc *softc, int *indent,
628 				   struct sbuf *sb);
629 static void		sapopulateprots(struct sa_prot_state *cur_state,
630 					struct sa_prot_map *new_table,
631 					int table_ents);
632 static struct sa_prot_map *safindprotent(char *name, struct sa_prot_map *table,
633 					 int table_ents);
634 static int		sasetprotents(struct cam_periph *periph,
635 				      struct mtparamset *ps, int num_params);
636 static const struct sa_param_ent *safindparament(struct mtparamset *ps);
637 static int		saparamsetlist(struct cam_periph *periph,
638 				       struct mtsetlist *list, int need_copy);
639 static	int		saextget(struct cdev *dev, struct cam_periph *periph,
640 				 struct sbuf *sb, struct mtextget *g);
641 static	int		saparamget(struct sa_softc *softc, struct sbuf *sb);
642 static void		saprevent(struct cam_periph *periph, int action);
643 static int		sarewind(struct cam_periph *periph);
644 static int		saspace(struct cam_periph *periph, int count,
645 				scsi_space_code code);
646 static void		sadevgonecb(void *arg);
647 static void		sasetupdev(struct sa_softc *softc, struct cdev *dev);
648 static void		saloadtotunables(struct sa_softc *softc);
649 static void		sasysctlinit(void *context, int pending);
650 static int		samount(struct cam_periph *, int, struct cdev *);
651 static int		saretension(struct cam_periph *periph);
652 static int		sareservereleaseunit(struct cam_periph *periph,
653 					     int reserve);
654 static int		saloadunload(struct cam_periph *periph, int load);
655 static int		saerase(struct cam_periph *periph, int longerase);
656 static int		sawritefilemarks(struct cam_periph *periph,
657 					 int nmarks, int setmarks, int immed);
658 static int		sagetpos(struct cam_periph *periph);
659 static int		sardpos(struct cam_periph *periph, int, uint32_t *);
660 static int		sasetpos(struct cam_periph *periph, int,
661 				 struct mtlocate *);
662 static void		safilldenstypesb(struct sbuf *sb, int *indent,
663 					 uint8_t *buf, int buf_len,
664 					 int is_density);
665 static void		safilldensitysb(struct sa_softc *softc, int *indent,
666 					struct sbuf *sb);
667 static void		saloadtimeouts(struct sa_softc *softc, union ccb *ccb);
668 
669 #ifndef	SA_DEFAULT_IO_SPLIT
670 #define	SA_DEFAULT_IO_SPLIT	0
671 #endif
672 
673 static int sa_allow_io_split = SA_DEFAULT_IO_SPLIT;
674 
675 /*
676  * Tunable to allow the user to set a global allow_io_split value.  Note
677  * that this WILL GO AWAY in FreeBSD 11.0.  Silently splitting the I/O up
678  * is bad behavior, because it hides the true tape block size from the
679  * application.
680  */
681 static SYSCTL_NODE(_kern_cam, OID_AUTO, sa, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
682     "CAM Sequential Access Tape Driver");
683 SYSCTL_INT(_kern_cam_sa, OID_AUTO, allow_io_split, CTLFLAG_RDTUN,
684     &sa_allow_io_split, 0, "Default I/O split value");
685 
686 static struct periph_driver sadriver =
687 {
688 	sainit, "sa",
689 	TAILQ_HEAD_INITIALIZER(sadriver.units), /* generation */ 0
690 };
691 
692 PERIPHDRIVER_DECLARE(sa, sadriver);
693 
694 /* For 2.2-stable support */
695 #ifndef D_TAPE
696 #define D_TAPE 0
697 #endif
698 
699 static struct cdevsw sa_cdevsw = {
700 	.d_version =	D_VERSION,
701 	.d_open =	saopen,
702 	.d_close =	saclose,
703 	.d_read =	physread,
704 	.d_write =	physwrite,
705 	.d_ioctl =	saioctl,
706 	.d_strategy =	sastrategy,
707 	.d_name =	"sa",
708 	.d_flags =	D_TAPE | D_TRACKCLOSE,
709 };
710 
711 static int
saopen(struct cdev * dev,int flags,int fmt,struct thread * td)712 saopen(struct cdev *dev, int flags, int fmt, struct thread *td)
713 {
714 	struct cam_periph *periph;
715 	struct sa_softc *softc;
716 	int error;
717 
718 	periph = (struct cam_periph *)dev->si_drv1;
719 	if (cam_periph_acquire(periph) != 0) {
720 		return (ENXIO);
721 	}
722 
723 	cam_periph_lock(periph);
724 
725 	softc = (struct sa_softc *)periph->softc;
726 
727 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE|CAM_DEBUG_INFO,
728 	    ("saopen(%s): softc=0x%x\n", devtoname(dev), softc->flags));
729 
730 	if (SA_IS_CTRL(dev)) {
731 		softc->ctrl_mode = 1;
732 		softc->open_count++;
733 		cam_periph_unlock(periph);
734 		return (0);
735 	}
736 
737 	if ((error = cam_periph_hold(periph, PRIBIO|PCATCH)) != 0) {
738 		cam_periph_unlock(periph);
739 		cam_periph_release(periph);
740 		return (error);
741 	}
742 
743 	if (softc->flags & SA_FLAG_OPEN) {
744 		error = EBUSY;
745 	} else if (softc->flags & SA_FLAG_INVALID) {
746 		error = ENXIO;
747 	} else {
748 		/*
749 		 * Preserve whether this is a read_only open.
750 		 */
751 		softc->open_rdonly = (flags & O_RDWR) == O_RDONLY;
752 
753 		/*
754 		 * The function samount ensures media is loaded and ready.
755 		 * It also does a device RESERVE if the tape isn't yet mounted.
756 		 *
757 		 * If the mount fails and this was a non-blocking open,
758 		 * make this a 'open_pending_mount' action.
759 		 */
760 		error = samount(periph, flags, dev);
761 		if (error && (flags & O_NONBLOCK)) {
762 			softc->flags |= SA_FLAG_OPEN;
763 			softc->open_pending_mount = 1;
764 			softc->open_count++;
765 			cam_periph_unhold(periph);
766 			cam_periph_unlock(periph);
767 			return (0);
768 		}
769 	}
770 
771 	if (error) {
772 		cam_periph_unhold(periph);
773 		cam_periph_unlock(periph);
774 		cam_periph_release(periph);
775 		return (error);
776 	}
777 
778 	saprevent(periph, PR_PREVENT);
779 	softc->flags |= SA_FLAG_OPEN;
780 	softc->open_count++;
781 
782 	cam_periph_unhold(periph);
783 	cam_periph_unlock(periph);
784 	return (error);
785 }
786 
787 static int
saclose(struct cdev * dev,int flag,int fmt,struct thread * td)788 saclose(struct cdev *dev, int flag, int fmt, struct thread *td)
789 {
790 	struct	cam_periph *periph;
791 	struct	sa_softc *softc;
792 	int	mode, error, writing, tmp, i;
793 	int	closedbits = SA_FLAG_OPEN;
794 
795 	mode = SAMODE(dev);
796 	periph = (struct cam_periph *)dev->si_drv1;
797 	cam_periph_lock(periph);
798 
799 	softc = (struct sa_softc *)periph->softc;
800 
801 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE|CAM_DEBUG_INFO,
802 	    ("saclose(%s): softc=0x%x\n", devtoname(dev), softc->flags));
803 
804 	softc->open_rdonly = 0;
805 	if (SA_IS_CTRL(dev)) {
806 		softc->ctrl_mode = 0;
807 		softc->open_count--;
808 		cam_periph_unlock(periph);
809 		cam_periph_release(periph);
810 		return (0);
811 	}
812 
813 	if (softc->open_pending_mount) {
814 		softc->flags &= ~SA_FLAG_OPEN;
815 		softc->open_pending_mount = 0;
816 		softc->open_count--;
817 		cam_periph_unlock(periph);
818 		cam_periph_release(periph);
819 		return (0);
820 	}
821 
822 	if ((error = cam_periph_hold(periph, PRIBIO)) != 0) {
823 		cam_periph_unlock(periph);
824 		return (error);
825 	}
826 
827 	/*
828 	 * Were we writing the tape?
829 	 */
830 	writing = (softc->flags & SA_FLAG_TAPE_WRITTEN) != 0;
831 
832 	/*
833 	 * See whether or not we need to write filemarks. If this
834 	 * fails, we probably have to assume we've lost tape
835 	 * position.
836 	 */
837 	error = sacheckeod(periph);
838 	if (error) {
839 		xpt_print(periph->path,
840 		    "failed to write terminating filemark(s)\n");
841 		softc->flags |= SA_FLAG_TAPE_FROZEN;
842 	}
843 
844 	/*
845 	 * Whatever we end up doing, allow users to eject tapes from here on.
846 	 */
847 	saprevent(periph, PR_ALLOW);
848 
849 	/*
850 	 * Decide how to end...
851 	 */
852 	if ((softc->flags & SA_FLAG_TAPE_MOUNTED) == 0) {
853 		closedbits |= SA_FLAG_TAPE_FROZEN;
854 	} else switch (mode) {
855 	case SA_MODE_OFFLINE:
856 		/*
857 		 * An 'offline' close is an unconditional release of
858 		 * frozen && mount conditions, irrespective of whether
859 		 * these operations succeeded. The reason for this is
860 		 * to allow at least some kind of programmatic way
861 		 * around our state getting all fouled up. If somebody
862 		 * issues an 'offline' command, that will be allowed
863 		 * to clear state.
864 		 */
865 		(void) sarewind(periph);
866 		(void) saloadunload(periph, FALSE);
867 		closedbits |= SA_FLAG_TAPE_MOUNTED|SA_FLAG_TAPE_FROZEN;
868 		break;
869 	case SA_MODE_REWIND:
870 		/*
871 		 * If the rewind fails, return an error- if anyone cares,
872 		 * but not overwriting any previous error.
873 		 *
874 		 * We don't clear the notion of mounted here, but we do
875 		 * clear the notion of frozen if we successfully rewound.
876 		 */
877 		tmp = sarewind(periph);
878 		if (tmp) {
879 			if (error != 0)
880 				error = tmp;
881 		} else {
882 			closedbits |= SA_FLAG_TAPE_FROZEN;
883 		}
884 		break;
885 	case SA_MODE_NOREWIND:
886 		/*
887 		 * If we're not rewinding/unloading the tape, find out
888 		 * whether we need to back up over one of two filemarks
889 		 * we wrote (if we wrote two filemarks) so that appends
890 		 * from this point on will be sane.
891 		 */
892 		if (error == 0 && writing && (softc->quirks & SA_QUIRK_2FM)) {
893 			tmp = saspace(periph, -1, SS_FILEMARKS);
894 			if (tmp) {
895 				xpt_print(periph->path, "unable to backspace "
896 				    "over one of double filemarks at end of "
897 				    "tape\n");
898 				xpt_print(periph->path, "it is possible that "
899 				    "this device needs a SA_QUIRK_1FM quirk set"
900 				    "for it\n");
901 				softc->flags |= SA_FLAG_TAPE_FROZEN;
902 			}
903 		}
904 		break;
905 	default:
906 		xpt_print(periph->path, "unknown mode 0x%x in saclose\n", mode);
907 		/* NOTREACHED */
908 		break;
909 	}
910 
911 	/*
912 	 * We wish to note here that there are no more filemarks to be written.
913 	 */
914 	softc->filemarks = 0;
915 	softc->flags &= ~SA_FLAG_TAPE_WRITTEN;
916 
917 	/*
918 	 * And we are no longer open for business.
919 	 */
920 	softc->flags &= ~closedbits;
921 	softc->open_count--;
922 
923 	/*
924 	 * Invalidate any density information that depends on having tape
925 	 * media in the drive.
926 	 */
927 	for (i = 0; i < SA_DENSITY_TYPES; i++) {
928 		if (softc->density_type_bits[i] & SRDS_MEDIA)
929 			softc->density_info_valid[i] = 0;
930 	}
931 
932 	/*
933 	 * Inform users if tape state if frozen....
934 	 */
935 	if (softc->flags & SA_FLAG_TAPE_FROZEN) {
936 		xpt_print(periph->path, "tape is now frozen- use an OFFLINE, "
937 		    "REWIND or MTEOM command to clear this state.\n");
938 	}
939 
940 	/* release the device if it is no longer mounted */
941 	if ((softc->flags & SA_FLAG_TAPE_MOUNTED) == 0)
942 		sareservereleaseunit(periph, FALSE);
943 
944 	cam_periph_unhold(periph);
945 	cam_periph_unlock(periph);
946 	cam_periph_release(periph);
947 
948 	return (error);
949 }
950 
951 /*
952  * Actually translate the requested transfer into one the physical driver
953  * can understand.  The transfer is described by a buf and will include
954  * only one physical transfer.
955  */
956 static void
sastrategy(struct bio * bp)957 sastrategy(struct bio *bp)
958 {
959 	struct cam_periph *periph;
960 	struct sa_softc *softc;
961 
962 	bp->bio_resid = bp->bio_bcount;
963 	if (SA_IS_CTRL(bp->bio_dev)) {
964 		biofinish(bp, NULL, EINVAL);
965 		return;
966 	}
967 	periph = (struct cam_periph *)bp->bio_dev->si_drv1;
968 	cam_periph_lock(periph);
969 
970 	softc = (struct sa_softc *)periph->softc;
971 
972 	if (softc->flags & SA_FLAG_INVALID) {
973 		cam_periph_unlock(periph);
974 		biofinish(bp, NULL, ENXIO);
975 		return;
976 	}
977 
978 	if (softc->flags & SA_FLAG_TAPE_FROZEN) {
979 		cam_periph_unlock(periph);
980 		biofinish(bp, NULL, EPERM);
981 		return;
982 	}
983 
984 	/*
985 	 * This should actually never occur as the write(2)
986 	 * system call traps attempts to write to a read-only
987 	 * file descriptor.
988 	 */
989 	if (bp->bio_cmd == BIO_WRITE && softc->open_rdonly) {
990 		cam_periph_unlock(periph);
991 		biofinish(bp, NULL, EBADF);
992 		return;
993 	}
994 
995 	if (softc->open_pending_mount) {
996 		int error = samount(periph, 0, bp->bio_dev);
997 		if (error) {
998 			cam_periph_unlock(periph);
999 			biofinish(bp, NULL, ENXIO);
1000 			return;
1001 		}
1002 		saprevent(periph, PR_PREVENT);
1003 		softc->open_pending_mount = 0;
1004 	}
1005 
1006 	/*
1007 	 * If it's a null transfer, return immediately
1008 	 */
1009 	if (bp->bio_bcount == 0) {
1010 		cam_periph_unlock(periph);
1011 		biodone(bp);
1012 		return;
1013 	}
1014 
1015 	/* valid request?  */
1016 	if (softc->flags & SA_FLAG_FIXED) {
1017 		/*
1018 		 * Fixed block device.  The byte count must
1019 		 * be a multiple of our block size.
1020 		 */
1021 		if (((softc->blk_mask != ~0) &&
1022 		    ((bp->bio_bcount & softc->blk_mask) != 0)) ||
1023 		    ((softc->blk_mask == ~0) &&
1024 		    ((bp->bio_bcount % softc->min_blk) != 0))) {
1025 			xpt_print(periph->path, "Invalid request.  Fixed block "
1026 			    "device requests must be a multiple of %d bytes\n",
1027 			    softc->min_blk);
1028 			cam_periph_unlock(periph);
1029 			biofinish(bp, NULL, EINVAL);
1030 			return;
1031 		}
1032 	} else if ((bp->bio_bcount > softc->max_blk) ||
1033 		   (bp->bio_bcount < softc->min_blk) ||
1034 		   (bp->bio_bcount & softc->blk_mask) != 0) {
1035 		xpt_print_path(periph->path);
1036 		printf("Invalid request.  Variable block "
1037 		    "device requests must be ");
1038 		if (softc->blk_mask != 0) {
1039 			printf("a multiple of %d ", (0x1 << softc->blk_gran));
1040 		}
1041 		printf("between %d and %d bytes\n", softc->min_blk,
1042 		    softc->max_blk);
1043 		cam_periph_unlock(periph);
1044 		biofinish(bp, NULL, EINVAL);
1045 		return;
1046         }
1047 
1048 	/*
1049 	 * Place it at the end of the queue.
1050 	 */
1051 	bioq_insert_tail(&softc->bio_queue, bp);
1052 	softc->queue_count++;
1053 #if	0
1054 	CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
1055 	    ("sastrategy: queuing a %ld %s byte %s\n", bp->bio_bcount,
1056  	    (softc->flags & SA_FLAG_FIXED)?  "fixed" : "variable",
1057 	    (bp->bio_cmd == BIO_READ)? "read" : "write"));
1058 #endif
1059 	if (softc->queue_count > 1) {
1060 		CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
1061 		    ("sastrategy: queue count now %d\n", softc->queue_count));
1062 	}
1063 
1064 	/*
1065 	 * Schedule ourselves for performing the work.
1066 	 */
1067 	xpt_schedule(periph, CAM_PRIORITY_NORMAL);
1068 	cam_periph_unlock(periph);
1069 
1070 	return;
1071 }
1072 
1073 static int
sasetsili(struct cam_periph * periph,struct mtparamset * ps,int num_params)1074 sasetsili(struct cam_periph *periph, struct mtparamset *ps, int num_params)
1075 {
1076 	uint32_t sili_blocksize;
1077 	struct sa_softc *softc;
1078 	int error;
1079 
1080 	error = 0;
1081 	softc = (struct sa_softc *)periph->softc;
1082 
1083 	if (ps->value_type != MT_PARAM_SET_SIGNED) {
1084 		snprintf(ps->error_str, sizeof(ps->error_str),
1085 		    "sili is a signed parameter");
1086 		goto bailout;
1087 	}
1088 	if ((ps->value.value_signed < 0)
1089 	 || (ps->value.value_signed > 1)) {
1090 		snprintf(ps->error_str, sizeof(ps->error_str),
1091 		    "invalid sili value %jd", (intmax_t)ps->value.value_signed);
1092 		goto bailout_error;
1093 	}
1094 	/*
1095 	 * We only set the SILI flag in variable block
1096 	 * mode.  You'll get a check condition in fixed
1097 	 * block mode if things don't line up in any case.
1098 	 */
1099 	if (softc->flags & SA_FLAG_FIXED) {
1100 		snprintf(ps->error_str, sizeof(ps->error_str),
1101 		    "can't set sili bit in fixed block mode");
1102 		goto bailout_error;
1103 	}
1104 	if (softc->sili == ps->value.value_signed)
1105 		goto bailout;
1106 
1107 	if (ps->value.value_signed == 1)
1108 		sili_blocksize = 4;
1109 	else
1110 		sili_blocksize = 0;
1111 
1112 	error = sasetparams(periph, SA_PARAM_BLOCKSIZE,
1113 			    sili_blocksize, 0, 0, SF_QUIET_IR);
1114 	if (error != 0) {
1115 		snprintf(ps->error_str, sizeof(ps->error_str),
1116 		    "sasetparams() returned error %d", error);
1117 		goto bailout_error;
1118 	}
1119 
1120 	softc->sili = ps->value.value_signed;
1121 
1122 bailout:
1123 	ps->status = MT_PARAM_STATUS_OK;
1124 	return (error);
1125 
1126 bailout_error:
1127 	ps->status = MT_PARAM_STATUS_ERROR;
1128 	if (error == 0)
1129 		error = EINVAL;
1130 
1131 	return (error);
1132 }
1133 
1134 static int
saseteotwarn(struct cam_periph * periph,struct mtparamset * ps,int num_params)1135 saseteotwarn(struct cam_periph *periph, struct mtparamset *ps, int num_params)
1136 {
1137 	struct sa_softc *softc;
1138 	int error;
1139 
1140 	error = 0;
1141 	softc = (struct sa_softc *)periph->softc;
1142 
1143 	if (ps->value_type != MT_PARAM_SET_SIGNED) {
1144 		snprintf(ps->error_str, sizeof(ps->error_str),
1145 		    "eot_warn is a signed parameter");
1146 		ps->status = MT_PARAM_STATUS_ERROR;
1147 		goto bailout;
1148 	}
1149 	if ((ps->value.value_signed < 0)
1150 	 || (ps->value.value_signed > 1)) {
1151 		snprintf(ps->error_str, sizeof(ps->error_str),
1152 		    "invalid eot_warn value %jd\n",
1153 		    (intmax_t)ps->value.value_signed);
1154 		ps->status = MT_PARAM_STATUS_ERROR;
1155 		goto bailout;
1156 	}
1157 	softc->eot_warn = ps->value.value_signed;
1158 	ps->status = MT_PARAM_STATUS_OK;
1159 bailout:
1160 	if (ps->status != MT_PARAM_STATUS_OK)
1161 		error = EINVAL;
1162 
1163 	return (error);
1164 }
1165 
1166 static void
safillprot(struct sa_softc * softc,int * indent,struct sbuf * sb)1167 safillprot(struct sa_softc *softc, int *indent, struct sbuf *sb)
1168 {
1169 	int tmpint;
1170 
1171 	SASBADDNODE(sb, *indent, protection);
1172 	if (softc->flags & SA_FLAG_PROTECT_SUPP)
1173 		tmpint = 1;
1174 	else
1175 		tmpint = 0;
1176 	SASBADDINTDESC(sb, *indent, tmpint, %d, protection_supported,
1177 	    "Set to 1 if protection information is supported");
1178 
1179 	if ((tmpint != 0)
1180 	 && (softc->prot_info.cur_prot_state.initialized != 0)) {
1181 		struct sa_prot_state *prot;
1182 
1183 		prot = &softc->prot_info.cur_prot_state;
1184 
1185 		SASBADDUINTDESC(sb, *indent, prot->prot_method, %u,
1186 		    prot_method, "Current Protection Method");
1187 		SASBADDUINTDESC(sb, *indent, prot->pi_length, %u,
1188 		    pi_length, "Length of Protection Information");
1189 		SASBADDUINTDESC(sb, *indent, prot->lbp_w, %u,
1190 		    lbp_w, "Check Protection on Writes");
1191 		SASBADDUINTDESC(sb, *indent, prot->lbp_r, %u,
1192 		    lbp_r, "Check and Include Protection on Reads");
1193 		SASBADDUINTDESC(sb, *indent, prot->rbdp, %u,
1194 		    rbdp, "Transfer Protection Information for RECOVER "
1195 		    "BUFFERED DATA command");
1196 	}
1197 	SASBENDNODE(sb, *indent, protection);
1198 }
1199 
1200 static void
sapopulateprots(struct sa_prot_state * cur_state,struct sa_prot_map * new_table,int table_ents)1201 sapopulateprots(struct sa_prot_state *cur_state, struct sa_prot_map *new_table,
1202     int table_ents)
1203 {
1204 	int i;
1205 
1206 	bcopy(sa_prot_table, new_table, min(table_ents * sizeof(*new_table),
1207 	    sizeof(sa_prot_table)));
1208 
1209 	table_ents = min(table_ents, SA_NUM_PROT_ENTS);
1210 
1211 	for (i = 0; i < table_ents; i++)
1212 		new_table[i].value = (uint32_t *)((uint8_t *)cur_state +
1213 		    new_table[i].offset);
1214 
1215 	return;
1216 }
1217 
1218 static struct sa_prot_map *
safindprotent(char * name,struct sa_prot_map * table,int table_ents)1219 safindprotent(char *name, struct sa_prot_map *table, int table_ents)
1220 {
1221 	char *prot_name = "protection.";
1222 	int i, prot_len;
1223 
1224 	prot_len = strlen(prot_name);
1225 
1226 	/*
1227 	 * This shouldn't happen, but we check just in case.
1228 	 */
1229 	if (strncmp(name, prot_name, prot_len) != 0)
1230 		goto bailout;
1231 
1232 	for (i = 0; i < table_ents; i++) {
1233 		if (strcmp(&name[prot_len], table[i].name) != 0)
1234 			continue;
1235 		return (&table[i]);
1236 	}
1237 bailout:
1238 	return (NULL);
1239 }
1240 
1241 static int
sasetprotents(struct cam_periph * periph,struct mtparamset * ps,int num_params)1242 sasetprotents(struct cam_periph *periph, struct mtparamset *ps, int num_params)
1243 {
1244 	struct sa_softc *softc;
1245 	struct sa_prot_map prot_ents[SA_NUM_PROT_ENTS];
1246 	struct sa_prot_state new_state;
1247 	int error;
1248 	int i;
1249 
1250 	softc = (struct sa_softc *)periph->softc;
1251 	error = 0;
1252 
1253 	/*
1254 	 * Make sure that this tape drive supports protection information.
1255 	 * Otherwise we can't set anything.
1256 	 */
1257 	if ((softc->flags & SA_FLAG_PROTECT_SUPP) == 0) {
1258 		snprintf(ps[0].error_str, sizeof(ps[0].error_str),
1259 		    "Protection information is not supported for this device");
1260 		ps[0].status = MT_PARAM_STATUS_ERROR;
1261 		goto bailout;
1262 	}
1263 
1264 	/*
1265 	 * We can't operate with physio(9) splitting enabled, because there
1266 	 * is no way to insure (especially in variable block mode) that
1267 	 * what the user writes (with a checksum block at the end) will
1268 	 * make it into the sa(4) driver intact.
1269 	 */
1270 	if ((softc->si_flags & SI_NOSPLIT) == 0) {
1271 		snprintf(ps[0].error_str, sizeof(ps[0].error_str),
1272 		    "Protection information cannot be enabled with I/O "
1273 		    "splitting");
1274 		ps[0].status = MT_PARAM_STATUS_ERROR;
1275 		goto bailout;
1276 	}
1277 
1278 	/*
1279 	 * Take the current cached protection state and use that as the
1280 	 * basis for our new entries.
1281 	 */
1282 	bcopy(&softc->prot_info.cur_prot_state, &new_state, sizeof(new_state));
1283 
1284 	/*
1285 	 * Populate the table mapping property names to pointers into the
1286 	 * state structure.
1287 	 */
1288 	sapopulateprots(&new_state, prot_ents, SA_NUM_PROT_ENTS);
1289 
1290 	/*
1291 	 * For each parameter the user passed in, make sure the name, type
1292 	 * and value are valid.
1293 	 */
1294 	for (i = 0; i < num_params; i++) {
1295 		struct sa_prot_map *ent;
1296 
1297 		ent = safindprotent(ps[i].value_name, prot_ents,
1298 		    SA_NUM_PROT_ENTS);
1299 		if (ent == NULL) {
1300 			ps[i].status = MT_PARAM_STATUS_ERROR;
1301 			snprintf(ps[i].error_str, sizeof(ps[i].error_str),
1302 			    "Invalid protection entry name %s",
1303 			    ps[i].value_name);
1304 			error = EINVAL;
1305 			goto bailout;
1306 		}
1307 		if (ent->param_type != ps[i].value_type) {
1308 			ps[i].status = MT_PARAM_STATUS_ERROR;
1309 			snprintf(ps[i].error_str, sizeof(ps[i].error_str),
1310 			    "Supplied type %d does not match actual type %d",
1311 			    ps[i].value_type, ent->param_type);
1312 			error = EINVAL;
1313 			goto bailout;
1314 		}
1315 		if ((ps[i].value.value_unsigned < ent->min_val)
1316 		 || (ps[i].value.value_unsigned > ent->max_val)) {
1317 			ps[i].status = MT_PARAM_STATUS_ERROR;
1318 			snprintf(ps[i].error_str, sizeof(ps[i].error_str),
1319 			    "Value %ju is outside valid range %u - %u",
1320 			    (uintmax_t)ps[i].value.value_unsigned, ent->min_val,
1321 			    ent->max_val);
1322 			error = EINVAL;
1323 			goto bailout;
1324 		}
1325 		*(ent->value) = ps[i].value.value_unsigned;
1326 	}
1327 
1328 	/*
1329 	 * Actually send the protection settings to the drive.
1330 	 */
1331 	error = sasetprot(periph, &new_state);
1332 	if (error != 0) {
1333 		for (i = 0; i < num_params; i++) {
1334 			ps[i].status = MT_PARAM_STATUS_ERROR;
1335 			snprintf(ps[i].error_str, sizeof(ps[i].error_str),
1336 			    "Unable to set parameter, see dmesg(8)");
1337 		}
1338 		goto bailout;
1339 	}
1340 
1341 	/*
1342 	 * Let the user know that his settings were stored successfully.
1343 	 */
1344 	for (i = 0; i < num_params; i++)
1345 		ps[i].status = MT_PARAM_STATUS_OK;
1346 
1347 bailout:
1348 	return (error);
1349 }
1350 /*
1351  * Entry handlers generally only handle a single entry.  Node handlers will
1352  * handle a contiguous range of parameters to set in a single call.
1353  */
1354 typedef enum {
1355 	SA_PARAM_TYPE_ENTRY,
1356 	SA_PARAM_TYPE_NODE
1357 } sa_param_type;
1358 
1359 static const struct sa_param_ent {
1360 	char *name;
1361 	sa_param_type param_type;
1362 	int (*set_func)(struct cam_periph *periph, struct mtparamset *ps,
1363 			int num_params);
1364 } sa_param_table[] = {
1365 	{"sili", SA_PARAM_TYPE_ENTRY, sasetsili },
1366 	{"eot_warn", SA_PARAM_TYPE_ENTRY, saseteotwarn },
1367 	{"protection.", SA_PARAM_TYPE_NODE, sasetprotents }
1368 };
1369 
1370 static const struct sa_param_ent *
safindparament(struct mtparamset * ps)1371 safindparament(struct mtparamset *ps)
1372 {
1373 	unsigned int i;
1374 
1375 	for (i = 0; i < nitems(sa_param_table); i++){
1376 		/*
1377 		 * For entries, we compare all of the characters.  For
1378 		 * nodes, we only compare the first N characters.  The node
1379 		 * handler will decode the rest.
1380 		 */
1381 		if (sa_param_table[i].param_type == SA_PARAM_TYPE_ENTRY) {
1382 			if (strcmp(ps->value_name, sa_param_table[i].name) != 0)
1383 				continue;
1384 		} else {
1385 			if (strncmp(ps->value_name, sa_param_table[i].name,
1386 			    strlen(sa_param_table[i].name)) != 0)
1387 				continue;
1388 		}
1389 		return (&sa_param_table[i]);
1390 	}
1391 
1392 	return (NULL);
1393 }
1394 
1395 /*
1396  * Go through a list of parameters, coalescing contiguous parameters with
1397  * the same parent node into a single call to a set_func.
1398  */
1399 static int
saparamsetlist(struct cam_periph * periph,struct mtsetlist * list,int need_copy)1400 saparamsetlist(struct cam_periph *periph, struct mtsetlist *list,
1401     int need_copy)
1402 {
1403 	int i, contig_ents;
1404 	int error;
1405 	struct mtparamset *params, *first;
1406 	const struct sa_param_ent *first_ent;
1407 
1408 	error = 0;
1409 	params = NULL;
1410 
1411 	if (list->num_params == 0)
1412 		/* Nothing to do */
1413 		goto bailout;
1414 
1415 	/*
1416 	 * Verify that the user has the correct structure size.
1417 	 */
1418 	if ((list->num_params * sizeof(struct mtparamset)) !=
1419 	     list->param_len) {
1420 		xpt_print(periph->path, "%s: length of params %d != "
1421 		    "sizeof(struct mtparamset) %zd * num_params %d\n",
1422 		    __func__, list->param_len, sizeof(struct mtparamset),
1423 		    list->num_params);
1424 		error = EINVAL;
1425 		goto bailout;
1426 	}
1427 
1428 	if (need_copy != 0) {
1429 		/*
1430 		 * XXX KDM will dropping the lock cause an issue here?
1431 		 */
1432 		cam_periph_unlock(periph);
1433 		params = malloc(list->param_len, M_SCSISA, M_WAITOK | M_ZERO);
1434 		error = copyin(list->params, params, list->param_len);
1435 		cam_periph_lock(periph);
1436 
1437 		if (error != 0)
1438 			goto bailout;
1439 	} else {
1440 		params = list->params;
1441 	}
1442 
1443 	contig_ents = 0;
1444 	first = NULL;
1445 	first_ent = NULL;
1446 	for (i = 0; i < list->num_params; i++) {
1447 		const struct sa_param_ent *ent;
1448 
1449 		ent = safindparament(&params[i]);
1450 		if (ent == NULL) {
1451 			snprintf(params[i].error_str,
1452 			    sizeof(params[i].error_str),
1453 			    "%s: cannot find parameter %s", __func__,
1454 			    params[i].value_name);
1455 			params[i].status = MT_PARAM_STATUS_ERROR;
1456 			break;
1457 		}
1458 
1459 		if (first != NULL) {
1460 			if (first_ent == ent) {
1461 				/*
1462 				 * We're still in a contiguous list of
1463 				 * parameters that can be handled by one
1464 				 * node handler.
1465 				 */
1466 				contig_ents++;
1467 				continue;
1468 			} else {
1469 				error = first_ent->set_func(periph, first,
1470 				    contig_ents);
1471 				first = NULL;
1472 				first_ent = NULL;
1473 				contig_ents = 0;
1474 				if (error != 0) {
1475 					error = 0;
1476 					break;
1477 				}
1478 			}
1479 		}
1480 		if (ent->param_type == SA_PARAM_TYPE_NODE) {
1481 			first = &params[i];
1482 			first_ent = ent;
1483 			contig_ents = 1;
1484 		} else {
1485 			error = ent->set_func(periph, &params[i], 1);
1486 			if (error != 0) {
1487 				error = 0;
1488 				break;
1489 			}
1490 		}
1491 	}
1492 	if (first != NULL)
1493 		first_ent->set_func(periph, first, contig_ents);
1494 
1495 bailout:
1496 	if (need_copy != 0) {
1497 		if (error != EFAULT) {
1498 			int error1;
1499 
1500 			cam_periph_unlock(periph);
1501 			error1 = copyout(params, list->params, list->param_len);
1502 			if (error == 0)
1503 				error = error1;
1504 			cam_periph_lock(periph);
1505 		}
1506 		free(params, M_SCSISA);
1507 	}
1508 	return (error);
1509 }
1510 
1511 static int
sagetparams_common(struct cdev * dev,struct cam_periph * periph)1512 sagetparams_common(struct cdev *dev, struct cam_periph *periph)
1513 {
1514 	struct sa_softc *softc;
1515 	uint8_t write_protect;
1516 	int comp_enabled, comp_supported, error;
1517 
1518 	softc = (struct sa_softc *)periph->softc;
1519 
1520 	if (softc->open_pending_mount)
1521 		return (0);
1522 
1523 	/* The control device may issue getparams() if there are no opens. */
1524 	if (SA_IS_CTRL(dev) && (softc->flags & SA_FLAG_OPEN) != 0)
1525 		return (0);
1526 
1527 	error = sagetparams(periph, SA_PARAM_ALL, &softc->media_blksize,
1528 	    &softc->media_density, &softc->media_numblks, &softc->buffer_mode,
1529 	    &write_protect, &softc->speed, &comp_supported, &comp_enabled,
1530 	    &softc->comp_algorithm, NULL, NULL, 0, 0);
1531 	if (error)
1532 		return (error);
1533 	if (write_protect)
1534 		softc->flags |= SA_FLAG_TAPE_WP;
1535 	else
1536 		softc->flags &= ~SA_FLAG_TAPE_WP;
1537 	softc->flags &= ~SA_FLAG_COMPRESSION;
1538 	if (comp_supported) {
1539 		if (softc->saved_comp_algorithm == 0)
1540 			softc->saved_comp_algorithm =
1541 			    softc->comp_algorithm;
1542 		softc->flags |= SA_FLAG_COMP_SUPP;
1543 		if (comp_enabled)
1544 			softc->flags |= SA_FLAG_COMP_ENABLED;
1545 	} else
1546 		softc->flags |= SA_FLAG_COMP_UNSUPP;
1547 
1548 	return (0);
1549 }
1550 
1551 #define	PENDING_MOUNT_CHECK(softc, periph, dev)		\
1552 	if (softc->open_pending_mount) {		\
1553 		error = samount(periph, 0, dev);	\
1554 		if (error) {				\
1555 			break;				\
1556 		}					\
1557 		saprevent(periph, PR_PREVENT);		\
1558 		softc->open_pending_mount = 0;		\
1559 	}
1560 
1561 static int
saioctl(struct cdev * dev,u_long cmd,caddr_t arg,int flag,struct thread * td)1562 saioctl(struct cdev *dev, u_long cmd, caddr_t arg, int flag, struct thread *td)
1563 {
1564 	struct cam_periph *periph;
1565 	struct sa_softc *softc;
1566 	scsi_space_code spaceop;
1567 	int didlockperiph = 0;
1568 	int mode;
1569 	int error = 0;
1570 
1571 	mode = SAMODE(dev);
1572 	error = 0;		/* shut up gcc */
1573 	spaceop = 0;		/* shut up gcc */
1574 
1575 	periph = (struct cam_periph *)dev->si_drv1;
1576 	cam_periph_lock(periph);
1577 	softc = (struct sa_softc *)periph->softc;
1578 
1579 	/*
1580 	 * Check for control mode accesses. We allow MTIOCGET and
1581 	 * MTIOCERRSTAT (but need to be the only one open in order
1582 	 * to clear latched status), and MTSETBSIZE, MTSETDNSTY
1583 	 * and MTCOMP (but need to be the only one accessing this
1584 	 * device to run those).
1585 	 */
1586 
1587 	if (SA_IS_CTRL(dev)) {
1588 		switch (cmd) {
1589 		case MTIOCGETEOTMODEL:
1590 		case MTIOCGET:
1591 		case MTIOCEXTGET:
1592 		case MTIOCPARAMGET:
1593 		case MTIOCRBLIM:
1594 			break;
1595 		case MTIOCERRSTAT:
1596 			/*
1597 			 * If the periph isn't already locked, lock it
1598 			 * so our MTIOCERRSTAT can reset latched error stats.
1599 			 *
1600 			 * If the periph is already locked, skip it because
1601 			 * we're just getting status and it'll be up to the
1602 			 * other thread that has this device open to do
1603 			 * an MTIOCERRSTAT that would clear latched status.
1604 			 */
1605 			if ((periph->flags & CAM_PERIPH_LOCKED) == 0) {
1606 				error = cam_periph_hold(periph, PRIBIO|PCATCH);
1607 				if (error != 0) {
1608 					cam_periph_unlock(periph);
1609 					return (error);
1610 				}
1611 				didlockperiph = 1;
1612 			}
1613 			break;
1614 
1615 		case MTIOCTOP:
1616 		{
1617 			struct mtop *mt = (struct mtop *) arg;
1618 
1619 			/*
1620 			 * Check to make sure it's an OP we can perform
1621 			 * with no media inserted.
1622 			 */
1623 			switch (mt->mt_op) {
1624 			case MTSETBSIZ:
1625 			case MTSETDNSTY:
1626 			case MTCOMP:
1627 				mt = NULL;
1628 				/* FALLTHROUGH */
1629 			default:
1630 				break;
1631 			}
1632 			if (mt != NULL) {
1633 				break;
1634 			}
1635 			/* FALLTHROUGH */
1636 		}
1637 		case MTIOCSETEOTMODEL:
1638 			/*
1639 			 * We need to acquire the peripheral here rather
1640 			 * than at open time because we are sharing writable
1641 			 * access to data structures.
1642 			 */
1643 			error = cam_periph_hold(periph, PRIBIO|PCATCH);
1644 			if (error != 0) {
1645 				cam_periph_unlock(periph);
1646 				return (error);
1647 			}
1648 			didlockperiph = 1;
1649 			break;
1650 
1651 		default:
1652 			cam_periph_unlock(periph);
1653 			return (EINVAL);
1654 		}
1655 	}
1656 
1657 	/*
1658 	 * Find the device that the user is talking about
1659 	 */
1660 	switch (cmd) {
1661 	case MTIOCGET:
1662 	{
1663 		struct mtget *g = (struct mtget *)arg;
1664 
1665 		error = sagetparams_common(dev, periph);
1666 		if (error)
1667 			break;
1668 		bzero(g, sizeof(struct mtget));
1669 		g->mt_type = MT_ISAR;
1670 		if (softc->flags & SA_FLAG_COMP_UNSUPP) {
1671 			g->mt_comp = MT_COMP_UNSUPP;
1672 			g->mt_comp0 = MT_COMP_UNSUPP;
1673 			g->mt_comp1 = MT_COMP_UNSUPP;
1674 			g->mt_comp2 = MT_COMP_UNSUPP;
1675 			g->mt_comp3 = MT_COMP_UNSUPP;
1676 		} else {
1677 			if ((softc->flags & SA_FLAG_COMP_ENABLED) == 0) {
1678 				g->mt_comp = MT_COMP_DISABLED;
1679 			} else {
1680 				g->mt_comp = softc->comp_algorithm;
1681 			}
1682 			g->mt_comp0 = softc->comp_algorithm;
1683 			g->mt_comp1 = softc->comp_algorithm;
1684 			g->mt_comp2 = softc->comp_algorithm;
1685 			g->mt_comp3 = softc->comp_algorithm;
1686 		}
1687 		g->mt_density = softc->media_density;
1688 		g->mt_density0 = softc->media_density;
1689 		g->mt_density1 = softc->media_density;
1690 		g->mt_density2 = softc->media_density;
1691 		g->mt_density3 = softc->media_density;
1692 		g->mt_blksiz = softc->media_blksize;
1693 		g->mt_blksiz0 = softc->media_blksize;
1694 		g->mt_blksiz1 = softc->media_blksize;
1695 		g->mt_blksiz2 = softc->media_blksize;
1696 		g->mt_blksiz3 = softc->media_blksize;
1697 		g->mt_fileno = softc->fileno;
1698 		g->mt_blkno = softc->blkno;
1699 		g->mt_dsreg = (short) softc->dsreg;
1700 		/*
1701 		 * Yes, we know that this is likely to overflow
1702 		 */
1703 		if (softc->last_resid_was_io) {
1704 			if ((g->mt_resid = (short) softc->last_io_resid) != 0) {
1705 				if (SA_IS_CTRL(dev) == 0 || didlockperiph) {
1706 					softc->last_io_resid = 0;
1707 				}
1708 			}
1709 		} else {
1710 			if ((g->mt_resid = (short)softc->last_ctl_resid) != 0) {
1711 				if (SA_IS_CTRL(dev) == 0 || didlockperiph) {
1712 					softc->last_ctl_resid = 0;
1713 				}
1714 			}
1715 		}
1716 		error = 0;
1717 		break;
1718 	}
1719 	case MTIOCEXTGET:
1720 	case MTIOCPARAMGET:
1721 	{
1722 		struct mtextget *g = (struct mtextget *)arg;
1723 		char *tmpstr2;
1724 		struct sbuf *sb;
1725 
1726 		/*
1727 		 * Report drive status using an XML format.
1728 		 */
1729 
1730 		/*
1731 		 * XXX KDM will dropping the lock cause any problems here?
1732 		 */
1733 		cam_periph_unlock(periph);
1734 		sb = sbuf_new(NULL, NULL, g->alloc_len, SBUF_FIXEDLEN);
1735 		if (sb == NULL) {
1736 			g->status = MT_EXT_GET_ERROR;
1737 			snprintf(g->error_str, sizeof(g->error_str),
1738 				 "Unable to allocate %d bytes for status info",
1739 				 g->alloc_len);
1740 			cam_periph_lock(periph);
1741 			goto extget_bailout;
1742 		}
1743 		cam_periph_lock(periph);
1744 
1745 		if (cmd == MTIOCEXTGET)
1746 			error = saextget(dev, periph, sb, g);
1747 		else
1748 			error = saparamget(softc, sb);
1749 
1750 		if (error != 0)
1751 			goto extget_bailout;
1752 
1753 		error = sbuf_finish(sb);
1754 		if (error == ENOMEM) {
1755 			g->status = MT_EXT_GET_NEED_MORE_SPACE;
1756 			error = 0;
1757 		} else if (error != 0) {
1758 			g->status = MT_EXT_GET_ERROR;
1759 			snprintf(g->error_str, sizeof(g->error_str),
1760 			    "Error %d returned from sbuf_finish()", error);
1761 		} else
1762 			g->status = MT_EXT_GET_OK;
1763 
1764 		error = 0;
1765 		tmpstr2 = sbuf_data(sb);
1766 		g->fill_len = strlen(tmpstr2) + 1;
1767 		cam_periph_unlock(periph);
1768 
1769 		error = copyout(tmpstr2, g->status_xml, g->fill_len);
1770 
1771 		cam_periph_lock(periph);
1772 
1773 extget_bailout:
1774 		sbuf_delete(sb);
1775 		break;
1776 	}
1777 	case MTIOCPARAMSET:
1778 	{
1779 		struct mtsetlist list;
1780 		struct mtparamset *ps = (struct mtparamset *)arg;
1781 
1782 		bzero(&list, sizeof(list));
1783 		list.num_params = 1;
1784 		list.param_len = sizeof(*ps);
1785 		list.params = ps;
1786 
1787 		error = saparamsetlist(periph, &list, /*need_copy*/ 0);
1788 		break;
1789 	}
1790 	case MTIOCSETLIST:
1791 	{
1792 		struct mtsetlist *list = (struct mtsetlist *)arg;
1793 
1794 		error = saparamsetlist(periph, list, /*need_copy*/ 1);
1795 		break;
1796 	}
1797 	case MTIOCERRSTAT:
1798 	{
1799 		struct scsi_tape_errors *sep =
1800 		    &((union mterrstat *)arg)->scsi_errstat;
1801 
1802 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
1803 		    ("saioctl: MTIOCERRSTAT\n"));
1804 
1805 		bzero(sep, sizeof(*sep));
1806 		sep->io_resid = softc->last_io_resid;
1807 		bcopy((caddr_t) &softc->last_io_sense, sep->io_sense,
1808 		    sizeof (sep->io_sense));
1809 		bcopy((caddr_t) &softc->last_io_cdb, sep->io_cdb,
1810 		    sizeof (sep->io_cdb));
1811 		sep->ctl_resid = softc->last_ctl_resid;
1812 		bcopy((caddr_t) &softc->last_ctl_sense, sep->ctl_sense,
1813 		    sizeof (sep->ctl_sense));
1814 		bcopy((caddr_t) &softc->last_ctl_cdb, sep->ctl_cdb,
1815 		    sizeof (sep->ctl_cdb));
1816 
1817 		if ((SA_IS_CTRL(dev) == 0 && !softc->open_pending_mount) ||
1818 		    didlockperiph)
1819 			bzero((caddr_t) &softc->errinfo,
1820 			    sizeof (softc->errinfo));
1821 		error = 0;
1822 		break;
1823 	}
1824 	case MTIOCTOP:
1825 	{
1826 		struct mtop *mt;
1827 		int    count;
1828 
1829 		PENDING_MOUNT_CHECK(softc, periph, dev);
1830 
1831 		mt = (struct mtop *)arg;
1832 
1833 		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
1834 			 ("saioctl: op=0x%x count=0x%x\n",
1835 			  mt->mt_op, mt->mt_count));
1836 
1837 		count = mt->mt_count;
1838 		switch (mt->mt_op) {
1839 		case MTWEOF:	/* write an end-of-file marker */
1840 			/*
1841 			 * We don't need to clear the SA_FLAG_TAPE_WRITTEN
1842 			 * flag because by keeping track of filemarks
1843 			 * we have last written we know whether or not
1844 			 * we need to write more when we close the device.
1845 			 */
1846 			error = sawritefilemarks(periph, count, FALSE, FALSE);
1847 			break;
1848 		case MTWEOFI:
1849 			/* write an end-of-file marker without waiting */
1850 			error = sawritefilemarks(periph, count, FALSE, TRUE);
1851 			break;
1852 		case MTWSS:	/* write a setmark */
1853 			error = sawritefilemarks(periph, count, TRUE, FALSE);
1854 			break;
1855 		case MTBSR:	/* backward space record */
1856 		case MTFSR:	/* forward space record */
1857 		case MTBSF:	/* backward space file */
1858 		case MTFSF:	/* forward space file */
1859 		case MTBSS:	/* backward space setmark */
1860 		case MTFSS:	/* forward space setmark */
1861 		case MTEOD:	/* space to end of recorded medium */
1862 		{
1863 			int nmarks;
1864 
1865 			spaceop = SS_FILEMARKS;
1866 			nmarks = softc->filemarks;
1867 			error = sacheckeod(periph);
1868 			if (error) {
1869 				xpt_print(periph->path,
1870 				    "EOD check prior to spacing failed\n");
1871 				softc->flags |= SA_FLAG_EIO_PENDING;
1872 				break;
1873 			}
1874 			nmarks -= softc->filemarks;
1875 			switch(mt->mt_op) {
1876 			case MTBSR:
1877 				count = -count;
1878 				/* FALLTHROUGH */
1879 			case MTFSR:
1880 				spaceop = SS_BLOCKS;
1881 				break;
1882 			case MTBSF:
1883 				count = -count;
1884 				/* FALLTHROUGH */
1885 			case MTFSF:
1886 				break;
1887 			case MTBSS:
1888 				count = -count;
1889 				/* FALLTHROUGH */
1890 			case MTFSS:
1891 				spaceop = SS_SETMARKS;
1892 				break;
1893 			case MTEOD:
1894 				spaceop = SS_EOD;
1895 				count = 0;
1896 				nmarks = 0;
1897 				break;
1898 			default:
1899 				error = EINVAL;
1900 				break;
1901 			}
1902 			if (error)
1903 				break;
1904 
1905 			nmarks = softc->filemarks;
1906 			/*
1907 			 * XXX: Why are we checking again?
1908 			 */
1909 			error = sacheckeod(periph);
1910 			if (error)
1911 				break;
1912 			nmarks -= softc->filemarks;
1913 			error = saspace(periph, count - nmarks, spaceop);
1914 			/*
1915 			 * At this point, clear that we've written the tape
1916 			 * and that we've written any filemarks. We really
1917 			 * don't know what the applications wishes to do next-
1918 			 * the sacheckeod's will make sure we terminated the
1919 			 * tape correctly if we'd been writing, but the next
1920 			 * action the user application takes will set again
1921 			 * whether we need to write filemarks.
1922 			 */
1923 			softc->flags &=
1924 			    ~(SA_FLAG_TAPE_WRITTEN|SA_FLAG_TAPE_FROZEN);
1925 			softc->filemarks = 0;
1926 			break;
1927 		}
1928 		case MTREW:	/* rewind */
1929 			PENDING_MOUNT_CHECK(softc, periph, dev);
1930 			(void) sacheckeod(periph);
1931 			error = sarewind(periph);
1932 			/* see above */
1933 			softc->flags &=
1934 			    ~(SA_FLAG_TAPE_WRITTEN|SA_FLAG_TAPE_FROZEN);
1935 			softc->flags &= ~SA_FLAG_ERR_PENDING;
1936 			softc->filemarks = 0;
1937 			break;
1938 		case MTERASE:	/* erase */
1939 			PENDING_MOUNT_CHECK(softc, periph, dev);
1940 			error = saerase(periph, count);
1941 			softc->flags &=
1942 			    ~(SA_FLAG_TAPE_WRITTEN|SA_FLAG_TAPE_FROZEN);
1943 			softc->flags &= ~SA_FLAG_ERR_PENDING;
1944 			break;
1945 		case MTRETENS:	/* re-tension tape */
1946 			PENDING_MOUNT_CHECK(softc, periph, dev);
1947 			error = saretension(periph);
1948 			softc->flags &=
1949 			    ~(SA_FLAG_TAPE_WRITTEN|SA_FLAG_TAPE_FROZEN);
1950 			softc->flags &= ~SA_FLAG_ERR_PENDING;
1951 			break;
1952 		case MTOFFL:	/* rewind and put the drive offline */
1953 
1954 			PENDING_MOUNT_CHECK(softc, periph, dev);
1955 
1956 			(void) sacheckeod(periph);
1957 			/* see above */
1958 			softc->flags &= ~SA_FLAG_TAPE_WRITTEN;
1959 			softc->filemarks = 0;
1960 
1961 			error = sarewind(periph);
1962 			/* clear the frozen flag anyway */
1963 			softc->flags &= ~SA_FLAG_TAPE_FROZEN;
1964 
1965 			/*
1966 			 * Be sure to allow media removal before ejecting.
1967 			 */
1968 
1969 			saprevent(periph, PR_ALLOW);
1970 			if (error == 0) {
1971 				error = saloadunload(periph, FALSE);
1972 				if (error == 0) {
1973 					softc->flags &= ~SA_FLAG_TAPE_MOUNTED;
1974 				}
1975 			}
1976 			break;
1977 
1978 		case MTLOAD:
1979 			error = saloadunload(periph, TRUE);
1980 			break;
1981 		case MTNOP:	/* no operation, sets status only */
1982 		case MTCACHE:	/* enable controller cache */
1983 		case MTNOCACHE:	/* disable controller cache */
1984 			error = 0;
1985 			break;
1986 
1987 		case MTSETBSIZ:	/* Set block size for device */
1988 
1989 			PENDING_MOUNT_CHECK(softc, periph, dev);
1990 
1991 			if ((softc->sili != 0)
1992 			 && (count != 0)) {
1993 				xpt_print(periph->path, "Can't enter fixed "
1994 				    "block mode with SILI enabled\n");
1995 				error = EINVAL;
1996 				break;
1997 			}
1998 			error = sasetparams(periph, SA_PARAM_BLOCKSIZE, count,
1999 					    0, 0, 0);
2000 			if (error == 0) {
2001 				softc->last_media_blksize =
2002 				    softc->media_blksize;
2003 				softc->media_blksize = count;
2004 				if (count) {
2005 					softc->flags |= SA_FLAG_FIXED;
2006 					if (powerof2(count)) {
2007 						softc->blk_shift =
2008 						    ffs(count) - 1;
2009 						softc->blk_mask = count - 1;
2010 					} else {
2011 						softc->blk_mask = ~0;
2012 						softc->blk_shift = 0;
2013 					}
2014 					/*
2015 					 * Make the user's desire 'persistent'.
2016 					 */
2017 					softc->quirks &= ~SA_QUIRK_VARIABLE;
2018 					softc->quirks |= SA_QUIRK_FIXED;
2019 				} else {
2020 					softc->flags &= ~SA_FLAG_FIXED;
2021 					if (softc->max_blk == 0) {
2022 						softc->max_blk = ~0;
2023 					}
2024 					softc->blk_shift = 0;
2025 					if (softc->blk_gran != 0) {
2026 						softc->blk_mask =
2027 						    softc->blk_gran - 1;
2028 					} else {
2029 						softc->blk_mask = 0;
2030 					}
2031 					/*
2032 					 * Make the user's desire 'persistent'.
2033 					 */
2034 					softc->quirks |= SA_QUIRK_VARIABLE;
2035 					softc->quirks &= ~SA_QUIRK_FIXED;
2036 				}
2037 			}
2038 			break;
2039 		case MTSETDNSTY:	/* Set density for device and mode */
2040 			PENDING_MOUNT_CHECK(softc, periph, dev);
2041 
2042 			if (count > UCHAR_MAX) {
2043 				error = EINVAL;
2044 				break;
2045 			} else {
2046 				error = sasetparams(periph, SA_PARAM_DENSITY,
2047 						    0, count, 0, 0);
2048 			}
2049 			break;
2050 		case MTCOMP:	/* enable compression */
2051 			PENDING_MOUNT_CHECK(softc, periph, dev);
2052 			/*
2053 			 * Some devices don't support compression, and
2054 			 * don't like it if you ask them for the
2055 			 * compression page.
2056 			 */
2057 			if ((softc->quirks & SA_QUIRK_NOCOMP) ||
2058 			    (softc->flags & SA_FLAG_COMP_UNSUPP)) {
2059 				error = ENODEV;
2060 				break;
2061 			}
2062 			error = sasetparams(periph, SA_PARAM_COMPRESSION,
2063 			    0, 0, count, SF_NO_PRINT);
2064 			break;
2065 		default:
2066 			error = EINVAL;
2067 		}
2068 		break;
2069 	}
2070 	case MTIOCIEOT:
2071 	case MTIOCEEOT:
2072 		error = 0;
2073 		break;
2074 	case MTIOCRDSPOS:
2075 		PENDING_MOUNT_CHECK(softc, periph, dev);
2076 		error = sardpos(periph, 0, (uint32_t *) arg);
2077 		break;
2078 	case MTIOCRDHPOS:
2079 		PENDING_MOUNT_CHECK(softc, periph, dev);
2080 		error = sardpos(periph, 1, (uint32_t *) arg);
2081 		break;
2082 	case MTIOCSLOCATE:
2083 	case MTIOCHLOCATE: {
2084 		struct mtlocate locate_info;
2085 		int hard;
2086 
2087 		bzero(&locate_info, sizeof(locate_info));
2088 		locate_info.logical_id = *((uint32_t *)arg);
2089 		if (cmd == MTIOCSLOCATE)
2090 			hard = 0;
2091 		else
2092 			hard = 1;
2093 
2094 		PENDING_MOUNT_CHECK(softc, periph, dev);
2095 
2096 		error = sasetpos(periph, hard, &locate_info);
2097 		break;
2098 	}
2099 	case MTIOCEXTLOCATE:
2100 		PENDING_MOUNT_CHECK(softc, periph, dev);
2101 		error = sasetpos(periph, /*hard*/ 0, (struct mtlocate *)arg);
2102 		softc->flags &=
2103 		    ~(SA_FLAG_TAPE_WRITTEN|SA_FLAG_TAPE_FROZEN);
2104 		softc->flags &= ~SA_FLAG_ERR_PENDING;
2105 		softc->filemarks = 0;
2106 		break;
2107 	case MTIOCGETEOTMODEL:
2108 		error = 0;
2109 		if (softc->quirks & SA_QUIRK_1FM)
2110 			mode = 1;
2111 		else
2112 			mode = 2;
2113 		*((uint32_t *) arg) = mode;
2114 		break;
2115 	case MTIOCSETEOTMODEL:
2116 		error = 0;
2117 		switch (*((uint32_t *) arg)) {
2118 		case 1:
2119 			softc->quirks &= ~SA_QUIRK_2FM;
2120 			softc->quirks |= SA_QUIRK_1FM;
2121 			break;
2122 		case 2:
2123 			softc->quirks &= ~SA_QUIRK_1FM;
2124 			softc->quirks |= SA_QUIRK_2FM;
2125 			break;
2126 		default:
2127 			error = EINVAL;
2128 			break;
2129 		}
2130 		break;
2131 	case MTIOCRBLIM: {
2132 		struct mtrblim *rblim;
2133 
2134 		rblim = (struct mtrblim *)arg;
2135 
2136 		rblim->granularity = softc->blk_gran;
2137 		rblim->min_block_length = softc->min_blk;
2138 		rblim->max_block_length = softc->max_blk;
2139 		break;
2140 	}
2141 	default:
2142 		error = cam_periph_ioctl(periph, cmd, arg, saerror);
2143 		break;
2144 	}
2145 
2146 	/*
2147 	 * Check to see if we cleared a frozen state
2148 	 */
2149 	if (error == 0 && (softc->flags & SA_FLAG_TAPE_FROZEN)) {
2150 		switch(cmd) {
2151 		case MTIOCRDSPOS:
2152 		case MTIOCRDHPOS:
2153 		case MTIOCSLOCATE:
2154 		case MTIOCHLOCATE:
2155 			/*
2156 			 * XXX KDM look at this.
2157 			 */
2158 			softc->fileno = (daddr_t) -1;
2159 			softc->blkno = (daddr_t) -1;
2160 			softc->rep_blkno = (daddr_t) -1;
2161 			softc->rep_fileno = (daddr_t) -1;
2162 			softc->partition = (daddr_t) -1;
2163 			softc->flags &= ~SA_FLAG_TAPE_FROZEN;
2164 			xpt_print(periph->path,
2165 			    "tape state now unfrozen.\n");
2166 			break;
2167 		default:
2168 			break;
2169 		}
2170 	}
2171 	if (didlockperiph) {
2172 		cam_periph_unhold(periph);
2173 	}
2174 	cam_periph_unlock(periph);
2175 	return (error);
2176 }
2177 
2178 static void
sainit(void)2179 sainit(void)
2180 {
2181 	cam_status status;
2182 
2183 	/*
2184 	 * Install a global async callback.
2185 	 */
2186 	status = xpt_register_async(AC_FOUND_DEVICE, saasync, NULL, NULL);
2187 
2188 	if (status != CAM_REQ_CMP) {
2189 		printf("sa: Failed to attach master async callback "
2190 		       "due to status 0x%x!\n", status);
2191 	}
2192 }
2193 
2194 static void
sadevgonecb(void * arg)2195 sadevgonecb(void *arg)
2196 {
2197 	struct cam_periph *periph;
2198 	struct mtx *mtx;
2199 	struct sa_softc *softc;
2200 
2201 	periph = (struct cam_periph *)arg;
2202 	softc = (struct sa_softc *)periph->softc;
2203 
2204 	mtx = cam_periph_mtx(periph);
2205 	mtx_lock(mtx);
2206 
2207 	softc->num_devs_to_destroy--;
2208 	if (softc->num_devs_to_destroy == 0) {
2209 		int i;
2210 
2211 		/*
2212 		 * When we have gotten all of our callbacks, we will get
2213 		 * no more close calls from devfs.  So if we have any
2214 		 * dangling opens, we need to release the reference held
2215 		 * for that particular context.
2216 		 */
2217 		for (i = 0; i < softc->open_count; i++)
2218 			cam_periph_release_locked(periph);
2219 
2220 		softc->open_count = 0;
2221 
2222 		/*
2223 		 * Release the reference held for devfs, all of our
2224 		 * instances are gone now.
2225 		 */
2226 		cam_periph_release_locked(periph);
2227 	}
2228 
2229 	/*
2230 	 * We reference the lock directly here, instead of using
2231 	 * cam_periph_unlock().  The reason is that the final call to
2232 	 * cam_periph_release_locked() above could result in the periph
2233 	 * getting freed.  If that is the case, dereferencing the periph
2234 	 * with a cam_periph_unlock() call would cause a page fault.
2235 	 */
2236 	mtx_unlock(mtx);
2237 }
2238 
2239 static void
saoninvalidate(struct cam_periph * periph)2240 saoninvalidate(struct cam_periph *periph)
2241 {
2242 	struct sa_softc *softc;
2243 
2244 	softc = (struct sa_softc *)periph->softc;
2245 
2246 	/*
2247 	 * De-register any async callbacks.
2248 	 */
2249 	xpt_register_async(0, saasync, periph, periph->path);
2250 
2251 	softc->flags |= SA_FLAG_INVALID;
2252 
2253 	/*
2254 	 * Return all queued I/O with ENXIO.
2255 	 * XXX Handle any transactions queued to the card
2256 	 *     with XPT_ABORT_CCB.
2257 	 */
2258 	bioq_flush(&softc->bio_queue, NULL, ENXIO);
2259 	softc->queue_count = 0;
2260 
2261 	/*
2262 	 * Tell devfs that all of our devices have gone away, and ask for a
2263 	 * callback when it has cleaned up its state.
2264 	 */
2265 	destroy_dev_sched_cb(softc->devs.ctl_dev, sadevgonecb, periph);
2266 	destroy_dev_sched_cb(softc->devs.r_dev, sadevgonecb, periph);
2267 	destroy_dev_sched_cb(softc->devs.nr_dev, sadevgonecb, periph);
2268 	destroy_dev_sched_cb(softc->devs.er_dev, sadevgonecb, periph);
2269 }
2270 
2271 static void
sacleanup(struct cam_periph * periph)2272 sacleanup(struct cam_periph *periph)
2273 {
2274 	struct sa_softc *softc;
2275 
2276 	softc = (struct sa_softc *)periph->softc;
2277 
2278 	cam_periph_unlock(periph);
2279 
2280 	if ((softc->flags & SA_FLAG_SCTX_INIT) != 0
2281 	 && (((softc->sysctl_timeout_tree != NULL)
2282 	   && (sysctl_ctx_free(&softc->sysctl_timeout_ctx) != 0))
2283 	  || sysctl_ctx_free(&softc->sysctl_ctx) != 0))
2284 		xpt_print(periph->path, "can't remove sysctl context\n");
2285 
2286 	cam_periph_lock(periph);
2287 
2288 	devstat_remove_entry(softc->device_stats);
2289 
2290 	free(softc, M_SCSISA);
2291 }
2292 
2293 static void
saasync(void * callback_arg,uint32_t code,struct cam_path * path,void * arg)2294 saasync(void *callback_arg, uint32_t code,
2295 	struct cam_path *path, void *arg)
2296 {
2297 	struct cam_periph *periph;
2298 
2299 	periph = (struct cam_periph *)callback_arg;
2300 	switch (code) {
2301 	case AC_FOUND_DEVICE:
2302 	{
2303 		struct ccb_getdev *cgd;
2304 		cam_status status;
2305 
2306 		cgd = (struct ccb_getdev *)arg;
2307 		if (cgd == NULL)
2308 			break;
2309 
2310 		if (cgd->protocol != PROTO_SCSI)
2311 			break;
2312 		if (SID_QUAL(&cgd->inq_data) != SID_QUAL_LU_CONNECTED)
2313 			break;
2314 		if (SID_TYPE(&cgd->inq_data) != T_SEQUENTIAL)
2315 			break;
2316 
2317 		/*
2318 		 * Allocate a peripheral instance for
2319 		 * this device and start the probe
2320 		 * process.
2321 		 */
2322 		status = cam_periph_alloc(saregister, saoninvalidate,
2323 					  sacleanup, sastart,
2324 					  "sa", CAM_PERIPH_BIO, path,
2325 					  saasync, AC_FOUND_DEVICE, cgd);
2326 
2327 		if (status != CAM_REQ_CMP
2328 		 && status != CAM_REQ_INPROG)
2329 			printf("saasync: Unable to probe new device "
2330 				"due to status 0x%x\n", status);
2331 		break;
2332 	}
2333 	default:
2334 		cam_periph_async(periph, code, path, arg);
2335 		break;
2336 	}
2337 }
2338 
2339 static void
sasetupdev(struct sa_softc * softc,struct cdev * dev)2340 sasetupdev(struct sa_softc *softc, struct cdev *dev)
2341 {
2342 
2343 	dev->si_iosize_max = softc->maxio;
2344 	dev->si_flags |= softc->si_flags;
2345 	/*
2346 	 * Keep a count of how many non-alias devices we have created,
2347 	 * so we can make sure we clean them all up on shutdown.  Aliases
2348 	 * are cleaned up when we destroy the device they're an alias for.
2349 	 */
2350 	if ((dev->si_flags & SI_ALIAS) == 0)
2351 		softc->num_devs_to_destroy++;
2352 }
2353 
2354 /*
2355  * Load the global (for all sa(4) instances) and per-instance tunable
2356  * values for timeouts for various sa(4) commands.  This should be run
2357  * after the default timeouts are fetched from the drive, so the user's
2358  * preference will override the drive's defaults.
2359  */
2360 static void
saloadtotunables(struct sa_softc * softc)2361 saloadtotunables(struct sa_softc *softc)
2362 {
2363 	int i;
2364 	char tmpstr[80];
2365 
2366 	for (i = 0; i < SA_TIMEOUT_TYPE_MAX; i++) {
2367 		int tmpval, retval;
2368 
2369 		/* First grab any global timeout setting */
2370 		snprintf(tmpstr, sizeof(tmpstr), "kern.cam.sa.timeout.%s",
2371 		    sa_default_timeouts[i].desc);
2372 		retval = TUNABLE_INT_FETCH(tmpstr, &tmpval);
2373 		if (retval != 0)
2374 			softc->timeout_info[i] = tmpval;
2375 
2376 		/*
2377 		 * Then overwrite any global timeout settings with
2378 		 * per-instance timeout settings.
2379 		 */
2380 		snprintf(tmpstr, sizeof(tmpstr), "kern.cam.sa.%u.timeout.%s",
2381 		    softc->periph->unit_number, sa_default_timeouts[i].desc);
2382 		retval = TUNABLE_INT_FETCH(tmpstr, &tmpval);
2383 		if (retval != 0)
2384 			softc->timeout_info[i] = tmpval;
2385 	}
2386 }
2387 
2388 static void
sasysctlinit(void * context,int pending)2389 sasysctlinit(void *context, int pending)
2390 {
2391 	struct cam_periph *periph;
2392 	struct sa_softc *softc;
2393 	char tmpstr[64], tmpstr2[16];
2394 	int i;
2395 
2396 	periph = (struct cam_periph *)context;
2397 	/*
2398 	 * If the periph is invalid, no need to setup the sysctls.
2399 	 */
2400 	if (periph->flags & CAM_PERIPH_INVALID)
2401 		goto bailout;
2402 
2403 	softc = (struct sa_softc *)periph->softc;
2404 
2405 	snprintf(tmpstr, sizeof(tmpstr), "CAM SA unit %d", periph->unit_number);
2406 	snprintf(tmpstr2, sizeof(tmpstr2), "%u", periph->unit_number);
2407 
2408 	sysctl_ctx_init(&softc->sysctl_ctx);
2409 	softc->flags |= SA_FLAG_SCTX_INIT;
2410 	softc->sysctl_tree = SYSCTL_ADD_NODE_WITH_LABEL(&softc->sysctl_ctx,
2411 	    SYSCTL_STATIC_CHILDREN(_kern_cam_sa), OID_AUTO, tmpstr2,
2412 	    CTLFLAG_RD | CTLFLAG_MPSAFE, 0, tmpstr, "device_index");
2413 	if (softc->sysctl_tree == NULL)
2414 		goto bailout;
2415 
2416 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
2417 	    OID_AUTO, "allow_io_split", CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
2418 	    &softc->allow_io_split, 0, "Allow Splitting I/O");
2419 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
2420 	    OID_AUTO, "maxio", CTLFLAG_RD,
2421 	    &softc->maxio, 0, "Maximum I/O size");
2422 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
2423 	    OID_AUTO, "cpi_maxio", CTLFLAG_RD,
2424 	    &softc->cpi_maxio, 0, "Maximum Controller I/O size");
2425 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
2426 	    OID_AUTO, "inject_eom", CTLFLAG_RW,
2427 	    &softc->inject_eom, 0, "Queue EOM for the next write/read");
2428 
2429 	sysctl_ctx_init(&softc->sysctl_timeout_ctx);
2430 	softc->sysctl_timeout_tree = SYSCTL_ADD_NODE(&softc->sysctl_timeout_ctx,
2431 	    SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO, "timeout",
2432 	    CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "Timeouts");
2433 	if (softc->sysctl_timeout_tree == NULL)
2434 		goto bailout;
2435 
2436 	for (i = 0; i < SA_TIMEOUT_TYPE_MAX; i++) {
2437 		snprintf(tmpstr, sizeof(tmpstr), "%s timeout",
2438 		    sa_default_timeouts[i].desc);
2439 
2440 		/*
2441 		 * Do NOT change this sysctl declaration to also load any
2442 		 * tunable values for this sa(4) instance.  In other words,
2443 		 * do not change this to CTLFLAG_RWTUN.  This function is
2444 		 * run in parallel with the probe routine that fetches
2445 		 * recommended timeout values from the tape drive, and we
2446 		 * don't want the values from the drive to override the
2447 		 * user's preference.
2448 		 */
2449 		SYSCTL_ADD_INT(&softc->sysctl_timeout_ctx,
2450 		    SYSCTL_CHILDREN(softc->sysctl_timeout_tree),
2451 	            OID_AUTO, sa_default_timeouts[i].desc, CTLFLAG_RW,
2452 		    &softc->timeout_info[i], 0, tmpstr);
2453 	}
2454 
2455 bailout:
2456 	/*
2457 	 * Release the reference that was held when this task was enqueued.
2458 	 */
2459 	cam_periph_release(periph);
2460 }
2461 
2462 static cam_status
saregister(struct cam_periph * periph,void * arg)2463 saregister(struct cam_periph *periph, void *arg)
2464 {
2465 	struct sa_softc *softc;
2466 	struct ccb_getdev *cgd;
2467 	struct ccb_pathinq cpi;
2468 	struct make_dev_args args;
2469 	caddr_t match;
2470 	char tmpstr[80];
2471 	int error;
2472 	int i;
2473 
2474 	cgd = (struct ccb_getdev *)arg;
2475 	if (cgd == NULL) {
2476 		printf("saregister: no getdev CCB, can't register device\n");
2477 		return (CAM_REQ_CMP_ERR);
2478 	}
2479 
2480 	softc = (struct sa_softc *)
2481 	    malloc(sizeof (*softc), M_SCSISA, M_NOWAIT | M_ZERO);
2482 	if (softc == NULL) {
2483 		printf("saregister: Unable to probe new device. "
2484 		       "Unable to allocate softc\n");
2485 		return (CAM_REQ_CMP_ERR);
2486 	}
2487 	softc->scsi_rev = SID_ANSI_REV(&cgd->inq_data);
2488 	softc->state = SA_STATE_NORMAL;
2489 	softc->fileno = (daddr_t) -1;
2490 	softc->blkno = (daddr_t) -1;
2491 	softc->rep_fileno = (daddr_t) -1;
2492 	softc->rep_blkno = (daddr_t) -1;
2493 	softc->partition = (daddr_t) -1;
2494 	softc->bop = -1;
2495 	softc->eop = -1;
2496 	softc->bpew = -1;
2497 
2498 	bioq_init(&softc->bio_queue);
2499 	softc->periph = periph;
2500 	periph->softc = softc;
2501 
2502 	/*
2503 	 * See if this device has any quirks.
2504 	 */
2505 	match = cam_quirkmatch((caddr_t)&cgd->inq_data,
2506 			       (caddr_t)sa_quirk_table,
2507 			       nitems(sa_quirk_table),
2508 			       sizeof(*sa_quirk_table), scsi_inquiry_match);
2509 
2510 	if (match != NULL) {
2511 		softc->quirks = ((struct sa_quirk_entry *)match)->quirks;
2512 		softc->last_media_blksize =
2513 		    ((struct sa_quirk_entry *)match)->prefblk;
2514 	} else
2515 		softc->quirks = SA_QUIRK_NONE;
2516 
2517 
2518 	/*
2519 	 * Initialize the default timeouts.  If this drive supports
2520 	 * timeout descriptors we'll overwrite these values with the
2521 	 * recommended timeouts from the drive.
2522 	 */
2523 	for (i = 0; i < SA_TIMEOUT_TYPE_MAX; i++)
2524 		softc->timeout_info[i] = sa_default_timeouts[i].value;
2525 
2526 	/*
2527 	 * Long format data for READ POSITION was introduced in SSC, which
2528 	 * was after SCSI-2.  (Roughly equivalent to SCSI-3.)  If the drive
2529 	 * reports that it is SCSI-2 or older, it is unlikely to support
2530 	 * long position data, but it might.  Some drives from that era
2531 	 * claim to be SCSI-2, but do support long position information.
2532 	 * So, instead of immediately disabling long position information
2533 	 * for SCSI-2 devices, we'll try one pass through sagetpos(), and
2534 	 * then disable long position information if we get an error.
2535 	 */
2536 	if (cgd->inq_data.version <= SCSI_REV_CCS)
2537 		softc->quirks |= SA_QUIRK_NO_LONG_POS;
2538 
2539 	/*
2540 	 * The SCSI REPORT SUPPORTED OPERATION CODES command was added in
2541 	 * SPC-4.  That command optionally includes timeout data for
2542 	 * different commands.  Timeout values can vary wildly among
2543 	 * different drives, so if the drive itself has recommended values,
2544 	 * we will try to use them.  Set this flag to indicate we're going
2545 	 * to ask the drive for timeout data.  This flag also tells us to
2546 	 * wait on loading timeout tunables so we can properly override
2547 	 * timeouts with any user-specified values.
2548 	 */
2549 	if (SID_ANSI_REV(&cgd->inq_data) >= SCSI_REV_SPC4)
2550 		softc->flags |= SA_FLAG_RSOC_TO_TRY;
2551 
2552 	if (cgd->inq_data.spc3_flags & SPC3_SID_PROTECT) {
2553 		struct ccb_dev_advinfo cdai;
2554 		struct scsi_vpd_extended_inquiry_data ext_inq;
2555 
2556 		bzero(&ext_inq, sizeof(ext_inq));
2557 
2558 		memset(&cdai, 0, sizeof(cdai));
2559 		xpt_setup_ccb(&cdai.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
2560 
2561 		cdai.ccb_h.func_code = XPT_DEV_ADVINFO;
2562 		cdai.flags = CDAI_FLAG_NONE;
2563 		cdai.buftype = CDAI_TYPE_EXT_INQ;
2564 		cdai.bufsiz = sizeof(ext_inq);
2565 		cdai.buf = (uint8_t *)&ext_inq;
2566 		xpt_action((union ccb *)&cdai);
2567 
2568 		if ((cdai.ccb_h.status & CAM_DEV_QFRZN) != 0)
2569 			cam_release_devq(cdai.ccb_h.path, 0, 0, 0, FALSE);
2570 		if ((cdai.ccb_h.status == CAM_REQ_CMP)
2571 		 && (ext_inq.flags1 & SVPD_EID_SA_SPT_LBP))
2572 			softc->flags |= SA_FLAG_PROTECT_SUPP;
2573 	}
2574 
2575 	xpt_path_inq(&cpi, periph->path);
2576 
2577 	/*
2578 	 * The SA driver supports a blocksize, but we don't know the
2579 	 * blocksize until we media is inserted.  So, set a flag to
2580 	 * indicate that the blocksize is unavailable right now.
2581 	 */
2582 	cam_periph_unlock(periph);
2583 	softc->device_stats = devstat_new_entry("sa", periph->unit_number, 0,
2584 	    DEVSTAT_BS_UNAVAILABLE, SID_TYPE(&cgd->inq_data) |
2585 	    XPORT_DEVSTAT_TYPE(cpi.transport), DEVSTAT_PRIORITY_TAPE);
2586 
2587 	/*
2588 	 * Load the default value that is either compiled in, or loaded
2589 	 * in the global kern.cam.sa.allow_io_split tunable.
2590 	 */
2591 	softc->allow_io_split = sa_allow_io_split;
2592 
2593 	/*
2594 	 * Load a per-instance tunable, if it exists.  NOTE that this
2595 	 * tunable WILL GO AWAY in FreeBSD 11.0.
2596 	 */
2597 	snprintf(tmpstr, sizeof(tmpstr), "kern.cam.sa.%u.allow_io_split",
2598 		 periph->unit_number);
2599 	TUNABLE_INT_FETCH(tmpstr, &softc->allow_io_split);
2600 
2601 	/*
2602 	 * If maxio isn't set, we fall back to DFLTPHYS.  Otherwise we take
2603 	 * the smaller of cpi.maxio or maxphys.
2604 	 */
2605 	if (cpi.maxio == 0)
2606 		softc->maxio = DFLTPHYS;
2607 	else if (cpi.maxio > maxphys)
2608 		softc->maxio = maxphys;
2609 	else
2610 		softc->maxio = cpi.maxio;
2611 
2612 	/*
2613 	 * Record the controller's maximum I/O size so we can report it to
2614 	 * the user later.
2615 	 */
2616 	softc->cpi_maxio = cpi.maxio;
2617 
2618 	/*
2619 	 * By default we tell physio that we do not want our I/O split.
2620 	 * The user needs to have a 1:1 mapping between the size of his
2621 	 * write to a tape character device and the size of the write
2622 	 * that actually goes down to the drive.
2623 	 */
2624 	if (softc->allow_io_split == 0)
2625 		softc->si_flags = SI_NOSPLIT;
2626 	else
2627 		softc->si_flags = 0;
2628 
2629 	TASK_INIT(&softc->sysctl_task, 0, sasysctlinit, periph);
2630 
2631 	/*
2632 	 * If the SIM supports unmapped I/O, let physio know that we can
2633 	 * handle unmapped buffers.
2634 	 */
2635 	if (cpi.hba_misc & PIM_UNMAPPED)
2636 		softc->si_flags |= SI_UNMAPPED;
2637 
2638 	/*
2639 	 * Acquire a reference to the periph before we create the devfs
2640 	 * instances for it.  We'll release this reference once the devfs
2641 	 * instances have been freed.
2642 	 */
2643 	if (cam_periph_acquire(periph) != 0) {
2644 		xpt_print(periph->path, "%s: lost periph during "
2645 			  "registration!\n", __func__);
2646 		cam_periph_lock(periph);
2647 		return (CAM_REQ_CMP_ERR);
2648 	}
2649 
2650 	make_dev_args_init(&args);
2651 	args.mda_devsw = &sa_cdevsw;
2652 	args.mda_si_drv1 = softc->periph;
2653 	args.mda_uid = UID_ROOT;
2654 	args.mda_gid = GID_OPERATOR;
2655 	args.mda_mode = 0660;
2656 
2657 	args.mda_unit = SAMINOR(SA_CTLDEV, SA_ATYPE_R);
2658 	error = make_dev_s(&args, &softc->devs.ctl_dev, "%s%d.ctl",
2659 	    periph->periph_name, periph->unit_number);
2660 	if (error != 0) {
2661 		cam_periph_lock(periph);
2662 		return (CAM_REQ_CMP_ERR);
2663 	}
2664 	sasetupdev(softc, softc->devs.ctl_dev);
2665 
2666 	args.mda_unit = SAMINOR(SA_NOT_CTLDEV, SA_ATYPE_R);
2667 	error = make_dev_s(&args, &softc->devs.r_dev, "%s%d",
2668 	    periph->periph_name, periph->unit_number);
2669 	if (error != 0) {
2670 		cam_periph_lock(periph);
2671 		return (CAM_REQ_CMP_ERR);
2672 	}
2673 	sasetupdev(softc, softc->devs.r_dev);
2674 
2675 	args.mda_unit = SAMINOR(SA_NOT_CTLDEV, SA_ATYPE_NR);
2676 	error = make_dev_s(&args, &softc->devs.nr_dev, "n%s%d",
2677 	    periph->periph_name, periph->unit_number);
2678 	if (error != 0) {
2679 		cam_periph_lock(periph);
2680 		return (CAM_REQ_CMP_ERR);
2681 	}
2682 	sasetupdev(softc, softc->devs.nr_dev);
2683 
2684 	args.mda_unit = SAMINOR(SA_NOT_CTLDEV, SA_ATYPE_ER);
2685 	error = make_dev_s(&args, &softc->devs.er_dev, "e%s%d",
2686 	    periph->periph_name, periph->unit_number);
2687 	if (error != 0) {
2688 		cam_periph_lock(periph);
2689 		return (CAM_REQ_CMP_ERR);
2690 	}
2691 	sasetupdev(softc, softc->devs.er_dev);
2692 
2693 	cam_periph_lock(periph);
2694 
2695 	softc->density_type_bits[0] = 0;
2696 	softc->density_type_bits[1] = SRDS_MEDIA;
2697 	softc->density_type_bits[2] = SRDS_MEDIUM_TYPE;
2698 	softc->density_type_bits[3] = SRDS_MEDIUM_TYPE | SRDS_MEDIA;
2699 	/*
2700 	 * Bump the peripheral refcount for the sysctl thread, in case we
2701 	 * get invalidated before the thread has a chance to run.  Note
2702 	 * that this runs in parallel with the probe for the timeout
2703 	 * values.
2704 	 */
2705 	cam_periph_acquire(periph);
2706 	taskqueue_enqueue(taskqueue_thread, &softc->sysctl_task);
2707 
2708 	/*
2709 	 * Add an async callback so that we get
2710 	 * notified if this device goes away.
2711 	 */
2712 	xpt_register_async(AC_LOST_DEVICE, saasync, periph, periph->path);
2713 
2714 	/*
2715 	 * See comment above, try fetching timeout values for drives that
2716 	 * might support it.  Otherwise, use the defaults.
2717 	 *
2718 	 * We get timeouts from the following places in order of increasing
2719 	 * priority:
2720 	 * 1. Driver default timeouts.
2721 	 * 2. Timeouts loaded from the drive via REPORT SUPPORTED OPERATION
2722 	 *    CODES. (We kick that off here if SA_FLAG_RSOC_TO_TRY is set.)
2723 	 * 3. Global loader tunables, used for all sa(4) driver instances on
2724 	 *    a machine.
2725 	 * 4. Instance-specific loader tunables, used for say sa5.
2726 	 * 5. On the fly user sysctl changes.
2727 	 *
2728 	 * Each step will overwrite the timeout value set from the one
2729 	 * before, so you go from general to most specific.
2730 	 */
2731 	if (softc->flags & SA_FLAG_RSOC_TO_TRY) {
2732 		/*
2733 		 * Bump the peripheral refcount while we are probing.
2734 		 */
2735 		cam_periph_acquire(periph);
2736 		softc->state = SA_STATE_PROBE;
2737 		xpt_schedule(periph, CAM_PRIORITY_DEV);
2738 	} else {
2739 		/*
2740 		 * This drive doesn't support Report Supported Operation
2741 		 * Codes, so we load the tunables at this point to bring
2742 		 * in any user preferences.
2743 		 */
2744 		saloadtotunables(softc);
2745 
2746 		xpt_announce_periph(periph, NULL);
2747 		xpt_announce_quirks(periph, softc->quirks, SA_QUIRK_BIT_STRING);
2748 	}
2749 
2750 	return (CAM_REQ_CMP);
2751 }
2752 
2753 static void
sastart(struct cam_periph * periph,union ccb * start_ccb)2754 sastart(struct cam_periph *periph, union ccb *start_ccb)
2755 {
2756 	struct sa_softc *softc;
2757 
2758 	softc = (struct sa_softc *)periph->softc;
2759 
2760 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("sastart\n"));
2761 
2762 	switch (softc->state) {
2763 	case SA_STATE_NORMAL:
2764 	{
2765 		/* Pull a buffer from the queue and get going on it */
2766 		struct bio *bp;
2767 
2768 		/*
2769 		 * See if there is a buf with work for us to do..
2770 		 */
2771 		bp = bioq_first(&softc->bio_queue);
2772 		if (bp == NULL) {
2773 			xpt_release_ccb(start_ccb);
2774 		} else if (((softc->flags & SA_FLAG_ERR_PENDING) != 0)
2775 			|| (softc->inject_eom != 0)) {
2776 			struct bio *done_bp;
2777 
2778 			if (softc->inject_eom != 0) {
2779 				softc->flags |= SA_FLAG_EOM_PENDING;
2780 				softc->inject_eom = 0;
2781 				/*
2782 				 * If we're injecting EOM for writes, we
2783 				 * need to keep PEWS set for 3 queries
2784 				 * to cover 2 position requests from the
2785 				 * kernel via sagetpos(), and then allow
2786 				 * for one for the user to see the BPEW
2787 				 * flag (e.g. via mt status).  After that,
2788 				 * it will be cleared.
2789 				 */
2790 				if (bp->bio_cmd == BIO_WRITE)
2791 					softc->set_pews_status = 3;
2792 				else
2793 					softc->set_pews_status = 1;
2794 			}
2795 again:
2796 			softc->queue_count--;
2797 			bioq_remove(&softc->bio_queue, bp);
2798 			bp->bio_resid = bp->bio_bcount;
2799 			done_bp = bp;
2800 			if ((softc->flags & SA_FLAG_EOM_PENDING) != 0) {
2801 				/*
2802 				 * We have two different behaviors for
2803 				 * writes when we hit either Early Warning
2804 				 * or the PEWZ (Programmable Early Warning
2805 				 * Zone).  The default behavior is that
2806 				 * for all writes that are currently
2807 				 * queued after the write where we saw the
2808 				 * early warning, we will return the write
2809 				 * with the residual equal to the count.
2810 				 * i.e. tell the application that 0 bytes
2811 				 * were written.
2812 				 *
2813 				 * The alternate behavior, which is enabled
2814 				 * when eot_warn is set, is that in
2815 				 * addition to setting the residual equal
2816 				 * to the count, we will set the error
2817 				 * to ENOSPC.
2818 				 *
2819 				 * In either case, once queued writes are
2820 				 * cleared out, we clear the error flag
2821 				 * (see below) and the application is free to
2822 				 * attempt to write more.
2823 				 */
2824 				if (softc->eot_warn != 0) {
2825 					bp->bio_flags |= BIO_ERROR;
2826 					bp->bio_error = ENOSPC;
2827 				} else
2828 					bp->bio_error = 0;
2829 			} else if ((softc->flags & SA_FLAG_EOF_PENDING) != 0) {
2830 				/*
2831 				 * This can only happen if we're reading
2832 				 * in fixed length mode. In this case,
2833 				 * we dump the rest of the list the
2834 				 * same way.
2835 				 */
2836 				bp->bio_error = 0;
2837 				if (bioq_first(&softc->bio_queue) != NULL) {
2838 					biodone(done_bp);
2839 					goto again;
2840 				}
2841 			} else if ((softc->flags & SA_FLAG_EIO_PENDING) != 0) {
2842 				bp->bio_error = EIO;
2843 				bp->bio_flags |= BIO_ERROR;
2844 			}
2845 			bp = bioq_first(&softc->bio_queue);
2846 			/*
2847 			 * Only if we have no other buffers queued up
2848 			 * do we clear the pending error flag.
2849 			 */
2850 			if (bp == NULL)
2851 				softc->flags &= ~SA_FLAG_ERR_PENDING;
2852 			CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
2853 			    ("sastart- ERR_PENDING now 0x%x, bp is %sNULL, "
2854 			    "%d more buffers queued up\n",
2855 			    (softc->flags & SA_FLAG_ERR_PENDING),
2856 			    (bp != NULL)? "not " : " ", softc->queue_count));
2857 			xpt_release_ccb(start_ccb);
2858 			biodone(done_bp);
2859 		} else {
2860 			uint32_t length;
2861 
2862 			bioq_remove(&softc->bio_queue, bp);
2863 			softc->queue_count--;
2864 
2865 			if ((bp->bio_cmd != BIO_READ) &&
2866 			    (bp->bio_cmd != BIO_WRITE)) {
2867 				biofinish(bp, NULL, EOPNOTSUPP);
2868 				xpt_release_ccb(start_ccb);
2869 				return;
2870 			}
2871 			length = bp->bio_bcount;
2872 
2873 			if ((softc->flags & SA_FLAG_FIXED) != 0) {
2874 				if (softc->blk_shift != 0) {
2875 					length = length >> softc->blk_shift;
2876 				} else if (softc->media_blksize != 0) {
2877 					length = length / softc->media_blksize;
2878 				} else {
2879 					bp->bio_error = EIO;
2880 					xpt_print(periph->path, "zero blocksize"
2881 					    " for FIXED length writes?\n");
2882 					biodone(bp);
2883 					break;
2884 				}
2885 #if	0
2886 				CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_INFO,
2887 				    ("issuing a %d fixed record %s\n",
2888 				    length,  (bp->bio_cmd == BIO_READ)? "read" :
2889 				    "write"));
2890 #endif
2891 			} else {
2892 #if	0
2893 				CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_INFO,
2894 				    ("issuing a %d variable byte %s\n",
2895 				    length,  (bp->bio_cmd == BIO_READ)? "read" :
2896 				    "write"));
2897 #endif
2898 			}
2899 			devstat_start_transaction_bio(softc->device_stats, bp);
2900 			/*
2901 			 * Some people have theorized that we should
2902 			 * suppress illegal length indication if we are
2903 			 * running in variable block mode so that we don't
2904 			 * have to request sense every time our requested
2905 			 * block size is larger than the written block.
2906 			 * The residual information from the ccb allows
2907 			 * us to identify this situation anyway.  The only
2908 			 * problem with this is that we will not get
2909 			 * information about blocks that are larger than
2910 			 * our read buffer unless we set the block size
2911 			 * in the mode page to something other than 0.
2912 			 *
2913 			 * I believe that this is a non-issue. If user apps
2914 			 * don't adjust their read size to match our record
2915 			 * size, that's just life. Anyway, the typical usage
2916 			 * would be to issue, e.g., 64KB reads and occasionally
2917 			 * have to do deal with 512 byte or 1KB intermediate
2918 			 * records.
2919 			 *
2920 			 * That said, though, we now support setting the
2921 			 * SILI bit on reads, and we set the blocksize to 4
2922 			 * bytes when we do that.  This gives us
2923 			 * compatibility with software that wants this,
2924 			 * although the only real difference between that
2925 			 * and not setting the SILI bit on reads is that we
2926 			 * won't get a check condition on reads where our
2927 			 * request size is larger than the block on tape.
2928 			 * That probably only makes a real difference in
2929 			 * non-packetized SCSI, where you have to go back
2930 			 * to the drive to request sense and thus incur
2931 			 * more latency.
2932 			 */
2933 			softc->dsreg = (bp->bio_cmd == BIO_READ)?
2934 			    MTIO_DSREG_RD : MTIO_DSREG_WR;
2935 			scsi_sa_read_write(&start_ccb->csio, 0, sadone,
2936 			    MSG_SIMPLE_Q_TAG, (bp->bio_cmd == BIO_READ ?
2937 			    SCSI_RW_READ : SCSI_RW_WRITE) |
2938 			    ((bp->bio_flags & BIO_UNMAPPED) != 0 ?
2939 			    SCSI_RW_BIO : 0), softc->sili,
2940 			    (softc->flags & SA_FLAG_FIXED) != 0, length,
2941 			    (bp->bio_flags & BIO_UNMAPPED) != 0 ? (void *)bp :
2942 			    bp->bio_data, bp->bio_bcount, SSD_FULL_SIZE,
2943 			    (bp->bio_cmd == BIO_READ) ?
2944 			    softc->timeout_info[SA_TIMEOUT_READ] :
2945 			    softc->timeout_info[SA_TIMEOUT_WRITE]);
2946 			start_ccb->ccb_h.ccb_pflags &= ~SA_POSITION_UPDATED;
2947 			start_ccb->ccb_h.ccb_bp = bp;
2948 			bp = bioq_first(&softc->bio_queue);
2949 			xpt_action(start_ccb);
2950 		}
2951 
2952 		if (bp != NULL) {
2953 			/* Have more work to do, so ensure we stay scheduled */
2954 			xpt_schedule(periph, CAM_PRIORITY_NORMAL);
2955 		}
2956 		break;
2957 	}
2958 	case SA_STATE_PROBE: {
2959 		int num_opcodes;
2960 		size_t alloc_len;
2961 		uint8_t *params;
2962 
2963 		/*
2964 		 * This is an arbitrary number.  An IBM LTO-6 drive reports
2965 		 * 67 entries, and an IBM LTO-9 drive reports 71 entries.
2966 		 * There can theoretically be more than 256 because
2967 		 * service actions of a particular opcode are reported
2968 		 * separately, but we're far enough ahead of the practical
2969 		 * number here that we don't need to implement logic to
2970 		 * retry if we don't get all the timeout descriptors.
2971 		 */
2972 		num_opcodes = 256;
2973 
2974 		alloc_len = num_opcodes *
2975 		    (sizeof(struct scsi_report_supported_opcodes_descr) +
2976 		     sizeof(struct scsi_report_supported_opcodes_timeout));
2977 
2978 		params = malloc(alloc_len, M_SCSISA, M_NOWAIT| M_ZERO);
2979 		if (params == NULL) {
2980 			/*
2981 			 * If this happens, go with default
2982 			 * timeouts and announce the drive.
2983 			 */
2984 			saloadtotunables(softc);
2985 
2986 			softc->state = SA_STATE_NORMAL;
2987 
2988 			xpt_announce_periph(periph, NULL);
2989 			xpt_announce_quirks(periph, softc->quirks,
2990 					    SA_QUIRK_BIT_STRING);
2991 			xpt_release_ccb(start_ccb);
2992 			cam_periph_release_locked(periph);
2993 			return;
2994 		}
2995 
2996 		scsi_report_supported_opcodes(&start_ccb->csio,
2997 		    /*retries*/ 3,
2998 		    /*cbfcnp*/ sadone,
2999 		    /*tag_action*/ MSG_SIMPLE_Q_TAG,
3000 		    /*options*/ RSO_RCTD,
3001 		    /*req_opcode*/ 0,
3002 		    /*req_service_action*/ 0,
3003 		    /*data_ptr*/ params,
3004 		    /*dxfer_len*/ alloc_len,
3005 		    /*sense_len*/ SSD_FULL_SIZE,
3006 		    /*timeout*/ softc->timeout_info[SA_TIMEOUT_TUR]);
3007 
3008 		xpt_action(start_ccb);
3009 		break;
3010 	}
3011 	case SA_STATE_ABNORMAL:
3012 	default:
3013 		panic("state 0x%x in sastart", softc->state);
3014 		break;
3015 	}
3016 }
3017 
3018 static void
sadone(struct cam_periph * periph,union ccb * done_ccb)3019 sadone(struct cam_periph *periph, union ccb *done_ccb)
3020 {
3021 	struct sa_softc *softc;
3022 	struct ccb_scsiio *csio;
3023 	struct bio *bp;
3024 	int error;
3025 
3026 	softc = (struct sa_softc *)periph->softc;
3027 	csio = &done_ccb->csio;
3028 	error = 0;
3029 
3030 	if (softc->state == SA_STATE_NORMAL) {
3031 		softc->dsreg = MTIO_DSREG_REST;
3032 		bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
3033 
3034 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
3035 			if ((error = saerror(done_ccb, 0, 0)) == ERESTART) {
3036 				/*
3037 				 * A retry was scheduled, so just return.
3038 				 */
3039 				return;
3040 			}
3041 		}
3042 	} else if (softc->state == SA_STATE_PROBE) {
3043 		bp = NULL;
3044 		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
3045 			/*
3046 			 * Note that on probe, we just run through
3047 			 * cam_periph_error(), since saerror() has a lot of
3048 			 * special handling for I/O errors.  We don't need
3049 			 * that to get the opcodes.  We either succeed
3050 			 * after a retry or two, or give up.  We don't
3051 			 * print sense, we don't need to worry the user if
3052 			 * this drive doesn't support timeout descriptors.
3053 			 */
3054 			if ((error = cam_periph_error(done_ccb, 0,
3055 			     SF_NO_PRINT)) == ERESTART) {
3056 				/*
3057 				 * A retry was scheduled, so just return.
3058 				 */
3059 				return;
3060 			} else if (error != 0) {
3061 				/* We failed to get opcodes.  Give up. */
3062 
3063 				saloadtotunables(softc);
3064 
3065 				softc->state = SA_STATE_NORMAL;
3066 
3067 				xpt_release_ccb(done_ccb);
3068 
3069 				xpt_announce_periph(periph, NULL);
3070 				xpt_announce_quirks(periph, softc->quirks,
3071 						    SA_QUIRK_BIT_STRING);
3072 				cam_periph_release_locked(periph);
3073 				return;
3074 			}
3075 		}
3076 		/*
3077 		 * At this point, we have succeeded, so load the timeouts
3078 		 * and go into the normal state.
3079 		 */
3080 		softc->state = SA_STATE_NORMAL;
3081 
3082 		/*
3083 		 * First, load the timeouts we got from the drive.
3084 		 */
3085 		saloadtimeouts(softc, done_ccb);
3086 
3087 		/*
3088 		 * Next, overwrite the timeouts from the drive with any
3089 		 * loader tunables that the user set.
3090 		 */
3091 		saloadtotunables(softc);
3092 
3093 		xpt_release_ccb(done_ccb);
3094 		xpt_announce_periph(periph, NULL);
3095 		xpt_announce_quirks(periph, softc->quirks,
3096 				    SA_QUIRK_BIT_STRING);
3097 		cam_periph_release_locked(periph);
3098 		return;
3099 	} else {
3100 		panic("state 0x%x in sadone", softc->state);
3101 	}
3102 
3103 	if (error == EIO) {
3104 		/*
3105 		 * Catastrophic error. Mark the tape as frozen
3106 		 * (we no longer know tape position).
3107 		 *
3108 		 * Return all queued I/O with EIO, and unfreeze
3109 		 * our queue so that future transactions that
3110 		 * attempt to fix this problem can get to the
3111 		 * device.
3112 		 *
3113 		 */
3114 
3115 		softc->flags |= SA_FLAG_TAPE_FROZEN;
3116 		bioq_flush(&softc->bio_queue, NULL, EIO);
3117 	}
3118 	if (error != 0) {
3119 		bp->bio_resid = bp->bio_bcount;
3120 		bp->bio_error = error;
3121 		bp->bio_flags |= BIO_ERROR;
3122 		/*
3123 		 * In the error case, position is updated in saerror.
3124 		 */
3125 	} else {
3126 		bp->bio_resid = csio->resid;
3127 		bp->bio_error = 0;
3128 		if (csio->resid != 0) {
3129 			bp->bio_flags |= BIO_ERROR;
3130 		}
3131 		if (bp->bio_cmd == BIO_WRITE) {
3132 			softc->flags |= SA_FLAG_TAPE_WRITTEN;
3133 			softc->filemarks = 0;
3134 		}
3135 		if (!(csio->ccb_h.ccb_pflags & SA_POSITION_UPDATED) &&
3136 		    (softc->blkno != (daddr_t) -1)) {
3137 			if ((softc->flags & SA_FLAG_FIXED) != 0) {
3138 				uint32_t l;
3139 				if (softc->blk_shift != 0) {
3140 					l = bp->bio_bcount >>
3141 						softc->blk_shift;
3142 				} else {
3143 					l = bp->bio_bcount /
3144 						softc->media_blksize;
3145 				}
3146 				softc->blkno += (daddr_t) l;
3147 			} else {
3148 				softc->blkno++;
3149 			}
3150 		}
3151 	}
3152 	/*
3153 	 * If we had an error (immediate or pending),
3154 	 * release the device queue now.
3155 	 */
3156 	if (error || (softc->flags & SA_FLAG_ERR_PENDING))
3157 		cam_release_devq(done_ccb->ccb_h.path, 0, 0, 0, 0);
3158 	if (error || bp->bio_resid) {
3159 		CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
3160 		    	  ("error %d resid %ld count %ld\n", error,
3161 			  bp->bio_resid, bp->bio_bcount));
3162 	}
3163 	biofinish(bp, softc->device_stats, 0);
3164 	xpt_release_ccb(done_ccb);
3165 }
3166 
3167 /*
3168  * Mount the tape (make sure it's ready for I/O).
3169  */
3170 static int
samount(struct cam_periph * periph,int oflags,struct cdev * dev)3171 samount(struct cam_periph *periph, int oflags, struct cdev *dev)
3172 {
3173 	struct	sa_softc *softc;
3174 	union	ccb *ccb;
3175 	int	error;
3176 
3177 	/*
3178 	 * oflags can be checked for 'kind' of open (read-only check) - later
3179 	 * dev can be checked for a control-mode or compression open - later
3180 	 */
3181 	UNUSED_PARAMETER(oflags);
3182 	UNUSED_PARAMETER(dev);
3183 
3184 	softc = (struct sa_softc *)periph->softc;
3185 
3186 	/*
3187 	 * This should determine if something has happened since the last
3188 	 * open/mount that would invalidate the mount. We do *not* want
3189 	 * to retry this command- we just want the status. But we only
3190 	 * do this if we're mounted already- if we're not mounted,
3191 	 * we don't care about the unit read state and can instead use
3192 	 * this opportunity to attempt to reserve the tape unit.
3193 	 */
3194 
3195 	if (softc->flags & SA_FLAG_TAPE_MOUNTED) {
3196 		ccb = cam_periph_getccb(periph, 1);
3197 		scsi_test_unit_ready(&ccb->csio, 0, NULL,
3198 		    MSG_SIMPLE_Q_TAG, SSD_FULL_SIZE,
3199 		    softc->timeout_info[SA_TIMEOUT_TUR]);
3200 		error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
3201 		    softc->device_stats);
3202 		if (error == ENXIO) {
3203 			softc->flags &= ~SA_FLAG_TAPE_MOUNTED;
3204 			scsi_test_unit_ready(&ccb->csio, 0, NULL,
3205 			    MSG_SIMPLE_Q_TAG, SSD_FULL_SIZE,
3206 			    softc->timeout_info[SA_TIMEOUT_TUR]);
3207 			error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
3208 			    softc->device_stats);
3209 		} else if (error) {
3210 			/*
3211 			 * We don't need to freeze the tape because we
3212 			 * will now attempt to rewind/load it.
3213 			 */
3214 			softc->flags &= ~SA_FLAG_TAPE_MOUNTED;
3215 			if (CAM_DEBUGGED(periph->path, CAM_DEBUG_INFO)) {
3216 				xpt_print(periph->path,
3217 				    "error %d on TUR in samount\n", error);
3218 			}
3219 		}
3220 	} else {
3221 		error = sareservereleaseunit(periph, TRUE);
3222 		if (error) {
3223 			return (error);
3224 		}
3225 		ccb = cam_periph_getccb(periph, 1);
3226 		scsi_test_unit_ready(&ccb->csio, 0, NULL,
3227 		    MSG_SIMPLE_Q_TAG, SSD_FULL_SIZE,
3228 		    softc->timeout_info[SA_TIMEOUT_TUR]);
3229 		error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
3230 		    softc->device_stats);
3231 	}
3232 
3233 	if ((softc->flags & SA_FLAG_TAPE_MOUNTED) == 0) {
3234 		struct scsi_read_block_limits_data *rblim = NULL;
3235 		int comp_enabled, comp_supported;
3236 		uint8_t write_protect, guessing = 0;
3237 
3238 		/*
3239 		 * Clear out old state.
3240 		 */
3241 		softc->flags &= ~(SA_FLAG_TAPE_WP|SA_FLAG_TAPE_WRITTEN|
3242 				  SA_FLAG_ERR_PENDING|SA_FLAG_COMPRESSION);
3243 		softc->filemarks = 0;
3244 
3245 		/*
3246 		 * *Very* first off, make sure we're loaded to BOT.
3247 		 */
3248 		scsi_load_unload(&ccb->csio, 2, NULL, MSG_SIMPLE_Q_TAG, FALSE,
3249 		    FALSE, FALSE, 1, SSD_FULL_SIZE,
3250 		    softc->timeout_info[SA_TIMEOUT_LOAD]);
3251 		error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
3252 		    softc->device_stats);
3253 
3254 		/*
3255 		 * In case this doesn't work, do a REWIND instead
3256 		 */
3257 		if (error) {
3258 			scsi_rewind(&ccb->csio, 2, NULL, MSG_SIMPLE_Q_TAG,
3259 			    FALSE, SSD_FULL_SIZE,
3260 			    softc->timeout_info[SA_TIMEOUT_REWIND]);
3261 			error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
3262 				softc->device_stats);
3263 		}
3264 		if (error) {
3265 			xpt_release_ccb(ccb);
3266 			goto exit;
3267 		}
3268 
3269 		/*
3270 		 * Do a dummy test read to force access to the
3271 		 * media so that the drive will really know what's
3272 		 * there. We actually don't really care what the
3273 		 * blocksize on tape is and don't expect to really
3274 		 * read a full record.
3275 		 */
3276 		rblim = (struct  scsi_read_block_limits_data *)
3277 		    malloc(8192, M_SCSISA, M_NOWAIT);
3278 		if (rblim == NULL) {
3279 			xpt_print(periph->path, "no memory for test read\n");
3280 			xpt_release_ccb(ccb);
3281 			error = ENOMEM;
3282 			goto exit;
3283 		}
3284 
3285 		if ((softc->quirks & SA_QUIRK_NODREAD) == 0) {
3286 			scsi_sa_read_write(&ccb->csio, 0, NULL,
3287 			    MSG_SIMPLE_Q_TAG, 1, FALSE, 0, 8192,
3288 			    (void *) rblim, 8192, SSD_FULL_SIZE,
3289 			    softc->timeout_info[SA_TIMEOUT_READ]);
3290 			(void) cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
3291 			    softc->device_stats);
3292 			scsi_rewind(&ccb->csio, 1, NULL, MSG_SIMPLE_Q_TAG,
3293 			    FALSE, SSD_FULL_SIZE,
3294 			    softc->timeout_info[SA_TIMEOUT_REWIND]);
3295 			error = cam_periph_runccb(ccb, saerror, CAM_RETRY_SELTO,
3296 			    SF_NO_PRINT | SF_RETRY_UA,
3297 			    softc->device_stats);
3298 			if (error) {
3299 				xpt_print(periph->path,
3300 				    "unable to rewind after test read\n");
3301 				xpt_release_ccb(ccb);
3302 				goto exit;
3303 			}
3304 		}
3305 
3306 		/*
3307 		 * Next off, determine block limits.
3308 		 */
3309 		scsi_read_block_limits(&ccb->csio, 5, NULL, MSG_SIMPLE_Q_TAG,
3310 		    rblim, SSD_FULL_SIZE,
3311 		    softc->timeout_info[SA_TIMEOUT_READ_BLOCK_LIMITS]);
3312 
3313 		error = cam_periph_runccb(ccb, saerror, CAM_RETRY_SELTO,
3314 		    SF_NO_PRINT | SF_RETRY_UA, softc->device_stats);
3315 
3316 		xpt_release_ccb(ccb);
3317 
3318 		if (error != 0) {
3319 			/*
3320 			 * If it's less than SCSI-2, READ BLOCK LIMITS is not
3321 			 * a MANDATORY command. Anyway- it doesn't matter-
3322 			 * we can proceed anyway.
3323 			 */
3324 			softc->blk_gran = 0;
3325 			softc->max_blk = ~0;
3326 			softc->min_blk = 0;
3327 		} else {
3328 			if (softc->scsi_rev >= SCSI_REV_SPC) {
3329 				softc->blk_gran = RBL_GRAN(rblim);
3330 			} else {
3331 				softc->blk_gran = 0;
3332 			}
3333 			/*
3334 			 * We take max_blk == min_blk to mean a default to
3335 			 * fixed mode- but note that whatever we get out of
3336 			 * sagetparams below will actually determine whether
3337 			 * we are actually *in* fixed mode.
3338 			 */
3339 			softc->max_blk = scsi_3btoul(rblim->maximum);
3340 			softc->min_blk = scsi_2btoul(rblim->minimum);
3341 		}
3342 		/*
3343 		 * Next, perform a mode sense to determine
3344 		 * current density, blocksize, compression etc.
3345 		 */
3346 		error = sagetparams(periph, SA_PARAM_ALL,
3347 				    &softc->media_blksize,
3348 				    &softc->media_density,
3349 				    &softc->media_numblks,
3350 				    &softc->buffer_mode, &write_protect,
3351 				    &softc->speed, &comp_supported,
3352 				    &comp_enabled, &softc->comp_algorithm,
3353 				    NULL, NULL, 0, 0);
3354 
3355 		if (error != 0) {
3356 			/*
3357 			 * We could work a little harder here. We could
3358 			 * adjust our attempts to get information. It
3359 			 * might be an ancient tape drive. If someone
3360 			 * nudges us, we'll do that.
3361 			 */
3362 			goto exit;
3363 		}
3364 
3365 		/*
3366 		 * If no quirk has determined that this is a device that is
3367 		 * preferred to be in fixed or variable mode, now is the time
3368 		 * to find out.
3369 	 	 */
3370 		if ((softc->quirks & (SA_QUIRK_FIXED|SA_QUIRK_VARIABLE)) == 0) {
3371 			guessing = 1;
3372 			/*
3373 			 * This could be expensive to find out. Luckily we
3374 			 * only need to do this once. If we start out in
3375 			 * 'default' mode, try and set ourselves to one
3376 			 * of the densities that would determine a wad
3377 			 * of other stuff. Go from highest to lowest.
3378 			 */
3379 			if (softc->media_density == SCSI_DEFAULT_DENSITY) {
3380 				int i;
3381 				static uint8_t ctry[] = {
3382 					SCSI_DENSITY_HALFINCH_PE,
3383 					SCSI_DENSITY_HALFINCH_6250C,
3384 					SCSI_DENSITY_HALFINCH_6250,
3385 					SCSI_DENSITY_HALFINCH_1600,
3386 					SCSI_DENSITY_HALFINCH_800,
3387 					SCSI_DENSITY_QIC_4GB,
3388 					SCSI_DENSITY_QIC_2GB,
3389 					SCSI_DENSITY_QIC_525_320,
3390 					SCSI_DENSITY_QIC_150,
3391 					SCSI_DENSITY_QIC_120,
3392 					SCSI_DENSITY_QIC_24,
3393 					SCSI_DENSITY_QIC_11_9TRK,
3394 					SCSI_DENSITY_QIC_11_4TRK,
3395 					SCSI_DENSITY_QIC_1320,
3396 					SCSI_DENSITY_QIC_3080,
3397 					0
3398 				};
3399 				for (i = 0; ctry[i]; i++) {
3400 					error = sasetparams(periph,
3401 					    SA_PARAM_DENSITY, 0, ctry[i],
3402 					    0, SF_NO_PRINT);
3403 					if (error == 0) {
3404 						softc->media_density = ctry[i];
3405 						break;
3406 					}
3407 				}
3408 			}
3409 			switch (softc->media_density) {
3410 			case SCSI_DENSITY_QIC_11_4TRK:
3411 			case SCSI_DENSITY_QIC_11_9TRK:
3412 			case SCSI_DENSITY_QIC_24:
3413 			case SCSI_DENSITY_QIC_120:
3414 			case SCSI_DENSITY_QIC_150:
3415 			case SCSI_DENSITY_QIC_525_320:
3416 			case SCSI_DENSITY_QIC_1320:
3417 			case SCSI_DENSITY_QIC_3080:
3418 				softc->quirks &= ~SA_QUIRK_2FM;
3419 				softc->quirks |= SA_QUIRK_FIXED|SA_QUIRK_1FM;
3420 				softc->last_media_blksize = 512;
3421 				break;
3422 			case SCSI_DENSITY_QIC_4GB:
3423 			case SCSI_DENSITY_QIC_2GB:
3424 				softc->quirks &= ~SA_QUIRK_2FM;
3425 				softc->quirks |= SA_QUIRK_FIXED|SA_QUIRK_1FM;
3426 				softc->last_media_blksize = 1024;
3427 				break;
3428 			default:
3429 				softc->last_media_blksize =
3430 				    softc->media_blksize;
3431 				softc->quirks |= SA_QUIRK_VARIABLE;
3432 				break;
3433 			}
3434 		}
3435 
3436 		/*
3437 		 * If no quirk has determined that this is a device that needs
3438 		 * to have 2 Filemarks at EOD, now is the time to find out.
3439 		 */
3440 
3441 		if ((softc->quirks & SA_QUIRK_2FM) == 0) {
3442 			switch (softc->media_density) {
3443 			case SCSI_DENSITY_HALFINCH_800:
3444 			case SCSI_DENSITY_HALFINCH_1600:
3445 			case SCSI_DENSITY_HALFINCH_6250:
3446 			case SCSI_DENSITY_HALFINCH_6250C:
3447 			case SCSI_DENSITY_HALFINCH_PE:
3448 				softc->quirks &= ~SA_QUIRK_1FM;
3449 				softc->quirks |= SA_QUIRK_2FM;
3450 				break;
3451 			default:
3452 				break;
3453 			}
3454 		}
3455 
3456 		/*
3457 		 * Now validate that some info we got makes sense.
3458 		 */
3459 		if ((softc->max_blk < softc->media_blksize) ||
3460 		    (softc->min_blk > softc->media_blksize &&
3461 		    softc->media_blksize)) {
3462 			xpt_print(periph->path,
3463 			    "BLOCK LIMITS (%d..%d) could not match current "
3464 			    "block settings (%d)- adjusting\n", softc->min_blk,
3465 			    softc->max_blk, softc->media_blksize);
3466 			softc->max_blk = softc->min_blk =
3467 			    softc->media_blksize;
3468 		}
3469 
3470 		/*
3471 		 * Now put ourselves into the right frame of mind based
3472 		 * upon quirks...
3473 		 */
3474 tryagain:
3475 		/*
3476 		 * If we want to be in FIXED mode and our current blocksize
3477 		 * is not equal to our last blocksize (if nonzero), try and
3478 		 * set ourselves to this last blocksize (as the 'preferred'
3479 		 * block size).  The initial quirkmatch at registry sets the
3480 		 * initial 'last' blocksize. If, for whatever reason, this
3481 		 * 'last' blocksize is zero, set the blocksize to 512,
3482 		 * or min_blk if that's larger.
3483 		 */
3484 		if ((softc->quirks & SA_QUIRK_FIXED) &&
3485 		    (softc->quirks & SA_QUIRK_NO_MODESEL) == 0 &&
3486 		    (softc->media_blksize != softc->last_media_blksize)) {
3487 			softc->media_blksize = softc->last_media_blksize;
3488 			if (softc->media_blksize == 0) {
3489 				softc->media_blksize = 512;
3490 				if (softc->media_blksize < softc->min_blk) {
3491 					softc->media_blksize = softc->min_blk;
3492 				}
3493 			}
3494 			error = sasetparams(periph, SA_PARAM_BLOCKSIZE,
3495 			    softc->media_blksize, 0, 0, SF_NO_PRINT);
3496 			if (error) {
3497 				xpt_print(periph->path,
3498 				    "unable to set fixed blocksize to %d\n",
3499 				    softc->media_blksize);
3500 				goto exit;
3501 			}
3502 		}
3503 
3504 		if ((softc->quirks & SA_QUIRK_VARIABLE) &&
3505 		    (softc->media_blksize != 0)) {
3506 			softc->last_media_blksize = softc->media_blksize;
3507 			softc->media_blksize = 0;
3508 			error = sasetparams(periph, SA_PARAM_BLOCKSIZE,
3509 			    0, 0, 0, SF_NO_PRINT);
3510 			if (error) {
3511 				/*
3512 				 * If this fails and we were guessing, just
3513 				 * assume that we got it wrong and go try
3514 				 * fixed block mode. Don't even check against
3515 				 * density code at this point.
3516 				 */
3517 				if (guessing) {
3518 					softc->quirks &= ~SA_QUIRK_VARIABLE;
3519 					softc->quirks |= SA_QUIRK_FIXED;
3520 					if (softc->last_media_blksize == 0)
3521 						softc->last_media_blksize = 512;
3522 					goto tryagain;
3523 				}
3524 				xpt_print(periph->path,
3525 				    "unable to set variable blocksize\n");
3526 				goto exit;
3527 			}
3528 		}
3529 
3530 		/*
3531 		 * Now that we have the current block size,
3532 		 * set up some parameters for sastart's usage.
3533 		 */
3534 		if (softc->media_blksize) {
3535 			softc->flags |= SA_FLAG_FIXED;
3536 			if (powerof2(softc->media_blksize)) {
3537 				softc->blk_shift =
3538 				    ffs(softc->media_blksize) - 1;
3539 				softc->blk_mask = softc->media_blksize - 1;
3540 			} else {
3541 				softc->blk_mask = ~0;
3542 				softc->blk_shift = 0;
3543 			}
3544 		} else {
3545 			/*
3546 			 * The SCSI-3 spec allows 0 to mean "unspecified".
3547 			 * The SCSI-1 spec allows 0 to mean 'infinite'.
3548 			 *
3549 			 * Either works here.
3550 			 */
3551 			if (softc->max_blk == 0) {
3552 				softc->max_blk = ~0;
3553 			}
3554 			softc->blk_shift = 0;
3555 			if (softc->blk_gran != 0) {
3556 				softc->blk_mask = softc->blk_gran - 1;
3557 			} else {
3558 				softc->blk_mask = 0;
3559 			}
3560 		}
3561 
3562 		if (write_protect)
3563 			softc->flags |= SA_FLAG_TAPE_WP;
3564 
3565 		if (comp_supported) {
3566 			if (softc->saved_comp_algorithm == 0)
3567 				softc->saved_comp_algorithm =
3568 				    softc->comp_algorithm;
3569 			softc->flags |= SA_FLAG_COMP_SUPP;
3570 			if (comp_enabled)
3571 				softc->flags |= SA_FLAG_COMP_ENABLED;
3572 		} else
3573 			softc->flags |= SA_FLAG_COMP_UNSUPP;
3574 
3575 		if ((softc->buffer_mode == SMH_SA_BUF_MODE_NOBUF) &&
3576 		    (softc->quirks & SA_QUIRK_NO_MODESEL) == 0) {
3577 			error = sasetparams(periph, SA_PARAM_BUFF_MODE, 0,
3578 			    0, 0, SF_NO_PRINT);
3579 			if (error == 0) {
3580 				softc->buffer_mode = SMH_SA_BUF_MODE_SIBUF;
3581 			} else {
3582 				xpt_print(periph->path,
3583 				    "unable to set buffered mode\n");
3584 			}
3585 			error = 0;	/* not an error */
3586 		}
3587 
3588 		if (error == 0) {
3589 			softc->flags |= SA_FLAG_TAPE_MOUNTED;
3590 		}
3591 exit:
3592 		if (rblim != NULL)
3593 			free(rblim, M_SCSISA);
3594 
3595 		if (error != 0) {
3596 			softc->dsreg = MTIO_DSREG_NIL;
3597 		} else {
3598 			softc->fileno = softc->blkno = 0;
3599 			softc->rep_fileno = softc->rep_blkno = -1;
3600 			softc->partition = 0;
3601 			softc->dsreg = MTIO_DSREG_REST;
3602 		}
3603 #ifdef	SA_1FM_AT_EOD
3604 		if ((softc->quirks & SA_QUIRK_2FM) == 0)
3605 			softc->quirks |= SA_QUIRK_1FM;
3606 #else
3607 		if ((softc->quirks & SA_QUIRK_1FM) == 0)
3608 			softc->quirks |= SA_QUIRK_2FM;
3609 #endif
3610 	} else
3611 		xpt_release_ccb(ccb);
3612 
3613 	/*
3614 	 * If we return an error, we're not mounted any more,
3615 	 * so release any device reservation.
3616 	 */
3617 	if (error != 0) {
3618 		(void) sareservereleaseunit(periph, FALSE);
3619 	} else {
3620 		/*
3621 		 * Clear I/O residual.
3622 		 */
3623 		softc->last_io_resid = 0;
3624 		softc->last_ctl_resid = 0;
3625 	}
3626 	return (error);
3627 }
3628 
3629 /*
3630  * How many filemarks do we need to write if we were to terminate the
3631  * tape session right now? Note that this can be a negative number
3632  */
3633 
3634 static int
samarkswanted(struct cam_periph * periph)3635 samarkswanted(struct cam_periph *periph)
3636 {
3637 	int	markswanted;
3638 	struct	sa_softc *softc;
3639 
3640 	softc = (struct sa_softc *)periph->softc;
3641 	markswanted = 0;
3642 	if ((softc->flags & SA_FLAG_TAPE_WRITTEN) != 0) {
3643 		markswanted++;
3644 		if (softc->quirks & SA_QUIRK_2FM)
3645 			markswanted++;
3646 	}
3647 	markswanted -= softc->filemarks;
3648 	return (markswanted);
3649 }
3650 
3651 static int
sacheckeod(struct cam_periph * periph)3652 sacheckeod(struct cam_periph *periph)
3653 {
3654 	int	error;
3655 	int	markswanted;
3656 
3657 	markswanted = samarkswanted(periph);
3658 
3659 	if (markswanted > 0) {
3660 		error = sawritefilemarks(periph, markswanted, FALSE, FALSE);
3661 	} else {
3662 		error = 0;
3663 	}
3664 	return (error);
3665 }
3666 
3667 static int
saerror(union ccb * ccb,uint32_t cflgs,uint32_t sflgs)3668 saerror(union ccb *ccb, uint32_t cflgs, uint32_t sflgs)
3669 {
3670 	static const char *toobig =
3671 	    "%d-byte tape record bigger than supplied buffer\n";
3672 	struct	cam_periph *periph;
3673 	struct	sa_softc *softc;
3674 	struct	ccb_scsiio *csio;
3675 	struct	scsi_sense_data *sense;
3676 	uint64_t resid = 0;
3677 	int64_t	info = 0;
3678 	cam_status status;
3679 	int error_code, sense_key, asc, ascq, error, aqvalid, stream_valid;
3680 	int sense_len;
3681 	uint8_t stream_bits;
3682 
3683 	periph = xpt_path_periph(ccb->ccb_h.path);
3684 	softc = (struct sa_softc *)periph->softc;
3685 	csio = &ccb->csio;
3686 	sense = &csio->sense_data;
3687 	sense_len = csio->sense_len - csio->sense_resid;
3688 	scsi_extract_sense_len(sense, sense_len, &error_code, &sense_key,
3689 	    &asc, &ascq, /*show_errors*/ 1);
3690 	if (asc != -1 && ascq != -1)
3691 		aqvalid = 1;
3692 	else
3693 		aqvalid = 0;
3694 	if (scsi_get_stream_info(sense, sense_len, NULL, &stream_bits) == 0)
3695 		stream_valid = 1;
3696 	else
3697 		stream_valid = 0;
3698 	error = 0;
3699 
3700 	status = csio->ccb_h.status & CAM_STATUS_MASK;
3701 
3702 	/*
3703 	 * Calculate/latch up, any residuals... We do this in a funny 2-step
3704 	 * so we can print stuff here if we have CAM_DEBUG enabled for this
3705 	 * unit.
3706 	 */
3707 	if (status == CAM_SCSI_STATUS_ERROR) {
3708 		if (scsi_get_sense_info(sense, sense_len, SSD_DESC_INFO, &resid,
3709 					&info) == 0) {
3710 			if ((softc->flags & SA_FLAG_FIXED) != 0)
3711 				resid *= softc->media_blksize;
3712 		} else {
3713 			resid = csio->dxfer_len;
3714 			info = resid;
3715 			if ((softc->flags & SA_FLAG_FIXED) != 0) {
3716 				if (softc->media_blksize)
3717 					info /= softc->media_blksize;
3718 			}
3719 		}
3720 		if (csio->cdb_io.cdb_bytes[0] == SA_READ ||
3721 		    csio->cdb_io.cdb_bytes[0] == SA_WRITE) {
3722 			bcopy((caddr_t) sense, (caddr_t) &softc->last_io_sense,
3723 			    sizeof (struct scsi_sense_data));
3724 			bcopy(csio->cdb_io.cdb_bytes, softc->last_io_cdb,
3725 			    (int) csio->cdb_len);
3726 			softc->last_io_resid = resid;
3727 			softc->last_resid_was_io = 1;
3728 		} else {
3729 			bcopy((caddr_t) sense, (caddr_t) &softc->last_ctl_sense,
3730 			    sizeof (struct scsi_sense_data));
3731 			bcopy(csio->cdb_io.cdb_bytes, softc->last_ctl_cdb,
3732 			    (int) csio->cdb_len);
3733 			softc->last_ctl_resid = resid;
3734 			softc->last_resid_was_io = 0;
3735 		}
3736 		CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("CDB[0]=0x%x Key 0x%x "
3737 		    "ASC/ASCQ 0x%x/0x%x CAM STATUS 0x%x flags 0x%x resid %jd "
3738 		    "dxfer_len %d\n", csio->cdb_io.cdb_bytes[0] & 0xff,
3739 		    sense_key, asc, ascq, status,
3740 		    (stream_valid) ? stream_bits : 0, (intmax_t)resid,
3741 		    csio->dxfer_len));
3742 	} else {
3743 		CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
3744 		    ("Cam Status 0x%x\n", status));
3745 	}
3746 
3747 	switch (status) {
3748 	case CAM_REQ_CMP:
3749 		return (0);
3750 	case CAM_SCSI_STATUS_ERROR:
3751 		/*
3752 		 * If a read/write command, we handle it here.
3753 		 */
3754 		if (csio->cdb_io.cdb_bytes[0] == SA_READ ||
3755 		    csio->cdb_io.cdb_bytes[0] == SA_WRITE) {
3756 			break;
3757 		}
3758 		/*
3759 		 * If this was just EOM/EOP, Filemark, Setmark, ILI or
3760 		 * PEW detected on a non read/write command, we assume
3761 		 * it's not an error and propagate the residual and return.
3762 		 */
3763 		if ((aqvalid && asc == 0 && ((ascq > 0 && ascq <= 5)
3764 		  || (ascq == 0x07)))
3765 		 || (aqvalid == 0 && sense_key == SSD_KEY_NO_SENSE)) {
3766 			csio->resid = resid;
3767 			QFRLS(ccb);
3768 			return (0);
3769 		}
3770 		/*
3771 		 * Otherwise, we let the common code handle this.
3772 		 */
3773 		return (cam_periph_error(ccb, cflgs, sflgs));
3774 
3775 	/*
3776 	 * XXX: To Be Fixed
3777 	 * We cannot depend upon CAM honoring retry counts for these.
3778 	 */
3779 	case CAM_SCSI_BUS_RESET:
3780 	case CAM_BDR_SENT:
3781 		if (ccb->ccb_h.retry_count <= 0) {
3782 			return (EIO);
3783 		}
3784 		/* FALLTHROUGH */
3785 	default:
3786 		return (cam_periph_error(ccb, cflgs, sflgs));
3787 	}
3788 
3789 	/*
3790 	 * Handle filemark, end of tape, mismatched record sizes....
3791 	 * From this point out, we're only handling read/write cases.
3792 	 * Handle writes && reads differently.
3793 	 */
3794 
3795 	if (csio->cdb_io.cdb_bytes[0] == SA_WRITE) {
3796 		if (sense_key == SSD_KEY_VOLUME_OVERFLOW) {
3797 			csio->resid = resid;
3798 			error = ENOSPC;
3799 		} else if ((stream_valid != 0) && (stream_bits & SSD_EOM)) {
3800 			softc->flags |= SA_FLAG_EOM_PENDING;
3801 			/*
3802 			 * Grotesque as it seems, the few times
3803 			 * I've actually seen a non-zero resid,
3804 			 * the tape drive actually lied and had
3805 			 * written all the data!.
3806 			 */
3807 			csio->resid = 0;
3808 		}
3809 	} else {
3810 		csio->resid = resid;
3811 		if (sense_key == SSD_KEY_BLANK_CHECK) {
3812 			if (softc->quirks & SA_QUIRK_1FM) {
3813 				error = 0;
3814 				softc->flags |= SA_FLAG_EOM_PENDING;
3815 			} else {
3816 				error = EIO;
3817 			}
3818 		} else if ((stream_valid != 0) && (stream_bits & SSD_FILEMARK)){
3819 			if (softc->flags & SA_FLAG_FIXED) {
3820 				error = -1;
3821 				softc->flags |= SA_FLAG_EOF_PENDING;
3822 			}
3823 			/*
3824 			 * Unconditionally, if we detected a filemark on a read,
3825 			 * mark that we've run moved a file ahead.
3826 			 */
3827 			if (softc->fileno != (daddr_t) -1) {
3828 				softc->fileno++;
3829 				softc->blkno = 0;
3830 				csio->ccb_h.ccb_pflags |= SA_POSITION_UPDATED;
3831 			}
3832 		}
3833 	}
3834 
3835 	/*
3836 	 * Incorrect Length usually applies to read, but can apply to writes.
3837 	 */
3838 	if (error == 0 && (stream_valid != 0) && (stream_bits & SSD_ILI)) {
3839 		if (info < 0) {
3840 			xpt_print(csio->ccb_h.path, toobig,
3841 			    csio->dxfer_len - info);
3842 			csio->resid = csio->dxfer_len;
3843 			error = EIO;
3844 		} else {
3845 			csio->resid = resid;
3846 			if (softc->flags & SA_FLAG_FIXED) {
3847 				softc->flags |= SA_FLAG_EIO_PENDING;
3848 			}
3849 			/*
3850 			 * Bump the block number if we hadn't seen a filemark.
3851 			 * Do this independent of errors (we've moved anyway).
3852 			 */
3853 			if ((stream_valid == 0) ||
3854 			    (stream_bits & SSD_FILEMARK) == 0) {
3855 				if (softc->blkno != (daddr_t) -1) {
3856 					softc->blkno++;
3857 					csio->ccb_h.ccb_pflags |=
3858 					   SA_POSITION_UPDATED;
3859 				}
3860 			}
3861 		}
3862 	}
3863 
3864 	if (error <= 0) {
3865 		/*
3866 		 * Unfreeze the queue if frozen as we're not returning anything
3867 		 * to our waiters that would indicate an I/O error has occurred
3868 		 * (yet).
3869 		 */
3870 		QFRLS(ccb);
3871 		error = 0;
3872 	}
3873 	return (error);
3874 }
3875 
3876 static int
sagetparams(struct cam_periph * periph,sa_params params_to_get,uint32_t * blocksize,uint8_t * density,uint32_t * numblocks,int * buff_mode,uint8_t * write_protect,uint8_t * speed,int * comp_supported,int * comp_enabled,uint32_t * comp_algorithm,sa_comp_t * tcs,struct scsi_control_data_prot_subpage * prot_page,int dp_size,int prot_changeable)3877 sagetparams(struct cam_periph *periph, sa_params params_to_get,
3878 	    uint32_t *blocksize, uint8_t *density, uint32_t *numblocks,
3879 	    int *buff_mode, uint8_t *write_protect, uint8_t *speed,
3880 	    int *comp_supported, int *comp_enabled, uint32_t *comp_algorithm,
3881 	    sa_comp_t *tcs, struct scsi_control_data_prot_subpage *prot_page,
3882 	    int dp_size, int prot_changeable)
3883 {
3884 	union ccb *ccb;
3885 	void *mode_buffer;
3886 	struct scsi_mode_header_6 *mode_hdr;
3887 	struct scsi_mode_blk_desc *mode_blk;
3888 	int mode_buffer_len;
3889 	struct sa_softc *softc;
3890 	uint8_t cpage;
3891 	int error;
3892 	cam_status status;
3893 
3894 	softc = (struct sa_softc *)periph->softc;
3895 	ccb = cam_periph_getccb(periph, 1);
3896 	if (softc->quirks & SA_QUIRK_NO_CPAGE)
3897 		cpage = SA_DEVICE_CONFIGURATION_PAGE;
3898 	else
3899 		cpage = SA_DATA_COMPRESSION_PAGE;
3900 
3901 retry:
3902 	mode_buffer_len = sizeof(*mode_hdr) + sizeof(*mode_blk);
3903 
3904 	if (params_to_get & SA_PARAM_COMPRESSION) {
3905 		if (softc->quirks & SA_QUIRK_NOCOMP) {
3906 			*comp_supported = FALSE;
3907 			params_to_get &= ~SA_PARAM_COMPRESSION;
3908 		} else
3909 			mode_buffer_len += sizeof (sa_comp_t);
3910 	}
3911 
3912 	/* XXX Fix M_NOWAIT */
3913 	mode_buffer = malloc(mode_buffer_len, M_SCSISA, M_NOWAIT | M_ZERO);
3914 	if (mode_buffer == NULL) {
3915 		xpt_release_ccb(ccb);
3916 		return (ENOMEM);
3917 	}
3918 	mode_hdr = (struct scsi_mode_header_6 *)mode_buffer;
3919 	mode_blk = (struct scsi_mode_blk_desc *)&mode_hdr[1];
3920 
3921 	/* it is safe to retry this */
3922 	scsi_mode_sense(&ccb->csio, 5, NULL, MSG_SIMPLE_Q_TAG, FALSE,
3923 	    SMS_PAGE_CTRL_CURRENT, (params_to_get & SA_PARAM_COMPRESSION) ?
3924 	    cpage : SMS_VENDOR_SPECIFIC_PAGE, mode_buffer, mode_buffer_len,
3925 	    SSD_FULL_SIZE, softc->timeout_info[SA_TIMEOUT_MODE_SENSE]);
3926 
3927 	error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
3928 	    softc->device_stats);
3929 
3930 	status = ccb->ccb_h.status & CAM_STATUS_MASK;
3931 
3932 	if (error == EINVAL && (params_to_get & SA_PARAM_COMPRESSION) != 0) {
3933 		/*
3934 		 * Hmm. Let's see if we can try another page...
3935 		 * If we've already done that, give up on compression
3936 		 * for this device and remember this for the future
3937 		 * and attempt the request without asking for compression
3938 		 * info.
3939 		 */
3940 		if (cpage == SA_DATA_COMPRESSION_PAGE) {
3941 			cpage = SA_DEVICE_CONFIGURATION_PAGE;
3942 			goto retry;
3943 		}
3944 		softc->quirks |= SA_QUIRK_NOCOMP;
3945 		free(mode_buffer, M_SCSISA);
3946 		goto retry;
3947 	} else if (status == CAM_SCSI_STATUS_ERROR) {
3948 		/* Tell the user about the fatal error. */
3949 		scsi_sense_print(&ccb->csio);
3950 		goto sagetparamsexit;
3951 	}
3952 
3953 	/*
3954 	 * If the user only wants the compression information, and
3955 	 * the device doesn't send back the block descriptor, it's
3956 	 * no big deal.  If the user wants more than just
3957 	 * compression, though, and the device doesn't pass back the
3958 	 * block descriptor, we need to send another mode sense to
3959 	 * get the block descriptor.
3960 	 */
3961 	if ((mode_hdr->blk_desc_len == 0) &&
3962 	    (params_to_get & SA_PARAM_COMPRESSION) &&
3963 	    (params_to_get & ~(SA_PARAM_COMPRESSION))) {
3964 		/*
3965 		 * Decrease the mode buffer length by the size of
3966 		 * the compression page, to make sure the data
3967 		 * there doesn't get overwritten.
3968 		 */
3969 		mode_buffer_len -= sizeof (sa_comp_t);
3970 
3971 		/*
3972 		 * Now move the compression page that we presumably
3973 		 * got back down the memory chunk a little bit so
3974 		 * it doesn't get spammed.
3975 		 */
3976 		bcopy(&mode_hdr[0], &mode_hdr[1], sizeof (sa_comp_t));
3977 		bzero(&mode_hdr[0], sizeof (mode_hdr[0]));
3978 
3979 		/*
3980 		 * Now, we issue another mode sense and just ask
3981 		 * for the block descriptor, etc.
3982 		 */
3983 
3984 		scsi_mode_sense(&ccb->csio, 2, NULL, MSG_SIMPLE_Q_TAG, FALSE,
3985 		    SMS_PAGE_CTRL_CURRENT, SMS_VENDOR_SPECIFIC_PAGE,
3986 		    mode_buffer, mode_buffer_len, SSD_FULL_SIZE,
3987 		    softc->timeout_info[SA_TIMEOUT_MODE_SENSE]);
3988 
3989 		error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
3990 		    softc->device_stats);
3991 
3992 		if (error != 0)
3993 			goto sagetparamsexit;
3994 	}
3995 
3996 	if (params_to_get & SA_PARAM_BLOCKSIZE)
3997 		*blocksize = scsi_3btoul(mode_blk->blklen);
3998 
3999 	if (params_to_get & SA_PARAM_NUMBLOCKS)
4000 		*numblocks = scsi_3btoul(mode_blk->nblocks);
4001 
4002 	if (params_to_get & SA_PARAM_BUFF_MODE)
4003 		*buff_mode = mode_hdr->dev_spec & SMH_SA_BUF_MODE_MASK;
4004 
4005 	if (params_to_get & SA_PARAM_DENSITY)
4006 		*density = mode_blk->density;
4007 
4008 	if (params_to_get & SA_PARAM_WP)
4009 		*write_protect = (mode_hdr->dev_spec & SMH_SA_WP)? TRUE : FALSE;
4010 
4011 	if (params_to_get & SA_PARAM_SPEED)
4012 		*speed = mode_hdr->dev_spec & SMH_SA_SPEED_MASK;
4013 
4014 	if (params_to_get & SA_PARAM_COMPRESSION) {
4015 		sa_comp_t *ntcs = (sa_comp_t *) &mode_blk[1];
4016 		if (cpage == SA_DATA_COMPRESSION_PAGE) {
4017 			struct scsi_data_compression_page *cp = &ntcs->dcomp;
4018 			*comp_supported =
4019 			    (cp->dce_and_dcc & SA_DCP_DCC)? TRUE : FALSE;
4020 			*comp_enabled =
4021 			    (cp->dce_and_dcc & SA_DCP_DCE)? TRUE : FALSE;
4022 			*comp_algorithm = scsi_4btoul(cp->comp_algorithm);
4023 		} else {
4024 			struct scsi_dev_conf_page *cp = &ntcs->dconf;
4025 			/*
4026 			 * We don't really know whether this device supports
4027 			 * Data Compression if the algorithm field is
4028 			 * zero. Just say we do.
4029 			 */
4030 			*comp_supported = TRUE;
4031 			*comp_enabled =
4032 			    (cp->sel_comp_alg != SA_COMP_NONE)? TRUE : FALSE;
4033 			*comp_algorithm = cp->sel_comp_alg;
4034 		}
4035 		if (tcs != NULL)
4036 			bcopy(ntcs, tcs, sizeof (sa_comp_t));
4037 	}
4038 
4039 	if ((params_to_get & SA_PARAM_DENSITY_EXT)
4040 	 && (softc->scsi_rev >= SCSI_REV_SPC)) {
4041 		int i;
4042 
4043 		for (i = 0; i < SA_DENSITY_TYPES; i++) {
4044 			scsi_report_density_support(&ccb->csio,
4045 			    /*retries*/ 1,
4046 			    /*cbfcnp*/ NULL,
4047 			    /*tag_action*/ MSG_SIMPLE_Q_TAG,
4048 			    /*media*/ softc->density_type_bits[i] & SRDS_MEDIA,
4049 			    /*medium_type*/ softc->density_type_bits[i] &
4050 					    SRDS_MEDIUM_TYPE,
4051 			    /*data_ptr*/ softc->density_info[i],
4052 			    /*length*/ sizeof(softc->density_info[i]),
4053 			    /*sense_len*/ SSD_FULL_SIZE,
4054 			    /*timeout*/
4055 			        softc->timeout_info[SA_TIMEOUT_REP_DENSITY]);
4056 			error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
4057 			    softc->device_stats);
4058 			status = ccb->ccb_h.status & CAM_STATUS_MASK;
4059 
4060 			/*
4061 			 * Some tape drives won't support this command at
4062 			 * all, but hopefully we'll minimize that with the
4063 			 * check for SPC or greater support above.  If they
4064 			 * don't support the default report (neither the
4065 			 * MEDIA or MEDIUM_TYPE bits set), then there is
4066 			 * really no point in continuing on to look for
4067 			 * other reports.
4068 			 */
4069 			if ((error != 0)
4070 			 || (status != CAM_REQ_CMP)) {
4071 				error = 0;
4072 				softc->density_info_valid[i] = 0;
4073 				if (softc->density_type_bits[i] == 0)
4074 					break;
4075 				else
4076 					continue;
4077 			}
4078 			softc->density_info_valid[i] = ccb->csio.dxfer_len -
4079 			    ccb->csio.resid;
4080 		}
4081 	}
4082 
4083 	/*
4084 	 * Get logical block protection parameters if the drive supports it.
4085 	 */
4086 	if ((params_to_get & SA_PARAM_LBP)
4087 	 && (softc->flags & SA_FLAG_PROTECT_SUPP)) {
4088 		struct scsi_mode_header_10 *mode10_hdr;
4089 		struct scsi_control_data_prot_subpage *dp_page;
4090 		struct scsi_mode_sense_10 *cdb;
4091 		struct sa_prot_state *prot;
4092 		int dp_len, returned_len;
4093 
4094 		if (dp_size == 0)
4095 			dp_size = sizeof(*dp_page);
4096 
4097 		dp_len = sizeof(*mode10_hdr) + dp_size;
4098 		mode10_hdr = malloc(dp_len, M_SCSISA, M_NOWAIT | M_ZERO);
4099 		if (mode10_hdr == NULL) {
4100 			error = ENOMEM;
4101 			goto sagetparamsexit;
4102 		}
4103 
4104 		scsi_mode_sense_len(&ccb->csio,
4105 				    /*retries*/ 5,
4106 				    /*cbfcnp*/ NULL,
4107 				    /*tag_action*/ MSG_SIMPLE_Q_TAG,
4108 				    /*dbd*/ TRUE,
4109 				    /*page_code*/ (prot_changeable == 0) ?
4110 						  SMS_PAGE_CTRL_CURRENT :
4111 						  SMS_PAGE_CTRL_CHANGEABLE,
4112 				    /*page*/ SMS_CONTROL_MODE_PAGE,
4113 				    /*param_buf*/ (uint8_t *)mode10_hdr,
4114 				    /*param_len*/ dp_len,
4115 				    /*minimum_cmd_size*/ 10,
4116 				    /*sense_len*/ SSD_FULL_SIZE,
4117 				    /*timeout*/
4118 				    softc->timeout_info[SA_TIMEOUT_MODE_SENSE]);
4119 		/*
4120 		 * XXX KDM we need to be able to set the subpage in the
4121 		 * fill function.
4122 		 */
4123 		cdb = (struct scsi_mode_sense_10 *)ccb->csio.cdb_io.cdb_bytes;
4124 		cdb->subpage = SA_CTRL_DP_SUBPAGE_CODE;
4125 
4126 		error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
4127 		    softc->device_stats);
4128 		if (error != 0) {
4129 			free(mode10_hdr, M_SCSISA);
4130 			goto sagetparamsexit;
4131 		}
4132 
4133 		status = ccb->ccb_h.status & CAM_STATUS_MASK;
4134 		if (status != CAM_REQ_CMP) {
4135 			error = EINVAL;
4136 			free(mode10_hdr, M_SCSISA);
4137 			goto sagetparamsexit;
4138 		}
4139 
4140 		/*
4141 		 * The returned data length at least has to be long enough
4142 		 * for us to look at length in the mode page header.
4143 		 */
4144 		returned_len = ccb->csio.dxfer_len - ccb->csio.resid;
4145 		if (returned_len < sizeof(mode10_hdr->data_length)) {
4146 			error = EINVAL;
4147 			free(mode10_hdr, M_SCSISA);
4148 			goto sagetparamsexit;
4149 		}
4150 
4151 		returned_len = min(returned_len,
4152 		    sizeof(mode10_hdr->data_length) +
4153 		    scsi_2btoul(mode10_hdr->data_length));
4154 
4155 		dp_page = (struct scsi_control_data_prot_subpage *)
4156 		    &mode10_hdr[1];
4157 
4158 		/*
4159 		 * We also have to have enough data to include the prot_bits
4160 		 * in the subpage.
4161 		 */
4162 		if (returned_len < (sizeof(*mode10_hdr) +
4163 		    __offsetof(struct scsi_control_data_prot_subpage, prot_bits)
4164 		    + sizeof(dp_page->prot_bits))) {
4165 			error = EINVAL;
4166 			free(mode10_hdr, M_SCSISA);
4167 			goto sagetparamsexit;
4168 		}
4169 
4170 		prot = &softc->prot_info.cur_prot_state;
4171 		prot->prot_method = dp_page->prot_method;
4172 		prot->pi_length = dp_page->pi_length &
4173 		    SA_CTRL_DP_PI_LENGTH_MASK;
4174 		prot->lbp_w = (dp_page->prot_bits & SA_CTRL_DP_LBP_W) ? 1 :0;
4175 		prot->lbp_r = (dp_page->prot_bits & SA_CTRL_DP_LBP_R) ? 1 :0;
4176 		prot->rbdp = (dp_page->prot_bits & SA_CTRL_DP_RBDP) ? 1 :0;
4177 		prot->initialized = 1;
4178 
4179 		if (prot_page != NULL)
4180 			bcopy(dp_page, prot_page, min(sizeof(*prot_page),
4181 			    sizeof(*dp_page)));
4182 
4183 		free(mode10_hdr, M_SCSISA);
4184 	}
4185 
4186 	if (CAM_DEBUGGED(periph->path, CAM_DEBUG_INFO)) {
4187 		int idx;
4188 		char *xyz = mode_buffer;
4189 		xpt_print_path(periph->path);
4190 		printf("Mode Sense Data=");
4191 		for (idx = 0; idx < mode_buffer_len; idx++)
4192 			printf(" 0x%02x", xyz[idx] & 0xff);
4193 		printf("\n");
4194 	}
4195 
4196 sagetparamsexit:
4197 
4198 	xpt_release_ccb(ccb);
4199 	free(mode_buffer, M_SCSISA);
4200 	return (error);
4201 }
4202 
4203 /*
4204  * Set protection information to the pending protection information stored
4205  * in the softc.
4206  */
4207 static int
sasetprot(struct cam_periph * periph,struct sa_prot_state * new_prot)4208 sasetprot(struct cam_periph *periph, struct sa_prot_state *new_prot)
4209 {
4210 	struct sa_softc *softc;
4211 	struct scsi_control_data_prot_subpage *dp_page, *dp_changeable;
4212 	struct scsi_mode_header_10 *mode10_hdr, *mode10_changeable;
4213 	union ccb *ccb;
4214 	uint8_t current_speed;
4215 	size_t dp_size, dp_page_length;
4216 	int dp_len, buff_mode;
4217 	int error;
4218 
4219 	softc = (struct sa_softc *)periph->softc;
4220 	mode10_hdr = NULL;
4221 	mode10_changeable = NULL;
4222 	ccb = NULL;
4223 
4224 	/*
4225 	 * Start off with the size set to the actual length of the page
4226 	 * that we have defined.
4227 	 */
4228 	dp_size = sizeof(*dp_changeable);
4229 	dp_page_length = dp_size -
4230 	    __offsetof(struct scsi_control_data_prot_subpage, prot_method);
4231 
4232 retry_length:
4233 
4234 	dp_len = sizeof(*mode10_changeable) + dp_size;
4235 	mode10_changeable = malloc(dp_len, M_SCSISA, M_NOWAIT | M_ZERO);
4236 	if (mode10_changeable == NULL) {
4237 		error = ENOMEM;
4238 		goto bailout;
4239 	}
4240 
4241 	dp_changeable =
4242 	    (struct scsi_control_data_prot_subpage *)&mode10_changeable[1];
4243 
4244 	/*
4245 	 * First get the data protection page changeable parameters mask.
4246 	 * We need to know which parameters the drive supports changing.
4247 	 * We also need to know what the drive claims that its page length
4248 	 * is.  The reason is that IBM drives in particular are very picky
4249 	 * about the page length.  They want it (the length set in the
4250 	 * page structure itself) to be 28 bytes, and they want the
4251 	 * parameter list length specified in the mode select header to be
4252 	 * 40 bytes.  So, to work with IBM drives as well as any other tape
4253 	 * drive, find out what the drive claims the page length is, and
4254 	 * make sure that we match that.
4255 	 */
4256 	error = sagetparams(periph, SA_PARAM_SPEED | SA_PARAM_LBP,
4257 	    NULL, NULL, NULL, &buff_mode, NULL, &current_speed, NULL, NULL,
4258 	    NULL, NULL, dp_changeable, dp_size, /*prot_changeable*/ 1);
4259 	if (error != 0)
4260 		goto bailout;
4261 
4262 	if (scsi_2btoul(dp_changeable->length) > dp_page_length) {
4263 		dp_page_length = scsi_2btoul(dp_changeable->length);
4264 		dp_size = dp_page_length +
4265 		    __offsetof(struct scsi_control_data_prot_subpage,
4266 		    prot_method);
4267 		free(mode10_changeable, M_SCSISA);
4268 		mode10_changeable = NULL;
4269 		goto retry_length;
4270 	}
4271 
4272 	mode10_hdr = malloc(dp_len, M_SCSISA, M_NOWAIT | M_ZERO);
4273 	if (mode10_hdr == NULL) {
4274 		error = ENOMEM;
4275 		goto bailout;
4276 	}
4277 
4278 	dp_page = (struct scsi_control_data_prot_subpage *)&mode10_hdr[1];
4279 
4280 	/*
4281 	 * Now grab the actual current settings in the page.
4282 	 */
4283 	error = sagetparams(periph, SA_PARAM_SPEED | SA_PARAM_LBP,
4284 	    NULL, NULL, NULL, &buff_mode, NULL, &current_speed, NULL, NULL,
4285 	    NULL, NULL, dp_page, dp_size, /*prot_changeable*/ 0);
4286 	if (error != 0)
4287 		goto bailout;
4288 
4289 	/* These two fields need to be 0 for MODE SELECT */
4290 	scsi_ulto2b(0, mode10_hdr->data_length);
4291 	mode10_hdr->medium_type = 0;
4292 	/* We are not including a block descriptor */
4293 	scsi_ulto2b(0, mode10_hdr->blk_desc_len);
4294 
4295 	mode10_hdr->dev_spec = current_speed;
4296 	/* if set, set single-initiator buffering mode */
4297 	if (softc->buffer_mode == SMH_SA_BUF_MODE_SIBUF) {
4298 		mode10_hdr->dev_spec |= SMH_SA_BUF_MODE_SIBUF;
4299 	}
4300 
4301 	/*
4302 	 * For each field, make sure that the drive allows changing it
4303 	 * before bringing in the user's setting.
4304 	 */
4305 	if (dp_changeable->prot_method != 0)
4306 		dp_page->prot_method = new_prot->prot_method;
4307 
4308 	if (dp_changeable->pi_length & SA_CTRL_DP_PI_LENGTH_MASK) {
4309 		dp_page->pi_length &= ~SA_CTRL_DP_PI_LENGTH_MASK;
4310 		dp_page->pi_length |= (new_prot->pi_length &
4311 		    SA_CTRL_DP_PI_LENGTH_MASK);
4312 	}
4313 	if (dp_changeable->prot_bits & SA_CTRL_DP_LBP_W) {
4314 		if (new_prot->lbp_w)
4315 			dp_page->prot_bits |= SA_CTRL_DP_LBP_W;
4316 		else
4317 			dp_page->prot_bits &= ~SA_CTRL_DP_LBP_W;
4318 	}
4319 
4320 	if (dp_changeable->prot_bits & SA_CTRL_DP_LBP_R) {
4321 		if (new_prot->lbp_r)
4322 			dp_page->prot_bits |= SA_CTRL_DP_LBP_R;
4323 		else
4324 			dp_page->prot_bits &= ~SA_CTRL_DP_LBP_R;
4325 	}
4326 
4327 	if (dp_changeable->prot_bits & SA_CTRL_DP_RBDP) {
4328 		if (new_prot->rbdp)
4329 			dp_page->prot_bits |= SA_CTRL_DP_RBDP;
4330 		else
4331 			dp_page->prot_bits &= ~SA_CTRL_DP_RBDP;
4332 	}
4333 
4334 	ccb = cam_periph_getccb(periph, 1);
4335 
4336 	scsi_mode_select_len(&ccb->csio,
4337 			     /*retries*/ 5,
4338 			     /*cbfcnp*/ NULL,
4339 			     /*tag_action*/ MSG_SIMPLE_Q_TAG,
4340 			     /*scsi_page_fmt*/ TRUE,
4341 			     /*save_pages*/ FALSE,
4342 			     /*param_buf*/ (uint8_t *)mode10_hdr,
4343 			     /*param_len*/ dp_len,
4344 			     /*minimum_cmd_size*/ 10,
4345 			     /*sense_len*/ SSD_FULL_SIZE,
4346 			     /*timeout*/
4347 			           softc->timeout_info[SA_TIMEOUT_MODE_SELECT]);
4348 
4349 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
4350 	if (error != 0)
4351 		goto bailout;
4352 
4353 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
4354 		error = EINVAL;
4355 		goto bailout;
4356 	}
4357 
4358 	/*
4359 	 * The operation was successful.  We could just copy the settings
4360 	 * the user requested, but just in case the drive ignored some of
4361 	 * our settings, let's ask for status again.
4362 	 */
4363 	error = sagetparams(periph, SA_PARAM_SPEED | SA_PARAM_LBP,
4364 	    NULL, NULL, NULL, &buff_mode, NULL, &current_speed, NULL, NULL,
4365 	    NULL, NULL, dp_page, dp_size, 0);
4366 
4367 bailout:
4368 	if (ccb != NULL)
4369 		xpt_release_ccb(ccb);
4370 	free(mode10_hdr, M_SCSISA);
4371 	free(mode10_changeable, M_SCSISA);
4372 	return (error);
4373 }
4374 
4375 /*
4376  * The purpose of this function is to set one of four different parameters
4377  * for a tape drive:
4378  *	- blocksize
4379  *	- density
4380  *	- compression / compression algorithm
4381  *	- buffering mode
4382  *
4383  * The assumption is that this will be called from saioctl(), and therefore
4384  * from a process context.  Thus the waiting malloc calls below.  If that
4385  * assumption ever changes, the malloc calls should be changed to be
4386  * NOWAIT mallocs.
4387  *
4388  * Any or all of the four parameters may be set when this function is
4389  * called.  It should handle setting more than one parameter at once.
4390  */
4391 static int
sasetparams(struct cam_periph * periph,sa_params params_to_set,uint32_t blocksize,uint8_t density,uint32_t calg,uint32_t sense_flags)4392 sasetparams(struct cam_periph *periph, sa_params params_to_set,
4393 	    uint32_t blocksize, uint8_t density, uint32_t calg,
4394 	    uint32_t sense_flags)
4395 {
4396 	struct sa_softc *softc;
4397 	uint32_t current_blocksize;
4398 	uint32_t current_calg;
4399 	uint8_t current_density;
4400 	uint8_t current_speed;
4401 	int comp_enabled, comp_supported;
4402 	void *mode_buffer;
4403 	int mode_buffer_len;
4404 	struct scsi_mode_header_6 *mode_hdr;
4405 	struct scsi_mode_blk_desc *mode_blk;
4406 	sa_comp_t *ccomp, *cpage;
4407 	int buff_mode;
4408 	union ccb *ccb = NULL;
4409 	int error;
4410 
4411 	softc = (struct sa_softc *)periph->softc;
4412 
4413 	ccomp = malloc(sizeof (sa_comp_t), M_SCSISA, M_NOWAIT);
4414 	if (ccomp == NULL)
4415 		return (ENOMEM);
4416 
4417 	/*
4418 	 * Since it doesn't make sense to set the number of blocks, or
4419 	 * write protection, we won't try to get the current value.  We
4420 	 * always want to get the blocksize, so we can set it back to the
4421 	 * proper value.
4422 	 */
4423 	error = sagetparams(periph,
4424 	    params_to_set | SA_PARAM_BLOCKSIZE | SA_PARAM_SPEED,
4425 	    &current_blocksize, &current_density, NULL, &buff_mode, NULL,
4426 	    &current_speed, &comp_supported, &comp_enabled,
4427 	    &current_calg, ccomp, NULL, 0, 0);
4428 
4429 	if (error != 0) {
4430 		free(ccomp, M_SCSISA);
4431 		return (error);
4432 	}
4433 
4434 	mode_buffer_len = sizeof(*mode_hdr) + sizeof(*mode_blk);
4435 	if (params_to_set & SA_PARAM_COMPRESSION)
4436 		mode_buffer_len += sizeof (sa_comp_t);
4437 
4438 	mode_buffer = malloc(mode_buffer_len, M_SCSISA, M_NOWAIT | M_ZERO);
4439 	if (mode_buffer == NULL) {
4440 		free(ccomp, M_SCSISA);
4441 		return (ENOMEM);
4442 	}
4443 
4444 	mode_hdr = (struct scsi_mode_header_6 *)mode_buffer;
4445 	mode_blk = (struct scsi_mode_blk_desc *)&mode_hdr[1];
4446 
4447 	ccb = cam_periph_getccb(periph, 1);
4448 
4449 retry:
4450 
4451 	if (params_to_set & SA_PARAM_COMPRESSION) {
4452 		if (mode_blk) {
4453 			cpage = (sa_comp_t *)&mode_blk[1];
4454 		} else {
4455 			cpage = (sa_comp_t *)&mode_hdr[1];
4456 		}
4457 		bcopy(ccomp, cpage, sizeof (sa_comp_t));
4458 		cpage->hdr.pagecode &= ~0x80;
4459 	} else
4460 		cpage = NULL;
4461 
4462 	/*
4463 	 * If the caller wants us to set the blocksize, use the one they
4464 	 * pass in.  Otherwise, use the blocksize we got back from the
4465 	 * mode select above.
4466 	 */
4467 	if (mode_blk) {
4468 		if (params_to_set & SA_PARAM_BLOCKSIZE)
4469 			scsi_ulto3b(blocksize, mode_blk->blklen);
4470 		else
4471 			scsi_ulto3b(current_blocksize, mode_blk->blklen);
4472 
4473 		/*
4474 		 * Set density if requested, else preserve old density.
4475 		 * SCSI_SAME_DENSITY only applies to SCSI-2 or better
4476 		 * devices, else density we've latched up in our softc.
4477 		 */
4478 		if (params_to_set & SA_PARAM_DENSITY) {
4479 			mode_blk->density = density;
4480 		} else if (softc->scsi_rev > SCSI_REV_CCS) {
4481 			mode_blk->density = SCSI_SAME_DENSITY;
4482 		} else {
4483 			mode_blk->density = softc->media_density;
4484 		}
4485 	}
4486 
4487 	/*
4488 	 * For mode selects, these two fields must be zero.
4489 	 */
4490 	mode_hdr->data_length = 0;
4491 	mode_hdr->medium_type = 0;
4492 
4493 	/* set the speed to the current value */
4494 	mode_hdr->dev_spec = current_speed;
4495 
4496 	/* if set, set single-initiator buffering mode */
4497 	if (softc->buffer_mode == SMH_SA_BUF_MODE_SIBUF) {
4498 		mode_hdr->dev_spec |= SMH_SA_BUF_MODE_SIBUF;
4499 	}
4500 
4501 	if (mode_blk)
4502 		mode_hdr->blk_desc_len = sizeof(struct scsi_mode_blk_desc);
4503 	else
4504 		mode_hdr->blk_desc_len = 0;
4505 
4506 	/*
4507 	 * First, if the user wants us to set the compression algorithm or
4508 	 * just turn compression on, check to make sure that this drive
4509 	 * supports compression.
4510 	 */
4511 	if (params_to_set & SA_PARAM_COMPRESSION) {
4512 		/*
4513 		 * If the compression algorithm is 0, disable compression.
4514 		 * If the compression algorithm is non-zero, enable
4515 		 * compression and set the compression type to the
4516 		 * specified compression algorithm, unless the algorithm is
4517 		 * MT_COMP_ENABLE.  In that case, we look at the
4518 		 * compression algorithm that is currently set and if it is
4519 		 * non-zero, we leave it as-is.  If it is zero, and we have
4520 		 * saved a compression algorithm from a time when
4521 		 * compression was enabled before, set the compression to
4522 		 * the saved value.
4523 		 */
4524 		switch (ccomp->hdr.pagecode & ~0x80) {
4525 		case SA_DEVICE_CONFIGURATION_PAGE:
4526 		{
4527 			struct scsi_dev_conf_page *dcp = &cpage->dconf;
4528 			if (calg == 0) {
4529 				dcp->sel_comp_alg = SA_COMP_NONE;
4530 				break;
4531 			}
4532 			if (calg != MT_COMP_ENABLE) {
4533 				dcp->sel_comp_alg = calg;
4534 			} else if (dcp->sel_comp_alg == SA_COMP_NONE &&
4535 			    softc->saved_comp_algorithm != 0) {
4536 				dcp->sel_comp_alg = softc->saved_comp_algorithm;
4537 			}
4538 			break;
4539 		}
4540 		case SA_DATA_COMPRESSION_PAGE:
4541 		if (ccomp->dcomp.dce_and_dcc & SA_DCP_DCC) {
4542 			struct scsi_data_compression_page *dcp = &cpage->dcomp;
4543 			if (calg == 0) {
4544 				/*
4545 				 * Disable compression, but leave the
4546 				 * decompression and the capability bit
4547 				 * alone.
4548 				 */
4549 				dcp->dce_and_dcc = SA_DCP_DCC;
4550 				dcp->dde_and_red |= SA_DCP_DDE;
4551 				break;
4552 			}
4553 			/* enable compression && decompression */
4554 			dcp->dce_and_dcc = SA_DCP_DCE | SA_DCP_DCC;
4555 			dcp->dde_and_red |= SA_DCP_DDE;
4556 			/*
4557 			 * If there, use compression algorithm from caller.
4558 			 * Otherwise, if there's a saved compression algorithm
4559 			 * and there is no current algorithm, use the saved
4560 			 * algorithm. Else parrot back what we got and hope
4561 			 * for the best.
4562 			 */
4563 			if (calg != MT_COMP_ENABLE) {
4564 				scsi_ulto4b(calg, dcp->comp_algorithm);
4565 				scsi_ulto4b(calg, dcp->decomp_algorithm);
4566 			} else if (scsi_4btoul(dcp->comp_algorithm) == 0 &&
4567 			    softc->saved_comp_algorithm != 0) {
4568 				scsi_ulto4b(softc->saved_comp_algorithm,
4569 				    dcp->comp_algorithm);
4570 				scsi_ulto4b(softc->saved_comp_algorithm,
4571 				    dcp->decomp_algorithm);
4572 			}
4573 			break;
4574 		}
4575 		/*
4576 		 * Compression does not appear to be supported-
4577 		 * at least via the DATA COMPRESSION page. It
4578 		 * would be too much to ask us to believe that
4579 		 * the page itself is supported, but incorrectly
4580 		 * reports an ability to manipulate data compression,
4581 		 * so we'll assume that this device doesn't support
4582 		 * compression. We can just fall through for that.
4583 		 */
4584 		/* FALLTHROUGH */
4585 		default:
4586 			/*
4587 			 * The drive doesn't seem to support compression,
4588 			 * so turn off the set compression bit.
4589 			 */
4590 			params_to_set &= ~SA_PARAM_COMPRESSION;
4591 			xpt_print(periph->path,
4592 			    "device does not seem to support compression\n");
4593 
4594 			/*
4595 			 * If that was the only thing the user wanted us to set,
4596 			 * clean up allocated resources and return with
4597 			 * 'operation not supported'.
4598 			 */
4599 			if (params_to_set == SA_PARAM_NONE) {
4600 				free(mode_buffer, M_SCSISA);
4601 				xpt_release_ccb(ccb);
4602 				return (ENODEV);
4603 			}
4604 
4605 			/*
4606 			 * That wasn't the only thing the user wanted us to set.
4607 			 * So, decrease the stated mode buffer length by the
4608 			 * size of the compression mode page.
4609 			 */
4610 			mode_buffer_len -= sizeof(sa_comp_t);
4611 		}
4612 	}
4613 
4614 	/* It is safe to retry this operation */
4615 	scsi_mode_select(&ccb->csio, 5, NULL, MSG_SIMPLE_Q_TAG,
4616 	    (params_to_set & SA_PARAM_COMPRESSION)? TRUE : FALSE,
4617 	    FALSE, mode_buffer, mode_buffer_len, SSD_FULL_SIZE,
4618 	    softc->timeout_info[SA_TIMEOUT_MODE_SELECT]);
4619 
4620 	error = cam_periph_runccb(ccb, saerror, 0,
4621 	    sense_flags, softc->device_stats);
4622 
4623 	if (CAM_DEBUGGED(periph->path, CAM_DEBUG_INFO)) {
4624 		int idx;
4625 		char *xyz = mode_buffer;
4626 		xpt_print_path(periph->path);
4627 		printf("Err%d, Mode Select Data=", error);
4628 		for (idx = 0; idx < mode_buffer_len; idx++)
4629 			printf(" 0x%02x", xyz[idx] & 0xff);
4630 		printf("\n");
4631 	}
4632 
4633 	if (error) {
4634 		/*
4635 		 * If we can, try without setting density/blocksize.
4636 		 */
4637 		if (mode_blk) {
4638 			if ((params_to_set &
4639 			    (SA_PARAM_DENSITY|SA_PARAM_BLOCKSIZE)) == 0) {
4640 				mode_blk = NULL;
4641 				goto retry;
4642 			}
4643 		} else {
4644 			mode_blk = (struct scsi_mode_blk_desc *)&mode_hdr[1];
4645 			cpage = (sa_comp_t *)&mode_blk[1];
4646 		}
4647 
4648 		/*
4649 		 * If we were setting the blocksize, and that failed, we
4650 		 * want to set it to its original value.  If we weren't
4651 		 * setting the blocksize, we don't want to change it.
4652 		 */
4653 		scsi_ulto3b(current_blocksize, mode_blk->blklen);
4654 
4655 		/*
4656 		 * Set density if requested, else preserve old density.
4657 		 * SCSI_SAME_DENSITY only applies to SCSI-2 or better
4658 		 * devices, else density we've latched up in our softc.
4659 		 */
4660 		if (params_to_set & SA_PARAM_DENSITY) {
4661 			mode_blk->density = current_density;
4662 		} else if (softc->scsi_rev > SCSI_REV_CCS) {
4663 			mode_blk->density = SCSI_SAME_DENSITY;
4664 		} else {
4665 			mode_blk->density = softc->media_density;
4666 		}
4667 
4668 		if (params_to_set & SA_PARAM_COMPRESSION)
4669 			bcopy(ccomp, cpage, sizeof (sa_comp_t));
4670 
4671 		/*
4672 		 * The retry count is the only CCB field that might have been
4673 		 * changed that we care about, so reset it back to 1.
4674 		 */
4675 		ccb->ccb_h.retry_count = 1;
4676 		cam_periph_runccb(ccb, saerror, 0, sense_flags,
4677 		    softc->device_stats);
4678 	}
4679 
4680 	xpt_release_ccb(ccb);
4681 
4682 	if (ccomp != NULL)
4683 		free(ccomp, M_SCSISA);
4684 
4685 	if (params_to_set & SA_PARAM_COMPRESSION) {
4686 		if (error) {
4687 			softc->flags &= ~SA_FLAG_COMP_ENABLED;
4688 			/*
4689 			 * Even if we get an error setting compression,
4690 			 * do not say that we don't support it. We could
4691 			 * have been wrong, or it may be media specific.
4692 			 *	softc->flags &= ~SA_FLAG_COMP_SUPP;
4693 			 */
4694 			softc->saved_comp_algorithm = softc->comp_algorithm;
4695 			softc->comp_algorithm = 0;
4696 		} else {
4697 			softc->flags |= SA_FLAG_COMP_ENABLED;
4698 			softc->comp_algorithm = calg;
4699 		}
4700 	}
4701 
4702 	free(mode_buffer, M_SCSISA);
4703 	return (error);
4704 }
4705 
4706 static int
saextget(struct cdev * dev,struct cam_periph * periph,struct sbuf * sb,struct mtextget * g)4707 saextget(struct cdev *dev, struct cam_periph *periph, struct sbuf *sb,
4708     struct mtextget *g)
4709 {
4710 	int indent, error;
4711 	char tmpstr[80];
4712 	struct sa_softc *softc;
4713 	int tmpint;
4714 	uint32_t maxio_tmp;
4715 	struct ccb_getdev cgd;
4716 
4717 	softc = (struct sa_softc *)periph->softc;
4718 
4719 	error = 0;
4720 
4721 	error = sagetparams_common(dev, periph);
4722 	if (error)
4723 		goto extget_bailout;
4724 	if (!SA_IS_CTRL(dev) && !softc->open_pending_mount)
4725 		sagetpos(periph);
4726 
4727 	indent = 0;
4728 	SASBADDNODE(sb, indent, mtextget);
4729 	/*
4730 	 * Basic CAM peripheral information.
4731 	 */
4732 	SASBADDVARSTR(sb, indent, periph->periph_name, %s, periph_name,
4733 	    strlen(periph->periph_name) + 1);
4734 	SASBADDUINT(sb, indent, periph->unit_number, %u, unit_number);
4735 	memset(&cgd, 0, sizeof(cgd));
4736 	xpt_setup_ccb(&cgd.ccb_h,
4737 		      periph->path,
4738 		      CAM_PRIORITY_NORMAL);
4739 	cgd.ccb_h.func_code = XPT_GDEV_TYPE;
4740 	xpt_action((union ccb *)&cgd);
4741 	if ((cgd.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
4742 		g->status = MT_EXT_GET_ERROR;
4743 		snprintf(g->error_str, sizeof(g->error_str),
4744 		    "Error %#x returned for XPT_GDEV_TYPE CCB",
4745 		    cgd.ccb_h.status);
4746 		goto extget_bailout;
4747 	}
4748 
4749 	cam_strvis(tmpstr, cgd.inq_data.vendor,
4750 	    sizeof(cgd.inq_data.vendor), sizeof(tmpstr));
4751 	SASBADDVARSTRDESC(sb, indent, tmpstr, %s, vendor,
4752 	    sizeof(cgd.inq_data.vendor) + 1, "SCSI Vendor ID");
4753 
4754 	cam_strvis(tmpstr, cgd.inq_data.product,
4755 	    sizeof(cgd.inq_data.product), sizeof(tmpstr));
4756 	SASBADDVARSTRDESC(sb, indent, tmpstr, %s, product,
4757 	    sizeof(cgd.inq_data.product) + 1, "SCSI Product ID");
4758 
4759 	cam_strvis(tmpstr, cgd.inq_data.revision,
4760 	    sizeof(cgd.inq_data.revision), sizeof(tmpstr));
4761 	SASBADDVARSTRDESC(sb, indent, tmpstr, %s, revision,
4762 	    sizeof(cgd.inq_data.revision) + 1, "SCSI Revision");
4763 
4764 	if (cgd.serial_num_len > 0) {
4765 		char *tmpstr2;
4766 		size_t ts2_len;
4767 		int ts2_malloc;
4768 
4769 		ts2_len = 0;
4770 
4771 		if (cgd.serial_num_len > sizeof(tmpstr)) {
4772 			ts2_len = cgd.serial_num_len + 1;
4773 			ts2_malloc = 1;
4774 			tmpstr2 = malloc(ts2_len, M_SCSISA, M_NOWAIT | M_ZERO);
4775 			/*
4776 			 * The 80 characters allocated on the stack above
4777 			 * will handle the vast majority of serial numbers.
4778 			 * If we run into one that is larger than that, and
4779 			 * we can't malloc the length without blocking,
4780 			 * bail out with an out of memory error.
4781 			 */
4782 			if (tmpstr2 == NULL) {
4783 				error = ENOMEM;
4784 				goto extget_bailout;
4785 			}
4786 		} else {
4787 			ts2_len = sizeof(tmpstr);
4788 			ts2_malloc = 0;
4789 			tmpstr2 = tmpstr;
4790 		}
4791 
4792 		cam_strvis(tmpstr2, cgd.serial_num, cgd.serial_num_len,
4793 		    ts2_len);
4794 
4795 		SASBADDVARSTRDESC(sb, indent, tmpstr2, %s, serial_num,
4796 		    (ssize_t)cgd.serial_num_len + 1, "Serial Number");
4797 		if (ts2_malloc != 0)
4798 			free(tmpstr2, M_SCSISA);
4799 	} else {
4800 		/*
4801 		 * We return a serial_num element in any case, but it will
4802 		 * be empty if the device has no serial number.
4803 		 */
4804 		tmpstr[0] = '\0';
4805 		SASBADDVARSTRDESC(sb, indent, tmpstr, %s, serial_num,
4806 		    (ssize_t)0, "Serial Number");
4807 	}
4808 
4809 	SASBADDUINTDESC(sb, indent, softc->maxio, %u, maxio,
4810 	    "Maximum I/O size allowed by driver and controller");
4811 
4812 	SASBADDUINTDESC(sb, indent, softc->cpi_maxio, %u, cpi_maxio,
4813 	    "Maximum I/O size reported by controller");
4814 
4815 	SASBADDUINTDESC(sb, indent, softc->max_blk, %u, max_blk,
4816 	    "Maximum block size supported by tape drive and media");
4817 
4818 	SASBADDUINTDESC(sb, indent, softc->min_blk, %u, min_blk,
4819 	    "Minimum block size supported by tape drive and media");
4820 
4821 	SASBADDUINTDESC(sb, indent, softc->blk_gran, %u, blk_gran,
4822 	    "Block granularity supported by tape drive and media");
4823 
4824 	maxio_tmp = min(softc->max_blk, softc->maxio);
4825 
4826 	SASBADDUINTDESC(sb, indent, maxio_tmp, %u, max_effective_iosize,
4827 	    "Maximum possible I/O size");
4828 
4829 	SASBADDINTDESC(sb, indent, softc->flags & SA_FLAG_FIXED ? 1 : 0, %d,
4830 	    fixed_mode, "Set to 1 for fixed block mode, 0 for variable block");
4831 
4832 	/*
4833 	 * XXX KDM include SIM, bus, target, LUN?
4834 	 */
4835 	if (softc->flags & SA_FLAG_COMP_UNSUPP)
4836 		tmpint = 0;
4837 	else
4838 		tmpint = 1;
4839 	SASBADDINTDESC(sb, indent, tmpint, %d, compression_supported,
4840 	    "Set to 1 if compression is supported, 0 if not");
4841 	if (softc->flags & SA_FLAG_COMP_ENABLED)
4842 		tmpint = 1;
4843 	else
4844 		tmpint = 0;
4845 	SASBADDINTDESC(sb, indent, tmpint, %d, compression_enabled,
4846 	    "Set to 1 if compression is enabled, 0 if not");
4847 	SASBADDUINTDESC(sb, indent, softc->comp_algorithm, %u,
4848 	    compression_algorithm, "Numeric compression algorithm");
4849 
4850 	safillprot(softc, &indent, sb);
4851 
4852 	SASBADDUINTDESC(sb, indent, softc->media_blksize, %u,
4853 	    media_blocksize, "Block size reported by drive or set by user");
4854 	SASBADDINTDESC(sb, indent, (intmax_t)softc->fileno, %jd,
4855 	    calculated_fileno, "Calculated file number, -1 if unknown");
4856 	SASBADDINTDESC(sb, indent, (intmax_t)softc->blkno, %jd,
4857 	    calculated_rel_blkno, "Calculated block number relative to file, "
4858 	    "set to -1 if unknown");
4859 	SASBADDINTDESC(sb, indent, (intmax_t)softc->rep_fileno, %jd,
4860 	    reported_fileno, "File number reported by drive, -1 if unknown");
4861 	SASBADDINTDESC(sb, indent, (intmax_t)softc->rep_blkno, %jd,
4862 	    reported_blkno, "Block number relative to BOP/BOT reported by "
4863 	    "drive, -1 if unknown");
4864 	SASBADDINTDESC(sb, indent, (intmax_t)softc->partition, %jd,
4865 	    partition, "Current partition number, 0 is the default");
4866 	SASBADDINTDESC(sb, indent, softc->bop, %d, bop,
4867 	    "Set to 1 if drive is at the beginning of partition/tape, 0 if "
4868 	    "not, -1 if unknown");
4869 	SASBADDINTDESC(sb, indent, softc->eop, %d, eop,
4870 	    "Set to 1 if drive is past early warning, 0 if not, -1 if unknown");
4871 	SASBADDINTDESC(sb, indent, softc->bpew, %d, bpew,
4872 	    "Set to 1 if drive is past programmable early warning, 0 if not, "
4873 	    "-1 if unknown");
4874 	SASBADDINTDESC(sb, indent, (intmax_t)softc->last_io_resid, %jd,
4875 	    residual, "Residual for the last I/O");
4876 	/*
4877 	 * XXX KDM should we send a string with the current driver
4878 	 * status already decoded instead of a numeric value?
4879 	 */
4880 	SASBADDINTDESC(sb, indent, softc->dsreg, %d, dsreg,
4881 	    "Current state of the driver");
4882 
4883 	safilldensitysb(softc, &indent, sb);
4884 
4885 	SASBENDNODE(sb, indent, mtextget);
4886 
4887 extget_bailout:
4888 
4889 	return (error);
4890 }
4891 
4892 static int
saparamget(struct sa_softc * softc,struct sbuf * sb)4893 saparamget(struct sa_softc *softc, struct sbuf *sb)
4894 {
4895 	int indent;
4896 
4897 	indent = 0;
4898 	SASBADDNODE(sb, indent, mtparamget);
4899 	SASBADDINTDESC(sb, indent, softc->sili, %d, sili,
4900 	    "Suppress an error on underlength variable reads");
4901 	SASBADDINTDESC(sb, indent, softc->eot_warn, %d, eot_warn,
4902 	    "Return an error to warn that end of tape is approaching");
4903 	safillprot(softc, &indent, sb);
4904 	SASBENDNODE(sb, indent, mtparamget);
4905 
4906 	return (0);
4907 }
4908 
4909 static void
saprevent(struct cam_periph * periph,int action)4910 saprevent(struct cam_periph *periph, int action)
4911 {
4912 	struct	sa_softc *softc;
4913 	union	ccb *ccb;
4914 	int	error, sf;
4915 
4916 	softc = (struct sa_softc *)periph->softc;
4917 
4918 	if ((action == PR_ALLOW) && (softc->flags & SA_FLAG_TAPE_LOCKED) == 0)
4919 		return;
4920 	if ((action == PR_PREVENT) && (softc->flags & SA_FLAG_TAPE_LOCKED) != 0)
4921 		return;
4922 
4923 	/*
4924 	 * We can be quiet about illegal requests.
4925 	 */
4926 	if (CAM_DEBUGGED(periph->path, CAM_DEBUG_INFO)) {
4927 		sf = 0;
4928 	} else
4929 		sf = SF_QUIET_IR;
4930 
4931 	ccb = cam_periph_getccb(periph, 1);
4932 
4933 	/* It is safe to retry this operation */
4934 	scsi_prevent(&ccb->csio, 5, NULL, MSG_SIMPLE_Q_TAG, action,
4935 	    SSD_FULL_SIZE, softc->timeout_info[SA_TIMEOUT_PREVENT]);
4936 
4937 	error = cam_periph_runccb(ccb, saerror, 0, sf, softc->device_stats);
4938 	if (error == 0) {
4939 		if (action == PR_ALLOW)
4940 			softc->flags &= ~SA_FLAG_TAPE_LOCKED;
4941 		else
4942 			softc->flags |= SA_FLAG_TAPE_LOCKED;
4943 	}
4944 
4945 	xpt_release_ccb(ccb);
4946 }
4947 
4948 static int
sarewind(struct cam_periph * periph)4949 sarewind(struct cam_periph *periph)
4950 {
4951 	union	ccb *ccb;
4952 	struct	sa_softc *softc;
4953 	int	error;
4954 
4955 	softc = (struct sa_softc *)periph->softc;
4956 
4957 	ccb = cam_periph_getccb(periph, 1);
4958 
4959 	/* It is safe to retry this operation */
4960 	scsi_rewind(&ccb->csio, 2, NULL, MSG_SIMPLE_Q_TAG, FALSE,
4961 	    SSD_FULL_SIZE, softc->timeout_info[SA_TIMEOUT_REWIND]);
4962 
4963 	softc->dsreg = MTIO_DSREG_REW;
4964 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
4965 	softc->dsreg = MTIO_DSREG_REST;
4966 
4967 	xpt_release_ccb(ccb);
4968 	if (error == 0) {
4969 		softc->partition = softc->fileno = softc->blkno = (daddr_t) 0;
4970 		softc->rep_fileno = softc->rep_blkno = (daddr_t) 0;
4971 	} else {
4972 		softc->fileno = softc->blkno = (daddr_t) -1;
4973 		softc->partition = (daddr_t) -1;
4974 		softc->rep_fileno = softc->rep_blkno = (daddr_t) -1;
4975 	}
4976 	return (error);
4977 }
4978 
4979 static int
saspace(struct cam_periph * periph,int count,scsi_space_code code)4980 saspace(struct cam_periph *periph, int count, scsi_space_code code)
4981 {
4982 	union	ccb *ccb;
4983 	struct	sa_softc *softc;
4984 	int	error;
4985 
4986 	softc = (struct sa_softc *)periph->softc;
4987 
4988 	ccb = cam_periph_getccb(periph, 1);
4989 
4990 	/* This cannot be retried */
4991 
4992 	scsi_space(&ccb->csio, 0, NULL, MSG_SIMPLE_Q_TAG, code, count,
4993 	    SSD_FULL_SIZE, softc->timeout_info[SA_TIMEOUT_SPACE]);
4994 
4995 	/*
4996 	 * Clear residual because we will be using it.
4997 	 */
4998 	softc->last_ctl_resid = 0;
4999 
5000 	softc->dsreg = (count < 0)? MTIO_DSREG_REV : MTIO_DSREG_FWD;
5001 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
5002 	softc->dsreg = MTIO_DSREG_REST;
5003 
5004 	xpt_release_ccb(ccb);
5005 
5006 	/*
5007 	 * If a spacing operation has failed, we need to invalidate
5008 	 * this mount.
5009 	 *
5010 	 * If the spacing operation was setmarks or to end of recorded data,
5011 	 * we no longer know our relative position.
5012 	 *
5013 	 * If the spacing operations was spacing files in reverse, we
5014 	 * take account of the residual, but still check against less
5015 	 * than zero- if we've gone negative, we must have hit BOT.
5016 	 *
5017 	 * If the spacing operations was spacing records in reverse and
5018 	 * we have a residual, we've either hit BOT or hit a filemark.
5019 	 * In the former case, we know our new record number (0). In
5020 	 * the latter case, we have absolutely no idea what the real
5021 	 * record number is- we've stopped between the end of the last
5022 	 * record in the previous file and the filemark that stopped
5023 	 * our spacing backwards.
5024 	 */
5025 	if (error) {
5026 		softc->fileno = softc->blkno = (daddr_t) -1;
5027 		softc->rep_blkno = softc->partition = (daddr_t) -1;
5028 		softc->rep_fileno = (daddr_t) -1;
5029 	} else if (code == SS_SETMARKS || code == SS_EOD) {
5030 		softc->fileno = softc->blkno = (daddr_t) -1;
5031 	} else if (code == SS_FILEMARKS && softc->fileno != (daddr_t) -1) {
5032 		softc->fileno += (count - softc->last_ctl_resid);
5033 		if (softc->fileno < 0)	/* we must of hit BOT */
5034 			softc->fileno = 0;
5035 		softc->blkno = 0;
5036 	} else if (code == SS_BLOCKS && softc->blkno != (daddr_t) -1) {
5037 		softc->blkno += (count - softc->last_ctl_resid);
5038 		if (count < 0) {
5039 			if (softc->last_ctl_resid || softc->blkno < 0) {
5040 				if (softc->fileno == 0) {
5041 					softc->blkno = 0;
5042 				} else {
5043 					softc->blkno = (daddr_t) -1;
5044 				}
5045 			}
5046 		}
5047 	}
5048 	if (error == 0)
5049 		sagetpos(periph);
5050 
5051 	return (error);
5052 }
5053 
5054 static int
sawritefilemarks(struct cam_periph * periph,int nmarks,int setmarks,int immed)5055 sawritefilemarks(struct cam_periph *periph, int nmarks, int setmarks, int immed)
5056 {
5057 	union	ccb *ccb;
5058 	struct	sa_softc *softc;
5059 	int	error, nwm = 0;
5060 
5061 	softc = (struct sa_softc *)periph->softc;
5062 	if (softc->open_rdonly)
5063 		return (EBADF);
5064 
5065 	ccb = cam_periph_getccb(periph, 1);
5066 	/*
5067 	 * Clear residual because we will be using it.
5068 	 */
5069 	softc->last_ctl_resid = 0;
5070 
5071 	softc->dsreg = MTIO_DSREG_FMK;
5072 	/* this *must* not be retried */
5073 	scsi_write_filemarks(&ccb->csio, 0, NULL, MSG_SIMPLE_Q_TAG,
5074 	    immed, setmarks, nmarks, SSD_FULL_SIZE,
5075 	    softc->timeout_info[SA_TIMEOUT_WRITE_FILEMARKS]);
5076 	softc->dsreg = MTIO_DSREG_REST;
5077 
5078 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
5079 
5080 	if (error == 0 && nmarks) {
5081 		struct sa_softc *softc = (struct sa_softc *)periph->softc;
5082 		nwm = nmarks - softc->last_ctl_resid;
5083 		softc->filemarks += nwm;
5084 	}
5085 
5086 	xpt_release_ccb(ccb);
5087 
5088 	/*
5089 	 * Update relative positions (if we're doing that).
5090 	 */
5091 	if (error) {
5092 		softc->fileno = softc->blkno = softc->partition = (daddr_t) -1;
5093 	} else if (softc->fileno != (daddr_t) -1) {
5094 		softc->fileno += nwm;
5095 		softc->blkno = 0;
5096 	}
5097 
5098 	/*
5099 	 * Ask the tape drive for position information.
5100 	 */
5101 	sagetpos(periph);
5102 
5103 	/*
5104 	 * If we got valid position information, since we just wrote a file
5105 	 * mark, we know we're at the file mark and block 0 after that
5106 	 * filemark.
5107 	 */
5108 	if (softc->rep_fileno != (daddr_t) -1) {
5109 		softc->fileno = softc->rep_fileno;
5110 		softc->blkno = 0;
5111 	}
5112 
5113 	return (error);
5114 }
5115 
5116 static int
sagetpos(struct cam_periph * periph)5117 sagetpos(struct cam_periph *periph)
5118 {
5119 	union ccb *ccb;
5120 	struct scsi_tape_position_long_data long_pos;
5121 	struct sa_softc *softc = (struct sa_softc *)periph->softc;
5122 	int error;
5123 
5124 	if (softc->quirks & SA_QUIRK_NO_LONG_POS) {
5125 		softc->rep_fileno = (daddr_t) -1;
5126 		softc->rep_blkno = (daddr_t) -1;
5127 		softc->bop = softc->eop = softc->bpew = -1;
5128 		return (EOPNOTSUPP);
5129 	}
5130 
5131 	bzero(&long_pos, sizeof(long_pos));
5132 
5133 	ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
5134 	scsi_read_position_10(&ccb->csio,
5135 			      /*retries*/ 1,
5136 			      /*cbfcnp*/ NULL,
5137 			      /*tag_action*/ MSG_SIMPLE_Q_TAG,
5138 			      /*service_action*/ SA_RPOS_LONG_FORM,
5139 			      /*data_ptr*/ (uint8_t *)&long_pos,
5140 			      /*length*/ sizeof(long_pos),
5141 			      /*sense_len*/ SSD_FULL_SIZE,
5142 			      /*timeout*/
5143 				 softc->timeout_info[SA_TIMEOUT_READ_POSITION]);
5144 
5145 	softc->dsreg = MTIO_DSREG_RBSY;
5146 	error = cam_periph_runccb(ccb, saerror, 0, SF_QUIET_IR,
5147 				  softc->device_stats);
5148 	softc->dsreg = MTIO_DSREG_REST;
5149 
5150 	if (error == 0) {
5151 		if (long_pos.flags & SA_RPOS_LONG_MPU) {
5152 			/*
5153 			 * If the drive doesn't know what file mark it is
5154 			 * on, our calculated filemark isn't going to be
5155 			 * accurate either.
5156 			 */
5157 			softc->fileno = (daddr_t) -1;
5158 			softc->rep_fileno = (daddr_t) -1;
5159 		} else {
5160 			softc->fileno = softc->rep_fileno =
5161 			    scsi_8btou64(long_pos.logical_file_num);
5162 		}
5163 
5164 		if (long_pos.flags & SA_RPOS_LONG_LONU) {
5165 			softc->partition = (daddr_t) -1;
5166 			softc->rep_blkno = (daddr_t) -1;
5167 			/*
5168 			 * If the tape drive doesn't know its block
5169 			 * position, we can't claim to know it either.
5170 			 */
5171 			softc->blkno = (daddr_t) -1;
5172 		} else {
5173 			softc->partition = scsi_4btoul(long_pos.partition);
5174 			softc->rep_blkno =
5175 			    scsi_8btou64(long_pos.logical_object_num);
5176 		}
5177 		if (long_pos.flags & SA_RPOS_LONG_BOP)
5178 			softc->bop = 1;
5179 		else
5180 			softc->bop = 0;
5181 
5182 		if (long_pos.flags & SA_RPOS_LONG_EOP)
5183 			softc->eop = 1;
5184 		else
5185 			softc->eop = 0;
5186 
5187 		if ((long_pos.flags & SA_RPOS_LONG_BPEW)
5188 		 || (softc->set_pews_status != 0)) {
5189 			softc->bpew = 1;
5190 			if (softc->set_pews_status > 0)
5191 				softc->set_pews_status--;
5192 		} else
5193 			softc->bpew = 0;
5194 	} else if (error == EINVAL) {
5195 		/*
5196 		 * If this drive returned an invalid-request type error,
5197 		 * then it likely doesn't support the long form report.
5198 		 */
5199 		softc->quirks |= SA_QUIRK_NO_LONG_POS;
5200 	}
5201 
5202 	if (error != 0) {
5203 		softc->rep_fileno = softc->rep_blkno = (daddr_t) -1;
5204 		softc->partition = (daddr_t) -1;
5205 		softc->bop = softc->eop = softc->bpew = -1;
5206 	}
5207 
5208 	xpt_release_ccb(ccb);
5209 
5210 	return (error);
5211 }
5212 
5213 static int
sardpos(struct cam_periph * periph,int hard,uint32_t * blkptr)5214 sardpos(struct cam_periph *periph, int hard, uint32_t *blkptr)
5215 {
5216 	struct scsi_tape_position_data loc;
5217 	union ccb *ccb;
5218 	struct sa_softc *softc = (struct sa_softc *)periph->softc;
5219 	int error;
5220 
5221 	/*
5222 	 * We try and flush any buffered writes here if we were writing
5223 	 * and we're trying to get hardware block position. It eats
5224 	 * up performance substantially, but I'm wary of drive firmware.
5225 	 *
5226 	 * I think that *logical* block position is probably okay-
5227 	 * but hardware block position might have to wait for data
5228 	 * to hit media to be valid. Caveat Emptor.
5229 	 */
5230 
5231 	if (hard && (softc->flags & SA_FLAG_TAPE_WRITTEN)) {
5232 		error = sawritefilemarks(periph, 0, 0, 0);
5233 		if (error && error != EACCES)
5234 			return (error);
5235 	}
5236 
5237 	ccb = cam_periph_getccb(periph, 1);
5238 	scsi_read_position(&ccb->csio, 1, NULL, MSG_SIMPLE_Q_TAG,
5239 	    hard, &loc, SSD_FULL_SIZE,
5240 	    softc->timeout_info[SA_TIMEOUT_READ_POSITION]);
5241 	softc->dsreg = MTIO_DSREG_RBSY;
5242 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
5243 	softc->dsreg = MTIO_DSREG_REST;
5244 
5245 	if (error == 0) {
5246 		if (loc.flags & SA_RPOS_UNCERTAIN) {
5247 			error = EINVAL;		/* nothing is certain */
5248 		} else {
5249 			*blkptr = scsi_4btoul(loc.firstblk);
5250 		}
5251 	}
5252 
5253 	xpt_release_ccb(ccb);
5254 	return (error);
5255 }
5256 
5257 static int
sasetpos(struct cam_periph * periph,int hard,struct mtlocate * locate_info)5258 sasetpos(struct cam_periph *periph, int hard, struct mtlocate *locate_info)
5259 {
5260 	union ccb *ccb;
5261 	struct sa_softc *softc;
5262 	int locate16;
5263 	int immed, cp;
5264 	int error;
5265 
5266 	/*
5267 	 * We used to try and flush any buffered writes here.
5268 	 * Now we push this onto user applications to either
5269 	 * flush the pending writes themselves (via a zero count
5270 	 * WRITE FILEMARKS command) or they can trust their tape
5271 	 * drive to do this correctly for them.
5272  	 */
5273 
5274 	softc = (struct sa_softc *)periph->softc;
5275 	ccb = cam_periph_getccb(periph, 1);
5276 
5277 	cp = locate_info->flags & MT_LOCATE_FLAG_CHANGE_PART ? 1 : 0;
5278 	immed = locate_info->flags & MT_LOCATE_FLAG_IMMED ? 1 : 0;
5279 
5280 	/*
5281 	 * Determine whether we have to use LOCATE or LOCATE16.  The hard
5282 	 * bit is only possible with LOCATE, but the new ioctls do not
5283 	 * allow setting that bit.  So we can't get into the situation of
5284 	 * having the hard bit set with a block address that is larger than
5285 	 * 32-bits.
5286 	 */
5287 	if (hard != 0)
5288 		locate16 = 0;
5289 	else if ((locate_info->dest_type != MT_LOCATE_DEST_OBJECT)
5290 	      || (locate_info->block_address_mode != MT_LOCATE_BAM_IMPLICIT)
5291 	      || (locate_info->logical_id > SA_SPOS_MAX_BLK))
5292 		locate16 = 1;
5293 	else
5294 		locate16 = 0;
5295 
5296 	if (locate16 != 0) {
5297 		scsi_locate_16(&ccb->csio,
5298 			       /*retries*/ 1,
5299 			       /*cbfcnp*/ NULL,
5300 			       /*tag_action*/ MSG_SIMPLE_Q_TAG,
5301 			       /*immed*/ immed,
5302 			       /*cp*/ cp,
5303 			       /*dest_type*/ locate_info->dest_type,
5304 			       /*bam*/ locate_info->block_address_mode,
5305 			       /*partition*/ locate_info->partition,
5306 			       /*logical_id*/ locate_info->logical_id,
5307 			       /*sense_len*/ SSD_FULL_SIZE,
5308 			       /*timeout*/
5309 				   softc->timeout_info[SA_TIMEOUT_LOCATE]);
5310 	} else {
5311 		scsi_locate_10(&ccb->csio,
5312 			       /*retries*/ 1,
5313 			       /*cbfcnp*/ NULL,
5314 			       /*tag_action*/ MSG_SIMPLE_Q_TAG,
5315 			       /*immed*/ immed,
5316 			       /*cp*/ cp,
5317 			       /*hard*/ hard,
5318 			       /*partition*/ locate_info->partition,
5319 			       /*block_address*/ locate_info->logical_id,
5320 			       /*sense_len*/ SSD_FULL_SIZE,
5321 			       /*timeout*/
5322 				   softc->timeout_info[SA_TIMEOUT_LOCATE]);
5323 	}
5324 
5325 	softc->dsreg = MTIO_DSREG_POS;
5326 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
5327 	softc->dsreg = MTIO_DSREG_REST;
5328 	xpt_release_ccb(ccb);
5329 
5330 	/*
5331 	 * We assume the calculated file and block numbers are unknown
5332 	 * unless we have enough information to populate them.
5333 	 */
5334 	softc->fileno = softc->blkno = (daddr_t) -1;
5335 
5336 	/*
5337 	 * If the user requested changing the partition and the request
5338 	 * succeeded, note the partition.
5339 	 */
5340 	if ((error == 0)
5341 	 && (cp != 0))
5342 		softc->partition = locate_info->partition;
5343 	else
5344 		softc->partition = (daddr_t) -1;
5345 
5346 	if (error == 0) {
5347 		switch (locate_info->dest_type) {
5348 		case MT_LOCATE_DEST_FILE:
5349 			/*
5350 			 * This is the only case where we can reliably
5351 			 * calculate the file and block numbers.
5352 			 */
5353 			softc->fileno = locate_info->logical_id;
5354 			softc->blkno = 0;
5355 			break;
5356 		case MT_LOCATE_DEST_OBJECT:
5357 		case MT_LOCATE_DEST_SET:
5358 		case MT_LOCATE_DEST_EOD:
5359 		default:
5360 			break;
5361 		}
5362 	}
5363 
5364 	/*
5365 	 * Ask the drive for current position information.
5366 	 */
5367 	sagetpos(periph);
5368 
5369 	return (error);
5370 }
5371 
5372 static int
saretension(struct cam_periph * periph)5373 saretension(struct cam_periph *periph)
5374 {
5375 	union ccb *ccb;
5376 	struct sa_softc *softc;
5377 	int error;
5378 
5379 	softc = (struct sa_softc *)periph->softc;
5380 
5381 	ccb = cam_periph_getccb(periph, 1);
5382 
5383 	/* It is safe to retry this operation */
5384 	scsi_load_unload(&ccb->csio, 5, NULL, MSG_SIMPLE_Q_TAG, FALSE,
5385 	    FALSE, TRUE,  TRUE, SSD_FULL_SIZE,
5386 	    softc->timeout_info[SA_TIMEOUT_LOAD]);
5387 
5388 	softc->dsreg = MTIO_DSREG_TEN;
5389 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
5390 	softc->dsreg = MTIO_DSREG_REST;
5391 
5392 	xpt_release_ccb(ccb);
5393 	if (error == 0) {
5394 		softc->partition = softc->fileno = softc->blkno = (daddr_t) 0;
5395 		sagetpos(periph);
5396 	} else
5397 		softc->partition = softc->fileno = softc->blkno = (daddr_t) -1;
5398 	return (error);
5399 }
5400 
5401 static int
sareservereleaseunit(struct cam_periph * periph,int reserve)5402 sareservereleaseunit(struct cam_periph *periph, int reserve)
5403 {
5404 	union ccb *ccb;
5405 	struct sa_softc *softc;
5406 	int error;
5407 
5408 	softc = (struct sa_softc *)periph->softc;
5409 	ccb = cam_periph_getccb(periph,  1);
5410 
5411 	/* It is safe to retry this operation */
5412 	scsi_reserve_release_unit(&ccb->csio, 2, NULL, MSG_SIMPLE_Q_TAG,
5413 	    FALSE,  0, SSD_FULL_SIZE,  softc->timeout_info[SA_TIMEOUT_RESERVE],
5414 	    reserve);
5415 	softc->dsreg = MTIO_DSREG_RBSY;
5416 	error = cam_periph_runccb(ccb, saerror, 0,
5417 	    SF_RETRY_UA | SF_NO_PRINT, softc->device_stats);
5418 	softc->dsreg = MTIO_DSREG_REST;
5419 	xpt_release_ccb(ccb);
5420 
5421 	/*
5422 	 * If the error was Illegal Request, then the device doesn't support
5423 	 * RESERVE/RELEASE. This is not an error.
5424 	 */
5425 	if (error == EINVAL) {
5426 		error = 0;
5427 	}
5428 
5429 	return (error);
5430 }
5431 
5432 static int
saloadunload(struct cam_periph * periph,int load)5433 saloadunload(struct cam_periph *periph, int load)
5434 {
5435 	union	ccb *ccb;
5436 	struct	sa_softc *softc;
5437 	int	error;
5438 
5439 	softc = (struct sa_softc *)periph->softc;
5440 
5441 	ccb = cam_periph_getccb(periph, 1);
5442 
5443 	/* It is safe to retry this operation */
5444 	scsi_load_unload(&ccb->csio, 5, NULL, MSG_SIMPLE_Q_TAG, FALSE,
5445 	    FALSE, FALSE, load, SSD_FULL_SIZE,
5446 	    softc->timeout_info[SA_TIMEOUT_LOAD]);
5447 
5448 	softc->dsreg = (load)? MTIO_DSREG_LD : MTIO_DSREG_UNL;
5449 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
5450 	softc->dsreg = MTIO_DSREG_REST;
5451 	xpt_release_ccb(ccb);
5452 
5453 	if (error || load == 0) {
5454 		softc->partition = softc->fileno = softc->blkno = (daddr_t) -1;
5455 		softc->rep_fileno = softc->rep_blkno = (daddr_t) -1;
5456 	} else if (error == 0) {
5457 		softc->partition = softc->fileno = softc->blkno = (daddr_t) 0;
5458 		sagetpos(periph);
5459 	}
5460 	return (error);
5461 }
5462 
5463 static int
saerase(struct cam_periph * periph,int longerase)5464 saerase(struct cam_periph *periph, int longerase)
5465 {
5466 
5467 	union	ccb *ccb;
5468 	struct	sa_softc *softc;
5469 	int error;
5470 
5471 	softc = (struct sa_softc *)periph->softc;
5472 	if (softc->open_rdonly)
5473 		return (EBADF);
5474 
5475 	ccb = cam_periph_getccb(periph, 1);
5476 
5477 	scsi_erase(&ccb->csio, 1, NULL, MSG_SIMPLE_Q_TAG, FALSE, longerase,
5478 	    SSD_FULL_SIZE, softc->timeout_info[SA_TIMEOUT_ERASE]);
5479 
5480 	softc->dsreg = MTIO_DSREG_ZER;
5481 	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
5482 	softc->dsreg = MTIO_DSREG_REST;
5483 
5484 	xpt_release_ccb(ccb);
5485 	return (error);
5486 }
5487 
5488 /*
5489  * Fill an sbuf with density data in XML format.  This particular macro
5490  * works for multi-byte integer fields.
5491  *
5492  * Note that 1 byte fields aren't supported here.  The reason is that the
5493  * compiler does not evaluate the sizeof(), and assumes that any of the
5494  * sizes are possible for a given field.  So passing in a multi-byte
5495  * field will result in a warning that the assignment makes an integer
5496  * from a pointer without a cast, if there is an assignment in the 1 byte
5497  * case.
5498  */
5499 #define	SAFILLDENSSB(dens_data, sb, indent, field, desc_remain, 	\
5500 		     len_to_go, cur_offset, desc){			\
5501 	size_t cur_field_len;						\
5502 									\
5503 	cur_field_len = sizeof(dens_data->field);			\
5504 	if (desc_remain < cur_field_len) {				\
5505 		len_to_go -= desc_remain;				\
5506 		cur_offset += desc_remain;				\
5507 		continue;						\
5508 	}								\
5509 	len_to_go -= cur_field_len;					\
5510 	cur_offset += cur_field_len;					\
5511 	desc_remain -= cur_field_len;					\
5512 									\
5513 	switch (sizeof(dens_data->field)) {				\
5514 	case 1:								\
5515 		KASSERT(1 == 0, ("Programmer error, invalid 1 byte "	\
5516 			"field width for SAFILLDENSFIELD"));		\
5517 		break;							\
5518 	case 2:								\
5519 		SASBADDUINTDESC(sb, indent,				\
5520 		    scsi_2btoul(dens_data->field), %u, field, desc);	\
5521 		break;							\
5522 	case 3:								\
5523 		SASBADDUINTDESC(sb, indent,				\
5524 		    scsi_3btoul(dens_data->field), %u, field, desc);	\
5525 		break;							\
5526 	case 4:								\
5527 		SASBADDUINTDESC(sb, indent,				\
5528 		    scsi_4btoul(dens_data->field), %u, field, desc);	\
5529 		break;							\
5530 	case 8:								\
5531 		SASBADDUINTDESC(sb, indent, 				\
5532 		    (uintmax_t)scsi_8btou64(dens_data->field),	%ju, 	\
5533 		    field, desc);					\
5534 		break;							\
5535 	default:							\
5536 		break;							\
5537 	}								\
5538 };
5539 /*
5540  * Fill an sbuf with density data in XML format.  This particular macro
5541  * works for strings.
5542  */
5543 #define	SAFILLDENSSBSTR(dens_data, sb, indent, field, desc_remain, 	\
5544 			len_to_go, cur_offset, desc){			\
5545 	size_t cur_field_len;						\
5546 	char tmpstr[32];						\
5547 									\
5548 	cur_field_len = sizeof(dens_data->field);			\
5549 	if (desc_remain < cur_field_len) {				\
5550 		len_to_go -= desc_remain;				\
5551 		cur_offset += desc_remain;				\
5552 		continue;						\
5553 	}								\
5554 	len_to_go -= cur_field_len;					\
5555 	cur_offset += cur_field_len;					\
5556 	desc_remain -= cur_field_len;					\
5557 									\
5558 	cam_strvis(tmpstr, dens_data->field,				\
5559 	    sizeof(dens_data->field), sizeof(tmpstr));			\
5560 	SASBADDVARSTRDESC(sb, indent, tmpstr, %s, field,		\
5561 	    strlen(tmpstr) + 1, desc);					\
5562 };
5563 
5564 /*
5565  * Fill an sbuf with density data descriptors.
5566  */
5567 static void
safilldenstypesb(struct sbuf * sb,int * indent,uint8_t * buf,int buf_len,int is_density)5568 safilldenstypesb(struct sbuf *sb, int *indent, uint8_t *buf, int buf_len,
5569     int is_density)
5570 {
5571 	struct scsi_density_hdr *hdr;
5572 	uint32_t hdr_len;
5573 	int len_to_go, cur_offset;
5574 	int length_offset;
5575 	int num_reports, need_close;
5576 
5577 	/*
5578 	 * We need at least the header length.  Note that this isn't an
5579 	 * error, not all tape drives will have every data type.
5580 	 */
5581 	if (buf_len < sizeof(*hdr))
5582 		goto bailout;
5583 
5584 	hdr = (struct scsi_density_hdr *)buf;
5585 	hdr_len = scsi_2btoul(hdr->length);
5586 	len_to_go = min(buf_len - sizeof(*hdr), hdr_len);
5587 	if (is_density) {
5588 		length_offset = __offsetof(struct scsi_density_data,
5589 		    bits_per_mm);
5590 	} else {
5591 		length_offset = __offsetof(struct scsi_medium_type_data,
5592 		    num_density_codes);
5593 	}
5594 	cur_offset = sizeof(*hdr);
5595 
5596 	num_reports = 0;
5597 	need_close = 0;
5598 
5599 	while (len_to_go > length_offset) {
5600 		struct scsi_density_data *dens_data;
5601 		struct scsi_medium_type_data *type_data;
5602 		int desc_remain;
5603 		size_t cur_field_len;
5604 
5605 		dens_data = NULL;
5606 		type_data = NULL;
5607 
5608 		if (is_density) {
5609 			dens_data =(struct scsi_density_data *)&buf[cur_offset];
5610 			if (dens_data->byte2 & SDD_DLV)
5611 				desc_remain = scsi_2btoul(dens_data->length);
5612 			else
5613 				desc_remain = SDD_DEFAULT_LENGTH -
5614 				    length_offset;
5615 		} else {
5616 			type_data = (struct scsi_medium_type_data *)
5617 			    &buf[cur_offset];
5618 			desc_remain = scsi_2btoul(type_data->length);
5619 		}
5620 
5621 		len_to_go -= length_offset;
5622 		desc_remain = min(desc_remain, len_to_go);
5623 		cur_offset += length_offset;
5624 
5625 		if (need_close != 0) {
5626 			SASBENDNODE(sb, *indent, density_entry);
5627 		}
5628 
5629 		SASBADDNODENUM(sb, *indent, density_entry, num_reports);
5630 		num_reports++;
5631 		need_close = 1;
5632 
5633 		if (is_density) {
5634 			SASBADDUINTDESC(sb, *indent,
5635 			    dens_data->primary_density_code, %u,
5636 			    primary_density_code, "Primary Density Code");
5637 			SASBADDUINTDESC(sb, *indent,
5638 			    dens_data->secondary_density_code, %u,
5639 			    secondary_density_code, "Secondary Density Code");
5640 			SASBADDUINTDESC(sb, *indent,
5641 			    dens_data->byte2 & ~SDD_DLV, %#x, density_flags,
5642 			    "Density Flags");
5643 
5644 			SAFILLDENSSB(dens_data, sb, *indent, bits_per_mm,
5645 			    desc_remain, len_to_go, cur_offset, "Bits per mm");
5646 			SAFILLDENSSB(dens_data, sb, *indent, media_width,
5647 			    desc_remain, len_to_go, cur_offset, "Media width");
5648 			SAFILLDENSSB(dens_data, sb, *indent, tracks,
5649 			    desc_remain, len_to_go, cur_offset,
5650 			    "Number of Tracks");
5651 			SAFILLDENSSB(dens_data, sb, *indent, capacity,
5652 			    desc_remain, len_to_go, cur_offset, "Capacity");
5653 
5654 			SAFILLDENSSBSTR(dens_data, sb, *indent, assigning_org,
5655 			    desc_remain, len_to_go, cur_offset,
5656 			    "Assigning Organization");
5657 
5658 			SAFILLDENSSBSTR(dens_data, sb, *indent, density_name,
5659 			    desc_remain, len_to_go, cur_offset, "Density Name");
5660 
5661 			SAFILLDENSSBSTR(dens_data, sb, *indent, description,
5662 			    desc_remain, len_to_go, cur_offset, "Description");
5663 		} else {
5664 			int i;
5665 
5666 			SASBADDUINTDESC(sb, *indent, type_data->medium_type,
5667 			    %u, medium_type, "Medium Type");
5668 
5669 			cur_field_len =
5670 			    __offsetof(struct scsi_medium_type_data,
5671 				       media_width) -
5672 			    __offsetof(struct scsi_medium_type_data,
5673 				       num_density_codes);
5674 
5675 			if (desc_remain < cur_field_len) {
5676 				len_to_go -= desc_remain;
5677 				cur_offset += desc_remain;
5678 				continue;
5679 			}
5680 			len_to_go -= cur_field_len;
5681 			cur_offset += cur_field_len;
5682 			desc_remain -= cur_field_len;
5683 
5684 			SASBADDINTDESC(sb, *indent,
5685 			    type_data->num_density_codes, %d,
5686 			    num_density_codes, "Number of Density Codes");
5687 			SASBADDNODE(sb, *indent, density_code_list);
5688 			for (i = 0; i < type_data->num_density_codes;
5689 			     i++) {
5690 				SASBADDUINTDESC(sb, *indent,
5691 				    type_data->primary_density_codes[i], %u,
5692 				    density_code, "Density Code");
5693 			}
5694 			SASBENDNODE(sb, *indent, density_code_list);
5695 
5696 			SAFILLDENSSB(type_data, sb, *indent, media_width,
5697 			    desc_remain, len_to_go, cur_offset,
5698 			    "Media width");
5699 			SAFILLDENSSB(type_data, sb, *indent, medium_length,
5700 			    desc_remain, len_to_go, cur_offset,
5701 			    "Medium length");
5702 
5703 			/*
5704 			 * Account for the two reserved bytes.
5705 			 */
5706 			cur_field_len = sizeof(type_data->reserved2);
5707 			if (desc_remain < cur_field_len) {
5708 				len_to_go -= desc_remain;
5709 				cur_offset += desc_remain;
5710 				continue;
5711 			}
5712 			len_to_go -= cur_field_len;
5713 			cur_offset += cur_field_len;
5714 			desc_remain -= cur_field_len;
5715 
5716 			SAFILLDENSSBSTR(type_data, sb, *indent, assigning_org,
5717 			    desc_remain, len_to_go, cur_offset,
5718 			    "Assigning Organization");
5719 			SAFILLDENSSBSTR(type_data, sb, *indent,
5720 			    medium_type_name, desc_remain, len_to_go,
5721 			    cur_offset, "Medium type name");
5722 			SAFILLDENSSBSTR(type_data, sb, *indent, description,
5723 			    desc_remain, len_to_go, cur_offset, "Description");
5724 		}
5725 	}
5726 	if (need_close != 0) {
5727 		SASBENDNODE(sb, *indent, density_entry);
5728 	}
5729 
5730 bailout:
5731 	return;
5732 }
5733 
5734 /*
5735  * Fill an sbuf with density data information
5736  */
5737 static void
safilldensitysb(struct sa_softc * softc,int * indent,struct sbuf * sb)5738 safilldensitysb(struct sa_softc *softc, int *indent, struct sbuf *sb)
5739 {
5740 	int i, is_density;
5741 
5742 	SASBADDNODE(sb, *indent, mtdensity);
5743 	SASBADDUINTDESC(sb, *indent, softc->media_density, %u, media_density,
5744 	    "Current Medium Density");
5745 	is_density = 0;
5746 	for (i = 0; i < SA_DENSITY_TYPES; i++) {
5747 		int tmpint;
5748 
5749 		if (softc->density_info_valid[i] == 0)
5750 			continue;
5751 
5752 		SASBADDNODE(sb, *indent, density_report);
5753 		if (softc->density_type_bits[i] & SRDS_MEDIUM_TYPE) {
5754 			tmpint = 1;
5755 			is_density = 0;
5756 		} else {
5757 			tmpint = 0;
5758 			is_density = 1;
5759 		}
5760 		SASBADDINTDESC(sb, *indent, tmpint, %d, medium_type_report,
5761 		    "Medium type report");
5762 
5763 		if (softc->density_type_bits[i] & SRDS_MEDIA)
5764 			tmpint = 1;
5765 		else
5766 			tmpint = 0;
5767 		SASBADDINTDESC(sb, *indent, tmpint, %d, media_report,
5768 		    "Media report");
5769 
5770 		safilldenstypesb(sb, indent, softc->density_info[i],
5771 		    softc->density_info_valid[i], is_density);
5772 		SASBENDNODE(sb, *indent, density_report);
5773 	}
5774 	SASBENDNODE(sb, *indent, mtdensity);
5775 }
5776 
5777 /*
5778  * Given a completed REPORT SUPPORTED OPERATION CODES command with timeout
5779  * descriptors, go through the descriptors and set the sa(4) driver
5780  * timeouts to the recommended values.
5781  */
5782 static void
saloadtimeouts(struct sa_softc * softc,union ccb * ccb)5783 saloadtimeouts(struct sa_softc *softc, union ccb *ccb)
5784 {
5785 	uint32_t valid_len, avail_len = 0, used_len = 0;
5786 	struct scsi_report_supported_opcodes_all *hdr;
5787 	struct scsi_report_supported_opcodes_descr *desc;
5788 	uint8_t *buf;
5789 
5790 	hdr = (struct scsi_report_supported_opcodes_all *)ccb->csio.data_ptr;
5791 	valid_len = ccb->csio.dxfer_len - ccb->csio.resid;
5792 
5793 	if (valid_len < sizeof(*hdr))
5794 		return;
5795 
5796 	avail_len = scsi_4btoul(hdr->length) + sizeof(hdr->length);
5797 	if ((avail_len != 0)
5798 	 && (avail_len > valid_len)) {
5799 		xpt_print(softc->periph->path, "WARNING: available timeout "
5800 		    "descriptor len %zu > valid len %u\n", avail_len,valid_len);
5801 	}
5802 
5803 	used_len = sizeof(hdr->length);
5804 	avail_len = MIN(avail_len, valid_len - sizeof(*hdr));
5805 	buf = ccb->csio.data_ptr;
5806 	while ((avail_len - used_len) > sizeof(*desc)) {
5807 		struct scsi_report_supported_opcodes_timeout *td;
5808 		uint32_t td_len;
5809 		uint32_t rec_time;
5810 		uint8_t *cur_ptr;
5811 
5812 		cur_ptr = &buf[used_len];
5813 		desc = (struct scsi_report_supported_opcodes_descr *)cur_ptr;
5814 
5815 		used_len += sizeof(*desc);
5816 		/* If there's no timeout descriptor, keep going */
5817 		if ((desc->flags & RSO_CTDP) == 0)
5818 			continue;
5819 
5820 		/*
5821 		 * If we don't have enough space to fit a timeout
5822 		 * descriptor then we're done.
5823 		 */
5824 		if ((avail_len - used_len) < sizeof(*td)) {
5825 			used_len = avail_len;
5826 			continue;
5827 		}
5828 
5829 		cur_ptr = &buf[used_len];
5830 		td = (struct scsi_report_supported_opcodes_timeout *)cur_ptr;
5831 		td_len = scsi_2btoul(td->length);
5832 		td_len += sizeof(td->length);
5833 		used_len += td_len;
5834 
5835 		if (td_len < sizeof(*td))
5836 			continue;
5837 
5838 		/*
5839 		 * Use the recommended timeout.  The nominal time is the
5840 		 * time to wait before querying for status.
5841 		 */
5842 		rec_time = scsi_4btoul(td->recommended_time);
5843 
5844 		/*
5845 		 * Our timeouts are set in thousandths of a seconds.
5846 		 */
5847 		rec_time *= 1000;
5848 
5849 		switch(desc->opcode) {
5850 		case ERASE:
5851 			softc->timeout_info[SA_TIMEOUT_ERASE] = rec_time;
5852 			break;
5853 		case LOAD_UNLOAD:
5854 			softc->timeout_info[SA_TIMEOUT_LOAD] = rec_time;
5855 			break;
5856 		case LOCATE:
5857 		case LOCATE_16:
5858 			/*
5859 			 * We are assuming these are the same timeout.
5860 			 */
5861 			softc->timeout_info[SA_TIMEOUT_LOCATE] = rec_time;
5862 			break;
5863 		case MODE_SELECT_6:
5864 		case MODE_SELECT_10:
5865 			/*
5866 			 * We are assuming these are the same timeout.
5867 			 */
5868 			softc->timeout_info[SA_TIMEOUT_MODE_SELECT] = rec_time;
5869 			break;
5870 		case MODE_SENSE_6:
5871 		case MODE_SENSE_10:
5872 			/*
5873 			 * We are assuming these are the same timeout.
5874 			 */
5875 			softc->timeout_info[SA_TIMEOUT_MODE_SENSE] = rec_time;
5876 			break;
5877 		case PREVENT_ALLOW:
5878 			softc->timeout_info[SA_TIMEOUT_PREVENT] = rec_time;
5879 			break;
5880 		case SA_READ:
5881 			softc->timeout_info[SA_TIMEOUT_READ] = rec_time;
5882 			break;
5883 		case READ_BLOCK_LIMITS:
5884 			softc->timeout_info[SA_TIMEOUT_READ_BLOCK_LIMITS] =
5885 			    rec_time;
5886 			break;
5887 		case READ_POSITION:
5888 			/*
5889 			 * Note that this may show up multiple times for
5890 			 * the short form, long form and extended form
5891 			 * service actions.  We're assuming they are all
5892 			 * the same.
5893 			 */
5894 			softc->timeout_info[SA_TIMEOUT_READ_POSITION] =rec_time;
5895 			break;
5896 		case REPORT_DENSITY_SUPPORT:
5897 			softc->timeout_info[SA_TIMEOUT_REP_DENSITY] = rec_time;
5898 			break;
5899 		case RESERVE_UNIT:
5900 		case RELEASE_UNIT:
5901 			/* We are assuming these are the same timeout.*/
5902 			softc->timeout_info[SA_TIMEOUT_RESERVE] = rec_time;
5903 			break;
5904 		case REWIND:
5905 			softc->timeout_info[SA_TIMEOUT_REWIND] = rec_time;
5906 			break;
5907 		case SPACE:
5908 			softc->timeout_info[SA_TIMEOUT_SPACE] = rec_time;
5909 			break;
5910 		case TEST_UNIT_READY:
5911 			softc->timeout_info[SA_TIMEOUT_TUR] = rec_time;
5912 			break;
5913 		case SA_WRITE:
5914 			softc->timeout_info[SA_TIMEOUT_WRITE] = rec_time;
5915 			break;
5916 		case WRITE_FILEMARKS:
5917 			softc->timeout_info[SA_TIMEOUT_WRITE_FILEMARKS] =
5918 			    rec_time;
5919 			break;
5920 		default:
5921 			/*
5922 			 * We have explicit cases for all of the timeouts
5923 			 * we use.
5924 			 */
5925 			break;
5926 		}
5927 	}
5928 }
5929 
5930 #endif /* _KERNEL */
5931 
5932 /*
5933  * Read tape block limits command.
5934  */
5935 void
scsi_read_block_limits(struct ccb_scsiio * csio,uint32_t retries,void (* cbfcnp)(struct cam_periph *,union ccb *),uint8_t tag_action,struct scsi_read_block_limits_data * rlimit_buf,uint8_t sense_len,uint32_t timeout)5936 scsi_read_block_limits(struct ccb_scsiio *csio, uint32_t retries,
5937 		   void (*cbfcnp)(struct cam_periph *, union ccb *),
5938 		   uint8_t tag_action,
5939 		   struct scsi_read_block_limits_data *rlimit_buf,
5940 		   uint8_t sense_len, uint32_t timeout)
5941 {
5942 	struct scsi_read_block_limits *scsi_cmd;
5943 
5944 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_IN, tag_action,
5945 	     (uint8_t *)rlimit_buf, sizeof(*rlimit_buf), sense_len,
5946 	     sizeof(*scsi_cmd), timeout);
5947 
5948 	scsi_cmd = (struct scsi_read_block_limits *)&csio->cdb_io.cdb_bytes;
5949 	bzero(scsi_cmd, sizeof(*scsi_cmd));
5950 	scsi_cmd->opcode = READ_BLOCK_LIMITS;
5951 }
5952 
5953 void
scsi_sa_read_write(struct ccb_scsiio * csio,uint32_t retries,void (* cbfcnp)(struct cam_periph *,union ccb *),uint8_t tag_action,int readop,int sli,int fixed,uint32_t length,uint8_t * data_ptr,uint32_t dxfer_len,uint8_t sense_len,uint32_t timeout)5954 scsi_sa_read_write(struct ccb_scsiio *csio, uint32_t retries,
5955 		   void (*cbfcnp)(struct cam_periph *, union ccb *),
5956 		   uint8_t tag_action, int readop, int sli,
5957 		   int fixed, uint32_t length, uint8_t *data_ptr,
5958 		   uint32_t dxfer_len, uint8_t sense_len, uint32_t timeout)
5959 {
5960 	struct scsi_sa_rw *scsi_cmd;
5961 	int read;
5962 
5963 	read = (readop & SCSI_RW_DIRMASK) == SCSI_RW_READ;
5964 
5965 	scsi_cmd = (struct scsi_sa_rw *)&csio->cdb_io.cdb_bytes;
5966 	scsi_cmd->opcode = read ? SA_READ : SA_WRITE;
5967 	scsi_cmd->sli_fixed = 0;
5968 	if (sli && read)
5969 		scsi_cmd->sli_fixed |= SAR_SLI;
5970 	if (fixed)
5971 		scsi_cmd->sli_fixed |= SARW_FIXED;
5972 	scsi_ulto3b(length, scsi_cmd->length);
5973 	scsi_cmd->control = 0;
5974 
5975 	cam_fill_csio(csio, retries, cbfcnp, (read ? CAM_DIR_IN : CAM_DIR_OUT) |
5976 	    ((readop & SCSI_RW_BIO) != 0 ? CAM_DATA_BIO : 0),
5977 	    tag_action, data_ptr, dxfer_len, sense_len,
5978 	    sizeof(*scsi_cmd), timeout);
5979 }
5980 
5981 void
scsi_load_unload(struct ccb_scsiio * csio,uint32_t retries,void (* cbfcnp)(struct cam_periph *,union ccb *),uint8_t tag_action,int immediate,int eot,int reten,int load,uint8_t sense_len,uint32_t timeout)5982 scsi_load_unload(struct ccb_scsiio *csio, uint32_t retries,
5983 		 void (*cbfcnp)(struct cam_periph *, union ccb *),
5984 		 uint8_t tag_action, int immediate, int eot,
5985 		 int reten, int load, uint8_t sense_len,
5986 		 uint32_t timeout)
5987 {
5988 	struct scsi_load_unload *scsi_cmd;
5989 
5990 	scsi_cmd = (struct scsi_load_unload *)&csio->cdb_io.cdb_bytes;
5991 	bzero(scsi_cmd, sizeof(*scsi_cmd));
5992 	scsi_cmd->opcode = LOAD_UNLOAD;
5993 	if (immediate)
5994 		scsi_cmd->immediate = SLU_IMMED;
5995 	if (eot)
5996 		scsi_cmd->eot_reten_load |= SLU_EOT;
5997 	if (reten)
5998 		scsi_cmd->eot_reten_load |= SLU_RETEN;
5999 	if (load)
6000 		scsi_cmd->eot_reten_load |= SLU_LOAD;
6001 
6002 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action,
6003 	    NULL, 0, sense_len, sizeof(*scsi_cmd), timeout);
6004 }
6005 
6006 void
scsi_rewind(struct ccb_scsiio * csio,uint32_t retries,void (* cbfcnp)(struct cam_periph *,union ccb *),uint8_t tag_action,int immediate,uint8_t sense_len,uint32_t timeout)6007 scsi_rewind(struct ccb_scsiio *csio, uint32_t retries,
6008 	    void (*cbfcnp)(struct cam_periph *, union ccb *),
6009 	    uint8_t tag_action, int immediate, uint8_t sense_len,
6010 	    uint32_t timeout)
6011 {
6012 	struct scsi_rewind *scsi_cmd;
6013 
6014 	scsi_cmd = (struct scsi_rewind *)&csio->cdb_io.cdb_bytes;
6015 	bzero(scsi_cmd, sizeof(*scsi_cmd));
6016 	scsi_cmd->opcode = REWIND;
6017 	if (immediate)
6018 		scsi_cmd->immediate = SREW_IMMED;
6019 
6020 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action, NULL,
6021 	    0, sense_len, sizeof(*scsi_cmd), timeout);
6022 }
6023 
6024 void
scsi_space(struct ccb_scsiio * csio,uint32_t retries,void (* cbfcnp)(struct cam_periph *,union ccb *),uint8_t tag_action,scsi_space_code code,uint32_t count,uint8_t sense_len,uint32_t timeout)6025 scsi_space(struct ccb_scsiio *csio, uint32_t retries,
6026 	   void (*cbfcnp)(struct cam_periph *, union ccb *),
6027 	   uint8_t tag_action, scsi_space_code code,
6028 	   uint32_t count, uint8_t sense_len, uint32_t timeout)
6029 {
6030 	struct scsi_space *scsi_cmd;
6031 
6032 	scsi_cmd = (struct scsi_space *)&csio->cdb_io.cdb_bytes;
6033 	scsi_cmd->opcode = SPACE;
6034 	scsi_cmd->code = code;
6035 	scsi_ulto3b(count, scsi_cmd->count);
6036 	scsi_cmd->control = 0;
6037 
6038 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action, NULL,
6039 	    0, sense_len, sizeof(*scsi_cmd), timeout);
6040 }
6041 
6042 void
scsi_write_filemarks(struct ccb_scsiio * csio,uint32_t retries,void (* cbfcnp)(struct cam_periph *,union ccb *),uint8_t tag_action,int immediate,int setmark,uint32_t num_marks,uint8_t sense_len,uint32_t timeout)6043 scsi_write_filemarks(struct ccb_scsiio *csio, uint32_t retries,
6044 		     void (*cbfcnp)(struct cam_periph *, union ccb *),
6045 		     uint8_t tag_action, int immediate, int setmark,
6046 		     uint32_t num_marks, uint8_t sense_len,
6047 		     uint32_t timeout)
6048 {
6049 	struct scsi_write_filemarks *scsi_cmd;
6050 
6051 	scsi_cmd = (struct scsi_write_filemarks *)&csio->cdb_io.cdb_bytes;
6052 	bzero(scsi_cmd, sizeof(*scsi_cmd));
6053 	scsi_cmd->opcode = WRITE_FILEMARKS;
6054 	if (immediate)
6055 		scsi_cmd->byte2 |= SWFMRK_IMMED;
6056 	if (setmark)
6057 		scsi_cmd->byte2 |= SWFMRK_WSMK;
6058 
6059 	scsi_ulto3b(num_marks, scsi_cmd->num_marks);
6060 
6061 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action, NULL,
6062 	    0, sense_len, sizeof(*scsi_cmd), timeout);
6063 }
6064 
6065 /*
6066  * The reserve and release unit commands differ only by their opcodes.
6067  */
6068 void
scsi_reserve_release_unit(struct ccb_scsiio * csio,uint32_t retries,void (* cbfcnp)(struct cam_periph *,union ccb *),uint8_t tag_action,int third_party,int third_party_id,uint8_t sense_len,uint32_t timeout,int reserve)6069 scsi_reserve_release_unit(struct ccb_scsiio *csio, uint32_t retries,
6070 			  void (*cbfcnp)(struct cam_periph *, union ccb *),
6071 			  uint8_t tag_action, int third_party,
6072 			  int third_party_id, uint8_t sense_len,
6073 			  uint32_t timeout, int reserve)
6074 {
6075 	struct scsi_reserve_release_unit *scsi_cmd;
6076 
6077 	scsi_cmd = (struct scsi_reserve_release_unit *)&csio->cdb_io.cdb_bytes;
6078 	bzero(scsi_cmd, sizeof(*scsi_cmd));
6079 
6080 	if (reserve)
6081 		scsi_cmd->opcode = RESERVE_UNIT;
6082 	else
6083 		scsi_cmd->opcode = RELEASE_UNIT;
6084 
6085 	if (third_party) {
6086 		scsi_cmd->lun_thirdparty |= SRRU_3RD_PARTY;
6087 		scsi_cmd->lun_thirdparty |=
6088 			((third_party_id << SRRU_3RD_SHAMT) & SRRU_3RD_MASK);
6089 	}
6090 
6091 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action, NULL,
6092 	    0, sense_len, sizeof(*scsi_cmd), timeout);
6093 }
6094 
6095 void
scsi_erase(struct ccb_scsiio * csio,uint32_t retries,void (* cbfcnp)(struct cam_periph *,union ccb *),uint8_t tag_action,int immediate,int long_erase,uint8_t sense_len,uint32_t timeout)6096 scsi_erase(struct ccb_scsiio *csio, uint32_t retries,
6097 	   void (*cbfcnp)(struct cam_periph *, union ccb *),
6098 	   uint8_t tag_action, int immediate, int long_erase,
6099 	   uint8_t sense_len, uint32_t timeout)
6100 {
6101 	struct scsi_erase *scsi_cmd;
6102 
6103 	scsi_cmd = (struct scsi_erase *)&csio->cdb_io.cdb_bytes;
6104 	bzero(scsi_cmd, sizeof(*scsi_cmd));
6105 
6106 	scsi_cmd->opcode = ERASE;
6107 
6108 	if (immediate)
6109 		scsi_cmd->lun_imm_long |= SE_IMMED;
6110 
6111 	if (long_erase)
6112 		scsi_cmd->lun_imm_long |= SE_LONG;
6113 
6114 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action, NULL,
6115 	    0, sense_len, sizeof(*scsi_cmd), timeout);
6116 }
6117 
6118 /*
6119  * Read Tape Position command.
6120  */
6121 void
scsi_read_position(struct ccb_scsiio * csio,uint32_t retries,void (* cbfcnp)(struct cam_periph *,union ccb *),uint8_t tag_action,int hardsoft,struct scsi_tape_position_data * sbp,uint8_t sense_len,uint32_t timeout)6122 scsi_read_position(struct ccb_scsiio *csio, uint32_t retries,
6123 		   void (*cbfcnp)(struct cam_periph *, union ccb *),
6124 		   uint8_t tag_action, int hardsoft,
6125 		   struct scsi_tape_position_data *sbp,
6126 		   uint8_t sense_len, uint32_t timeout)
6127 {
6128 	struct scsi_tape_read_position *scmd;
6129 
6130 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_IN, tag_action,
6131 	    (uint8_t *)sbp, sizeof (*sbp), sense_len, sizeof(*scmd), timeout);
6132 	scmd = (struct scsi_tape_read_position *)&csio->cdb_io.cdb_bytes;
6133 	bzero(scmd, sizeof(*scmd));
6134 	scmd->opcode = READ_POSITION;
6135 	scmd->byte1 = hardsoft;
6136 }
6137 
6138 /*
6139  * Read Tape Position command.
6140  */
6141 void
scsi_read_position_10(struct ccb_scsiio * csio,uint32_t retries,void (* cbfcnp)(struct cam_periph *,union ccb *),uint8_t tag_action,int service_action,uint8_t * data_ptr,uint32_t length,uint32_t sense_len,uint32_t timeout)6142 scsi_read_position_10(struct ccb_scsiio *csio, uint32_t retries,
6143 		      void (*cbfcnp)(struct cam_periph *, union ccb *),
6144 		      uint8_t tag_action, int service_action,
6145 		      uint8_t *data_ptr, uint32_t length,
6146 		      uint32_t sense_len, uint32_t timeout)
6147 {
6148 	struct scsi_tape_read_position *scmd;
6149 
6150 	cam_fill_csio(csio,
6151 		      retries,
6152 		      cbfcnp,
6153 		      /*flags*/CAM_DIR_IN,
6154 		      tag_action,
6155 		      /*data_ptr*/data_ptr,
6156 		      /*dxfer_len*/length,
6157 		      sense_len,
6158 		      sizeof(*scmd),
6159 		      timeout);
6160 
6161 	scmd = (struct scsi_tape_read_position *)&csio->cdb_io.cdb_bytes;
6162 	bzero(scmd, sizeof(*scmd));
6163 	scmd->opcode = READ_POSITION;
6164 	scmd->byte1 = service_action;
6165 	/*
6166 	 * The length is only currently set (as of SSC4r03) if the extended
6167 	 * form is specified.  The other forms have fixed lengths.
6168 	 */
6169 	if (service_action == SA_RPOS_EXTENDED_FORM)
6170 		scsi_ulto2b(length, scmd->length);
6171 }
6172 
6173 /*
6174  * Set Tape Position command.
6175  */
6176 void
scsi_set_position(struct ccb_scsiio * csio,uint32_t retries,void (* cbfcnp)(struct cam_periph *,union ccb *),uint8_t tag_action,int hardsoft,uint32_t blkno,uint8_t sense_len,uint32_t timeout)6177 scsi_set_position(struct ccb_scsiio *csio, uint32_t retries,
6178 		   void (*cbfcnp)(struct cam_periph *, union ccb *),
6179 		   uint8_t tag_action, int hardsoft, uint32_t blkno,
6180 		   uint8_t sense_len, uint32_t timeout)
6181 {
6182 	struct scsi_tape_locate *scmd;
6183 
6184 	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action,
6185 	    (uint8_t *)NULL, 0, sense_len, sizeof(*scmd), timeout);
6186 	scmd = (struct scsi_tape_locate *)&csio->cdb_io.cdb_bytes;
6187 	bzero(scmd, sizeof(*scmd));
6188 	scmd->opcode = LOCATE;
6189 	if (hardsoft)
6190 		scmd->byte1 |= SA_SPOS_BT;
6191 	scsi_ulto4b(blkno, scmd->blkaddr);
6192 }
6193 
6194 /*
6195  * XXX KDM figure out how to make a compatibility function.
6196  */
6197 void
scsi_locate_10(struct ccb_scsiio * csio,uint32_t retries,void (* cbfcnp)(struct cam_periph *,union ccb *),uint8_t tag_action,int immed,int cp,int hard,int64_t partition,uint32_t block_address,int sense_len,uint32_t timeout)6198 scsi_locate_10(struct ccb_scsiio *csio, uint32_t retries,
6199 	       void (*cbfcnp)(struct cam_periph *, union ccb *),
6200 	       uint8_t tag_action, int immed, int cp, int hard,
6201 	       int64_t partition, uint32_t block_address,
6202 	       int sense_len, uint32_t timeout)
6203 {
6204 	struct scsi_tape_locate *scmd;
6205 
6206 	cam_fill_csio(csio,
6207 		      retries,
6208 		      cbfcnp,
6209 		      CAM_DIR_NONE,
6210 		      tag_action,
6211 		      /*data_ptr*/ NULL,
6212 		      /*dxfer_len*/ 0,
6213 		      sense_len,
6214 		      sizeof(*scmd),
6215 		      timeout);
6216 	scmd = (struct scsi_tape_locate *)&csio->cdb_io.cdb_bytes;
6217 	bzero(scmd, sizeof(*scmd));
6218 	scmd->opcode = LOCATE;
6219 	if (immed)
6220 		scmd->byte1 |= SA_SPOS_IMMED;
6221 	if (cp)
6222 		scmd->byte1 |= SA_SPOS_CP;
6223 	if (hard)
6224 		scmd->byte1 |= SA_SPOS_BT;
6225 	scsi_ulto4b(block_address, scmd->blkaddr);
6226 	scmd->partition = partition;
6227 }
6228 
6229 void
scsi_locate_16(struct ccb_scsiio * csio,uint32_t retries,void (* cbfcnp)(struct cam_periph *,union ccb *),uint8_t tag_action,int immed,int cp,uint8_t dest_type,int bam,int64_t partition,uint64_t logical_id,int sense_len,uint32_t timeout)6230 scsi_locate_16(struct ccb_scsiio *csio, uint32_t retries,
6231 	       void (*cbfcnp)(struct cam_periph *, union ccb *),
6232 	       uint8_t tag_action, int immed, int cp, uint8_t dest_type,
6233 	       int bam, int64_t partition, uint64_t logical_id,
6234 	       int sense_len, uint32_t timeout)
6235 {
6236 
6237 	struct scsi_locate_16 *scsi_cmd;
6238 
6239 	cam_fill_csio(csio,
6240 		      retries,
6241 		      cbfcnp,
6242 		      /*flags*/CAM_DIR_NONE,
6243 		      tag_action,
6244 		      /*data_ptr*/NULL,
6245 		      /*dxfer_len*/0,
6246 		      sense_len,
6247 		      sizeof(*scsi_cmd),
6248 		      timeout);
6249 
6250 	scsi_cmd = (struct scsi_locate_16 *)&csio->cdb_io.cdb_bytes;
6251 	bzero(scsi_cmd, sizeof(*scsi_cmd));
6252 	scsi_cmd->opcode = LOCATE_16;
6253 	if (immed)
6254 		scsi_cmd->byte1 |= SA_LC_IMMEDIATE;
6255 	if (cp)
6256 		scsi_cmd->byte1 |= SA_LC_CP;
6257 	scsi_cmd->byte1 |= (dest_type << SA_LC_DEST_TYPE_SHIFT);
6258 
6259 	scsi_cmd->byte2 |= bam;
6260 	scsi_cmd->partition = partition;
6261 	scsi_u64to8b(logical_id, scsi_cmd->logical_id);
6262 }
6263 
6264 void
scsi_report_density_support(struct ccb_scsiio * csio,uint32_t retries,void (* cbfcnp)(struct cam_periph *,union ccb *),uint8_t tag_action,int media,int medium_type,uint8_t * data_ptr,uint32_t length,uint32_t sense_len,uint32_t timeout)6265 scsi_report_density_support(struct ccb_scsiio *csio, uint32_t retries,
6266 			    void (*cbfcnp)(struct cam_periph *, union ccb *),
6267 			    uint8_t tag_action, int media, int medium_type,
6268 			    uint8_t *data_ptr, uint32_t length,
6269 			    uint32_t sense_len, uint32_t timeout)
6270 {
6271 	struct scsi_report_density_support *scsi_cmd;
6272 
6273 	scsi_cmd =(struct scsi_report_density_support *)&csio->cdb_io.cdb_bytes;
6274 	bzero(scsi_cmd, sizeof(*scsi_cmd));
6275 
6276 	scsi_cmd->opcode = REPORT_DENSITY_SUPPORT;
6277 	if (media != 0)
6278 		scsi_cmd->byte1 |= SRDS_MEDIA;
6279 	if (medium_type != 0)
6280 		scsi_cmd->byte1 |= SRDS_MEDIUM_TYPE;
6281 
6282 	scsi_ulto2b(length, scsi_cmd->length);
6283 
6284 	cam_fill_csio(csio,
6285 		      retries,
6286 		      cbfcnp,
6287 		      /*flags*/CAM_DIR_IN,
6288 		      tag_action,
6289 		      /*data_ptr*/data_ptr,
6290 		      /*dxfer_len*/length,
6291 		      sense_len,
6292 		      sizeof(*scsi_cmd),
6293 		      timeout);
6294 }
6295 
6296 void
scsi_set_capacity(struct ccb_scsiio * csio,uint32_t retries,void (* cbfcnp)(struct cam_periph *,union ccb *),uint8_t tag_action,int byte1,uint32_t proportion,uint32_t sense_len,uint32_t timeout)6297 scsi_set_capacity(struct ccb_scsiio *csio, uint32_t retries,
6298 		  void (*cbfcnp)(struct cam_periph *, union ccb *),
6299 		  uint8_t tag_action, int byte1, uint32_t proportion,
6300 		  uint32_t sense_len, uint32_t timeout)
6301 {
6302 	struct scsi_set_capacity *scsi_cmd;
6303 
6304 	scsi_cmd = (struct scsi_set_capacity *)&csio->cdb_io.cdb_bytes;
6305 	bzero(scsi_cmd, sizeof(*scsi_cmd));
6306 
6307 	scsi_cmd->opcode = SET_CAPACITY;
6308 
6309 	scsi_cmd->byte1 = byte1;
6310 	scsi_ulto2b(proportion, scsi_cmd->cap_proportion);
6311 
6312 	cam_fill_csio(csio,
6313 		      retries,
6314 		      cbfcnp,
6315 		      /*flags*/CAM_DIR_NONE,
6316 		      tag_action,
6317 		      /*data_ptr*/NULL,
6318 		      /*dxfer_len*/0,
6319 		      sense_len,
6320 		      sizeof(*scsi_cmd),
6321 		      timeout);
6322 }
6323 
6324 void
scsi_format_medium(struct ccb_scsiio * csio,uint32_t retries,void (* cbfcnp)(struct cam_periph *,union ccb *),uint8_t tag_action,int byte1,int byte2,uint8_t * data_ptr,uint32_t dxfer_len,uint32_t sense_len,uint32_t timeout)6325 scsi_format_medium(struct ccb_scsiio *csio, uint32_t retries,
6326 		   void (*cbfcnp)(struct cam_periph *, union ccb *),
6327 		   uint8_t tag_action, int byte1, int byte2,
6328 		   uint8_t *data_ptr, uint32_t dxfer_len,
6329 		   uint32_t sense_len, uint32_t timeout)
6330 {
6331 	struct scsi_format_medium *scsi_cmd;
6332 
6333 	scsi_cmd = (struct scsi_format_medium*)&csio->cdb_io.cdb_bytes;
6334 	bzero(scsi_cmd, sizeof(*scsi_cmd));
6335 
6336 	scsi_cmd->opcode = FORMAT_MEDIUM;
6337 
6338 	scsi_cmd->byte1 = byte1;
6339 	scsi_cmd->byte2 = byte2;
6340 
6341 	scsi_ulto2b(dxfer_len, scsi_cmd->length);
6342 
6343 	cam_fill_csio(csio,
6344 		      retries,
6345 		      cbfcnp,
6346 		      /*flags*/(dxfer_len > 0) ? CAM_DIR_OUT : CAM_DIR_NONE,
6347 		      tag_action,
6348 		      /*data_ptr*/ data_ptr,
6349 		      /*dxfer_len*/ dxfer_len,
6350 		      sense_len,
6351 		      sizeof(*scsi_cmd),
6352 		      timeout);
6353 }
6354 
6355 void
scsi_allow_overwrite(struct ccb_scsiio * csio,uint32_t retries,void (* cbfcnp)(struct cam_periph *,union ccb *),uint8_t tag_action,int allow_overwrite,int partition,uint64_t logical_id,uint32_t sense_len,uint32_t timeout)6356 scsi_allow_overwrite(struct ccb_scsiio *csio, uint32_t retries,
6357 		   void (*cbfcnp)(struct cam_periph *, union ccb *),
6358 		   uint8_t tag_action, int allow_overwrite, int partition,
6359 		   uint64_t logical_id, uint32_t sense_len, uint32_t timeout)
6360 {
6361 	struct scsi_allow_overwrite *scsi_cmd;
6362 
6363 	scsi_cmd = (struct scsi_allow_overwrite *)&csio->cdb_io.cdb_bytes;
6364 	bzero(scsi_cmd, sizeof(*scsi_cmd));
6365 
6366 	scsi_cmd->opcode = ALLOW_OVERWRITE;
6367 
6368 	scsi_cmd->allow_overwrite = allow_overwrite;
6369 	scsi_cmd->partition = partition;
6370 	scsi_u64to8b(logical_id, scsi_cmd->logical_id);
6371 
6372 	cam_fill_csio(csio,
6373 		      retries,
6374 		      cbfcnp,
6375 		      CAM_DIR_NONE,
6376 		      tag_action,
6377 		      /*data_ptr*/ NULL,
6378 		      /*dxfer_len*/ 0,
6379 		      sense_len,
6380 		      sizeof(*scsi_cmd),
6381 		      timeout);
6382 }
6383