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