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