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