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