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