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