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