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