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