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