Initial import of binutils 2.22 on the new vendor branch
[dragonfly.git] / sys / bus / cam / scsi / scsi_ch.c
1 /*
2  * Copyright (c) 1997 Justin T. Gibbs.
3  * Copyright (c) 1997, 1998, 1999 Kenneth D. Merry.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions, and the following disclaimer,
11  *    without modification, immediately at the beginning of the file.
12  * 2. The name of the author may not be used to endorse or promote products
13  *    derived from this software without specific prior written permission.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
19  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  * $FreeBSD: src/sys/cam/scsi/scsi_ch.c,v 1.20.2.2 2000/10/31 08:09:49 dwmalone Exp $
28  */
29 /*
30  * Derived from the NetBSD SCSI changer driver.
31  *
32  *      $NetBSD: ch.c,v 1.32 1998/01/12 09:49:12 thorpej Exp $
33  *
34  */
35 /*
36  * Copyright (c) 1996, 1997 Jason R. Thorpe <thorpej@and.com>
37  * All rights reserved.
38  *
39  * Partially based on an autochanger driver written by Stefan Grefen
40  * and on an autochanger driver written by the Systems Programming Group
41  * at the University of Utah Computer Science Department.
42  *
43  * Redistribution and use in source and binary forms, with or without
44  * modification, are permitted provided that the following conditions
45  * are met:
46  * 1. Redistributions of source code must retain the above copyright
47  *    notice, this list of conditions and the following disclaimer.
48  * 2. Redistributions in binary form must reproduce the above copyright
49  *    notice, this list of conditions and the following disclaimer in the
50  *    documentation and/or other materials provided with the distribution.
51  * 3. All advertising materials mentioning features or use of this software
52  *    must display the following acknowledgements:
53  *      This product includes software developed by Jason R. Thorpe
54  *      for And Communications, http://www.and.com/
55  * 4. The name of the author may not be used to endorse or promote products
56  *    derived from this software without specific prior written permission.
57  *
58  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
59  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
60  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
61  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
62  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
63  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
64  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
65  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
66  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68  * SUCH DAMAGE.
69  */
70
71 #include <sys/param.h>
72 #include <sys/queue.h>
73 #include <sys/systm.h>
74 #include <sys/kernel.h>
75 #include <sys/types.h>
76 #include <sys/malloc.h>
77 #include <sys/fcntl.h>
78 #include <sys/conf.h>
79 #include <sys/buf.h>
80 #include <sys/chio.h>
81 #include <sys/errno.h>
82 #include <sys/devicestat.h>
83 #include <sys/thread2.h>
84
85 #include "../cam.h"
86 #include "../cam_ccb.h"
87 #include "../cam_extend.h"
88 #include "../cam_periph.h"
89 #include "../cam_xpt_periph.h"
90 #include "../cam_queue.h"
91 #include "../cam_debug.h"
92
93 #include "scsi_all.h"
94 #include "scsi_message.h"
95 #include "scsi_ch.h"
96
97 /*
98  * Timeout definitions for various changer related commands.  They may
99  * be too short for some devices (especially the timeout for INITIALIZE
100  * ELEMENT STATUS).
101  */
102
103 static const u_int32_t  CH_TIMEOUT_MODE_SENSE                = 6000;
104 static const u_int32_t  CH_TIMEOUT_MOVE_MEDIUM               = 100000;
105 static const u_int32_t  CH_TIMEOUT_EXCHANGE_MEDIUM           = 100000;
106 static const u_int32_t  CH_TIMEOUT_POSITION_TO_ELEMENT       = 100000;
107 static const u_int32_t  CH_TIMEOUT_READ_ELEMENT_STATUS       = 10000;
108 static const u_int32_t  CH_TIMEOUT_SEND_VOLTAG               = 10000;
109 static const u_int32_t  CH_TIMEOUT_INITIALIZE_ELEMENT_STATUS = 500000;
110
111 typedef enum {
112         CH_FLAG_INVALID         = 0x001,
113         CH_FLAG_OPEN            = 0x002
114 } ch_flags;
115
116 typedef enum {
117         CH_STATE_PROBE,
118         CH_STATE_NORMAL
119 } ch_state;
120
121 typedef enum {
122         CH_CCB_PROBE,
123         CH_CCB_WAITING
124 } ch_ccb_types;
125
126 typedef enum {
127         CH_Q_NONE       = 0x00,
128         CH_Q_NO_DBD     = 0x01
129 } ch_quirks;
130
131 #define ccb_state       ppriv_field0
132 #define ccb_bio         ppriv_ptr1
133
134 struct scsi_mode_sense_data {
135         struct scsi_mode_header_6 header;
136         struct scsi_mode_blk_desc blk_desc;
137         union {
138                 struct page_element_address_assignment ea;
139                 struct page_transport_geometry_parameters tg;
140                 struct page_device_capabilities cap;
141         } pages;
142 };
143
144 struct ch_softc {
145         ch_flags        flags;
146         ch_state        state;
147         ch_quirks       quirks;
148         union ccb       saved_ccb;
149         struct devstat  device_stats;
150
151         int             sc_picker;      /* current picker */
152
153         /*
154          * The following information is obtained from the
155          * element address assignment page.
156          */
157         int             sc_firsts[CHET_MAX + 1];        /* firsts */
158         int             sc_counts[CHET_MAX + 1];        /* counts */
159
160         /*
161          * The following mask defines the legal combinations
162          * of elements for the MOVE MEDIUM command.
163          */
164         u_int8_t        sc_movemask[CHET_MAX + 1];
165
166         /*
167          * As above, but for EXCHANGE MEDIUM.
168          */
169         u_int8_t        sc_exchangemask[CHET_MAX + 1];
170
171         /*
172          * Quirks; see below.  XXX KDM not implemented yet
173          */
174         int             sc_settledelay; /* delay for settle */
175 };
176
177 #define CHUNIT(x)       (minor((x)))
178
179 static  d_open_t        chopen;
180 static  d_close_t       chclose;
181 static  d_ioctl_t       chioctl;
182 static  periph_init_t   chinit;
183 static  periph_ctor_t   chregister;
184 static  periph_oninv_t  choninvalidate;
185 static  periph_dtor_t   chcleanup;
186 static  periph_start_t  chstart;
187 static  void            chasync(void *callback_arg, u_int32_t code,
188                                 struct cam_path *path, void *arg);
189 static  void            chdone(struct cam_periph *periph,
190                                union ccb *done_ccb);
191 static  int             cherror(union ccb *ccb, u_int32_t cam_flags,
192                                 u_int32_t sense_flags);
193 static  int             chmove(struct cam_periph *periph,
194                                struct changer_move *cm);
195 static  int             chexchange(struct cam_periph *periph,
196                                    struct changer_exchange *ce);
197 static  int             chposition(struct cam_periph *periph,
198                                    struct changer_position *cp);
199 static  int             chgetelemstatus(struct cam_periph *periph,
200                                 struct changer_element_status_request *csr);
201 static  int             chsetvoltag(struct cam_periph *periph,
202                                     struct changer_set_voltag_request *csvr);
203 static  int             chielem(struct cam_periph *periph, 
204                                 unsigned int timeout);
205 static  int             chgetparams(struct cam_periph *periph);
206
207 static struct periph_driver chdriver =
208 {
209         chinit, "ch",
210         TAILQ_HEAD_INITIALIZER(chdriver.units), /* generation */ 0
211 };
212
213 PERIPHDRIVER_DECLARE(ch, chdriver);
214
215 static struct dev_ops ch_ops = {
216         { "ch", 0, 0 },
217         .d_open = chopen,
218         .d_close = chclose,
219         .d_ioctl = chioctl
220 };
221
222 static struct extend_array *chperiphs;
223
224 MALLOC_DEFINE(M_SCSICH, "scsi_ch", "scsi_ch buffers");
225
226 static void
227 chinit(void)
228 {
229         cam_status status;
230
231         /*
232          * Create our extend array for storing the devices we attach to.
233          */
234         chperiphs = cam_extend_new();
235         if (chperiphs == NULL) {
236                 kprintf("ch: Failed to alloc extend array!\n");
237                 return;
238         }
239
240         /*
241          * Install a global async callback.  This callback will
242          * receive async callbacks like "new device found".
243          */
244         status = xpt_register_async(AC_FOUND_DEVICE, chasync, NULL, NULL);
245
246         if (status != CAM_REQ_CMP) {
247                 kprintf("ch: Failed to attach master async callback "
248                        "due to status 0x%x!\n", status);
249         }
250 }
251
252 static void
253 choninvalidate(struct cam_periph *periph)
254 {
255         struct ch_softc *softc;
256
257         softc = (struct ch_softc *)periph->softc;
258
259         /*
260          * De-register any async callbacks.
261          */
262         xpt_register_async(0, chasync, periph, periph->path);
263
264         softc->flags |= CH_FLAG_INVALID;
265
266         xpt_print(periph->path, "lost device\n");
267
268 }
269
270 static void
271 chcleanup(struct cam_periph *periph)
272 {
273         struct ch_softc *softc;
274
275         softc = (struct ch_softc *)periph->softc;
276
277         devstat_remove_entry(&softc->device_stats);
278         cam_extend_release(chperiphs, periph->unit_number);
279         xpt_print(periph->path, "removing device entry\n");
280         dev_ops_remove_minor(&ch_ops, periph->unit_number);
281         kfree(softc, M_DEVBUF);
282 }
283
284 static void
285 chasync(void *callback_arg, u_int32_t code, struct cam_path *path, void *arg)
286 {
287         struct cam_periph *periph;
288
289         periph = (struct cam_periph *)callback_arg;
290
291         switch(code) {
292         case AC_FOUND_DEVICE:
293         {
294                 struct ccb_getdev *cgd;
295                 cam_status status;
296
297                 cgd = (struct ccb_getdev *)arg;
298                 if (cgd == NULL)
299                         break;
300
301                 if (SID_TYPE(&cgd->inq_data)!= T_CHANGER)
302                         break;
303
304                 /*
305                  * Allocate a peripheral instance for
306                  * this device and start the probe
307                  * process.
308                  */
309                 status = cam_periph_alloc(chregister, choninvalidate,
310                                           chcleanup, chstart, "ch",
311                                           CAM_PERIPH_BIO, cgd->ccb_h.path,
312                                           chasync, AC_FOUND_DEVICE, cgd);
313
314                 if (status != CAM_REQ_CMP
315                  && status != CAM_REQ_INPROG)
316                         kprintf("chasync: Unable to probe new device "
317                                "due to status 0x%x\n", status);
318
319                 break;
320
321         }
322         default:
323                 cam_periph_async(periph, code, path, arg);
324                 break;
325         }
326 }
327
328 static cam_status
329 chregister(struct cam_periph *periph, void *arg)
330 {
331         struct ch_softc *softc;
332         struct ccb_getdev *cgd;
333
334         cgd = (struct ccb_getdev *)arg;
335         if (periph == NULL) {
336                 kprintf("chregister: periph was NULL!!\n");
337                 return(CAM_REQ_CMP_ERR);
338         }
339
340         if (cgd == NULL) {
341                 kprintf("chregister: no getdev CCB, can't register device\n");
342                 return(CAM_REQ_CMP_ERR);
343         }
344
345         softc = kmalloc(sizeof(*softc), M_DEVBUF, M_INTWAIT | M_ZERO);
346         softc->state = CH_STATE_PROBE;
347         periph->softc = softc;
348         cam_extend_set(chperiphs, periph->unit_number, periph);
349         softc->quirks = CH_Q_NONE;
350
351         /*
352          * Changers don't have a blocksize, and obviously don't support
353          * tagged queueing.
354          */
355         cam_periph_unlock(periph);
356         devstat_add_entry(&softc->device_stats, "ch",
357                           periph->unit_number, 0,
358                           DEVSTAT_NO_BLOCKSIZE | DEVSTAT_NO_ORDERED_TAGS,
359                           SID_TYPE(&cgd->inq_data)| DEVSTAT_TYPE_IF_SCSI,
360                           DEVSTAT_PRIORITY_OTHER);
361
362         /* Register the device */
363         make_dev(&ch_ops, periph->unit_number, UID_ROOT,
364                   GID_OPERATOR, 0600, "%s%d", periph->periph_name,
365                   periph->unit_number);
366         cam_periph_lock(periph);
367
368         /*
369          * Add an async callback so that we get
370          * notified if this device goes away.
371          */
372         xpt_register_async(AC_LOST_DEVICE, chasync, periph, periph->path);
373
374         /*
375          * Lock this periph until we are setup.
376          * This first call can't block
377          */
378         cam_periph_hold(periph, 0);
379         xpt_schedule(periph, /*priority*/5);
380
381         return(CAM_REQ_CMP);
382 }
383
384 static int
385 chopen(struct dev_open_args *ap)
386 {
387         cdev_t dev = ap->a_head.a_dev;
388         struct cam_periph *periph;
389         struct ch_softc *softc;
390         int unit, error;
391
392         unit = CHUNIT(dev);
393         periph = cam_extend_get(chperiphs, unit);
394
395         if (cam_periph_acquire(periph) != CAM_REQ_CMP)
396                 return (ENXIO);
397
398         softc = (struct ch_softc *)periph->softc;
399
400         cam_periph_lock(periph);
401
402         if (softc->flags & CH_FLAG_INVALID) {
403                 cam_periph_unlock(periph);
404                 cam_periph_release(periph);
405                 return(ENXIO);
406         }
407
408         if ((softc->flags & CH_FLAG_OPEN) == 0)
409                 softc->flags |= CH_FLAG_OPEN;
410         else
411                 cam_periph_release(periph);
412
413         if ((error = cam_periph_hold(periph, PCATCH)) != 0) {
414                 cam_periph_unlock(periph);
415                 cam_periph_release(periph);
416                 return (error);
417         }
418
419         /*
420          * Load information about this changer device into the softc.
421          */
422         if ((error = chgetparams(periph)) != 0) {
423                 softc->flags &= ~CH_FLAG_OPEN;
424                 cam_periph_unhold(periph, 1);
425                 cam_periph_release(periph);
426         } else {
427                 cam_periph_unhold(periph, 1);
428         }
429
430         return(error);
431 }
432
433 static int
434 chclose(struct dev_close_args *ap)
435 {
436         cdev_t dev = ap->a_head.a_dev;
437         struct  cam_periph *periph;
438         struct  ch_softc *softc;
439         int     unit, error;
440
441         error = 0;
442
443         unit = CHUNIT(dev);
444         periph = cam_extend_get(chperiphs, unit);
445         if (periph == NULL)
446                 return(ENXIO);
447
448         softc = (struct ch_softc *)periph->softc;
449
450         cam_periph_lock(periph);
451
452         softc->flags &= ~CH_FLAG_OPEN;
453
454         cam_periph_unlock(periph);
455         cam_periph_release(periph);
456
457         return(0);
458 }
459
460 static void
461 chstart(struct cam_periph *periph, union ccb *start_ccb)
462 {
463         struct ch_softc *softc;
464
465         softc = (struct ch_softc *)periph->softc;
466
467         switch (softc->state) {
468         case CH_STATE_NORMAL:
469         {
470                 if (periph->immediate_priority <= periph->pinfo.priority){
471                         start_ccb->ccb_h.ccb_state = CH_CCB_WAITING;
472
473                         SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
474                                           periph_links.sle);
475                         periph->immediate_priority = CAM_PRIORITY_NONE;
476                         wakeup(&periph->ccb_list);
477                 }
478                 break;
479         }
480         case CH_STATE_PROBE:
481         {
482                 int mode_buffer_len;
483                 void *mode_buffer;
484
485                 /*
486                  * Include the block descriptor when calculating the mode
487                  * buffer length,
488                  */
489                 mode_buffer_len = sizeof(struct scsi_mode_header_6) +
490                                   sizeof(struct scsi_mode_blk_desc) +
491                                  sizeof(struct page_element_address_assignment);
492
493                 mode_buffer = kmalloc(mode_buffer_len, M_SCSICH, M_INTWAIT | M_ZERO);
494                 /*
495                  * Get the element address assignment page.
496                  */
497                 scsi_mode_sense(&start_ccb->csio,
498                                 /* retries */ 1,
499                                 /* cbfcnp */ chdone,
500                                 /* tag_action */ MSG_SIMPLE_Q_TAG,
501                                 /* dbd */ (softc->quirks & CH_Q_NO_DBD) ?
502                                         FALSE : TRUE,
503                                 /* page_code */ SMS_PAGE_CTRL_CURRENT,
504                                 /* page */ CH_ELEMENT_ADDR_ASSIGN_PAGE,
505                                 /* param_buf */ (u_int8_t *)mode_buffer,
506                                 /* param_len */ mode_buffer_len,
507                                 /* sense_len */ SSD_FULL_SIZE,
508                                 /* timeout */ CH_TIMEOUT_MODE_SENSE);
509
510                 start_ccb->ccb_h.ccb_bio = NULL;
511                 start_ccb->ccb_h.ccb_state = CH_CCB_PROBE;
512                 xpt_action(start_ccb);
513                 break;
514         }
515         }
516 }
517
518 static void
519 chdone(struct cam_periph *periph, union ccb *done_ccb)
520 {
521         struct ch_softc *softc;
522         struct ccb_scsiio *csio;
523
524         softc = (struct ch_softc *)periph->softc;
525         csio = &done_ccb->csio;
526
527         switch(done_ccb->ccb_h.ccb_state) {
528         case CH_CCB_PROBE:
529         {
530                 struct scsi_mode_header_6 *mode_header;
531                 struct page_element_address_assignment *ea;
532                 char announce_buf[80];
533
534
535                 mode_header = (struct scsi_mode_header_6 *)csio->data_ptr;
536
537                 ea = (struct page_element_address_assignment *)
538                         find_mode_page_6(mode_header);
539
540                 if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP){
541                         
542                         softc->sc_firsts[CHET_MT] = scsi_2btoul(ea->mtea);
543                         softc->sc_counts[CHET_MT] = scsi_2btoul(ea->nmte);
544                         softc->sc_firsts[CHET_ST] = scsi_2btoul(ea->fsea);
545                         softc->sc_counts[CHET_ST] = scsi_2btoul(ea->nse);
546                         softc->sc_firsts[CHET_IE] = scsi_2btoul(ea->fieea);
547                         softc->sc_counts[CHET_IE] = scsi_2btoul(ea->niee);
548                         softc->sc_firsts[CHET_DT] = scsi_2btoul(ea->fdtea);
549                         softc->sc_counts[CHET_DT] = scsi_2btoul(ea->ndte);
550                         softc->sc_picker = softc->sc_firsts[CHET_MT];
551
552 #define PLURAL(c)       (c) == 1 ? "" : "s"
553                         ksnprintf(announce_buf, sizeof(announce_buf),
554                                 "%d slot%s, %d drive%s, "
555                                 "%d picker%s, %d portal%s",
556                                 softc->sc_counts[CHET_ST],
557                                 PLURAL(softc->sc_counts[CHET_ST]),
558                                 softc->sc_counts[CHET_DT],
559                                 PLURAL(softc->sc_counts[CHET_DT]),
560                                 softc->sc_counts[CHET_MT],
561                                 PLURAL(softc->sc_counts[CHET_MT]),
562                                 softc->sc_counts[CHET_IE],
563                                 PLURAL(softc->sc_counts[CHET_IE]));
564 #undef PLURAL
565                 } else {
566                         int error;
567
568                         error = cherror(done_ccb, CAM_RETRY_SELTO,
569                                         SF_RETRY_UA | SF_NO_PRINT);
570                         /*
571                          * Retry any UNIT ATTENTION type errors.  They
572                          * are expected at boot.
573                          */
574                         if (error == ERESTART) {
575                                 /*
576                                  * A retry was scheuled, so
577                                  * just return.
578                                  */
579                                 return;
580                         } else if (error != 0) {
581                                 int retry_scheduled;
582                                 struct scsi_mode_sense_6 *sms;
583
584                                 sms = (struct scsi_mode_sense_6 *)
585                                         done_ccb->csio.cdb_io.cdb_bytes;
586
587                                 /*
588                                  * Check to see if block descriptors were
589                                  * disabled.  Some devices don't like that.
590                                  * We're taking advantage of the fact that
591                                  * the first few bytes of the 6 and 10 byte
592                                  * mode sense commands are the same.  If
593                                  * block descriptors were disabled, enable
594                                  * them and re-send the command.
595                                  */
596                                 if (sms->byte2 & SMS_DBD) {
597                                         sms->byte2 &= ~SMS_DBD;
598                                         xpt_action(done_ccb);
599                                         softc->quirks |= CH_Q_NO_DBD;
600                                         retry_scheduled = 1;
601                                 } else
602                                         retry_scheduled = 0;
603
604                                 /* Don't wedge this device's queue */
605                                 cam_release_devq(done_ccb->ccb_h.path,
606                                                  /*relsim_flags*/0,
607                                                  /*reduction*/0,
608                                                  /*timeout*/0,
609                                                  /*getcount_only*/0);
610
611                                 if (retry_scheduled)
612                                         return;
613
614                                 if ((done_ccb->ccb_h.status & CAM_STATUS_MASK)
615                                     == CAM_SCSI_STATUS_ERROR) 
616                                         scsi_sense_print(&done_ccb->csio);
617                                 else {
618                                         xpt_print(periph->path,
619                                             "got CAM status %#x\n",
620                                             done_ccb->ccb_h.status);
621                                 }
622                                 xpt_print(periph->path, "fatal error, failed "
623                                     "to attach to device\n");
624
625                                 cam_periph_invalidate(periph);
626
627                                 announce_buf[0] = '\0';
628                         }
629                 }
630                 if (announce_buf[0] != '\0')
631                         xpt_announce_periph(periph, announce_buf);
632                 softc->state = CH_STATE_NORMAL;
633                 kfree(mode_header, M_SCSICH);
634                 /*
635                  * Since our peripheral may be invalidated by an error
636                  * above or an external event, we must release our CCB
637                  * before releasing the probe lock on the peripheral.
638                  * The peripheral will only go away once the last lock
639                  * is removed, and we need it around for the CCB release
640                  * operation.
641                  */
642                 xpt_release_ccb(done_ccb);
643                 cam_periph_unhold(periph, 0);
644                 return;
645         }
646         case CH_CCB_WAITING:
647         {
648                 /* Caller will release the CCB */
649                 wakeup(&done_ccb->ccb_h.cbfcnp);
650                 return;
651         }
652         default:
653                 break;
654         }
655         xpt_release_ccb(done_ccb);
656 }
657
658 static int
659 cherror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
660 {
661         struct ch_softc *softc;
662         struct cam_periph *periph;
663
664         periph = xpt_path_periph(ccb->ccb_h.path);
665         softc = (struct ch_softc *)periph->softc;
666
667         return (cam_periph_error(ccb, cam_flags, sense_flags,
668                                  &softc->saved_ccb));
669 }
670
671 static int
672 chioctl(struct dev_ioctl_args *ap)
673 {
674         cdev_t dev = ap->a_head.a_dev;
675         caddr_t addr = ap->a_data;
676         int flag = ap->a_fflag;
677         struct cam_periph *periph;
678         struct ch_softc *softc;
679         u_int8_t unit;
680         int error;
681
682         unit = CHUNIT(dev);
683
684         periph = cam_extend_get(chperiphs, unit);
685         if (periph == NULL)
686                 return(ENXIO);
687
688         cam_periph_lock(periph);
689         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering chioctl\n"));
690
691         softc = (struct ch_softc *)periph->softc;
692
693         error = 0;
694
695         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, 
696                   ("trying to do ioctl %#lx\n", ap->a_cmd));
697
698         /*
699          * If this command can change the device's state, we must
700          * have the device open for writing.
701          */
702         switch (ap->a_cmd) {
703         case CHIOGPICKER:
704         case CHIOGPARAMS:
705         case CHIOGSTATUS:
706                 break;
707
708         default:
709                 if ((flag & FWRITE) == 0) {
710                         cam_periph_unlock(periph);
711                         return (EBADF);
712                 }
713         }
714
715         switch (ap->a_cmd) {
716         case CHIOMOVE:
717                 error = chmove(periph, (struct changer_move *)addr);
718                 break;
719
720         case CHIOEXCHANGE:
721                 error = chexchange(periph, (struct changer_exchange *)addr);
722                 break;
723
724         case CHIOPOSITION:
725                 error = chposition(periph, (struct changer_position *)addr);
726                 break;
727
728         case CHIOGPICKER:
729                 *(int *)addr = softc->sc_picker - softc->sc_firsts[CHET_MT];
730                 break;
731
732         case CHIOSPICKER:
733         {
734                 int new_picker = *(int *)addr;
735
736                 if (new_picker > (softc->sc_counts[CHET_MT] - 1)) {
737                         error = EINVAL;
738                         break;
739                 }
740                 softc->sc_picker = softc->sc_firsts[CHET_MT] + new_picker;
741                 break;
742         }
743         case CHIOGPARAMS:
744         {
745                 struct changer_params *cp = (struct changer_params *)addr;
746
747                 cp->cp_npickers = softc->sc_counts[CHET_MT];
748                 cp->cp_nslots = softc->sc_counts[CHET_ST];
749                 cp->cp_nportals = softc->sc_counts[CHET_IE];
750                 cp->cp_ndrives = softc->sc_counts[CHET_DT];
751                 break;
752         }
753         case CHIOIELEM:
754                 error = chielem(periph, *(unsigned int *)addr);
755                 break;
756
757         case CHIOGSTATUS:
758         {
759                 error = chgetelemstatus(periph,
760                                (struct changer_element_status_request *) addr);
761                 break;
762         }
763
764         case CHIOSETVOLTAG:
765         {
766                 error = chsetvoltag(periph,
767                                     (struct changer_set_voltag_request *) addr);
768                 break;
769         }
770
771         /* Implement prevent/allow? */
772
773         default:
774                 error = cam_periph_ioctl(periph, ap->a_cmd, addr, cherror);
775                 break;
776         }
777
778         cam_periph_unlock(periph);
779         return (error);
780 }
781
782 static int
783 chmove(struct cam_periph *periph, struct changer_move *cm)
784 {
785         struct ch_softc *softc;
786         u_int16_t fromelem, toelem;
787         union ccb *ccb;
788         int error;
789
790         error = 0;
791         softc = (struct ch_softc *)periph->softc;
792
793         /*
794          * Check arguments.
795          */
796         if ((cm->cm_fromtype > CHET_DT) || (cm->cm_totype > CHET_DT))
797                 return (EINVAL);
798         if ((cm->cm_fromunit > (softc->sc_counts[cm->cm_fromtype] - 1)) ||
799             (cm->cm_tounit > (softc->sc_counts[cm->cm_totype] - 1)))
800                 return (ENODEV);
801
802         /*
803          * Check the request against the changer's capabilities.
804          */
805         if ((softc->sc_movemask[cm->cm_fromtype] & (1 << cm->cm_totype)) == 0)
806                 return (ENODEV);
807
808         /*
809          * Calculate the source and destination elements.
810          */
811         fromelem = softc->sc_firsts[cm->cm_fromtype] + cm->cm_fromunit;
812         toelem = softc->sc_firsts[cm->cm_totype] + cm->cm_tounit;
813
814         ccb = cam_periph_getccb(periph, /*priority*/ 1);
815
816         scsi_move_medium(&ccb->csio,
817                          /* retries */ 1,
818                          /* cbfcnp */ chdone,
819                          /* tag_action */ MSG_SIMPLE_Q_TAG,
820                          /* tea */ softc->sc_picker,
821                          /* src */ fromelem,
822                          /* dst */ toelem,
823                          /* invert */ (cm->cm_flags & CM_INVERT) ? TRUE : FALSE,
824                          /* sense_len */ SSD_FULL_SIZE,
825                          /* timeout */ CH_TIMEOUT_MOVE_MEDIUM);
826
827         error = cam_periph_runccb(ccb, cherror, /*cam_flags*/CAM_RETRY_SELTO,
828                                   /*sense_flags*/ SF_RETRY_UA,
829                                   &softc->device_stats);
830
831         xpt_release_ccb(ccb);
832
833         return(error);
834 }
835
836 static int
837 chexchange(struct cam_periph *periph, struct changer_exchange *ce)
838 {
839         struct ch_softc *softc;
840         u_int16_t src, dst1, dst2;
841         union ccb *ccb;
842         int error;
843
844         error = 0;
845         softc = (struct ch_softc *)periph->softc;
846         /*
847          * Check arguments.
848          */
849         if ((ce->ce_srctype > CHET_DT) || (ce->ce_fdsttype > CHET_DT) ||
850             (ce->ce_sdsttype > CHET_DT))
851                 return (EINVAL);
852         if ((ce->ce_srcunit > (softc->sc_counts[ce->ce_srctype] - 1)) ||
853             (ce->ce_fdstunit > (softc->sc_counts[ce->ce_fdsttype] - 1)) ||
854             (ce->ce_sdstunit > (softc->sc_counts[ce->ce_sdsttype] - 1)))
855                 return (ENODEV);
856
857         /*
858          * Check the request against the changer's capabilities.
859          */
860         if (((softc->sc_exchangemask[ce->ce_srctype] &
861              (1 << ce->ce_fdsttype)) == 0) ||
862             ((softc->sc_exchangemask[ce->ce_fdsttype] &
863              (1 << ce->ce_sdsttype)) == 0))
864                 return (ENODEV);
865
866         /*
867          * Calculate the source and destination elements.
868          */
869         src = softc->sc_firsts[ce->ce_srctype] + ce->ce_srcunit;
870         dst1 = softc->sc_firsts[ce->ce_fdsttype] + ce->ce_fdstunit;
871         dst2 = softc->sc_firsts[ce->ce_sdsttype] + ce->ce_sdstunit;
872
873         ccb = cam_periph_getccb(periph, /*priority*/ 1);
874
875         scsi_exchange_medium(&ccb->csio,
876                              /* retries */ 1,
877                              /* cbfcnp */ chdone,
878                              /* tag_action */ MSG_SIMPLE_Q_TAG,
879                              /* tea */ softc->sc_picker,
880                              /* src */ src,
881                              /* dst1 */ dst1,
882                              /* dst2 */ dst2,
883                              /* invert1 */ (ce->ce_flags & CE_INVERT1) ?
884                                            TRUE : FALSE,
885                              /* invert2 */ (ce->ce_flags & CE_INVERT2) ?
886                                            TRUE : FALSE,
887                              /* sense_len */ SSD_FULL_SIZE,
888                              /* timeout */ CH_TIMEOUT_EXCHANGE_MEDIUM);
889
890         error = cam_periph_runccb(ccb, cherror, /*cam_flags*/CAM_RETRY_SELTO,
891                                   /*sense_flags*/ SF_RETRY_UA,
892                                   &softc->device_stats);
893
894         xpt_release_ccb(ccb);
895
896         return(error);
897 }
898
899 static int
900 chposition(struct cam_periph *periph, struct changer_position *cp)
901 {
902         struct ch_softc *softc;
903         u_int16_t dst;
904         union ccb *ccb;
905         int error;
906
907         error = 0;
908         softc = (struct ch_softc *)periph->softc;
909
910         /*
911          * Check arguments.
912          */
913         if (cp->cp_type > CHET_DT)
914                 return (EINVAL);
915         if (cp->cp_unit > (softc->sc_counts[cp->cp_type] - 1))
916                 return (ENODEV);
917
918         /*
919          * Calculate the destination element.
920          */
921         dst = softc->sc_firsts[cp->cp_type] + cp->cp_unit;
922
923         ccb = cam_periph_getccb(periph, /*priority*/ 1);
924
925         scsi_position_to_element(&ccb->csio,
926                                  /* retries */ 1,
927                                  /* cbfcnp */ chdone,
928                                  /* tag_action */ MSG_SIMPLE_Q_TAG,
929                                  /* tea */ softc->sc_picker,
930                                  /* dst */ dst,
931                                  /* invert */ (cp->cp_flags & CP_INVERT) ?
932                                               TRUE : FALSE,
933                                  /* sense_len */ SSD_FULL_SIZE,
934                                  /* timeout */ CH_TIMEOUT_POSITION_TO_ELEMENT);
935
936         error = cam_periph_runccb(ccb, cherror, /*cam_flags*/ CAM_RETRY_SELTO,
937                                   /*sense_flags*/ SF_RETRY_UA,
938                                   &softc->device_stats);
939
940         xpt_release_ccb(ccb);
941
942         return(error);
943 }
944
945 /*
946  * Copy a volume tag to a volume_tag struct, converting SCSI byte order
947  * to host native byte order in the volume serial number.  The volume
948  * label as returned by the changer is transferred to user mode as
949  * nul-terminated string.  Volume labels are truncated at the first
950  * space, as suggested by SCSI-2.
951  */
952 static  void
953 copy_voltag(struct changer_voltag *uvoltag, struct volume_tag *voltag)
954 {
955         int i;
956         for (i=0; i<CH_VOLTAG_MAXLEN; i++) {
957                 char c = voltag->vif[i];
958                 if (c && c != ' ')
959                         uvoltag->cv_volid[i] = c;
960                 else
961                         break;
962         }
963         uvoltag->cv_serial = scsi_2btoul(voltag->vsn);
964 }
965
966 /*
967  * Copy an an element status descriptor to a user-mode
968  * changer_element_status structure.
969  */
970
971 static  void
972 copy_element_status(struct ch_softc *softc,
973                     u_int16_t flags,
974                     struct read_element_status_descriptor *desc,
975                     struct changer_element_status *ces)
976 {
977         u_int16_t eaddr = scsi_2btoul(desc->eaddr);
978         u_int16_t et;
979
980         ces->ces_int_addr = eaddr;
981         /* set up logical address in element status */
982         for (et = CHET_MT; et <= CHET_DT; et++) {
983                 if ((softc->sc_firsts[et] <= eaddr)
984                     && ((softc->sc_firsts[et] + softc->sc_counts[et])
985                         > eaddr)) {
986                         ces->ces_addr = eaddr - softc->sc_firsts[et];
987                         ces->ces_type = et;
988                         break;
989                 }
990         }
991
992         ces->ces_flags = desc->flags1;
993
994         ces->ces_sensecode = desc->sense_code;
995         ces->ces_sensequal = desc->sense_qual;
996
997         if (desc->flags2 & READ_ELEMENT_STATUS_INVERT)
998                 ces->ces_flags |= CES_INVERT;
999
1000         if (desc->flags2 & READ_ELEMENT_STATUS_SVALID) {
1001
1002                 eaddr = scsi_2btoul(desc->ssea);
1003
1004                 /* convert source address to logical format */
1005                 for (et = CHET_MT; et <= CHET_DT; et++) {
1006                         if ((softc->sc_firsts[et] <= eaddr)
1007                             && ((softc->sc_firsts[et] + softc->sc_counts[et])
1008                                 > eaddr)) {
1009                                 ces->ces_source_addr = 
1010                                         eaddr - softc->sc_firsts[et];
1011                                 ces->ces_source_type = et;
1012                                 ces->ces_flags |= CES_SOURCE_VALID;
1013                                 break;
1014                         }
1015                 }
1016
1017                 if (!(ces->ces_flags & CES_SOURCE_VALID))
1018                         kprintf("ch: warning: could not map element source "
1019                                "address %ud to a valid element type\n",
1020                                eaddr);
1021         }
1022                         
1023
1024         if (flags & READ_ELEMENT_STATUS_PVOLTAG)
1025                 copy_voltag(&(ces->ces_pvoltag), &(desc->pvoltag));
1026         if (flags & READ_ELEMENT_STATUS_AVOLTAG)
1027                 copy_voltag(&(ces->ces_avoltag), &(desc->avoltag));
1028
1029         if (desc->dt_scsi_flags & READ_ELEMENT_STATUS_DT_IDVALID) {
1030                 ces->ces_flags |= CES_SCSIID_VALID;
1031                 ces->ces_scsi_id = desc->dt_scsi_addr;
1032         }
1033
1034         if (desc->dt_scsi_addr & READ_ELEMENT_STATUS_DT_LUVALID) {
1035                 ces->ces_flags |= CES_LUN_VALID;
1036                 ces->ces_scsi_lun = 
1037                         desc->dt_scsi_flags & READ_ELEMENT_STATUS_DT_LUNMASK;
1038         }
1039 }
1040
1041 static int
1042 chgetelemstatus(struct cam_periph *periph, 
1043                 struct changer_element_status_request *cesr)
1044 {
1045         struct read_element_status_header *st_hdr;
1046         struct read_element_status_page_header *pg_hdr;
1047         struct read_element_status_descriptor *desc;
1048         caddr_t data = NULL;
1049         size_t size, desclen;
1050         int avail, i, error = 0;
1051         struct changer_element_status *user_data = NULL;
1052         struct ch_softc *softc;
1053         union ccb *ccb;
1054         int chet = cesr->cesr_element_type;
1055         int want_voltags = (cesr->cesr_flags & CESR_VOLTAGS) ? 1 : 0;
1056
1057         softc = (struct ch_softc *)periph->softc;
1058
1059         /* perform argument checking */
1060
1061         /*
1062          * Perform a range check on the cesr_element_{base,count}
1063          * request argument fields.
1064          */
1065         if ((softc->sc_counts[chet] - cesr->cesr_element_base) <= 0
1066             || (cesr->cesr_element_base + cesr->cesr_element_count)
1067                 > softc->sc_counts[chet])
1068                 return (EINVAL);
1069
1070         /*
1071          * Request one descriptor for the given element type.  This
1072          * is used to determine the size of the descriptor so that
1073          * we can allocate enough storage for all of them.  We assume
1074          * that the first one can fit into 1k.
1075          */
1076         cam_periph_unlock(periph);
1077         data = (caddr_t)kmalloc(1024, M_DEVBUF, M_INTWAIT);
1078
1079         cam_periph_lock(periph);
1080         ccb = cam_periph_getccb(periph, /*priority*/ 1);
1081
1082         scsi_read_element_status(&ccb->csio,
1083                                  /* retries */ 1,
1084                                  /* cbfcnp */ chdone,
1085                                  /* tag_action */ MSG_SIMPLE_Q_TAG,
1086                                  /* voltag */ want_voltags,
1087                                  /* sea */ softc->sc_firsts[chet],
1088                                  /* count */ 1,
1089                                  /* data_ptr */ data,
1090                                  /* dxfer_len */ 1024,
1091                                  /* sense_len */ SSD_FULL_SIZE,
1092                                  /* timeout */ CH_TIMEOUT_READ_ELEMENT_STATUS);
1093
1094         error = cam_periph_runccb(ccb, cherror, /*cam_flags*/ CAM_RETRY_SELTO,
1095                                   /*sense_flags*/ SF_RETRY_UA,
1096                                   &softc->device_stats);
1097
1098         if (error)
1099                 goto done;
1100         cam_periph_unlock(periph);
1101
1102         st_hdr = (struct read_element_status_header *)data;
1103         pg_hdr = (struct read_element_status_page_header *)((uintptr_t)st_hdr +
1104                   sizeof(struct read_element_status_header));
1105         desclen = scsi_2btoul(pg_hdr->edl);
1106
1107         size = sizeof(struct read_element_status_header) +
1108                sizeof(struct read_element_status_page_header) +
1109                (desclen * cesr->cesr_element_count);
1110
1111         /*
1112          * Reallocate storage for descriptors and get them from the
1113          * device.
1114          */
1115         kfree(data, M_DEVBUF);
1116         data = (caddr_t)kmalloc(size, M_DEVBUF, M_INTWAIT);
1117
1118         cam_periph_lock(periph);
1119         scsi_read_element_status(&ccb->csio,
1120                                  /* retries */ 1,
1121                                  /* cbfcnp */ chdone,
1122                                  /* tag_action */ MSG_SIMPLE_Q_TAG,
1123                                  /* voltag */ want_voltags,
1124                                  /* sea */ softc->sc_firsts[chet]
1125                                  + cesr->cesr_element_base,
1126                                  /* count */ cesr->cesr_element_count,
1127                                  /* data_ptr */ data,
1128                                  /* dxfer_len */ size,
1129                                  /* sense_len */ SSD_FULL_SIZE,
1130                                  /* timeout */ CH_TIMEOUT_READ_ELEMENT_STATUS);
1131         
1132         error = cam_periph_runccb(ccb, cherror, /*cam_flags*/ CAM_RETRY_SELTO,
1133                                   /*sense_flags*/ SF_RETRY_UA,
1134                                   &softc->device_stats);
1135
1136         if (error)
1137                 goto done;
1138         cam_periph_unlock(periph);
1139
1140         /*
1141          * Fill in the user status array.
1142          */
1143         st_hdr = (struct read_element_status_header *)data;
1144         pg_hdr = (struct read_element_status_page_header *)((uintptr_t)st_hdr +
1145                   sizeof(struct read_element_status_header));
1146         avail = scsi_2btoul(st_hdr->count);
1147
1148         if (avail != cesr->cesr_element_count) {
1149                 xpt_print(periph->path,
1150                     "warning, READ ELEMENT STATUS avail != count\n");
1151         }
1152
1153         user_data = (struct changer_element_status *)
1154                 kmalloc(avail * sizeof(struct changer_element_status),
1155                        M_DEVBUF, M_INTWAIT | M_ZERO);
1156
1157         desc = (struct read_element_status_descriptor *)((uintptr_t)data +
1158                 sizeof(struct read_element_status_header) +
1159                 sizeof(struct read_element_status_page_header));
1160         /*
1161          * Set up the individual element status structures
1162          */
1163         for (i = 0; i < avail; ++i) {
1164                 struct changer_element_status *ces = &(user_data[i]);
1165
1166                 copy_element_status(softc, pg_hdr->flags, desc, ces);
1167
1168                 desc = (struct read_element_status_descriptor *)
1169                        ((uintptr_t)desc + desclen);
1170         }
1171
1172         /* Copy element status structures out to userspace. */
1173         error = copyout(user_data,
1174                         cesr->cesr_element_status,
1175                         avail * sizeof(struct changer_element_status));
1176         cam_periph_lock(periph);
1177
1178  done:
1179         xpt_release_ccb(ccb);
1180
1181         if (data != NULL)
1182                 kfree(data, M_DEVBUF);
1183         if (user_data != NULL)
1184                 kfree(user_data, M_DEVBUF);
1185
1186         return (error);
1187 }
1188
1189 static int
1190 chielem(struct cam_periph *periph,
1191         unsigned int timeout)
1192 {
1193         union ccb *ccb;
1194         struct ch_softc *softc;
1195         int error;
1196
1197         if (!timeout) {
1198                 timeout = CH_TIMEOUT_INITIALIZE_ELEMENT_STATUS;
1199         } else {
1200                 timeout *= 1000;
1201         }
1202
1203         error = 0;
1204         softc = (struct ch_softc *)periph->softc;
1205
1206         ccb = cam_periph_getccb(periph, /*priority*/ 1);
1207
1208         scsi_initialize_element_status(&ccb->csio,
1209                                       /* retries */ 1,
1210                                       /* cbfcnp */ chdone,
1211                                       /* tag_action */ MSG_SIMPLE_Q_TAG,
1212                                       /* sense_len */ SSD_FULL_SIZE,
1213                                       /* timeout */ timeout);
1214
1215         error = cam_periph_runccb(ccb, cherror, /*cam_flags*/ CAM_RETRY_SELTO,
1216                                   /*sense_flags*/ SF_RETRY_UA,
1217                                   &softc->device_stats);
1218
1219         xpt_release_ccb(ccb);
1220
1221         return(error);
1222 }
1223
1224 static int
1225 chsetvoltag(struct cam_periph *periph,
1226             struct changer_set_voltag_request *csvr)
1227 {
1228         union ccb *ccb;
1229         struct ch_softc *softc;
1230         u_int16_t ea;
1231         u_int8_t sac;
1232         struct scsi_send_volume_tag_parameters ssvtp;
1233         int error;
1234         int i;
1235
1236         error = 0;
1237         softc = (struct ch_softc *)periph->softc;
1238
1239         bzero(&ssvtp, sizeof(ssvtp));
1240         for (i=0; i<sizeof(ssvtp.vitf); i++) {
1241                 ssvtp.vitf[i] = ' ';
1242         }
1243
1244         /*
1245          * Check arguments.
1246          */
1247         if (csvr->csvr_type > CHET_DT)
1248                 return EINVAL;
1249         if (csvr->csvr_addr > (softc->sc_counts[csvr->csvr_type] - 1))
1250                 return ENODEV;
1251
1252         ea = softc->sc_firsts[csvr->csvr_type] + csvr->csvr_addr;
1253
1254         if (csvr->csvr_flags & CSVR_ALTERNATE) {
1255                 switch (csvr->csvr_flags & CSVR_MODE_MASK) {
1256                 case CSVR_MODE_SET:
1257                         sac = SEND_VOLUME_TAG_ASSERT_ALTERNATE;
1258                         break;
1259                 case CSVR_MODE_REPLACE:
1260                         sac = SEND_VOLUME_TAG_REPLACE_ALTERNATE;
1261                         break;
1262                 case CSVR_MODE_CLEAR:
1263                         sac = SEND_VOLUME_TAG_UNDEFINED_ALTERNATE;
1264                         break;
1265                 default:
1266                         error = EINVAL;
1267                         goto out;
1268                 }
1269         } else {
1270                 switch (csvr->csvr_flags & CSVR_MODE_MASK) {
1271                 case CSVR_MODE_SET:
1272                         sac = SEND_VOLUME_TAG_ASSERT_PRIMARY;
1273                         break;
1274                 case CSVR_MODE_REPLACE:
1275                         sac = SEND_VOLUME_TAG_REPLACE_PRIMARY;
1276                         break;
1277                 case CSVR_MODE_CLEAR:
1278                         sac = SEND_VOLUME_TAG_UNDEFINED_PRIMARY;
1279                         break;
1280                 default:
1281                         error = EINVAL;
1282                         goto out;
1283                 }
1284         }
1285
1286         memcpy(ssvtp.vitf, csvr->csvr_voltag.cv_volid,
1287                min(strlen(csvr->csvr_voltag.cv_volid), sizeof(ssvtp.vitf)));
1288         scsi_ulto2b(csvr->csvr_voltag.cv_serial, ssvtp.minvsn);
1289
1290         ccb = cam_periph_getccb(periph, /*priority*/ 1);
1291
1292         scsi_send_volume_tag(&ccb->csio,
1293                              /* retries */ 1,
1294                              /* cbfcnp */ chdone,
1295                              /* tag_action */ MSG_SIMPLE_Q_TAG,
1296                              /* element_address */ ea,
1297                              /* send_action_code */ sac,
1298                              /* parameters */ &ssvtp,
1299                              /* sense_len */ SSD_FULL_SIZE,
1300                              /* timeout */ CH_TIMEOUT_SEND_VOLTAG);
1301         
1302         error = cam_periph_runccb(ccb, cherror, /*cam_flags*/ CAM_RETRY_SELTO,
1303                                   /*sense_flags*/ SF_RETRY_UA,
1304                                   &softc->device_stats);
1305
1306         xpt_release_ccb(ccb);
1307
1308  out:
1309         return error;
1310 }
1311
1312 static int
1313 chgetparams(struct cam_periph *periph)
1314 {
1315         union ccb *ccb;
1316         struct ch_softc *softc;
1317         void *mode_buffer;
1318         int mode_buffer_len;
1319         struct page_element_address_assignment *ea;
1320         struct page_device_capabilities *cap;
1321         int error, from, dbd;
1322         u_int8_t *moves, *exchanges;
1323
1324         error = 0;
1325
1326         softc = (struct ch_softc *)periph->softc;
1327
1328         ccb = cam_periph_getccb(periph, /*priority*/ 1);
1329
1330         /*
1331          * The scsi_mode_sense_data structure is just a convenience
1332          * structure that allows us to easily calculate the worst-case
1333          * storage size of the mode sense buffer.
1334          */
1335         mode_buffer_len = sizeof(struct scsi_mode_sense_data);
1336
1337         mode_buffer = kmalloc(mode_buffer_len, M_SCSICH, M_INTWAIT | M_ZERO);
1338
1339         if (softc->quirks & CH_Q_NO_DBD)
1340                 dbd = FALSE;
1341         else
1342                 dbd = TRUE;
1343
1344         /*
1345          * Get the element address assignment page.
1346          */
1347         scsi_mode_sense(&ccb->csio,
1348                         /* retries */ 1,
1349                         /* cbfcnp */ chdone,
1350                         /* tag_action */ MSG_SIMPLE_Q_TAG,
1351                         /* dbd */ dbd,
1352                         /* page_code */ SMS_PAGE_CTRL_CURRENT,
1353                         /* page */ CH_ELEMENT_ADDR_ASSIGN_PAGE,
1354                         /* param_buf */ (u_int8_t *)mode_buffer,
1355                         /* param_len */ mode_buffer_len,
1356                         /* sense_len */ SSD_FULL_SIZE,
1357                         /* timeout */ CH_TIMEOUT_MODE_SENSE);
1358
1359         error = cam_periph_runccb(ccb, cherror, /*cam_flags*/ CAM_RETRY_SELTO,
1360                                   /* sense_flags */ SF_RETRY_UA|SF_NO_PRINT,
1361                                   &softc->device_stats);
1362
1363         if (error) {
1364                 if (dbd) {
1365                         struct scsi_mode_sense_6 *sms;
1366
1367                         sms = (struct scsi_mode_sense_6 *)
1368                                 ccb->csio.cdb_io.cdb_bytes;
1369
1370                         sms->byte2 &= ~SMS_DBD;
1371                         error = cam_periph_runccb(ccb, cherror,
1372                                                   /*cam_flags*/ CAM_RETRY_SELTO,
1373                                                   /*sense_flags*/ SF_RETRY_UA,
1374                                                   &softc->device_stats);
1375                 } else {
1376                         /*
1377                          * Since we disabled sense printing above, print
1378                          * out the sense here since we got an error.
1379                          */
1380                         scsi_sense_print(&ccb->csio);
1381                 }
1382
1383                 if (error) {
1384                         xpt_print(periph->path,
1385                             "chgetparams: error getting element "
1386                             "address page\n");
1387                         xpt_release_ccb(ccb);
1388                         kfree(mode_buffer, M_SCSICH);
1389                         return(error);
1390                 }
1391         }
1392
1393         ea = (struct page_element_address_assignment *)
1394                 find_mode_page_6((struct scsi_mode_header_6 *)mode_buffer);
1395
1396         softc->sc_firsts[CHET_MT] = scsi_2btoul(ea->mtea);
1397         softc->sc_counts[CHET_MT] = scsi_2btoul(ea->nmte);
1398         softc->sc_firsts[CHET_ST] = scsi_2btoul(ea->fsea);
1399         softc->sc_counts[CHET_ST] = scsi_2btoul(ea->nse);
1400         softc->sc_firsts[CHET_IE] = scsi_2btoul(ea->fieea);
1401         softc->sc_counts[CHET_IE] = scsi_2btoul(ea->niee);
1402         softc->sc_firsts[CHET_DT] = scsi_2btoul(ea->fdtea);
1403         softc->sc_counts[CHET_DT] = scsi_2btoul(ea->ndte);
1404
1405         bzero(mode_buffer, mode_buffer_len);
1406
1407         /*
1408          * Now get the device capabilities page.
1409          */
1410         scsi_mode_sense(&ccb->csio,
1411                         /* retries */ 1,
1412                         /* cbfcnp */ chdone,
1413                         /* tag_action */ MSG_SIMPLE_Q_TAG,
1414                         /* dbd */ dbd,
1415                         /* page_code */ SMS_PAGE_CTRL_CURRENT,
1416                         /* page */ CH_DEVICE_CAP_PAGE,
1417                         /* param_buf */ (u_int8_t *)mode_buffer,
1418                         /* param_len */ mode_buffer_len,
1419                         /* sense_len */ SSD_FULL_SIZE,
1420                         /* timeout */ CH_TIMEOUT_MODE_SENSE);
1421         
1422         error = cam_periph_runccb(ccb, cherror, /*cam_flags*/ CAM_RETRY_SELTO,
1423                                   /* sense_flags */ SF_RETRY_UA | SF_NO_PRINT,
1424                                   &softc->device_stats);
1425
1426         if (error) {
1427                 if (dbd) {
1428                         struct scsi_mode_sense_6 *sms;
1429
1430                         sms = (struct scsi_mode_sense_6 *)
1431                                 ccb->csio.cdb_io.cdb_bytes;
1432
1433                         sms->byte2 &= ~SMS_DBD;
1434                         error = cam_periph_runccb(ccb, cherror,
1435                                                   /*cam_flags*/ CAM_RETRY_SELTO,
1436                                                   /*sense_flags*/ SF_RETRY_UA,
1437                                                   &softc->device_stats);
1438                 } else {
1439                         /*
1440                          * Since we disabled sense printing above, print
1441                          * out the sense here since we got an error.
1442                          */
1443                         scsi_sense_print(&ccb->csio);
1444                 }
1445
1446                 if (error) {
1447                         xpt_print(periph->path,
1448                             "chgetparams: error getting device "
1449                             "capabilities page\n");
1450                         xpt_release_ccb(ccb);
1451                         kfree(mode_buffer, M_SCSICH);
1452                         return(error);
1453                 }
1454         }
1455
1456         xpt_release_ccb(ccb);
1457
1458         cap = (struct page_device_capabilities *)
1459                 find_mode_page_6((struct scsi_mode_header_6 *)mode_buffer);
1460
1461         bzero(softc->sc_movemask, sizeof(softc->sc_movemask));
1462         bzero(softc->sc_exchangemask, sizeof(softc->sc_exchangemask));
1463         moves = cap->move_from;
1464         exchanges = cap->exchange_with;
1465         for (from = CHET_MT; from <= CHET_MAX; ++from) {
1466                 softc->sc_movemask[from] = moves[from];
1467                 softc->sc_exchangemask[from] = exchanges[from];
1468         }
1469
1470         kfree(mode_buffer, M_SCSICH);
1471
1472         return(error);
1473 }
1474
1475 void
1476 scsi_move_medium(struct ccb_scsiio *csio, u_int32_t retries,
1477                  void (*cbfcnp)(struct cam_periph *, union ccb *),
1478                  u_int8_t tag_action, u_int32_t tea, u_int32_t src,
1479                  u_int32_t dst, int invert, u_int8_t sense_len,
1480                  u_int32_t timeout)
1481 {
1482         struct scsi_move_medium *scsi_cmd;
1483
1484         scsi_cmd = (struct scsi_move_medium *)&csio->cdb_io.cdb_bytes;
1485         bzero(scsi_cmd, sizeof(*scsi_cmd));
1486
1487         scsi_cmd->opcode = MOVE_MEDIUM;
1488
1489         scsi_ulto2b(tea, scsi_cmd->tea);
1490         scsi_ulto2b(src, scsi_cmd->src);
1491         scsi_ulto2b(dst, scsi_cmd->dst);
1492
1493         if (invert)
1494                 scsi_cmd->invert |= MOVE_MEDIUM_INVERT;
1495
1496         cam_fill_csio(csio,
1497                       retries,
1498                       cbfcnp,
1499                       /*flags*/ CAM_DIR_NONE,
1500                       tag_action,
1501                       /*data_ptr*/ NULL,
1502                       /*dxfer_len*/ 0,
1503                       sense_len,
1504                       sizeof(*scsi_cmd),
1505                       timeout);
1506 }
1507
1508 void
1509 scsi_exchange_medium(struct ccb_scsiio *csio, u_int32_t retries,
1510                      void (*cbfcnp)(struct cam_periph *, union ccb *),
1511                      u_int8_t tag_action, u_int32_t tea, u_int32_t src,
1512                      u_int32_t dst1, u_int32_t dst2, int invert1,
1513                      int invert2, u_int8_t sense_len, u_int32_t timeout)
1514 {
1515         struct scsi_exchange_medium *scsi_cmd;
1516
1517         scsi_cmd = (struct scsi_exchange_medium *)&csio->cdb_io.cdb_bytes;
1518         bzero(scsi_cmd, sizeof(*scsi_cmd));
1519
1520         scsi_cmd->opcode = EXCHANGE_MEDIUM;
1521
1522         scsi_ulto2b(tea, scsi_cmd->tea);
1523         scsi_ulto2b(src, scsi_cmd->src);
1524         scsi_ulto2b(dst1, scsi_cmd->fdst);
1525         scsi_ulto2b(dst2, scsi_cmd->sdst);
1526
1527         if (invert1)
1528                 scsi_cmd->invert |= EXCHANGE_MEDIUM_INV1;
1529
1530         if (invert2)
1531                 scsi_cmd->invert |= EXCHANGE_MEDIUM_INV2;
1532
1533         cam_fill_csio(csio,
1534                       retries,
1535                       cbfcnp,
1536                       /*flags*/ CAM_DIR_NONE,
1537                       tag_action,
1538                       /*data_ptr*/ NULL,
1539                       /*dxfer_len*/ 0,
1540                       sense_len,
1541                       sizeof(*scsi_cmd),
1542                       timeout);
1543 }
1544
1545 void
1546 scsi_position_to_element(struct ccb_scsiio *csio, u_int32_t retries,
1547                          void (*cbfcnp)(struct cam_periph *, union ccb *),
1548                          u_int8_t tag_action, u_int32_t tea, u_int32_t dst,
1549                          int invert, u_int8_t sense_len, u_int32_t timeout)
1550 {
1551         struct scsi_position_to_element *scsi_cmd;
1552
1553         scsi_cmd = (struct scsi_position_to_element *)&csio->cdb_io.cdb_bytes;
1554         bzero(scsi_cmd, sizeof(*scsi_cmd));
1555
1556         scsi_cmd->opcode = POSITION_TO_ELEMENT;
1557
1558         scsi_ulto2b(tea, scsi_cmd->tea);
1559         scsi_ulto2b(dst, scsi_cmd->dst);
1560
1561         if (invert)
1562                 scsi_cmd->invert |= POSITION_TO_ELEMENT_INVERT;
1563
1564         cam_fill_csio(csio,
1565                       retries,
1566                       cbfcnp,
1567                       /*flags*/ CAM_DIR_NONE,
1568                       tag_action,
1569                       /*data_ptr*/ NULL,
1570                       /*dxfer_len*/ 0,
1571                       sense_len,
1572                       sizeof(*scsi_cmd),
1573                       timeout);
1574 }
1575
1576 void
1577 scsi_read_element_status(struct ccb_scsiio *csio, u_int32_t retries,
1578                          void (*cbfcnp)(struct cam_periph *, union ccb *),
1579                          u_int8_t tag_action, int voltag, u_int32_t sea,
1580                          u_int32_t count, u_int8_t *data_ptr,
1581                          u_int32_t dxfer_len, u_int8_t sense_len,
1582                          u_int32_t timeout)
1583 {
1584         struct scsi_read_element_status *scsi_cmd;
1585
1586         scsi_cmd = (struct scsi_read_element_status *)&csio->cdb_io.cdb_bytes;
1587         bzero(scsi_cmd, sizeof(*scsi_cmd));
1588
1589         scsi_cmd->opcode = READ_ELEMENT_STATUS;
1590
1591         scsi_ulto2b(sea, scsi_cmd->sea);
1592         scsi_ulto2b(count, scsi_cmd->count);
1593         scsi_ulto3b(dxfer_len, scsi_cmd->len);
1594
1595         if (voltag)
1596                 scsi_cmd->byte2 |= READ_ELEMENT_STATUS_VOLTAG;
1597
1598         cam_fill_csio(csio,
1599                       retries,
1600                       cbfcnp,
1601                       /*flags*/ CAM_DIR_IN,
1602                       tag_action,
1603                       data_ptr,
1604                       dxfer_len,
1605                       sense_len,
1606                       sizeof(*scsi_cmd),
1607                       timeout);
1608 }
1609
1610 void
1611 scsi_initialize_element_status(struct ccb_scsiio *csio, u_int32_t retries,
1612                                void (*cbfcnp)(struct cam_periph *, union ccb *),
1613                                u_int8_t tag_action, u_int8_t sense_len,
1614                                u_int32_t timeout)
1615 {
1616         struct scsi_initialize_element_status *scsi_cmd;
1617
1618         scsi_cmd = (struct scsi_initialize_element_status *)
1619                     &csio->cdb_io.cdb_bytes;
1620         bzero(scsi_cmd, sizeof(*scsi_cmd));
1621
1622         scsi_cmd->opcode = INITIALIZE_ELEMENT_STATUS;
1623
1624         cam_fill_csio(csio,
1625                       retries,
1626                       cbfcnp,
1627                       /*flags*/ CAM_DIR_NONE,
1628                       tag_action,
1629                       /* data_ptr */ NULL,
1630                       /* dxfer_len */ 0,
1631                       sense_len,
1632                       sizeof(*scsi_cmd),
1633                       timeout);
1634 }
1635
1636 void
1637 scsi_send_volume_tag(struct ccb_scsiio *csio, u_int32_t retries,
1638                      void (*cbfcnp)(struct cam_periph *, union ccb *),
1639                      u_int8_t tag_action, 
1640                      u_int16_t element_address,
1641                      u_int8_t send_action_code,
1642                      struct scsi_send_volume_tag_parameters *parameters,
1643                      u_int8_t sense_len, u_int32_t timeout)
1644 {
1645         struct scsi_send_volume_tag *scsi_cmd;
1646
1647         scsi_cmd = (struct scsi_send_volume_tag *) &csio->cdb_io.cdb_bytes;
1648         bzero(scsi_cmd, sizeof(*scsi_cmd));
1649
1650         scsi_cmd->opcode = SEND_VOLUME_TAG;
1651         scsi_ulto2b(element_address, scsi_cmd->ea);
1652         scsi_cmd->sac = send_action_code;
1653         scsi_ulto2b(sizeof(*parameters), scsi_cmd->pll);
1654
1655         cam_fill_csio(csio,
1656                       retries,
1657                       cbfcnp,
1658                       /*flags*/ CAM_DIR_OUT,
1659                       tag_action,
1660                       /* data_ptr */ (u_int8_t *) parameters,
1661                       sizeof(*parameters),
1662                       sense_len,
1663                       sizeof(*scsi_cmd),
1664                       timeout);
1665 }