]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cam/scsi/scsi_cd.c
openssh: cherry-pick OpenSSL 1.1.1 compatibility
[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     nocopyout, 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         nocopyout = 0;
1360         switch (cmd) {
1361
1362         case CDIOCPLAYTRACKS:
1363                 {
1364                         struct ioc_play_track *args
1365                             = (struct ioc_play_track *) addr;
1366                         struct cd_mode_params params;
1367                         union cd_pages *page;
1368
1369                         params.alloc_len = sizeof(union cd_mode_data_6_10);
1370                         params.mode_buf = malloc(params.alloc_len, M_SCSICD,
1371                                                  M_WAITOK | M_ZERO);
1372
1373                         cam_periph_lock(periph);
1374                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
1375                                   ("trying to do CDIOCPLAYTRACKS\n"));
1376
1377                         error = cdgetmode(periph, &params, AUDIO_PAGE);
1378                         if (error) {
1379                                 free(params.mode_buf, M_SCSICD);
1380                                 cam_periph_unlock(periph);
1381                                 break;
1382                         }
1383                         page = cdgetpage(&params);
1384
1385                         page->audio.flags &= ~CD_PA_SOTC;
1386                         page->audio.flags |= CD_PA_IMMED;
1387                         error = cdsetmode(periph, &params);
1388                         free(params.mode_buf, M_SCSICD);
1389                         if (error) {
1390                                 cam_periph_unlock(periph);
1391                                 break;
1392                         }
1393
1394                         /*
1395                          * This was originally implemented with the PLAY
1396                          * AUDIO TRACK INDEX command, but that command was
1397                          * deprecated after SCSI-2.  Most (all?) SCSI CDROM
1398                          * drives support it but ATAPI and ATAPI-derivative
1399                          * drives don't seem to support it.  So we keep a
1400                          * cache of the table of contents and translate
1401                          * track numbers to MSF format.
1402                          */
1403                         if (softc->flags & CD_FLAG_VALID_TOC) {
1404                                 union msf_lba *sentry, *eentry;
1405                                 int st, et;
1406
1407                                 if (args->end_track <
1408                                     softc->toc.header.ending_track + 1)
1409                                         args->end_track++;
1410                                 if (args->end_track >
1411                                     softc->toc.header.ending_track + 1)
1412                                         args->end_track =
1413                                             softc->toc.header.ending_track + 1;
1414                                 st = args->start_track -
1415                                         softc->toc.header.starting_track;
1416                                 et = args->end_track -
1417                                         softc->toc.header.starting_track;
1418                                 if ((st < 0)
1419                                  || (et < 0)
1420                                  || (st > (softc->toc.header.ending_track -
1421                                      softc->toc.header.starting_track))) {
1422                                         error = EINVAL;
1423                                         cam_periph_unlock(periph);
1424                                         break;
1425                                 }
1426                                 sentry = &softc->toc.entries[st].addr;
1427                                 eentry = &softc->toc.entries[et].addr;
1428                                 error = cdplaymsf(periph,
1429                                                   sentry->msf.minute,
1430                                                   sentry->msf.second,
1431                                                   sentry->msf.frame,
1432                                                   eentry->msf.minute,
1433                                                   eentry->msf.second,
1434                                                   eentry->msf.frame);
1435                         } else {
1436                                 /*
1437                                  * If we don't have a valid TOC, try the
1438                                  * play track index command.  It is part of
1439                                  * the SCSI-2 spec, but was removed in the
1440                                  * MMC specs.  ATAPI and ATAPI-derived
1441                                  * drives don't support it.
1442                                  */
1443                                 if (softc->quirks & CD_Q_BCD_TRACKS) {
1444                                         args->start_track =
1445                                                 bin2bcd(args->start_track);
1446                                         args->end_track =
1447                                                 bin2bcd(args->end_track);
1448                                 }
1449                                 error = cdplaytracks(periph,
1450                                                      args->start_track,
1451                                                      args->start_index,
1452                                                      args->end_track,
1453                                                      args->end_index);
1454                         }
1455                         cam_periph_unlock(periph);
1456                 }
1457                 break;
1458         case CDIOCPLAYMSF:
1459                 {
1460                         struct ioc_play_msf *args
1461                                 = (struct ioc_play_msf *) addr;
1462                         struct cd_mode_params params;
1463                         union cd_pages *page;
1464
1465                         params.alloc_len = sizeof(union cd_mode_data_6_10);
1466                         params.mode_buf = malloc(params.alloc_len, M_SCSICD,
1467                                                  M_WAITOK | M_ZERO);
1468
1469                         cam_periph_lock(periph);
1470                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
1471                                   ("trying to do CDIOCPLAYMSF\n"));
1472
1473                         error = cdgetmode(periph, &params, AUDIO_PAGE);
1474                         if (error) {
1475                                 free(params.mode_buf, M_SCSICD);
1476                                 cam_periph_unlock(periph);
1477                                 break;
1478                         }
1479                         page = cdgetpage(&params);
1480
1481                         page->audio.flags &= ~CD_PA_SOTC;
1482                         page->audio.flags |= CD_PA_IMMED;
1483                         error = cdsetmode(periph, &params);
1484                         free(params.mode_buf, M_SCSICD);
1485                         if (error) {
1486                                 cam_periph_unlock(periph);
1487                                 break;
1488                         }
1489                         error = cdplaymsf(periph,
1490                                           args->start_m,
1491                                           args->start_s,
1492                                           args->start_f,
1493                                           args->end_m,
1494                                           args->end_s,
1495                                           args->end_f);
1496                         cam_periph_unlock(periph);
1497                 }
1498                 break;
1499         case CDIOCPLAYBLOCKS:
1500                 {
1501                         struct ioc_play_blocks *args
1502                                 = (struct ioc_play_blocks *) addr;
1503                         struct cd_mode_params params;
1504                         union cd_pages *page;
1505
1506                         params.alloc_len = sizeof(union cd_mode_data_6_10);
1507                         params.mode_buf = malloc(params.alloc_len, M_SCSICD,
1508                                                  M_WAITOK | M_ZERO);
1509
1510                         cam_periph_lock(periph);
1511                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
1512                                   ("trying to do CDIOCPLAYBLOCKS\n"));
1513
1514
1515                         error = cdgetmode(periph, &params, AUDIO_PAGE);
1516                         if (error) {
1517                                 free(params.mode_buf, M_SCSICD);
1518                                 cam_periph_unlock(periph);
1519                                 break;
1520                         }
1521                         page = cdgetpage(&params);
1522
1523                         page->audio.flags &= ~CD_PA_SOTC;
1524                         page->audio.flags |= CD_PA_IMMED;
1525                         error = cdsetmode(periph, &params);
1526                         free(params.mode_buf, M_SCSICD);
1527                         if (error) {
1528                                 cam_periph_unlock(periph);
1529                                 break;
1530                         }
1531                         error = cdplay(periph, args->blk, args->len);
1532                         cam_periph_unlock(periph);
1533                 }
1534                 break;
1535         case CDIOCREADSUBCHANNEL_SYSSPACE:
1536                 nocopyout = 1;
1537                 /* Fallthrough */
1538         case CDIOCREADSUBCHANNEL:
1539                 {
1540                         struct ioc_read_subchannel *args
1541                                 = (struct ioc_read_subchannel *) addr;
1542                         struct cd_sub_channel_info *data;
1543                         u_int32_t len = args->data_len;
1544
1545                         data = malloc(sizeof(struct cd_sub_channel_info), 
1546                                       M_SCSICD, M_WAITOK | M_ZERO);
1547
1548                         cam_periph_lock(periph);
1549                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
1550                                   ("trying to do CDIOCREADSUBCHANNEL\n"));
1551
1552                         if ((len > sizeof(struct cd_sub_channel_info)) ||
1553                             (len < sizeof(struct cd_sub_channel_header))) {
1554                                 printf(
1555                                         "scsi_cd: cdioctl: "
1556                                         "cdioreadsubchannel: error, len=%d\n",
1557                                         len);
1558                                 error = EINVAL;
1559                                 free(data, M_SCSICD);
1560                                 cam_periph_unlock(periph);
1561                                 break;
1562                         }
1563
1564                         if (softc->quirks & CD_Q_BCD_TRACKS)
1565                                 args->track = bin2bcd(args->track);
1566
1567                         error = cdreadsubchannel(periph, args->address_format,
1568                                 args->data_format, args->track, data, len);
1569
1570                         if (error) {
1571                                 free(data, M_SCSICD);
1572                                 cam_periph_unlock(periph);
1573                                 break;
1574                         }
1575                         if (softc->quirks & CD_Q_BCD_TRACKS)
1576                                 data->what.track_info.track_number =
1577                                     bcd2bin(data->what.track_info.track_number);
1578                         len = min(len, ((data->header.data_len[0] << 8) +
1579                                 data->header.data_len[1] +
1580                                 sizeof(struct cd_sub_channel_header)));
1581                         cam_periph_unlock(periph);
1582                         if (nocopyout == 0) {
1583                                 if (copyout(data, args->data, len) != 0) {
1584                                         error = EFAULT;
1585                                 }
1586                         } else {
1587                                 bcopy(data, args->data, len);
1588                         }
1589                         free(data, M_SCSICD);
1590                 }
1591                 break;
1592
1593         case CDIOREADTOCHEADER:
1594                 {
1595                         struct ioc_toc_header *th;
1596
1597                         th = malloc(sizeof(struct ioc_toc_header), M_SCSICD,
1598                                     M_WAITOK | M_ZERO);
1599
1600                         cam_periph_lock(periph);
1601                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
1602                                   ("trying to do CDIOREADTOCHEADER\n"));
1603
1604                         error = cdreadtoc(periph, 0, 0, (u_int8_t *)th, 
1605                                           sizeof (*th), /*sense_flags*/SF_NO_PRINT);
1606                         if (error) {
1607                                 free(th, M_SCSICD);
1608                                 cam_periph_unlock(periph);
1609                                 break;
1610                         }
1611                         if (softc->quirks & CD_Q_BCD_TRACKS) {
1612                                 /* we are going to have to convert the BCD
1613                                  * encoding on the cd to what is expected
1614                                  */
1615                                 th->starting_track = 
1616                                         bcd2bin(th->starting_track);
1617                                 th->ending_track = bcd2bin(th->ending_track);
1618                         }
1619                         th->len = ntohs(th->len);
1620                         bcopy(th, addr, sizeof(*th));
1621                         free(th, M_SCSICD);
1622                         cam_periph_unlock(periph);
1623                 }
1624                 break;
1625         case CDIOREADTOCENTRYS:
1626 #ifdef COMPAT_FREEBSD32
1627         case CDIOREADTOCENTRYS_32:
1628 #endif
1629                 {
1630                         struct cd_tocdata *data;
1631                         struct cd_toc_single *lead;
1632                         struct ioc_read_toc_entry *te =
1633                                 (struct ioc_read_toc_entry *) addr;
1634                         struct ioc_toc_header *th;
1635                         u_int32_t len, readlen, idx, num;
1636                         u_int32_t starting_track = te->starting_track;
1637
1638                         data = malloc(sizeof(*data), M_SCSICD, M_WAITOK | M_ZERO);
1639                         lead = malloc(sizeof(*lead), M_SCSICD, M_WAITOK | M_ZERO);
1640
1641                         cam_periph_lock(periph);
1642                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
1643                                   ("trying to do CDIOREADTOCENTRYS\n"));
1644
1645                         if (te->data_len < sizeof(struct cd_toc_entry)
1646                          || (te->data_len % sizeof(struct cd_toc_entry)) != 0
1647                          || (te->address_format != CD_MSF_FORMAT
1648                           && te->address_format != CD_LBA_FORMAT)) {
1649                                 error = EINVAL;
1650                                 printf("scsi_cd: error in readtocentries, "
1651                                        "returning EINVAL\n");
1652                                 free(data, M_SCSICD);
1653                                 free(lead, M_SCSICD);
1654                                 cam_periph_unlock(periph);
1655                                 break;
1656                         }
1657
1658                         th = &data->header;
1659                         error = cdreadtoc(periph, 0, 0, (u_int8_t *)th, 
1660                                           sizeof (*th), /*sense_flags*/0);
1661                         if (error) {
1662                                 free(data, M_SCSICD);
1663                                 free(lead, M_SCSICD);
1664                                 cam_periph_unlock(periph);
1665                                 break;
1666                         }
1667
1668                         if (softc->quirks & CD_Q_BCD_TRACKS) {
1669                                 /* we are going to have to convert the BCD
1670                                  * encoding on the cd to what is expected
1671                                  */
1672                                 th->starting_track =
1673                                     bcd2bin(th->starting_track);
1674                                 th->ending_track = bcd2bin(th->ending_track);
1675                         }
1676
1677                         if (starting_track == 0)
1678                                 starting_track = th->starting_track;
1679                         else if (starting_track == LEADOUT)
1680                                 starting_track = th->ending_track + 1;
1681                         else if (starting_track < th->starting_track ||
1682                                  starting_track > th->ending_track + 1) {
1683                                 printf("scsi_cd: error in readtocentries, "
1684                                        "returning EINVAL\n");
1685                                 free(data, M_SCSICD);
1686                                 free(lead, M_SCSICD);
1687                                 cam_periph_unlock(periph);
1688                                 error = EINVAL;
1689                                 break;
1690                         }
1691
1692                         /* calculate reading length without leadout entry */
1693                         readlen = (th->ending_track - starting_track + 1) *
1694                                   sizeof(struct cd_toc_entry);
1695
1696                         /* and with leadout entry */
1697                         len = readlen + sizeof(struct cd_toc_entry);
1698                         if (te->data_len < len) {
1699                                 len = te->data_len;
1700                                 if (readlen > len)
1701                                         readlen = len;
1702                         }
1703                         if (len > sizeof(data->entries)) {
1704                                 printf("scsi_cd: error in readtocentries, "
1705                                        "returning EINVAL\n");
1706                                 error = EINVAL;
1707                                 free(data, M_SCSICD);
1708                                 free(lead, M_SCSICD);
1709                                 cam_periph_unlock(periph);
1710                                 break;
1711                         }
1712                         num = len / sizeof(struct cd_toc_entry);
1713
1714                         if (readlen > 0) {
1715                                 error = cdreadtoc(periph, te->address_format,
1716                                                   starting_track,
1717                                                   (u_int8_t *)data,
1718                                                   readlen + sizeof (*th),
1719                                                   /*sense_flags*/0);
1720                                 if (error) {
1721                                         free(data, M_SCSICD);
1722                                         free(lead, M_SCSICD);
1723                                         cam_periph_unlock(periph);
1724                                         break;
1725                                 }
1726                         }
1727
1728                         /* make leadout entry if needed */
1729                         idx = starting_track + num - 1;
1730                         if (softc->quirks & CD_Q_BCD_TRACKS)
1731                                 th->ending_track = bcd2bin(th->ending_track);
1732                         if (idx == th->ending_track + 1) {
1733                                 error = cdreadtoc(periph, te->address_format,
1734                                                   LEADOUT, (u_int8_t *)lead,
1735                                                   sizeof(*lead),
1736                                                   /*sense_flags*/0);
1737                                 if (error) {
1738                                         free(data, M_SCSICD);
1739                                         free(lead, M_SCSICD);
1740                                         cam_periph_unlock(periph);
1741                                         break;
1742                                 }
1743                                 data->entries[idx - starting_track] = 
1744                                         lead->entry;
1745                         }
1746                         if (softc->quirks & CD_Q_BCD_TRACKS) {
1747                                 for (idx = 0; idx < num - 1; idx++) {
1748                                         data->entries[idx].track =
1749                                             bcd2bin(data->entries[idx].track);
1750                                 }
1751                         }
1752
1753                         cam_periph_unlock(periph);
1754                         error = copyout(data->entries, te_data_get_ptr(te, cmd),
1755                             len);
1756                         free(data, M_SCSICD);
1757                         free(lead, M_SCSICD);
1758                 }
1759                 break;
1760         case CDIOREADTOCENTRY:
1761                 {
1762                         struct cd_toc_single *data;
1763                         struct ioc_read_toc_single_entry *te =
1764                                 (struct ioc_read_toc_single_entry *) addr;
1765                         struct ioc_toc_header *th;
1766                         u_int32_t track;
1767
1768                         data = malloc(sizeof(*data), M_SCSICD, M_WAITOK | M_ZERO);
1769
1770                         cam_periph_lock(periph);
1771                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
1772                                   ("trying to do CDIOREADTOCENTRY\n"));
1773
1774                         if (te->address_format != CD_MSF_FORMAT
1775                             && te->address_format != CD_LBA_FORMAT) {
1776                                 printf("error in readtocentry, "
1777                                        " returning EINVAL\n");
1778                                 free(data, M_SCSICD);
1779                                 error = EINVAL;
1780                                 cam_periph_unlock(periph);
1781                                 break;
1782                         }
1783
1784                         th = &data->header;
1785                         error = cdreadtoc(periph, 0, 0, (u_int8_t *)th,
1786                                           sizeof (*th), /*sense_flags*/0);
1787                         if (error) {
1788                                 free(data, M_SCSICD);
1789                                 cam_periph_unlock(periph);
1790                                 break;
1791                         }
1792
1793                         if (softc->quirks & CD_Q_BCD_TRACKS) {
1794                                 /* we are going to have to convert the BCD
1795                                  * encoding on the cd to what is expected
1796                                  */
1797                                 th->starting_track =
1798                                     bcd2bin(th->starting_track);
1799                                 th->ending_track = bcd2bin(th->ending_track);
1800                         }
1801                         track = te->track;
1802                         if (track == 0)
1803                                 track = th->starting_track;
1804                         else if (track == LEADOUT)
1805                                 /* OK */;
1806                         else if (track < th->starting_track ||
1807                                  track > th->ending_track + 1) {
1808                                 printf("error in readtocentry, "
1809                                        " returning EINVAL\n");
1810                                 free(data, M_SCSICD);
1811                                 error = EINVAL;
1812                                 cam_periph_unlock(periph);
1813                                 break;
1814                         }
1815
1816                         error = cdreadtoc(periph, te->address_format, track,
1817                                           (u_int8_t *)data, sizeof(*data),
1818                                           /*sense_flags*/0);
1819                         if (error) {
1820                                 free(data, M_SCSICD);
1821                                 cam_periph_unlock(periph);
1822                                 break;
1823                         }
1824
1825                         if (softc->quirks & CD_Q_BCD_TRACKS)
1826                                 data->entry.track = bcd2bin(data->entry.track);
1827                         bcopy(&data->entry, &te->entry,
1828                               sizeof(struct cd_toc_entry));
1829                         free(data, M_SCSICD);
1830                         cam_periph_unlock(periph);
1831                 }
1832                 break;
1833         case CDIOCSETPATCH:
1834                 {
1835                         struct ioc_patch *arg = (struct ioc_patch *)addr;
1836                         struct cd_mode_params params;
1837                         union cd_pages *page;
1838
1839                         params.alloc_len = sizeof(union cd_mode_data_6_10);
1840                         params.mode_buf = malloc(params.alloc_len, M_SCSICD, 
1841                                                  M_WAITOK | M_ZERO);
1842
1843                         cam_periph_lock(periph);
1844                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
1845                                   ("trying to do CDIOCSETPATCH\n"));
1846
1847                         error = cdgetmode(periph, &params, AUDIO_PAGE);
1848                         if (error) {
1849                                 free(params.mode_buf, M_SCSICD);
1850                                 cam_periph_unlock(periph);
1851                                 break;
1852                         }
1853                         page = cdgetpage(&params);
1854
1855                         page->audio.port[LEFT_PORT].channels = 
1856                                 arg->patch[0];
1857                         page->audio.port[RIGHT_PORT].channels = 
1858                                 arg->patch[1];
1859                         page->audio.port[2].channels = arg->patch[2];
1860                         page->audio.port[3].channels = arg->patch[3];
1861                         error = cdsetmode(periph, &params);
1862                         free(params.mode_buf, M_SCSICD);
1863                         cam_periph_unlock(periph);
1864                 }
1865                 break;
1866         case CDIOCGETVOL:
1867                 {
1868                         struct ioc_vol *arg = (struct ioc_vol *) addr;
1869                         struct cd_mode_params params;
1870                         union cd_pages *page;
1871
1872                         params.alloc_len = sizeof(union cd_mode_data_6_10);
1873                         params.mode_buf = malloc(params.alloc_len, M_SCSICD, 
1874                                                  M_WAITOK | M_ZERO);
1875
1876                         cam_periph_lock(periph);
1877                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
1878                                   ("trying to do CDIOCGETVOL\n"));
1879
1880                         error = cdgetmode(periph, &params, AUDIO_PAGE);
1881                         if (error) {
1882                                 free(params.mode_buf, M_SCSICD);
1883                                 cam_periph_unlock(periph);
1884                                 break;
1885                         }
1886                         page = cdgetpage(&params);
1887
1888                         arg->vol[LEFT_PORT] = 
1889                                 page->audio.port[LEFT_PORT].volume;
1890                         arg->vol[RIGHT_PORT] = 
1891                                 page->audio.port[RIGHT_PORT].volume;
1892                         arg->vol[2] = page->audio.port[2].volume;
1893                         arg->vol[3] = page->audio.port[3].volume;
1894                         free(params.mode_buf, M_SCSICD);
1895                         cam_periph_unlock(periph);
1896                 }
1897                 break;
1898         case CDIOCSETVOL:
1899                 {
1900                         struct ioc_vol *arg = (struct ioc_vol *) addr;
1901                         struct cd_mode_params params;
1902                         union cd_pages *page;
1903
1904                         params.alloc_len = sizeof(union cd_mode_data_6_10);
1905                         params.mode_buf = malloc(params.alloc_len, M_SCSICD, 
1906                                                  M_WAITOK | M_ZERO);
1907
1908                         cam_periph_lock(periph);
1909                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
1910                                   ("trying to do CDIOCSETVOL\n"));
1911
1912                         error = cdgetmode(periph, &params, AUDIO_PAGE);
1913                         if (error) {
1914                                 free(params.mode_buf, M_SCSICD);
1915                                 cam_periph_unlock(periph);
1916                                 break;
1917                         }
1918                         page = cdgetpage(&params);
1919
1920                         page->audio.port[LEFT_PORT].channels = CHANNEL_0;
1921                         page->audio.port[LEFT_PORT].volume = 
1922                                 arg->vol[LEFT_PORT];
1923                         page->audio.port[RIGHT_PORT].channels = CHANNEL_1;
1924                         page->audio.port[RIGHT_PORT].volume = 
1925                                 arg->vol[RIGHT_PORT];
1926                         page->audio.port[2].volume = arg->vol[2];
1927                         page->audio.port[3].volume = arg->vol[3];
1928                         error = cdsetmode(periph, &params);
1929                         cam_periph_unlock(periph);
1930                         free(params.mode_buf, M_SCSICD);
1931                 }
1932                 break;
1933         case CDIOCSETMONO:
1934                 {
1935                         struct cd_mode_params params;
1936                         union cd_pages *page;
1937
1938                         params.alloc_len = sizeof(union cd_mode_data_6_10);
1939                         params.mode_buf = malloc(params.alloc_len, M_SCSICD,
1940                                                  M_WAITOK | M_ZERO);
1941
1942                         cam_periph_lock(periph);
1943                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
1944                                   ("trying to do CDIOCSETMONO\n"));
1945
1946                         error = cdgetmode(periph, &params, AUDIO_PAGE);
1947                         if (error) {
1948                                 free(params.mode_buf, M_SCSICD);
1949                                 cam_periph_unlock(periph);
1950                                 break;
1951                         }
1952                         page = cdgetpage(&params);
1953
1954                         page->audio.port[LEFT_PORT].channels = 
1955                                 LEFT_CHANNEL | RIGHT_CHANNEL;
1956                         page->audio.port[RIGHT_PORT].channels = 
1957                                 LEFT_CHANNEL | RIGHT_CHANNEL;
1958                         page->audio.port[2].channels = 0;
1959                         page->audio.port[3].channels = 0;
1960                         error = cdsetmode(periph, &params);
1961                         cam_periph_unlock(periph);
1962                         free(params.mode_buf, M_SCSICD);
1963                 }
1964                 break;
1965         case CDIOCSETSTEREO:
1966                 {
1967                         struct cd_mode_params params;
1968                         union cd_pages *page;
1969
1970                         params.alloc_len = sizeof(union cd_mode_data_6_10);
1971                         params.mode_buf = malloc(params.alloc_len, M_SCSICD,
1972                                                  M_WAITOK | M_ZERO);
1973
1974                         cam_periph_lock(periph);
1975                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
1976                                   ("trying to do CDIOCSETSTEREO\n"));
1977
1978                         error = cdgetmode(periph, &params, AUDIO_PAGE);
1979                         if (error) {
1980                                 free(params.mode_buf, M_SCSICD);
1981                                 cam_periph_unlock(periph);
1982                                 break;
1983                         }
1984                         page = cdgetpage(&params);
1985
1986                         page->audio.port[LEFT_PORT].channels = 
1987                                 LEFT_CHANNEL;
1988                         page->audio.port[RIGHT_PORT].channels = 
1989                                 RIGHT_CHANNEL;
1990                         page->audio.port[2].channels = 0;
1991                         page->audio.port[3].channels = 0;
1992                         error = cdsetmode(periph, &params);
1993                         free(params.mode_buf, M_SCSICD);
1994                         cam_periph_unlock(periph);
1995                 }
1996                 break;
1997         case CDIOCSETMUTE:
1998                 {
1999                         struct cd_mode_params params;
2000                         union cd_pages *page;
2001
2002                         params.alloc_len = sizeof(union cd_mode_data_6_10);
2003                         params.mode_buf = malloc(params.alloc_len, M_SCSICD,
2004                                                  M_WAITOK | M_ZERO);
2005
2006                         cam_periph_lock(periph);
2007                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2008                                   ("trying to do CDIOCSETMUTE\n"));
2009
2010                         error = cdgetmode(periph, &params, AUDIO_PAGE);
2011                         if (error) {
2012                                 free(params.mode_buf, M_SCSICD);
2013                                 cam_periph_unlock(periph);
2014                                 break;
2015                         }
2016                         page = cdgetpage(&params);
2017
2018                         page->audio.port[LEFT_PORT].channels = 0;
2019                         page->audio.port[RIGHT_PORT].channels = 0;
2020                         page->audio.port[2].channels = 0;
2021                         page->audio.port[3].channels = 0;
2022                         error = cdsetmode(periph, &params);
2023                         free(params.mode_buf, M_SCSICD);
2024                         cam_periph_unlock(periph);
2025                 }
2026                 break;
2027         case CDIOCSETLEFT:
2028                 {
2029                         struct cd_mode_params params;
2030                         union cd_pages *page;
2031
2032                         params.alloc_len = sizeof(union cd_mode_data_6_10);
2033                         params.mode_buf = malloc(params.alloc_len, M_SCSICD,
2034                                                  M_WAITOK | M_ZERO);
2035
2036                         cam_periph_lock(periph);
2037                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2038                                   ("trying to do CDIOCSETLEFT\n"));
2039
2040                         error = cdgetmode(periph, &params, AUDIO_PAGE);
2041                         if (error) {
2042                                 free(params.mode_buf, M_SCSICD);
2043                                 cam_periph_unlock(periph);
2044                                 break;
2045                         }
2046                         page = cdgetpage(&params);
2047
2048                         page->audio.port[LEFT_PORT].channels = LEFT_CHANNEL;
2049                         page->audio.port[RIGHT_PORT].channels = LEFT_CHANNEL;
2050                         page->audio.port[2].channels = 0;
2051                         page->audio.port[3].channels = 0;
2052                         error = cdsetmode(periph, &params);
2053                         free(params.mode_buf, M_SCSICD);
2054                         cam_periph_unlock(periph);
2055                 }
2056                 break;
2057         case CDIOCSETRIGHT:
2058                 {
2059                         struct cd_mode_params params;
2060                         union cd_pages *page;
2061
2062                         params.alloc_len = sizeof(union cd_mode_data_6_10);
2063                         params.mode_buf = malloc(params.alloc_len, M_SCSICD,
2064                                                  M_WAITOK | M_ZERO);
2065
2066                         cam_periph_lock(periph);
2067                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2068                                   ("trying to do CDIOCSETRIGHT\n"));
2069
2070                         error = cdgetmode(periph, &params, AUDIO_PAGE);
2071                         if (error) {
2072                                 free(params.mode_buf, M_SCSICD);
2073                                 cam_periph_unlock(periph);
2074                                 break;
2075                         }
2076                         page = cdgetpage(&params);
2077
2078                         page->audio.port[LEFT_PORT].channels = RIGHT_CHANNEL;
2079                         page->audio.port[RIGHT_PORT].channels = RIGHT_CHANNEL;
2080                         page->audio.port[2].channels = 0;
2081                         page->audio.port[3].channels = 0;
2082                         error = cdsetmode(periph, &params);
2083                         free(params.mode_buf, M_SCSICD);
2084                         cam_periph_unlock(periph);
2085                 }
2086                 break;
2087         case CDIOCRESUME:
2088                 cam_periph_lock(periph);
2089                 error = cdpause(periph, 1);
2090                 cam_periph_unlock(periph);
2091                 break;
2092         case CDIOCPAUSE:
2093                 cam_periph_lock(periph);
2094                 error = cdpause(periph, 0);
2095                 cam_periph_unlock(periph);
2096                 break;
2097         case CDIOCSTART:
2098                 cam_periph_lock(periph);
2099                 error = cdstartunit(periph, 0);
2100                 cam_periph_unlock(periph);
2101                 break;
2102         case CDIOCCLOSE:
2103                 cam_periph_lock(periph);
2104                 error = cdstartunit(periph, 1);
2105                 cam_periph_unlock(periph);
2106                 break;
2107         case CDIOCSTOP:
2108                 cam_periph_lock(periph);
2109                 error = cdstopunit(periph, 0);
2110                 cam_periph_unlock(periph);
2111                 break;
2112         case CDIOCEJECT:
2113                 cam_periph_lock(periph);
2114                 error = cdstopunit(periph, 1);
2115                 cam_periph_unlock(periph);
2116                 break;
2117         case CDIOCALLOW:
2118                 cam_periph_lock(periph);
2119                 cdprevent(periph, PR_ALLOW);
2120                 cam_periph_unlock(periph);
2121                 break;
2122         case CDIOCPREVENT:
2123                 cam_periph_lock(periph);
2124                 cdprevent(periph, PR_PREVENT);
2125                 cam_periph_unlock(periph);
2126                 break;
2127         case CDIOCSETDEBUG:
2128                 /* sc_link->flags |= (SDEV_DB1 | SDEV_DB2); */
2129                 error = ENOTTY;
2130                 break;
2131         case CDIOCCLRDEBUG:
2132                 /* sc_link->flags &= ~(SDEV_DB1 | SDEV_DB2); */
2133                 error = ENOTTY;
2134                 break;
2135         case CDIOCRESET:
2136                 /* return (cd_reset(periph)); */
2137                 error = ENOTTY;
2138                 break;
2139         case CDRIOCREADSPEED:
2140                 cam_periph_lock(periph);
2141                 error = cdsetspeed(periph, *(u_int32_t *)addr, CDR_MAX_SPEED);
2142                 cam_periph_unlock(periph);
2143                 break;
2144         case CDRIOCWRITESPEED:
2145                 cam_periph_lock(periph);
2146                 error = cdsetspeed(periph, CDR_MAX_SPEED, *(u_int32_t *)addr);
2147                 cam_periph_unlock(periph);
2148                 break;
2149         case CDRIOCGETBLOCKSIZE:
2150                 *(int *)addr = softc->params.blksize;
2151                 break;
2152         case CDRIOCSETBLOCKSIZE:
2153                 if (*(int *)addr <= 0) {
2154                         error = EINVAL;
2155                         break;
2156                 }
2157                 softc->disk->d_sectorsize = softc->params.blksize = *(int *)addr;
2158                 break;
2159         case DVDIOCSENDKEY:
2160         case DVDIOCREPORTKEY: {
2161                 struct dvd_authinfo *authinfo;
2162
2163                 authinfo = (struct dvd_authinfo *)addr;
2164
2165                 if (cmd == DVDIOCREPORTKEY)
2166                         error = cdreportkey(periph, authinfo);
2167                 else
2168                         error = cdsendkey(periph, authinfo);
2169                 break;
2170                 }
2171         case DVDIOCREADSTRUCTURE: {
2172                 struct dvd_struct *dvdstruct;
2173
2174                 dvdstruct = (struct dvd_struct *)addr;
2175
2176                 error = cdreaddvdstructure(periph, dvdstruct);
2177
2178                 break;
2179         }
2180         default:
2181                 cam_periph_lock(periph);
2182                 error = cam_periph_ioctl(periph, cmd, addr, cderror);
2183                 cam_periph_unlock(periph);
2184                 break;
2185         }
2186
2187         cam_periph_lock(periph);
2188         cam_periph_unhold(periph);
2189         
2190         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("leaving cdioctl\n"));
2191         if (error && bootverbose) {
2192                 printf("scsi_cd.c::ioctl cmd=%08lx error=%d\n", cmd, error);
2193         }
2194         cam_periph_unlock(periph);
2195
2196         return (error);
2197 }
2198
2199 static void
2200 cdprevent(struct cam_periph *periph, int action)
2201 {
2202         union   ccb *ccb;
2203         struct  cd_softc *softc;
2204         int     error;
2205
2206         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdprevent\n"));
2207
2208         softc = (struct cd_softc *)periph->softc;
2209         
2210         if (((action == PR_ALLOW)
2211           && (softc->flags & CD_FLAG_DISC_LOCKED) == 0)
2212          || ((action == PR_PREVENT)
2213           && (softc->flags & CD_FLAG_DISC_LOCKED) != 0)) {
2214                 return;
2215         }
2216             
2217         ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
2218
2219         scsi_prevent(&ccb->csio, 
2220                      /*retries*/ cd_retry_count,
2221                      /*cbfcnp*/NULL,
2222                      MSG_SIMPLE_Q_TAG,
2223                      action,
2224                      SSD_FULL_SIZE,
2225                      /* timeout */60000);
2226         
2227         error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
2228                         /*sense_flags*/SF_RETRY_UA|SF_NO_PRINT);
2229
2230         xpt_release_ccb(ccb);
2231
2232         if (error == 0) {
2233                 if (action == PR_ALLOW)
2234                         softc->flags &= ~CD_FLAG_DISC_LOCKED;
2235                 else
2236                         softc->flags |= CD_FLAG_DISC_LOCKED;
2237         }
2238 }
2239
2240 /*
2241  * XXX: the disk media and sector size is only really able to change
2242  * XXX: while the device is closed.
2243  */
2244 static int
2245 cdcheckmedia(struct cam_periph *periph)
2246 {
2247         struct cd_softc *softc;
2248         struct ioc_toc_header *toch;
2249         struct cd_toc_single leadout;
2250         u_int32_t size, toclen;
2251         int error, num_entries, cdindex;
2252
2253         softc = (struct cd_softc *)periph->softc;
2254
2255         cdprevent(periph, PR_PREVENT);
2256         softc->disk->d_sectorsize = 2048;
2257         softc->disk->d_mediasize = 0;
2258
2259         /*
2260          * Get the disc size and block size.  If we can't get it, we don't
2261          * have media, most likely.
2262          */
2263         if ((error = cdsize(periph, &size)) != 0) {
2264                 softc->flags &= ~(CD_FLAG_VALID_MEDIA|CD_FLAG_VALID_TOC);
2265                 cdprevent(periph, PR_ALLOW);
2266                 return (error);
2267         } else {
2268                 softc->flags |= CD_FLAG_SAW_MEDIA | CD_FLAG_VALID_MEDIA;
2269                 softc->disk->d_sectorsize = softc->params.blksize;
2270                 softc->disk->d_mediasize =
2271                     (off_t)softc->params.blksize * softc->params.disksize;
2272         }
2273
2274         /*
2275          * Now we check the table of contents.  This (currently) is only
2276          * used for the CDIOCPLAYTRACKS ioctl.  It may be used later to do
2277          * things like present a separate entry in /dev for each track,
2278          * like that acd(4) driver does.
2279          */
2280         bzero(&softc->toc, sizeof(softc->toc));
2281         toch = &softc->toc.header;
2282         /*
2283          * We will get errors here for media that doesn't have a table of
2284          * contents.  According to the MMC-3 spec: "When a Read TOC/PMA/ATIP
2285          * command is presented for a DDCD/CD-R/RW media, where the first TOC
2286          * has not been recorded (no complete session) and the Format codes
2287          * 0000b, 0001b, or 0010b are specified, this command shall be rejected
2288          * with an INVALID FIELD IN CDB.  Devices that are not capable of
2289          * reading an incomplete session on DDC/CD-R/RW media shall report
2290          * CANNOT READ MEDIUM - INCOMPATIBLE FORMAT."
2291          *
2292          * So this isn't fatal if we can't read the table of contents, it
2293          * just means that the user won't be able to issue the play tracks
2294          * ioctl, and likely lots of other stuff won't work either.  They
2295          * need to burn the CD before we can do a whole lot with it.  So
2296          * we don't print anything here if we get an error back.
2297          */
2298         error = cdreadtoc(periph, 0, 0, (u_int8_t *)toch, sizeof(*toch),
2299                           SF_NO_PRINT);
2300         /*
2301          * Errors in reading the table of contents aren't fatal, we just
2302          * won't have a valid table of contents cached.
2303          */
2304         if (error != 0) {
2305                 error = 0;
2306                 bzero(&softc->toc, sizeof(softc->toc));
2307                 goto bailout;
2308         }
2309
2310         if (softc->quirks & CD_Q_BCD_TRACKS) {
2311                 toch->starting_track = bcd2bin(toch->starting_track);
2312                 toch->ending_track = bcd2bin(toch->ending_track);
2313         }
2314
2315         /* Number of TOC entries, plus leadout */
2316         num_entries = (toch->ending_track - toch->starting_track) + 2;
2317
2318         if (num_entries <= 0)
2319                 goto bailout;
2320
2321         toclen = num_entries * sizeof(struct cd_toc_entry);
2322
2323         error = cdreadtoc(periph, CD_MSF_FORMAT, toch->starting_track,
2324                           (u_int8_t *)&softc->toc, toclen + sizeof(*toch),
2325                           SF_NO_PRINT);
2326         if (error != 0) {
2327                 error = 0;
2328                 bzero(&softc->toc, sizeof(softc->toc));
2329                 goto bailout;
2330         }
2331
2332         if (softc->quirks & CD_Q_BCD_TRACKS) {
2333                 toch->starting_track = bcd2bin(toch->starting_track);
2334                 toch->ending_track = bcd2bin(toch->ending_track);
2335         }
2336         /*
2337          * XXX KDM is this necessary?  Probably only if the drive doesn't
2338          * return leadout information with the table of contents.
2339          */
2340         cdindex = toch->starting_track + num_entries -1;
2341         if (cdindex == toch->ending_track + 1) {
2342
2343                 error = cdreadtoc(periph, CD_MSF_FORMAT, LEADOUT, 
2344                                   (u_int8_t *)&leadout, sizeof(leadout),
2345                                   SF_NO_PRINT);
2346                 if (error != 0) {
2347                         error = 0;
2348                         goto bailout;
2349                 }
2350                 softc->toc.entries[cdindex - toch->starting_track] =
2351                         leadout.entry;
2352         }
2353         if (softc->quirks & CD_Q_BCD_TRACKS) {
2354                 for (cdindex = 0; cdindex < num_entries - 1; cdindex++) {
2355                         softc->toc.entries[cdindex].track =
2356                                 bcd2bin(softc->toc.entries[cdindex].track);
2357                 }
2358         }
2359
2360         softc->flags |= CD_FLAG_VALID_TOC;
2361
2362         /* If the first track is audio, correct sector size. */
2363         if ((softc->toc.entries[0].control & 4) == 0) {
2364                 softc->disk->d_sectorsize = softc->params.blksize = 2352;
2365                 softc->disk->d_mediasize =
2366                     (off_t)softc->params.blksize * softc->params.disksize;
2367         }
2368
2369 bailout:
2370
2371         /*
2372          * We unconditionally (re)set the blocksize each time the
2373          * CD device is opened.  This is because the CD can change,
2374          * and therefore the blocksize might change.
2375          * XXX problems here if some slice or partition is still
2376          * open with the old size?
2377          */
2378         if ((softc->disk->d_devstat->flags & DEVSTAT_BS_UNAVAILABLE) != 0)
2379                 softc->disk->d_devstat->flags &= ~DEVSTAT_BS_UNAVAILABLE;
2380         softc->disk->d_devstat->block_size = softc->params.blksize;
2381
2382         return (error);
2383 }
2384
2385 static int
2386 cdsize(struct cam_periph *periph, u_int32_t *size)
2387 {
2388         struct cd_softc *softc;
2389         union ccb *ccb;
2390         struct scsi_read_capacity_data *rcap_buf;
2391         int error;
2392
2393         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdsize\n"));
2394
2395         softc = (struct cd_softc *)periph->softc;
2396              
2397         ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
2398
2399         /* XXX Should be M_WAITOK */
2400         rcap_buf = malloc(sizeof(struct scsi_read_capacity_data), 
2401                           M_SCSICD, M_NOWAIT | M_ZERO);
2402         if (rcap_buf == NULL)
2403                 return (ENOMEM);
2404
2405         scsi_read_capacity(&ccb->csio, 
2406                            /*retries*/ cd_retry_count,
2407                            /*cbfcnp*/NULL,
2408                            MSG_SIMPLE_Q_TAG,
2409                            rcap_buf,
2410                            SSD_FULL_SIZE,
2411                            /* timeout */20000);
2412
2413         error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
2414                          /*sense_flags*/SF_RETRY_UA|SF_NO_PRINT);
2415
2416         xpt_release_ccb(ccb);
2417
2418         softc->params.disksize = scsi_4btoul(rcap_buf->addr) + 1;
2419         softc->params.blksize  = scsi_4btoul(rcap_buf->length);
2420         /* Make sure we got at least some block size. */
2421         if (error == 0 && softc->params.blksize == 0)
2422                 error = EIO;
2423         /*
2424          * SCSI-3 mandates that the reported blocksize shall be 2048.
2425          * Older drives sometimes report funny values, trim it down to
2426          * 2048, or other parts of the kernel will get confused.
2427          *
2428          * XXX we leave drives alone that might report 512 bytes, as
2429          * well as drives reporting more weird sizes like perhaps 4K.
2430          */
2431         if (softc->params.blksize > 2048 && softc->params.blksize <= 2352)
2432                 softc->params.blksize = 2048;
2433
2434         free(rcap_buf, M_SCSICD);
2435         *size = softc->params.disksize;
2436
2437         return (error);
2438
2439 }
2440
2441 static int
2442 cd6byteworkaround(union ccb *ccb)
2443 {
2444         u_int8_t *cdb;
2445         struct cam_periph *periph;
2446         struct cd_softc *softc;
2447         struct cd_mode_params *params;
2448         int frozen, found;
2449
2450         periph = xpt_path_periph(ccb->ccb_h.path);
2451         softc = (struct cd_softc *)periph->softc;
2452
2453         cdb = ccb->csio.cdb_io.cdb_bytes;
2454
2455         if ((ccb->ccb_h.flags & CAM_CDB_POINTER)
2456          || ((cdb[0] != MODE_SENSE_6)
2457           && (cdb[0] != MODE_SELECT_6)))
2458                 return (0);
2459
2460         /*
2461          * Because there is no convenient place to stash the overall
2462          * cd_mode_params structure pointer, we have to grab it like this.
2463          * This means that ALL MODE_SENSE and MODE_SELECT requests in the
2464          * cd(4) driver MUST go through cdgetmode() and cdsetmode()!
2465          *
2466          * XXX It would be nice if, at some point, we could increase the
2467          * number of available peripheral private pointers.  Both pointers
2468          * are currently used in most every peripheral driver.
2469          */
2470         found = 0;
2471
2472         STAILQ_FOREACH(params, &softc->mode_queue, links) {
2473                 if (params->mode_buf == ccb->csio.data_ptr) {
2474                         found = 1;
2475                         break;
2476                 }
2477         }
2478
2479         /*
2480          * This shouldn't happen.  All mode sense and mode select
2481          * operations in the cd(4) driver MUST go through cdgetmode() and
2482          * cdsetmode()!
2483          */
2484         if (found == 0) {
2485                 xpt_print(periph->path,
2486                     "mode buffer not found in mode queue!\n");
2487                 return (0);
2488         }
2489
2490         params->cdb_size = 10;
2491         softc->minimum_command_size = 10;
2492         xpt_print(ccb->ccb_h.path,
2493             "%s(6) failed, increasing minimum CDB size to 10 bytes\n",
2494             (cdb[0] == MODE_SENSE_6) ? "MODE_SENSE" : "MODE_SELECT");
2495
2496         if (cdb[0] == MODE_SENSE_6) {
2497                 struct scsi_mode_sense_10 ms10;
2498                 struct scsi_mode_sense_6 *ms6;
2499                 int len;
2500
2501                 ms6 = (struct scsi_mode_sense_6 *)cdb;
2502
2503                 bzero(&ms10, sizeof(ms10));
2504                 ms10.opcode = MODE_SENSE_10;
2505                 ms10.byte2 = ms6->byte2;
2506                 ms10.page = ms6->page;
2507
2508                 /*
2509                  * 10 byte mode header, block descriptor,
2510                  * sizeof(union cd_pages)
2511                  */
2512                 len = sizeof(struct cd_mode_data_10);
2513                 ccb->csio.dxfer_len = len;
2514
2515                 scsi_ulto2b(len, ms10.length);
2516                 ms10.control = ms6->control;
2517                 bcopy(&ms10, cdb, 10);
2518                 ccb->csio.cdb_len = 10;
2519         } else {
2520                 struct scsi_mode_select_10 ms10;
2521                 struct scsi_mode_select_6 *ms6;
2522                 struct scsi_mode_header_6 *header6;
2523                 struct scsi_mode_header_10 *header10;
2524                 struct scsi_mode_page_header *page_header;
2525                 int blk_desc_len, page_num, page_size, len;
2526
2527                 ms6 = (struct scsi_mode_select_6 *)cdb;
2528
2529                 bzero(&ms10, sizeof(ms10));
2530                 ms10.opcode = MODE_SELECT_10;
2531                 ms10.byte2 = ms6->byte2;
2532
2533                 header6 = (struct scsi_mode_header_6 *)params->mode_buf;
2534                 header10 = (struct scsi_mode_header_10 *)params->mode_buf;
2535
2536                 page_header = find_mode_page_6(header6);
2537                 page_num = page_header->page_code;
2538
2539                 blk_desc_len = header6->blk_desc_len;
2540
2541                 page_size = cdgetpagesize(page_num);
2542
2543                 if (page_size != (page_header->page_length +
2544                     sizeof(*page_header)))
2545                         page_size = page_header->page_length +
2546                                 sizeof(*page_header);
2547
2548                 len = sizeof(*header10) + blk_desc_len + page_size;
2549
2550                 len = min(params->alloc_len, len);
2551
2552                 /*
2553                  * Since the 6 byte parameter header is shorter than the 10
2554                  * byte parameter header, we need to copy the actual mode
2555                  * page data, and the block descriptor, if any, so things wind
2556                  * up in the right place.  The regions will overlap, but
2557                  * bcopy() does the right thing.
2558                  */
2559                 bcopy(params->mode_buf + sizeof(*header6),
2560                       params->mode_buf + sizeof(*header10),
2561                       len - sizeof(*header10));
2562
2563                 /* Make sure these fields are set correctly. */
2564                 scsi_ulto2b(0, header10->data_length);
2565                 header10->medium_type = 0;
2566                 scsi_ulto2b(blk_desc_len, header10->blk_desc_len);
2567
2568                 ccb->csio.dxfer_len = len;
2569
2570                 scsi_ulto2b(len, ms10.length);
2571                 ms10.control = ms6->control;
2572                 bcopy(&ms10, cdb, 10);
2573                 ccb->csio.cdb_len = 10;
2574         }
2575
2576         frozen = (ccb->ccb_h.status & CAM_DEV_QFRZN) != 0;
2577         ccb->ccb_h.status = CAM_REQUEUE_REQ;
2578         xpt_action(ccb);
2579         if (frozen) {
2580                 cam_release_devq(ccb->ccb_h.path,
2581                                  /*relsim_flags*/0,
2582                                  /*openings*/0,
2583                                  /*timeout*/0,
2584                                  /*getcount_only*/0);
2585         }
2586
2587         return (ERESTART);
2588 }
2589
2590 static int
2591 cderror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
2592 {
2593         struct cd_softc *softc;
2594         struct cam_periph *periph;
2595         int error, error_code, sense_key, asc, ascq;
2596
2597         periph = xpt_path_periph(ccb->ccb_h.path);
2598         softc = (struct cd_softc *)periph->softc;
2599
2600         error = 0;
2601
2602         /*
2603          * We use a status of CAM_REQ_INVALID as shorthand -- if a 6 byte
2604          * CDB comes back with this particular error, try transforming it
2605          * into the 10 byte version.
2606          */
2607         if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INVALID) {
2608                 error = cd6byteworkaround(ccb);
2609         } else if (scsi_extract_sense_ccb(ccb,
2610             &error_code, &sense_key, &asc, &ascq)) {
2611                 if (sense_key == SSD_KEY_ILLEGAL_REQUEST)
2612                         error = cd6byteworkaround(ccb);
2613                 else if (sense_key == SSD_KEY_UNIT_ATTENTION &&
2614                     asc == 0x28 && ascq == 0x00)
2615                         disk_media_changed(softc->disk, M_NOWAIT);
2616                 else if (sense_key == SSD_KEY_NOT_READY &&
2617                     asc == 0x3a && (softc->flags & CD_FLAG_SAW_MEDIA)) {
2618                         softc->flags &= ~CD_FLAG_SAW_MEDIA;
2619                         disk_media_gone(softc->disk, M_NOWAIT);
2620                 }
2621         }
2622
2623         if (error == ERESTART)
2624                 return (error);
2625
2626         /*
2627          * XXX
2628          * Until we have a better way of doing pack validation,
2629          * don't treat UAs as errors.
2630          */
2631         sense_flags |= SF_RETRY_UA;
2632
2633         if (softc->quirks & CD_Q_RETRY_BUSY)
2634                 sense_flags |= SF_RETRY_BUSY;
2635         return (cam_periph_error(ccb, cam_flags, sense_flags));
2636 }
2637
2638 static void
2639 cdmediapoll(void *arg)
2640 {
2641         struct cam_periph *periph = arg;
2642         struct cd_softc *softc = periph->softc;
2643
2644         if (softc->state == CD_STATE_NORMAL && !softc->tur &&
2645             softc->outstanding_cmds == 0) {
2646                 if (cam_periph_acquire(periph) == 0) {
2647                         softc->tur = 1;
2648                         xpt_schedule(periph, CAM_PRIORITY_NORMAL);
2649                 }
2650         }
2651         /* Queue us up again */
2652         if (cd_poll_period != 0)
2653                 callout_schedule(&softc->mediapoll_c, cd_poll_period * hz);
2654 }
2655
2656 /*
2657  * Read table of contents
2658  */
2659 static int 
2660 cdreadtoc(struct cam_periph *periph, u_int32_t mode, u_int32_t start, 
2661           u_int8_t *data, u_int32_t len, u_int32_t sense_flags)
2662 {
2663         struct scsi_read_toc *scsi_cmd;
2664         u_int32_t ntoc;
2665         struct ccb_scsiio *csio;
2666         union ccb *ccb;
2667         int error;
2668
2669         ntoc = len;
2670         error = 0;
2671
2672         ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
2673
2674         csio = &ccb->csio;
2675
2676         cam_fill_csio(csio, 
2677                       /* retries */ cd_retry_count, 
2678                       /* cbfcnp */ NULL,
2679                       /* flags */ CAM_DIR_IN,
2680                       /* tag_action */ MSG_SIMPLE_Q_TAG,
2681                       /* data_ptr */ data,
2682                       /* dxfer_len */ len,
2683                       /* sense_len */ SSD_FULL_SIZE,
2684                       sizeof(struct scsi_read_toc),
2685                       /* timeout */ 50000);
2686
2687         scsi_cmd = (struct scsi_read_toc *)&csio->cdb_io.cdb_bytes;
2688         bzero (scsi_cmd, sizeof(*scsi_cmd));
2689
2690         if (mode == CD_MSF_FORMAT)
2691                 scsi_cmd->byte2 |= CD_MSF;
2692         scsi_cmd->from_track = start;
2693         /* scsi_ulto2b(ntoc, (u_int8_t *)scsi_cmd->data_len); */
2694         scsi_cmd->data_len[0] = (ntoc) >> 8;
2695         scsi_cmd->data_len[1] = (ntoc) & 0xff;
2696
2697         scsi_cmd->op_code = READ_TOC;
2698
2699         error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
2700                          /*sense_flags*/SF_RETRY_UA | sense_flags);
2701
2702         xpt_release_ccb(ccb);
2703
2704         return(error);
2705 }
2706
2707 static int
2708 cdreadsubchannel(struct cam_periph *periph, u_int32_t mode, 
2709                  u_int32_t format, int track, 
2710                  struct cd_sub_channel_info *data, u_int32_t len) 
2711 {
2712         struct scsi_read_subchannel *scsi_cmd;
2713         struct ccb_scsiio *csio;
2714         union ccb *ccb;
2715         int error;
2716
2717         error = 0;
2718
2719         ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
2720
2721         csio = &ccb->csio;
2722
2723         cam_fill_csio(csio, 
2724                       /* retries */ cd_retry_count, 
2725                       /* cbfcnp */ NULL,
2726                       /* flags */ CAM_DIR_IN,
2727                       /* tag_action */ MSG_SIMPLE_Q_TAG,
2728                       /* data_ptr */ (u_int8_t *)data,
2729                       /* dxfer_len */ len,
2730                       /* sense_len */ SSD_FULL_SIZE,
2731                       sizeof(struct scsi_read_subchannel),
2732                       /* timeout */ 50000);
2733
2734         scsi_cmd = (struct scsi_read_subchannel *)&csio->cdb_io.cdb_bytes;
2735         bzero (scsi_cmd, sizeof(*scsi_cmd));
2736
2737         scsi_cmd->op_code = READ_SUBCHANNEL;
2738         if (mode == CD_MSF_FORMAT)
2739                 scsi_cmd->byte1 |= CD_MSF;
2740         scsi_cmd->byte2 = SRS_SUBQ;
2741         scsi_cmd->subchan_format = format;
2742         scsi_cmd->track = track;
2743         scsi_ulto2b(len, (u_int8_t *)scsi_cmd->data_len);
2744         scsi_cmd->control = 0;
2745
2746         error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
2747                          /*sense_flags*/SF_RETRY_UA);
2748
2749         xpt_release_ccb(ccb);
2750
2751         return(error);
2752 }
2753
2754
2755 /*
2756  * All MODE_SENSE requests in the cd(4) driver MUST go through this
2757  * routine.  See comments in cd6byteworkaround() for details.
2758  */
2759 static int
2760 cdgetmode(struct cam_periph *periph, struct cd_mode_params *data,
2761           u_int32_t page)
2762 {
2763         struct ccb_scsiio *csio;
2764         struct cd_softc *softc;
2765         union ccb *ccb;
2766         int param_len;
2767         int error;
2768
2769         softc = (struct cd_softc *)periph->softc;
2770
2771         ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
2772
2773         csio = &ccb->csio;
2774
2775         data->cdb_size = softc->minimum_command_size;
2776         if (data->cdb_size < 10)
2777                 param_len = sizeof(struct cd_mode_data);
2778         else
2779                 param_len = sizeof(struct cd_mode_data_10);
2780
2781         /* Don't say we've got more room than we actually allocated */
2782         param_len = min(param_len, data->alloc_len);
2783
2784         scsi_mode_sense_len(csio,
2785                             /* retries */ cd_retry_count,
2786                             /* cbfcnp */ NULL,
2787                             /* tag_action */ MSG_SIMPLE_Q_TAG,
2788                             /* dbd */ 0,
2789                             /* page_code */ SMS_PAGE_CTRL_CURRENT,
2790                             /* page */ page,
2791                             /* param_buf */ data->mode_buf,
2792                             /* param_len */ param_len,
2793                             /* minimum_cmd_size */ softc->minimum_command_size,
2794                             /* sense_len */ SSD_FULL_SIZE,
2795                             /* timeout */ 50000);
2796
2797         /*
2798          * It would be nice not to have to do this, but there's no
2799          * available pointer in the CCB that would allow us to stuff the
2800          * mode params structure in there and retrieve it in
2801          * cd6byteworkaround(), so we can set the cdb size.  The cdb size
2802          * lets the caller know what CDB size we ended up using, so they
2803          * can find the actual mode page offset.
2804          */
2805         STAILQ_INSERT_TAIL(&softc->mode_queue, data, links);
2806
2807         error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
2808                          /*sense_flags*/SF_RETRY_UA);
2809
2810         xpt_release_ccb(ccb);
2811
2812         STAILQ_REMOVE(&softc->mode_queue, data, cd_mode_params, links);
2813
2814         /*
2815          * This is a bit of belt-and-suspenders checking, but if we run
2816          * into a situation where the target sends back multiple block
2817          * descriptors, we might not have enough space in the buffer to
2818          * see the whole mode page.  Better to return an error than
2819          * potentially access memory beyond our malloced region.
2820          */
2821         if (error == 0) {
2822                 u_int32_t data_len;
2823
2824                 if (data->cdb_size == 10) {
2825                         struct scsi_mode_header_10 *hdr10;
2826
2827                         hdr10 = (struct scsi_mode_header_10 *)data->mode_buf;
2828                         data_len = scsi_2btoul(hdr10->data_length);
2829                         data_len += sizeof(hdr10->data_length);
2830                 } else {
2831                         struct scsi_mode_header_6 *hdr6;
2832
2833                         hdr6 = (struct scsi_mode_header_6 *)data->mode_buf;
2834                         data_len = hdr6->data_length;
2835                         data_len += sizeof(hdr6->data_length);
2836                 }
2837
2838                 /*
2839                  * Complain if there is more mode data available than we
2840                  * allocated space for.  This could potentially happen if
2841                  * we miscalculated the page length for some reason, if the
2842                  * drive returns multiple block descriptors, or if it sets
2843                  * the data length incorrectly.
2844                  */
2845                 if (data_len > data->alloc_len) {
2846                         xpt_print(periph->path, "allocated modepage %d length "
2847                             "%d < returned length %d\n", page, data->alloc_len,
2848                             data_len);
2849                         error = ENOSPC;
2850                 }
2851         }
2852         return (error);
2853 }
2854
2855 /*
2856  * All MODE_SELECT requests in the cd(4) driver MUST go through this
2857  * routine.  See comments in cd6byteworkaround() for details.
2858  */
2859 static int
2860 cdsetmode(struct cam_periph *periph, struct cd_mode_params *data)
2861 {
2862         struct ccb_scsiio *csio;
2863         struct cd_softc *softc;
2864         union ccb *ccb;
2865         int cdb_size, param_len;
2866         int error;
2867
2868         softc = (struct cd_softc *)periph->softc;
2869
2870         ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
2871
2872         csio = &ccb->csio;
2873
2874         error = 0;
2875
2876         /*
2877          * If the data is formatted for the 10 byte version of the mode
2878          * select parameter list, we need to use the 10 byte CDB.
2879          * Otherwise, we use whatever the stored minimum command size.
2880          */
2881         if (data->cdb_size == 10)
2882                 cdb_size = data->cdb_size;
2883         else
2884                 cdb_size = softc->minimum_command_size;
2885
2886         if (cdb_size >= 10) {
2887                 struct scsi_mode_header_10 *mode_header;
2888                 u_int32_t data_len;
2889
2890                 mode_header = (struct scsi_mode_header_10 *)data->mode_buf;
2891
2892                 data_len = scsi_2btoul(mode_header->data_length);
2893
2894                 scsi_ulto2b(0, mode_header->data_length);
2895                 /*
2896                  * SONY drives do not allow a mode select with a medium_type
2897                  * value that has just been returned by a mode sense; use a
2898                  * medium_type of 0 (Default) instead.
2899                  */
2900                 mode_header->medium_type = 0;
2901
2902                 /*
2903                  * Pass back whatever the drive passed to us, plus the size
2904                  * of the data length field.
2905                  */
2906                 param_len = data_len + sizeof(mode_header->data_length);
2907
2908         } else {
2909                 struct scsi_mode_header_6 *mode_header;
2910
2911                 mode_header = (struct scsi_mode_header_6 *)data->mode_buf;
2912
2913                 param_len = mode_header->data_length + 1;
2914
2915                 mode_header->data_length = 0;
2916                 /*
2917                  * SONY drives do not allow a mode select with a medium_type
2918                  * value that has just been returned by a mode sense; use a
2919                  * medium_type of 0 (Default) instead.
2920                  */
2921                 mode_header->medium_type = 0;
2922         }
2923
2924         /* Don't say we've got more room than we actually allocated */
2925         param_len = min(param_len, data->alloc_len);
2926
2927         scsi_mode_select_len(csio,
2928                              /* retries */ cd_retry_count,
2929                              /* cbfcnp */ NULL,
2930                              /* tag_action */ MSG_SIMPLE_Q_TAG,
2931                              /* scsi_page_fmt */ 1,
2932                              /* save_pages */ 0,
2933                              /* param_buf */ data->mode_buf,
2934                              /* param_len */ param_len,
2935                              /* minimum_cmd_size */ cdb_size,
2936                              /* sense_len */ SSD_FULL_SIZE,
2937                              /* timeout */ 50000);
2938
2939         /* See comments in cdgetmode() and cd6byteworkaround(). */
2940         STAILQ_INSERT_TAIL(&softc->mode_queue, data, links);
2941
2942         error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
2943                          /*sense_flags*/SF_RETRY_UA);
2944
2945         xpt_release_ccb(ccb);
2946
2947         STAILQ_REMOVE(&softc->mode_queue, data, cd_mode_params, links);
2948
2949         return (error);
2950 }
2951
2952
2953 static int 
2954 cdplay(struct cam_periph *periph, u_int32_t blk, u_int32_t len)
2955 {
2956         struct ccb_scsiio *csio;
2957         union ccb *ccb;
2958         int error;
2959         u_int8_t cdb_len;
2960
2961         error = 0;
2962         ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
2963         csio = &ccb->csio;
2964         /*
2965          * Use the smallest possible command to perform the operation.
2966          */
2967         if ((len & 0xffff0000) == 0) {
2968                 /*
2969                  * We can fit in a 10 byte cdb.
2970                  */
2971                 struct scsi_play_10 *scsi_cmd;
2972
2973                 scsi_cmd = (struct scsi_play_10 *)&csio->cdb_io.cdb_bytes;
2974                 bzero (scsi_cmd, sizeof(*scsi_cmd));
2975                 scsi_cmd->op_code = PLAY_10;
2976                 scsi_ulto4b(blk, (u_int8_t *)scsi_cmd->blk_addr);
2977                 scsi_ulto2b(len, (u_int8_t *)scsi_cmd->xfer_len);
2978                 cdb_len = sizeof(*scsi_cmd);
2979         } else  {
2980                 struct scsi_play_12 *scsi_cmd;
2981
2982                 scsi_cmd = (struct scsi_play_12 *)&csio->cdb_io.cdb_bytes;
2983                 bzero (scsi_cmd, sizeof(*scsi_cmd));
2984                 scsi_cmd->op_code = PLAY_12;
2985                 scsi_ulto4b(blk, (u_int8_t *)scsi_cmd->blk_addr);
2986                 scsi_ulto4b(len, (u_int8_t *)scsi_cmd->xfer_len);
2987                 cdb_len = sizeof(*scsi_cmd);
2988         }
2989         cam_fill_csio(csio,
2990                       /*retries*/ cd_retry_count,
2991                       /*cbfcnp*/NULL,
2992                       /*flags*/CAM_DIR_NONE,
2993                       MSG_SIMPLE_Q_TAG,
2994                       /*dataptr*/NULL,
2995                       /*datalen*/0,
2996                       /*sense_len*/SSD_FULL_SIZE,
2997                       cdb_len,
2998                       /*timeout*/50 * 1000);
2999
3000         error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3001                          /*sense_flags*/SF_RETRY_UA);
3002
3003         xpt_release_ccb(ccb);
3004
3005         return(error);
3006 }
3007
3008 static int
3009 cdplaymsf(struct cam_periph *periph, u_int32_t startm, u_int32_t starts,
3010           u_int32_t startf, u_int32_t endm, u_int32_t ends, u_int32_t endf)
3011 {
3012         struct scsi_play_msf *scsi_cmd;
3013         struct ccb_scsiio *csio;
3014         union ccb *ccb;
3015         int error;
3016
3017         error = 0;
3018
3019         ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
3020
3021         csio = &ccb->csio;
3022
3023         cam_fill_csio(csio, 
3024                       /* retries */ cd_retry_count, 
3025                       /* cbfcnp */ NULL,
3026                       /* flags */ CAM_DIR_NONE,
3027                       /* tag_action */ MSG_SIMPLE_Q_TAG,
3028                       /* data_ptr */ NULL,
3029                       /* dxfer_len */ 0,
3030                       /* sense_len */ SSD_FULL_SIZE,
3031                       sizeof(struct scsi_play_msf),
3032                       /* timeout */ 50000);
3033
3034         scsi_cmd = (struct scsi_play_msf *)&csio->cdb_io.cdb_bytes;
3035         bzero (scsi_cmd, sizeof(*scsi_cmd));
3036
3037         scsi_cmd->op_code = PLAY_MSF;
3038         scsi_cmd->start_m = startm;
3039         scsi_cmd->start_s = starts;
3040         scsi_cmd->start_f = startf;
3041         scsi_cmd->end_m = endm;
3042         scsi_cmd->end_s = ends;
3043         scsi_cmd->end_f = endf; 
3044
3045         error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3046                          /*sense_flags*/SF_RETRY_UA);
3047         
3048         xpt_release_ccb(ccb);
3049
3050         return(error);
3051 }
3052
3053
3054 static int
3055 cdplaytracks(struct cam_periph *periph, u_int32_t strack, u_int32_t sindex,
3056              u_int32_t etrack, u_int32_t eindex)
3057 {
3058         struct scsi_play_track *scsi_cmd;
3059         struct ccb_scsiio *csio;
3060         union ccb *ccb;
3061         int error;
3062
3063         error = 0;
3064
3065         ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
3066
3067         csio = &ccb->csio;
3068
3069         cam_fill_csio(csio, 
3070                       /* retries */ cd_retry_count, 
3071                       /* cbfcnp */ NULL,
3072                       /* flags */ CAM_DIR_NONE,
3073                       /* tag_action */ MSG_SIMPLE_Q_TAG,
3074                       /* data_ptr */ NULL,
3075                       /* dxfer_len */ 0,
3076                       /* sense_len */ SSD_FULL_SIZE,
3077                       sizeof(struct scsi_play_track),
3078                       /* timeout */ 50000);
3079
3080         scsi_cmd = (struct scsi_play_track *)&csio->cdb_io.cdb_bytes;
3081         bzero (scsi_cmd, sizeof(*scsi_cmd));
3082
3083         scsi_cmd->op_code = PLAY_TRACK;
3084         scsi_cmd->start_track = strack;
3085         scsi_cmd->start_index = sindex;
3086         scsi_cmd->end_track = etrack;
3087         scsi_cmd->end_index = eindex;
3088
3089         error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3090                          /*sense_flags*/SF_RETRY_UA);
3091
3092         xpt_release_ccb(ccb);
3093
3094         return(error);
3095 }
3096
3097 static int
3098 cdpause(struct cam_periph *periph, u_int32_t go)
3099 {
3100         struct scsi_pause *scsi_cmd;
3101         struct ccb_scsiio *csio;
3102         union ccb *ccb;
3103         int error;
3104
3105         error = 0;
3106
3107         ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
3108
3109         csio = &ccb->csio;
3110
3111         cam_fill_csio(csio, 
3112                       /* retries */ cd_retry_count, 
3113                       /* cbfcnp */ NULL,
3114                       /* flags */ CAM_DIR_NONE,
3115                       /* tag_action */ MSG_SIMPLE_Q_TAG,
3116                       /* data_ptr */ NULL,
3117                       /* dxfer_len */ 0,
3118                       /* sense_len */ SSD_FULL_SIZE,
3119                       sizeof(struct scsi_pause),
3120                       /* timeout */ 50000);
3121
3122         scsi_cmd = (struct scsi_pause *)&csio->cdb_io.cdb_bytes;
3123         bzero (scsi_cmd, sizeof(*scsi_cmd));
3124
3125         scsi_cmd->op_code = PAUSE;
3126         scsi_cmd->resume = go;
3127
3128         error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3129                          /*sense_flags*/SF_RETRY_UA);
3130
3131         xpt_release_ccb(ccb);
3132
3133         return(error);
3134 }
3135
3136 static int
3137 cdstartunit(struct cam_periph *periph, int load)
3138 {
3139         union ccb *ccb;
3140         int error;
3141
3142         error = 0;
3143
3144         ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
3145
3146         scsi_start_stop(&ccb->csio,
3147                         /* retries */ cd_retry_count,
3148                         /* cbfcnp */ NULL,
3149                         /* tag_action */ MSG_SIMPLE_Q_TAG,
3150                         /* start */ TRUE,
3151                         /* load_eject */ load,
3152                         /* immediate */ FALSE,
3153                         /* sense_len */ SSD_FULL_SIZE,
3154                         /* timeout */ 50000);
3155
3156         error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3157                          /*sense_flags*/SF_RETRY_UA);
3158
3159         xpt_release_ccb(ccb);
3160
3161         return(error);
3162 }
3163
3164 static int
3165 cdstopunit(struct cam_periph *periph, u_int32_t eject)
3166 {
3167         union ccb *ccb;
3168         int error;
3169
3170         error = 0;
3171
3172         ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
3173
3174         scsi_start_stop(&ccb->csio,
3175                         /* retries */ cd_retry_count,
3176                         /* cbfcnp */ NULL,
3177                         /* tag_action */ MSG_SIMPLE_Q_TAG,
3178                         /* start */ FALSE,
3179                         /* load_eject */ eject,
3180                         /* immediate */ FALSE,
3181                         /* sense_len */ SSD_FULL_SIZE,
3182                         /* timeout */ 50000);
3183
3184         error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3185                          /*sense_flags*/SF_RETRY_UA);
3186
3187         xpt_release_ccb(ccb);
3188
3189         return(error);
3190 }
3191
3192 static int
3193 cdsetspeed(struct cam_periph *periph, u_int32_t rdspeed, u_int32_t wrspeed)
3194 {
3195         struct scsi_set_speed *scsi_cmd;
3196         struct ccb_scsiio *csio;
3197         union ccb *ccb;
3198         int error;
3199
3200         error = 0;
3201         ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
3202         csio = &ccb->csio;
3203
3204         /* Preserve old behavior: units in multiples of CDROM speed */
3205         if (rdspeed < 177)
3206                 rdspeed *= 177;
3207         if (wrspeed < 177)
3208                 wrspeed *= 177;
3209
3210         cam_fill_csio(csio,
3211                       /* retries */ cd_retry_count,
3212                       /* cbfcnp */ NULL,
3213                       /* flags */ CAM_DIR_NONE,
3214                       /* tag_action */ MSG_SIMPLE_Q_TAG,
3215                       /* data_ptr */ NULL,
3216                       /* dxfer_len */ 0,
3217                       /* sense_len */ SSD_FULL_SIZE,
3218                       sizeof(struct scsi_set_speed),
3219                       /* timeout */ 50000);
3220
3221         scsi_cmd = (struct scsi_set_speed *)&csio->cdb_io.cdb_bytes;
3222         bzero(scsi_cmd, sizeof(*scsi_cmd));
3223
3224         scsi_cmd->opcode = SET_CD_SPEED;
3225         scsi_ulto2b(rdspeed, scsi_cmd->readspeed);
3226         scsi_ulto2b(wrspeed, scsi_cmd->writespeed);
3227
3228         error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3229                          /*sense_flags*/SF_RETRY_UA);
3230
3231         xpt_release_ccb(ccb);
3232
3233         return(error);
3234 }
3235
3236 static int
3237 cdreportkey(struct cam_periph *periph, struct dvd_authinfo *authinfo)
3238 {
3239         union ccb *ccb;
3240         u_int8_t *databuf;
3241         u_int32_t lba;
3242         int error;
3243         int length;
3244
3245         error = 0;
3246         databuf = NULL;
3247         lba = 0;
3248
3249         switch (authinfo->format) {
3250         case DVD_REPORT_AGID:
3251                 length = sizeof(struct scsi_report_key_data_agid);
3252                 break;
3253         case DVD_REPORT_CHALLENGE:
3254                 length = sizeof(struct scsi_report_key_data_challenge);
3255                 break;
3256         case DVD_REPORT_KEY1:
3257                 length = sizeof(struct scsi_report_key_data_key1_key2);
3258                 break;
3259         case DVD_REPORT_TITLE_KEY:
3260                 length = sizeof(struct scsi_report_key_data_title);
3261                 /* The lba field is only set for the title key */
3262                 lba = authinfo->lba;
3263                 break;
3264         case DVD_REPORT_ASF:
3265                 length = sizeof(struct scsi_report_key_data_asf);
3266                 break;
3267         case DVD_REPORT_RPC:
3268                 length = sizeof(struct scsi_report_key_data_rpc);
3269                 break;
3270         case DVD_INVALIDATE_AGID:
3271                 length = 0;
3272                 break;
3273         default:
3274                 return (EINVAL);
3275         }
3276
3277         if (length != 0) {
3278                 databuf = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
3279         } else
3280                 databuf = NULL;
3281
3282         cam_periph_lock(periph);
3283         ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
3284
3285         scsi_report_key(&ccb->csio,
3286                         /* retries */ cd_retry_count,
3287                         /* cbfcnp */ NULL,
3288                         /* tag_action */ MSG_SIMPLE_Q_TAG,
3289                         /* lba */ lba,
3290                         /* agid */ authinfo->agid,
3291                         /* key_format */ authinfo->format,
3292                         /* data_ptr */ databuf,
3293                         /* dxfer_len */ length,
3294                         /* sense_len */ SSD_FULL_SIZE,
3295                         /* timeout */ 50000);
3296
3297         error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3298                          /*sense_flags*/SF_RETRY_UA);
3299
3300         if (error != 0)
3301                 goto bailout;
3302
3303         if (ccb->csio.resid != 0) {
3304                 xpt_print(periph->path, "warning, residual for report key "
3305                     "command is %d\n", ccb->csio.resid);
3306         }
3307
3308         switch(authinfo->format) {
3309         case DVD_REPORT_AGID: {
3310                 struct scsi_report_key_data_agid *agid_data;
3311
3312                 agid_data = (struct scsi_report_key_data_agid *)databuf;
3313
3314                 authinfo->agid = (agid_data->agid & RKD_AGID_MASK) >>
3315                         RKD_AGID_SHIFT;
3316                 break;
3317         }
3318         case DVD_REPORT_CHALLENGE: {
3319                 struct scsi_report_key_data_challenge *chal_data;
3320
3321                 chal_data = (struct scsi_report_key_data_challenge *)databuf;
3322
3323                 bcopy(chal_data->challenge_key, authinfo->keychal,
3324                       min(sizeof(chal_data->challenge_key),
3325                           sizeof(authinfo->keychal)));
3326                 break;
3327         }
3328         case DVD_REPORT_KEY1: {
3329                 struct scsi_report_key_data_key1_key2 *key1_data;
3330
3331                 key1_data = (struct scsi_report_key_data_key1_key2 *)databuf;
3332
3333                 bcopy(key1_data->key1, authinfo->keychal,
3334                       min(sizeof(key1_data->key1), sizeof(authinfo->keychal)));
3335                 break;
3336         }
3337         case DVD_REPORT_TITLE_KEY: {
3338                 struct scsi_report_key_data_title *title_data;
3339
3340                 title_data = (struct scsi_report_key_data_title *)databuf;
3341
3342                 authinfo->cpm = (title_data->byte0 & RKD_TITLE_CPM) >>
3343                         RKD_TITLE_CPM_SHIFT;
3344                 authinfo->cp_sec = (title_data->byte0 & RKD_TITLE_CP_SEC) >>
3345                         RKD_TITLE_CP_SEC_SHIFT;
3346                 authinfo->cgms = (title_data->byte0 & RKD_TITLE_CMGS_MASK) >>
3347                         RKD_TITLE_CMGS_SHIFT;
3348                 bcopy(title_data->title_key, authinfo->keychal,
3349                       min(sizeof(title_data->title_key),
3350                           sizeof(authinfo->keychal)));
3351                 break;
3352         }
3353         case DVD_REPORT_ASF: {
3354                 struct scsi_report_key_data_asf *asf_data;
3355
3356                 asf_data = (struct scsi_report_key_data_asf *)databuf;
3357
3358                 authinfo->asf = asf_data->success & RKD_ASF_SUCCESS;
3359                 break;
3360         }
3361         case DVD_REPORT_RPC: {
3362                 struct scsi_report_key_data_rpc *rpc_data;
3363
3364                 rpc_data = (struct scsi_report_key_data_rpc *)databuf;
3365
3366                 authinfo->reg_type = (rpc_data->byte4 & RKD_RPC_TYPE_MASK) >>
3367                         RKD_RPC_TYPE_SHIFT;
3368                 authinfo->vend_rsts =
3369                         (rpc_data->byte4 & RKD_RPC_VENDOR_RESET_MASK) >>
3370                         RKD_RPC_VENDOR_RESET_SHIFT;
3371                 authinfo->user_rsts = rpc_data->byte4 & RKD_RPC_USER_RESET_MASK;
3372                 authinfo->region = rpc_data->region_mask;
3373                 authinfo->rpc_scheme = rpc_data->rpc_scheme1;
3374                 break;
3375         }
3376         case DVD_INVALIDATE_AGID:
3377                 break;
3378         default:
3379                 /* This should be impossible, since we checked above */
3380                 error = EINVAL;
3381                 goto bailout;
3382                 break; /* NOTREACHED */
3383         }
3384
3385 bailout:
3386         xpt_release_ccb(ccb);
3387         cam_periph_unlock(periph);
3388
3389         if (databuf != NULL)
3390                 free(databuf, M_DEVBUF);
3391
3392         return(error);
3393 }
3394
3395 static int
3396 cdsendkey(struct cam_periph *periph, struct dvd_authinfo *authinfo)
3397 {
3398         union ccb *ccb;
3399         u_int8_t *databuf;
3400         int length;
3401         int error;
3402
3403         error = 0;
3404         databuf = NULL;
3405
3406         switch(authinfo->format) {
3407         case DVD_SEND_CHALLENGE: {
3408                 struct scsi_report_key_data_challenge *challenge_data;
3409
3410                 length = sizeof(*challenge_data);
3411
3412                 challenge_data = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
3413
3414                 databuf = (u_int8_t *)challenge_data;
3415
3416                 scsi_ulto2b(length - sizeof(challenge_data->data_len),
3417                             challenge_data->data_len);
3418
3419                 bcopy(authinfo->keychal, challenge_data->challenge_key,
3420                       min(sizeof(authinfo->keychal),
3421                           sizeof(challenge_data->challenge_key)));
3422                 break;
3423         }
3424         case DVD_SEND_KEY2: {
3425                 struct scsi_report_key_data_key1_key2 *key2_data;
3426
3427                 length = sizeof(*key2_data);
3428
3429                 key2_data = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
3430
3431                 databuf = (u_int8_t *)key2_data;
3432
3433                 scsi_ulto2b(length - sizeof(key2_data->data_len),
3434                             key2_data->data_len);
3435
3436                 bcopy(authinfo->keychal, key2_data->key1,
3437                       min(sizeof(authinfo->keychal), sizeof(key2_data->key1)));
3438
3439                 break;
3440         }
3441         case DVD_SEND_RPC: {
3442                 struct scsi_send_key_data_rpc *rpc_data;
3443
3444                 length = sizeof(*rpc_data);
3445
3446                 rpc_data = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
3447
3448                 databuf = (u_int8_t *)rpc_data;
3449
3450                 scsi_ulto2b(length - sizeof(rpc_data->data_len),
3451                             rpc_data->data_len);
3452
3453                 rpc_data->region_code = authinfo->region;
3454                 break;
3455         }
3456         default:
3457                 return (EINVAL);
3458         }
3459
3460         cam_periph_lock(periph);
3461         ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
3462
3463         scsi_send_key(&ccb->csio,
3464                       /* retries */ cd_retry_count,
3465                       /* cbfcnp */ NULL,
3466                       /* tag_action */ MSG_SIMPLE_Q_TAG,
3467                       /* agid */ authinfo->agid,
3468                       /* key_format */ authinfo->format,
3469                       /* data_ptr */ databuf,
3470                       /* dxfer_len */ length,
3471                       /* sense_len */ SSD_FULL_SIZE,
3472                       /* timeout */ 50000);
3473
3474         error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3475                          /*sense_flags*/SF_RETRY_UA);
3476
3477         xpt_release_ccb(ccb);
3478         cam_periph_unlock(periph);
3479
3480         if (databuf != NULL)
3481                 free(databuf, M_DEVBUF);
3482
3483         return(error);
3484 }
3485
3486 static int
3487 cdreaddvdstructure(struct cam_periph *periph, struct dvd_struct *dvdstruct)
3488 {
3489         union ccb *ccb;
3490         u_int8_t *databuf;
3491         u_int32_t address;
3492         int error;
3493         int length;
3494
3495         error = 0;
3496         databuf = NULL;
3497         /* The address is reserved for many of the formats */
3498         address = 0;
3499
3500         switch(dvdstruct->format) {
3501         case DVD_STRUCT_PHYSICAL:
3502                 length = sizeof(struct scsi_read_dvd_struct_data_physical);
3503                 break;
3504         case DVD_STRUCT_COPYRIGHT:
3505                 length = sizeof(struct scsi_read_dvd_struct_data_copyright);
3506                 break;
3507         case DVD_STRUCT_DISCKEY:
3508                 length = sizeof(struct scsi_read_dvd_struct_data_disc_key);
3509                 break;
3510         case DVD_STRUCT_BCA:
3511                 length = sizeof(struct scsi_read_dvd_struct_data_bca);
3512                 break;
3513         case DVD_STRUCT_MANUFACT:
3514                 length = sizeof(struct scsi_read_dvd_struct_data_manufacturer);
3515                 break;
3516         case DVD_STRUCT_CMI:
3517                 return (ENODEV);
3518         case DVD_STRUCT_PROTDISCID:
3519                 length = sizeof(struct scsi_read_dvd_struct_data_prot_discid);
3520                 break;
3521         case DVD_STRUCT_DISCKEYBLOCK:
3522                 length = sizeof(struct scsi_read_dvd_struct_data_disc_key_blk);
3523                 break;
3524         case DVD_STRUCT_DDS:
3525                 length = sizeof(struct scsi_read_dvd_struct_data_dds);
3526                 break;
3527         case DVD_STRUCT_MEDIUM_STAT:
3528                 length = sizeof(struct scsi_read_dvd_struct_data_medium_status);
3529                 break;
3530         case DVD_STRUCT_SPARE_AREA:
3531                 length = sizeof(struct scsi_read_dvd_struct_data_spare_area);
3532                 break;
3533         case DVD_STRUCT_RMD_LAST:
3534                 return (ENODEV);
3535         case DVD_STRUCT_RMD_RMA:
3536                 return (ENODEV);
3537         case DVD_STRUCT_PRERECORDED:
3538                 length = sizeof(struct scsi_read_dvd_struct_data_leadin);
3539                 break;
3540         case DVD_STRUCT_UNIQUEID:
3541                 length = sizeof(struct scsi_read_dvd_struct_data_disc_id);
3542                 break;
3543         case DVD_STRUCT_DCB:
3544                 return (ENODEV);
3545         case DVD_STRUCT_LIST:
3546                 /*
3547                  * This is the maximum allocation length for the READ DVD
3548                  * STRUCTURE command.  There's nothing in the MMC3 spec
3549                  * that indicates a limit in the amount of data that can
3550                  * be returned from this call, other than the limits
3551                  * imposed by the 2-byte length variables.
3552                  */
3553                 length = 65535;
3554                 break;
3555         default:
3556                 return (EINVAL);
3557         }
3558
3559         if (length != 0) {
3560                 databuf = malloc(length, M_DEVBUF, M_WAITOK | M_ZERO);
3561         } else
3562                 databuf = NULL;
3563
3564         cam_periph_lock(periph);
3565         ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
3566
3567         scsi_read_dvd_structure(&ccb->csio,
3568                                 /* retries */ cd_retry_count,
3569                                 /* cbfcnp */ NULL,
3570                                 /* tag_action */ MSG_SIMPLE_Q_TAG,
3571                                 /* lba */ address,
3572                                 /* layer_number */ dvdstruct->layer_num,
3573                                 /* key_format */ dvdstruct->format,
3574                                 /* agid */ dvdstruct->agid,
3575                                 /* data_ptr */ databuf,
3576                                 /* dxfer_len */ length,
3577                                 /* sense_len */ SSD_FULL_SIZE,
3578                                 /* timeout */ 50000);
3579
3580         error = cdrunccb(ccb, cderror, /*cam_flags*/CAM_RETRY_SELTO,
3581                          /*sense_flags*/SF_RETRY_UA);
3582
3583         if (error != 0)
3584                 goto bailout;
3585
3586         switch(dvdstruct->format) {
3587         case DVD_STRUCT_PHYSICAL: {
3588                 struct scsi_read_dvd_struct_data_layer_desc *inlayer;
3589                 struct dvd_layer *outlayer;
3590                 struct scsi_read_dvd_struct_data_physical *phys_data;
3591
3592                 phys_data =
3593                         (struct scsi_read_dvd_struct_data_physical *)databuf;
3594                 inlayer = &phys_data->layer_desc;
3595                 outlayer = (struct dvd_layer *)&dvdstruct->data;
3596
3597                 dvdstruct->length = sizeof(*inlayer);
3598
3599                 outlayer->book_type = (inlayer->book_type_version &
3600                         RDSD_BOOK_TYPE_MASK) >> RDSD_BOOK_TYPE_SHIFT;
3601                 outlayer->book_version = (inlayer->book_type_version &
3602                         RDSD_BOOK_VERSION_MASK);
3603                 outlayer->disc_size = (inlayer->disc_size_max_rate &
3604                         RDSD_DISC_SIZE_MASK) >> RDSD_DISC_SIZE_SHIFT;
3605                 outlayer->max_rate = (inlayer->disc_size_max_rate &
3606                         RDSD_MAX_RATE_MASK);
3607                 outlayer->nlayers = (inlayer->layer_info &
3608                         RDSD_NUM_LAYERS_MASK) >> RDSD_NUM_LAYERS_SHIFT;
3609                 outlayer->track_path = (inlayer->layer_info &
3610                         RDSD_TRACK_PATH_MASK) >> RDSD_TRACK_PATH_SHIFT;
3611                 outlayer->layer_type = (inlayer->layer_info &
3612                         RDSD_LAYER_TYPE_MASK);
3613                 outlayer->linear_density = (inlayer->density &
3614                         RDSD_LIN_DENSITY_MASK) >> RDSD_LIN_DENSITY_SHIFT;
3615                 outlayer->track_density = (inlayer->density &
3616                         RDSD_TRACK_DENSITY_MASK);
3617                 outlayer->bca = (inlayer->bca & RDSD_BCA_MASK) >>
3618                         RDSD_BCA_SHIFT;
3619                 outlayer->start_sector = scsi_3btoul(inlayer->main_data_start);
3620                 outlayer->end_sector = scsi_3btoul(inlayer->main_data_end);
3621                 outlayer->end_sector_l0 =
3622                         scsi_3btoul(inlayer->end_sector_layer0);
3623                 break;
3624         }
3625         case DVD_STRUCT_COPYRIGHT: {
3626                 struct scsi_read_dvd_struct_data_copyright *copy_data;
3627
3628                 copy_data = (struct scsi_read_dvd_struct_data_copyright *)
3629                         databuf;
3630
3631                 dvdstruct->cpst = copy_data->cps_type;
3632                 dvdstruct->rmi = copy_data->region_info;
3633                 dvdstruct->length = 0;
3634
3635                 break;
3636         }
3637         default:
3638                 /*
3639                  * Tell the user what the overall length is, no matter
3640                  * what we can actually fit in the data buffer.
3641                  */
3642                 dvdstruct->length = length - ccb->csio.resid - 
3643                         sizeof(struct scsi_read_dvd_struct_data_header);
3644
3645                 /*
3646                  * But only actually copy out the smaller of what we read
3647                  * in or what the structure can take.
3648                  */
3649                 bcopy(databuf + sizeof(struct scsi_read_dvd_struct_data_header),
3650                       dvdstruct->data,
3651                       min(sizeof(dvdstruct->data), dvdstruct->length));
3652                 break;
3653         }
3654
3655 bailout:
3656         xpt_release_ccb(ccb);
3657         cam_periph_unlock(periph);
3658
3659         if (databuf != NULL)
3660                 free(databuf, M_DEVBUF);
3661
3662         return(error);
3663 }
3664
3665 void
3666 scsi_report_key(struct ccb_scsiio *csio, u_int32_t retries,
3667                 void (*cbfcnp)(struct cam_periph *, union ccb *),
3668                 u_int8_t tag_action, u_int32_t lba, u_int8_t agid,
3669                 u_int8_t key_format, u_int8_t *data_ptr, u_int32_t dxfer_len,
3670                 u_int8_t sense_len, u_int32_t timeout)
3671 {
3672         struct scsi_report_key *scsi_cmd;
3673
3674         scsi_cmd = (struct scsi_report_key *)&csio->cdb_io.cdb_bytes;
3675         bzero(scsi_cmd, sizeof(*scsi_cmd));
3676         scsi_cmd->opcode = REPORT_KEY;
3677         scsi_ulto4b(lba, scsi_cmd->lba);
3678         scsi_ulto2b(dxfer_len, scsi_cmd->alloc_len);
3679         scsi_cmd->agid_keyformat = (agid << RK_KF_AGID_SHIFT) |
3680                 (key_format & RK_KF_KEYFORMAT_MASK);
3681
3682         cam_fill_csio(csio,
3683                       retries,
3684                       cbfcnp,
3685                       /*flags*/ (dxfer_len == 0) ? CAM_DIR_NONE : CAM_DIR_IN,
3686                       tag_action,
3687                       /*data_ptr*/ data_ptr,
3688                       /*dxfer_len*/ dxfer_len,
3689                       sense_len,
3690                       sizeof(*scsi_cmd),
3691                       timeout);
3692 }
3693
3694 void
3695 scsi_send_key(struct ccb_scsiio *csio, u_int32_t retries,
3696               void (*cbfcnp)(struct cam_periph *, union ccb *),
3697               u_int8_t tag_action, u_int8_t agid, u_int8_t key_format,
3698               u_int8_t *data_ptr, u_int32_t dxfer_len, u_int8_t sense_len,
3699               u_int32_t timeout)
3700 {
3701         struct scsi_send_key *scsi_cmd;
3702
3703         scsi_cmd = (struct scsi_send_key *)&csio->cdb_io.cdb_bytes;
3704         bzero(scsi_cmd, sizeof(*scsi_cmd));
3705         scsi_cmd->opcode = SEND_KEY;
3706
3707         scsi_ulto2b(dxfer_len, scsi_cmd->param_len);
3708         scsi_cmd->agid_keyformat = (agid << RK_KF_AGID_SHIFT) |
3709                 (key_format & RK_KF_KEYFORMAT_MASK);
3710
3711         cam_fill_csio(csio,
3712                       retries,
3713                       cbfcnp,
3714                       /*flags*/ CAM_DIR_OUT,
3715                       tag_action,
3716                       /*data_ptr*/ data_ptr,
3717                       /*dxfer_len*/ dxfer_len,
3718                       sense_len,
3719                       sizeof(*scsi_cmd),
3720                       timeout);
3721 }
3722
3723
3724 void
3725 scsi_read_dvd_structure(struct ccb_scsiio *csio, u_int32_t retries,
3726                         void (*cbfcnp)(struct cam_periph *, union ccb *),
3727                         u_int8_t tag_action, u_int32_t address,
3728                         u_int8_t layer_number, u_int8_t format, u_int8_t agid,
3729                         u_int8_t *data_ptr, u_int32_t dxfer_len,
3730                         u_int8_t sense_len, u_int32_t timeout)
3731 {
3732         struct scsi_read_dvd_structure *scsi_cmd;
3733
3734         scsi_cmd = (struct scsi_read_dvd_structure *)&csio->cdb_io.cdb_bytes;
3735         bzero(scsi_cmd, sizeof(*scsi_cmd));
3736         scsi_cmd->opcode = READ_DVD_STRUCTURE;
3737
3738         scsi_ulto4b(address, scsi_cmd->address);
3739         scsi_cmd->layer_number = layer_number;
3740         scsi_cmd->format = format;
3741         scsi_ulto2b(dxfer_len, scsi_cmd->alloc_len);
3742         /* The AGID is the top two bits of this byte */
3743         scsi_cmd->agid = agid << 6;
3744
3745         cam_fill_csio(csio,
3746                       retries,
3747                       cbfcnp,
3748                       /*flags*/ CAM_DIR_IN,
3749                       tag_action,
3750                       /*data_ptr*/ data_ptr,
3751                       /*dxfer_len*/ dxfer_len,
3752                       sense_len,
3753                       sizeof(*scsi_cmd),
3754                       timeout);
3755 }