Merge from vendor branch FILE:
[dragonfly.git] / sys / bus / cam / scsi / scsi_cd.c
1 /*
2  * Copyright (c) 1997 Justin T. Gibbs.
3  * Copyright (c) 1997, 1998, 1999, 2000, 2001, 2003, 2003 Kenneth D. Merry.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions, and the following disclaimer,
11  *    without modification, immediately at the beginning of the file.
12  * 2. The name of the author may not be used to endorse or promote products
13  *    derived from this software without specific prior written permission.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
19  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  * $FreeBSD: src/sys/cam/scsi/scsi_cd.c,v 1.31.2.16 2003/10/21 22:26:11 thomas Exp $
28  * $DragonFly: src/sys/bus/cam/scsi/scsi_cd.c,v 1.18 2005/06/02 20:40:31 dillon Exp $
29  */
30 /*
31  * Portions of this driver taken from the original FreeBSD cd driver.
32  * Written by Julian Elischer (julian@tfs.com)
33  * for TRW Financial Systems for use under the MACH(2.5) operating system.
34  *
35  * TRW Financial Systems, in accordance with their agreement with Carnegie
36  * Mellon University, makes this software available to CMU to distribute
37  * or use in any manner that they see fit as long as this message is kept with
38  * the software. For this reason TFS also grants any other persons or
39  * organisations permission to use or modify this software.
40  *
41  * TFS supplies this software to be publicly redistributed
42  * on the understanding that TFS is not responsible for the correct
43  * functioning of this software in any circumstances.
44  *
45  * Ported to run under 386BSD by Julian Elischer (julian@tfs.com) Sept 1992
46  *
47  *      from: cd.c,v 1.83 1997/05/04 15:24:22 joerg Exp $
48  */
49
50 #include "opt_cd.h"
51
52 #include <sys/param.h>
53 #include <sys/bootmaj.h>
54 #include <sys/systm.h>
55 #include <sys/kernel.h>
56 #include <sys/buf.h>
57 #include <sys/conf.h>
58 #include <sys/disk.h>
59 #include <sys/malloc.h>
60 #include <sys/cdio.h>
61 #include <sys/cdrio.h>
62 #include <sys/dvdio.h>
63 #include <sys/devicestat.h>
64 #include <sys/sysctl.h>
65 #include <sys/taskqueue.h>
66 #include <sys/proc.h>
67 #include <sys/buf2.h>
68 #include <sys/thread2.h>
69
70 #include "../cam.h"
71 #include "../cam_ccb.h"
72 #include "../cam_extend.h"
73 #include "../cam_periph.h"
74 #include "../cam_xpt_periph.h"
75 #include "../cam_queue.h"
76
77 #include "scsi_message.h"
78 #include "scsi_da.h"
79 #include "scsi_cd.h"
80
81 #define LEADOUT         0xaa            /* leadout toc entry */
82
83 struct cd_params {
84         u_int32_t blksize;
85         u_long    disksize;
86 };
87
88 typedef enum {
89         CD_Q_NONE               = 0x00,
90         CD_Q_NO_TOUCH           = 0x01,
91         CD_Q_BCD_TRACKS         = 0x02,
92         CD_Q_NO_CHANGER         = 0x04,
93         CD_Q_CHANGER            = 0x08,
94         CD_Q_10_BYTE_ONLY       = 0x10
95 } cd_quirks;
96
97 typedef enum {
98         CD_FLAG_INVALID         = 0x0001,
99         CD_FLAG_NEW_DISC        = 0x0002,
100         CD_FLAG_DISC_LOCKED     = 0x0004,
101         CD_FLAG_DISC_REMOVABLE  = 0x0008,
102         CD_FLAG_TAGGED_QUEUING  = 0x0010,
103         CD_FLAG_CHANGER         = 0x0040,
104         CD_FLAG_ACTIVE          = 0x0080,
105         CD_FLAG_SCHED_ON_COMP   = 0x0100,
106         CD_FLAG_RETRY_UA        = 0x0200,
107         CD_FLAG_VALID_MEDIA     = 0x0400,
108         CD_FLAG_VALID_TOC       = 0x0800,
109         CD_FLAG_OPEN            = 0x1000,
110         CD_FLAG_SCTX_INIT       = 0x2000
111 } cd_flags;
112
113 typedef enum {
114         CD_CCB_PROBE            = 0x01,
115         CD_CCB_BUFFER_IO        = 0x02,
116         CD_CCB_WAITING          = 0x03,
117         CD_CCB_TYPE_MASK        = 0x0F,
118         CD_CCB_RETRY_UA         = 0x10
119 } cd_ccb_state;
120
121 typedef enum {
122         CHANGER_TIMEOUT_SCHED           = 0x01,
123         CHANGER_SHORT_TMOUT_SCHED       = 0x02,
124         CHANGER_MANUAL_CALL             = 0x04,
125         CHANGER_NEED_TIMEOUT            = 0x08
126 } cd_changer_flags;
127
128 #define ccb_state ppriv_field0
129 #define ccb_bp ppriv_ptr1
130
131 struct cd_tocdata {
132         struct ioc_toc_header header;
133         struct cd_toc_entry entries[100];
134 };
135
136 struct cd_toc_single {
137         struct ioc_toc_header header;
138         struct cd_toc_entry entry;
139 };
140
141 typedef enum {
142         CD_STATE_PROBE,
143         CD_STATE_NORMAL
144 } cd_state;
145
146 struct cd_softc {
147         cam_pinfo               pinfo;
148         cd_state                state;
149         volatile cd_flags       flags;
150         struct buf_queue_head   buf_queue;
151         LIST_HEAD(, ccb_hdr)    pending_ccbs;
152         struct cd_params        params;
153         struct disk             disk;
154         union ccb               saved_ccb;
155         cd_quirks               quirks;
156         struct devstat          device_stats;
157         STAILQ_ENTRY(cd_softc)  changer_links;
158         struct cdchanger        *changer;
159         int                     bufs_left;
160         struct cam_periph       *periph;
161         int                     minimum_command_size;
162         struct task             sysctl_task;
163         struct sysctl_ctx_list  sysctl_ctx;
164         struct sysctl_oid       *sysctl_tree;
165         STAILQ_HEAD(, cd_mode_params)   mode_queue;
166         struct cd_tocdata       toc;
167 };
168
169 struct cd_page_sizes {
170         int page;
171         int page_size;
172 };
173
174 static struct cd_page_sizes cd_page_size_table[] =
175 {
176         { AUDIO_PAGE, sizeof(struct cd_audio_page)}
177 };
178
179 struct cd_quirk_entry {
180         struct scsi_inquiry_pattern inq_pat;
181         cd_quirks quirks;
182 };
183
184 /*
185  * The changer quirk entries aren't strictly necessary.  Basically, what
186  * they do is tell cdregister() up front that a device is a changer.
187  * Otherwise, it will figure that fact out once it sees a LUN on the device
188  * that is greater than 0.  If it is known up front that a device is a changer,
189  * all I/O to the device will go through the changer scheduling routines, as
190  * opposed to the "normal" CD code.
191  *
192  * NOTE ON 10_BYTE_ONLY quirks:  Any 10_BYTE_ONLY quirks MUST be because
193  * your device hangs when it gets a 10 byte command.  Adding a quirk just
194  * to get rid of the informative diagnostic message is not acceptable.  All
195  * 10_BYTE_ONLY quirks must be documented in full in a PR (which should be
196  * referenced in a comment along with the quirk) , and must be approved by
197  * ken@FreeBSD.org.  Any quirks added that don't adhere to this policy may
198  * be removed until the submitter can explain why they are needed.
199  * 10_BYTE_ONLY quirks will be removed (as they will no longer be necessary)
200  * when the CAM_NEW_TRAN_CODE work is done.
201  */
202 static struct cd_quirk_entry cd_quirk_table[] =
203 {
204         {
205                 { T_CDROM, SIP_MEDIA_REMOVABLE, "NRC", "MBR-7", "*"},
206                  /*quirks*/ CD_Q_CHANGER
207         },
208         {
209                 { T_CDROM, SIP_MEDIA_REMOVABLE, "PIONEER", "CD-ROM DRM*",
210                   "*"}, /* quirks */ CD_Q_CHANGER
211         },
212         {
213                 { T_CDROM, SIP_MEDIA_REMOVABLE, "NAKAMICH", "MJ-*", "*"},
214                  /* quirks */ CD_Q_CHANGER
215         },
216         {
217                 { T_CDROM, SIP_MEDIA_REMOVABLE, "CHINON", "CD-ROM CDS-535","*"},
218                 /* quirks */ CD_Q_BCD_TRACKS
219         }
220 };
221
222 static  d_open_t        cdopen;
223 static  d_close_t       cdclose;
224 static  d_ioctl_t       cdioctl;
225 static  d_strategy_t    cdstrategy;
226
227 static  periph_init_t   cdinit;
228 static  periph_ctor_t   cdregister;
229 static  periph_dtor_t   cdcleanup;
230 static  periph_start_t  cdstart;
231 static  periph_oninv_t  cdoninvalidate;
232 static  void            cdasync(void *callback_arg, u_int32_t code,
233                                 struct cam_path *path, void *arg);
234 static  int             cdcmdsizesysctl(SYSCTL_HANDLER_ARGS);
235 static  void            cdshorttimeout(void *arg);
236 static  void            cdschedule(struct cam_periph *periph, int priority);
237 static  void            cdrunchangerqueue(void *arg);
238 static  void            cdchangerschedule(struct cd_softc *softc);
239 static  int             cdrunccb(union ccb *ccb,
240                                  int (*error_routine)(union ccb *ccb,
241                                                       u_int32_t cam_flags,
242                                                       u_int32_t sense_flags),
243                                  u_int32_t cam_flags, u_int32_t sense_flags);
244 static union    ccb     *cdgetccb(struct cam_periph *periph,
245                                   u_int32_t priority);
246 static  void            cddone(struct cam_periph *periph,
247                                union ccb *start_ccb);
248 static  int             cderror(union ccb *ccb, u_int32_t cam_flags,
249                                 u_int32_t sense_flags);
250 static  union cd_pages  *cdgetpage(struct cd_mode_params *mode_params);
251 static  int             cdgetpagesize(int page_num);
252 static  void            cdprevent(struct cam_periph *periph, int action);
253 static  int             cdcheckmedia(struct cam_periph *periph);
254 static  int             cdsize(struct cam_periph *periph, u_int32_t *size);
255 static  int             cd6byteworkaround(union ccb *ccb);
256 static  int             cdreadtoc(struct cam_periph *periph, u_int32_t mode, 
257                                   u_int32_t start, u_int8_t *data, 
258                                   u_int32_t len, u_int32_t sense_flags);
259 static  int             cdgetmode(struct cam_periph *periph, 
260                                   struct cd_mode_params *data, u_int32_t page);
261 static  int             cdsetmode(struct cam_periph *periph,
262                                   struct cd_mode_params *data);
263 static  int             cdplay(struct cam_periph *periph, u_int32_t blk, 
264                                u_int32_t len);
265 static  int             cdreadsubchannel(struct cam_periph *periph, 
266                                          u_int32_t mode, u_int32_t format, 
267                                          int track, 
268                                          struct cd_sub_channel_info *data, 
269                                          u_int32_t len);
270 static  int             cdplaymsf(struct cam_periph *periph, u_int32_t startm, 
271                                   u_int32_t starts, u_int32_t startf, 
272                                   u_int32_t endm, u_int32_t ends, 
273                                   u_int32_t endf);
274 static  int             cdplaytracks(struct cam_periph *periph, 
275                                      u_int32_t strack, u_int32_t sindex,
276                                      u_int32_t etrack, u_int32_t eindex);
277 static  int             cdpause(struct cam_periph *periph, u_int32_t go);
278 static  int             cdstopunit(struct cam_periph *periph, u_int32_t eject);
279 static  int             cdstartunit(struct cam_periph *periph, int load);
280 static  int             cdsetspeed(struct cam_periph *periph,
281                                    u_int32_t rdspeed, u_int32_t wrspeed);
282 static  int             cdreportkey(struct cam_periph *periph,
283                                     struct dvd_authinfo *authinfo);
284 static  int             cdsendkey(struct cam_periph *periph,
285                                   struct dvd_authinfo *authinfo);
286 static  int             cdreaddvdstructure(struct cam_periph *periph,
287                                            struct dvd_struct *dvdstruct);
288
289 static struct periph_driver cddriver =
290 {
291         cdinit, "cd",
292         TAILQ_HEAD_INITIALIZER(cddriver.units), /* generation */ 0
293 };
294
295 DATA_SET(periphdriver_set, cddriver);
296
297 /* For 2.2-stable support */
298 #ifndef D_DISK
299 #define D_DISK 0
300 #endif
301 static struct cdevsw cd_cdevsw = {
302         /* name */      "cd",
303         /* maj */       SCSICD_CDEV_MAJOR,
304         /* flags */     D_DISK,
305         /* port */      NULL,
306         /* clone */     NULL,
307
308         /* open */      cdopen,
309         /* close */     cdclose,
310         /* read */      physread,
311         /* write */     physwrite,
312         /* ioctl */     cdioctl,
313         /* poll */      nopoll,
314         /* mmap */      nommap,
315         /* strategy */  cdstrategy,
316         /* dump */      nodump,
317         /* psize */     nopsize,
318 };
319
320 static struct extend_array *cdperiphs;
321 static int num_changers;
322
323 #ifndef CHANGER_MIN_BUSY_SECONDS
324 #define CHANGER_MIN_BUSY_SECONDS        5
325 #endif
326 #ifndef CHANGER_MAX_BUSY_SECONDS
327 #define CHANGER_MAX_BUSY_SECONDS        15
328 #endif
329
330 static int changer_min_busy_seconds = CHANGER_MIN_BUSY_SECONDS;
331 static int changer_max_busy_seconds = CHANGER_MAX_BUSY_SECONDS;
332
333 /*
334  * XXX KDM this CAM node should be moved if we ever get more CAM sysctl
335  * variables.
336  */
337 SYSCTL_NODE(_kern_cam, OID_AUTO, cd, CTLFLAG_RD, 0, "CAM CDROM driver");
338 SYSCTL_NODE(_kern_cam_cd, OID_AUTO, changer, CTLFLAG_RD, 0, "CD Changer");
339 SYSCTL_INT(_kern_cam_cd_changer, OID_AUTO, min_busy_seconds, CTLFLAG_RW,
340            &changer_min_busy_seconds, 0, "Minimum changer scheduling quantum");
341 TUNABLE_INT("kern.cam.cd.changer.min_busy_seconds", &changer_min_busy_seconds);
342 SYSCTL_INT(_kern_cam_cd_changer, OID_AUTO, max_busy_seconds, CTLFLAG_RW,
343            &changer_max_busy_seconds, 0, "Maximum changer scheduling quantum");
344 TUNABLE_INT("kern.cam.cd.changer.max_busy_seconds", &changer_max_busy_seconds);
345
346 struct cdchanger {
347         path_id_t                        path_id;
348         target_id_t                      target_id;
349         int                              num_devices;
350         struct camq                      devq;
351         struct timeval                   start_time;
352         struct cd_softc                  *cur_device;
353         struct callout                   short_handle;
354         struct callout                   long_handle;
355         volatile cd_changer_flags        flags;
356         STAILQ_ENTRY(cdchanger)          changer_links;
357         STAILQ_HEAD(chdevlist, cd_softc) chluns;
358 };
359
360 static STAILQ_HEAD(changerlist, cdchanger) changerq;
361
362 void
363 cdinit(void)
364 {
365         cam_status status;
366         struct cam_path *path;
367
368         /*
369          * Create our extend array for storing the devices we attach to.
370          */
371         cdperiphs = cam_extend_new();
372         if (cdperiphs == NULL) {
373                 printf("cd: Failed to alloc extend array!\n");
374                 return;
375         }
376
377         /*
378          * Install a global async callback.  This callback will
379          * receive async callbacks like "new device found".
380          */
381         status = xpt_create_path(&path, /*periph*/NULL, CAM_XPT_PATH_ID,
382                                  CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
383
384         if (status == CAM_REQ_CMP) {
385                 struct ccb_setasync csa;
386
387                 xpt_setup_ccb(&csa.ccb_h, path, /*priority*/5);
388                 csa.ccb_h.func_code = XPT_SASYNC_CB;
389                 csa.event_enable = AC_FOUND_DEVICE;
390                 csa.callback = cdasync;
391                 csa.callback_arg = NULL;
392                 xpt_action((union ccb *)&csa);
393                 status = csa.ccb_h.status;
394                 xpt_free_path(path);
395         }
396
397         if (status != CAM_REQ_CMP) {
398                 printf("cd: Failed to attach master async callback "
399                        "due to status 0x%x!\n", status);
400         }
401 }
402
403 static void
404 cdoninvalidate(struct cam_periph *periph)
405 {
406         struct cd_softc *softc;
407         struct buf *q_bp;
408         struct ccb_setasync csa;
409
410         softc = (struct cd_softc *)periph->softc;
411
412         /*
413          * De-register any async callbacks.
414          */
415         xpt_setup_ccb(&csa.ccb_h, periph->path,
416                       /* priority */ 5);
417         csa.ccb_h.func_code = XPT_SASYNC_CB;
418         csa.event_enable = 0;
419         csa.callback = cdasync;
420         csa.callback_arg = periph;
421         xpt_action((union ccb *)&csa);
422
423         softc->flags |= CD_FLAG_INVALID;
424
425         /*
426          * Although the oninvalidate() routines are always while in a
427          * critical section, we need to be in a critical section here to
428          * keep the buffer queue from being modified while we traverse it.
429          */
430         crit_enter();
431
432         /*
433          * Return all queued I/O with ENXIO.
434          * XXX Handle any transactions queued to the card
435          *     with XPT_ABORT_CCB.
436          */
437         while ((q_bp = bufq_first(&softc->buf_queue)) != NULL){
438                 bufq_remove(&softc->buf_queue, q_bp);
439                 q_bp->b_resid = q_bp->b_bcount;
440                 q_bp->b_error = ENXIO;
441                 q_bp->b_flags |= B_ERROR;
442                 biodone(q_bp);
443         }
444         crit_exit();
445
446         /*
447          * If this device is part of a changer, and it was scheduled
448          * to run, remove it from the run queue since we just nuked
449          * all of its scheduled I/O.
450          */
451         if ((softc->flags & CD_FLAG_CHANGER)
452          && (softc->pinfo.index != CAM_UNQUEUED_INDEX))
453                 camq_remove(&softc->changer->devq, softc->pinfo.index);
454
455         xpt_print_path(periph->path);
456         printf("lost device\n");
457 }
458
459 static void
460 cdcleanup(struct cam_periph *periph)
461 {
462         struct cd_softc *softc;
463
464         softc = (struct cd_softc *)periph->softc;
465
466         xpt_print_path(periph->path);
467         printf("removing device entry\n");
468
469         if ((softc->flags & CD_FLAG_SCTX_INIT) != 0
470             && sysctl_ctx_free(&softc->sysctl_ctx) != 0) {
471                 xpt_print_path(periph->path);
472                 printf("can't remove sysctl context\n");
473         }
474
475         crit_enter();
476         /*
477          * In the queued, non-active case, the device in question
478          * has already been removed from the changer run queue.  Since this
479          * device is active, we need to de-activate it, and schedule
480          * another device to run.  (if there is another one to run)
481          */
482         if ((softc->flags & CD_FLAG_CHANGER)
483          && (softc->flags & CD_FLAG_ACTIVE)) {
484
485                 /*
486                  * The purpose of the short timeout is soley to determine
487                  * whether the current device has finished or not.  Well,
488                  * since we're removing the active device, we know that it
489                  * is finished.  So, get rid of the short timeout.
490                  * Otherwise, if we're in the time period before the short
491                  * timeout fires, and there are no other devices in the
492                  * queue to run, there won't be any other device put in the
493                  * active slot.  i.e., when we call cdrunchangerqueue()
494                  * below, it won't do anything.  Then, when the short
495                  * timeout fires, it'll look at the "current device", which
496                  * we are free below, and possibly panic the kernel on a
497                  * bogus pointer reference.
498                  *
499                  * The long timeout doesn't really matter, since we
500                  * decrement the qfrozen_cnt to indicate that there is
501                  * nothing in the active slot now.  Therefore, there won't
502                  * be any bogus pointer references there.
503                  */
504                 if (softc->changer->flags & CHANGER_SHORT_TMOUT_SCHED) {
505                         callout_stop(&softc->changer->short_handle);
506                         softc->changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
507                 }
508                 softc->changer->devq.qfrozen_cnt--;
509                 softc->changer->flags |= CHANGER_MANUAL_CALL;
510                 cdrunchangerqueue(softc->changer);
511         }
512
513         /*
514          * If we're removing the last device on the changer, go ahead and
515          * remove the changer device structure.
516          */
517         if ((softc->flags & CD_FLAG_CHANGER)
518          && (--softc->changer->num_devices == 0)) {
519
520                 /*
521                  * Theoretically, there shouldn't be any timeouts left, but
522                  * I'm not completely sure that that will be the case.  So,
523                  * it won't hurt to check and see if there are any left.
524                  */
525                 if (softc->changer->flags & CHANGER_TIMEOUT_SCHED) {
526                         callout_stop(&softc->changer->long_handle);
527                         softc->changer->flags &= ~CHANGER_TIMEOUT_SCHED;
528                 }
529
530                 if (softc->changer->flags & CHANGER_SHORT_TMOUT_SCHED) {
531                         callout_stop(&softc->changer->short_handle);
532                         softc->changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
533                 }
534
535                 STAILQ_REMOVE(&changerq, softc->changer, cdchanger,
536                               changer_links);
537                 xpt_print_path(periph->path);
538                 printf("removing changer entry\n");
539                 free(softc->changer, M_DEVBUF);
540                 num_changers--;
541         }
542         devstat_remove_entry(&softc->device_stats);
543         cam_extend_release(cdperiphs, periph->unit_number);
544         if (softc->disk.d_rawdev) {
545                 disk_destroy(&softc->disk);
546         }
547         free(softc, M_DEVBUF);
548         crit_exit();
549 }
550
551 static void
552 cdasync(void *callback_arg, u_int32_t code,
553         struct cam_path *path, void *arg)
554 {
555         struct cam_periph *periph;
556
557         periph = (struct cam_periph *)callback_arg;
558         switch (code) {
559         case AC_FOUND_DEVICE:
560         {
561                 struct ccb_getdev *cgd;
562                 cam_status status;
563
564                 cgd = (struct ccb_getdev *)arg;
565
566                 if (SID_TYPE(&cgd->inq_data) != T_CDROM
567                     && SID_TYPE(&cgd->inq_data) != T_WORM)
568                         break;
569
570                 /*
571                  * Allocate a peripheral instance for
572                  * this device and start the probe
573                  * process.
574                  */
575                 status = cam_periph_alloc(cdregister, cdoninvalidate,
576                                           cdcleanup, cdstart,
577                                           "cd", CAM_PERIPH_BIO,
578                                           cgd->ccb_h.path, cdasync,
579                                           AC_FOUND_DEVICE, cgd);
580
581                 if (status != CAM_REQ_CMP
582                  && status != CAM_REQ_INPROG)
583                         printf("cdasync: Unable to attach new device "
584                                "due to status 0x%x\n", status);
585
586                 break;
587         }
588         case AC_SENT_BDR:
589         case AC_BUS_RESET:
590         {
591                 struct cd_softc *softc;
592                 struct ccb_hdr *ccbh;
593
594                 softc = (struct cd_softc *)periph->softc;
595                 crit_enter();
596                 /*
597                  * Don't fail on the expected unit attention
598                  * that will occur.
599                  */
600                 softc->flags |= CD_FLAG_RETRY_UA;
601                 for (ccbh = LIST_FIRST(&softc->pending_ccbs);
602                      ccbh != NULL; ccbh = LIST_NEXT(ccbh, periph_links.le))
603                         ccbh->ccb_state |= CD_CCB_RETRY_UA;
604                 crit_exit();
605                 /* FALLTHROUGH */
606         }
607         default:
608                 cam_periph_async(periph, code, path, arg);
609                 break;
610         }
611 }
612
613 static void
614 cdsysctlinit(void *context, int pending)
615 {
616         struct cam_periph *periph;
617         struct cd_softc *softc;
618         char tmpstr[80], tmpstr2[80];
619
620         periph = (struct cam_periph *)context;
621         softc = (struct cd_softc *)periph->softc;
622
623         snprintf(tmpstr, sizeof(tmpstr), "CAM CD unit %d", periph->unit_number);
624         snprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number);
625
626         sysctl_ctx_init(&softc->sysctl_ctx);
627         softc->flags |= CD_FLAG_SCTX_INIT;
628         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
629         SYSCTL_STATIC_CHILDREN(_kern_cam_cd), OID_AUTO,
630         tmpstr2, CTLFLAG_RD, 0, tmpstr);
631
632         if (softc->sysctl_tree == NULL) {
633                 printf("cdsysctlinit: unable to allocate sysctl tree\n");
634                 return;
635         }
636
637         /*
638          * Now register the sysctl handler, so the user can the value on
639          * the fly.
640          */
641         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
642                         OID_AUTO, "minimum_cmd_size", CTLTYPE_INT | CTLFLAG_RW,
643                         &softc->minimum_command_size, 0, cdcmdsizesysctl, "I",
644                         "Minimum CDB size");
645 }
646
647 /*
648  * We have a handler function for this so we can check the values when the
649  * user sets them, instead of every time we look at them.
650  */
651 static int
652 cdcmdsizesysctl(SYSCTL_HANDLER_ARGS)
653 {
654         int error, value;
655
656         value = *(int *)arg1;
657
658         error = sysctl_handle_int(oidp, &value, 0, req);
659
660         if ((error != 0) || (req->newptr == NULL))
661                 return (error);
662
663         /*
664          * The only real values we can have here are 6 or 10.  I don't
665          * really forsee having 12 be an option at any time in the future.
666          * So if the user sets something less than or equal to 6, we'll set
667          * it to 6.  If he sets something greater than 6, we'll set it to 10.
668          *
669          * I suppose we could just return an error here for the wrong values,
670          * but I don't think it's necessary to do so, as long as we can
671          * determine the user's intent without too much trouble.
672          */
673         if (value < 6)
674                 value = 6;
675         else if (value > 6)
676                 value = 10;
677
678         *(int *)arg1 = value;
679
680         return (0);
681 }
682
683
684 static cam_status
685 cdregister(struct cam_periph *periph, void *arg)
686 {
687         struct cd_softc *softc;
688         struct ccb_setasync csa;
689         struct ccb_pathinq cpi;
690         struct ccb_getdev *cgd;
691         char tmpstr[80];
692         caddr_t match;
693
694         cgd = (struct ccb_getdev *)arg;
695         if (periph == NULL) {
696                 printf("cdregister: periph was NULL!!\n");
697                 return(CAM_REQ_CMP_ERR);
698         }
699         if (cgd == NULL) {
700                 printf("cdregister: no getdev CCB, can't register device\n");
701                 return(CAM_REQ_CMP_ERR);
702         }
703
704         softc = malloc(sizeof(*softc), M_DEVBUF, M_INTWAIT | M_ZERO);
705         LIST_INIT(&softc->pending_ccbs);
706         STAILQ_INIT(&softc->mode_queue);
707         softc->state = CD_STATE_PROBE;
708         bufq_init(&softc->buf_queue);
709         if (SID_IS_REMOVABLE(&cgd->inq_data))
710                 softc->flags |= CD_FLAG_DISC_REMOVABLE;
711         if ((cgd->inq_data.flags & SID_CmdQue) != 0)
712                 softc->flags |= CD_FLAG_TAGGED_QUEUING;
713
714         periph->softc = softc;
715         softc->periph = periph;
716
717         cam_extend_set(cdperiphs, periph->unit_number, periph);
718
719         /*
720          * See if this device has any quirks.
721          */
722         match = cam_quirkmatch((caddr_t)&cgd->inq_data,
723                                (caddr_t)cd_quirk_table,
724                                sizeof(cd_quirk_table)/sizeof(*cd_quirk_table),
725                                sizeof(*cd_quirk_table), scsi_inquiry_match);
726
727         if (match != NULL)
728                 softc->quirks = ((struct cd_quirk_entry *)match)->quirks;
729         else
730                 softc->quirks = CD_Q_NONE;
731
732         /* Check if the SIM does not want 6 byte commands */
733         xpt_setup_ccb(&cpi.ccb_h, periph->path, /*priority*/1);
734         cpi.ccb_h.func_code = XPT_PATH_INQ;
735         xpt_action((union ccb *)&cpi);
736         if (cpi.ccb_h.status == CAM_REQ_CMP && (cpi.hba_misc & PIM_NO_6_BYTE))
737                 softc->quirks |= CD_Q_10_BYTE_ONLY;
738
739         TASK_INIT(&softc->sysctl_task, 0, cdsysctlinit, periph);
740
741         /* The default is 6 byte commands, unless quirked otherwise */
742         if (softc->quirks & CD_Q_10_BYTE_ONLY)
743                 softc->minimum_command_size = 10;
744         else
745                 softc->minimum_command_size = 6;
746
747         /*
748          * Load the user's default, if any.
749          */
750         snprintf(tmpstr, sizeof(tmpstr), "kern.cam.cd.%d.minimum_cmd_size",
751                 periph->unit_number);
752         TUNABLE_INT_FETCH(tmpstr, &softc->minimum_command_size);
753
754         /* 6 and 10 are the only permissible values here. */
755         if (softc->minimum_command_size < 6)
756                 softc->minimum_command_size = 6;
757         else if (softc->minimum_command_size > 6)
758                 softc->minimum_command_size = 10;
759
760         /*
761          * We need to register the statistics structure for this device,
762          * but we don't have the blocksize yet for it.  So, we register
763          * the structure and indicate that we don't have the blocksize
764          * yet.  Unlike other SCSI peripheral drivers, we explicitly set
765          * the device type here to be CDROM, rather than just ORing in
766          * the device type.  This is because this driver can attach to either
767          * CDROM or WORM devices, and we want this peripheral driver to
768          * show up in the devstat list as a CD peripheral driver, not a
769          * WORM peripheral driver.  WORM drives will also have the WORM
770          * driver attached to them.
771          */
772         devstat_add_entry(&softc->device_stats, "cd", 
773                           periph->unit_number, 0,
774                           DEVSTAT_BS_UNAVAILABLE,
775                           DEVSTAT_TYPE_CDROM | DEVSTAT_TYPE_IF_SCSI,
776                           DEVSTAT_PRIORITY_CD);
777         disk_create(periph->unit_number, &softc->disk,
778                     DSO_ONESLICE | DSO_COMPATLABEL, &cd_cdevsw);
779
780         /*
781          * Add an async callback so that we get
782          * notified if this device goes away.
783          */
784         xpt_setup_ccb(&csa.ccb_h, periph->path,
785                       /* priority */ 5);
786         csa.ccb_h.func_code = XPT_SASYNC_CB;
787         csa.event_enable = AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE;
788         csa.callback = cdasync;
789         csa.callback_arg = periph;
790         xpt_action((union ccb *)&csa);
791
792         /*
793          * If the target lun is greater than 0, we most likely have a CD
794          * changer device.  Check the quirk entries as well, though, just
795          * in case someone has a CD tower with one lun per drive or
796          * something like that.  Also, if we know up front that a
797          * particular device is a changer, we can mark it as such starting
798          * with lun 0, instead of lun 1.  It shouldn't be necessary to have
799          * a quirk entry to define something as a changer, however.
800          */
801         if (((cgd->ccb_h.target_lun > 0)
802           && ((softc->quirks & CD_Q_NO_CHANGER) == 0))
803          || ((softc->quirks & CD_Q_CHANGER) != 0)) {
804                 struct cdchanger *nchanger;
805                 struct cam_periph *nperiph;
806                 struct cam_path *path;
807                 cam_status status;
808                 int found;
809
810                 /* Set the changer flag in the current device's softc */
811                 softc->flags |= CD_FLAG_CHANGER;
812
813                 if (num_changers == 0)
814                         STAILQ_INIT(&changerq);
815
816                 /*
817                  * Now, look around for an existing changer device with the
818                  * same path and target ID as the current device.
819                  */
820                 for (found = 0,
821                      nchanger = (struct cdchanger *)STAILQ_FIRST(&changerq);
822                      nchanger != NULL;
823                      nchanger = STAILQ_NEXT(nchanger, changer_links)){
824                         if ((nchanger->path_id == cgd->ccb_h.path_id) 
825                          && (nchanger->target_id == cgd->ccb_h.target_id)) {
826                                 found = 1;
827                                 break;
828                         }
829                 }
830
831                 /*
832                  * If we found a matching entry, just add this device to
833                  * the list of devices on this changer.
834                  */
835                 if (found == 1) {
836                         struct chdevlist *chlunhead;
837
838                         chlunhead = &nchanger->chluns;
839
840                         /*
841                          * XXX KDM look at consolidating this code with the
842                          * code below in a separate function.
843                          */
844
845                         /*
846                          * Create a path with lun id 0, and see if we can
847                          * find a matching device
848                          */
849                         status = xpt_create_path(&path, /*periph*/ periph,
850                                                  cgd->ccb_h.path_id,
851                                                  cgd->ccb_h.target_id, 0);
852
853                         if ((status == CAM_REQ_CMP)
854                          && ((nperiph = cam_periph_find(path, "cd")) != NULL)){
855                                 struct cd_softc *nsoftc;
856
857                                 nsoftc = (struct cd_softc *)nperiph->softc;
858
859                                 if ((nsoftc->flags & CD_FLAG_CHANGER) == 0){
860                                         nsoftc->flags |= CD_FLAG_CHANGER;
861                                         nchanger->num_devices++;
862                                         if (camq_resize(&nchanger->devq,
863                                            nchanger->num_devices)!=CAM_REQ_CMP){
864                                                 printf("cdregister: "
865                                                        "camq_resize "
866                                                        "failed, changer "
867                                                        "support may "
868                                                        "be messed up\n");
869                                         }
870                                         nsoftc->changer = nchanger;
871                                         nsoftc->pinfo.index =CAM_UNQUEUED_INDEX;
872
873                                         STAILQ_INSERT_TAIL(&nchanger->chluns,
874                                                           nsoftc,changer_links);
875                                 }
876                                 xpt_free_path(path);
877                         } else if (status == CAM_REQ_CMP)
878                                 xpt_free_path(path);
879                         else {
880                                 printf("cdregister: unable to allocate path\n"
881                                        "cdregister: changer support may be "
882                                        "broken\n");
883                         }
884
885                         nchanger->num_devices++;
886
887                         softc->changer = nchanger;
888                         softc->pinfo.index = CAM_UNQUEUED_INDEX;
889
890                         if (camq_resize(&nchanger->devq,
891                             nchanger->num_devices) != CAM_REQ_CMP) {
892                                 printf("cdregister: camq_resize "
893                                        "failed, changer support may "
894                                        "be messed up\n");
895                         }
896
897                         STAILQ_INSERT_TAIL(chlunhead, softc, changer_links);
898                 }
899                 /*
900                  * In this case, we don't already have an entry for this
901                  * particular changer, so we need to create one, add it to
902                  * the queue, and queue this device on the list for this
903                  * changer.  Before we queue this device, however, we need
904                  * to search for lun id 0 on this target, and add it to the
905                  * queue first, if it exists.  (and if it hasn't already
906                  * been marked as part of the changer.)
907                  */
908                 else {
909                         nchanger = malloc(sizeof(struct cdchanger),
910                                         M_DEVBUF, M_INTWAIT | M_ZERO);
911                         callout_init(&nchanger->short_handle);
912                         callout_init(&nchanger->long_handle);
913                         if (camq_init(&nchanger->devq, 1) != 0) {
914                                 softc->flags &= ~CD_FLAG_CHANGER;
915                                 printf("cdregister: changer support "
916                                        "disabled\n");
917                                 goto cdregisterexit;
918                         }
919
920                         num_changers++;
921
922                         nchanger->path_id = cgd->ccb_h.path_id;
923                         nchanger->target_id = cgd->ccb_h.target_id;
924
925                         /* this is superfluous, but it makes things clearer */
926                         nchanger->num_devices = 0;
927
928                         STAILQ_INIT(&nchanger->chluns);
929
930                         STAILQ_INSERT_TAIL(&changerq, nchanger,
931                                            changer_links);
932                         
933                         /*
934                          * Create a path with lun id 0, and see if we can
935                          * find a matching device
936                          */
937                         status = xpt_create_path(&path, /*periph*/ periph,
938                                                  cgd->ccb_h.path_id,
939                                                  cgd->ccb_h.target_id, 0);
940
941                         /*
942                          * If we were able to allocate the path, and if we
943                          * find a matching device and it isn't already
944                          * marked as part of a changer, then we add it to
945                          * the current changer.
946                          */
947                         if ((status == CAM_REQ_CMP)
948                          && ((nperiph = cam_periph_find(path, "cd")) != NULL)
949                          && ((((struct cd_softc *)periph->softc)->flags &
950                                CD_FLAG_CHANGER) == 0)) {
951                                 struct cd_softc *nsoftc;
952
953                                 nsoftc = (struct cd_softc *)nperiph->softc;
954
955                                 nsoftc->flags |= CD_FLAG_CHANGER;
956                                 nchanger->num_devices++;
957                                 if (camq_resize(&nchanger->devq,
958                                     nchanger->num_devices) != CAM_REQ_CMP) {
959                                         printf("cdregister: camq_resize "
960                                                "failed, changer support may "
961                                                "be messed up\n");
962                                 }
963                                 nsoftc->changer = nchanger;
964                                 nsoftc->pinfo.index = CAM_UNQUEUED_INDEX;
965
966                                 STAILQ_INSERT_TAIL(&nchanger->chluns,
967                                                    nsoftc, changer_links);
968                                 xpt_free_path(path);
969                         } else if (status == CAM_REQ_CMP)
970                                 xpt_free_path(path);
971                         else {
972                                 printf("cdregister: unable to allocate path\n"
973                                        "cdregister: changer support may be "
974                                        "broken\n");
975                         }
976
977                         softc->changer = nchanger;
978                         softc->pinfo.index = CAM_UNQUEUED_INDEX;
979                         nchanger->num_devices++;
980                         if (camq_resize(&nchanger->devq,
981                             nchanger->num_devices) != CAM_REQ_CMP) {
982                                 printf("cdregister: camq_resize "
983                                        "failed, changer support may "
984                                        "be messed up\n");
985                         }
986                         STAILQ_INSERT_TAIL(&nchanger->chluns, softc,
987                                            changer_links);
988                 }
989         }
990
991 cdregisterexit:
992
993         /* Lock this peripheral until we are setup */
994         /* Can't block */
995         cam_periph_lock(periph, 0); 
996
997         if ((softc->flags & CD_FLAG_CHANGER) == 0)
998                 xpt_schedule(periph, /*priority*/5);
999         else
1000                 cdschedule(periph, /*priority*/ 5);
1001
1002         return(CAM_REQ_CMP);
1003 }
1004
1005 static int
1006 cdopen(dev_t dev, int flags, int fmt, struct thread *td)
1007 {
1008         struct cam_periph *periph;
1009         struct cd_softc *softc;
1010         int unit, error;
1011
1012         unit = dkunit(dev);
1013         periph = cam_extend_get(cdperiphs, unit);
1014
1015         if (periph == NULL)
1016                 return (ENXIO);
1017
1018         softc = (struct cd_softc *)periph->softc;
1019
1020         /*
1021          * Grab a critical section and hold it until we lock the peripheral.
1022          */
1023         crit_enter();
1024         if (softc->flags & CD_FLAG_INVALID) {
1025                 crit_exit();
1026                 return(ENXIO);
1027         }
1028
1029         if ((error = cam_periph_lock(periph, PCATCH)) != 0) {
1030                 crit_exit();
1031                 return (error);
1032         }
1033
1034         crit_exit();
1035
1036         if (cam_periph_acquire(periph) != CAM_REQ_CMP)
1037                 return(ENXIO);
1038
1039         /*
1040          * Check for media, and set the appropriate flags.  We don't bail
1041          * if we don't have media, but then we don't allow anything but the
1042          * CDIOCEJECT/CDIOCCLOSE ioctls if there is no media.
1043          *
1044          * XXX KDM for now, we do fail the open if we don't have media.  We
1045          * can change this once we've figured out how to make the slice
1046          * code work well with media changing underneath it.
1047          */
1048         error = cdcheckmedia(periph);
1049
1050         if (error == 0)
1051                 softc->flags |= CD_FLAG_OPEN;
1052
1053         cam_periph_unlock(periph);
1054
1055         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("leaving cdopen\n"));
1056
1057         return (error);
1058 }
1059
1060 static int
1061 cdclose(dev_t dev, int flag, int fmt, struct thread *td)
1062 {
1063         struct  cam_periph *periph;
1064         struct  cd_softc *softc;
1065         int     unit, error;
1066
1067         unit = dkunit(dev);
1068         periph = cam_extend_get(cdperiphs, unit);
1069         if (periph == NULL)
1070                 return (ENXIO); 
1071
1072         softc = (struct cd_softc *)periph->softc;
1073
1074         if ((error = cam_periph_lock(periph, 0)) != 0)
1075                 return (error);
1076
1077         if ((softc->flags & CD_FLAG_DISC_REMOVABLE) != 0)
1078                 cdprevent(periph, PR_ALLOW);
1079
1080         /*
1081          * Unconditionally set the dsopen() flags back to their default
1082          * state.
1083          */
1084         softc->disk.d_dsflags &= ~DSO_NOLABELS;
1085         softc->disk.d_dsflags |= DSO_COMPATLABEL;
1086
1087         /*
1088          * Since we're closing this CD, mark the blocksize as unavailable.
1089          * It will be marked as available when the CD is opened again.
1090          */
1091         softc->device_stats.flags |= DEVSTAT_BS_UNAVAILABLE;
1092
1093         /*
1094          * We'll check the media and toc again at the next open().
1095          */
1096         softc->flags &= ~(CD_FLAG_VALID_MEDIA|CD_FLAG_VALID_TOC);
1097         
1098         softc->flags &= ~CD_FLAG_OPEN;
1099
1100         cam_periph_unlock(periph);
1101         cam_periph_release(periph);
1102
1103         return (0);
1104 }
1105
1106 static void
1107 cdshorttimeout(void *arg)
1108 {
1109         struct cdchanger *changer;
1110
1111         crit_enter();
1112
1113         changer = (struct cdchanger *)arg;
1114
1115         /* Always clear the short timeout flag, since that's what we're in */
1116         changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
1117
1118         /*
1119          * Check to see if there is any more pending or outstanding I/O for
1120          * this device.  If not, move it out of the active slot.
1121          */
1122         if ((bufq_first(&changer->cur_device->buf_queue) == NULL)
1123          && (changer->cur_device->device_stats.busy_count == 0)) {
1124                 changer->flags |= CHANGER_MANUAL_CALL;
1125                 cdrunchangerqueue(changer);
1126         }
1127         crit_exit();
1128 }
1129
1130 /*
1131  * This is a wrapper for xpt_schedule.  It only applies to changers.
1132  */
1133 static void
1134 cdschedule(struct cam_periph *periph, int priority)
1135 {
1136         struct cd_softc *softc;
1137
1138         crit_enter();
1139
1140         softc = (struct cd_softc *)periph->softc;
1141
1142         /*
1143          * If this device isn't currently queued, and if it isn't
1144          * the active device, then we queue this device and run the
1145          * changer queue if there is no timeout scheduled to do it.
1146          * If this device is the active device, just schedule it
1147          * to run again.  If this device is queued, there should be
1148          * a timeout in place already that will make sure it runs.
1149          */
1150         if ((softc->pinfo.index == CAM_UNQUEUED_INDEX) 
1151          && ((softc->flags & CD_FLAG_ACTIVE) == 0)) {
1152                 /*
1153                  * We don't do anything with the priority here.
1154                  * This is strictly a fifo queue.
1155                  */
1156                 softc->pinfo.priority = 1;
1157                 softc->pinfo.generation = ++softc->changer->devq.generation;
1158                 camq_insert(&softc->changer->devq, (cam_pinfo *)softc);
1159
1160                 /*
1161                  * Since we just put a device in the changer queue,
1162                  * check and see if there is a timeout scheduled for
1163                  * this changer.  If so, let the timeout handle
1164                  * switching this device into the active slot.  If
1165                  * not, manually call the timeout routine to
1166                  * bootstrap things.
1167                  */
1168                 if (((softc->changer->flags & CHANGER_TIMEOUT_SCHED)==0)
1169                  && ((softc->changer->flags & CHANGER_NEED_TIMEOUT)==0)
1170                  && ((softc->changer->flags & CHANGER_SHORT_TMOUT_SCHED)==0)){
1171                         softc->changer->flags |= CHANGER_MANUAL_CALL;
1172                         cdrunchangerqueue(softc->changer);
1173                 }
1174         } else if ((softc->flags & CD_FLAG_ACTIVE)
1175                 && ((softc->flags & CD_FLAG_SCHED_ON_COMP) == 0)) {
1176                 xpt_schedule(periph, priority);
1177         }
1178         crit_exit();
1179 }
1180
1181 static void
1182 cdrunchangerqueue(void *arg)
1183 {
1184         struct cd_softc *softc;
1185         struct cdchanger *changer;
1186         int called_from_timeout;
1187
1188         crit_enter();
1189
1190         changer = (struct cdchanger *)arg;
1191
1192         /*
1193          * If we have NOT been called from cdstrategy() or cddone(), and
1194          * instead from a timeout routine, go ahead and clear the
1195          * timeout flag.
1196          */
1197         if ((changer->flags & CHANGER_MANUAL_CALL) == 0) {
1198                 changer->flags &= ~CHANGER_TIMEOUT_SCHED;
1199                 called_from_timeout = 1;
1200         } else
1201                 called_from_timeout = 0;
1202
1203         /* Always clear the manual call flag */
1204         changer->flags &= ~CHANGER_MANUAL_CALL;
1205
1206         /* nothing to do if the queue is empty */
1207         if (changer->devq.entries <= 0) {
1208                 crit_exit();
1209                 return;
1210         }
1211
1212         /*
1213          * If the changer queue is frozen, that means we have an active
1214          * device.
1215          */
1216         if (changer->devq.qfrozen_cnt > 0) {
1217
1218                 if (changer->cur_device->device_stats.busy_count > 0) {
1219                         changer->cur_device->flags |= CD_FLAG_SCHED_ON_COMP;
1220                         changer->cur_device->bufs_left = 
1221                                 changer->cur_device->device_stats.busy_count;
1222                         if (called_from_timeout) {
1223                                 callout_reset(&changer->long_handle,
1224                                         changer_max_busy_seconds * hz,
1225                                         cdrunchangerqueue, changer);
1226                                 changer->flags |= CHANGER_TIMEOUT_SCHED;
1227                         }
1228                         crit_exit();
1229                         return;
1230                 }
1231
1232                 /*
1233                  * We always need to reset the frozen count and clear the
1234                  * active flag.
1235                  */
1236                 changer->devq.qfrozen_cnt--;
1237                 changer->cur_device->flags &= ~CD_FLAG_ACTIVE;
1238                 changer->cur_device->flags &= ~CD_FLAG_SCHED_ON_COMP;
1239
1240                 /*
1241                  * Check to see whether the current device has any I/O left
1242                  * to do.  If so, requeue it at the end of the queue.  If
1243                  * not, there is no need to requeue it.
1244                  */
1245                 if (bufq_first(&changer->cur_device->buf_queue) != NULL) {
1246
1247                         changer->cur_device->pinfo.generation =
1248                                 ++changer->devq.generation;
1249                         camq_insert(&changer->devq,
1250                                 (cam_pinfo *)changer->cur_device);
1251                 } 
1252         }
1253
1254         softc = (struct cd_softc *)camq_remove(&changer->devq, CAMQ_HEAD);
1255
1256         changer->cur_device = softc;
1257
1258         changer->devq.qfrozen_cnt++;
1259         softc->flags |= CD_FLAG_ACTIVE;
1260
1261         /* Just in case this device is waiting */
1262         wakeup(&softc->changer);
1263         xpt_schedule(softc->periph, /*priority*/ 1);
1264
1265         /*
1266          * Get rid of any pending timeouts, and set a flag to schedule new
1267          * ones so this device gets its full time quantum.
1268          */
1269         if (changer->flags & CHANGER_TIMEOUT_SCHED) {
1270                 callout_stop(&changer->long_handle);
1271                 changer->flags &= ~CHANGER_TIMEOUT_SCHED;
1272         }
1273
1274         if (changer->flags & CHANGER_SHORT_TMOUT_SCHED) {
1275                 callout_stop(&changer->short_handle);
1276                 changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
1277         }
1278
1279         /*
1280          * We need to schedule timeouts, but we only do this after the
1281          * first transaction has completed.  This eliminates the changer
1282          * switch time.
1283          */
1284         changer->flags |= CHANGER_NEED_TIMEOUT;
1285
1286         crit_exit();
1287 }
1288
1289 static void
1290 cdchangerschedule(struct cd_softc *softc)
1291 {
1292         struct cdchanger *changer;
1293
1294         crit_enter();
1295
1296         changer = softc->changer;
1297
1298         /*
1299          * If this is a changer, and this is the current device,
1300          * and this device has at least the minimum time quantum to
1301          * run, see if we can switch it out.
1302          */
1303         if ((softc->flags & CD_FLAG_ACTIVE) 
1304          && ((changer->flags & CHANGER_SHORT_TMOUT_SCHED) == 0)
1305          && ((changer->flags & CHANGER_NEED_TIMEOUT) == 0)) {
1306                 /*
1307                  * We try three things here.  The first is that we
1308                  * check to see whether the schedule on completion
1309                  * flag is set.  If it is, we decrement the number
1310                  * of buffers left, and if it's zero, we reschedule.
1311                  * Next, we check to see whether the pending buffer
1312                  * queue is empty and whether there are no
1313                  * outstanding transactions.  If so, we reschedule.
1314                  * Next, we see if the pending buffer queue is empty.
1315                  * If it is, we set the number of buffers left to
1316                  * the current active buffer count and set the
1317                  * schedule on complete flag.
1318                  */
1319                 if (softc->flags & CD_FLAG_SCHED_ON_COMP) {
1320                         if (--softc->bufs_left == 0) {
1321                                 softc->changer->flags |=
1322                                         CHANGER_MANUAL_CALL;
1323                                 softc->flags &= ~CD_FLAG_SCHED_ON_COMP;
1324                                 cdrunchangerqueue(softc->changer);
1325                         }
1326                 } else if ((bufq_first(&softc->buf_queue) == NULL)
1327                         && (softc->device_stats.busy_count == 0)) {
1328                         softc->changer->flags |= CHANGER_MANUAL_CALL;
1329                         cdrunchangerqueue(softc->changer);
1330                 }
1331         } else if ((softc->changer->flags & CHANGER_NEED_TIMEOUT) 
1332                 && (softc->flags & CD_FLAG_ACTIVE)) {
1333
1334                 /*
1335                  * Now that the first transaction to this
1336                  * particular device has completed, we can go ahead
1337                  * and schedule our timeouts.
1338                  */
1339                 if ((changer->flags & CHANGER_TIMEOUT_SCHED) == 0) {
1340                         callout_reset(&changer->long_handle,
1341                                     changer_max_busy_seconds * hz,
1342                                     cdrunchangerqueue, changer);
1343                         changer->flags |= CHANGER_TIMEOUT_SCHED;
1344                 } else
1345                         printf("cdchangerschedule: already have a long"
1346                                " timeout!\n");
1347
1348                 if ((changer->flags & CHANGER_SHORT_TMOUT_SCHED) == 0) {
1349                         callout_reset(&changer->short_handle,
1350                                         changer_min_busy_seconds * hz,
1351                                         cdshorttimeout, changer);
1352                         changer->flags |= CHANGER_SHORT_TMOUT_SCHED;
1353                 } else
1354                         printf("cdchangerschedule: already have a short "
1355                                "timeout!\n");
1356
1357                 /*
1358                  * We just scheduled timeouts, no need to schedule
1359                  * more.
1360                  */
1361                 changer->flags &= ~CHANGER_NEED_TIMEOUT;
1362
1363         }
1364         crit_exit();
1365 }
1366
1367 static int
1368 cdrunccb(union ccb *ccb, int (*error_routine)(union ccb *ccb,
1369                                               u_int32_t cam_flags,
1370                                               u_int32_t sense_flags),
1371          u_int32_t cam_flags, u_int32_t sense_flags)
1372 {
1373         struct cd_softc *softc;
1374         struct cam_periph *periph;
1375         int error;
1376
1377         periph = xpt_path_periph(ccb->ccb_h.path);
1378         softc = (struct cd_softc *)periph->softc;
1379
1380         error = cam_periph_runccb(ccb, error_routine, cam_flags, sense_flags,
1381                                   &softc->device_stats);
1382
1383         if (softc->flags & CD_FLAG_CHANGER)
1384                 cdchangerschedule(softc);
1385
1386         return(error);
1387 }
1388
1389 static union ccb *
1390 cdgetccb(struct cam_periph *periph, u_int32_t priority)
1391 {
1392         struct cd_softc *softc;
1393
1394         softc = (struct cd_softc *)periph->softc;
1395
1396         if (softc->flags & CD_FLAG_CHANGER) {
1397                 crit_enter();
1398
1399                 /*
1400                  * This should work the first time this device is woken up,
1401                  * but just in case it doesn't, we use a while loop.
1402                  */
1403                 while ((softc->flags & CD_FLAG_ACTIVE) == 0) {
1404                         /*
1405                          * If this changer isn't already queued, queue it up.
1406                          */
1407                         if (softc->pinfo.index == CAM_UNQUEUED_INDEX) {
1408                                 softc->pinfo.priority = 1;
1409                                 softc->pinfo.generation =
1410                                         ++softc->changer->devq.generation;
1411                                 camq_insert(&softc->changer->devq,
1412                                             (cam_pinfo *)softc);
1413                         }
1414                         if (((softc->changer->flags & CHANGER_TIMEOUT_SCHED)==0)
1415                          && ((softc->changer->flags & CHANGER_NEED_TIMEOUT)==0)
1416                          && ((softc->changer->flags
1417                               & CHANGER_SHORT_TMOUT_SCHED)==0)) {
1418                                 softc->changer->flags |= CHANGER_MANUAL_CALL;
1419                                 cdrunchangerqueue(softc->changer);
1420                         } else
1421                                 tsleep(&softc->changer, 0, "cgticb", 0);
1422                 }
1423                 crit_exit();
1424         }
1425         return(cam_periph_getccb(periph, priority));
1426 }
1427
1428 /*
1429  * Actually translate the requested transfer into one the physical driver
1430  * can understand.  The transfer is described by a buf and will include
1431  * only one physical transfer.
1432  */
1433 static void
1434 cdstrategy(struct buf *bp)
1435 {
1436         struct cam_periph *periph;
1437         struct cd_softc *softc;
1438         u_int  unit, part;
1439
1440         unit = dkunit(bp->b_dev);
1441         part = dkpart(bp->b_dev);
1442         periph = cam_extend_get(cdperiphs, unit);
1443         if (periph == NULL) {
1444                 bp->b_error = ENXIO;
1445                 goto bad;
1446         }
1447
1448         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdstrategy\n"));
1449
1450         softc = (struct cd_softc *)periph->softc;
1451
1452         /*
1453          * Mask interrupts so that the pack cannot be invalidated until
1454          * after we are in the queue.  Otherwise, we might not properly
1455          * clean up one of the buffers.
1456          */
1457         crit_enter();
1458         
1459         /*
1460          * If the device has been made invalid, error out
1461          */
1462         if ((softc->flags & CD_FLAG_INVALID)) {
1463                 crit_exit();
1464                 bp->b_error = ENXIO;
1465                 goto bad;
1466         }
1467
1468         /*
1469          * If we don't have valid media, look for it before trying to
1470          * schedule the I/O.
1471          */
1472         if ((softc->flags & CD_FLAG_VALID_MEDIA) == 0) {
1473                 int error;
1474
1475                 error = cdcheckmedia(periph);
1476                 if (error != 0) {
1477                         crit_exit();
1478                         bp->b_error = error;
1479                         goto bad;
1480                 }
1481         }
1482
1483         /*
1484          * Place it in the queue of disk activities for this disk
1485          */
1486         bufqdisksort(&softc->buf_queue, bp);
1487
1488         crit_exit();
1489         
1490         /*
1491          * Schedule ourselves for performing the work.  We do things
1492          * differently for changers.
1493          */
1494         if ((softc->flags & CD_FLAG_CHANGER) == 0)
1495                 xpt_schedule(periph, /* XXX priority */1);
1496         else
1497                 cdschedule(periph, /* priority */ 1);
1498
1499         return;
1500 bad:
1501         bp->b_flags |= B_ERROR;
1502         /*
1503          * Correctly set the buf to indicate a completed xfer
1504          */
1505         bp->b_resid = bp->b_bcount;
1506         biodone(bp);
1507         return;
1508 }
1509
1510 static void
1511 cdstart(struct cam_periph *periph, union ccb *start_ccb)
1512 {
1513         struct cd_softc *softc;
1514         struct buf *bp;
1515         struct ccb_scsiio *csio;
1516         struct scsi_read_capacity_data *rcap;
1517
1518         softc = (struct cd_softc *)periph->softc;
1519
1520         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdstart\n"));
1521
1522         switch (softc->state) {
1523         case CD_STATE_NORMAL:
1524         {
1525                 crit_enter();
1526                 bp = bufq_first(&softc->buf_queue);
1527                 if (periph->immediate_priority <= periph->pinfo.priority) {
1528                         start_ccb->ccb_h.ccb_state = CD_CCB_WAITING;
1529
1530                         SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
1531                                           periph_links.sle);
1532                         periph->immediate_priority = CAM_PRIORITY_NONE;
1533                         crit_exit();
1534                         wakeup(&periph->ccb_list);
1535                 } else if (bp == NULL) {
1536                         crit_exit();
1537                         xpt_release_ccb(start_ccb);
1538                 } else {
1539                         bufq_remove(&softc->buf_queue, bp);
1540
1541                         devstat_start_transaction(&softc->device_stats);
1542
1543                         scsi_read_write(&start_ccb->csio,
1544                                         /*retries*/4,
1545                                         /* cbfcnp */ cddone,
1546                                         (bp->b_flags & B_ORDERED) != 0 ?
1547                                             MSG_ORDERED_Q_TAG : 
1548                                             MSG_SIMPLE_Q_TAG,
1549                                         /* read */bp->b_flags & B_READ,
1550                                         /* byte2 */ 0,
1551                                         /* minimum_cmd_size */ 10,
1552                                         /* lba */ bp->b_pblkno,
1553                                         bp->b_bcount / softc->params.blksize,
1554                                         /* data_ptr */ bp->b_data,
1555                                         /* dxfer_len */ bp->b_bcount,
1556                                         /* sense_len */ SSD_FULL_SIZE,
1557                                         /* timeout */ 30000);
1558                         start_ccb->ccb_h.ccb_state = CD_CCB_BUFFER_IO;
1559
1560                         
1561                         /*
1562                          * Block out any asyncronous callbacks
1563                          * while we touch the pending ccb list.
1564                          */
1565                         LIST_INSERT_HEAD(&softc->pending_ccbs,
1566                                          &start_ccb->ccb_h, periph_links.le);
1567
1568                         /* We expect a unit attention from this device */
1569                         if ((softc->flags & CD_FLAG_RETRY_UA) != 0) {
1570                                 start_ccb->ccb_h.ccb_state |= CD_CCB_RETRY_UA;
1571                                 softc->flags &= ~CD_FLAG_RETRY_UA;
1572                         }
1573
1574                         start_ccb->ccb_h.ccb_bp = bp;
1575                         bp = bufq_first(&softc->buf_queue);
1576                         crit_exit();
1577
1578                         xpt_action(start_ccb);
1579                 }
1580                 if (bp != NULL) {
1581                         /* Have more work to do, so ensure we stay scheduled */
1582                         xpt_schedule(periph, /* XXX priority */1);
1583                 }
1584                 break;
1585         }
1586         case CD_STATE_PROBE:
1587         {
1588
1589                 rcap = malloc(sizeof(*rcap), M_TEMP, M_INTWAIT);
1590                 csio = &start_ccb->csio;
1591                 scsi_read_capacity(csio,
1592                                    /*retries*/1,
1593                                    cddone,
1594                                    MSG_SIMPLE_Q_TAG,
1595                                    rcap,
1596                                    SSD_FULL_SIZE,
1597                                    /*timeout*/20000);
1598                 start_ccb->ccb_h.ccb_bp = NULL;
1599                 start_ccb->ccb_h.ccb_state = CD_CCB_PROBE;
1600                 xpt_action(start_ccb);
1601                 break;
1602         }
1603         }
1604 }
1605
1606 static void
1607 cddone(struct cam_periph *periph, union ccb *done_ccb)
1608
1609         struct cd_softc *softc;
1610         struct ccb_scsiio *csio;
1611
1612         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cddone\n"));
1613
1614         softc = (struct cd_softc *)periph->softc;
1615         csio = &done_ccb->csio;
1616
1617         switch (csio->ccb_h.ccb_state & CD_CCB_TYPE_MASK) {
1618         case CD_CCB_BUFFER_IO:
1619         {
1620                 struct buf      *bp;
1621                 int             error;
1622
1623                 bp = (struct buf *)done_ccb->ccb_h.ccb_bp;
1624                 error = 0;
1625
1626                 if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1627                         int sf;
1628
1629                         if ((done_ccb->ccb_h.ccb_state & CD_CCB_RETRY_UA) != 0)
1630                                 sf = SF_RETRY_UA;
1631                         else
1632                                 sf = 0;
1633
1634                         /* Retry selection timeouts */
1635                         sf |= SF_RETRY_SELTO;
1636
1637                         if ((error = cderror(done_ccb, 0, sf)) == ERESTART) {
1638                                 /*
1639                                  * A retry was scheuled, so
1640                                  * just return.
1641                                  */
1642                                 return;
1643                         }
1644                 }
1645
1646                 if (error != 0) {
1647                         struct buf *q_bp;
1648
1649                         xpt_print_path(periph->path);
1650                         printf("cddone: got error %#x back\n", error);
1651                         crit_enter();
1652                         while ((q_bp = bufq_first(&softc->buf_queue)) != NULL) {
1653                                 bufq_remove(&softc->buf_queue, q_bp);
1654                                 q_bp->b_resid = q_bp->b_bcount;
1655                                 q_bp->b_error = EIO;
1656                                 q_bp->b_flags |= B_ERROR;
1657                                 biodone(q_bp);
1658                         }
1659                         crit_exit();
1660                         bp->b_resid = bp->b_bcount;
1661                         bp->b_error = error;
1662                         bp->b_flags |= B_ERROR;
1663                         cam_release_devq(done_ccb->ccb_h.path,
1664                                          /*relsim_flags*/0,
1665                                          /*reduction*/0,
1666                                          /*timeout*/0,
1667                                          /*getcount_only*/0);
1668
1669                 } else {
1670                         bp->b_resid = csio->resid;
1671                         bp->b_error = 0;
1672                         if (bp->b_resid != 0) {
1673                                 /* Short transfer ??? */
1674                                 bp->b_flags |= B_ERROR;
1675                         }
1676                 }
1677
1678                 /*
1679                  * Block out any asyncronous callbacks
1680                  * while we touch the pending ccb list.
1681                  */
1682                 crit_enter();
1683                 LIST_REMOVE(&done_ccb->ccb_h, periph_links.le);
1684                 crit_exit();
1685
1686                 if (softc->flags & CD_FLAG_CHANGER)
1687                         cdchangerschedule(softc);
1688
1689                 devstat_end_transaction_buf(&softc->device_stats, bp);
1690                 biodone(bp);
1691                 break;
1692         }
1693         case CD_CCB_PROBE:
1694         {
1695                 struct     scsi_read_capacity_data *rdcap;
1696                 char       announce_buf[120]; /*
1697                                                * Currently (9/30/97) the 
1698                                                * longest possible announce 
1699                                                * buffer is 108 bytes, for the 
1700                                                * first error case below.  
1701                                                * That is 39 bytes for the 
1702                                                * basic string, 16 bytes for the
1703                                                * biggest sense key (hardware 
1704                                                * error), 52 bytes for the
1705                                                * text of the largest sense 
1706                                                * qualifier valid for a CDROM,
1707                                                * (0x72, 0x03 or 0x04,
1708                                                * 0x03), and one byte for the
1709                                                * null terminating character.
1710                                                * To allow for longer strings, 
1711                                                * the announce buffer is 120
1712                                                * bytes.
1713                                                */
1714                 struct     cd_params *cdp;
1715
1716                 cdp = &softc->params;
1717
1718                 rdcap = (struct scsi_read_capacity_data *)csio->data_ptr;
1719                 
1720                 cdp->disksize = scsi_4btoul (rdcap->addr) + 1;
1721                 cdp->blksize = scsi_4btoul (rdcap->length);
1722
1723                 if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1724
1725                         snprintf(announce_buf, sizeof(announce_buf),
1726                                 "cd present [%lu x %lu byte records]",
1727                                 cdp->disksize, (u_long)cdp->blksize);
1728
1729                 } else {
1730                         int     error;
1731                         /*
1732                          * Retry any UNIT ATTENTION type errors.  They
1733                          * are expected at boot.
1734                          */
1735                         error = cderror(done_ccb, 0, SF_RETRY_UA |
1736                                         SF_NO_PRINT | SF_RETRY_SELTO);
1737                         if (error == ERESTART) {
1738                                 /*
1739                                  * A retry was scheuled, so
1740                                  * just return.
1741                                  */
1742                                 return;
1743                         } else if (error != 0) {
1744
1745                                 struct scsi_sense_data *sense;
1746                                 int asc, ascq;
1747                                 int sense_key, error_code;
1748                                 int have_sense;
1749                                 cam_status status;
1750                                 struct ccb_getdev cgd;
1751
1752                                 /* Don't wedge this device's queue */
1753                                 cam_release_devq(done_ccb->ccb_h.path,
1754                                                  /*relsim_flags*/0,
1755                                                  /*reduction*/0,
1756                                                  /*timeout*/0,
1757                                                  /*getcount_only*/0);
1758
1759                                 status = done_ccb->ccb_h.status;
1760
1761                                 xpt_setup_ccb(&cgd.ccb_h, 
1762                                               done_ccb->ccb_h.path,
1763                                               /* priority */ 1);
1764                                 cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1765                                 xpt_action((union ccb *)&cgd);
1766
1767                                 if (((csio->ccb_h.flags & CAM_SENSE_PHYS) != 0)
1768                                  || ((csio->ccb_h.flags & CAM_SENSE_PTR) != 0)
1769                                  || ((status & CAM_AUTOSNS_VALID) == 0))
1770                                         have_sense = FALSE;
1771                                 else
1772                                         have_sense = TRUE;
1773
1774                                 if (have_sense) {
1775                                         sense = &csio->sense_data;
1776                                         scsi_extract_sense(sense, &error_code,
1777                                                            &sense_key, 
1778                                                            &asc, &ascq);
1779                                 }
1780                                 /*
1781                                  * Attach to anything that claims to be a
1782                                  * CDROM or WORM device, as long as it
1783                                  * doesn't return a "Logical unit not
1784                                  * supported" (0x25) error.
1785                                  */
1786                                 if ((have_sense) && (asc != 0x25)
1787                                  && (error_code == SSD_CURRENT_ERROR))
1788                                         snprintf(announce_buf,
1789                                             sizeof(announce_buf),
1790                                                 "Attempt to query device "
1791                                                 "size failed: %s, %s",
1792                                                 scsi_sense_key_text[sense_key],
1793                                                 scsi_sense_desc(asc,ascq,
1794                                                                 &cgd.inq_data));
1795                                 else if ((have_sense == 0)
1796                                       && ((status & CAM_STATUS_MASK) ==
1797                                            CAM_SCSI_STATUS_ERROR)
1798                                       && (csio->scsi_status ==
1799                                           SCSI_STATUS_BUSY)) {
1800                                         snprintf(announce_buf,
1801                                             sizeof(announce_buf),
1802                                             "Attempt to query device "
1803                                             "size failed: SCSI status: BUSY");
1804                                 } else if (SID_TYPE(&cgd.inq_data) == T_CDROM) {
1805                                         /*
1806                                          * We only print out an error for
1807                                          * CDROM type devices.  For WORM
1808                                          * devices, we don't print out an
1809                                          * error since a few WORM devices
1810                                          * don't support CDROM commands.
1811                                          * If we have sense information, go
1812                                          * ahead and print it out.
1813                                          * Otherwise, just say that we 
1814                                          * couldn't attach.
1815                                          */
1816
1817                                         /*
1818                                          * Just print out the error, not
1819                                          * the full probe message, when we
1820                                          * don't attach.
1821                                          */
1822                                         if (have_sense)
1823                                                 scsi_sense_print(
1824                                                         &done_ccb->csio);
1825                                         else {
1826                                                 xpt_print_path(periph->path);
1827                                                 printf("got CAM status %#x\n",
1828                                                        done_ccb->ccb_h.status);
1829                                         }
1830                                         xpt_print_path(periph->path);
1831                                         printf("fatal error, failed" 
1832                                                " to attach to device\n");
1833
1834                                         /*
1835                                          * Invalidate this peripheral.
1836                                          */
1837                                         cam_periph_invalidate(periph);
1838
1839                                         announce_buf[0] = '\0';
1840                                 } else {
1841
1842                                         /*
1843                                          * Invalidate this peripheral.
1844                                          */
1845                                         cam_periph_invalidate(periph);
1846                                         announce_buf[0] = '\0';
1847                                 }
1848                         }
1849                 }
1850                 free(rdcap, M_TEMP);
1851                 if (announce_buf[0] != '\0') {
1852                         xpt_announce_periph(periph, announce_buf);
1853                         if (softc->flags & CD_FLAG_CHANGER)
1854                                 cdchangerschedule(softc);
1855                         /*
1856                          * Create our sysctl variables, now that we know
1857                          * we have successfully attached.
1858                          */
1859                         taskqueue_enqueue(taskqueue_thread,&softc->sysctl_task);
1860                 }
1861                 softc->state = CD_STATE_NORMAL;         
1862                 /*
1863                  * Since our peripheral may be invalidated by an error
1864                  * above or an external event, we must release our CCB
1865                  * before releasing the probe lock on the peripheral.
1866                  * The peripheral will only go away once the last lock
1867                  * is removed, and we need it around for the CCB release
1868                  * operation.
1869                  */
1870                 xpt_release_ccb(done_ccb);
1871                 cam_periph_unlock(periph);
1872                 return;
1873         }
1874         case CD_CCB_WAITING:
1875         {
1876                 /* Caller will release the CCB */
1877                 CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, 
1878                           ("trying to wakeup ccbwait\n"));
1879
1880                 wakeup(&done_ccb->ccb_h.cbfcnp);
1881                 return;
1882         }
1883         default:
1884                 break;
1885         }
1886         xpt_release_ccb(done_ccb);
1887 }
1888
1889 static union cd_pages *
1890 cdgetpage(struct cd_mode_params *mode_params)
1891 {
1892         union cd_pages *page;
1893
1894         if (mode_params->cdb_size == 10)
1895                 page = (union cd_pages *)find_mode_page_10(
1896                         (struct scsi_mode_header_10 *)mode_params->mode_buf);
1897         else
1898                 page = (union cd_pages *)find_mode_page_6(
1899                         (struct scsi_mode_header_6 *)mode_params->mode_buf);
1900
1901         return (page);
1902 }
1903
1904 static int
1905 cdgetpagesize(int page_num)
1906 {
1907         int i;
1908
1909         for (i = 0; i < (sizeof(cd_page_size_table)/
1910             sizeof(cd_page_size_table[0])); i++) {
1911                 if (cd_page_size_table[i].page == page_num)
1912                         return (cd_page_size_table[i].page_size);
1913         }
1914         return (-1);
1915 }
1916
1917 static int
1918 cdioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
1919 {
1920
1921         struct  cam_periph *periph;
1922         struct  cd_softc *softc;
1923         int     error, unit;
1924
1925         unit = dkunit(dev);
1926
1927         periph = cam_extend_get(cdperiphs, unit);
1928         if (periph == NULL)
1929                 return(ENXIO);  
1930
1931         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdioctl\n"));
1932
1933         softc = (struct cd_softc *)periph->softc;
1934
1935         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, 
1936                   ("trying to do ioctl %#lx\n", cmd));
1937
1938         error = cam_periph_lock(periph, PCATCH);
1939
1940         if (error != 0)
1941                 return(error);
1942
1943         /*
1944          * If we don't have media loaded, check for it.  If still don't
1945          * have media loaded, we can only do a load or eject.
1946          */
1947         if (((softc->flags & CD_FLAG_VALID_MEDIA) == 0)
1948             && ((cmd != CDIOCCLOSE)
1949             && (cmd != CDIOCEJECT))) {
1950                 error = cdcheckmedia(periph);
1951                 if (error != 0) {
1952                         cam_periph_unlock(periph);
1953                         return (error);
1954                 }
1955         }
1956
1957         switch (cmd) {
1958
1959         case CDIOCPLAYTRACKS:
1960                 {
1961                         struct ioc_play_track *args
1962                             = (struct ioc_play_track *) addr;
1963                         struct cd_mode_params params;
1964                         union cd_pages *page;
1965
1966                         params.alloc_len = sizeof(union cd_mode_data_6_10);
1967                         params.mode_buf = malloc(params.alloc_len, M_TEMP,
1968                                                  M_WAITOK | M_ZERO);
1969
1970                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
1971                                   ("trying to do CDIOCPLAYTRACKS\n"));
1972
1973                         error = cdgetmode(periph, &params, AUDIO_PAGE);
1974                         if (error) {
1975                                 free(params.mode_buf, M_TEMP);
1976                                 break;
1977                         }
1978                         page = cdgetpage(&params);
1979
1980                         page->audio.flags &= ~CD_PA_SOTC;
1981                         page->audio.flags |= CD_PA_IMMED;
1982                         error = cdsetmode(periph, &params);
1983                         free(params.mode_buf, M_TEMP);
1984                         if (error)
1985                                 break;
1986
1987                         /*
1988                          * This was originally implemented with the PLAY
1989                          * AUDIO TRACK INDEX command, but that command was
1990                          * deprecated after SCSI-2.  Most (all?) SCSI CDROM
1991                          * drives support it but ATAPI and ATAPI-derivative
1992                          * drives don't seem to support it.  So we keep a
1993                          * cache of the table of contents and translate
1994                          * track numbers to MSF format.
1995                          */
1996                         if (softc->flags & CD_FLAG_VALID_TOC) {
1997                                 union msf_lba *sentry, *eentry;
1998                                 int st, et;
1999
2000                                 if (args->end_track <
2001                                     softc->toc.header.ending_track + 1)
2002                                         args->end_track++;
2003                                 if (args->end_track >
2004                                     softc->toc.header.ending_track + 1)
2005                                         args->end_track =
2006                                             softc->toc.header.ending_track + 1;
2007                                 st = args->start_track -
2008                                         softc->toc.header.starting_track;
2009                                 et = args->end_track -
2010                                         softc->toc.header.starting_track;
2011                                 if ((st < 0)
2012                                  || (et < 0)
2013                                  || (st > (softc->toc.header.ending_track -
2014                                      softc->toc.header.starting_track))) {
2015                                         error = EINVAL;
2016                                         break;
2017                                 }
2018                                 sentry = &softc->toc.entries[st].addr;
2019                                 eentry = &softc->toc.entries[et].addr;
2020                                 error = cdplaymsf(periph,
2021                                                   sentry->msf.minute,
2022                                                   sentry->msf.second,
2023                                                   sentry->msf.frame,
2024                                                   eentry->msf.minute,
2025                                                   eentry->msf.second,
2026                                                   eentry->msf.frame);
2027                         } else {
2028                                 /*
2029                                  * If we don't have a valid TOC, try the
2030                                  * play track index command.  It is part of
2031                                  * the SCSI-2 spec, but was removed in the
2032                                  * MMC specs.  ATAPI and ATAPI-derived
2033                                  * drives don't support it.
2034                                  */
2035                                 if (softc->quirks & CD_Q_BCD_TRACKS) {
2036                                         args->start_track =
2037                                                 bin2bcd(args->start_track);
2038                                         args->end_track =
2039                                                 bin2bcd(args->end_track);
2040                                 }
2041                                 error = cdplaytracks(periph,
2042                                                      args->start_track,
2043                                                      args->start_index,
2044                                                      args->end_track,
2045                                                      args->end_index);
2046                         }
2047                 }
2048                 break;
2049         case CDIOCPLAYMSF:
2050                 {
2051                         struct ioc_play_msf *args
2052                                 = (struct ioc_play_msf *) addr;
2053                         struct cd_mode_params params;
2054                         union cd_pages *page;
2055
2056                         params.alloc_len = sizeof(union cd_mode_data_6_10);
2057                         params.mode_buf = malloc(params.alloc_len, M_TEMP,
2058                                                  M_WAITOK | M_ZERO);
2059
2060                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2061                                   ("trying to do CDIOCPLAYMSF\n"));
2062
2063                         error = cdgetmode(periph, &params, AUDIO_PAGE);
2064                         if (error) {
2065                                 free(params.mode_buf, M_TEMP);
2066                                 break;
2067                         }
2068                         page = cdgetpage(&params);
2069
2070                         page->audio.flags &= ~CD_PA_SOTC;
2071                         page->audio.flags |= CD_PA_IMMED;
2072                         error = cdsetmode(periph, &params);
2073                         free(params.mode_buf, M_TEMP);
2074                         if (error)
2075                                 break;
2076                         error = cdplaymsf(periph,
2077                                           args->start_m,
2078                                           args->start_s,
2079                                           args->start_f,
2080                                           args->end_m,
2081                                           args->end_s,
2082                                           args->end_f);
2083                 }
2084                 break;
2085         case CDIOCPLAYBLOCKS:
2086                 {
2087                         struct ioc_play_blocks *args
2088                                 = (struct ioc_play_blocks *) addr;
2089                         struct cd_mode_params params;
2090                         union cd_pages *page;
2091
2092                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2093                                   ("trying to do CDIOCPLAYBLOCKS\n"));
2094
2095                         params.alloc_len = sizeof(union cd_mode_data_6_10);
2096                         params.mode_buf = malloc(params.alloc_len, M_TEMP,
2097                                                  M_WAITOK | M_ZERO);
2098
2099                         error = cdgetmode(periph, &params, AUDIO_PAGE);
2100                         if (error) {
2101                                 free(params.mode_buf, M_TEMP);
2102                                 break;
2103                         }
2104                         page = cdgetpage(&params);
2105
2106                         page->audio.flags &= ~CD_PA_SOTC;
2107                         page->audio.flags |= CD_PA_IMMED;
2108                         error = cdsetmode(periph, &params);
2109                         free(params.mode_buf, M_TEMP);
2110                         if (error)
2111                                 break;
2112                         error = cdplay(periph, args->blk, args->len);
2113                 }
2114                 break;
2115         case CDIOCREADSUBCHANNEL:
2116                 {
2117                         struct ioc_read_subchannel *args
2118                                 = (struct ioc_read_subchannel *) addr;
2119                         struct cd_sub_channel_info *data;
2120                         u_int32_t len = args->data_len;
2121
2122                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2123                                   ("trying to do CDIOCREADSUBCHANNEL\n"));
2124
2125                         data = malloc(sizeof(struct cd_sub_channel_info), 
2126                                       M_TEMP, M_WAITOK);
2127
2128                         if ((len > sizeof(struct cd_sub_channel_info)) ||
2129                             (len < sizeof(struct cd_sub_channel_header))) {
2130                                 printf(
2131                                         "scsi_cd: cdioctl: "
2132                                         "cdioreadsubchannel: error, len=%d\n",
2133                                         len);
2134                                 error = EINVAL;
2135                                 free(data, M_TEMP);
2136                                 break;
2137                         }
2138
2139                         if (softc->quirks & CD_Q_BCD_TRACKS)
2140                                 args->track = bin2bcd(args->track);
2141
2142                         error = cdreadsubchannel(periph, args->address_format,
2143                                 args->data_format, args->track, data, len);
2144
2145                         if (error) {
2146                                 free(data, M_TEMP);
2147                                 break;
2148                         }
2149                         if (softc->quirks & CD_Q_BCD_TRACKS)
2150                                 data->what.track_info.track_number =
2151                                     bcd2bin(data->what.track_info.track_number);
2152                         len = min(len, ((data->header.data_len[0] << 8) +
2153                                 data->header.data_len[1] +
2154                                 sizeof(struct cd_sub_channel_header)));
2155                         if (copyout(data, args->data, len) != 0) {
2156                                 error = EFAULT;
2157                         }
2158                         free(data, M_TEMP);
2159                 }
2160                 break;
2161
2162         case CDIOREADTOCHEADER:
2163                 {
2164                         struct ioc_toc_header *th;
2165
2166                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2167                                   ("trying to do CDIOREADTOCHEADER\n"));
2168
2169                         th = malloc(sizeof(struct ioc_toc_header), M_TEMP,
2170                                     M_WAITOK);
2171                         error = cdreadtoc(periph, 0, 0, (u_int8_t *)th, 
2172                                           sizeof (*th), /*sense_flags*/0);
2173                         if (error) {
2174                                 free(th, M_TEMP);
2175                                 break;
2176                         }
2177                         if (softc->quirks & CD_Q_BCD_TRACKS) {
2178                                 /* we are going to have to convert the BCD
2179                                  * encoding on the cd to what is expected
2180                                  */
2181                                 th->starting_track = 
2182                                         bcd2bin(th->starting_track);
2183                                 th->ending_track = bcd2bin(th->ending_track);
2184                         }
2185                         th->len = ntohs(th->len);
2186                         bcopy(th, addr, sizeof(*th));
2187                         free(th, M_TEMP);
2188                 }
2189                 break;
2190         case CDIOREADTOCENTRYS:
2191                 {
2192                         struct cd_tocdata *data;
2193                         struct cd_toc_single *lead;
2194                         struct ioc_read_toc_entry *te =
2195                                 (struct ioc_read_toc_entry *) addr;
2196                         struct ioc_toc_header *th;
2197                         u_int32_t len, readlen, idx, num;
2198                         u_int32_t starting_track = te->starting_track;
2199
2200                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2201                                   ("trying to do CDIOREADTOCENTRYS\n"));
2202
2203                         data = malloc(sizeof(*data), M_TEMP, M_WAITOK);
2204                         lead = malloc(sizeof(*lead), M_TEMP, M_WAITOK);
2205
2206                         if (te->data_len < sizeof(struct cd_toc_entry)
2207                          || (te->data_len % sizeof(struct cd_toc_entry)) != 0
2208                          || (te->address_format != CD_MSF_FORMAT
2209                           && te->address_format != CD_LBA_FORMAT)) {
2210                                 error = EINVAL;
2211                                 printf("scsi_cd: error in readtocentries, "
2212                                        "returning EINVAL\n");
2213                                 free(data, M_TEMP);
2214                                 free(lead, M_TEMP);
2215                                 break;
2216                         }
2217
2218                         th = &data->header;
2219                         error = cdreadtoc(periph, 0, 0, (u_int8_t *)th, 
2220                                           sizeof (*th), /*sense_flags*/0);
2221                         if (error) {
2222                                 free(data, M_TEMP);
2223                                 free(lead, M_TEMP);
2224                                 break;
2225                         }
2226
2227                         if (softc->quirks & CD_Q_BCD_TRACKS) {
2228                                 /* we are going to have to convert the BCD
2229                                  * encoding on the cd to what is expected
2230                                  */
2231                                 th->starting_track =
2232                                     bcd2bin(th->starting_track);
2233                                 th->ending_track = bcd2bin(th->ending_track);
2234                         }
2235
2236                         if (starting_track == 0)
2237                                 starting_track = th->starting_track;
2238                         else if (starting_track == LEADOUT)
2239                                 starting_track = th->ending_track + 1;
2240                         else if (starting_track < th->starting_track ||
2241                                  starting_track > th->ending_track + 1) {
2242                                 printf("scsi_cd: error in readtocentries, "
2243                                        "returning EINVAL\n");
2244                                 free(data, M_TEMP);
2245                                 free(lead, M_TEMP);
2246                                 error = EINVAL;
2247                                 break;
2248                         }
2249
2250                         /* calculate reading length without leadout entry */
2251                         readlen = (th->ending_track - starting_track + 1) *
2252                                   sizeof(struct cd_toc_entry);
2253
2254                         /* and with leadout entry */
2255                         len = readlen + sizeof(struct cd_toc_entry);
2256                         if (te->data_len < len) {
2257                                 len = te->data_len;
2258                                 if (readlen > len)
2259                                         readlen = len;
2260                         }
2261                         if (len > sizeof(data->entries)) {
2262                                 printf("scsi_cd: error in readtocentries, "
2263                                        "returning EINVAL\n");
2264                                 error = EINVAL;
2265                                 free(data, M_TEMP);
2266                                 free(lead, M_TEMP);
2267                                 break;
2268                         }
2269                         num = len / sizeof(struct cd_toc_entry);
2270
2271                         if (readlen > 0) {
2272                                 error = cdreadtoc(periph, te->address_format,
2273                                                   starting_track,
2274                                                   (u_int8_t *)data,
2275                                                   readlen + sizeof (*th),
2276                                                   /*sense_flags*/0);
2277                                 if (error) {
2278                                         free(data, M_TEMP);
2279                                         free(lead, M_TEMP);
2280                                         break;
2281                                 }
2282                         }
2283
2284                         /* make leadout entry if needed */
2285                         idx = starting_track + num - 1;
2286                         if (softc->quirks & CD_Q_BCD_TRACKS)
2287                                 th->ending_track = bcd2bin(th->ending_track);
2288                         if (idx == th->ending_track + 1) {
2289                                 error = cdreadtoc(periph, te->address_format,
2290                                                   LEADOUT, (u_int8_t *)lead,
2291                                                   sizeof(*lead),
2292                                                   /*sense_flags*/0);
2293                                 if (error) {
2294                                         free(data, M_TEMP);
2295                                         free(lead, M_TEMP);
2296                                         break;
2297                                 }
2298                                 data->entries[idx - starting_track] = 
2299                                         lead->entry;
2300                         }
2301                         if (softc->quirks & CD_Q_BCD_TRACKS) {
2302                                 for (idx = 0; idx < num - 1; idx++) {
2303                                         data->entries[idx].track =
2304                                             bcd2bin(data->entries[idx].track);
2305                                 }
2306                         }
2307
2308                         error = copyout(data->entries, te->data, len);
2309                         free(data, M_TEMP);
2310                         free(lead, M_TEMP);
2311                 }
2312                 break;
2313         case CDIOREADTOCENTRY:
2314                 {
2315                         struct cd_toc_single *data;
2316                         struct ioc_read_toc_single_entry *te =
2317                                 (struct ioc_read_toc_single_entry *) addr;
2318                         struct ioc_toc_header *th;
2319                         u_int32_t track;
2320
2321                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2322                                   ("trying to do CDIOREADTOCENTRY\n"));
2323
2324                         data = malloc(sizeof(*data), M_TEMP, M_WAITOK);
2325
2326                         if (te->address_format != CD_MSF_FORMAT
2327                             && te->address_format != CD_LBA_FORMAT) {
2328                                 printf("error in readtocentry, "
2329                                        " returning EINVAL\n");
2330                                 free(data, M_TEMP);
2331                                 error = EINVAL;
2332                                 break;
2333                         }
2334
2335                         th = &data->header;
2336                         error = cdreadtoc(periph, 0, 0, (u_int8_t *)th,
2337                                           sizeof (*th), /*sense_flags*/0);
2338                         if (error) {
2339                                 free(data, M_TEMP);
2340                                 break;
2341                         }
2342
2343                         if (softc->quirks & CD_Q_BCD_TRACKS) {
2344                                 /* we are going to have to convert the BCD
2345                                  * encoding on the cd to what is expected
2346                                  */
2347                                 th->starting_track =
2348                                     bcd2bin(th->starting_track);
2349                                 th->ending_track = bcd2bin(th->ending_track);
2350                         }
2351                         track = te->track;
2352                         if (track == 0)
2353                                 track = th->starting_track;
2354                         else if (track == LEADOUT)
2355                                 /* OK */;
2356                         else if (track < th->starting_track ||
2357                                  track > th->ending_track + 1) {
2358                                 printf("error in readtocentry, "
2359                                        " returning EINVAL\n");
2360                                 free(data, M_TEMP);
2361                                 error = EINVAL;
2362                                 break;
2363                         }
2364
2365                         error = cdreadtoc(periph, te->address_format, track,
2366                                           (u_int8_t *)data, sizeof(*data),
2367                                           /*sense_flags*/0);
2368                         if (error) {
2369                                 free(data, M_TEMP);
2370                                 break;
2371                         }
2372
2373                         if (softc->quirks & CD_Q_BCD_TRACKS)
2374                                 data->entry.track = bcd2bin(data->entry.track);
2375                         bcopy(&data->entry, &te->entry,
2376                               sizeof(struct cd_toc_entry));
2377                         free(data, M_TEMP);
2378                 }
2379                 break;
2380         case CDIOCSETPATCH:
2381                 {
2382                         struct ioc_patch *arg = (struct ioc_patch *)addr;
2383                         struct cd_mode_params params;
2384                         union cd_pages *page;
2385
2386                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2387                                   ("trying to do CDIOCSETPATCH\n"));
2388
2389                         params.alloc_len = sizeof(union cd_mode_data_6_10);
2390                         params.mode_buf = malloc(params.alloc_len, M_TEMP, 
2391                                                  M_WAITOK | M_ZERO);
2392                         error = cdgetmode(periph, &params, AUDIO_PAGE);
2393                         if (error) {
2394                                 free(params.mode_buf, M_TEMP);
2395                                 break;
2396                         }
2397                         page = cdgetpage(&params);
2398
2399                         page->audio.port[LEFT_PORT].channels = 
2400                                 arg->patch[0];
2401                         page->audio.port[RIGHT_PORT].channels = 
2402                                 arg->patch[1];
2403                         page->audio.port[2].channels = arg->patch[2];
2404                         page->audio.port[3].channels = arg->patch[3];
2405                         error = cdsetmode(periph, &params);
2406                         free(params.mode_buf, M_TEMP);
2407                 }
2408                 break;
2409         case CDIOCGETVOL:
2410                 {
2411                         struct ioc_vol *arg = (struct ioc_vol *) addr;
2412                         struct cd_mode_params params;
2413                         union cd_pages *page;
2414
2415                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2416                                   ("trying to do CDIOCGETVOL\n"));
2417
2418                         params.alloc_len = sizeof(union cd_mode_data_6_10);
2419                         params.mode_buf = malloc(params.alloc_len, M_TEMP, 
2420                                                  M_WAITOK | M_ZERO);
2421                         error = cdgetmode(periph, &params, AUDIO_PAGE);
2422                         if (error) {
2423                                 free(params.mode_buf, M_TEMP);
2424                                 break;
2425                         }
2426                         page = cdgetpage(&params);
2427
2428                         arg->vol[LEFT_PORT] = 
2429                                 page->audio.port[LEFT_PORT].volume;
2430                         arg->vol[RIGHT_PORT] = 
2431                                 page->audio.port[RIGHT_PORT].volume;
2432                         arg->vol[2] = page->audio.port[2].volume;
2433                         arg->vol[3] = page->audio.port[3].volume;
2434                         free(params.mode_buf, M_TEMP);
2435                 }
2436                 break;
2437         case CDIOCSETVOL:
2438                 {
2439                         struct ioc_vol *arg = (struct ioc_vol *) addr;
2440                         struct cd_mode_params params;
2441                         union cd_pages *page;
2442
2443                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2444                                   ("trying to do CDIOCSETVOL\n"));
2445
2446                         params.alloc_len = sizeof(union cd_mode_data_6_10);
2447                         params.mode_buf = malloc(params.alloc_len, M_TEMP, 
2448                                                  M_WAITOK | M_ZERO);
2449                         error = cdgetmode(periph, &params, AUDIO_PAGE);
2450                         if (error) {
2451                                 free(params.mode_buf, M_TEMP);
2452                                 break;
2453                         }
2454                         page = cdgetpage(&params);
2455
2456                         page->audio.port[LEFT_PORT].channels = CHANNEL_0;
2457                         page->audio.port[LEFT_PORT].volume = 
2458                                 arg->vol[LEFT_PORT];
2459                         page->audio.port[RIGHT_PORT].channels = CHANNEL_1;
2460                         page->audio.port[RIGHT_PORT].volume = 
2461                                 arg->vol[RIGHT_PORT];
2462                         page->audio.port[2].volume = arg->vol[2];
2463                         page->audio.port[3].volume = arg->vol[3];
2464                         error = cdsetmode(periph, &params);
2465                         free(params.mode_buf, M_TEMP);
2466                 }
2467                 break;
2468         case CDIOCSETMONO:
2469                 {
2470                         struct cd_mode_params params;
2471                         union cd_pages *page;
2472
2473                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2474                                   ("trying to do CDIOCSETMONO\n"));
2475
2476                         params.alloc_len = sizeof(union cd_mode_data_6_10);
2477                         params.mode_buf = malloc(params.alloc_len, M_TEMP,
2478                                                  M_WAITOK | M_ZERO);
2479                         error = cdgetmode(periph, &params, AUDIO_PAGE);
2480                         if (error) {
2481                                 free(params.mode_buf, M_TEMP);
2482                                 break;
2483                         }
2484                         page = cdgetpage(&params);
2485
2486                         page->audio.port[LEFT_PORT].channels = 
2487                                 LEFT_CHANNEL | RIGHT_CHANNEL;
2488                         page->audio.port[RIGHT_PORT].channels = 
2489                                 LEFT_CHANNEL | RIGHT_CHANNEL;
2490                         page->audio.port[2].channels = 0;
2491                         page->audio.port[3].channels = 0;
2492                         error = cdsetmode(periph, &params);
2493                         free(params.mode_buf, M_TEMP);
2494                 }
2495                 break;
2496         case CDIOCSETSTEREO:
2497                 {
2498                         struct cd_mode_params params;
2499                         union cd_pages *page;
2500
2501                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2502                                   ("trying to do CDIOCSETSTEREO\n"));
2503
2504                         params.alloc_len = sizeof(union cd_mode_data_6_10);
2505                         params.mode_buf = malloc(params.alloc_len, M_TEMP,
2506                                                  M_WAITOK | M_ZERO);
2507                         error = cdgetmode(periph, &params, AUDIO_PAGE);
2508                         if (error) {
2509                                 free(params.mode_buf, M_TEMP);
2510                                 break;
2511                         }
2512                         page = cdgetpage(&params);
2513
2514                         page->audio.port[LEFT_PORT].channels = 
2515                                 LEFT_CHANNEL;
2516                         page->audio.port[RIGHT_PORT].channels = 
2517                                 RIGHT_CHANNEL;
2518                         page->audio.port[2].channels = 0;
2519                         page->audio.port[3].channels = 0;
2520                         error = cdsetmode(periph, &params);
2521                         free(params.mode_buf, M_TEMP);
2522                 }
2523                 break;
2524         case CDIOCSETMUTE:
2525                 {
2526                         struct cd_mode_params params;
2527                         union cd_pages *page;
2528
2529                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2530                                   ("trying to do CDIOCSETMUTE\n"));
2531
2532                         params.alloc_len = sizeof(union cd_mode_data_6_10);
2533                         params.mode_buf = malloc(params.alloc_len, M_TEMP,
2534                                                  M_WAITOK | M_ZERO);
2535                         error = cdgetmode(periph, &params, AUDIO_PAGE);
2536                         if (error) {
2537                                 free(&params, M_TEMP);
2538                                 break;
2539                         }
2540                         page = cdgetpage(&params);
2541
2542                         page->audio.port[LEFT_PORT].channels = 0;
2543                         page->audio.port[RIGHT_PORT].channels = 0;
2544                         page->audio.port[2].channels = 0;
2545                         page->audio.port[3].channels = 0;
2546                         error = cdsetmode(periph, &params);
2547                         free(params.mode_buf, M_TEMP);
2548                 }
2549                 break;
2550         case CDIOCSETLEFT:
2551                 {
2552                         struct cd_mode_params params;
2553                         union cd_pages *page;
2554
2555                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2556                                   ("trying to do CDIOCSETLEFT\n"));
2557
2558                         params.alloc_len = sizeof(union cd_mode_data_6_10);
2559                         params.mode_buf = malloc(params.alloc_len, M_TEMP,
2560                                                  M_WAITOK | M_ZERO);
2561                         
2562                         error = cdgetmode(periph, &params, AUDIO_PAGE);
2563                         if (error) {
2564                                 free(params.mode_buf, M_TEMP);
2565                                 break;
2566                         }
2567                         page = cdgetpage(&params);
2568
2569                         page->audio.port[LEFT_PORT].channels = LEFT_CHANNEL;
2570                         page->audio.port[RIGHT_PORT].channels = LEFT_CHANNEL;
2571                         page->audio.port[2].channels = 0;
2572                         page->audio.port[3].channels = 0;
2573                         error = cdsetmode(periph, &params);
2574                         free(params.mode_buf, M_TEMP);
2575                 }
2576                 break;
2577         case CDIOCSETRIGHT:
2578                 {
2579                         struct cd_mode_params params;
2580                         union cd_pages *page;
2581
2582                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2583                                   ("trying to do CDIOCSETRIGHT\n"));
2584
2585                         params.alloc_len = sizeof(union cd_mode_data_6_10);
2586                         params.mode_buf = malloc(params.alloc_len, M_TEMP,
2587                                                  M_WAITOK | M_ZERO);
2588
2589                         error = cdgetmode(periph, &params, AUDIO_PAGE);
2590                         if (error) {
2591                                 free(params.mode_buf, M_TEMP);
2592                                 break;
2593                         }
2594                         page = cdgetpage(&params);
2595
2596                         page->audio.port[LEFT_PORT].channels = RIGHT_CHANNEL;
2597                         page->audio.port[RIGHT_PORT].channels = RIGHT_CHANNEL;
2598                         page->audio.port[2].channels = 0;
2599                         page->audio.port[3].channels = 0;
2600                         error = cdsetmode(periph, &params);
2601                         free(params.mode_buf, M_TEMP);
2602                 }
2603                 break;
2604         case CDIOCRESUME:
2605                 error = cdpause(periph, 1);
2606                 break;
2607         case CDIOCPAUSE:
2608                 error = cdpause(periph, 0);
2609                 break;
2610         case CDIOCSTART:
2611                 error = cdstartunit(periph, 0);
2612                 break;
2613         case CDIOCCLOSE:
2614                 error = cdstartunit(periph, 1);
2615
2616 #ifdef notyet
2617                 if (error != 0)
2618                         break;
2619
2620                 /*
2621                  * The user successfully closed the tray, run
2622                  * cdcheckmedia() again so we can re-sync the disklabel
2623                  * information.
2624                  */
2625                 cdcheckmedia(periph);
2626 #endif /* notyet */
2627                 break;
2628         case CDIOCSTOP:
2629                 error = cdstopunit(periph, 0);
2630                 break;
2631         case CDIOCEJECT:
2632                 error = cdstopunit(periph, 1);
2633
2634 #ifdef notyet
2635                 if (error != 0)
2636                         break;
2637
2638                 /*
2639                  * Since we've successfully ejected the media, run
2640                  * cdcheckmedia() again so we re-sync the disklabel
2641                  * information.
2642                  */
2643                 cdcheckmedia(periph);
2644 #endif /* notyet */
2645                 break;
2646         case CDIOCALLOW:
2647                 cdprevent(periph, PR_ALLOW);
2648                 break;
2649         case CDIOCPREVENT:
2650                 cdprevent(periph, PR_PREVENT);
2651                 break;
2652         case CDIOCSETDEBUG:
2653                 /* sc_link->flags |= (SDEV_DB1 | SDEV_DB2); */
2654                 error = ENOTTY;
2655                 break;
2656         case CDIOCCLRDEBUG:
2657                 /* sc_link->flags &= ~(SDEV_DB1 | SDEV_DB2); */
2658                 error = ENOTTY;
2659                 break;
2660         case CDIOCRESET:
2661                 /* return (cd_reset(periph)); */
2662                 error = ENOTTY;
2663                 break;
2664         case CDRIOCREADSPEED:
2665                 error = cdsetspeed(periph, *(u_int32_t *)addr, CDR_MAX_SPEED);
2666                 break;
2667         case CDRIOCWRITESPEED:
2668                 error = cdsetspeed(periph, CDR_MAX_SPEED, *(u_int32_t *)addr);
2669                 break;
2670         case DVDIOCSENDKEY:
2671         case DVDIOCREPORTKEY: {
2672                 struct dvd_authinfo *authinfo;
2673
2674                 authinfo = (struct dvd_authinfo *)addr;
2675
2676                 if (cmd == DVDIOCREPORTKEY)
2677                         error = cdreportkey(periph, authinfo);
2678                 else
2679                         error = cdsendkey(periph, authinfo);
2680                 break;
2681         }
2682         case DVDIOCREADSTRUCTURE: {
2683                 struct dvd_struct *dvdstruct;
2684
2685                 dvdstruct = (struct dvd_struct *)addr;
2686
2687                 error = cdreaddvdstructure(periph, dvdstruct);
2688
2689                 break;
2690         }
2691         default:
2692                 error = cam_periph_ioctl(periph, cmd, addr, cderror);
2693                 break;
2694         }
2695
2696         cam_periph_unlock(periph);
2697
2698         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("leaving cdioctl\n"));
2699
2700         return (error);
2701 }
2702
2703 static void
2704 cdprevent(struct cam_periph *periph, int action)
2705 {
2706         union   ccb *ccb;
2707         struct  cd_softc *softc;
2708         int     error;
2709
2710         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdprevent\n"));
2711
2712         softc = (struct cd_softc *)periph->softc;
2713         
2714         if (((action == PR_ALLOW)
2715           && (softc->flags & CD_FLAG_DISC_LOCKED) == 0)
2716          || ((action == PR_PREVENT)
2717           && (softc->flags & CD_FLAG_DISC_LOCKED) != 0)) {
2718                 return;
2719         }
2720             
2721         ccb = cdgetccb(periph, /* priority */ 1);
2722
2723         scsi_prevent(&ccb->csio, 
2724                      /*retries*/ 1,
2725                      cddone,
2726                      MSG_SIMPLE_Q_TAG,
2727                      action,
2728                      SSD_FULL_SIZE,
2729                      /* timeout */60000);
2730         
2731         error = cdrunccb(ccb, cderror, /*cam_flags*/0,
2732                         /*sense_flags*/SF_RETRY_UA|SF_NO_PRINT|SF_RETRY_SELTO);
2733
2734         xpt_release_ccb(ccb);
2735
2736         if (error == 0) {
2737                 if (action == PR_ALLOW)
2738                         softc->flags &= ~CD_FLAG_DISC_LOCKED;
2739                 else
2740                         softc->flags |= CD_FLAG_DISC_LOCKED;
2741         }
2742 }
2743
2744 int
2745 cdcheckmedia(struct cam_periph *periph)
2746 {
2747         struct cd_softc *softc;
2748         struct ioc_toc_header *toch;
2749         struct cd_toc_single leadout;
2750         struct ccb_getdev cgd;
2751         u_int32_t size, toclen;
2752         int error, num_entries, cdindex;
2753         int first_track_audio;
2754         struct disklabel *label;
2755
2756         softc = (struct cd_softc *)periph->softc;
2757
2758         first_track_audio = -1;
2759         error = 0;
2760
2761         cdprevent(periph, PR_PREVENT);
2762
2763         /*
2764          * Build prototype label for whole disk.
2765          * Should take information about different data tracks from the
2766          * TOC and put it in the partition table.
2767          */
2768         label = &softc->disk.d_label;
2769         bzero(label, sizeof(*label));
2770         label->d_type = DTYPE_SCSI;
2771
2772         /*
2773          * Grab the inquiry data to get the vendor and product names.
2774          * Put them in the typename and packname for the label.
2775          */
2776         xpt_setup_ccb(&cgd.ccb_h, periph->path, /*priority*/ 1);
2777         cgd.ccb_h.func_code = XPT_GDEV_TYPE;
2778         xpt_action((union ccb *)&cgd);
2779
2780         strncpy(label->d_typename, cgd.inq_data.vendor,
2781                 min(SID_VENDOR_SIZE, sizeof(label->d_typename)));
2782         strncpy(label->d_packname, cgd.inq_data.product,
2783                 min(SID_PRODUCT_SIZE, sizeof(label->d_packname)));
2784                 
2785         label->d_flags = D_REMOVABLE;
2786         /*
2787          * Make partition 'a' cover the whole disk.  This is a temporary
2788          * compatibility hack.  The 'a' partition should not exist, so
2789          * the slice code won't create it.  The slice code will make
2790          * partition (RAW_PART + 'a') cover the whole disk and fill in
2791          * some more defaults.
2792          */
2793         label->d_partitions[0].p_size = label->d_secperunit;
2794         label->d_partitions[0].p_fstype = FS_OTHER;
2795
2796         /*
2797          * Default to not reading the disklabel off the disk, until we can
2798          * verify that we have media, that we have a table of contents, and
2799          * that the first track is a data track (which could theoretically
2800          * contain a disklabel).
2801          */
2802         softc->disk.d_dsflags &= ~DSO_COMPATLABEL;
2803         softc->disk.d_dsflags |= DSO_NOLABELS;
2804
2805         /*
2806          * Clear the valid media and TOC flags until we've verified that we
2807          * have both.
2808          */
2809         softc->flags &= ~(CD_FLAG_VALID_MEDIA|CD_FLAG_VALID_TOC);
2810
2811         /*
2812          * Get the disc size and block size.  If we can't get it, we don't
2813          * have media, most likely.
2814          */
2815         if ((error = cdsize(periph, &size)) != 0) {
2816                 /*
2817                  * Set a bogus sector size, so the slice code won't try to
2818                  * divide by 0 and panic the kernel.
2819                  */
2820                 label->d_secsize = 2048;
2821
2822                 label->d_secperunit = 0;
2823
2824                 /*
2825                  * XXX KDM is this a good idea?  Seems to cause more
2826                  * problems.
2827                  */
2828                 if (softc->flags & CD_FLAG_OPEN) {
2829                         int force;
2830
2831                         force = 1;
2832
2833                         /*
2834                          * We don't bother checking the return value here,
2835                          * since we already have an error...
2836                          */
2837                         dsioctl(softc->disk.d_cdev, DIOCSYNCSLICEINFO,
2838                                 /*data*/(caddr_t)&force, /*flags*/ 0,
2839                                 &softc->disk.d_slice);
2840                 }
2841
2842                 /*
2843                  * Tell devstat(9) we don't have a blocksize.
2844                  */
2845                 softc->device_stats.flags |= DEVSTAT_BS_UNAVAILABLE;
2846
2847                 cdprevent(periph, PR_ALLOW);
2848
2849                 return (error);
2850         } else {
2851
2852                 label->d_secsize = softc->params.blksize;
2853                 label->d_secperunit = softc->params.disksize;
2854
2855                 /*
2856                  * Force a re-sync of slice information, like the blocksize,
2857                  * now that we know it.  It isn't pretty...but according to
2858                  * Bruce Evans, this is probably the best way to do it in
2859                  * -stable.  We only do this if we're already open, and
2860                  * therefore dsopen() has already run.  If CD_FLAG_OPEN
2861                  * isn't set, this isn't necessary.
2862                  */
2863                 if (softc->flags & CD_FLAG_OPEN) {
2864                         int force;
2865
2866                         force = 1;
2867
2868                         error = dsioctl(softc->disk.d_cdev, DIOCSYNCSLICEINFO,
2869                                         /*data*/(caddr_t)&force, /*flags*/ 0,
2870                                         &softc->disk.d_slice);
2871                         if (error != 0) {
2872                                 /*
2873                                  * Set a bogus sector size, so the slice code
2874                                  * won't try to divide by 0 and panic the
2875                                  * kernel.
2876                                  */
2877                                 label->d_secsize = 2048;
2878
2879                                 label->d_secperunit = 0;
2880
2881                                 /*
2882                                  * Tell devstat(9) we don't have a blocksize.
2883                                  */
2884                                 softc->device_stats.flags |=
2885                                         DEVSTAT_BS_UNAVAILABLE;
2886
2887                                 cdprevent(periph, PR_ALLOW);
2888                         }
2889                 }
2890
2891                 /*
2892                  * We unconditionally (re)set the blocksize each time the
2893                  * CD device is opened.  This is because the CD can change,
2894                  * and therefore the blocksize might change.
2895                  * XXX problems here if some slice or partition is still
2896                  * open with the old size?
2897                  */
2898                 if ((softc->device_stats.flags & DEVSTAT_BS_UNAVAILABLE) != 0)
2899                         softc->device_stats.flags &= ~DEVSTAT_BS_UNAVAILABLE;
2900                 softc->device_stats.block_size = softc->params.blksize;
2901
2902                 softc->flags |= CD_FLAG_VALID_MEDIA;
2903         }
2904
2905         /*
2906          * Now we check the table of contents.  This (currently) is only
2907          * used for the CDIOCPLAYTRACKS ioctl.  It may be used later to do
2908          * things like present a separate entry in /dev for each track,
2909          * like that acd(4) driver does.
2910          */
2911         bzero(&softc->toc, sizeof(softc->toc));
2912         toch = &softc->toc.header;
2913
2914         /*
2915          * We will get errors here for media that doesn't have a table of
2916          * contents.  According to the MMC-3 spec: "When a Read TOC/PMA/ATIP
2917          * command is presented for a DDCD/CD-R/RW media, where the first TOC
2918          * has not been recorded (no complete session) and the Format codes
2919          * 0000b, 0001b, or 0010b are specified, this command shall be rejected
2920          * with an INVALID FIELD IN CDB.  Devices that are not capable of
2921          * reading an incomplete session on DDC/CD-R/RW media shall report
2922          * CANNOT READ MEDIUM - INCOMPATIBLE FORMAT."
2923          *
2924          * So this isn't fatal if we can't read the table of contents, it
2925          * just means that the user won't be able to issue the play tracks
2926          * ioctl, and likely lots of other stuff won't work either.  They
2927          * need to burn the CD before we can do a whole lot with it.  So
2928          * we don't print anything here if we get an error back.
2929          */
2930         error = cdreadtoc(periph, 0, 0, (u_int8_t *)toch, sizeof(*toch),
2931                           SF_NO_PRINT);
2932         /*
2933          * Errors in reading the table of contents aren't fatal, we just
2934          * won't have a valid table of contents cached.
2935          */
2936         if (error != 0) {
2937                 error = 0;
2938                 bzero(&softc->toc, sizeof(softc->toc));
2939                 goto bailout;
2940         }
2941
2942         if (softc->quirks & CD_Q_BCD_TRACKS) {
2943                 toch->starting_track = bcd2bin(toch->starting_track);
2944                 toch->ending_track = bcd2bin(toch->ending_track);
2945         }
2946
2947         /* Number of TOC entries, plus leadout */
2948         num_entries = (toch->ending_track - toch->starting_track) + 2;
2949
2950         if (num_entries <= 0)
2951                 goto bailout;
2952
2953         toclen = num_entries * sizeof(struct cd_toc_entry);
2954
2955         error = cdreadtoc(periph, CD_MSF_FORMAT, toch->starting_track,
2956                           (u_int8_t *)&softc->toc, toclen + sizeof(*toch),
2957                           SF_NO_PRINT);
2958         if (error != 0) {
2959                 error = 0;
2960                 bzero(&softc->toc, sizeof(softc->toc));
2961                 goto bailout;
2962         }
2963
2964         if (softc->quirks & CD_Q_BCD_TRACKS) {
2965                 toch->starting_track = bcd2bin(toch->starting_track);
2966                 toch->ending_track = bcd2bin(toch->ending_track);
2967         }
2968         toch->len = scsi_2btoul((uint8_t *)&toch->len);
2969
2970         /*
2971          * XXX KDM is this necessary?  Probably only if the drive doesn't
2972          * return leadout information with the table of contents.
2973          */
2974         cdindex = toch->starting_track + num_entries -1;
2975         if (cdindex == toch->ending_track + 1) {
2976
2977                 error = cdreadtoc(periph, CD_MSF_FORMAT, LEADOUT, 
2978                                   (u_int8_t *)&leadout, sizeof(leadout),
2979                                   SF_NO_PRINT);
2980                 if (error != 0) {
2981                         error = 0;
2982                         goto bailout;
2983                 }
2984                 softc->toc.entries[cdindex - toch->starting_track] =
2985                         leadout.entry;
2986         }
2987         if (softc->quirks & CD_Q_BCD_TRACKS) {
2988                 for (cdindex = 0; cdindex < (num_entries - 1); cdindex++) {
2989                         softc->toc.entries[cdindex].track =
2990                                 bcd2bin(softc->toc.entries[cdindex].track);
2991                 }
2992         }
2993
2994         /*
2995          * Run through the TOC entries, find the first entry and determine
2996          * whether it is an audio or data track.
2997          */
2998         for (cdindex = 0; cdindex < (num_entries - 1); cdindex++) {
2999                 if (softc->toc.entries[cdindex].track == toch->starting_track) {
3000                         if (softc->toc.entries[cdindex].control & 0x04)
3001                                 first_track_audio = 0;
3002                         else
3003                                 first_track_audio = 1;
3004                         break;
3005                 }
3006         }
3007
3008         /*
3009          * If first_track_audio is non-zero, we either have an error (e.g.
3010          * couldn't find the starting track) or the first track is an audio
3011          * track.  If first_track_audio is 0, the first track is a data
3012          * track that could have a disklabel.  Attempt to read the
3013          * disklabel off the media, just in case the user put one there.
3014          */
3015         if (first_track_audio == 0) {
3016                 softc->disk.d_dsflags |= DSO_COMPATLABEL;
3017                 softc->disk.d_dsflags &= ~DSO_NOLABELS;
3018         }
3019         softc->flags |= CD_FLAG_VALID_TOC;
3020
3021 bailout:
3022         return (error);
3023 }
3024
3025 static int
3026 cdsize(struct cam_periph *periph, u_int32_t *size)
3027 {
3028         struct cd_softc *softc;
3029         union ccb *ccb;
3030         struct scsi_read_capacity_data *rcap_buf;
3031         int error;
3032
3033         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdsize\n"));
3034
3035         softc = (struct cd_softc *)periph->softc;
3036              
3037         ccb = cdgetccb(periph, /* priority */ 1);
3038
3039         rcap_buf = malloc(sizeof(struct scsi_read_capacity_data), 
3040                           M_TEMP, M_INTWAIT | M_ZERO);
3041
3042         scsi_read_capacity(&ccb->csio, 
3043                            /*retries*/ 1,
3044                            cddone,
3045                            MSG_SIMPLE_Q_TAG,
3046                            rcap_buf,
3047                            SSD_FULL_SIZE,
3048                            /* timeout */20000);
3049
3050         error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3051                          /*sense_flags*/SF_RETRY_UA|SF_NO_PRINT|SF_RETRY_SELTO);
3052
3053         xpt_release_ccb(ccb);
3054
3055         softc->params.disksize = scsi_4btoul(rcap_buf->addr) + 1;
3056         softc->params.blksize  = scsi_4btoul(rcap_buf->length);
3057         /*
3058          * SCSI-3 mandates that the reported blocksize shall be 2048.
3059          * Older drives sometimes report funny values, trim it down to
3060          * 2048, or other parts of the kernel will get confused.
3061          *
3062          * XXX we leave drives alone that might report 512 bytes, as
3063          * well as drives reporting more weird sizes like perhaps 4K.
3064          */
3065         if (softc->params.blksize > 2048 && softc->params.blksize <= 2352)
3066                 softc->params.blksize = 2048;
3067
3068         free(rcap_buf, M_TEMP);
3069         *size = softc->params.disksize;
3070
3071         return (error);
3072
3073 }
3074
3075 static int
3076 cd6byteworkaround(union ccb *ccb)
3077 {
3078         u_int8_t *cdb;
3079         struct cam_periph *periph;
3080         struct cd_softc *softc;
3081         struct cd_mode_params *params;
3082         int frozen, found;
3083
3084         periph = xpt_path_periph(ccb->ccb_h.path);
3085         softc = (struct cd_softc *)periph->softc;
3086
3087         cdb = ccb->csio.cdb_io.cdb_bytes;
3088
3089         if ((ccb->ccb_h.flags & CAM_CDB_POINTER)
3090          || ((cdb[0] != MODE_SENSE_6)
3091           && (cdb[0] != MODE_SELECT_6)))
3092                 return (0);
3093
3094         /*
3095          * Because there is no convenient place to stash the overall
3096          * cd_mode_params structure pointer, we have to grab it like this.
3097          * This means that ALL MODE_SENSE and MODE_SELECT requests in the
3098          * cd(4) driver MUST go through cdgetmode() and cdsetmode()!
3099          *
3100          * XXX It would be nice if, at some point, we could increase the
3101          * number of available peripheral private pointers.  Both pointers
3102          * are currently used in most every peripheral driver.
3103          */
3104         found = 0;
3105
3106         STAILQ_FOREACH(params, &softc->mode_queue, links) {
3107                 if (params->mode_buf == ccb->csio.data_ptr) {
3108                         found = 1;
3109                         break;
3110                 }
3111         }
3112
3113         /*
3114          * This shouldn't happen.  All mode sense and mode select
3115          * operations in the cd(4) driver MUST go through cdgetmode() and
3116          * cdsetmode()!
3117          */
3118         if (found == 0) {
3119                 xpt_print_path(periph->path);
3120                 printf("mode buffer not found in mode queue!\n");
3121                 return (0);
3122         }
3123
3124         params->cdb_size = 10;
3125         softc->minimum_command_size = 10;
3126         xpt_print_path(ccb->ccb_h.path);
3127         printf("%s(6) failed, increasing minimum CDB size to 10 bytes\n",
3128                (cdb[0] == MODE_SENSE_6) ? "MODE_SENSE" : "MODE_SELECT");
3129
3130         if (cdb[0] == MODE_SENSE_6) {
3131                 struct scsi_mode_sense_10 ms10;
3132                 struct scsi_mode_sense_6 *ms6;
3133                 int len;
3134
3135                 ms6 = (struct scsi_mode_sense_6 *)cdb;
3136
3137                 bzero(&ms10, sizeof(ms10));
3138                 ms10.opcode = MODE_SENSE_10;
3139                 ms10.byte2 = ms6->byte2;
3140                 ms10.page = ms6->page;
3141
3142                 /*
3143                  * 10 byte mode header, block descriptor,
3144                  * sizeof(union cd_pages)
3145                  */
3146                 len = sizeof(struct cd_mode_data_10);
3147                 ccb->csio.dxfer_len = len;
3148
3149                 scsi_ulto2b(len, ms10.length);
3150                 ms10.control = ms6->control;
3151                 bcopy(&ms10, cdb, 10);
3152                 ccb->csio.cdb_len = 10;
3153         } else {
3154                 struct scsi_mode_select_10 ms10;
3155                 struct scsi_mode_select_6 *ms6;
3156                 struct scsi_mode_header_6 *header6;
3157                 struct scsi_mode_header_10 *header10;
3158                 struct scsi_mode_page_header *page_header;
3159                 int blk_desc_len, page_num, page_size, len;
3160
3161                 ms6 = (struct scsi_mode_select_6 *)cdb;
3162
3163                 bzero(&ms10, sizeof(ms10));
3164                 ms10.opcode = MODE_SELECT_10;
3165                 ms10.byte2 = ms6->byte2;
3166
3167                 header6 = (struct scsi_mode_header_6 *)params->mode_buf;
3168                 header10 = (struct scsi_mode_header_10 *)params->mode_buf;
3169
3170                 page_header = find_mode_page_6(header6);
3171                 page_num = page_header->page_code;
3172
3173                 blk_desc_len = header6->blk_desc_len;
3174
3175                 page_size = cdgetpagesize(page_num);
3176
3177                 if (page_size != (page_header->page_length +
3178                     sizeof(*page_header)))
3179                         page_size = page_header->page_length +
3180                                 sizeof(*page_header);
3181
3182                 len = sizeof(*header10) + blk_desc_len + page_size;
3183
3184                 len = min(params->alloc_len, len);
3185
3186                 /*
3187                  * Since the 6 byte parameter header is shorter than the 10
3188                  * byte parameter header, we need to copy the actual mode
3189                  * page data, and the block descriptor, if any, so things wind
3190                  * up in the right place.  The regions will overlap, but
3191                  * bcopy() does the right thing.
3192                  */
3193                 bcopy(params->mode_buf + sizeof(*header6),
3194                       params->mode_buf + sizeof(*header10),
3195                       len - sizeof(*header10));
3196
3197                 /* Make sure these fields are set correctly. */
3198                 scsi_ulto2b(0, header10->data_length);
3199                 header10->medium_type = 0;
3200                 scsi_ulto2b(blk_desc_len, header10->blk_desc_len);
3201
3202                 ccb->csio.dxfer_len = len;
3203
3204                 scsi_ulto2b(len, ms10.length);
3205                 ms10.control = ms6->control;
3206                 bcopy(&ms10, cdb, 10);
3207                 ccb->csio.cdb_len = 10;
3208         }
3209
3210         frozen = (ccb->ccb_h.status & CAM_DEV_QFRZN) != 0;
3211         ccb->ccb_h.status = CAM_REQUEUE_REQ;
3212         xpt_action(ccb);
3213         if (frozen) {
3214                 cam_release_devq(ccb->ccb_h.path,
3215                                  /*relsim_flags*/0,
3216                                  /*openings*/0,
3217                                  /*timeout*/0,
3218                                  /*getcount_only*/0);
3219         }
3220
3221         return (ERESTART);
3222 }
3223
3224 static int
3225 cderror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
3226 {
3227         struct cd_softc *softc;
3228         struct cam_periph *periph;
3229         int error;
3230
3231         periph = xpt_path_periph(ccb->ccb_h.path);
3232         softc = (struct cd_softc *)periph->softc;
3233
3234         error = 0;
3235
3236         /*
3237          * We use a status of CAM_REQ_INVALID as shorthand -- if a 6 byte
3238          * CDB comes back with this particular error, try transforming it
3239          * into the 10 byte version.
3240          */
3241         if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INVALID) {
3242                 error = cd6byteworkaround(ccb);
3243         } else if (((ccb->ccb_h.status & CAM_STATUS_MASK) ==
3244                      CAM_SCSI_STATUS_ERROR)
3245          && (ccb->ccb_h.status & CAM_AUTOSNS_VALID)
3246          && (ccb->csio.scsi_status == SCSI_STATUS_CHECK_COND)
3247          && ((ccb->ccb_h.flags & CAM_SENSE_PHYS) == 0)
3248          && ((ccb->ccb_h.flags & CAM_SENSE_PTR) == 0)) {
3249                 int sense_key, error_code, asc, ascq;
3250
3251                 scsi_extract_sense(&ccb->csio.sense_data,
3252                                    &error_code, &sense_key, &asc, &ascq);
3253                 if (sense_key == SSD_KEY_ILLEGAL_REQUEST)
3254                         error = cd6byteworkaround(ccb);
3255         }
3256
3257         if (error == ERESTART)
3258                 return (error);
3259
3260         /*
3261          * XXX
3262          * Until we have a better way of doing pack validation,
3263          * don't treat UAs as errors.
3264          */
3265         sense_flags |= SF_RETRY_UA;
3266         return (cam_periph_error(ccb, cam_flags, sense_flags, 
3267                                  &softc->saved_ccb));
3268 }
3269
3270 /*
3271  * Read table of contents
3272  */
3273 static int 
3274 cdreadtoc(struct cam_periph *periph, u_int32_t mode, u_int32_t start, 
3275           u_int8_t *data, u_int32_t len, u_int32_t sense_flags)
3276 {
3277         struct scsi_read_toc *scsi_cmd;
3278         u_int32_t ntoc;
3279         struct ccb_scsiio *csio;
3280         union ccb *ccb;
3281         int error;
3282
3283         ntoc = len;
3284         error = 0;
3285
3286         ccb = cdgetccb(periph, /* priority */ 1);
3287
3288         csio = &ccb->csio;
3289
3290         cam_fill_csio(csio, 
3291                       /* retries */ 1, 
3292                       /* cbfcnp */ cddone, 
3293                       /* flags */ CAM_DIR_IN,
3294                       /* tag_action */ MSG_SIMPLE_Q_TAG,
3295                       /* data_ptr */ data,
3296                       /* dxfer_len */ len,
3297                       /* sense_len */ SSD_FULL_SIZE,
3298                       sizeof(struct scsi_read_toc),
3299                       /* timeout */ 50000);
3300
3301         scsi_cmd = (struct scsi_read_toc *)&csio->cdb_io.cdb_bytes;
3302         bzero (scsi_cmd, sizeof(*scsi_cmd));
3303
3304         if (mode == CD_MSF_FORMAT)
3305                 scsi_cmd->byte2 |= CD_MSF;
3306         scsi_cmd->from_track = start;
3307         /* scsi_ulto2b(ntoc, (u_int8_t *)scsi_cmd->data_len); */
3308         scsi_cmd->data_len[0] = (ntoc) >> 8;
3309         scsi_cmd->data_len[1] = (ntoc) & 0xff;
3310
3311         scsi_cmd->op_code = READ_TOC;
3312
3313         error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3314                          /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO |
3315                          sense_flags);
3316
3317         xpt_release_ccb(ccb);
3318
3319         return(error);
3320 }
3321
3322 static int
3323 cdreadsubchannel(struct cam_periph *periph, u_int32_t mode, 
3324                  u_int32_t format, int track, 
3325                  struct cd_sub_channel_info *data, u_int32_t len) 
3326 {
3327         struct scsi_read_subchannel *scsi_cmd;
3328         struct ccb_scsiio *csio;
3329         union ccb *ccb;
3330         int error;
3331
3332         error = 0;
3333
3334         ccb = cdgetccb(periph, /* priority */ 1);
3335
3336         csio = &ccb->csio;
3337
3338         cam_fill_csio(csio, 
3339                       /* retries */ 1, 
3340                       /* cbfcnp */ cddone, 
3341                       /* flags */ CAM_DIR_IN,
3342                       /* tag_action */ MSG_SIMPLE_Q_TAG,
3343                       /* data_ptr */ (u_int8_t *)data,
3344                       /* dxfer_len */ len,
3345                       /* sense_len */ SSD_FULL_SIZE,
3346                       sizeof(struct scsi_read_subchannel),
3347                       /* timeout */ 50000);
3348
3349         scsi_cmd = (struct scsi_read_subchannel *)&csio->cdb_io.cdb_bytes;
3350         bzero (scsi_cmd, sizeof(*scsi_cmd));
3351
3352         scsi_cmd->op_code = READ_SUBCHANNEL;
3353         if (mode == CD_MSF_FORMAT)
3354                 scsi_cmd->byte1 |= CD_MSF;
3355         scsi_cmd->byte2 = SRS_SUBQ;
3356         scsi_cmd->subchan_format = format;
3357         scsi_cmd->track = track;
3358         scsi_ulto2b(len, (u_int8_t *)scsi_cmd->data_len);
3359         scsi_cmd->control = 0;
3360
3361         error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3362                          /*sense_flags*/SF_RETRY_UA|SF_RETRY_SELTO);
3363
3364         xpt_release_ccb(ccb);
3365
3366         return(error);
3367 }
3368
3369 /*
3370  * All MODE_SENSE requests in the cd(4) driver MUST go through this
3371  * routine.  See comments in cd6byteworkaround() for details.
3372  */
3373 static int
3374 cdgetmode(struct cam_periph *periph, struct cd_mode_params *data,
3375           u_int32_t page)
3376 {
3377         struct ccb_scsiio *csio;
3378         struct cd_softc *softc;
3379         union ccb *ccb;
3380         int param_len;
3381         int error;
3382
3383         softc = (struct cd_softc *)periph->softc;
3384
3385         ccb = cdgetccb(periph, /* priority */ 1);
3386
3387         csio = &ccb->csio;
3388
3389         data->cdb_size = softc->minimum_command_size;
3390         if (data->cdb_size < 10)
3391                 param_len = sizeof(struct cd_mode_data);
3392         else
3393                 param_len = sizeof(struct cd_mode_data_10);
3394
3395         /* Don't say we've got more room than we actually allocated */
3396         param_len = min(param_len, data->alloc_len);
3397
3398         scsi_mode_sense_len(csio,
3399                             /* retries */ 1,
3400                             /* cbfcnp */ cddone,
3401                             /* tag_action */ MSG_SIMPLE_Q_TAG,
3402                             /* dbd */ 0,
3403                             /* page_code */ SMS_PAGE_CTRL_CURRENT,
3404                             /* page */ page,
3405                             /* param_buf */ data->mode_buf,
3406                             /* param_len */ param_len,
3407                             /* minimum_cmd_size */ softc->minimum_command_size,
3408                             /* sense_len */ SSD_FULL_SIZE,
3409                             /* timeout */ 50000);
3410
3411         /*
3412          * It would be nice not to have to do this, but there's no
3413          * available pointer in the CCB that would allow us to stuff the
3414          * mode params structure in there and retrieve it in
3415          * cd6byteworkaround(), so we can set the cdb size.  The cdb size
3416          * lets the caller know what CDB size we ended up using, so they
3417          * can find the actual mode page offset.
3418          */
3419         STAILQ_INSERT_TAIL(&softc->mode_queue, data, links);
3420
3421         error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3422                          /*sense_flags*/SF_RETRY_UA|SF_RETRY_SELTO);
3423
3424         xpt_release_ccb(ccb);
3425
3426         STAILQ_REMOVE(&softc->mode_queue, data, cd_mode_params, links);
3427
3428         /*
3429          * This is a bit of belt-and-suspenders checking, but if we run
3430          * into a situation where the target sends back multiple block
3431          * descriptors, we might not have enough space in the buffer to
3432          * see the whole mode page.  Better to return an error than
3433          * potentially access memory beyond our malloced region.
3434          */
3435         if (error == 0) {
3436                 u_int32_t data_len;
3437
3438                 if (data->cdb_size == 10) {
3439                         struct scsi_mode_header_10 *hdr10;
3440
3441                         hdr10 = (struct scsi_mode_header_10 *)data->mode_buf;
3442                         data_len = scsi_2btoul(hdr10->data_length);
3443                         data_len += sizeof(hdr10->data_length);
3444                 } else {
3445                         struct scsi_mode_header_6 *hdr6;
3446
3447                         hdr6 = (struct scsi_mode_header_6 *)data->mode_buf;
3448                         data_len = hdr6->data_length;
3449                         data_len += sizeof(hdr6->data_length);
3450                 }
3451
3452                 /*
3453                  * Complain if there is more mode data available than we
3454                  * allocated space for.  This could potentially happen if
3455                  * we miscalculated the page length for some reason, if the
3456                  * drive returns multiple block descriptors, or if it sets
3457                  * the data length incorrectly.
3458                  */
3459                 if (data_len > data->alloc_len) {
3460                         xpt_print_path(periph->path);
3461                         printf("allocated modepage %d length %d < returned "
3462                                "length %d\n", page, data->alloc_len, data_len);
3463
3464                         error = ENOSPC;
3465                 }
3466         }
3467         return (error);
3468 }
3469
3470 /*
3471  * All MODE_SELECT requests in the cd(4) driver MUST go through this
3472  * routine.  See comments in cd6byteworkaround() for details.
3473  */
3474 static int
3475 cdsetmode(struct cam_periph *periph, struct cd_mode_params *data)
3476 {
3477         struct ccb_scsiio *csio;
3478         struct cd_softc *softc;
3479         union ccb *ccb;
3480         int cdb_size, param_len;
3481         int error;
3482
3483         softc = (struct cd_softc *)periph->softc;
3484
3485         ccb = cdgetccb(periph, /* priority */ 1);
3486
3487         csio = &ccb->csio;
3488
3489         error = 0;
3490
3491         /*
3492          * If the data is formatted for the 10 byte version of the mode
3493          * select parameter list, we need to use the 10 byte CDB.
3494          * Otherwise, we use whatever the stored minimum command size.
3495          */
3496         if (data->cdb_size == 10)
3497                 cdb_size = data->cdb_size;
3498         else
3499                 cdb_size = softc->minimum_command_size;
3500
3501         if (cdb_size >= 10) {
3502                 struct scsi_mode_header_10 *mode_header;
3503                 u_int32_t data_len;
3504
3505                 mode_header = (struct scsi_mode_header_10 *)data->mode_buf;
3506
3507                 data_len = scsi_2btoul(mode_header->data_length);
3508
3509                 scsi_ulto2b(0, mode_header->data_length);
3510                 /*
3511                  * SONY drives do not allow a mode select with a medium_type
3512                  * value that has just been returned by a mode sense; use a
3513                  * medium_type of 0 (Default) instead.
3514                  */
3515                 mode_header->medium_type = 0;
3516
3517                 /*
3518                  * Pass back whatever the drive passed to us, plus the size
3519                  * of the data length field.
3520                  */
3521                 param_len = data_len + sizeof(mode_header->data_length);
3522
3523         } else {
3524                 struct scsi_mode_header_6 *mode_header;
3525
3526                 mode_header = (struct scsi_mode_header_6 *)data->mode_buf;
3527
3528                 param_len = mode_header->data_length + 1;
3529
3530                 mode_header->data_length = 0;
3531                 /*
3532                  * SONY drives do not allow a mode select with a medium_type
3533                  * value that has just been returned by a mode sense; use a
3534                  * medium_type of 0 (Default) instead.
3535                  */
3536                 mode_header->medium_type = 0;
3537         }
3538
3539         /* Don't say we've got more room than we actually allocated */
3540         param_len = min(param_len, data->alloc_len);
3541
3542         scsi_mode_select_len(csio,
3543                              /* retries */ 1,
3544                              /* cbfcnp */ cddone,
3545                              /* tag_action */ MSG_SIMPLE_Q_TAG,
3546                              /* scsi_page_fmt */ 1,
3547                              /* save_pages */ 0,
3548                              /* param_buf */ data->mode_buf,
3549                              /* param_len */ param_len,
3550                              /* minimum_cmd_size */ cdb_size,
3551                              /* sense_len */ SSD_FULL_SIZE,
3552                              /* timeout */ 50000);
3553
3554         /* See comments in cdgetmode() and cd6byteworkaround(). */
3555         STAILQ_INSERT_TAIL(&softc->mode_queue, data, links);
3556
3557         error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3558                          /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
3559
3560         xpt_release_ccb(ccb);
3561
3562         STAILQ_REMOVE(&softc->mode_queue, data, cd_mode_params, links);
3563
3564         return (error);
3565 }
3566
3567   
3568
3569 static int 
3570 cdplay(struct cam_periph *periph, u_int32_t blk, u_int32_t len)
3571 {
3572         struct ccb_scsiio *csio;
3573         union ccb *ccb;
3574         int error;
3575         u_int8_t cdb_len;
3576
3577         error = 0;
3578         ccb = cdgetccb(periph, /* priority */ 1);
3579         csio = &ccb->csio;
3580         /*
3581          * Use the smallest possible command to perform the operation.
3582          */
3583         if ((len & 0xffff0000) == 0) {
3584                 /*
3585                  * We can fit in a 10 byte cdb.
3586                  */
3587                 struct scsi_play_10 *scsi_cmd;
3588
3589                 scsi_cmd = (struct scsi_play_10 *)&csio->cdb_io.cdb_bytes;
3590                 bzero (scsi_cmd, sizeof(*scsi_cmd));
3591                 scsi_cmd->op_code = PLAY_10;
3592                 scsi_ulto4b(blk, (u_int8_t *)scsi_cmd->blk_addr);
3593                 scsi_ulto2b(len, (u_int8_t *)scsi_cmd->xfer_len);
3594                 cdb_len = sizeof(*scsi_cmd);
3595         } else  {
3596                 struct scsi_play_12 *scsi_cmd;
3597
3598                 scsi_cmd = (struct scsi_play_12 *)&csio->cdb_io.cdb_bytes;
3599                 bzero (scsi_cmd, sizeof(*scsi_cmd));
3600                 scsi_cmd->op_code = PLAY_12;
3601                 scsi_ulto4b(blk, (u_int8_t *)scsi_cmd->blk_addr);
3602                 scsi_ulto4b(len, (u_int8_t *)scsi_cmd->xfer_len);
3603                 cdb_len = sizeof(*scsi_cmd);
3604         }
3605         cam_fill_csio(csio,
3606                       /*retries*/2,
3607                       cddone,
3608                       /*flags*/CAM_DIR_NONE,
3609                       MSG_SIMPLE_Q_TAG,
3610                       /*dataptr*/NULL,
3611                       /*datalen*/0,
3612                       /*sense_len*/SSD_FULL_SIZE,
3613                       cdb_len,
3614                       /*timeout*/50 * 1000);
3615
3616         error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3617                          /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
3618
3619         xpt_release_ccb(ccb);
3620
3621         return(error);
3622 }
3623
3624 static int
3625 cdplaymsf(struct cam_periph *periph, u_int32_t startm, u_int32_t starts,
3626           u_int32_t startf, u_int32_t endm, u_int32_t ends, u_int32_t endf)
3627 {
3628         struct scsi_play_msf *scsi_cmd;
3629         struct ccb_scsiio *csio;
3630         union ccb *ccb;
3631         int error;
3632
3633         error = 0;
3634
3635         ccb = cdgetccb(periph, /* priority */ 1);
3636
3637         csio = &ccb->csio;
3638
3639         cam_fill_csio(csio, 
3640                       /* retries */ 1, 
3641                       /* cbfcnp */ cddone, 
3642                       /* flags */ CAM_DIR_NONE,
3643                       /* tag_action */ MSG_SIMPLE_Q_TAG,
3644                       /* data_ptr */ NULL,
3645                       /* dxfer_len */ 0,
3646                       /* sense_len */ SSD_FULL_SIZE,
3647                       sizeof(struct scsi_play_msf),
3648                       /* timeout */ 50000);
3649
3650         scsi_cmd = (struct scsi_play_msf *)&csio->cdb_io.cdb_bytes;
3651         bzero (scsi_cmd, sizeof(*scsi_cmd));
3652
3653         scsi_cmd->op_code = PLAY_MSF;
3654         scsi_cmd->start_m = startm;
3655         scsi_cmd->start_s = starts;
3656         scsi_cmd->start_f = startf;
3657         scsi_cmd->end_m = endm;
3658         scsi_cmd->end_s = ends;
3659         scsi_cmd->end_f = endf; 
3660
3661         error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3662                          /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
3663         
3664         xpt_release_ccb(ccb);
3665
3666         return(error);
3667 }
3668
3669
3670 static int
3671 cdplaytracks(struct cam_periph *periph, u_int32_t strack, u_int32_t sindex,
3672              u_int32_t etrack, u_int32_t eindex)
3673 {
3674         struct scsi_play_track *scsi_cmd;
3675         struct ccb_scsiio *csio;
3676         union ccb *ccb;
3677         int error;
3678
3679         error = 0;
3680
3681         ccb = cdgetccb(periph, /* priority */ 1);
3682
3683         csio = &ccb->csio;
3684
3685         cam_fill_csio(csio, 
3686                       /* retries */ 1, 
3687                       /* cbfcnp */ cddone, 
3688                       /* flags */ CAM_DIR_NONE,
3689                       /* tag_action */ MSG_SIMPLE_Q_TAG,
3690                       /* data_ptr */ NULL,
3691                       /* dxfer_len */ 0,
3692                       /* sense_len */ SSD_FULL_SIZE,
3693                       sizeof(struct scsi_play_track),
3694                       /* timeout */ 50000);
3695
3696         scsi_cmd = (struct scsi_play_track *)&csio->cdb_io.cdb_bytes;
3697         bzero (scsi_cmd, sizeof(*scsi_cmd));
3698
3699         scsi_cmd->op_code = PLAY_TRACK;
3700         scsi_cmd->start_track = strack;
3701         scsi_cmd->start_index = sindex;
3702         scsi_cmd->end_track = etrack;
3703         scsi_cmd->end_index = eindex;
3704
3705         error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3706                          /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
3707
3708         xpt_release_ccb(ccb);
3709
3710         return(error);
3711 }
3712
3713 static int
3714 cdpause(struct cam_periph *periph, u_int32_t go)
3715 {
3716         struct scsi_pause *scsi_cmd;
3717         struct ccb_scsiio *csio;
3718         union ccb *ccb;
3719         int error;
3720
3721         error = 0;
3722
3723         ccb = cdgetccb(periph, /* priority */ 1);
3724
3725         csio = &ccb->csio;
3726
3727         cam_fill_csio(csio, 
3728                       /* retries */ 1, 
3729                       /* cbfcnp */ cddone, 
3730                       /* flags */ CAM_DIR_NONE,
3731                       /* tag_action */ MSG_SIMPLE_Q_TAG,
3732                       /* data_ptr */ NULL,
3733                       /* dxfer_len */ 0,
3734                       /* sense_len */ SSD_FULL_SIZE,
3735                       sizeof(struct scsi_pause),
3736                       /* timeout */ 50000);
3737
3738         scsi_cmd = (struct scsi_pause *)&csio->cdb_io.cdb_bytes;
3739         bzero (scsi_cmd, sizeof(*scsi_cmd));
3740
3741         scsi_cmd->op_code = PAUSE;
3742         scsi_cmd->resume = go;
3743
3744         error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3745                          /*sense_flags*/SF_RETRY_UA |SF_RETRY_SELTO);
3746
3747         xpt_release_ccb(ccb);
3748
3749         return(error);
3750 }
3751
3752 static int
3753 cdstartunit(struct cam_periph *periph, int load)
3754 {
3755         union ccb *ccb;
3756         int error;
3757
3758         error = 0;
3759
3760         ccb = cdgetccb(periph, /* priority */ 1);
3761
3762         scsi_start_stop(&ccb->csio,
3763                         /* retries */ 1,
3764                         /* cbfcnp */ cddone,
3765                         /* tag_action */ MSG_SIMPLE_Q_TAG,
3766                         /* start */ TRUE,
3767                         /* load_eject */ load,
3768                         /* immediate */ FALSE,
3769                         /* sense_len */ SSD_FULL_SIZE,
3770                         /* timeout */ 50000);
3771
3772         error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3773                          /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
3774
3775         xpt_release_ccb(ccb);
3776
3777         return(error);
3778 }
3779
3780 static int
3781 cdstopunit(struct cam_periph *periph, u_int32_t eject)
3782 {
3783         union ccb *ccb;
3784         int error;
3785
3786         error = 0;
3787
3788         ccb = cdgetccb(periph, /* priority */ 1);
3789
3790         scsi_start_stop(&ccb->csio,
3791                         /* retries */ 1,
3792                         /* cbfcnp */ cddone,
3793                         /* tag_action */ MSG_SIMPLE_Q_TAG,
3794                         /* start */ FALSE,
3795                         /* load_eject */ eject,
3796                         /* immediate */ FALSE,
3797                         /* sense_len */ SSD_FULL_SIZE,
3798                         /* timeout */ 50000);
3799
3800         error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3801                          /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
3802
3803         xpt_release_ccb(ccb);
3804
3805         return(error);
3806 }
3807
3808 static int
3809 cdsetspeed(struct cam_periph *periph, u_int32_t rdspeed, u_int32_t wrspeed)
3810 {
3811         struct scsi_set_speed *scsi_cmd;
3812         struct ccb_scsiio *csio;
3813         union ccb *ccb;
3814         int error;
3815
3816         error = 0;
3817         ccb = cdgetccb(periph, /* priority */ 1);
3818         csio = &ccb->csio;
3819
3820         /* Preserve old behavior: units in multiples of CDROM speed */
3821         if (rdspeed < 177)
3822                 rdspeed *= 177;
3823         if (wrspeed < 177)
3824                 wrspeed *= 177;
3825
3826         cam_fill_csio(csio,
3827                       /* retries */ 1,
3828                       /* cbfcnp */ cddone,
3829                       /* flags */ CAM_DIR_NONE,
3830                       /* tag_action */ MSG_SIMPLE_Q_TAG,
3831                       /* data_ptr */ NULL,
3832                       /* dxfer_len */ 0,
3833                       /* sense_len */ SSD_FULL_SIZE,
3834                       sizeof(struct scsi_set_speed),
3835                       /* timeout */ 50000);
3836
3837         scsi_cmd = (struct scsi_set_speed *)&csio->cdb_io.cdb_bytes;
3838         bzero(scsi_cmd, sizeof(*scsi_cmd));
3839
3840         scsi_cmd->opcode = SET_CD_SPEED;
3841         scsi_ulto2b(rdspeed, scsi_cmd->readspeed);
3842         scsi_ulto2b(wrspeed, scsi_cmd->writespeed);
3843
3844         error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3845                          /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
3846
3847         xpt_release_ccb(ccb);
3848
3849         return(error);
3850 }
3851
3852 static int
3853 cdreportkey(struct cam_periph *periph, struct dvd_authinfo *authinfo)
3854 {
3855         union ccb *ccb;
3856         u_int8_t *databuf;
3857         u_int32_t lba;
3858         int error;
3859         int length;
3860
3861         error = 0;
3862         databuf = NULL;
3863         lba = 0;
3864
3865         ccb = cdgetccb(periph, /* priority */ 1);
3866
3867         switch (authinfo->format) {
3868         case DVD_REPORT_AGID:
3869                 length = sizeof(struct scsi_report_key_data_agid);
3870                 break;
3871         case DVD_REPORT_CHALLENGE:
3872                 length = sizeof(struct scsi_report_key_data_challenge);
3873                 break;
3874         case DVD_REPORT_KEY1:
3875                 length = sizeof(struct scsi_report_key_data_key1_key2);
3876                 break;
3877         case DVD_REPORT_TITLE_KEY:
3878                 length = sizeof(struct scsi_report_key_data_title);
3879                 /* The lba field is only set for the title key */
3880                 lba = authinfo->lba;
3881                 break;
3882         case DVD_REPORT_ASF:
3883                 length = sizeof(struct scsi_report_key_data_asf);
3884                 break;
3885         case DVD_REPORT_RPC:
3886                 length = sizeof(struct scsi_report_key_data_rpc);
3887                 break;
3888         case DVD_INVALIDATE_AGID:
3889                 length = 0;
3890                 break;
3891         default:
3892                 error = EINVAL;
3893                 goto bailout;
3894                 break; /* NOTREACHED */
3895         }
3896
3897         if (length != 0) {
3898                 databuf = malloc(length, M_DEVBUF, M_INTWAIT | M_ZERO);
3899         } else {
3900                 databuf = NULL;
3901         }
3902
3903
3904         scsi_report_key(&ccb->csio,
3905                         /* retries */ 1,
3906                         /* cbfcnp */ cddone,
3907                         /* tag_action */ MSG_SIMPLE_Q_TAG,
3908                         /* lba */ lba,
3909                         /* agid */ authinfo->agid,
3910                         /* key_format */ authinfo->format,
3911                         /* data_ptr */ databuf,
3912                         /* dxfer_len */ length,
3913                         /* sense_len */ SSD_FULL_SIZE,
3914                         /* timeout */ 50000);
3915
3916         error = cdrunccb(ccb, cderror, /*cam_flags*/0,
3917                          /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
3918
3919         if (error != 0)
3920                 goto bailout;
3921
3922         if (ccb->csio.resid != 0) {
3923                 xpt_print_path(periph->path);
3924                 printf("warning, residual for report key command is %d\n",
3925                        ccb->csio.resid);
3926         }
3927
3928         switch(authinfo->format) {
3929         case DVD_REPORT_AGID: {
3930                 struct scsi_report_key_data_agid *agid_data;
3931
3932                 agid_data = (struct scsi_report_key_data_agid *)databuf;
3933
3934                 authinfo->agid = (agid_data->agid & RKD_AGID_MASK) >>
3935                         RKD_AGID_SHIFT;
3936                 break;
3937         }
3938         case DVD_REPORT_CHALLENGE: {
3939                 struct scsi_report_key_data_challenge *chal_data;
3940
3941                 chal_data = (struct scsi_report_key_data_challenge *)databuf;
3942
3943                 bcopy(chal_data->challenge_key, authinfo->keychal,
3944                       min(sizeof(chal_data->challenge_key),
3945                           sizeof(authinfo->keychal)));
3946                 break;
3947         }
3948         case DVD_REPORT_KEY1: {
3949                 struct scsi_report_key_data_key1_key2 *key1_data;
3950
3951                 key1_data = (struct scsi_report_key_data_key1_key2 *)databuf;
3952
3953                 bcopy(key1_data->key1, authinfo->keychal,
3954                       min(sizeof(key1_data->key1), sizeof(authinfo->keychal)));
3955                 break;
3956         }
3957         case DVD_REPORT_TITLE_KEY: {
3958                 struct scsi_report_key_data_title *title_data;
3959
3960                 title_data = (struct scsi_report_key_data_title *)databuf;
3961
3962                 authinfo->cpm = (title_data->byte0 & RKD_TITLE_CPM) >>
3963                         RKD_TITLE_CPM_SHIFT;
3964                 authinfo->cp_sec = (title_data->byte0 & RKD_TITLE_CP_SEC) >>
3965                         RKD_TITLE_CP_SEC_SHIFT;
3966                 authinfo->cgms = (title_data->byte0 & RKD_TITLE_CMGS_MASK) >>
3967                         RKD_TITLE_CMGS_SHIFT;
3968                 bcopy(title_data->title_key, authinfo->keychal,
3969                       min(sizeof(title_data->title_key),
3970                           sizeof(authinfo->keychal)));
3971                 break;
3972         }
3973         case DVD_REPORT_ASF: {
3974                 struct scsi_report_key_data_asf *asf_data;
3975
3976                 asf_data = (struct scsi_report_key_data_asf *)databuf;
3977
3978                 authinfo->asf = asf_data->success & RKD_ASF_SUCCESS;
3979                 break;
3980         }
3981         case DVD_REPORT_RPC: {
3982                 struct scsi_report_key_data_rpc *rpc_data;
3983
3984                 rpc_data = (struct scsi_report_key_data_rpc *)databuf;
3985
3986                 authinfo->reg_type = (rpc_data->byte4 & RKD_RPC_TYPE_MASK) >>
3987                         RKD_RPC_TYPE_SHIFT;
3988                 authinfo->vend_rsts =
3989                         (rpc_data->byte4 & RKD_RPC_VENDOR_RESET_MASK) >>
3990                         RKD_RPC_VENDOR_RESET_SHIFT;
3991                 authinfo->user_rsts = rpc_data->byte4 & RKD_RPC_USER_RESET_MASK;
3992                 authinfo->region = rpc_data->region_mask;
3993                 authinfo->rpc_scheme = rpc_data->rpc_scheme1;
3994                 break;
3995         }
3996         case DVD_INVALIDATE_AGID:
3997                 break;
3998         default:
3999                 /* This should be impossible, since we checked above */
4000                 error = EINVAL;
4001                 goto bailout;
4002                 break; /* NOTREACHED */
4003         }
4004 bailout:
4005         if (databuf != NULL)
4006                 free(databuf, M_DEVBUF);
4007
4008         xpt_release_ccb(ccb);
4009
4010         return(error);
4011 }
4012
4013 static int
4014 cdsendkey(struct cam_periph *periph, struct dvd_authinfo *authinfo)
4015 {
4016         union ccb *ccb;
4017         u_int8_t *databuf;
4018         int length;
4019         int error;
4020
4021         error = 0;
4022         databuf = NULL;
4023
4024         ccb = cdgetccb(periph, /* priority */ 1);
4025
4026         switch(authinfo->format) {
4027         case DVD_SEND_CHALLENGE: {
4028                 struct scsi_report_key_data_challenge *challenge_data;
4029
4030                 length = sizeof(*challenge_data);
4031
4032                 challenge_data = malloc(length, M_DEVBUF, M_INTWAIT | M_ZERO);
4033
4034                 databuf = (u_int8_t *)challenge_data;
4035
4036                 scsi_ulto2b(length - sizeof(challenge_data->data_len),
4037                             challenge_data->data_len);
4038
4039                 bcopy(authinfo->keychal, challenge_data->challenge_key,
4040                       min(sizeof(authinfo->keychal),
4041                           sizeof(challenge_data->challenge_key)));
4042                 break;
4043         }
4044         case DVD_SEND_KEY2: {
4045                 struct scsi_report_key_data_key1_key2 *key2_data;
4046
4047                 length = sizeof(*key2_data);
4048
4049                 key2_data = malloc(length, M_DEVBUF, M_INTWAIT | M_ZERO);
4050
4051                 databuf = (u_int8_t *)key2_data;
4052
4053                 scsi_ulto2b(length - sizeof(key2_data->data_len),
4054                             key2_data->data_len);
4055
4056                 bcopy(authinfo->keychal, key2_data->key1,
4057                       min(sizeof(authinfo->keychal), sizeof(key2_data->key1)));
4058
4059                 break;
4060         }
4061         case DVD_SEND_RPC: {
4062                 struct scsi_send_key_data_rpc *rpc_data;
4063
4064                 length = sizeof(*rpc_data);
4065
4066                 rpc_data = malloc(length, M_DEVBUF, M_INTWAIT | M_ZERO);
4067
4068                 databuf = (u_int8_t *)rpc_data;
4069
4070                 scsi_ulto2b(length - sizeof(rpc_data->data_len),
4071                             rpc_data->data_len);
4072
4073                 rpc_data->region_code = authinfo->region;
4074                 break;
4075         }
4076         default:
4077                 error = EINVAL;
4078                 goto bailout;
4079                 break; /* NOTREACHED */
4080         }
4081
4082         scsi_send_key(&ccb->csio,
4083                       /* retries */ 1,
4084                       /* cbfcnp */ cddone,
4085                       /* tag_action */ MSG_SIMPLE_Q_TAG,
4086                       /* agid */ authinfo->agid,
4087                       /* key_format */ authinfo->format,
4088                       /* data_ptr */ databuf,
4089                       /* dxfer_len */ length,
4090                       /* sense_len */ SSD_FULL_SIZE,
4091                       /* timeout */ 50000);
4092
4093         error = cdrunccb(ccb, cderror, /*cam_flags*/0,
4094                          /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
4095
4096 bailout:
4097
4098         if (databuf != NULL)
4099                 free(databuf, M_DEVBUF);
4100
4101         xpt_release_ccb(ccb);
4102
4103         return(error);
4104 }
4105
4106 static int
4107 cdreaddvdstructure(struct cam_periph *periph, struct dvd_struct *dvdstruct)
4108 {
4109         union ccb *ccb;
4110         u_int8_t *databuf;
4111         u_int32_t address;
4112         int error;
4113         int length;
4114
4115         error = 0;
4116         databuf = NULL;
4117         /* The address is reserved for many of the formats */
4118         address = 0;
4119
4120         ccb = cdgetccb(periph, /* priority */ 1);
4121
4122         switch(dvdstruct->format) {
4123         case DVD_STRUCT_PHYSICAL:
4124                 length = sizeof(struct scsi_read_dvd_struct_data_physical);
4125                 break;
4126         case DVD_STRUCT_COPYRIGHT:
4127                 length = sizeof(struct scsi_read_dvd_struct_data_copyright);
4128                 break;
4129         case DVD_STRUCT_DISCKEY:
4130                 length = sizeof(struct scsi_read_dvd_struct_data_disc_key);
4131                 break;
4132         case DVD_STRUCT_BCA:
4133                 length = sizeof(struct scsi_read_dvd_struct_data_bca);
4134                 break;
4135         case DVD_STRUCT_MANUFACT:
4136                 length = sizeof(struct scsi_read_dvd_struct_data_manufacturer);
4137                 break;
4138         case DVD_STRUCT_CMI:
4139                 error = ENODEV;
4140                 goto bailout;
4141 #ifdef notyet
4142                 length = sizeof(struct scsi_read_dvd_struct_data_copy_manage);
4143                 address = dvdstruct->address;
4144 #endif
4145                 break; /* NOTREACHED */
4146         case DVD_STRUCT_PROTDISCID:
4147                 length = sizeof(struct scsi_read_dvd_struct_data_prot_discid);
4148                 break;
4149         case DVD_STRUCT_DISCKEYBLOCK:
4150                 length = sizeof(struct scsi_read_dvd_struct_data_disc_key_blk);
4151                 break;
4152         case DVD_STRUCT_DDS:
4153                 length = sizeof(struct scsi_read_dvd_struct_data_dds);
4154                 break;
4155         case DVD_STRUCT_MEDIUM_STAT:
4156                 length = sizeof(struct scsi_read_dvd_struct_data_medium_status);
4157                 break;
4158         case DVD_STRUCT_SPARE_AREA:
4159                 length = sizeof(struct scsi_read_dvd_struct_data_spare_area);
4160                 break;
4161         case DVD_STRUCT_RMD_LAST:
4162                 error = ENODEV;
4163                 goto bailout;
4164 #ifdef notyet
4165                 length = sizeof(struct scsi_read_dvd_struct_data_rmd_borderout);
4166                 address = dvdstruct->address;
4167 #endif
4168                 break; /* NOTREACHED */
4169         case DVD_STRUCT_RMD_RMA:
4170                 error = ENODEV;
4171                 goto bailout;
4172 #ifdef notyet
4173                 length = sizeof(struct scsi_read_dvd_struct_data_rmd);
4174                 address = dvdstruct->address;
4175 #endif
4176                 break; /* NOTREACHED */
4177         case DVD_STRUCT_PRERECORDED:
4178                 length = sizeof(struct scsi_read_dvd_struct_data_leadin);
4179                 break;
4180         case DVD_STRUCT_UNIQUEID:
4181                 length = sizeof(struct scsi_read_dvd_struct_data_disc_id);
4182                 break;
4183         case DVD_STRUCT_DCB:
4184                 error = ENODEV;
4185                 goto bailout;
4186 #ifdef notyet
4187                 length = sizeof(struct scsi_read_dvd_struct_data_dcb);
4188                 address = dvdstruct->address;
4189 #endif
4190                 break; /* NOTREACHED */
4191         case DVD_STRUCT_LIST:
4192                 /*
4193                  * This is the maximum allocation length for the READ DVD
4194                  * STRUCTURE command.  There's nothing in the MMC3 spec
4195                  * that indicates a limit in the amount of data that can
4196                  * be returned from this call, other than the limits
4197                  * imposed by the 2-byte length variables.
4198                  */
4199                 length = 65535;
4200                 break;
4201         default:
4202                 error = EINVAL;
4203                 goto bailout;
4204                 break; /* NOTREACHED */
4205         }
4206
4207         if (length != 0) {
4208                 databuf = malloc(length, M_DEVBUF, M_INTWAIT | M_ZERO);
4209         } else {
4210                 databuf = NULL;
4211         }
4212
4213         scsi_read_dvd_structure(&ccb->csio,
4214                                 /* retries */ 1,
4215                                 /* cbfcnp */ cddone,
4216                                 /* tag_action */ MSG_SIMPLE_Q_TAG,
4217                                 /* lba */ address,
4218                                 /* layer_number */ dvdstruct->layer_num,
4219                                 /* key_format */ dvdstruct->format,
4220                                 /* agid */ dvdstruct->agid,
4221                                 /* data_ptr */ databuf,
4222                                 /* dxfer_len */ length,
4223                                 /* sense_len */ SSD_FULL_SIZE,
4224                                 /* timeout */ 50000);
4225
4226         error = cdrunccb(ccb, cderror, /*cam_flags*/0,
4227                          /*sense_flags*/SF_RETRY_UA | SF_RETRY_SELTO);
4228
4229         if (error != 0)
4230                 goto bailout;
4231
4232         switch(dvdstruct->format) {
4233         case DVD_STRUCT_PHYSICAL: {
4234                 struct scsi_read_dvd_struct_data_layer_desc *inlayer;
4235                 struct dvd_layer *outlayer;
4236                 struct scsi_read_dvd_struct_data_physical *phys_data;
4237
4238                 phys_data =
4239                         (struct scsi_read_dvd_struct_data_physical *)databuf;
4240                 inlayer = &phys_data->layer_desc;
4241                 outlayer = (struct dvd_layer *)&dvdstruct->data;
4242
4243                 dvdstruct->length = sizeof(*inlayer);
4244
4245                 outlayer->book_type = (inlayer->book_type_version &
4246                         RDSD_BOOK_TYPE_MASK) >> RDSD_BOOK_TYPE_SHIFT;
4247                 outlayer->book_version = (inlayer->book_type_version &
4248                         RDSD_BOOK_VERSION_MASK);
4249                 outlayer->disc_size = (inlayer->disc_size_max_rate &
4250                         RDSD_DISC_SIZE_MASK) >> RDSD_DISC_SIZE_SHIFT;
4251                 outlayer->max_rate = (inlayer->disc_size_max_rate &
4252                         RDSD_MAX_RATE_MASK);
4253                 outlayer->nlayers = (inlayer->layer_info &
4254                         RDSD_NUM_LAYERS_MASK) >> RDSD_NUM_LAYERS_SHIFT;
4255                 outlayer->track_path = (inlayer->layer_info &
4256                         RDSD_TRACK_PATH_MASK) >> RDSD_TRACK_PATH_SHIFT;
4257                 outlayer->layer_type = (inlayer->layer_info &
4258                         RDSD_LAYER_TYPE_MASK);
4259                 outlayer->linear_density = (inlayer->density &
4260                         RDSD_LIN_DENSITY_MASK) >> RDSD_LIN_DENSITY_SHIFT;
4261                 outlayer->track_density = (inlayer->density &
4262                         RDSD_TRACK_DENSITY_MASK);
4263                 outlayer->bca = (inlayer->bca & RDSD_BCA_MASK) >>
4264                         RDSD_BCA_SHIFT;
4265                 outlayer->start_sector = scsi_3btoul(inlayer->main_data_start);
4266                 outlayer->end_sector = scsi_3btoul(inlayer->main_data_end);
4267                 outlayer->end_sector_l0 =
4268                         scsi_3btoul(inlayer->end_sector_layer0);
4269                 break;
4270         }
4271         case DVD_STRUCT_COPYRIGHT: {
4272                 struct scsi_read_dvd_struct_data_copyright *copy_data;
4273
4274                 copy_data = (struct scsi_read_dvd_struct_data_copyright *)
4275                         databuf;
4276
4277                 dvdstruct->cpst = copy_data->cps_type;
4278                 dvdstruct->rmi = copy_data->region_info;
4279                 dvdstruct->length = 0;
4280
4281                 break;
4282         }
4283         default:
4284                 /*
4285                  * Tell the user what the overall length is, no matter
4286                  * what we can actually fit in the data buffer.
4287                  */
4288                 dvdstruct->length = length - ccb->csio.resid - 
4289                         sizeof(struct scsi_read_dvd_struct_data_header);
4290
4291                 /*
4292                  * But only actually copy out the smaller of what we read
4293                  * in or what the structure can take.
4294                  */
4295                 bcopy(databuf + sizeof(struct scsi_read_dvd_struct_data_header),
4296                       dvdstruct->data,
4297                       min(sizeof(dvdstruct->data), dvdstruct->length));
4298                 break;
4299         }
4300 bailout:
4301
4302         if (databuf != NULL)
4303                 free(databuf, M_DEVBUF);
4304
4305         xpt_release_ccb(ccb);
4306
4307         return(error);
4308 }
4309
4310 void
4311 scsi_report_key(struct ccb_scsiio *csio, u_int32_t retries,
4312                 void (*cbfcnp)(struct cam_periph *, union ccb *),
4313                 u_int8_t tag_action, u_int32_t lba, u_int8_t agid,
4314                 u_int8_t key_format, u_int8_t *data_ptr, u_int32_t dxfer_len,
4315                 u_int8_t sense_len, u_int32_t timeout)
4316 {
4317         struct scsi_report_key *scsi_cmd;
4318
4319         scsi_cmd = (struct scsi_report_key *)&csio->cdb_io.cdb_bytes;
4320         bzero(scsi_cmd, sizeof(*scsi_cmd));
4321         scsi_cmd->opcode = REPORT_KEY;
4322         scsi_ulto4b(lba, scsi_cmd->lba);
4323         scsi_ulto2b(dxfer_len, scsi_cmd->alloc_len);
4324         scsi_cmd->agid_keyformat = (agid << RK_KF_AGID_SHIFT) |
4325                 (key_format & RK_KF_KEYFORMAT_MASK);
4326
4327         cam_fill_csio(csio,
4328                       retries,
4329                       cbfcnp,
4330                       /*flags*/ (dxfer_len == 0) ? CAM_DIR_NONE : CAM_DIR_IN,
4331                       tag_action,
4332                       /*data_ptr*/ data_ptr,
4333                       /*dxfer_len*/ dxfer_len,
4334                       sense_len,
4335                       sizeof(*scsi_cmd),
4336                       timeout);
4337 }
4338
4339 void
4340 scsi_send_key(struct ccb_scsiio *csio, u_int32_t retries,
4341               void (*cbfcnp)(struct cam_periph *, union ccb *),
4342               u_int8_t tag_action, u_int8_t agid, u_int8_t key_format,
4343               u_int8_t *data_ptr, u_int32_t dxfer_len, u_int8_t sense_len,
4344               u_int32_t timeout)
4345 {
4346         struct scsi_send_key *scsi_cmd;
4347
4348         scsi_cmd = (struct scsi_send_key *)&csio->cdb_io.cdb_bytes;
4349         bzero(scsi_cmd, sizeof(*scsi_cmd));
4350         scsi_cmd->opcode = SEND_KEY;
4351
4352         scsi_ulto2b(dxfer_len, scsi_cmd->param_len);
4353         scsi_cmd->agid_keyformat = (agid << RK_KF_AGID_SHIFT) |
4354                 (key_format & RK_KF_KEYFORMAT_MASK);
4355
4356         cam_fill_csio(csio,
4357                       retries,
4358                       cbfcnp,
4359                       /*flags*/ CAM_DIR_OUT,
4360                       tag_action,
4361                       /*data_ptr*/ data_ptr,
4362                       /*dxfer_len*/ dxfer_len,
4363                       sense_len,
4364                       sizeof(*scsi_cmd),
4365                       timeout);
4366 }
4367
4368
4369 void
4370 scsi_read_dvd_structure(struct ccb_scsiio *csio, u_int32_t retries,
4371                         void (*cbfcnp)(struct cam_periph *, union ccb *),
4372                         u_int8_t tag_action, u_int32_t address,
4373                         u_int8_t layer_number, u_int8_t format, u_int8_t agid,
4374                         u_int8_t *data_ptr, u_int32_t dxfer_len,
4375                         u_int8_t sense_len, u_int32_t timeout)
4376 {
4377         struct scsi_read_dvd_structure *scsi_cmd;
4378
4379         scsi_cmd = (struct scsi_read_dvd_structure *)&csio->cdb_io.cdb_bytes;
4380         bzero(scsi_cmd, sizeof(*scsi_cmd));
4381         scsi_cmd->opcode = READ_DVD_STRUCTURE;
4382
4383         scsi_ulto4b(address, scsi_cmd->address);
4384         scsi_cmd->layer_number = layer_number;
4385         scsi_cmd->format = format;
4386         scsi_ulto2b(dxfer_len, scsi_cmd->alloc_len);
4387         /* The AGID is the top two bits of this byte */
4388         scsi_cmd->agid = agid << 6;
4389
4390         cam_fill_csio(csio,
4391                       retries,
4392                       cbfcnp,
4393                       /*flags*/ CAM_DIR_IN,
4394                       tag_action,
4395                       /*data_ptr*/ data_ptr,
4396                       /*dxfer_len*/ dxfer_len,
4397                       sense_len,
4398                       sizeof(*scsi_cmd),
4399                       timeout);
4400 }