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