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