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