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