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