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