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