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