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