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