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