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