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