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