scsi_sa.c revision 114216
1/*
2 * $FreeBSD: head/sys/cam/scsi/scsi_sa.c 114216 2003-04-29 13:36:06Z kan $
3 *
4 * Implementation of SCSI Sequential Access Peripheral driver for CAM.
5 *
6 * Copyright (c) 1999, 2000 Matthew Jacob
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions, and the following disclaimer,
14 *    without modification, immediately at the beginning of the file.
15 * 2. The name of the author may not be used to endorse or promote products
16 *    derived from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
22 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * SUCH DAMAGE.
29 *
30 */
31
32#include <sys/param.h>
33#include <sys/queue.h>
34#ifdef _KERNEL
35#include <sys/systm.h>
36#include <sys/kernel.h>
37#endif
38#include <sys/types.h>
39#include <sys/time.h>
40#include <sys/bio.h>
41#include <sys/limits.h>
42#include <sys/malloc.h>
43#include <sys/mtio.h>
44#ifdef _KERNEL
45#include <sys/conf.h>
46#endif
47#include <sys/devicestat.h>
48
49#ifndef _KERNEL
50#include <stdio.h>
51#include <string.h>
52#endif
53
54#include <cam/cam.h>
55#include <cam/cam_ccb.h>
56#include <cam/cam_periph.h>
57#include <cam/cam_xpt_periph.h>
58#include <cam/cam_debug.h>
59
60#include <cam/scsi/scsi_all.h>
61#include <cam/scsi/scsi_message.h>
62#include <cam/scsi/scsi_sa.h>
63
64#ifdef _KERNEL
65
66#include <opt_sa.h>
67
68#ifndef SA_IO_TIMEOUT
69#define SA_IO_TIMEOUT		4
70#endif
71#ifndef SA_SPACE_TIMEOUT
72#define SA_SPACE_TIMEOUT	1 * 60
73#endif
74#ifndef SA_REWIND_TIMEOUT
75#define SA_REWIND_TIMEOUT	2 * 60
76#endif
77#ifndef SA_ERASE_TIMEOUT
78#define SA_ERASE_TIMEOUT	4 * 60
79#endif
80
81#define	SCSIOP_TIMEOUT		(60 * 1000)	/* not an option */
82
83#define	IO_TIMEOUT		(SA_IO_TIMEOUT * 60 * 1000)
84#define	REWIND_TIMEOUT		(SA_REWIND_TIMEOUT * 60 * 1000)
85#define	ERASE_TIMEOUT		(SA_ERASE_TIMEOUT * 60 * 1000)
86#define	SPACE_TIMEOUT		(SA_SPACE_TIMEOUT * 60 * 1000)
87
88/*
89 * Additional options that can be set for config: SA_1FM_AT_EOT
90 */
91
92#ifndef	UNUSED_PARAMETER
93#define	UNUSED_PARAMETER(x)	x = x
94#endif
95
96#define	QFRLS(ccb)	\
97	if (((ccb)->ccb_h.status & CAM_DEV_QFRZN) != 0)	\
98		cam_release_devq((ccb)->ccb_h.path, 0, 0, 0, FALSE)
99
100/*
101 * Driver states
102 */
103
104
105typedef enum {
106	SA_STATE_NORMAL, SA_STATE_ABNORMAL
107} sa_state;
108
109#define ccb_pflags	ppriv_field0
110#define ccb_bp	 	ppriv_ptr1
111
112#define	SA_CCB_BUFFER_IO	0x0
113#define	SA_CCB_WAITING		0x1
114#define	SA_CCB_TYPEMASK		0x1
115#define	SA_POSITION_UPDATED	0x2
116
117#define	Set_CCB_Type(x, type)				\
118	x->ccb_h.ccb_pflags &= ~SA_CCB_TYPEMASK;	\
119	x->ccb_h.ccb_pflags |= type
120
121#define	CCB_Type(x)	(x->ccb_h.ccb_pflags & SA_CCB_TYPEMASK)
122
123
124
125typedef enum {
126	SA_FLAG_OPEN		= 0x0001,
127	SA_FLAG_FIXED		= 0x0002,
128	SA_FLAG_TAPE_LOCKED	= 0x0004,
129	SA_FLAG_TAPE_MOUNTED	= 0x0008,
130	SA_FLAG_TAPE_WP		= 0x0010,
131	SA_FLAG_TAPE_WRITTEN	= 0x0020,
132	SA_FLAG_EOM_PENDING	= 0x0040,
133	SA_FLAG_EIO_PENDING	= 0x0080,
134	SA_FLAG_EOF_PENDING	= 0x0100,
135	SA_FLAG_ERR_PENDING	= (SA_FLAG_EOM_PENDING|SA_FLAG_EIO_PENDING|
136				   SA_FLAG_EOF_PENDING),
137	SA_FLAG_INVALID		= 0x0200,
138	SA_FLAG_COMP_ENABLED	= 0x0400,
139	SA_FLAG_COMP_SUPP	= 0x0800,
140	SA_FLAG_COMP_UNSUPP	= 0x1000,
141	SA_FLAG_TAPE_FROZEN	= 0x2000
142} sa_flags;
143
144typedef enum {
145	SA_MODE_REWIND		= 0x00,
146	SA_MODE_NOREWIND	= 0x01,
147	SA_MODE_OFFLINE		= 0x02
148} sa_mode;
149
150typedef enum {
151	SA_PARAM_NONE		= 0x00,
152	SA_PARAM_BLOCKSIZE	= 0x01,
153	SA_PARAM_DENSITY	= 0x02,
154	SA_PARAM_COMPRESSION	= 0x04,
155	SA_PARAM_BUFF_MODE	= 0x08,
156	SA_PARAM_NUMBLOCKS	= 0x10,
157	SA_PARAM_WP		= 0x20,
158	SA_PARAM_SPEED		= 0x40,
159	SA_PARAM_ALL		= 0x7f
160} sa_params;
161
162typedef enum {
163	SA_QUIRK_NONE		= 0x00,
164	SA_QUIRK_NOCOMP		= 0x01,	/* Can't deal with compression at all */
165	SA_QUIRK_FIXED		= 0x02,	/* Force fixed mode */
166	SA_QUIRK_VARIABLE	= 0x04,	/* Force variable mode */
167	SA_QUIRK_2FM		= 0x08,	/* Needs Two File Marks at EOD */
168	SA_QUIRK_1FM		= 0x10,	/* No more than 1 File Mark at EOD */
169	SA_QUIRK_NODREAD	= 0x20,	/* Don't try and dummy read density */
170	SA_QUIRK_NO_MODESEL	= 0x40,	/* Don't do mode select at all */
171	SA_QUIRK_NO_CPAGE	= 0x80	/* Don't use DEVICE COMPRESSION page */
172} sa_quirks;
173
174/* units are bits 4-7, 16-21 (1024 units) */
175#define SAUNIT(DEV) \
176	(((minor(DEV) & 0xF0) >> 4) |  ((minor(DEV) & 0x3f0000) >> 16))
177
178#define SAMODE(z) ((minor(z) & 0x3))
179#define SADENSITY(z) (((minor(z) >> 2) & 0x3))
180#define	SA_IS_CTRL(z) (minor(z) & (1 << 29))
181
182#define SA_NOT_CTLDEV	0
183#define SA_CTLDEV	1
184
185#define SA_ATYPE_R	0
186#define SA_ATYPE_NR	1
187#define SA_ATYPE_ER	2
188
189#define SAMINOR(ctl, unit, mode, access) \
190	((ctl << 29) | ((unit & 0x3f0) << 16) | ((unit & 0xf) << 4) | \
191	(mode << 0x2) | (access & 0x3))
192
193#define SA_NUM_MODES	4
194struct sa_devs {
195	dev_t	ctl_dev;
196	struct sa_mode_devs {
197		dev_t	r_dev;
198		dev_t	nr_dev;
199		dev_t	er_dev;
200	} mode_devs[SA_NUM_MODES];
201};
202
203struct sa_softc {
204	sa_state	state;
205	sa_flags	flags;
206	sa_quirks	quirks;
207	struct		bio_queue_head bio_queue;
208	int		queue_count;
209	struct		devstat *device_stats;
210	struct sa_devs	devs;
211	int		blk_gran;
212	int		blk_mask;
213	int		blk_shift;
214	u_int32_t	max_blk;
215	u_int32_t	min_blk;
216	u_int32_t	comp_algorithm;
217	u_int32_t	saved_comp_algorithm;
218	u_int32_t	media_blksize;
219	u_int32_t	last_media_blksize;
220	u_int32_t	media_numblks;
221	u_int8_t	media_density;
222	u_int8_t	speed;
223	u_int8_t	scsi_rev;
224	u_int8_t	dsreg;		/* mtio mt_dsreg, redux */
225	int		buffer_mode;
226	int		filemarks;
227	union		ccb saved_ccb;
228	int		last_resid_was_io;
229
230	/*
231	 * Relative to BOT Location.
232	 */
233	daddr_t		fileno;
234	daddr_t		blkno;
235
236	/*
237	 * Latched Error Info
238	 */
239	struct {
240		struct scsi_sense_data _last_io_sense;
241		u_int32_t _last_io_resid;
242		u_int8_t _last_io_cdb[CAM_MAX_CDBLEN];
243		struct scsi_sense_data _last_ctl_sense;
244		u_int32_t _last_ctl_resid;
245		u_int8_t _last_ctl_cdb[CAM_MAX_CDBLEN];
246#define	last_io_sense	errinfo._last_io_sense
247#define	last_io_resid	errinfo._last_io_resid
248#define	last_io_cdb	errinfo._last_io_cdb
249#define	last_ctl_sense	errinfo._last_ctl_sense
250#define	last_ctl_resid	errinfo._last_ctl_resid
251#define	last_ctl_cdb	errinfo._last_ctl_cdb
252	} errinfo;
253	/*
254	 * Misc other flags/state
255	 */
256	u_int32_t
257				: 31,
258		ctrl_mode	: 1;	/* control device open */
259};
260
261struct sa_quirk_entry {
262	struct scsi_inquiry_pattern inq_pat;	/* matching pattern */
263	sa_quirks quirks;	/* specific quirk type */
264	u_int32_t prefblk;	/* preferred blocksize when in fixed mode */
265};
266
267static struct sa_quirk_entry sa_quirk_table[] =
268{
269	{
270		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "OnStream",
271		  "ADR*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_NODREAD |
272		   SA_QUIRK_1FM|SA_QUIRK_NO_MODESEL, 32768
273	},
274	{
275		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
276		  "Python 06408*", "*"}, SA_QUIRK_NODREAD, 0
277	},
278	{
279		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
280		  "Python 25601*", "*"}, SA_QUIRK_NOCOMP|SA_QUIRK_NODREAD, 0
281	},
282	{
283		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
284		  "Python*", "*"}, SA_QUIRK_NODREAD, 0
285	},
286	{
287		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
288		  "VIPER 150*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 512
289	},
290	{
291		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
292		  "VIPER 2525 25462", "-011"},
293		  SA_QUIRK_NOCOMP|SA_QUIRK_1FM|SA_QUIRK_NODREAD, 0
294	},
295	{
296		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "ARCHIVE",
297		  "VIPER 2525*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 1024
298	},
299#if	0
300	{
301		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "HP",
302		  "C15*", "*"}, SA_QUIRK_VARIABLE|SA_QUIRK_NO_CPAGE, 0,
303	},
304#endif
305 	{
306 		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "HP",
307		  "C56*", "*"}, SA_QUIRK_VARIABLE|SA_QUIRK_2FM, 0
308	},
309	{
310		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "HP",
311		  "T20*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 512
312	},
313	{
314		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "HP",
315		  "T4000*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 512
316	},
317	{
318		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "HP",
319		  "HP-88780*", "*"}, SA_QUIRK_VARIABLE|SA_QUIRK_2FM, 0
320	},
321	{
322		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "KENNEDY",
323		  "*", "*"}, SA_QUIRK_VARIABLE|SA_QUIRK_2FM, 0
324	},
325	{
326		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "M4 DATA",
327		  "123107 SCSI*", "*"}, SA_QUIRK_VARIABLE|SA_QUIRK_2FM, 0
328	},
329	{	/* jreynold@primenet.com */
330		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "Seagate",
331		"STT8000N*", "*"}, SA_QUIRK_1FM, 0
332	},
333	{	/* mike@sentex.net */
334		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "Seagate",
335		"STT20000*", "*"}, SA_QUIRK_1FM, 0
336	},
337	{
338		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
339		  " TDC 3600", "U07:"}, SA_QUIRK_NOCOMP|SA_QUIRK_1FM, 512
340	},
341	{
342		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
343		  " TDC 3800", "*"}, SA_QUIRK_NOCOMP|SA_QUIRK_1FM, 512
344	},
345	{
346		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
347		  " TDC 4100", "*"}, SA_QUIRK_NOCOMP|SA_QUIRK_1FM, 512
348	},
349	{
350		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
351		  " TDC 4200", "*"}, SA_QUIRK_NOCOMP|SA_QUIRK_1FM, 512
352	},
353	{
354		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
355		  " SLR*", "*"}, SA_QUIRK_1FM, 0
356	},
357	{
358		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "WANGTEK",
359		  "5525ES*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 512
360	},
361	{
362		{ T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "WANGTEK",
363		  "51000*", "*"}, SA_QUIRK_FIXED|SA_QUIRK_1FM, 1024
364	}
365};
366
367static	d_open_t	saopen;
368static	d_close_t	saclose;
369static	d_strategy_t	sastrategy;
370static	d_ioctl_t	saioctl;
371static	periph_init_t	sainit;
372static	periph_ctor_t	saregister;
373static	periph_oninv_t	saoninvalidate;
374static	periph_dtor_t	sacleanup;
375static	periph_start_t	sastart;
376static	void		saasync(void *callback_arg, u_int32_t code,
377				struct cam_path *path, void *arg);
378static	void		sadone(struct cam_periph *periph,
379			       union ccb *start_ccb);
380static  int		saerror(union ccb *ccb, u_int32_t cam_flags,
381				u_int32_t sense_flags);
382static int		samarkswanted(struct cam_periph *);
383static int		sacheckeod(struct cam_periph *periph);
384static int		sagetparams(struct cam_periph *periph,
385				    sa_params params_to_get,
386				    u_int32_t *blocksize, u_int8_t *density,
387				    u_int32_t *numblocks, int *buff_mode,
388				    u_int8_t *write_protect, u_int8_t *speed,
389				    int *comp_supported, int *comp_enabled,
390				    u_int32_t *comp_algorithm,
391				    sa_comp_t *comp_page);
392static int		sasetparams(struct cam_periph *periph,
393				    sa_params params_to_set,
394				    u_int32_t blocksize, u_int8_t density,
395				    u_int32_t comp_algorithm,
396				    u_int32_t sense_flags);
397static void		saprevent(struct cam_periph *periph, int action);
398static int		sarewind(struct cam_periph *periph);
399static int		saspace(struct cam_periph *periph, int count,
400				scsi_space_code code);
401static int		samount(struct cam_periph *, int, dev_t);
402static int		saretension(struct cam_periph *periph);
403static int		sareservereleaseunit(struct cam_periph *periph,
404					     int reserve);
405static int		saloadunload(struct cam_periph *periph, int load);
406static int		saerase(struct cam_periph *periph, int longerase);
407static int		sawritefilemarks(struct cam_periph *periph,
408					 int nmarks, int setmarks);
409static int		sardpos(struct cam_periph *periph, int, u_int32_t *);
410static int		sasetpos(struct cam_periph *periph, int, u_int32_t *);
411
412
413static struct periph_driver sadriver =
414{
415	sainit, "sa",
416	TAILQ_HEAD_INITIALIZER(sadriver.units), /* generation */ 0
417};
418
419PERIPHDRIVER_DECLARE(sa, sadriver);
420
421/* For 2.2-stable support */
422#ifndef D_TAPE
423#define D_TAPE 0
424#endif
425
426#define SA_CDEV_MAJOR 14
427
428static struct cdevsw sa_cdevsw = {
429	.d_open =	saopen,
430	.d_close =	saclose,
431	.d_read =	physread,
432	.d_write =	physwrite,
433	.d_ioctl =	saioctl,
434	.d_strategy =	sastrategy,
435	.d_name =	"sa",
436	.d_maj =	SA_CDEV_MAJOR,
437	.d_flags =	D_TAPE,
438};
439
440static int
441saopen(dev_t dev, int flags, int fmt, struct thread *td)
442{
443	struct cam_periph *periph;
444	struct sa_softc *softc;
445	int unit;
446	int mode;
447	int density;
448	int error;
449	int s;
450
451	unit = SAUNIT(dev);
452	mode = SAMODE(dev);
453	density = SADENSITY(dev);
454
455	s = splsoftcam();
456	periph = (struct cam_periph *)dev->si_drv1;
457	if (periph == NULL) {
458		(void) splx(s);
459		return (ENXIO);
460	}
461	softc = (struct sa_softc *)periph->softc;
462	if ((error = cam_periph_lock(periph, PRIBIO|PCATCH)) != 0) {
463		splx(s);
464		return (error);
465	}
466	splx(s);
467
468	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE|CAM_DEBUG_INFO,
469	    ("saopen(%d): dev=0x%x softc=0x%x\n", unit, unit, softc->flags));
470
471	if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
472		cam_periph_unlock(periph);
473		return (ENXIO);
474	}
475	if (SA_IS_CTRL(dev)) {
476		softc->ctrl_mode = 1;
477		cam_periph_unlock(periph);
478		return (0);
479	}
480
481
482	if (softc->flags & SA_FLAG_OPEN) {
483		error = EBUSY;
484	} else if (softc->flags & SA_FLAG_INVALID) {
485		error = ENXIO;
486	} else {
487		/*
488		 * The function samount ensures media is loaded and ready.
489		 * It also does a device RESERVE if the tape isn't yet mounted.
490		 */
491		error = samount(periph, flags, dev);
492	}
493
494	if (error) {
495		cam_periph_release(periph);
496	} else {
497		saprevent(periph, PR_PREVENT);
498		softc->flags |= SA_FLAG_OPEN;
499	}
500	cam_periph_unlock(periph);
501	return (error);
502}
503
504static int
505saclose(dev_t dev, int flag, int fmt, struct thread *td)
506{
507	struct	cam_periph *periph;
508	struct	sa_softc *softc;
509	int	unit, mode, error, writing, tmp;
510	int	closedbits = SA_FLAG_OPEN;
511
512	unit = SAUNIT(dev);
513	mode = SAMODE(dev);
514	periph = (struct cam_periph *)dev->si_drv1;
515	if (periph == NULL)
516		return (ENXIO);
517
518	softc = (struct sa_softc *)periph->softc;
519
520	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE|CAM_DEBUG_INFO,
521	    ("saclose(%d): dev=0x%x softc=0x%x\n", unit, unit, softc->flags));
522
523
524	if ((error = cam_periph_lock(periph, PRIBIO)) != 0) {
525		return (error);
526	}
527
528	if (SA_IS_CTRL(dev)) {
529		softc->ctrl_mode = 0;
530		cam_periph_release(periph);
531		cam_periph_unlock(periph);
532		return (0);
533	}
534
535	/*
536	 * Were we writing the tape?
537	 */
538	writing = (softc->flags & SA_FLAG_TAPE_WRITTEN) != 0;
539
540	/*
541	 * See whether or not we need to write filemarks. If this
542	 * fails, we probably have to assume we've lost tape
543	 * position.
544	 */
545	error = sacheckeod(periph);
546	if (error) {
547		xpt_print_path(periph->path);
548		printf("failed to write terminating filemark(s)\n");
549		softc->flags |= SA_FLAG_TAPE_FROZEN;
550	}
551
552	/*
553	 * Whatever we end up doing, allow users to eject tapes from here on.
554	 */
555	saprevent(periph, PR_ALLOW);
556
557	/*
558	 * Decide how to end...
559	 */
560	if ((softc->flags & SA_FLAG_TAPE_MOUNTED) == 0) {
561		closedbits |= SA_FLAG_TAPE_FROZEN;
562	} else switch (mode) {
563	case SA_MODE_OFFLINE:
564		/*
565		 * An 'offline' close is an unconditional release of
566		 * frozen && mount conditions, irrespective of whether
567		 * these operations succeeded. The reason for this is
568		 * to allow at least some kind of programmatic way
569		 * around our state getting all fouled up. If somebody
570		 * issues an 'offline' command, that will be allowed
571		 * to clear state.
572		 */
573		(void) sarewind(periph);
574		(void) saloadunload(periph, FALSE);
575		closedbits |= SA_FLAG_TAPE_MOUNTED|SA_FLAG_TAPE_FROZEN;
576		break;
577	case SA_MODE_REWIND:
578		/*
579		 * If the rewind fails, return an error- if anyone cares,
580		 * but not overwriting any previous error.
581		 *
582		 * We don't clear the notion of mounted here, but we do
583		 * clear the notion of frozen if we successfully rewound.
584		 */
585		tmp = sarewind(periph);
586		if (tmp) {
587			if (error != 0)
588				error = tmp;
589		} else {
590			closedbits |= SA_FLAG_TAPE_FROZEN;
591		}
592		break;
593	case SA_MODE_NOREWIND:
594		/*
595		 * If we're not rewinding/unloading the tape, find out
596		 * whether we need to back up over one of two filemarks
597		 * we wrote (if we wrote two filemarks) so that appends
598		 * from this point on will be sane.
599		 */
600		if (error == 0 && writing && (softc->quirks & SA_QUIRK_2FM)) {
601			tmp = saspace(periph, -1, SS_FILEMARKS);
602			if (tmp) {
603				xpt_print_path(periph->path);
604				printf("unable to backspace over one of double"
605				   " filemarks at end of tape\n");
606				xpt_print_path(periph->path);
607				printf("it is possible that this device"
608				   " needs a SA_QUIRK_1FM quirk set for it\n");
609				softc->flags |= SA_FLAG_TAPE_FROZEN;
610			}
611		}
612		break;
613	default:
614		xpt_print_path(periph->path);
615		panic("unknown mode 0x%x in saclose", mode);
616		/* NOTREACHED */
617		break;
618	}
619
620	/*
621	 * We wish to note here that there are no more filemarks to be written.
622	 */
623	softc->filemarks = 0;
624	softc->flags &= ~SA_FLAG_TAPE_WRITTEN;
625
626	/*
627	 * And we are no longer open for business.
628	 */
629	softc->flags &= ~closedbits;
630
631	/*
632	 * Inform users if tape state if frozen....
633	 */
634	if (softc->flags & SA_FLAG_TAPE_FROZEN) {
635		xpt_print_path(periph->path);
636		printf("tape is now frozen- use an OFFLINE, REWIND or MTEOM "
637		    "command to clear this state.\n");
638	}
639
640	/* release the device if it is no longer mounted */
641	if ((softc->flags & SA_FLAG_TAPE_MOUNTED) == 0)
642		sareservereleaseunit(periph, FALSE);
643
644	cam_periph_unlock(periph);
645	cam_periph_release(periph);
646
647	return (error);
648}
649
650/*
651 * Actually translate the requested transfer into one the physical driver
652 * can understand.  The transfer is described by a buf and will include
653 * only one physical transfer.
654 */
655static void
656sastrategy(struct bio *bp)
657{
658	struct cam_periph *periph;
659	struct sa_softc *softc;
660	int    s;
661
662	bp->bio_resid = bp->bio_bcount;
663	if (SA_IS_CTRL(bp->bio_dev)) {
664		biofinish(bp, NULL, EINVAL);
665		return;
666	}
667	periph = (struct cam_periph *)bp->bio_dev->si_drv1;
668	if (periph == NULL) {
669		biofinish(bp, NULL, ENXIO);
670		return;
671	}
672	softc = (struct sa_softc *)periph->softc;
673
674	s = splsoftcam();
675
676	if (softc->flags & SA_FLAG_INVALID) {
677		splx(s);
678		biofinish(bp, NULL, ENXIO);
679		return;
680	}
681
682	if (softc->flags & SA_FLAG_TAPE_FROZEN) {
683		splx(s);
684		biofinish(bp, NULL, EPERM);
685		return;
686	}
687
688	splx(s);
689
690	/*
691	 * If it's a null transfer, return immediatly
692	 */
693	if (bp->bio_bcount == 0) {
694		biodone(bp);
695		return;
696	}
697
698	/* valid request?  */
699	if (softc->flags & SA_FLAG_FIXED) {
700		/*
701		 * Fixed block device.  The byte count must
702		 * be a multiple of our block size.
703		 */
704		if (((softc->blk_mask != ~0) &&
705		    ((bp->bio_bcount & softc->blk_mask) != 0)) ||
706		    ((softc->blk_mask == ~0) &&
707		    ((bp->bio_bcount % softc->min_blk) != 0))) {
708			xpt_print_path(periph->path);
709			printf("Invalid request.  Fixed block device "
710			       "requests must be a multiple "
711			       "of %d bytes\n", softc->min_blk);
712			biofinish(bp, NULL, EINVAL);
713			return;
714		}
715	} else if ((bp->bio_bcount > softc->max_blk) ||
716		   (bp->bio_bcount < softc->min_blk) ||
717		   (bp->bio_bcount & softc->blk_mask) != 0) {
718
719		xpt_print_path(periph->path);
720		printf("Invalid request.  Variable block device "
721		    "requests must be ");
722		if (softc->blk_mask != 0) {
723			printf("a multiple of %d ", (0x1 << softc->blk_gran));
724		}
725		printf("between %d and %d bytes\n", softc->min_blk,
726		    softc->max_blk);
727		biofinish(bp, NULL, EINVAL);
728		return;
729        }
730
731	/*
732	 * Mask interrupts so that the device cannot be invalidated until
733	 * after we are in the queue.  Otherwise, we might not properly
734	 * clean up one of the buffers.
735	 */
736	s = splbio();
737
738	/*
739	 * Place it at the end of the queue.
740	 */
741	bioq_insert_tail(&softc->bio_queue, bp);
742
743	softc->queue_count++;
744	CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("sastrategy: enqueuing a %d "
745	    "%s byte %s queue count now %d\n", (int) bp->bio_bcount,
746	     (softc->flags & SA_FLAG_FIXED)?  "fixed" : "variable",
747	     (bp->bio_cmd == BIO_READ)? "read" : "write", softc->queue_count));
748
749	splx(s);
750
751	/*
752	 * Schedule ourselves for performing the work.
753	 */
754	xpt_schedule(periph, 1);
755
756	return;
757}
758
759static int
760saioctl(dev_t dev, u_long cmd, caddr_t arg, int flag, struct thread *td)
761{
762	struct cam_periph *periph;
763	struct sa_softc *softc;
764	scsi_space_code spaceop;
765	int didlockperiph = 0;
766	int s;
767	int unit;
768	int mode;
769	int density;
770	int error = 0;
771
772	unit = SAUNIT(dev);
773	mode = SAMODE(dev);
774	density = SADENSITY(dev);
775	error = 0;		/* shut up gcc */
776	spaceop = 0;		/* shut up gcc */
777
778	periph = (struct cam_periph *)dev->si_drv1;
779	if (periph == NULL)
780		return (ENXIO);
781
782	softc = (struct sa_softc *)periph->softc;
783
784	/*
785	 * Check for control mode accesses. We allow MTIOCGET and
786	 * MTIOCERRSTAT (but need to be the only one open in order
787	 * to clear latched status), and MTSETBSIZE, MTSETDNSTY
788	 * and MTCOMP (but need to be the only one accessing this
789	 * device to run those).
790	 */
791
792	if (SA_IS_CTRL(dev)) {
793		switch (cmd) {
794		case MTIOCGETEOTMODEL:
795		case MTIOCGET:
796			break;
797		case MTIOCERRSTAT:
798			/*
799			 * If the periph isn't already locked, lock it
800			 * so our MTIOCERRSTAT can reset latched error stats.
801			 *
802			 * If the periph is already locked, skip it because
803			 * we're just getting status and it'll be up to the
804			 * other thread that has this device open to do
805			 * an MTIOCERRSTAT that would clear latched status.
806			 */
807			s = splsoftcam();
808			if ((periph->flags & CAM_PERIPH_LOCKED) == 0) {
809				error = cam_periph_lock(periph, PRIBIO|PCATCH);
810				if (error != 0) {
811					splx(s);
812					return (error);
813				}
814				didlockperiph = 1;
815			}
816			break;
817
818		case MTIOCSETEOTMODEL:
819		case MTSETBSIZ:
820		case MTSETDNSTY:
821		case MTCOMP:
822			/*
823			 * We need to acquire the peripheral here rather
824			 * than at open time because we are sharing writable
825			 * access to data structures.
826			 */
827			s = splsoftcam();
828			error = cam_periph_lock(periph, PRIBIO|PCATCH);
829			if (error != 0) {
830				splx(s);
831				return (error);
832			}
833			didlockperiph = 1;
834			break;
835
836		default:
837			return (EINVAL);
838		}
839	}
840
841	/*
842	 * Find the device that the user is talking about
843	 */
844	switch (cmd) {
845	case MTIOCGET:
846	{
847		struct mtget *g = (struct mtget *)arg;
848
849		/*
850		 * If this isn't the control mode device, actually go out
851		 * and ask the drive again what it's set to.
852		 */
853		if (!SA_IS_CTRL(dev)) {
854			u_int8_t write_protect;
855			int comp_enabled, comp_supported;
856			error = sagetparams(periph, SA_PARAM_ALL,
857			    &softc->media_blksize, &softc->media_density,
858			    &softc->media_numblks, &softc->buffer_mode,
859			    &write_protect, &softc->speed, &comp_supported,
860			    &comp_enabled, &softc->comp_algorithm, NULL);
861			if (error)
862				break;
863			if (write_protect)
864				softc->flags |= SA_FLAG_TAPE_WP;
865			else
866				softc->flags &= ~SA_FLAG_TAPE_WP;
867			softc->flags &= ~(SA_FLAG_COMP_SUPP|
868			    SA_FLAG_COMP_ENABLED|SA_FLAG_COMP_UNSUPP);
869			if (comp_supported) {
870				if (softc->saved_comp_algorithm == 0)
871					softc->saved_comp_algorithm =
872					    softc->comp_algorithm;
873				softc->flags |= SA_FLAG_COMP_SUPP;
874				if (comp_enabled)
875					softc->flags |= SA_FLAG_COMP_ENABLED;
876			} else
877				softc->flags |= SA_FLAG_COMP_UNSUPP;
878		}
879		bzero(g, sizeof(struct mtget));
880		g->mt_type = MT_ISAR;
881		if (softc->flags & SA_FLAG_COMP_UNSUPP) {
882			g->mt_comp = MT_COMP_UNSUPP;
883			g->mt_comp0 = MT_COMP_UNSUPP;
884			g->mt_comp1 = MT_COMP_UNSUPP;
885			g->mt_comp2 = MT_COMP_UNSUPP;
886			g->mt_comp3 = MT_COMP_UNSUPP;
887		} else {
888			if ((softc->flags & SA_FLAG_COMP_ENABLED) == 0) {
889				g->mt_comp = MT_COMP_DISABLED;
890			} else {
891				g->mt_comp = softc->comp_algorithm;
892			}
893			g->mt_comp0 = softc->comp_algorithm;
894			g->mt_comp1 = softc->comp_algorithm;
895			g->mt_comp2 = softc->comp_algorithm;
896			g->mt_comp3 = softc->comp_algorithm;
897		}
898		g->mt_density = softc->media_density;
899		g->mt_density0 = softc->media_density;
900		g->mt_density1 = softc->media_density;
901		g->mt_density2 = softc->media_density;
902		g->mt_density3 = softc->media_density;
903		g->mt_blksiz = softc->media_blksize;
904		g->mt_blksiz0 = softc->media_blksize;
905		g->mt_blksiz1 = softc->media_blksize;
906		g->mt_blksiz2 = softc->media_blksize;
907		g->mt_blksiz3 = softc->media_blksize;
908		g->mt_fileno = softc->fileno;
909		g->mt_blkno = softc->blkno;
910		g->mt_dsreg = (short) softc->dsreg;
911		/*
912		 * Yes, we know that this is likely to overflow
913		 */
914		if (softc->last_resid_was_io) {
915			if ((g->mt_resid = (short) softc->last_io_resid) != 0) {
916				if (SA_IS_CTRL(dev) == 0 || didlockperiph) {
917					softc->last_io_resid = 0;
918				}
919			}
920		} else {
921			if ((g->mt_resid = (short)softc->last_ctl_resid) != 0) {
922				if (SA_IS_CTRL(dev) == 0 || didlockperiph) {
923					softc->last_ctl_resid = 0;
924				}
925			}
926		}
927		error = 0;
928		break;
929	}
930	case MTIOCERRSTAT:
931	{
932		struct scsi_tape_errors *sep =
933		    &((union mterrstat *)arg)->scsi_errstat;
934
935		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
936		    ("saioctl: MTIOCERRSTAT\n"));
937
938		bzero(sep, sizeof(*sep));
939		sep->io_resid = softc->last_io_resid;
940		bcopy((caddr_t) &softc->last_io_sense, sep->io_sense,
941		    sizeof (sep->io_sense));
942		bcopy((caddr_t) &softc->last_io_cdb, sep->io_cdb,
943		    sizeof (sep->io_cdb));
944		sep->ctl_resid = softc->last_ctl_resid;
945		bcopy((caddr_t) &softc->last_ctl_sense, sep->ctl_sense,
946		    sizeof (sep->ctl_sense));
947		bcopy((caddr_t) &softc->last_ctl_cdb, sep->ctl_cdb,
948		    sizeof (sep->ctl_cdb));
949
950		if (SA_IS_CTRL(dev) == 0 || didlockperiph)
951			bzero((caddr_t) &softc->errinfo,
952			    sizeof (softc->errinfo));
953		error = 0;
954		break;
955	}
956	case MTIOCTOP:
957	{
958		struct mtop *mt;
959		int    count;
960
961		mt = (struct mtop *)arg;
962
963		CAM_DEBUG(periph->path, CAM_DEBUG_TRACE,
964			 ("saioctl: op=0x%x count=0x%x\n",
965			  mt->mt_op, mt->mt_count));
966
967		count = mt->mt_count;
968		switch (mt->mt_op) {
969		case MTWEOF:	/* write an end-of-file marker */
970			/*
971			 * We don't need to clear the SA_FLAG_TAPE_WRITTEN
972			 * flag because by keeping track of filemarks
973			 * we have last written we know ehether or not
974			 * we need to write more when we close the device.
975			 */
976			error = sawritefilemarks(periph, count, FALSE);
977			break;
978		case MTWSS:	/* write a setmark */
979			error = sawritefilemarks(periph, count, TRUE);
980			break;
981		case MTBSR:	/* backward space record */
982		case MTFSR:	/* forward space record */
983		case MTBSF:	/* backward space file */
984		case MTFSF:	/* forward space file */
985		case MTBSS:	/* backward space setmark */
986		case MTFSS:	/* forward space setmark */
987		case MTEOD:	/* space to end of recorded medium */
988		{
989			int nmarks;
990
991			spaceop = SS_FILEMARKS;
992			nmarks = softc->filemarks;
993			error = sacheckeod(periph);
994			if (error) {
995				xpt_print_path(periph->path);
996				printf("EOD check prior to spacing failed\n");
997				softc->flags |= SA_FLAG_EIO_PENDING;
998				break;
999			}
1000			nmarks -= softc->filemarks;
1001			switch(mt->mt_op) {
1002			case MTBSR:
1003				count = -count;
1004				/* FALLTHROUGH */
1005			case MTFSR:
1006				spaceop = SS_BLOCKS;
1007				break;
1008			case MTBSF:
1009				count = -count;
1010				/* FALLTHROUGH */
1011			case MTFSF:
1012				break;
1013			case MTBSS:
1014				count = -count;
1015				/* FALLTHROUGH */
1016			case MTFSS:
1017				spaceop = SS_SETMARKS;
1018				break;
1019			case MTEOD:
1020				spaceop = SS_EOD;
1021				count = 0;
1022				nmarks = 0;
1023				break;
1024			default:
1025				error = EINVAL;
1026				break;
1027			}
1028			if (error)
1029				break;
1030
1031			nmarks = softc->filemarks;
1032			/*
1033			 * XXX: Why are we checking again?
1034			 */
1035			error = sacheckeod(periph);
1036			if (error)
1037				break;
1038			nmarks -= softc->filemarks;
1039			error = saspace(periph, count - nmarks, spaceop);
1040			/*
1041			 * At this point, clear that we've written the tape
1042			 * and that we've written any filemarks. We really
1043			 * don't know what the applications wishes to do next-
1044			 * the sacheckeod's will make sure we terminated the
1045			 * tape correctly if we'd been writing, but the next
1046			 * action the user application takes will set again
1047			 * whether we need to write filemarks.
1048			 */
1049			softc->flags &=
1050			    ~(SA_FLAG_TAPE_WRITTEN|SA_FLAG_TAPE_FROZEN);
1051			softc->filemarks = 0;
1052			break;
1053		}
1054		case MTREW:	/* rewind */
1055			(void) sacheckeod(periph);
1056			error = sarewind(periph);
1057			/* see above */
1058			softc->flags &=
1059			    ~(SA_FLAG_TAPE_WRITTEN|SA_FLAG_TAPE_FROZEN);
1060			softc->flags &= ~SA_FLAG_ERR_PENDING;
1061			softc->filemarks = 0;
1062			break;
1063		case MTERASE:	/* erase */
1064			error = saerase(periph, count);
1065			softc->flags &=
1066			    ~(SA_FLAG_TAPE_WRITTEN|SA_FLAG_TAPE_FROZEN);
1067			softc->flags &= ~SA_FLAG_ERR_PENDING;
1068			break;
1069		case MTRETENS:	/* re-tension tape */
1070			error = saretension(periph);
1071			softc->flags &=
1072			    ~(SA_FLAG_TAPE_WRITTEN|SA_FLAG_TAPE_FROZEN);
1073			softc->flags &= ~SA_FLAG_ERR_PENDING;
1074			break;
1075		case MTOFFL:	/* rewind and put the drive offline */
1076
1077			(void) sacheckeod(periph);
1078			/* see above */
1079			softc->flags &= ~SA_FLAG_TAPE_WRITTEN;
1080			softc->filemarks = 0;
1081
1082			error = sarewind(periph);
1083			/* clear the frozen flag anyway */
1084			softc->flags &= ~SA_FLAG_TAPE_FROZEN;
1085
1086			/*
1087			 * Be sure to allow media removal before ejecting.
1088			 */
1089
1090			saprevent(periph, PR_ALLOW);
1091			if (error == 0) {
1092				error = saloadunload(periph, FALSE);
1093				if (error == 0) {
1094					softc->flags &= ~SA_FLAG_TAPE_MOUNTED;
1095				}
1096			}
1097			break;
1098
1099		case MTNOP:	/* no operation, sets status only */
1100		case MTCACHE:	/* enable controller cache */
1101		case MTNOCACHE:	/* disable controller cache */
1102			error = 0;
1103			break;
1104
1105		case MTSETBSIZ:	/* Set block size for device */
1106
1107			error = sasetparams(periph, SA_PARAM_BLOCKSIZE, count,
1108					    0, 0, 0);
1109			if (error == 0) {
1110				softc->last_media_blksize =
1111				    softc->media_blksize;
1112				softc->media_blksize = count;
1113				if (count) {
1114					softc->flags |= SA_FLAG_FIXED;
1115					if (powerof2(count)) {
1116						softc->blk_shift =
1117						    ffs(count) - 1;
1118						softc->blk_mask = count - 1;
1119					} else {
1120						softc->blk_mask = ~0;
1121						softc->blk_shift = 0;
1122					}
1123					/*
1124					 * Make the user's desire 'persistent'.
1125					 */
1126					softc->quirks &= ~SA_QUIRK_VARIABLE;
1127					softc->quirks |= SA_QUIRK_FIXED;
1128				} else {
1129					softc->flags &= ~SA_FLAG_FIXED;
1130					if (softc->max_blk == 0) {
1131						softc->max_blk = ~0;
1132					}
1133					softc->blk_shift = 0;
1134					if (softc->blk_gran != 0) {
1135						softc->blk_mask =
1136						    softc->blk_gran - 1;
1137					} else {
1138						softc->blk_mask = 0;
1139					}
1140					/*
1141					 * Make the user's desire 'persistent'.
1142					 */
1143					softc->quirks |= SA_QUIRK_VARIABLE;
1144					softc->quirks &= ~SA_QUIRK_FIXED;
1145				}
1146			}
1147			break;
1148		case MTSETDNSTY:	/* Set density for device and mode */
1149			if (count > UCHAR_MAX) {
1150				error = EINVAL;
1151				break;
1152			} else {
1153				error = sasetparams(periph, SA_PARAM_DENSITY,
1154						    0, count, 0, 0);
1155			}
1156			break;
1157		case MTCOMP:	/* enable compression */
1158			/*
1159			 * Some devices don't support compression, and
1160			 * don't like it if you ask them for the
1161			 * compression page.
1162			 */
1163			if ((softc->quirks & SA_QUIRK_NOCOMP) ||
1164			    (softc->flags & SA_FLAG_COMP_UNSUPP)) {
1165				error = ENODEV;
1166				break;
1167			}
1168			error = sasetparams(periph, SA_PARAM_COMPRESSION,
1169			    0, 0, count, SF_NO_PRINT);
1170			break;
1171		default:
1172			error = EINVAL;
1173		}
1174		break;
1175	}
1176	case MTIOCIEOT:
1177	case MTIOCEEOT:
1178		error = 0;
1179		break;
1180	case MTIOCRDSPOS:
1181		error = sardpos(periph, 0, (u_int32_t *) arg);
1182		break;
1183	case MTIOCRDHPOS:
1184		error = sardpos(periph, 1, (u_int32_t *) arg);
1185		break;
1186	case MTIOCSLOCATE:
1187		error = sasetpos(periph, 0, (u_int32_t *) arg);
1188		break;
1189	case MTIOCHLOCATE:
1190		error = sasetpos(periph, 1, (u_int32_t *) arg);
1191		break;
1192	case MTIOCGETEOTMODEL:
1193		error = 0;
1194		if (softc->quirks & SA_QUIRK_1FM)
1195			mode = 1;
1196		else
1197			mode = 2;
1198		*((u_int32_t *) arg) = mode;
1199		break;
1200	case MTIOCSETEOTMODEL:
1201		error = 0;
1202		switch (*((u_int32_t *) arg)) {
1203		case 1:
1204			softc->quirks &= ~SA_QUIRK_2FM;
1205			softc->quirks |= SA_QUIRK_1FM;
1206			break;
1207		case 2:
1208			softc->quirks &= ~SA_QUIRK_1FM;
1209			softc->quirks |= SA_QUIRK_2FM;
1210			break;
1211		default:
1212			error = EINVAL;
1213			break;
1214		}
1215		break;
1216	default:
1217		error = cam_periph_ioctl(periph, cmd, arg, saerror);
1218		break;
1219	}
1220
1221	/*
1222	 * Check to see if we cleared a frozen state
1223	 */
1224	if (error == 0 && (softc->flags & SA_FLAG_TAPE_FROZEN)) {
1225		switch(cmd) {
1226		case MTIOCRDSPOS:
1227		case MTIOCRDHPOS:
1228		case MTIOCSLOCATE:
1229		case MTIOCHLOCATE:
1230			softc->fileno = (daddr_t) -1;
1231			softc->blkno = (daddr_t) -1;
1232			softc->flags &= ~SA_FLAG_TAPE_FROZEN;
1233			xpt_print_path(periph->path);
1234			printf("tape state now unfrozen.\n");
1235			break;
1236		default:
1237			break;
1238		}
1239	}
1240	if (didlockperiph) {
1241		cam_periph_unlock(periph);
1242	}
1243	return (error);
1244}
1245
1246static void
1247sainit(void)
1248{
1249	cam_status status;
1250	struct cam_path *path;
1251
1252	/*
1253	 * Install a global async callback.
1254	 */
1255	status = xpt_create_path(&path, NULL, CAM_XPT_PATH_ID,
1256				 CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
1257
1258	if (status == CAM_REQ_CMP) {
1259		/* Register the async callbacks of interrest */
1260		struct ccb_setasync csa; /*
1261					  * This is an immediate CCB,
1262					  * so using the stack is OK
1263					  */
1264		xpt_setup_ccb(&csa.ccb_h, path, 5);
1265		csa.ccb_h.func_code = XPT_SASYNC_CB;
1266		csa.event_enable = AC_FOUND_DEVICE;
1267		csa.callback = saasync;
1268		csa.callback_arg = NULL;
1269		xpt_action((union ccb *)&csa);
1270		status = csa.ccb_h.status;
1271		xpt_free_path(path);
1272	}
1273
1274	if (status != CAM_REQ_CMP) {
1275		printf("sa: Failed to attach master async callback "
1276		       "due to status 0x%x!\n", status);
1277	}
1278}
1279
1280static void
1281saoninvalidate(struct cam_periph *periph)
1282{
1283	struct sa_softc *softc;
1284	struct ccb_setasync csa;
1285	int s;
1286
1287	softc = (struct sa_softc *)periph->softc;
1288
1289	/*
1290	 * De-register any async callbacks.
1291	 */
1292	xpt_setup_ccb(&csa.ccb_h, periph->path,
1293		      /* priority */ 5);
1294	csa.ccb_h.func_code = XPT_SASYNC_CB;
1295	csa.event_enable = 0;
1296	csa.callback = saasync;
1297	csa.callback_arg = periph;
1298	xpt_action((union ccb *)&csa);
1299
1300	softc->flags |= SA_FLAG_INVALID;
1301
1302	/*
1303	 * Although the oninvalidate() routines are always called at
1304	 * splsoftcam, we need to be at splbio() here to keep the buffer
1305	 * queue from being modified while we traverse it.
1306	 */
1307	s = splbio();
1308
1309	/*
1310	 * Return all queued I/O with ENXIO.
1311	 * XXX Handle any transactions queued to the card
1312	 *     with XPT_ABORT_CCB.
1313	 */
1314	bioq_flush(&softc->bio_queue, NULL, ENXIO);
1315	softc->queue_count = 0;
1316	splx(s);
1317
1318	xpt_print_path(periph->path);
1319	printf("lost device\n");
1320
1321}
1322
1323static void
1324sacleanup(struct cam_periph *periph)
1325{
1326	struct sa_softc *softc;
1327	int i;
1328
1329	softc = (struct sa_softc *)periph->softc;
1330
1331	devstat_remove_entry(softc->device_stats);
1332
1333	destroy_dev(softc->devs.ctl_dev);
1334
1335	for (i = 0; i < SA_NUM_MODES; i++) {
1336		destroy_dev(softc->devs.mode_devs[i].r_dev);
1337		destroy_dev(softc->devs.mode_devs[i].nr_dev);
1338		destroy_dev(softc->devs.mode_devs[i].er_dev);
1339	}
1340
1341	xpt_print_path(periph->path);
1342	printf("removing device entry\n");
1343	free(softc, M_DEVBUF);
1344}
1345
1346static void
1347saasync(void *callback_arg, u_int32_t code,
1348	struct cam_path *path, void *arg)
1349{
1350	struct cam_periph *periph;
1351
1352	periph = (struct cam_periph *)callback_arg;
1353	switch (code) {
1354	case AC_FOUND_DEVICE:
1355	{
1356		struct ccb_getdev *cgd;
1357		cam_status status;
1358
1359		cgd = (struct ccb_getdev *)arg;
1360		if (cgd == NULL)
1361			break;
1362
1363		if (SID_TYPE(&cgd->inq_data) != T_SEQUENTIAL)
1364			break;
1365
1366		/*
1367		 * Allocate a peripheral instance for
1368		 * this device and start the probe
1369		 * process.
1370		 */
1371		status = cam_periph_alloc(saregister, saoninvalidate,
1372					  sacleanup, sastart,
1373					  "sa", CAM_PERIPH_BIO, cgd->ccb_h.path,
1374					  saasync, AC_FOUND_DEVICE, cgd);
1375
1376		if (status != CAM_REQ_CMP
1377		 && status != CAM_REQ_INPROG)
1378			printf("saasync: Unable to probe new device "
1379				"due to status 0x%x\n", status);
1380		break;
1381	}
1382	default:
1383		cam_periph_async(periph, code, path, arg);
1384		break;
1385	}
1386}
1387
1388static cam_status
1389saregister(struct cam_periph *periph, void *arg)
1390{
1391	struct sa_softc *softc;
1392	struct ccb_setasync csa;
1393	struct ccb_getdev *cgd;
1394	caddr_t match;
1395	int i;
1396
1397	cgd = (struct ccb_getdev *)arg;
1398	if (periph == NULL) {
1399		printf("saregister: periph was NULL!!\n");
1400		return (CAM_REQ_CMP_ERR);
1401	}
1402
1403	if (cgd == NULL) {
1404		printf("saregister: no getdev CCB, can't register device\n");
1405		return (CAM_REQ_CMP_ERR);
1406	}
1407
1408	softc = (struct sa_softc *)
1409	    malloc(sizeof (*softc), M_DEVBUF, M_NOWAIT | M_ZERO);
1410	if (softc == NULL) {
1411		printf("saregister: Unable to probe new device. "
1412		       "Unable to allocate softc\n");
1413		return (CAM_REQ_CMP_ERR);
1414	}
1415	softc->scsi_rev = SID_ANSI_REV(&cgd->inq_data);
1416	softc->state = SA_STATE_NORMAL;
1417	softc->fileno = (daddr_t) -1;
1418	softc->blkno = (daddr_t) -1;
1419
1420	bioq_init(&softc->bio_queue);
1421	periph->softc = softc;
1422
1423	/*
1424	 * See if this device has any quirks.
1425	 */
1426	match = cam_quirkmatch((caddr_t)&cgd->inq_data,
1427			       (caddr_t)sa_quirk_table,
1428			       sizeof(sa_quirk_table)/sizeof(*sa_quirk_table),
1429			       sizeof(*sa_quirk_table), scsi_inquiry_match);
1430
1431	if (match != NULL) {
1432		softc->quirks = ((struct sa_quirk_entry *)match)->quirks;
1433		softc->last_media_blksize =
1434		    ((struct sa_quirk_entry *)match)->prefblk;
1435#ifdef	CAMDEBUG
1436		xpt_print_path(periph->path);
1437		printf("found quirk entry %d\n", (int)
1438		    (((struct sa_quirk_entry *) match) - sa_quirk_table));
1439#endif
1440	} else
1441		softc->quirks = SA_QUIRK_NONE;
1442
1443	/*
1444 	 * The SA driver supports a blocksize, but we don't know the
1445	 * blocksize until we media is inserted.  So, set a flag to
1446	 * indicate that the blocksize is unavailable right now.
1447	 */
1448	softc->device_stats = devstat_new_entry("sa", periph->unit_number, 0,
1449	    DEVSTAT_BS_UNAVAILABLE, SID_TYPE(&cgd->inq_data) |
1450	    DEVSTAT_TYPE_IF_SCSI, DEVSTAT_PRIORITY_TAPE);
1451
1452	softc->devs.ctl_dev = make_dev(&sa_cdevsw, SAMINOR(SA_CTLDEV,
1453	    periph->unit_number, 0, SA_ATYPE_R), UID_ROOT, GID_OPERATOR,
1454	    0660, "%s%d.ctl", periph->periph_name, periph->unit_number);
1455	softc->devs.ctl_dev->si_drv1 = periph;
1456
1457	for (i = 0; i < SA_NUM_MODES; i++) {
1458
1459		softc->devs.mode_devs[i].r_dev = make_dev(&sa_cdevsw,
1460		    SAMINOR(SA_NOT_CTLDEV, periph->unit_number, i, SA_ATYPE_R),
1461		    UID_ROOT, GID_OPERATOR, 0660, "%s%d.%d",
1462		    periph->periph_name, periph->unit_number, i);
1463		softc->devs.mode_devs[i].r_dev->si_drv1 = periph;
1464
1465		softc->devs.mode_devs[i].nr_dev = make_dev(&sa_cdevsw,
1466		    SAMINOR(SA_NOT_CTLDEV, periph->unit_number, i, SA_ATYPE_NR),
1467		    UID_ROOT, GID_OPERATOR, 0660, "n%s%d.%d",
1468		    periph->periph_name, periph->unit_number, i);
1469		softc->devs.mode_devs[i].nr_dev->si_drv1 = periph;
1470
1471		softc->devs.mode_devs[i].er_dev = make_dev(&sa_cdevsw,
1472		    SAMINOR(SA_NOT_CTLDEV, periph->unit_number, i, SA_ATYPE_ER),
1473		    UID_ROOT, GID_OPERATOR, 0660, "e%s%d.%d",
1474		    periph->periph_name, periph->unit_number, i);
1475		softc->devs.mode_devs[i].er_dev->si_drv1 = periph;
1476
1477		/*
1478		 * Make the (well known) aliases for the first mode.
1479		 */
1480		if (i == 0) {
1481			dev_t alias;
1482
1483			alias = make_dev_alias(softc->devs.mode_devs[i].r_dev,
1484			   "%s%d", periph->periph_name, periph->unit_number);
1485			alias->si_drv1 = periph;
1486			alias = make_dev_alias(softc->devs.mode_devs[i].nr_dev,
1487			    "n%s%d", periph->periph_name, periph->unit_number);
1488			alias->si_drv1 = periph;
1489			alias = make_dev_alias(softc->devs.mode_devs[i].er_dev,
1490			    "e%s%d", periph->periph_name, periph->unit_number);
1491			alias->si_drv1 = periph;
1492		}
1493	}
1494
1495	/*
1496	 * Add an async callback so that we get
1497	 * notified if this device goes away.
1498	 */
1499	xpt_setup_ccb(&csa.ccb_h, periph->path, /* priority */ 5);
1500	csa.ccb_h.func_code = XPT_SASYNC_CB;
1501	csa.event_enable = AC_LOST_DEVICE;
1502	csa.callback = saasync;
1503	csa.callback_arg = periph;
1504	xpt_action((union ccb *)&csa);
1505
1506	xpt_announce_periph(periph, NULL);
1507
1508	return (CAM_REQ_CMP);
1509}
1510
1511static void
1512sastart(struct cam_periph *periph, union ccb *start_ccb)
1513{
1514	struct sa_softc *softc;
1515
1516	softc = (struct sa_softc *)periph->softc;
1517
1518	CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("sastart"));
1519
1520
1521	switch (softc->state) {
1522	case SA_STATE_NORMAL:
1523	{
1524		/* Pull a buffer from the queue and get going on it */
1525		struct bio *bp;
1526		int s;
1527
1528		/*
1529		 * See if there is a buf with work for us to do..
1530		 */
1531		s = splbio();
1532		bp = bioq_first(&softc->bio_queue);
1533		if (periph->immediate_priority <= periph->pinfo.priority) {
1534			CAM_DEBUG_PRINT(CAM_DEBUG_SUBTRACE,
1535					("queuing for immediate ccb\n"));
1536			Set_CCB_Type(start_ccb, SA_CCB_WAITING);
1537			SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
1538					  periph_links.sle);
1539			periph->immediate_priority = CAM_PRIORITY_NONE;
1540			splx(s);
1541			wakeup(&periph->ccb_list);
1542		} else if (bp == NULL) {
1543			splx(s);
1544			xpt_release_ccb(start_ccb);
1545		} else if ((softc->flags & SA_FLAG_ERR_PENDING) != 0) {
1546			struct bio *done_bp;
1547again:
1548			softc->queue_count--;
1549			bioq_remove(&softc->bio_queue, bp);
1550			bp->bio_resid = bp->bio_bcount;
1551			done_bp = bp;
1552			if ((softc->flags & SA_FLAG_EOM_PENDING) != 0) {
1553				/*
1554				 * We now just clear errors in this case
1555				 * and let the residual be the notifier.
1556				 */
1557				bp->bio_error = 0;
1558			} else if ((softc->flags & SA_FLAG_EOF_PENDING) != 0) {
1559				/*
1560				 * This can only happen if we're reading
1561				 * in fixed length mode. In this case,
1562				 * we dump the rest of the list the
1563				 * same way.
1564				 */
1565				bp->bio_error = 0;
1566				if (bioq_first(&softc->bio_queue) != NULL) {
1567					biodone(done_bp);
1568					goto again;
1569				}
1570			} else if ((softc->flags & SA_FLAG_EIO_PENDING) != 0) {
1571				bp->bio_error = EIO;
1572				bp->bio_flags |= BIO_ERROR;
1573			}
1574			bp = bioq_first(&softc->bio_queue);
1575			/*
1576			 * Only if we have no other buffers queued up
1577			 * do we clear the pending error flag.
1578			 */
1579			if (bp == NULL)
1580				softc->flags &= ~SA_FLAG_ERR_PENDING;
1581			CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
1582			    ("sastart- ERR_PENDING now 0x%x, bp is %sNULL, "
1583			    "%d more buffers queued up\n",
1584			    (softc->flags & SA_FLAG_ERR_PENDING),
1585			    (bp != NULL)? "not " : " ", softc->queue_count));
1586			splx(s);
1587			xpt_release_ccb(start_ccb);
1588			biodone(done_bp);
1589		} else {
1590			u_int32_t length;
1591
1592			bioq_remove(&softc->bio_queue, bp);
1593			softc->queue_count--;
1594
1595			if ((softc->flags & SA_FLAG_FIXED) != 0) {
1596				if (softc->blk_shift != 0) {
1597					length =
1598					    bp->bio_bcount >> softc->blk_shift;
1599				} else if (softc->media_blksize != 0) {
1600					length = bp->bio_bcount /
1601					    softc->media_blksize;
1602				} else {
1603					bp->bio_error = EIO;
1604					xpt_print_path(periph->path);
1605					printf("zero blocksize for "
1606					    "FIXED length writes?\n");
1607					splx(s);
1608					biodone(bp);
1609					break;
1610				}
1611				CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
1612				    ("Fixed Record Count is %d\n", length));
1613			} else {
1614				length = bp->bio_bcount;
1615				CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_INFO,
1616				    ("Variable Record Count is %d\n", length));
1617			}
1618			devstat_start_transaction_bio(softc->device_stats, bp);
1619			/*
1620			 * Some people have theorized that we should
1621			 * suppress illegal length indication if we are
1622			 * running in variable block mode so that we don't
1623			 * have to request sense every time our requested
1624			 * block size is larger than the written block.
1625			 * The residual information from the ccb allows
1626			 * us to identify this situation anyway.  The only
1627			 * problem with this is that we will not get
1628			 * information about blocks that are larger than
1629			 * our read buffer unless we set the block size
1630			 * in the mode page to something other than 0.
1631			 *
1632			 * I believe that this is a non-issue. If user apps
1633			 * don't adjust their read size to match our record
1634			 * size, that's just life. Anyway, the typical usage
1635			 * would be to issue, e.g., 64KB reads and occasionally
1636			 * have to do deal with 512 byte or 1KB intermediate
1637			 * records.
1638			 */
1639			softc->dsreg = (bp->bio_cmd == BIO_READ)?
1640			    MTIO_DSREG_RD : MTIO_DSREG_WR;
1641			scsi_sa_read_write(&start_ccb->csio, 0, sadone,
1642			    MSG_SIMPLE_Q_TAG, (bp->bio_cmd == BIO_READ),
1643			    FALSE, (softc->flags & SA_FLAG_FIXED) != 0,
1644			    length, bp->bio_data, bp->bio_bcount, SSD_FULL_SIZE,
1645			    IO_TIMEOUT);
1646			start_ccb->ccb_h.ccb_pflags &= ~SA_POSITION_UPDATED;
1647			Set_CCB_Type(start_ccb, SA_CCB_BUFFER_IO);
1648			start_ccb->ccb_h.ccb_bp = bp;
1649			bp = bioq_first(&softc->bio_queue);
1650			splx(s);
1651			xpt_action(start_ccb);
1652		}
1653
1654		if (bp != NULL) {
1655			/* Have more work to do, so ensure we stay scheduled */
1656			xpt_schedule(periph, 1);
1657		}
1658		break;
1659	}
1660	case SA_STATE_ABNORMAL:
1661	default:
1662		panic("state 0x%x in sastart", softc->state);
1663		break;
1664	}
1665}
1666
1667
1668static void
1669sadone(struct cam_periph *periph, union ccb *done_ccb)
1670{
1671	struct sa_softc *softc;
1672	struct ccb_scsiio *csio;
1673
1674	softc = (struct sa_softc *)periph->softc;
1675	csio = &done_ccb->csio;
1676	switch (CCB_Type(csio)) {
1677	case SA_CCB_BUFFER_IO:
1678	{
1679		struct bio *bp;
1680		int error;
1681
1682		softc->dsreg = MTIO_DSREG_REST;
1683		bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
1684		error = 0;
1685		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1686			if ((error = saerror(done_ccb, 0, 0)) == ERESTART) {
1687				/*
1688				 * A retry was scheduled, so just return.
1689				 */
1690				return;
1691			}
1692		}
1693
1694		if (error == EIO) {
1695			int s;
1696
1697			/*
1698			 * Catastrophic error. Mark the tape as frozen
1699			 * (we no longer know tape position).
1700			 *
1701			 * Return all queued I/O with EIO, and unfreeze
1702			 * our queue so that future transactions that
1703			 * attempt to fix this problem can get to the
1704			 * device.
1705			 *
1706			 */
1707
1708			s = splbio();
1709			softc->flags |= SA_FLAG_TAPE_FROZEN;
1710			bioq_flush(&softc->bio_queue, NULL, EIO);
1711			splx(s);
1712		}
1713		if (error != 0) {
1714			bp->bio_resid = bp->bio_bcount;
1715			bp->bio_error = error;
1716			bp->bio_flags |= BIO_ERROR;
1717			/*
1718			 * In the error case, position is updated in saerror.
1719			 */
1720		} else {
1721			bp->bio_resid = csio->resid;
1722			bp->bio_error = 0;
1723			if (csio->resid != 0) {
1724				bp->bio_flags |= BIO_ERROR;
1725			}
1726			if (bp->bio_cmd == BIO_WRITE) {
1727				softc->flags |= SA_FLAG_TAPE_WRITTEN;
1728				softc->filemarks = 0;
1729			}
1730			if (!(csio->ccb_h.ccb_pflags & SA_POSITION_UPDATED) &&
1731			    (softc->blkno != (daddr_t) -1)) {
1732				if ((softc->flags & SA_FLAG_FIXED) != 0) {
1733					u_int32_t l;
1734					if (softc->blk_shift != 0) {
1735						l = bp->bio_bcount >>
1736							softc->blk_shift;
1737					} else {
1738						l = bp->bio_bcount /
1739							softc->media_blksize;
1740					}
1741					softc->blkno += (daddr_t) l;
1742				} else {
1743					softc->blkno++;
1744				}
1745			}
1746		}
1747		/*
1748		 * If we had an error (immediate or pending),
1749		 * release the device queue now.
1750		 */
1751		if (error || (softc->flags & SA_FLAG_ERR_PENDING))
1752			cam_release_devq(done_ccb->ccb_h.path, 0, 0, 0, 0);
1753#ifdef	CAMDEBUG
1754		if (error || bp->bio_resid) {
1755			CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
1756			    	  ("error %d resid %ld count %ld\n", error,
1757				  bp->bio_resid, bp->bio_bcount));
1758		}
1759#endif
1760		biofinish(bp, softc->device_stats, 0);
1761		break;
1762	}
1763	case SA_CCB_WAITING:
1764	{
1765		/* Caller will release the CCB */
1766		wakeup(&done_ccb->ccb_h.cbfcnp);
1767		return;
1768	}
1769	}
1770	xpt_release_ccb(done_ccb);
1771}
1772
1773/*
1774 * Mount the tape (make sure it's ready for I/O).
1775 */
1776static int
1777samount(struct cam_periph *periph, int oflags, dev_t dev)
1778{
1779	struct	sa_softc *softc;
1780	union	ccb *ccb;
1781	int	error;
1782
1783	/*
1784	 * oflags can be checked for 'kind' of open (read-only check) - later
1785	 * dev can be checked for a control-mode or compression open - later
1786	 */
1787	UNUSED_PARAMETER(oflags);
1788	UNUSED_PARAMETER(dev);
1789
1790
1791	softc = (struct sa_softc *)periph->softc;
1792
1793	/*
1794	 * This should determine if something has happend since the last
1795	 * open/mount that would invalidate the mount. We do *not* want
1796	 * to retry this command- we just want the status. But we only
1797	 * do this if we're mounted already- if we're not mounted,
1798	 * we don't care about the unit read state and can instead use
1799	 * this opportunity to attempt to reserve the tape unit.
1800	 */
1801
1802	if (softc->flags & SA_FLAG_TAPE_MOUNTED) {
1803		ccb = cam_periph_getccb(periph, 1);
1804		scsi_test_unit_ready(&ccb->csio, 0, sadone,
1805		    MSG_SIMPLE_Q_TAG, SSD_FULL_SIZE, IO_TIMEOUT);
1806		error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
1807		    softc->device_stats);
1808		QFRLS(ccb);
1809		if (error == ENXIO) {
1810			softc->flags &= ~SA_FLAG_TAPE_MOUNTED;
1811			scsi_test_unit_ready(&ccb->csio, 0, sadone,
1812			    MSG_SIMPLE_Q_TAG, SSD_FULL_SIZE, IO_TIMEOUT);
1813			error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
1814			    softc->device_stats);
1815			QFRLS(ccb);
1816		} else if (error) {
1817			/*
1818			 * We don't need to freeze the tape because we
1819			 * will now attempt to rewind/load it.
1820			 */
1821			softc->flags &= ~SA_FLAG_TAPE_MOUNTED;
1822			if (CAM_DEBUGGED(ccb->ccb_h.path, CAM_DEBUG_INFO)) {
1823				xpt_print_path(ccb->ccb_h.path);
1824				printf("error %d on TUR in samount\n", error);
1825			}
1826		}
1827	} else {
1828		error = sareservereleaseunit(periph, TRUE);
1829		if (error) {
1830			return (error);
1831		}
1832		ccb = cam_periph_getccb(periph, 1);
1833		scsi_test_unit_ready(&ccb->csio, 0, sadone,
1834		    MSG_SIMPLE_Q_TAG, SSD_FULL_SIZE, IO_TIMEOUT);
1835		error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
1836		    softc->device_stats);
1837		QFRLS(ccb);
1838	}
1839
1840	if ((softc->flags & SA_FLAG_TAPE_MOUNTED) == 0) {
1841		struct scsi_read_block_limits_data *rblim = NULL;
1842		int comp_enabled, comp_supported;
1843		u_int8_t write_protect, guessing = 0;
1844
1845		/*
1846		 * Clear out old state.
1847		 */
1848		softc->flags &= ~(SA_FLAG_TAPE_WP|SA_FLAG_TAPE_WRITTEN|
1849				  SA_FLAG_ERR_PENDING|SA_FLAG_COMP_ENABLED|
1850				  SA_FLAG_COMP_SUPP|SA_FLAG_COMP_UNSUPP);
1851		softc->filemarks = 0;
1852
1853		/*
1854		 * *Very* first off, make sure we're loaded to BOT.
1855		 */
1856		scsi_load_unload(&ccb->csio, 2, sadone, MSG_SIMPLE_Q_TAG, FALSE,
1857		    FALSE, FALSE, 1, SSD_FULL_SIZE, REWIND_TIMEOUT);
1858		error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
1859		    softc->device_stats);
1860		QFRLS(ccb);
1861
1862		/*
1863		 * In case this doesn't work, do a REWIND instead
1864		 */
1865		if (error) {
1866			scsi_rewind(&ccb->csio, 2, sadone, MSG_SIMPLE_Q_TAG,
1867			    FALSE, SSD_FULL_SIZE, REWIND_TIMEOUT);
1868			error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
1869				softc->device_stats);
1870			QFRLS(ccb);
1871		}
1872		if (error) {
1873			xpt_release_ccb(ccb);
1874			goto exit;
1875		}
1876
1877		/*
1878		 * Do a dummy test read to force access to the
1879		 * media so that the drive will really know what's
1880		 * there. We actually don't really care what the
1881		 * blocksize on tape is and don't expect to really
1882		 * read a full record.
1883		 */
1884		rblim = (struct  scsi_read_block_limits_data *)
1885		    malloc(8192, M_TEMP, M_WAITOK);
1886		if (rblim == NULL) {
1887			xpt_print_path(ccb->ccb_h.path);
1888			printf("no memory for test read\n");
1889			xpt_release_ccb(ccb);
1890			error = ENOMEM;
1891			goto exit;
1892		}
1893
1894		if ((softc->quirks & SA_QUIRK_NODREAD) == 0) {
1895			scsi_sa_read_write(&ccb->csio, 0, sadone,
1896			    MSG_SIMPLE_Q_TAG, 1, FALSE, 0, 8192,
1897			    (void *) rblim, 8192, SSD_FULL_SIZE,
1898			    IO_TIMEOUT);
1899			(void) cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
1900			    softc->device_stats);
1901			QFRLS(ccb);
1902			scsi_rewind(&ccb->csio, 1, sadone, MSG_SIMPLE_Q_TAG,
1903			    FALSE, SSD_FULL_SIZE, REWIND_TIMEOUT);
1904			error = cam_periph_runccb(ccb, saerror, CAM_RETRY_SELTO,
1905			    SF_NO_PRINT | SF_RETRY_UA,
1906			    softc->device_stats);
1907			QFRLS(ccb);
1908			if (error) {
1909				xpt_print_path(ccb->ccb_h.path);
1910				printf("unable to rewind after test read\n");
1911				xpt_release_ccb(ccb);
1912				goto exit;
1913			}
1914		}
1915
1916		/*
1917		 * Next off, determine block limits.
1918		 */
1919		scsi_read_block_limits(&ccb->csio, 5, sadone, MSG_SIMPLE_Q_TAG,
1920		    rblim, SSD_FULL_SIZE, SCSIOP_TIMEOUT);
1921
1922		error = cam_periph_runccb(ccb, saerror, CAM_RETRY_SELTO,
1923		    SF_NO_PRINT | SF_RETRY_UA, softc->device_stats);
1924
1925		QFRLS(ccb);
1926		xpt_release_ccb(ccb);
1927
1928		if (error != 0) {
1929			/*
1930			 * If it's less than SCSI-2, READ BLOCK LIMITS is not
1931			 * a MANDATORY command. Anyway- it doesn't matter-
1932			 * we can proceed anyway.
1933			 */
1934			softc->blk_gran = 0;
1935			softc->max_blk = ~0;
1936			softc->min_blk = 0;
1937		} else {
1938			if (softc->scsi_rev >= SCSI_REV_SPC) {
1939				softc->blk_gran = RBL_GRAN(rblim);
1940			} else {
1941				softc->blk_gran = 0;
1942			}
1943			/*
1944			 * We take max_blk == min_blk to mean a default to
1945			 * fixed mode- but note that whatever we get out of
1946			 * sagetparams below will actually determine whether
1947			 * we are actually *in* fixed mode.
1948			 */
1949			softc->max_blk = scsi_3btoul(rblim->maximum);
1950			softc->min_blk = scsi_2btoul(rblim->minimum);
1951
1952
1953		}
1954		/*
1955		 * Next, perform a mode sense to determine
1956		 * current density, blocksize, compression etc.
1957		 */
1958		error = sagetparams(periph, SA_PARAM_ALL,
1959				    &softc->media_blksize,
1960				    &softc->media_density,
1961				    &softc->media_numblks,
1962				    &softc->buffer_mode, &write_protect,
1963				    &softc->speed, &comp_supported,
1964				    &comp_enabled, &softc->comp_algorithm,
1965				    NULL);
1966
1967		if (error != 0) {
1968			/*
1969			 * We could work a little harder here. We could
1970			 * adjust our attempts to get information. It
1971			 * might be an ancient tape drive. If someone
1972			 * nudges us, we'll do that.
1973			 */
1974			goto exit;
1975		}
1976
1977		/*
1978		 * If no quirk has determined that this is a device that is
1979		 * preferred to be in fixed or variable mode, now is the time
1980		 * to find out.
1981	 	 */
1982		if ((softc->quirks & (SA_QUIRK_FIXED|SA_QUIRK_VARIABLE)) == 0) {
1983			guessing = 1;
1984			/*
1985			 * This could be expensive to find out. Luckily we
1986			 * only need to do this once. If we start out in
1987			 * 'default' mode, try and set ourselves to one
1988			 * of the densities that would determine a wad
1989			 * of other stuff. Go from highest to lowest.
1990			 */
1991			if (softc->media_density == SCSI_DEFAULT_DENSITY) {
1992				int i;
1993				static u_int8_t ctry[] = {
1994					SCSI_DENSITY_HALFINCH_PE,
1995					SCSI_DENSITY_HALFINCH_6250C,
1996					SCSI_DENSITY_HALFINCH_6250,
1997					SCSI_DENSITY_HALFINCH_1600,
1998					SCSI_DENSITY_HALFINCH_800,
1999					SCSI_DENSITY_QIC_4GB,
2000					SCSI_DENSITY_QIC_2GB,
2001					SCSI_DENSITY_QIC_525_320,
2002					SCSI_DENSITY_QIC_150,
2003					SCSI_DENSITY_QIC_120,
2004					SCSI_DENSITY_QIC_24,
2005					SCSI_DENSITY_QIC_11_9TRK,
2006					SCSI_DENSITY_QIC_11_4TRK,
2007					SCSI_DENSITY_QIC_1320,
2008					SCSI_DENSITY_QIC_3080,
2009					0
2010				};
2011				for (i = 0; ctry[i]; i++) {
2012					error = sasetparams(periph,
2013					    SA_PARAM_DENSITY, 0, ctry[i],
2014					    0, SF_NO_PRINT);
2015					if (error == 0) {
2016						softc->media_density = ctry[i];
2017						break;
2018					}
2019				}
2020			}
2021			switch (softc->media_density) {
2022			case SCSI_DENSITY_QIC_11_4TRK:
2023			case SCSI_DENSITY_QIC_11_9TRK:
2024			case SCSI_DENSITY_QIC_24:
2025			case SCSI_DENSITY_QIC_120:
2026			case SCSI_DENSITY_QIC_150:
2027			case SCSI_DENSITY_QIC_525_320:
2028			case SCSI_DENSITY_QIC_1320:
2029			case SCSI_DENSITY_QIC_3080:
2030				softc->quirks &= ~SA_QUIRK_2FM;
2031				softc->quirks |= SA_QUIRK_FIXED|SA_QUIRK_1FM;
2032				softc->last_media_blksize = 512;
2033				break;
2034			case SCSI_DENSITY_QIC_4GB:
2035			case SCSI_DENSITY_QIC_2GB:
2036				softc->quirks &= ~SA_QUIRK_2FM;
2037				softc->quirks |= SA_QUIRK_FIXED|SA_QUIRK_1FM;
2038				softc->last_media_blksize = 1024;
2039				break;
2040			default:
2041				softc->last_media_blksize =
2042				    softc->media_blksize;
2043				softc->quirks |= SA_QUIRK_VARIABLE;
2044				break;
2045			}
2046		}
2047
2048		/*
2049		 * If no quirk has determined that this is a device that needs
2050		 * to have 2 Filemarks at EOD, now is the time to find out.
2051		 */
2052
2053		if ((softc->quirks & SA_QUIRK_2FM) == 0) {
2054			switch (softc->media_density) {
2055			case SCSI_DENSITY_HALFINCH_800:
2056			case SCSI_DENSITY_HALFINCH_1600:
2057			case SCSI_DENSITY_HALFINCH_6250:
2058			case SCSI_DENSITY_HALFINCH_6250C:
2059			case SCSI_DENSITY_HALFINCH_PE:
2060				softc->quirks &= ~SA_QUIRK_1FM;
2061				softc->quirks |= SA_QUIRK_2FM;
2062				break;
2063			default:
2064				break;
2065			}
2066		}
2067
2068		/*
2069		 * Now validate that some info we got makes sense.
2070		 */
2071		if ((softc->max_blk < softc->media_blksize) ||
2072		    (softc->min_blk > softc->media_blksize &&
2073		    softc->media_blksize)) {
2074			xpt_print_path(ccb->ccb_h.path);
2075			printf("BLOCK LIMITS (%d..%d) could not match current "
2076			    "block settings (%d)- adjusting\n", softc->min_blk,
2077			    softc->max_blk, softc->media_blksize);
2078			softc->max_blk = softc->min_blk =
2079			    softc->media_blksize;
2080		}
2081
2082		/*
2083		 * Now put ourselves into the right frame of mind based
2084		 * upon quirks...
2085		 */
2086tryagain:
2087		/*
2088		 * If we want to be in FIXED mode and our current blocksize
2089		 * is not equal to our last blocksize (if nonzero), try and
2090		 * set ourselves to this last blocksize (as the 'preferred'
2091		 * block size).  The initial quirkmatch at registry sets the
2092		 * initial 'last' blocksize. If, for whatever reason, this
2093		 * 'last' blocksize is zero, set the blocksize to 512,
2094		 * or min_blk if that's larger.
2095		 */
2096		if ((softc->quirks & SA_QUIRK_FIXED) &&
2097		    (softc->quirks & SA_QUIRK_NO_MODESEL) == 0 &&
2098		    (softc->media_blksize != softc->last_media_blksize)) {
2099			softc->media_blksize = softc->last_media_blksize;
2100			if (softc->media_blksize == 0) {
2101				softc->media_blksize = 512;
2102				if (softc->media_blksize < softc->min_blk) {
2103					softc->media_blksize = softc->min_blk;
2104				}
2105			}
2106			error = sasetparams(periph, SA_PARAM_BLOCKSIZE,
2107			    softc->media_blksize, 0, 0, SF_NO_PRINT);
2108			if (error) {
2109				xpt_print_path(ccb->ccb_h.path);
2110				printf("unable to set fixed blocksize to %d\n",
2111				     softc->media_blksize);
2112				goto exit;
2113			}
2114		}
2115
2116		if ((softc->quirks & SA_QUIRK_VARIABLE) &&
2117		    (softc->media_blksize != 0)) {
2118			softc->last_media_blksize = softc->media_blksize;
2119			softc->media_blksize = 0;
2120			error = sasetparams(periph, SA_PARAM_BLOCKSIZE,
2121			    0, 0, 0, SF_NO_PRINT);
2122			if (error) {
2123				/*
2124				 * If this fails and we were guessing, just
2125				 * assume that we got it wrong and go try
2126				 * fixed block mode. Don't even check against
2127				 * density code at this point.
2128				 */
2129				if (guessing) {
2130					softc->quirks &= ~SA_QUIRK_VARIABLE;
2131					softc->quirks |= SA_QUIRK_FIXED;
2132					if (softc->last_media_blksize == 0)
2133						softc->last_media_blksize = 512;
2134					goto tryagain;
2135				}
2136				xpt_print_path(ccb->ccb_h.path);
2137				printf("unable to set variable blocksize\n");
2138				goto exit;
2139			}
2140		}
2141
2142		/*
2143		 * Now that we have the current block size,
2144		 * set up some parameters for sastart's usage.
2145		 */
2146		if (softc->media_blksize) {
2147			softc->flags |= SA_FLAG_FIXED;
2148			if (powerof2(softc->media_blksize)) {
2149				softc->blk_shift =
2150				    ffs(softc->media_blksize) - 1;
2151				softc->blk_mask = softc->media_blksize - 1;
2152			} else {
2153				softc->blk_mask = ~0;
2154				softc->blk_shift = 0;
2155			}
2156		} else {
2157			/*
2158			 * The SCSI-3 spec allows 0 to mean "unspecified".
2159			 * The SCSI-1 spec allows 0 to mean 'infinite'.
2160			 *
2161			 * Either works here.
2162			 */
2163			if (softc->max_blk == 0) {
2164				softc->max_blk = ~0;
2165			}
2166			softc->blk_shift = 0;
2167			if (softc->blk_gran != 0) {
2168				softc->blk_mask = softc->blk_gran - 1;
2169			} else {
2170				softc->blk_mask = 0;
2171			}
2172		}
2173
2174		if (write_protect)
2175			softc->flags |= SA_FLAG_TAPE_WP;
2176
2177		if (comp_supported) {
2178			if (softc->saved_comp_algorithm == 0)
2179				softc->saved_comp_algorithm =
2180				    softc->comp_algorithm;
2181			softc->flags |= SA_FLAG_COMP_SUPP;
2182			if (comp_enabled)
2183				softc->flags |= SA_FLAG_COMP_ENABLED;
2184		} else
2185			softc->flags |= SA_FLAG_COMP_UNSUPP;
2186
2187		if ((softc->buffer_mode == SMH_SA_BUF_MODE_NOBUF) &&
2188		    (softc->quirks & SA_QUIRK_NO_MODESEL) == 0) {
2189			error = sasetparams(periph, SA_PARAM_BUFF_MODE, 0,
2190			    0, 0, SF_NO_PRINT);
2191			if (error == 0) {
2192				softc->buffer_mode = SMH_SA_BUF_MODE_SIBUF;
2193			} else {
2194				xpt_print_path(ccb->ccb_h.path);
2195				printf("unable to set buffered mode\n");
2196			}
2197			error = 0;	/* not an error */
2198		}
2199
2200
2201		if (error == 0) {
2202			softc->flags |= SA_FLAG_TAPE_MOUNTED;
2203		}
2204exit:
2205		if (rblim != NULL)
2206			free(rblim, M_TEMP);
2207
2208		if (error != 0) {
2209			softc->dsreg = MTIO_DSREG_NIL;
2210		} else {
2211			softc->fileno = softc->blkno = 0;
2212			softc->dsreg = MTIO_DSREG_REST;
2213		}
2214#ifdef	SA_1FM_AT_EOD
2215		if ((softc->quirks & SA_QUIRK_2FM) == 0)
2216			softc->quirks |= SA_QUIRK_1FM;
2217#else
2218		if ((softc->quirks & SA_QUIRK_1FM) == 0)
2219			softc->quirks |= SA_QUIRK_2FM;
2220#endif
2221	} else
2222		xpt_release_ccb(ccb);
2223
2224	/*
2225	 * If we return an error, we're not mounted any more,
2226	 * so release any device reservation.
2227	 */
2228	if (error != 0) {
2229		(void) sareservereleaseunit(periph, FALSE);
2230	} else {
2231		/*
2232		 * Clear I/O residual.
2233		 */
2234		softc->last_io_resid = 0;
2235		softc->last_ctl_resid = 0;
2236	}
2237	return (error);
2238}
2239
2240/*
2241 * How many filemarks do we need to write if we were to terminate the
2242 * tape session right now? Note that this can be a negative number
2243 */
2244
2245static int
2246samarkswanted(struct cam_periph *periph)
2247{
2248	int	markswanted;
2249	struct	sa_softc *softc;
2250
2251	softc = (struct sa_softc *)periph->softc;
2252	markswanted = 0;
2253	if ((softc->flags & SA_FLAG_TAPE_WRITTEN) != 0) {
2254		markswanted++;
2255		if (softc->quirks & SA_QUIRK_2FM)
2256			markswanted++;
2257	}
2258	markswanted -= softc->filemarks;
2259	return (markswanted);
2260}
2261
2262static int
2263sacheckeod(struct cam_periph *periph)
2264{
2265	int	error;
2266	int	markswanted;
2267	struct	sa_softc *softc;
2268
2269	softc = (struct sa_softc *)periph->softc;
2270	markswanted = samarkswanted(periph);
2271
2272	if (markswanted > 0) {
2273		error = sawritefilemarks(periph, markswanted, FALSE);
2274	} else {
2275		error = 0;
2276	}
2277	return (error);
2278}
2279
2280static int
2281saerror(union ccb *ccb, u_int32_t cflgs, u_int32_t sflgs)
2282{
2283	static const char *toobig =
2284	    "%d-byte tape record bigger than supplied buffer\n";
2285	struct	cam_periph *periph;
2286	struct	sa_softc *softc;
2287	struct	ccb_scsiio *csio;
2288	struct	scsi_sense_data *sense;
2289	u_int32_t resid = 0;
2290	int32_t	info = 0;
2291	cam_status status;
2292	int error_code, sense_key, asc, ascq, error, aqvalid;
2293
2294	periph = xpt_path_periph(ccb->ccb_h.path);
2295	softc = (struct sa_softc *)periph->softc;
2296	csio = &ccb->csio;
2297	sense = &csio->sense_data;
2298	scsi_extract_sense(sense, &error_code, &sense_key, &asc, &ascq);
2299	aqvalid = sense->extra_len >= 6;
2300	error = 0;
2301
2302	status = csio->ccb_h.status & CAM_STATUS_MASK;
2303
2304	/*
2305	 * Calculate/latch up, any residuals... We do this in a funny 2-step
2306	 * so we can print stuff here if we have CAM_DEBUG enabled for this
2307	 * unit.
2308	 */
2309	if (status == CAM_SCSI_STATUS_ERROR) {
2310		if ((sense->error_code & SSD_ERRCODE_VALID) != 0) {
2311			info = (int32_t) scsi_4btoul(sense->info);
2312			resid = info;
2313			if ((softc->flags & SA_FLAG_FIXED) != 0)
2314				resid *= softc->media_blksize;
2315		} else {
2316			resid = csio->dxfer_len;
2317			info = resid;
2318			if ((softc->flags & SA_FLAG_FIXED) != 0) {
2319				if (softc->media_blksize)
2320					info /= softc->media_blksize;
2321			}
2322		}
2323		if (CCB_Type(csio) == SA_CCB_BUFFER_IO) {
2324			bcopy((caddr_t) sense, (caddr_t) &softc->last_io_sense,
2325			    sizeof (struct scsi_sense_data));
2326			bcopy(csio->cdb_io.cdb_bytes, softc->last_io_cdb,
2327			    (int) csio->cdb_len);
2328			softc->last_io_resid = resid;
2329			softc->last_resid_was_io = 1;
2330		} else {
2331			bcopy((caddr_t) sense, (caddr_t) &softc->last_ctl_sense,
2332			    sizeof (struct scsi_sense_data));
2333			bcopy(csio->cdb_io.cdb_bytes, softc->last_ctl_cdb,
2334			    (int) csio->cdb_len);
2335			softc->last_ctl_resid = resid;
2336			softc->last_resid_was_io = 0;
2337		}
2338		CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("CDB[0]=0x%x Key 0x%x "
2339		    "ASC/ASCQ 0x%x/0x%x CAM STATUS 0x%x flags 0x%x resid %d "
2340		    "dxfer_len %d\n", csio->cdb_io.cdb_bytes[0] & 0xff,
2341		    sense_key, asc, ascq, status,
2342		    sense->flags & ~SSD_KEY_RESERVED, resid, csio->dxfer_len));
2343	} else {
2344		CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
2345		    ("Cam Status 0x%x\n", status));
2346	}
2347
2348	switch (status) {
2349	case CAM_REQ_CMP:
2350		return (0);
2351	case CAM_SCSI_STATUS_ERROR:
2352		/*
2353		 * If a read/write command, we handle it here.
2354		 */
2355		if (CCB_Type(csio) != SA_CCB_WAITING) {
2356			break;
2357		}
2358		/*
2359		 * If this was just EOM/EOP, Filemark, Setmark or ILI detected
2360		 * on a non read/write command, we assume it's not an error
2361		 * and propagate the residule and return.
2362		 */
2363		if ((aqvalid && asc == 0 && ascq > 0 && ascq <= 5) ||
2364		    (aqvalid == 0 && sense_key == SSD_KEY_NO_SENSE)) {
2365			csio->resid = resid;
2366			QFRLS(ccb);
2367			return (0);
2368		}
2369		/*
2370		 * Otherwise, we let the common code handle this.
2371		 */
2372		return (cam_periph_error(ccb, cflgs, sflgs, &softc->saved_ccb));
2373
2374	/*
2375	 * XXX: To Be Fixed
2376	 * We cannot depend upon CAM honoring retry counts for these.
2377	 */
2378	case CAM_SCSI_BUS_RESET:
2379	case CAM_BDR_SENT:
2380		if (ccb->ccb_h.retry_count <= 0) {
2381			return (EIO);
2382			break;
2383		}
2384		/* FALLTHROUGH */
2385	default:
2386		return (cam_periph_error(ccb, cflgs, sflgs, &softc->saved_ccb));
2387	}
2388
2389	/*
2390	 * Handle filemark, end of tape, mismatched record sizes....
2391	 * From this point out, we're only handling read/write cases.
2392	 * Handle writes && reads differently.
2393	 */
2394
2395	if (csio->cdb_io.cdb_bytes[0] == SA_WRITE) {
2396		if (sense_key == SSD_KEY_VOLUME_OVERFLOW) {
2397			csio->resid = resid;
2398			error = ENOSPC;
2399		} else if (sense->flags & SSD_EOM) {
2400			softc->flags |= SA_FLAG_EOM_PENDING;
2401			/*
2402			 * Grotesque as it seems, the few times
2403			 * I've actually seen a non-zero resid,
2404			 * the tape drive actually lied and had
2405			 * writtent all the data!.
2406			 */
2407			csio->resid = 0;
2408		}
2409	} else {
2410		csio->resid = resid;
2411		if (sense_key == SSD_KEY_BLANK_CHECK) {
2412			if (softc->quirks & SA_QUIRK_1FM) {
2413				error = 0;
2414				softc->flags |= SA_FLAG_EOM_PENDING;
2415			} else {
2416				error = EIO;
2417			}
2418		} else if (sense->flags & SSD_FILEMARK) {
2419			if (softc->flags & SA_FLAG_FIXED) {
2420				error = -1;
2421				softc->flags |= SA_FLAG_EOF_PENDING;
2422			}
2423			/*
2424			 * Unconditionally, if we detected a filemark on a read,
2425			 * mark that we've run moved a file ahead.
2426			 */
2427			if (softc->fileno != (daddr_t) -1) {
2428				softc->fileno++;
2429				softc->blkno = 0;
2430				csio->ccb_h.ccb_pflags |= SA_POSITION_UPDATED;
2431			}
2432		}
2433	}
2434
2435	/*
2436	 * Incorrect Length usually applies to read, but can apply to writes.
2437	 */
2438	if (error == 0 && (sense->flags & SSD_ILI)) {
2439		if (info < 0) {
2440			xpt_print_path(csio->ccb_h.path);
2441			printf(toobig, csio->dxfer_len - info);
2442			csio->resid = csio->dxfer_len;
2443			error = EIO;
2444		} else {
2445			csio->resid = resid;
2446			if (softc->flags & SA_FLAG_FIXED) {
2447				softc->flags |= SA_FLAG_EIO_PENDING;
2448			}
2449			/*
2450			 * Bump the block number if we hadn't seen a filemark.
2451			 * Do this independent of errors (we've moved anyway).
2452			 */
2453			if ((sense->flags & SSD_FILEMARK) == 0) {
2454				if (softc->blkno != (daddr_t) -1) {
2455					softc->blkno++;
2456					csio->ccb_h.ccb_pflags |=
2457					   SA_POSITION_UPDATED;
2458				}
2459			}
2460		}
2461	}
2462
2463	if (error <= 0) {
2464		/*
2465		 * Unfreeze the queue if frozen as we're not returning anything
2466		 * to our waiters that would indicate an I/O error has occurred
2467		 * (yet).
2468		 */
2469		QFRLS(ccb);
2470		error = 0;
2471	}
2472	return (error);
2473}
2474
2475static int
2476sagetparams(struct cam_periph *periph, sa_params params_to_get,
2477	    u_int32_t *blocksize, u_int8_t *density, u_int32_t *numblocks,
2478	    int *buff_mode, u_int8_t *write_protect, u_int8_t *speed,
2479	    int *comp_supported, int *comp_enabled, u_int32_t *comp_algorithm,
2480	    sa_comp_t *tcs)
2481{
2482	union ccb *ccb;
2483	void *mode_buffer;
2484	struct scsi_mode_header_6 *mode_hdr;
2485	struct scsi_mode_blk_desc *mode_blk;
2486	int mode_buffer_len;
2487	struct sa_softc *softc;
2488	u_int8_t cpage;
2489	int error;
2490	cam_status status;
2491
2492	softc = (struct sa_softc *)periph->softc;
2493	ccb = cam_periph_getccb(periph, 1);
2494	if (softc->quirks & SA_QUIRK_NO_CPAGE)
2495		cpage = SA_DEVICE_CONFIGURATION_PAGE;
2496	else
2497		cpage = SA_DATA_COMPRESSION_PAGE;
2498
2499retry:
2500	mode_buffer_len = sizeof(*mode_hdr) + sizeof(*mode_blk);
2501
2502	if (params_to_get & SA_PARAM_COMPRESSION) {
2503		if (softc->quirks & SA_QUIRK_NOCOMP) {
2504			*comp_supported = FALSE;
2505			params_to_get &= ~SA_PARAM_COMPRESSION;
2506		} else
2507			mode_buffer_len += sizeof (sa_comp_t);
2508	}
2509
2510	mode_buffer = malloc(mode_buffer_len, M_TEMP, M_WAITOK | M_ZERO);
2511	mode_hdr = (struct scsi_mode_header_6 *)mode_buffer;
2512	mode_blk = (struct scsi_mode_blk_desc *)&mode_hdr[1];
2513
2514	/* it is safe to retry this */
2515	scsi_mode_sense(&ccb->csio, 5, sadone, MSG_SIMPLE_Q_TAG, FALSE,
2516	    SMS_PAGE_CTRL_CURRENT, (params_to_get & SA_PARAM_COMPRESSION) ?
2517	    cpage : SMS_VENDOR_SPECIFIC_PAGE, mode_buffer, mode_buffer_len,
2518	    SSD_FULL_SIZE, SCSIOP_TIMEOUT);
2519
2520	error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
2521	    softc->device_stats);
2522	QFRLS(ccb);
2523
2524	status = ccb->ccb_h.status & CAM_STATUS_MASK;
2525
2526	if (error == EINVAL && (params_to_get & SA_PARAM_COMPRESSION) != 0) {
2527		/*
2528		 * Hmm. Let's see if we can try another page...
2529		 * If we've already done that, give up on compression
2530		 * for this device and remember this for the future
2531		 * and attempt the request without asking for compression
2532		 * info.
2533		 */
2534		if (cpage == SA_DATA_COMPRESSION_PAGE) {
2535			cpage = SA_DEVICE_CONFIGURATION_PAGE;
2536			goto retry;
2537		}
2538		softc->quirks |= SA_QUIRK_NOCOMP;
2539		free(mode_buffer, M_TEMP);
2540		goto retry;
2541	} else if (status == CAM_SCSI_STATUS_ERROR) {
2542		/* Tell the user about the fatal error. */
2543		scsi_sense_print(&ccb->csio);
2544		goto sagetparamsexit;
2545	}
2546
2547	/*
2548	 * If the user only wants the compression information, and
2549	 * the device doesn't send back the block descriptor, it's
2550	 * no big deal.  If the user wants more than just
2551	 * compression, though, and the device doesn't pass back the
2552	 * block descriptor, we need to send another mode sense to
2553	 * get the block descriptor.
2554	 */
2555	if ((mode_hdr->blk_desc_len == 0) &&
2556	    (params_to_get & SA_PARAM_COMPRESSION) &&
2557	    (params_to_get & ~(SA_PARAM_COMPRESSION))) {
2558
2559		/*
2560		 * Decrease the mode buffer length by the size of
2561		 * the compression page, to make sure the data
2562		 * there doesn't get overwritten.
2563		 */
2564		mode_buffer_len -= sizeof (sa_comp_t);
2565
2566		/*
2567		 * Now move the compression page that we presumably
2568		 * got back down the memory chunk a little bit so
2569		 * it doesn't get spammed.
2570		 */
2571		bcopy(&mode_hdr[0], &mode_hdr[1], sizeof (sa_comp_t));
2572		bzero(&mode_hdr[0], sizeof (mode_hdr[0]));
2573
2574		/*
2575		 * Now, we issue another mode sense and just ask
2576		 * for the block descriptor, etc.
2577		 */
2578
2579		scsi_mode_sense(&ccb->csio, 2, sadone, MSG_SIMPLE_Q_TAG, FALSE,
2580		    SMS_PAGE_CTRL_CURRENT, SMS_VENDOR_SPECIFIC_PAGE,
2581		    mode_buffer, mode_buffer_len, SSD_FULL_SIZE,
2582		    SCSIOP_TIMEOUT);
2583
2584		error = cam_periph_runccb(ccb, saerror, 0, SF_NO_PRINT,
2585		    softc->device_stats);
2586		QFRLS(ccb);
2587
2588		if (error != 0)
2589			goto sagetparamsexit;
2590	}
2591
2592	if (params_to_get & SA_PARAM_BLOCKSIZE)
2593		*blocksize = scsi_3btoul(mode_blk->blklen);
2594
2595	if (params_to_get & SA_PARAM_NUMBLOCKS)
2596		*numblocks = scsi_3btoul(mode_blk->nblocks);
2597
2598	if (params_to_get & SA_PARAM_BUFF_MODE)
2599		*buff_mode = mode_hdr->dev_spec & SMH_SA_BUF_MODE_MASK;
2600
2601	if (params_to_get & SA_PARAM_DENSITY)
2602		*density = mode_blk->density;
2603
2604	if (params_to_get & SA_PARAM_WP)
2605		*write_protect = (mode_hdr->dev_spec & SMH_SA_WP)? TRUE : FALSE;
2606
2607	if (params_to_get & SA_PARAM_SPEED)
2608		*speed = mode_hdr->dev_spec & SMH_SA_SPEED_MASK;
2609
2610	if (params_to_get & SA_PARAM_COMPRESSION) {
2611		sa_comp_t *ntcs = (sa_comp_t *) &mode_blk[1];
2612		if (cpage == SA_DATA_COMPRESSION_PAGE) {
2613			struct scsi_data_compression_page *cp = &ntcs->dcomp;
2614			*comp_supported =
2615			    (cp->dce_and_dcc & SA_DCP_DCC)? TRUE : FALSE;
2616			*comp_enabled =
2617			    (cp->dce_and_dcc & SA_DCP_DCE)? TRUE : FALSE;
2618			*comp_algorithm = scsi_4btoul(cp->comp_algorithm);
2619		} else {
2620			struct scsi_dev_conf_page *cp = &ntcs->dconf;
2621			/*
2622			 * We don't really know whether this device supports
2623			 * Data Compression if the the algorithm field is
2624			 * zero. Just say we do.
2625			 */
2626			*comp_supported = TRUE;
2627			*comp_enabled =
2628			    (cp->sel_comp_alg != SA_COMP_NONE)? TRUE : FALSE;
2629			*comp_algorithm = cp->sel_comp_alg;
2630		}
2631		if (tcs != NULL)
2632			bcopy(ntcs, tcs, sizeof (sa_comp_t));
2633	}
2634
2635	if (CAM_DEBUGGED(periph->path, CAM_DEBUG_INFO)) {
2636		int idx;
2637		char *xyz = mode_buffer;
2638		xpt_print_path(periph->path);
2639		printf("Mode Sense Data=");
2640		for (idx = 0; idx < mode_buffer_len; idx++)
2641			printf(" 0x%02x", xyz[idx] & 0xff);
2642		printf("\n");
2643	}
2644
2645sagetparamsexit:
2646
2647	xpt_release_ccb(ccb);
2648	free(mode_buffer, M_TEMP);
2649	return (error);
2650}
2651
2652/*
2653 * The purpose of this function is to set one of four different parameters
2654 * for a tape drive:
2655 *	- blocksize
2656 *	- density
2657 *	- compression / compression algorithm
2658 *	- buffering mode
2659 *
2660 * The assumption is that this will be called from saioctl(), and therefore
2661 * from a process context.  Thus the waiting malloc calls below.  If that
2662 * assumption ever changes, the malloc calls should be changed to be
2663 * NOWAIT mallocs.
2664 *
2665 * Any or all of the four parameters may be set when this function is
2666 * called.  It should handle setting more than one parameter at once.
2667 */
2668static int
2669sasetparams(struct cam_periph *periph, sa_params params_to_set,
2670	    u_int32_t blocksize, u_int8_t density, u_int32_t calg,
2671	    u_int32_t sense_flags)
2672{
2673	struct sa_softc *softc;
2674	u_int32_t current_blocksize;
2675	u_int32_t current_calg;
2676	u_int8_t current_density;
2677	u_int8_t current_speed;
2678	int comp_enabled, comp_supported;
2679	void *mode_buffer;
2680	int mode_buffer_len;
2681	struct scsi_mode_header_6 *mode_hdr;
2682	struct scsi_mode_blk_desc *mode_blk;
2683	sa_comp_t *ccomp, *cpage;
2684	int buff_mode;
2685	union ccb *ccb = NULL;
2686	int error;
2687
2688	softc = (struct sa_softc *)periph->softc;
2689
2690	ccomp = malloc(sizeof (sa_comp_t), M_TEMP, M_WAITOK);
2691
2692	/*
2693	 * Since it doesn't make sense to set the number of blocks, or
2694	 * write protection, we won't try to get the current value.  We
2695	 * always want to get the blocksize, so we can set it back to the
2696	 * proper value.
2697	 */
2698	error = sagetparams(periph,
2699	    params_to_set | SA_PARAM_BLOCKSIZE | SA_PARAM_SPEED,
2700	    &current_blocksize, &current_density, NULL, &buff_mode, NULL,
2701	    &current_speed, &comp_supported, &comp_enabled,
2702	    &current_calg, ccomp);
2703
2704	if (error != 0) {
2705		free(ccomp, M_TEMP);
2706		return (error);
2707	}
2708
2709	mode_buffer_len = sizeof(*mode_hdr) + sizeof(*mode_blk);
2710	if (params_to_set & SA_PARAM_COMPRESSION)
2711		mode_buffer_len += sizeof (sa_comp_t);
2712
2713	mode_buffer = malloc(mode_buffer_len, M_TEMP, M_WAITOK | M_ZERO);
2714
2715	mode_hdr = (struct scsi_mode_header_6 *)mode_buffer;
2716	mode_blk = (struct scsi_mode_blk_desc *)&mode_hdr[1];
2717
2718	ccb = cam_periph_getccb(periph, 1);
2719
2720retry:
2721
2722	if (params_to_set & SA_PARAM_COMPRESSION) {
2723		if (mode_blk) {
2724			cpage = (sa_comp_t *)&mode_blk[1];
2725		} else {
2726			cpage = (sa_comp_t *)&mode_hdr[1];
2727		}
2728		bcopy(ccomp, cpage, sizeof (sa_comp_t));
2729		cpage->hdr.pagecode &= ~0x80;
2730	} else
2731		cpage = NULL;
2732
2733	/*
2734	 * If the caller wants us to set the blocksize, use the one they
2735	 * pass in.  Otherwise, use the blocksize we got back from the
2736	 * mode select above.
2737	 */
2738	if (mode_blk) {
2739		if (params_to_set & SA_PARAM_BLOCKSIZE)
2740			scsi_ulto3b(blocksize, mode_blk->blklen);
2741		else
2742			scsi_ulto3b(current_blocksize, mode_blk->blklen);
2743
2744		/*
2745		 * Set density if requested, else preserve old density.
2746		 * SCSI_SAME_DENSITY only applies to SCSI-2 or better
2747		 * devices, else density we've latched up in our softc.
2748		 */
2749		if (params_to_set & SA_PARAM_DENSITY) {
2750			mode_blk->density = density;
2751		} else if (softc->scsi_rev > SCSI_REV_CCS) {
2752			mode_blk->density = SCSI_SAME_DENSITY;
2753		} else {
2754			mode_blk->density = softc->media_density;
2755		}
2756	}
2757
2758	/*
2759	 * For mode selects, these two fields must be zero.
2760	 */
2761	mode_hdr->data_length = 0;
2762	mode_hdr->medium_type = 0;
2763
2764	/* set the speed to the current value */
2765	mode_hdr->dev_spec = current_speed;
2766
2767	/* set single-initiator buffering mode */
2768	mode_hdr->dev_spec |= SMH_SA_BUF_MODE_SIBUF;
2769
2770	if (mode_blk)
2771		mode_hdr->blk_desc_len = sizeof(struct scsi_mode_blk_desc);
2772	else
2773		mode_hdr->blk_desc_len = 0;
2774
2775	/*
2776	 * First, if the user wants us to set the compression algorithm or
2777	 * just turn compression on, check to make sure that this drive
2778	 * supports compression.
2779	 */
2780	if (params_to_set & SA_PARAM_COMPRESSION) {
2781		/*
2782		 * If the compression algorithm is 0, disable compression.
2783		 * If the compression algorithm is non-zero, enable
2784		 * compression and set the compression type to the
2785		 * specified compression algorithm, unless the algorithm is
2786		 * MT_COMP_ENABLE.  In that case, we look at the
2787		 * compression algorithm that is currently set and if it is
2788		 * non-zero, we leave it as-is.  If it is zero, and we have
2789		 * saved a compression algorithm from a time when
2790		 * compression was enabled before, set the compression to
2791		 * the saved value.
2792		 */
2793		switch (ccomp->hdr.pagecode & ~0x80) {
2794		case SA_DATA_COMPRESSION_PAGE:
2795		if (ccomp->dcomp.dce_and_dcc & SA_DCP_DCC) {
2796			struct scsi_data_compression_page *dcp = &cpage->dcomp;
2797			if (calg == 0) {
2798				/*
2799				 * Disable compression, but leave the
2800				 * decompression and the capability bit
2801				 * alone.
2802				 */
2803				dcp->dce_and_dcc = SA_DCP_DCC;
2804				dcp->dde_and_red |= SA_DCP_DDE;
2805				break;
2806			}
2807			/* enable compression && decompression */
2808			dcp->dce_and_dcc = SA_DCP_DCE | SA_DCP_DCC;
2809			dcp->dde_and_red |= SA_DCP_DDE;
2810			/*
2811			 * If there, use compression algorithm from caller.
2812			 * Otherwise, if there's a saved compression algorithm
2813			 * and there is no current algorithm, use the saved
2814			 * algorithm. Else parrot back what we got and hope
2815			 * for the best.
2816			 */
2817			if (calg != MT_COMP_ENABLE) {
2818				scsi_ulto4b(calg, dcp->comp_algorithm);
2819				scsi_ulto4b(calg, dcp->decomp_algorithm);
2820			} else if (scsi_4btoul(dcp->comp_algorithm) == 0 &&
2821			    softc->saved_comp_algorithm != 0) {
2822				scsi_ulto4b(softc->saved_comp_algorithm,
2823				    dcp->comp_algorithm);
2824				scsi_ulto4b(softc->saved_comp_algorithm,
2825				    dcp->decomp_algorithm);
2826			}
2827			break;
2828		}
2829		case SA_DEVICE_CONFIGURATION_PAGE:
2830		{
2831			struct scsi_dev_conf_page *dcp = &cpage->dconf;
2832			if (calg == 0) {
2833				dcp->sel_comp_alg = SA_COMP_NONE;
2834				break;
2835			}
2836			if (calg != MT_COMP_ENABLE) {
2837				dcp->sel_comp_alg = calg;
2838			} else if (dcp->sel_comp_alg == SA_COMP_NONE &&
2839			    softc->saved_comp_algorithm != 0) {
2840				dcp->sel_comp_alg = softc->saved_comp_algorithm;
2841			}
2842			break;
2843		}
2844		default:
2845			/*
2846			 * The drive doesn't seem to support compression,
2847			 * so turn off the set compression bit.
2848			 */
2849			params_to_set &= ~SA_PARAM_COMPRESSION;
2850			xpt_print_path(periph->path);
2851			printf("device does not seem to support compression\n");
2852
2853			/*
2854			 * If that was the only thing the user wanted us to set,
2855			 * clean up allocated resources and return with
2856			 * 'operation not supported'.
2857			 */
2858			if (params_to_set == SA_PARAM_NONE) {
2859				free(mode_buffer, M_TEMP);
2860				xpt_release_ccb(ccb);
2861				return (ENODEV);
2862			}
2863
2864			/*
2865			 * That wasn't the only thing the user wanted us to set.
2866			 * So, decrease the stated mode buffer length by the
2867			 * size of the compression mode page.
2868			 */
2869			mode_buffer_len -= sizeof(sa_comp_t);
2870		}
2871	}
2872
2873	/* It is safe to retry this operation */
2874	scsi_mode_select(&ccb->csio, 5, sadone, MSG_SIMPLE_Q_TAG,
2875	    (params_to_set & SA_PARAM_COMPRESSION)? TRUE : FALSE,
2876	    FALSE, mode_buffer, mode_buffer_len, SSD_FULL_SIZE, SCSIOP_TIMEOUT);
2877
2878	error = cam_periph_runccb(ccb, saerror, 0,
2879	    sense_flags, softc->device_stats);
2880	QFRLS(ccb);
2881
2882	if (CAM_DEBUGGED(periph->path, CAM_DEBUG_INFO)) {
2883		int idx;
2884		char *xyz = mode_buffer;
2885		xpt_print_path(periph->path);
2886		printf("Err%d, Mode Select Data=", error);
2887		for (idx = 0; idx < mode_buffer_len; idx++)
2888			printf(" 0x%02x", xyz[idx] & 0xff);
2889		printf("\n");
2890	}
2891
2892
2893	if (error) {
2894		/*
2895		 * If we can, try without setting density/blocksize.
2896		 */
2897		if (mode_blk) {
2898			if ((params_to_set &
2899			    (SA_PARAM_DENSITY|SA_PARAM_BLOCKSIZE)) == 0) {
2900				mode_blk = NULL;
2901				goto retry;
2902			}
2903		} else {
2904			mode_blk = (struct scsi_mode_blk_desc *)&mode_hdr[1];
2905			cpage = (sa_comp_t *)&mode_blk[1];
2906		}
2907
2908		/*
2909		 * If we were setting the blocksize, and that failed, we
2910		 * want to set it to its original value.  If we weren't
2911		 * setting the blocksize, we don't want to change it.
2912		 */
2913		scsi_ulto3b(current_blocksize, mode_blk->blklen);
2914
2915		/*
2916		 * Set density if requested, else preserve old density.
2917		 * SCSI_SAME_DENSITY only applies to SCSI-2 or better
2918		 * devices, else density we've latched up in our softc.
2919		 */
2920		if (params_to_set & SA_PARAM_DENSITY) {
2921			mode_blk->density = current_density;
2922		} else if (softc->scsi_rev > SCSI_REV_CCS) {
2923			mode_blk->density = SCSI_SAME_DENSITY;
2924		} else {
2925			mode_blk->density = softc->media_density;
2926		}
2927
2928		if (params_to_set & SA_PARAM_COMPRESSION)
2929			bcopy(ccomp, cpage, sizeof (sa_comp_t));
2930
2931		/*
2932		 * The retry count is the only CCB field that might have been
2933		 * changed that we care about, so reset it back to 1.
2934		 */
2935		ccb->ccb_h.retry_count = 1;
2936		cam_periph_runccb(ccb, saerror, 0, sense_flags,
2937		    softc->device_stats);
2938		QFRLS(ccb);
2939	}
2940
2941	xpt_release_ccb(ccb);
2942
2943	if (ccomp != NULL)
2944		free(ccomp, M_TEMP);
2945
2946	if (params_to_set & SA_PARAM_COMPRESSION) {
2947		if (error) {
2948			softc->flags &= ~SA_FLAG_COMP_ENABLED;
2949			/*
2950			 * Even if we get an error setting compression,
2951			 * do not say that we don't support it. We could
2952			 * have been wrong, or it may be media specific.
2953			 *	softc->flags &= ~SA_FLAG_COMP_SUPP;
2954			 */
2955			softc->saved_comp_algorithm = softc->comp_algorithm;
2956			softc->comp_algorithm = 0;
2957		} else {
2958			softc->flags |= SA_FLAG_COMP_ENABLED;
2959			softc->comp_algorithm = calg;
2960		}
2961	}
2962
2963	free(mode_buffer, M_TEMP);
2964	return (error);
2965}
2966
2967static void
2968saprevent(struct cam_periph *periph, int action)
2969{
2970	struct	sa_softc *softc;
2971	union	ccb *ccb;
2972	int	error, sf;
2973
2974	softc = (struct sa_softc *)periph->softc;
2975
2976	if ((action == PR_ALLOW) && (softc->flags & SA_FLAG_TAPE_LOCKED) == 0)
2977		return;
2978	if ((action == PR_PREVENT) && (softc->flags & SA_FLAG_TAPE_LOCKED) != 0)
2979		return;
2980
2981	/*
2982	 * We can be quiet about illegal requests.
2983	 */
2984	if (CAM_DEBUGGED(periph->path, CAM_DEBUG_INFO)) {
2985		sf = 0;
2986	} else
2987		sf = SF_QUIET_IR;
2988
2989	ccb = cam_periph_getccb(periph, 1);
2990
2991	/* It is safe to retry this operation */
2992	scsi_prevent(&ccb->csio, 5, sadone, MSG_SIMPLE_Q_TAG, action,
2993	    SSD_FULL_SIZE, SCSIOP_TIMEOUT);
2994
2995	error = cam_periph_runccb(ccb, saerror, 0, sf, softc->device_stats);
2996	QFRLS(ccb);
2997	if (error == 0) {
2998		if (action == PR_ALLOW)
2999			softc->flags &= ~SA_FLAG_TAPE_LOCKED;
3000		else
3001			softc->flags |= SA_FLAG_TAPE_LOCKED;
3002	}
3003
3004	xpt_release_ccb(ccb);
3005}
3006
3007static int
3008sarewind(struct cam_periph *periph)
3009{
3010	union	ccb *ccb;
3011	struct	sa_softc *softc;
3012	int	error;
3013
3014	softc = (struct sa_softc *)periph->softc;
3015
3016	ccb = cam_periph_getccb(periph, 1);
3017
3018	/* It is safe to retry this operation */
3019	scsi_rewind(&ccb->csio, 2, sadone, MSG_SIMPLE_Q_TAG, FALSE,
3020	    SSD_FULL_SIZE, REWIND_TIMEOUT);
3021
3022	softc->dsreg = MTIO_DSREG_REW;
3023	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
3024	softc->dsreg = MTIO_DSREG_REST;
3025
3026	if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
3027		cam_release_devq(ccb->ccb_h.path, 0, 0, 0, FALSE);
3028
3029	xpt_release_ccb(ccb);
3030	if (error == 0)
3031		softc->fileno = softc->blkno = (daddr_t) 0;
3032	else
3033		softc->fileno = softc->blkno = (daddr_t) -1;
3034	return (error);
3035}
3036
3037static int
3038saspace(struct cam_periph *periph, int count, scsi_space_code code)
3039{
3040	union	ccb *ccb;
3041	struct	sa_softc *softc;
3042	int	error;
3043
3044	softc = (struct sa_softc *)periph->softc;
3045
3046	ccb = cam_periph_getccb(periph, 1);
3047
3048	/* This cannot be retried */
3049
3050	scsi_space(&ccb->csio, 0, sadone, MSG_SIMPLE_Q_TAG, code, count,
3051	    SSD_FULL_SIZE, SPACE_TIMEOUT);
3052
3053	/*
3054	 * Clear residual because we will be using it.
3055	 */
3056	softc->last_ctl_resid = 0;
3057
3058	softc->dsreg = (count < 0)? MTIO_DSREG_REV : MTIO_DSREG_FWD;
3059	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
3060	softc->dsreg = MTIO_DSREG_REST;
3061
3062	if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
3063		cam_release_devq(ccb->ccb_h.path, 0, 0, 0, FALSE);
3064
3065	xpt_release_ccb(ccb);
3066
3067	/*
3068	 * If a spacing operation has failed, we need to invalidate
3069	 * this mount.
3070	 *
3071	 * If the spacing operation was setmarks or to end of recorded data,
3072	 * we no longer know our relative position.
3073	 *
3074	 * If the spacing operations was spacing files in reverse, we
3075	 * take account of the residual, but still check against less
3076	 * than zero- if we've gone negative, we must have hit BOT.
3077	 *
3078	 * If the spacing operations was spacing records in reverse and
3079	 * we have a residual, we've either hit BOT or hit a filemark.
3080	 * In the former case, we know our new record number (0). In
3081	 * the latter case, we have absolutely no idea what the real
3082	 * record number is- we've stopped between the end of the last
3083	 * record in the previous file and the filemark that stopped
3084	 * our spacing backwards.
3085	 */
3086	if (error) {
3087		softc->fileno = softc->blkno = (daddr_t) -1;
3088	} else if (code == SS_SETMARKS || code == SS_EOD) {
3089		softc->fileno = softc->blkno = (daddr_t) -1;
3090	} else if (code == SS_FILEMARKS && softc->fileno != (daddr_t) -1) {
3091		softc->fileno += (count - softc->last_ctl_resid);
3092		if (softc->fileno < 0)	/* we must of hit BOT */
3093			softc->fileno = 0;
3094		softc->blkno = 0;
3095	} else if (code == SS_BLOCKS && softc->blkno != (daddr_t) -1) {
3096		softc->blkno += (count - softc->last_ctl_resid);
3097		if (count < 0) {
3098			if (softc->last_ctl_resid || softc->blkno < 0) {
3099				if (softc->fileno == 0) {
3100					softc->blkno = 0;
3101				} else {
3102					softc->blkno = (daddr_t) -1;
3103				}
3104			}
3105		}
3106	}
3107	return (error);
3108}
3109
3110static int
3111sawritefilemarks(struct cam_periph *periph, int nmarks, int setmarks)
3112{
3113	union	ccb *ccb;
3114	struct	sa_softc *softc;
3115	int	error, nwm = 0;
3116
3117	softc = (struct sa_softc *)periph->softc;
3118
3119	ccb = cam_periph_getccb(periph, 1);
3120	/*
3121	 * Clear residual because we will be using it.
3122	 */
3123	softc->last_ctl_resid = 0;
3124
3125	softc->dsreg = MTIO_DSREG_FMK;
3126	/* this *must* not be retried */
3127	scsi_write_filemarks(&ccb->csio, 0, sadone, MSG_SIMPLE_Q_TAG,
3128	    FALSE, setmarks, nmarks, SSD_FULL_SIZE, IO_TIMEOUT);
3129	softc->dsreg = MTIO_DSREG_REST;
3130
3131
3132	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
3133
3134	if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
3135		cam_release_devq(ccb->ccb_h.path, 0, 0, 0, FALSE);
3136
3137	if (error == 0 && nmarks) {
3138		struct sa_softc *softc = (struct sa_softc *)periph->softc;
3139		nwm = nmarks - softc->last_ctl_resid;
3140		softc->filemarks += nwm;
3141	}
3142
3143	xpt_release_ccb(ccb);
3144
3145	/*
3146	 * Update relative positions (if we're doing that).
3147	 */
3148	if (error) {
3149		softc->fileno = softc->blkno = (daddr_t) -1;
3150	} else if (softc->fileno != (daddr_t) -1) {
3151		softc->fileno += nwm;
3152		softc->blkno = 0;
3153	}
3154	return (error);
3155}
3156
3157static int
3158sardpos(struct cam_periph *periph, int hard, u_int32_t *blkptr)
3159{
3160	struct scsi_tape_position_data loc;
3161	union ccb *ccb;
3162	struct sa_softc *softc = (struct sa_softc *)periph->softc;
3163	int error;
3164
3165	/*
3166	 * We try and flush any buffered writes here if we were writing
3167	 * and we're trying to get hardware block position. It eats
3168	 * up performance substantially, but I'm wary of drive firmware.
3169	 *
3170	 * I think that *logical* block position is probably okay-
3171	 * but hardware block position might have to wait for data
3172	 * to hit media to be valid. Caveat Emptor.
3173	 */
3174
3175	if (hard && (softc->flags & SA_FLAG_TAPE_WRITTEN)) {
3176		error = sawritefilemarks(periph, 0, 0);
3177		if (error && error != EACCES)
3178			return (error);
3179	}
3180
3181	ccb = cam_periph_getccb(periph, 1);
3182	scsi_read_position(&ccb->csio, 1, sadone, MSG_SIMPLE_Q_TAG,
3183	    hard, &loc, SSD_FULL_SIZE, SCSIOP_TIMEOUT);
3184	softc->dsreg = MTIO_DSREG_RBSY;
3185	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
3186	softc->dsreg = MTIO_DSREG_REST;
3187	if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
3188		cam_release_devq(ccb->ccb_h.path, 0, 0, 0, 0);
3189
3190	if (error == 0) {
3191		if (loc.flags & SA_RPOS_UNCERTAIN) {
3192			error = EINVAL;		/* nothing is certain */
3193		} else {
3194			*blkptr = scsi_4btoul(loc.firstblk);
3195		}
3196	}
3197
3198	xpt_release_ccb(ccb);
3199	return (error);
3200}
3201
3202static int
3203sasetpos(struct cam_periph *periph, int hard, u_int32_t *blkptr)
3204{
3205	union ccb *ccb;
3206	struct sa_softc *softc;
3207	int error;
3208
3209	/*
3210	 * We used to try and flush any buffered writes here.
3211	 * Now we push this onto user applications to either
3212	 * flush the pending writes themselves (via a zero count
3213	 * WRITE FILEMARKS command) or they can trust their tape
3214	 * drive to do this correctly for them.
3215 	 */
3216
3217	softc = (struct sa_softc *)periph->softc;
3218	ccb = cam_periph_getccb(periph, 1);
3219
3220
3221	scsi_set_position(&ccb->csio, 1, sadone, MSG_SIMPLE_Q_TAG,
3222	    hard, *blkptr, SSD_FULL_SIZE, SPACE_TIMEOUT);
3223
3224
3225	softc->dsreg = MTIO_DSREG_POS;
3226	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
3227	softc->dsreg = MTIO_DSREG_REST;
3228	if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
3229		cam_release_devq(ccb->ccb_h.path, 0, 0, 0, 0);
3230	xpt_release_ccb(ccb);
3231	/*
3232	 * Note relative file && block number position as now unknown.
3233	 */
3234	softc->fileno = softc->blkno = (daddr_t) -1;
3235	return (error);
3236}
3237
3238static int
3239saretension(struct cam_periph *periph)
3240{
3241	union ccb *ccb;
3242	struct sa_softc *softc;
3243	int error;
3244
3245	softc = (struct sa_softc *)periph->softc;
3246
3247	ccb = cam_periph_getccb(periph, 1);
3248
3249	/* It is safe to retry this operation */
3250	scsi_load_unload(&ccb->csio, 5, sadone, MSG_SIMPLE_Q_TAG, FALSE,
3251	    FALSE, TRUE,  TRUE, SSD_FULL_SIZE, ERASE_TIMEOUT);
3252
3253	softc->dsreg = MTIO_DSREG_TEN;
3254	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
3255	softc->dsreg = MTIO_DSREG_REST;
3256
3257	if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
3258		cam_release_devq(ccb->ccb_h.path, 0, 0, 0, FALSE);
3259	xpt_release_ccb(ccb);
3260	if (error == 0)
3261		softc->fileno = softc->blkno = (daddr_t) 0;
3262	else
3263		softc->fileno = softc->blkno = (daddr_t) -1;
3264	return (error);
3265}
3266
3267static int
3268sareservereleaseunit(struct cam_periph *periph, int reserve)
3269{
3270	union ccb *ccb;
3271	struct sa_softc *softc;
3272	int error;
3273
3274	softc = (struct sa_softc *)periph->softc;
3275	ccb = cam_periph_getccb(periph,  1);
3276
3277	/* It is safe to retry this operation */
3278	scsi_reserve_release_unit(&ccb->csio, 2, sadone, MSG_SIMPLE_Q_TAG,
3279	    FALSE,  0, SSD_FULL_SIZE,  SCSIOP_TIMEOUT, reserve);
3280	softc->dsreg = MTIO_DSREG_RBSY;
3281	error = cam_periph_runccb(ccb, saerror, 0,
3282	    SF_RETRY_UA | SF_NO_PRINT, softc->device_stats);
3283	softc->dsreg = MTIO_DSREG_REST;
3284	QFRLS(ccb);
3285	xpt_release_ccb(ccb);
3286
3287	/*
3288	 * If the error was Illegal Request, then the device doesn't support
3289	 * RESERVE/RELEASE. This is not an error.
3290	 */
3291	if (error == EINVAL) {
3292		error = 0;
3293	}
3294
3295	return (error);
3296}
3297
3298static int
3299saloadunload(struct cam_periph *periph, int load)
3300{
3301	union	ccb *ccb;
3302	struct	sa_softc *softc;
3303	int	error;
3304
3305	softc = (struct sa_softc *)periph->softc;
3306
3307	ccb = cam_periph_getccb(periph, 1);
3308
3309	/* It is safe to retry this operation */
3310	scsi_load_unload(&ccb->csio, 5, sadone, MSG_SIMPLE_Q_TAG, FALSE,
3311	    FALSE, FALSE, load, SSD_FULL_SIZE, REWIND_TIMEOUT);
3312
3313	softc->dsreg = (load)? MTIO_DSREG_LD : MTIO_DSREG_UNL;
3314	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
3315	softc->dsreg = MTIO_DSREG_REST;
3316	QFRLS(ccb);
3317	xpt_release_ccb(ccb);
3318
3319	if (error || load == 0)
3320		softc->fileno = softc->blkno = (daddr_t) -1;
3321	else if (error == 0)
3322		softc->fileno = softc->blkno = (daddr_t) 0;
3323	return (error);
3324}
3325
3326static int
3327saerase(struct cam_periph *periph, int longerase)
3328{
3329
3330	union	ccb *ccb;
3331	struct	sa_softc *softc;
3332	int error;
3333
3334	softc = (struct sa_softc *)periph->softc;
3335
3336	ccb = cam_periph_getccb(periph, 1);
3337
3338	scsi_erase(&ccb->csio, 1, sadone, MSG_SIMPLE_Q_TAG, FALSE, longerase,
3339	    SSD_FULL_SIZE, ERASE_TIMEOUT);
3340
3341	softc->dsreg = MTIO_DSREG_ZER;
3342	error = cam_periph_runccb(ccb, saerror, 0, 0, softc->device_stats);
3343	softc->dsreg = MTIO_DSREG_REST;
3344
3345	if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
3346		cam_release_devq(ccb->ccb_h.path, 0, 0, 0, FALSE);
3347	xpt_release_ccb(ccb);
3348	return (error);
3349}
3350
3351#endif /* _KERNEL */
3352
3353/*
3354 * Read tape block limits command.
3355 */
3356void
3357scsi_read_block_limits(struct ccb_scsiio *csio, u_int32_t retries,
3358		   void (*cbfcnp)(struct cam_periph *, union ccb *),
3359		   u_int8_t tag_action,
3360		   struct scsi_read_block_limits_data *rlimit_buf,
3361		   u_int8_t sense_len, u_int32_t timeout)
3362{
3363	struct scsi_read_block_limits *scsi_cmd;
3364
3365	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_IN, tag_action,
3366	     (u_int8_t *)rlimit_buf, sizeof(*rlimit_buf), sense_len,
3367	     sizeof(*scsi_cmd), timeout);
3368
3369	scsi_cmd = (struct scsi_read_block_limits *)&csio->cdb_io.cdb_bytes;
3370	bzero(scsi_cmd, sizeof(*scsi_cmd));
3371	scsi_cmd->opcode = READ_BLOCK_LIMITS;
3372}
3373
3374void
3375scsi_sa_read_write(struct ccb_scsiio *csio, u_int32_t retries,
3376		   void (*cbfcnp)(struct cam_periph *, union ccb *),
3377		   u_int8_t tag_action, int readop, int sli,
3378		   int fixed, u_int32_t length, u_int8_t *data_ptr,
3379		   u_int32_t dxfer_len, u_int8_t sense_len, u_int32_t timeout)
3380{
3381	struct scsi_sa_rw *scsi_cmd;
3382
3383	scsi_cmd = (struct scsi_sa_rw *)&csio->cdb_io.cdb_bytes;
3384	scsi_cmd->opcode = readop ? SA_READ : SA_WRITE;
3385	scsi_cmd->sli_fixed = 0;
3386	if (sli && readop)
3387		scsi_cmd->sli_fixed |= SAR_SLI;
3388	if (fixed)
3389		scsi_cmd->sli_fixed |= SARW_FIXED;
3390	scsi_ulto3b(length, scsi_cmd->length);
3391	scsi_cmd->control = 0;
3392
3393	cam_fill_csio(csio, retries, cbfcnp, readop ? CAM_DIR_IN : CAM_DIR_OUT,
3394	    tag_action, data_ptr, dxfer_len, sense_len,
3395	    sizeof(*scsi_cmd), timeout);
3396}
3397
3398void
3399scsi_load_unload(struct ccb_scsiio *csio, u_int32_t retries,
3400		 void (*cbfcnp)(struct cam_periph *, union ccb *),
3401		 u_int8_t tag_action, int immediate, int eot,
3402		 int reten, int load, u_int8_t sense_len,
3403		 u_int32_t timeout)
3404{
3405	struct scsi_load_unload *scsi_cmd;
3406
3407	scsi_cmd = (struct scsi_load_unload *)&csio->cdb_io.cdb_bytes;
3408	bzero(scsi_cmd, sizeof(*scsi_cmd));
3409	scsi_cmd->opcode = LOAD_UNLOAD;
3410	if (immediate)
3411		scsi_cmd->immediate = SLU_IMMED;
3412	if (eot)
3413		scsi_cmd->eot_reten_load |= SLU_EOT;
3414	if (reten)
3415		scsi_cmd->eot_reten_load |= SLU_RETEN;
3416	if (load)
3417		scsi_cmd->eot_reten_load |= SLU_LOAD;
3418
3419	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action,
3420	    NULL, 0, sense_len, sizeof(*scsi_cmd), timeout);
3421}
3422
3423void
3424scsi_rewind(struct ccb_scsiio *csio, u_int32_t retries,
3425	    void (*cbfcnp)(struct cam_periph *, union ccb *),
3426	    u_int8_t tag_action, int immediate, u_int8_t sense_len,
3427	    u_int32_t timeout)
3428{
3429	struct scsi_rewind *scsi_cmd;
3430
3431	scsi_cmd = (struct scsi_rewind *)&csio->cdb_io.cdb_bytes;
3432	bzero(scsi_cmd, sizeof(*scsi_cmd));
3433	scsi_cmd->opcode = REWIND;
3434	if (immediate)
3435		scsi_cmd->immediate = SREW_IMMED;
3436
3437	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action, NULL,
3438	    0, sense_len, sizeof(*scsi_cmd), timeout);
3439}
3440
3441void
3442scsi_space(struct ccb_scsiio *csio, u_int32_t retries,
3443	   void (*cbfcnp)(struct cam_periph *, union ccb *),
3444	   u_int8_t tag_action, scsi_space_code code,
3445	   u_int32_t count, u_int8_t sense_len, u_int32_t timeout)
3446{
3447	struct scsi_space *scsi_cmd;
3448
3449	scsi_cmd = (struct scsi_space *)&csio->cdb_io.cdb_bytes;
3450	scsi_cmd->opcode = SPACE;
3451	scsi_cmd->code = code;
3452	scsi_ulto3b(count, scsi_cmd->count);
3453	scsi_cmd->control = 0;
3454
3455	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action, NULL,
3456	    0, sense_len, sizeof(*scsi_cmd), timeout);
3457}
3458
3459void
3460scsi_write_filemarks(struct ccb_scsiio *csio, u_int32_t retries,
3461		     void (*cbfcnp)(struct cam_periph *, union ccb *),
3462		     u_int8_t tag_action, int immediate, int setmark,
3463		     u_int32_t num_marks, u_int8_t sense_len,
3464		     u_int32_t timeout)
3465{
3466	struct scsi_write_filemarks *scsi_cmd;
3467
3468	scsi_cmd = (struct scsi_write_filemarks *)&csio->cdb_io.cdb_bytes;
3469	bzero(scsi_cmd, sizeof(*scsi_cmd));
3470	scsi_cmd->opcode = WRITE_FILEMARKS;
3471	if (immediate)
3472		scsi_cmd->byte2 |= SWFMRK_IMMED;
3473	if (setmark)
3474		scsi_cmd->byte2 |= SWFMRK_WSMK;
3475
3476	scsi_ulto3b(num_marks, scsi_cmd->num_marks);
3477
3478	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action, NULL,
3479	    0, sense_len, sizeof(*scsi_cmd), timeout);
3480}
3481
3482/*
3483 * The reserve and release unit commands differ only by their opcodes.
3484 */
3485void
3486scsi_reserve_release_unit(struct ccb_scsiio *csio, u_int32_t retries,
3487			  void (*cbfcnp)(struct cam_periph *, union ccb *),
3488			  u_int8_t tag_action, int third_party,
3489			  int third_party_id, u_int8_t sense_len,
3490			  u_int32_t timeout, int reserve)
3491{
3492	struct scsi_reserve_release_unit *scsi_cmd;
3493
3494	scsi_cmd = (struct scsi_reserve_release_unit *)&csio->cdb_io.cdb_bytes;
3495	bzero(scsi_cmd, sizeof(*scsi_cmd));
3496
3497	if (reserve)
3498		scsi_cmd->opcode = RESERVE_UNIT;
3499	else
3500		scsi_cmd->opcode = RELEASE_UNIT;
3501
3502	if (third_party) {
3503		scsi_cmd->lun_thirdparty |= SRRU_3RD_PARTY;
3504		scsi_cmd->lun_thirdparty |=
3505			((third_party_id << SRRU_3RD_SHAMT) & SRRU_3RD_MASK);
3506	}
3507
3508	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action, NULL,
3509	    0, sense_len, sizeof(*scsi_cmd), timeout);
3510}
3511
3512void
3513scsi_erase(struct ccb_scsiio *csio, u_int32_t retries,
3514	   void (*cbfcnp)(struct cam_periph *, union ccb *),
3515	   u_int8_t tag_action, int immediate, int long_erase,
3516	   u_int8_t sense_len, u_int32_t timeout)
3517{
3518	struct scsi_erase *scsi_cmd;
3519
3520	scsi_cmd = (struct scsi_erase *)&csio->cdb_io.cdb_bytes;
3521	bzero(scsi_cmd, sizeof(*scsi_cmd));
3522
3523	scsi_cmd->opcode = ERASE;
3524
3525	if (immediate)
3526		scsi_cmd->lun_imm_long |= SE_IMMED;
3527
3528	if (long_erase)
3529		scsi_cmd->lun_imm_long |= SE_LONG;
3530
3531	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action, NULL,
3532	    0, sense_len, sizeof(*scsi_cmd), timeout);
3533}
3534
3535/*
3536 * Read Tape Position command.
3537 */
3538void
3539scsi_read_position(struct ccb_scsiio *csio, u_int32_t retries,
3540		   void (*cbfcnp)(struct cam_periph *, union ccb *),
3541		   u_int8_t tag_action, int hardsoft,
3542		   struct scsi_tape_position_data *sbp,
3543		   u_int8_t sense_len, u_int32_t timeout)
3544{
3545	struct scsi_tape_read_position *scmd;
3546
3547	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_IN, tag_action,
3548	    (u_int8_t *)sbp, sizeof (*sbp), sense_len, sizeof(*scmd), timeout);
3549	scmd = (struct scsi_tape_read_position *)&csio->cdb_io.cdb_bytes;
3550	bzero(scmd, sizeof(*scmd));
3551	scmd->opcode = READ_POSITION;
3552	scmd->byte1 = hardsoft;
3553}
3554
3555/*
3556 * Set Tape Position command.
3557 */
3558void
3559scsi_set_position(struct ccb_scsiio *csio, u_int32_t retries,
3560		   void (*cbfcnp)(struct cam_periph *, union ccb *),
3561		   u_int8_t tag_action, int hardsoft, u_int32_t blkno,
3562		   u_int8_t sense_len, u_int32_t timeout)
3563{
3564	struct scsi_tape_locate *scmd;
3565
3566	cam_fill_csio(csio, retries, cbfcnp, CAM_DIR_NONE, tag_action,
3567	    (u_int8_t *)NULL, 0, sense_len, sizeof(*scmd), timeout);
3568	scmd = (struct scsi_tape_locate *)&csio->cdb_io.cdb_bytes;
3569	bzero(scmd, sizeof(*scmd));
3570	scmd->opcode = LOCATE;
3571	if (hardsoft)
3572		scmd->byte1 |= SA_SPOS_BT;
3573	scsi_ulto4b(blkno, scmd->blkaddr);
3574}
3575