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