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