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