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