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