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