initial commit
[freebsd-arm:freebsd-arm.git] / cam / scsi / scsi_cd.c
1 /*-
2  * Copyright (c) 1997 Justin T. Gibbs.
3  * Copyright (c) 1997, 1998, 1999, 2000, 2001, 2002, 2003 Kenneth D. Merry.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions, and the following disclaimer,
11  *    without modification, immediately at the beginning of the file.
12  * 2. The name of the author may not be used to endorse or promote products
13  *    derived from this software without specific prior written permission.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
19  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27
28 /*-
29  * Portions of this driver taken from the original FreeBSD cd driver.
30  * Written by Julian Elischer (julian@tfs.com)
31  * for TRW Financial Systems for use under the MACH(2.5) operating system.
32  *
33  * TRW Financial Systems, in accordance with their agreement with Carnegie
34  * Mellon University, makes this software available to CMU to distribute
35  * or use in any manner that they see fit as long as this message is kept with
36  * the software. For this reason TFS also grants any other persons or
37  * organisations permission to use or modify this software.
38  *
39  * TFS supplies this software to be publicly redistributed
40  * on the understanding that TFS is not responsible for the correct
41  * functioning of this software in any circumstances.
42  *
43  * Ported to run under 386BSD by Julian Elischer (julian@tfs.com) Sept 1992
44  *
45  *      from: cd.c,v 1.83 1997/05/04 15:24:22 joerg Exp $
46  */
47
48 #include <sys/cdefs.h>
49 __FBSDID("$FreeBSD$");
50
51 #include "opt_cd.h"
52
53 #include <sys/param.h>
54 #include <sys/systm.h>
55 #include <sys/kernel.h>
56 #include <sys/bio.h>
57 #include <sys/conf.h>
58 #include <sys/disk.h>
59 #include <sys/malloc.h>
60 #include <sys/cdio.h>
61 #include <sys/cdrio.h>
62 #include <sys/dvdio.h>
63 #include <sys/devicestat.h>
64 #include <sys/sysctl.h>
65 #include <sys/taskqueue.h>
66 #include <geom/geom_disk.h>
67
68 #include <cam/cam.h>
69 #include <cam/cam_ccb.h>
70 #include <cam/cam_periph.h>
71 #include <cam/cam_xpt_periph.h>
72 #include <cam/cam_queue.h>
73 #include <cam/cam_sim.h>
74
75 #include <cam/scsi/scsi_message.h>
76 #include <cam/scsi/scsi_da.h>
77 #include <cam/scsi/scsi_cd.h>
78
79 #define LEADOUT         0xaa            /* leadout toc entry */
80
81 struct cd_params {
82         u_int32_t blksize;
83         u_long    disksize;
84 };
85
86 typedef enum {
87         CD_Q_NONE               = 0x00,
88         CD_Q_NO_TOUCH           = 0x01,
89         CD_Q_BCD_TRACKS         = 0x02,
90         CD_Q_NO_CHANGER         = 0x04,
91         CD_Q_CHANGER            = 0x08,
92         CD_Q_10_BYTE_ONLY       = 0x10
93 } cd_quirks;
94
95 typedef enum {
96         CD_FLAG_INVALID         = 0x0001,
97         CD_FLAG_NEW_DISC        = 0x0002,
98         CD_FLAG_DISC_LOCKED     = 0x0004,
99         CD_FLAG_DISC_REMOVABLE  = 0x0008,
100         CD_FLAG_TAGGED_QUEUING  = 0x0010,
101         CD_FLAG_CHANGER         = 0x0040,
102         CD_FLAG_ACTIVE          = 0x0080,
103         CD_FLAG_SCHED_ON_COMP   = 0x0100,
104         CD_FLAG_RETRY_UA        = 0x0200,
105         CD_FLAG_VALID_MEDIA     = 0x0400,
106         CD_FLAG_VALID_TOC       = 0x0800,
107         CD_FLAG_SCTX_INIT       = 0x1000,
108         CD_FLAG_OPEN            = 0x2000
109 } cd_flags;
110
111 typedef enum {
112         CD_CCB_PROBE            = 0x01,
113         CD_CCB_BUFFER_IO        = 0x02,
114         CD_CCB_WAITING          = 0x03,
115         CD_CCB_TYPE_MASK        = 0x0F,
116         CD_CCB_RETRY_UA         = 0x10
117 } cd_ccb_state;
118
119 typedef enum {
120         CHANGER_TIMEOUT_SCHED           = 0x01,
121         CHANGER_SHORT_TMOUT_SCHED       = 0x02,
122         CHANGER_MANUAL_CALL             = 0x04,
123         CHANGER_NEED_TIMEOUT            = 0x08
124 } cd_changer_flags;
125
126 #define ccb_state ppriv_field0
127 #define ccb_bp ppriv_ptr1
128
129 struct cd_tocdata {
130         struct ioc_toc_header header;
131         struct cd_toc_entry entries[100];
132 };
133
134 struct cd_toc_single {
135         struct ioc_toc_header header;
136         struct cd_toc_entry entry;
137 };
138
139 typedef enum {
140         CD_STATE_PROBE,
141         CD_STATE_NORMAL
142 } cd_state;
143
144 struct cd_softc {
145         cam_pinfo               pinfo;
146         cd_state                state;
147         volatile cd_flags       flags;
148         struct bio_queue_head   bio_queue;
149         LIST_HEAD(, ccb_hdr)    pending_ccbs;
150         struct cd_params        params;
151         union ccb               saved_ccb;
152         cd_quirks               quirks;
153         STAILQ_ENTRY(cd_softc)  changer_links;
154         struct cdchanger        *changer;
155         int                     bufs_left;
156         struct cam_periph       *periph;
157         int                     minimum_command_size;
158         int                     outstanding_cmds;
159         struct task             sysctl_task;
160         struct sysctl_ctx_list  sysctl_ctx;
161         struct sysctl_oid       *sysctl_tree;
162         STAILQ_HEAD(, cd_mode_params)   mode_queue;
163         struct cd_tocdata       toc;
164         struct disk             *disk;
165 };
166
167 struct cd_page_sizes {
168         int page;
169         int page_size;
170 };
171
172 static struct cd_page_sizes cd_page_size_table[] =
173 {
174         { AUDIO_PAGE, sizeof(struct cd_audio_page)}
175 };
176
177 struct cd_quirk_entry {
178         struct scsi_inquiry_pattern inq_pat;
179         cd_quirks quirks;
180 };
181
182 /*
183  * The changer quirk entries aren't strictly necessary.  Basically, what
184  * they do is tell cdregister() up front that a device is a changer.
185  * Otherwise, it will figure that fact out once it sees a LUN on the device
186  * that is greater than 0.  If it is known up front that a device is a changer,
187  * all I/O to the device will go through the changer scheduling routines, as
188  * opposed to the "normal" CD code.
189  *
190  * NOTE ON 10_BYTE_ONLY quirks:  Any 10_BYTE_ONLY quirks MUST be because
191  * your device hangs when it gets a 10 byte command.  Adding a quirk just
192  * to get rid of the informative diagnostic message is not acceptable.  All
193  * 10_BYTE_ONLY quirks must be documented in full in a PR (which should be
194  * referenced in a comment along with the quirk) , and must be approved by
195  * ken@FreeBSD.org.  Any quirks added that don't adhere to this policy may
196  * be removed until the submitter can explain why they are needed.
197  * 10_BYTE_ONLY quirks will be removed (as they will no longer be necessary)
198  * when the CAM_NEW_TRAN_CODE work is done.
199  */
200 static struct cd_quirk_entry cd_quirk_table[] =
201 {
202         {
203                 { T_CDROM, SIP_MEDIA_REMOVABLE, "NRC", "MBR-7", "*"},
204                  /*quirks*/ CD_Q_CHANGER
205         },
206         {
207                 { T_CDROM, SIP_MEDIA_REMOVABLE, "PIONEER", "CD-ROM DRM*",
208                   "*"}, /* quirks */ CD_Q_CHANGER
209         },
210         {
211                 { T_CDROM, SIP_MEDIA_REMOVABLE, "NAKAMICH", "MJ-*", "*"},
212                  /* quirks */ CD_Q_CHANGER
213         },
214         {
215                 { T_CDROM, SIP_MEDIA_REMOVABLE, "CHINON", "CD-ROM CDS-535","*"},
216                 /* quirks */ CD_Q_BCD_TRACKS
217         }
218 };
219
220 static  disk_open_t     cdopen;
221 static  disk_close_t    cdclose;
222 static  disk_ioctl_t    cdioctl;
223 static  disk_strategy_t cdstrategy;
224
225 static  periph_init_t   cdinit;
226 static  periph_ctor_t   cdregister;
227 static  periph_dtor_t   cdcleanup;
228 static  periph_start_t  cdstart;
229 static  periph_oninv_t  cdoninvalidate;
230 static  void            cdasync(void *callback_arg, u_int32_t code,
231                                 struct cam_path *path, void *arg);
232 static  int             cdcmdsizesysctl(SYSCTL_HANDLER_ARGS);
233 static  void            cdshorttimeout(void *arg);
234 static  void            cdschedule(struct cam_periph *periph, int priority);
235 static  void            cdrunchangerqueue(void *arg);
236 static  void            cdchangerschedule(struct cd_softc *softc);
237 static  int             cdrunccb(union ccb *ccb,
238                                  int (*error_routine)(union ccb *ccb,
239                                                       u_int32_t cam_flags,
240                                                       u_int32_t sense_flags),
241                                  u_int32_t cam_flags, u_int32_t sense_flags);
242 static  union ccb       *cdgetccb(struct cam_periph *periph,
243                                   u_int32_t priority);
244 static  void            cddone(struct cam_periph *periph,
245                                union ccb *start_ccb);
246 static  union cd_pages  *cdgetpage(struct cd_mode_params *mode_params);
247 static  int             cdgetpagesize(int page_num);
248 static  void            cdprevent(struct cam_periph *periph, int action);
249 static  int             cdcheckmedia(struct cam_periph *periph);
250 static  int             cdsize(struct cam_periph *periph, u_int32_t *size);
251 static  int             cd6byteworkaround(union ccb *ccb);
252 static  int             cderror(union ccb *ccb, u_int32_t cam_flags,
253                                 u_int32_t sense_flags);
254 static  int             cdreadtoc(struct cam_periph *periph, u_int32_t mode, 
255                                   u_int32_t start, u_int8_t *data, 
256                                   u_int32_t len, u_int32_t sense_flags);
257 static  int             cdgetmode(struct cam_periph *periph, 
258                                   struct cd_mode_params *data, u_int32_t page);
259 static  int             cdsetmode(struct cam_periph *periph,
260                                   struct cd_mode_params *data);
261 static  int             cdplay(struct cam_periph *periph, u_int32_t blk, 
262                                u_int32_t len);
263 static  int             cdreadsubchannel(struct cam_periph *periph, 
264                                          u_int32_t mode, u_int32_t format, 
265                                          int track, 
266                                          struct cd_sub_channel_info *data, 
267                                          u_int32_t len);
268 static  int             cdplaymsf(struct cam_periph *periph, u_int32_t startm, 
269                                   u_int32_t starts, u_int32_t startf, 
270                                   u_int32_t endm, u_int32_t ends, 
271                                   u_int32_t endf);
272 static  int             cdplaytracks(struct cam_periph *periph, 
273                                      u_int32_t strack, u_int32_t sindex,
274                                      u_int32_t etrack, u_int32_t eindex);
275 static  int             cdpause(struct cam_periph *periph, u_int32_t go);
276 static  int             cdstopunit(struct cam_periph *periph, u_int32_t eject);
277 static  int             cdstartunit(struct cam_periph *periph, int load);
278 static  int             cdsetspeed(struct cam_periph *periph,
279                                    u_int32_t rdspeed, u_int32_t wrspeed);
280 static  int             cdreportkey(struct cam_periph *periph,
281                                     struct dvd_authinfo *authinfo);
282 static  int             cdsendkey(struct cam_periph *periph,
283                                   struct dvd_authinfo *authinfo);
284 static  int             cdreaddvdstructure(struct cam_periph *periph,
285                                            struct dvd_struct *dvdstruct);
286
287 static struct periph_driver cddriver =
288 {
289         cdinit, "cd",
290         TAILQ_HEAD_INITIALIZER(cddriver.units), /* generation */ 0
291 };
292
293 PERIPHDRIVER_DECLARE(cd, cddriver);
294
295 #ifndef CD_DEFAULT_RETRY
296 #define CD_DEFAULT_RETRY        4
297 #endif
298 #ifndef CHANGER_MIN_BUSY_SECONDS
299 #define CHANGER_MIN_BUSY_SECONDS        5
300 #endif
301 #ifndef CHANGER_MAX_BUSY_SECONDS
302 #define CHANGER_MAX_BUSY_SECONDS        15
303 #endif
304
305 static int cd_retry_count = CD_DEFAULT_RETRY;
306 static int changer_min_busy_seconds = CHANGER_MIN_BUSY_SECONDS;
307 static int changer_max_busy_seconds = CHANGER_MAX_BUSY_SECONDS;
308
309 SYSCTL_NODE(_kern_cam, OID_AUTO, cd, CTLFLAG_RD, 0, "CAM CDROM driver");
310 SYSCTL_NODE(_kern_cam_cd, OID_AUTO, changer, CTLFLAG_RD, 0, "CD Changer");
311 SYSCTL_INT(_kern_cam_cd, OID_AUTO, retry_count, CTLFLAG_RW,
312            &cd_retry_count, 0, "Normal I/O retry count");
313 TUNABLE_INT("kern.cam.cd.retry_count", &cd_retry_count);
314 SYSCTL_INT(_kern_cam_cd_changer, OID_AUTO, min_busy_seconds, CTLFLAG_RW,
315            &changer_min_busy_seconds, 0, "Minimum changer scheduling quantum");
316 TUNABLE_INT("kern.cam.cd.changer.min_busy_seconds", &changer_min_busy_seconds);
317 SYSCTL_INT(_kern_cam_cd_changer, OID_AUTO, max_busy_seconds, CTLFLAG_RW,
318            &changer_max_busy_seconds, 0, "Maximum changer scheduling quantum");
319 TUNABLE_INT("kern.cam.cd.changer.max_busy_seconds", &changer_max_busy_seconds);
320
321 struct cdchanger {
322         path_id_t                        path_id;
323         target_id_t                      target_id;
324         int                              num_devices;
325         struct camq                      devq;
326         struct timeval                   start_time;
327         struct cd_softc                  *cur_device;
328         struct callout                   short_handle;
329         struct callout                   long_handle;
330         volatile cd_changer_flags        flags;
331         STAILQ_ENTRY(cdchanger)          changer_links;
332         STAILQ_HEAD(chdevlist, cd_softc) chluns;
333 };
334
335 static struct mtx changerq_mtx;
336 static STAILQ_HEAD(changerlist, cdchanger) changerq;
337 static int num_changers;
338
339 MALLOC_DEFINE(M_SCSICD, "scsi_cd", "scsi_cd buffers");
340
341 static void
342 cdinit(void)
343 {
344         cam_status status;
345
346         mtx_init(&changerq_mtx, "cdchangerq", "SCSI CD Changer List", MTX_DEF);
347         STAILQ_INIT(&changerq);
348
349         /*
350          * Install a global async callback.  This callback will
351          * receive async callbacks like "new device found".
352          */
353         status = xpt_register_async(AC_FOUND_DEVICE, cdasync, NULL, NULL);
354
355         if (status != CAM_REQ_CMP) {
356                 printf("cd: Failed to attach master async callback "
357                        "due to status 0x%x!\n", status);
358         }
359 }
360
361 static void
362 cdoninvalidate(struct cam_periph *periph)
363 {
364         struct cd_softc *softc;
365
366         softc = (struct cd_softc *)periph->softc;
367
368         /*
369          * De-register any async callbacks.
370          */
371         xpt_register_async(0, cdasync, periph, periph->path);
372
373         softc->flags |= CD_FLAG_INVALID;
374
375         /*
376          * Return all queued I/O with ENXIO.
377          * XXX Handle any transactions queued to the card
378          *     with XPT_ABORT_CCB.
379          */
380         bioq_flush(&softc->bio_queue, NULL, ENXIO);
381
382         /*
383          * If this device is part of a changer, and it was scheduled
384          * to run, remove it from the run queue since we just nuked
385          * all of its scheduled I/O.
386          */
387         if ((softc->flags & CD_FLAG_CHANGER)
388          && (softc->pinfo.index != CAM_UNQUEUED_INDEX))
389                 camq_remove(&softc->changer->devq, softc->pinfo.index);
390
391         disk_gone(softc->disk);
392         xpt_print(periph->path, "lost device\n");
393 }
394
395 static void
396 cdcleanup(struct cam_periph *periph)
397 {
398         struct cd_softc *softc;
399
400         softc = (struct cd_softc *)periph->softc;
401
402         xpt_print(periph->path, "removing device entry\n");
403
404         /*
405          * In the queued, non-active case, the device in question
406          * has already been removed from the changer run queue.  Since this
407          * device is active, we need to de-activate it, and schedule
408          * another device to run.  (if there is another one to run)
409          */
410         if ((softc->flags & CD_FLAG_CHANGER)
411          && (softc->flags & CD_FLAG_ACTIVE)) {
412
413                 /*
414                  * The purpose of the short timeout is soley to determine
415                  * whether the current device has finished or not.  Well,
416                  * since we're removing the active device, we know that it
417                  * is finished.  So, get rid of the short timeout.
418                  * Otherwise, if we're in the time period before the short
419                  * timeout fires, and there are no other devices in the
420                  * queue to run, there won't be any other device put in the
421                  * active slot.  i.e., when we call cdrunchangerqueue()
422                  * below, it won't do anything.  Then, when the short
423                  * timeout fires, it'll look at the "current device", which
424                  * we are free below, and possibly panic the kernel on a
425                  * bogus pointer reference.
426                  *
427                  * The long timeout doesn't really matter, since we
428                  * decrement the qfrozen_cnt to indicate that there is
429                  * nothing in the active slot now.  Therefore, there won't
430                  * be any bogus pointer references there.
431                  */
432                 if (softc->changer->flags & CHANGER_SHORT_TMOUT_SCHED) {
433                         callout_stop(&softc->changer->short_handle);
434                         softc->changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
435                 }
436                 softc->changer->devq.qfrozen_cnt[0]--;
437                 softc->changer->flags |= CHANGER_MANUAL_CALL;
438                 cdrunchangerqueue(softc->changer);
439         }
440
441         /*
442          * If we're removing the last device on the changer, go ahead and
443          * remove the changer device structure.
444          */
445         if ((softc->flags & CD_FLAG_CHANGER)
446          && (--softc->changer->num_devices == 0)) {
447
448                 /*
449                  * Theoretically, there shouldn't be any timeouts left, but
450                  * I'm not completely sure that that will be the case.  So,
451                  * it won't hurt to check and see if there are any left.
452                  */
453                 if (softc->changer->flags & CHANGER_TIMEOUT_SCHED) {
454                         callout_stop(&softc->changer->long_handle);
455                         softc->changer->flags &= ~CHANGER_TIMEOUT_SCHED;
456                 }
457
458                 if (softc->changer->flags & CHANGER_SHORT_TMOUT_SCHED) {
459                         callout_stop(&softc->changer->short_handle);
460                         softc->changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
461                 }
462
463                 mtx_lock(&changerq_mtx);
464                 STAILQ_REMOVE(&changerq, softc->changer, cdchanger,
465                               changer_links);
466                 num_changers--;
467                 mtx_unlock(&changerq_mtx);
468                 xpt_print(periph->path, "removing changer entry\n");
469                 free(softc->changer, M_DEVBUF);
470         }
471         cam_periph_unlock(periph);
472         if ((softc->flags & CD_FLAG_SCTX_INIT) != 0
473             && sysctl_ctx_free(&softc->sysctl_ctx) != 0) {
474                 xpt_print(periph->path, "can't remove sysctl context\n");
475         }
476
477         disk_destroy(softc->disk);
478         free(softc, M_DEVBUF);
479         cam_periph_lock(periph);
480 }
481
482 static void
483 cdasync(void *callback_arg, u_int32_t code,
484         struct cam_path *path, void *arg)
485 {
486         struct cam_periph *periph;
487
488         periph = (struct cam_periph *)callback_arg;
489         switch (code) {
490         case AC_FOUND_DEVICE:
491         {
492                 struct ccb_getdev *cgd;
493                 cam_status status;
494
495                 cgd = (struct ccb_getdev *)arg;
496                 if (cgd == NULL)
497                         break;
498
499                 if (cgd->protocol != PROTO_SCSI)
500                         break;
501
502                 if (SID_TYPE(&cgd->inq_data) != T_CDROM
503                     && SID_TYPE(&cgd->inq_data) != T_WORM)
504                         break;
505
506                 /*
507                  * Allocate a peripheral instance for
508                  * this device and start the probe
509                  * process.
510                  */
511                 status = cam_periph_alloc(cdregister, cdoninvalidate,
512                                           cdcleanup, cdstart,
513                                           "cd", CAM_PERIPH_BIO,
514                                           cgd->ccb_h.path, cdasync,
515                                           AC_FOUND_DEVICE, cgd);
516
517                 if (status != CAM_REQ_CMP
518                  && status != CAM_REQ_INPROG)
519                         printf("cdasync: Unable to attach new device "
520                                "due to status 0x%x\n", status);
521
522                 break;
523         }
524         case AC_SENT_BDR:
525         case AC_BUS_RESET:
526         {
527                 struct cd_softc *softc;
528                 struct ccb_hdr *ccbh;
529
530                 softc = (struct cd_softc *)periph->softc;
531                 /*
532                  * Don't fail on the expected unit attention
533                  * that will occur.
534                  */
535                 softc->flags |= CD_FLAG_RETRY_UA;
536                 LIST_FOREACH(ccbh, &softc->pending_ccbs, periph_links.le)
537                         ccbh->ccb_state |= CD_CCB_RETRY_UA;
538                 /* FALLTHROUGH */
539         }
540         default:
541                 cam_periph_async(periph, code, path, arg);
542                 break;
543         }
544 }
545
546 static void
547 cdsysctlinit(void *context, int pending)
548 {
549         struct cam_periph *periph;
550         struct cd_softc *softc;
551         char tmpstr[80], tmpstr2[80];
552
553         periph = (struct cam_periph *)context;
554         if (cam_periph_acquire(periph) != CAM_REQ_CMP)
555                 return;
556
557         softc = (struct cd_softc *)periph->softc;
558         snprintf(tmpstr, sizeof(tmpstr), "CAM CD unit %d", periph->unit_number);
559         snprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number);
560
561         sysctl_ctx_init(&softc->sysctl_ctx);
562         softc->flags |= CD_FLAG_SCTX_INIT;
563         softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
564                 SYSCTL_STATIC_CHILDREN(_kern_cam_cd), OID_AUTO,
565                 tmpstr2, CTLFLAG_RD, 0, tmpstr);
566
567         if (softc->sysctl_tree == NULL) {
568                 printf("cdsysctlinit: unable to allocate sysctl tree\n");
569                 cam_periph_release(periph);
570                 return;
571         }
572
573         /*
574          * Now register the sysctl handler, so the user can the value on
575          * the fly.
576          */
577         SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
578                 OID_AUTO, "minimum_cmd_size", CTLTYPE_INT | CTLFLAG_RW,
579                 &softc->minimum_command_size, 0, cdcmdsizesysctl, "I",
580                 "Minimum CDB size");
581
582         cam_periph_release(periph);
583 }
584
585 /*
586  * We have a handler function for this so we can check the values when the
587  * user sets them, instead of every time we look at them.
588  */
589 static int
590 cdcmdsizesysctl(SYSCTL_HANDLER_ARGS)
591 {
592         int error, value;
593
594         value = *(int *)arg1;
595
596         error = sysctl_handle_int(oidp, &value, 0, req);
597
598         if ((error != 0)
599          || (req->newptr == NULL))
600                 return (error);
601
602         /*
603          * The only real values we can have here are 6 or 10.  I don't
604          * really forsee having 12 be an option at any time in the future.
605          * So if the user sets something less than or equal to 6, we'll set
606          * it to 6.  If he sets something greater than 6, we'll set it to 10.
607          *
608          * I suppose we could just return an error here for the wrong values,
609          * but I don't think it's necessary to do so, as long as we can
610          * determine the user's intent without too much trouble.
611          */
612         if (value < 6)
613                 value = 6;
614         else if (value > 6)
615                 value = 10;
616
617         *(int *)arg1 = value;
618
619         return (0);
620 }
621
622 static cam_status
623 cdregister(struct cam_periph *periph, void *arg)
624 {
625         struct cd_softc *softc;
626         struct ccb_pathinq cpi;
627         struct ccb_getdev *cgd;
628         char tmpstr[80];
629         caddr_t match;
630
631         cgd = (struct ccb_getdev *)arg;
632         if (periph == NULL) {
633                 printf("cdregister: periph was NULL!!\n");
634                 return(CAM_REQ_CMP_ERR);
635         }
636         if (cgd == NULL) {
637                 printf("cdregister: no getdev CCB, can't register device\n");
638                 return(CAM_REQ_CMP_ERR);
639         }
640
641         softc = (struct cd_softc *)malloc(sizeof(*softc),M_DEVBUF,M_NOWAIT);
642
643         if (softc == NULL) {
644                 printf("cdregister: Unable to probe new device. "
645                        "Unable to allocate softc\n");                           
646                 return(CAM_REQ_CMP_ERR);
647         }
648
649         bzero(softc, sizeof(*softc));
650         LIST_INIT(&softc->pending_ccbs);
651         STAILQ_INIT(&softc->mode_queue);
652         softc->state = CD_STATE_PROBE;
653         bioq_init(&softc->bio_queue);
654         if (SID_IS_REMOVABLE(&cgd->inq_data))
655                 softc->flags |= CD_FLAG_DISC_REMOVABLE;
656         if ((cgd->inq_data.flags & SID_CmdQue) != 0)
657                 softc->flags |= CD_FLAG_TAGGED_QUEUING;
658
659         periph->softc = softc;
660         softc->periph = periph;
661
662         /*
663          * See if this device has any quirks.
664          */
665         match = cam_quirkmatch((caddr_t)&cgd->inq_data,
666                                (caddr_t)cd_quirk_table,
667                                sizeof(cd_quirk_table)/sizeof(*cd_quirk_table),
668                                sizeof(*cd_quirk_table), scsi_inquiry_match);
669
670         if (match != NULL)
671                 softc->quirks = ((struct cd_quirk_entry *)match)->quirks;
672         else
673                 softc->quirks = CD_Q_NONE;
674
675         /* Check if the SIM does not want 6 byte commands */
676         bzero(&cpi, sizeof(cpi));
677         xpt_setup_ccb(&cpi.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
678         cpi.ccb_h.func_code = XPT_PATH_INQ;
679         xpt_action((union ccb *)&cpi);
680         if (cpi.ccb_h.status == CAM_REQ_CMP && (cpi.hba_misc & PIM_NO_6_BYTE))
681                 softc->quirks |= CD_Q_10_BYTE_ONLY;
682
683         TASK_INIT(&softc->sysctl_task, 0, cdsysctlinit, periph);
684
685         /* The default is 6 byte commands, unless quirked otherwise */
686         if (softc->quirks & CD_Q_10_BYTE_ONLY)
687                 softc->minimum_command_size = 10;
688         else
689                 softc->minimum_command_size = 6;
690
691         /*
692          * Load the user's default, if any.
693          */
694         snprintf(tmpstr, sizeof(tmpstr), "kern.cam.cd.%d.minimum_cmd_size",
695                  periph->unit_number);
696         TUNABLE_INT_FETCH(tmpstr, &softc->minimum_command_size);
697
698         /* 6 and 10 are the only permissible values here. */
699         if (softc->minimum_command_size < 6)
700                 softc->minimum_command_size = 6;
701         else if (softc->minimum_command_size > 6)
702                 softc->minimum_command_size = 10;
703
704         /*
705          * We need to register the statistics structure for this device,
706          * but we don't have the blocksize yet for it.  So, we register
707          * the structure and indicate that we don't have the blocksize
708          * yet.  Unlike other SCSI peripheral drivers, we explicitly set
709          * the device type here to be CDROM, rather than just ORing in
710          * the device type.  This is because this driver can attach to either
711          * CDROM or WORM devices, and we want this peripheral driver to
712          * show up in the devstat list as a CD peripheral driver, not a
713          * WORM peripheral driver.  WORM drives will also have the WORM
714          * driver attached to them.
715          */
716         cam_periph_unlock(periph);
717         softc->disk = disk_alloc();
718         softc->disk->d_devstat = devstat_new_entry("cd", 
719                           periph->unit_number, 0,
720                           DEVSTAT_BS_UNAVAILABLE,
721                           DEVSTAT_TYPE_CDROM | DEVSTAT_TYPE_IF_SCSI,
722                           DEVSTAT_PRIORITY_CD);
723         softc->disk->d_open = cdopen;
724         softc->disk->d_close = cdclose;
725         softc->disk->d_strategy = cdstrategy;
726         softc->disk->d_ioctl = cdioctl;
727         softc->disk->d_name = "cd";
728         softc->disk->d_unit = periph->unit_number;
729         softc->disk->d_drv1 = periph;
730         if (cpi.maxio == 0)
731                 softc->disk->d_maxsize = DFLTPHYS;      /* traditional default */
732         else if (cpi.maxio > MAXPHYS)
733                 softc->disk->d_maxsize = MAXPHYS;       /* for safety */
734         else
735                 softc->disk->d_maxsize = cpi.maxio;
736         softc->disk->d_flags = 0;
737         disk_create(softc->disk, DISK_VERSION);
738         cam_periph_lock(periph);
739
740         /*
741          * Add an async callback so that we get
742          * notified if this device goes away.
743          */
744         xpt_register_async(AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE,
745                            cdasync, periph, periph->path);
746
747         /*
748          * If the target lun is greater than 0, we most likely have a CD
749          * changer device.  Check the quirk entries as well, though, just
750          * in case someone has a CD tower with one lun per drive or
751          * something like that.  Also, if we know up front that a
752          * particular device is a changer, we can mark it as such starting
753          * with lun 0, instead of lun 1.  It shouldn't be necessary to have
754          * a quirk entry to define something as a changer, however.
755          */
756         if (((cgd->ccb_h.target_lun > 0)
757           && ((softc->quirks & CD_Q_NO_CHANGER) == 0))
758          || ((softc->quirks & CD_Q_CHANGER) != 0)) {
759                 struct cdchanger *nchanger;
760                 struct cam_periph *nperiph;
761                 struct cam_path *path;
762                 cam_status status;
763                 int found;
764
765                 /* Set the changer flag in the current device's softc */
766                 softc->flags |= CD_FLAG_CHANGER;
767
768                 /*
769                  * Now, look around for an existing changer device with the
770                  * same path and target ID as the current device.
771                  */
772                 mtx_lock(&changerq_mtx);
773                 for (found = 0,
774                      nchanger = (struct cdchanger *)STAILQ_FIRST(&changerq);
775                      nchanger != NULL;
776                      nchanger = STAILQ_NEXT(nchanger, changer_links)){
777                         if ((nchanger->path_id == cgd->ccb_h.path_id) 
778                          && (nchanger->target_id == cgd->ccb_h.target_id)) {
779                                 found = 1;
780                                 break;
781                         }
782                 }
783                 mtx_unlock(&changerq_mtx);
784
785                 /*
786                  * If we found a matching entry, just add this device to
787                  * the list of devices on this changer.
788                  */
789                 if (found == 1) {
790                         struct chdevlist *chlunhead;
791
792                         chlunhead = &nchanger->chluns;
793
794                         /*
795                          * XXX KDM look at consolidating this code with the
796                          * code below in a separate function.
797                          */
798
799                         /*
800                          * Create a path with lun id 0, and see if we can
801                          * find a matching device
802                          */
803                         status = xpt_create_path(&path, /*periph*/ periph,
804                                                  cgd->ccb_h.path_id,
805                                                  cgd->ccb_h.target_id, 0);
806
807                         if ((status == CAM_REQ_CMP)
808                          && ((nperiph = cam_periph_find(path, "cd")) != NULL)){
809                                 struct cd_softc *nsoftc;
810
811                                 nsoftc = (struct cd_softc *)nperiph->softc;
812
813                                 if ((nsoftc->flags & CD_FLAG_CHANGER) == 0){
814                                         nsoftc->flags |= CD_FLAG_CHANGER;
815                                         nchanger->num_devices++;
816                                         if (camq_resize(&nchanger->devq,
817                                            nchanger->num_devices)!=CAM_REQ_CMP){
818                                                 printf("cdregister: "
819                                                        "camq_resize "
820                                                        "failed, changer "
821                                                        "support may "
822                                                        "be messed up\n");
823                                         }
824                                         nsoftc->changer = nchanger;
825                                         nsoftc->pinfo.index =CAM_UNQUEUED_INDEX;
826
827                                         STAILQ_INSERT_TAIL(&nchanger->chluns,
828                                                           nsoftc,changer_links);
829                                 }
830                                 xpt_free_path(path);
831                         } else if (status == CAM_REQ_CMP)
832                                 xpt_free_path(path);
833                         else {
834                                 printf("cdregister: unable to allocate path\n"
835                                        "cdregister: changer support may be "
836                                        "broken\n");
837                         }
838
839                         nchanger->num_devices++;
840
841                         softc->changer = nchanger;
842                         softc->pinfo.index = CAM_UNQUEUED_INDEX;
843
844                         if (camq_resize(&nchanger->devq,
845                             nchanger->num_devices) != CAM_REQ_CMP) {
846                                 printf("cdregister: camq_resize "
847                                        "failed, changer support may "
848                                        "be messed up\n");
849                         }
850
851                         STAILQ_INSERT_TAIL(chlunhead, softc, changer_links);
852                 }
853                 /*
854                  * In this case, we don't already have an entry for this
855                  * particular changer, so we need to create one, add it to
856                  * the queue, and queue this device on the list for this
857                  * changer.  Before we queue this device, however, we need
858                  * to search for lun id 0 on this target, and add it to the
859                  * queue first, if it exists.  (and if it hasn't already
860                  * been marked as part of the changer.)
861                  */
862                 else {
863                         nchanger = malloc(sizeof(struct cdchanger),
864                                 M_DEVBUF, M_NOWAIT);
865
866                         if (nchanger == NULL) {
867                                 softc->flags &= ~CD_FLAG_CHANGER;
868                                 printf("cdregister: unable to malloc "
869                                        "changer structure\ncdregister: "
870                                        "changer support disabled\n");
871
872                                 /*
873                                  * Yes, gotos can be gross but in this case
874                                  * I think it's justified..
875                                  */
876                                 goto cdregisterexit;
877                         }
878
879                         /* zero the structure */
880                         bzero(nchanger, sizeof(struct cdchanger));
881
882                         if (camq_init(&nchanger->devq, 1) != 0) {
883                                 softc->flags &= ~CD_FLAG_CHANGER;
884                                 printf("cdregister: changer support "
885                                        "disabled\n");
886                                 goto cdregisterexit;
887                         }
888
889                         nchanger->path_id = cgd->ccb_h.path_id;
890                         nchanger->target_id = cgd->ccb_h.target_id;
891
892                         /* this is superfluous, but it makes things clearer */
893                         nchanger->num_devices = 0;
894
895                         STAILQ_INIT(&nchanger->chluns);
896
897                         callout_init_mtx(&nchanger->long_handle,
898                             periph->sim->mtx, 0);
899                         callout_init_mtx(&nchanger->short_handle,
900                             periph->sim->mtx, 0);
901
902                         mtx_lock(&changerq_mtx);
903                         num_changers++;
904                         STAILQ_INSERT_TAIL(&changerq, nchanger,
905                                            changer_links);
906                         mtx_unlock(&changerq_mtx);
907                         
908                         /*
909                          * Create a path with lun id 0, and see if we can
910                          * find a matching device
911                          */
912                         status = xpt_create_path(&path, /*periph*/ periph,
913                                                  cgd->ccb_h.path_id,
914                                                  cgd->ccb_h.target_id, 0);
915
916                         /*
917                          * If we were able to allocate the path, and if we
918                          * find a matching device and it isn't already
919                          * marked as part of a changer, then we add it to
920                          * the current changer.
921                          */
922                         if ((status == CAM_REQ_CMP)
923                          && ((nperiph = cam_periph_find(path, "cd")) != NULL)
924                          && ((((struct cd_softc *)periph->softc)->flags &
925                                CD_FLAG_CHANGER) == 0)) {
926                                 struct cd_softc *nsoftc;
927
928                                 nsoftc = (struct cd_softc *)nperiph->softc;
929
930                                 nsoftc->flags |= CD_FLAG_CHANGER;
931                                 nchanger->num_devices++;
932                                 if (camq_resize(&nchanger->devq,
933                                     nchanger->num_devices) != CAM_REQ_CMP) {
934                                         printf("cdregister: camq_resize "
935                                                "failed, changer support may "
936                                                "be messed up\n");
937                                 }
938                                 nsoftc->changer = nchanger;
939                                 nsoftc->pinfo.index = CAM_UNQUEUED_INDEX;
940
941                                 STAILQ_INSERT_TAIL(&nchanger->chluns,
942                                                    nsoftc, changer_links);
943                                 xpt_free_path(path);
944                         } else if (status == CAM_REQ_CMP)
945                                 xpt_free_path(path);
946                         else {
947                                 printf("cdregister: unable to allocate path\n"
948                                        "cdregister: changer support may be "
949                                        "broken\n");
950                         }
951
952                         softc->changer = nchanger;
953                         softc->pinfo.index = CAM_UNQUEUED_INDEX;
954                         nchanger->num_devices++;
955                         if (camq_resize(&nchanger->devq,
956                             nchanger->num_devices) != CAM_REQ_CMP) {
957                                 printf("cdregister: camq_resize "
958                                        "failed, changer support may "
959                                        "be messed up\n");
960                         }
961                         STAILQ_INSERT_TAIL(&nchanger->chluns, softc,
962                                            changer_links);
963                 }
964         }
965
966 cdregisterexit:
967
968         /*
969          * Refcount and block open attempts until we are setup
970          * Can't block
971          */
972         (void)cam_periph_hold(periph, PRIBIO);
973
974         if ((softc->flags & CD_FLAG_CHANGER) == 0)
975                 xpt_schedule(periph, CAM_PRIORITY_DEV);
976         else
977                 cdschedule(periph, CAM_PRIORITY_DEV);
978
979         return(CAM_REQ_CMP);
980 }
981
982 static int
983 cdopen(struct disk *dp)
984 {
985         struct cam_periph *periph;
986         struct cd_softc *softc;
987         int error;
988
989         periph = (struct cam_periph *)dp->d_drv1;
990         if (periph == NULL)
991                 return (ENXIO);
992
993         softc = (struct cd_softc *)periph->softc;
994
995         if (cam_periph_acquire(periph) != CAM_REQ_CMP)
996                 return(ENXIO);
997
998         cam_periph_lock(periph);
999
1000         if (softc->flags & CD_FLAG_INVALID) {
1001                 cam_periph_unlock(periph);
1002                 cam_periph_release(periph);
1003                 return(ENXIO);
1004         }
1005
1006         if ((error = cam_periph_hold(periph, PRIBIO | PCATCH)) != 0) {
1007                 cam_periph_unlock(periph);
1008                 cam_periph_release(periph);
1009                 return (error);
1010         }
1011
1012         /*
1013          * Check for media, and set the appropriate flags.  We don't bail
1014          * if we don't have media, but then we don't allow anything but the
1015          * CDIOCEJECT/CDIOCCLOSE ioctls if there is no media.
1016          */
1017         cdcheckmedia(periph);
1018
1019         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("leaving cdopen\n"));
1020         cam_periph_unhold(periph);
1021
1022         /* Closes aren't symmetrical with opens, so fix up the refcounting. */
1023         if ((softc->flags & CD_FLAG_OPEN) == 0) {
1024                 softc->flags |= CD_FLAG_OPEN;
1025                 cam_periph_unlock(periph);
1026         } else {
1027                 cam_periph_unlock(periph);
1028                 cam_periph_release(periph);
1029         }
1030
1031         return (0);
1032 }
1033
1034 static int
1035 cdclose(struct disk *dp)
1036 {
1037         struct  cam_periph *periph;
1038         struct  cd_softc *softc;
1039
1040         periph = (struct cam_periph *)dp->d_drv1;
1041         if (periph == NULL)
1042                 return (ENXIO); 
1043
1044         softc = (struct cd_softc *)periph->softc;
1045
1046         cam_periph_lock(periph);
1047         cam_periph_hold(periph, PRIBIO);
1048
1049         if ((softc->flags & CD_FLAG_DISC_REMOVABLE) != 0)
1050                 cdprevent(periph, PR_ALLOW);
1051
1052         /*
1053          * Since we're closing this CD, mark the blocksize as unavailable.
1054          * It will be marked as available when the CD is opened again.
1055          */
1056         softc->disk->d_devstat->flags |= DEVSTAT_BS_UNAVAILABLE;
1057
1058         /*
1059          * We'll check the media and toc again at the next open().
1060          */
1061         softc->flags &= ~(CD_FLAG_VALID_MEDIA|CD_FLAG_VALID_TOC|CD_FLAG_OPEN);
1062
1063         cam_periph_unhold(periph);
1064         cam_periph_unlock(periph);
1065         cam_periph_release(periph);
1066
1067         return (0);
1068 }
1069
1070 static void
1071 cdshorttimeout(void *arg)
1072 {
1073         struct cdchanger *changer;
1074
1075         changer = (struct cdchanger *)arg;
1076
1077         /* Always clear the short timeout flag, since that's what we're in */
1078         changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
1079
1080         /*
1081          * Check to see if there is any more pending or outstanding I/O for
1082          * this device.  If not, move it out of the active slot.
1083          */
1084         if ((bioq_first(&changer->cur_device->bio_queue) == NULL)
1085          && (changer->cur_device->outstanding_cmds == 0)) {
1086                 changer->flags |= CHANGER_MANUAL_CALL;
1087                 cdrunchangerqueue(changer);
1088         }
1089 }
1090
1091 /*
1092  * This is a wrapper for xpt_schedule.  It only applies to changers.
1093  */
1094 static void
1095 cdschedule(struct cam_periph *periph, int priority)
1096 {
1097         struct cd_softc *softc;
1098
1099         softc = (struct cd_softc *)periph->softc;
1100
1101         /*
1102          * If this device isn't currently queued, and if it isn't
1103          * the active device, then we queue this device and run the
1104          * changer queue if there is no timeout scheduled to do it.
1105          * If this device is the active device, just schedule it
1106          * to run again.  If this device is queued, there should be
1107          * a timeout in place already that will make sure it runs.
1108          */
1109         if ((softc->pinfo.index == CAM_UNQUEUED_INDEX) 
1110          && ((softc->flags & CD_FLAG_ACTIVE) == 0)) {
1111                 /*
1112                  * We don't do anything with the priority here.
1113                  * This is strictly a fifo queue.
1114                  */
1115                 softc->pinfo.priority = CAM_PRIORITY_NORMAL;
1116                 softc->pinfo.generation = ++softc->changer->devq.generation;
1117                 camq_insert(&softc->changer->devq, (cam_pinfo *)softc);
1118
1119                 /*
1120                  * Since we just put a device in the changer queue,
1121                  * check and see if there is a timeout scheduled for
1122                  * this changer.  If so, let the timeout handle
1123                  * switching this device into the active slot.  If
1124                  * not, manually call the timeout routine to
1125                  * bootstrap things.
1126                  */
1127                 if (((softc->changer->flags & CHANGER_TIMEOUT_SCHED)==0)
1128                  && ((softc->changer->flags & CHANGER_NEED_TIMEOUT)==0)
1129                  && ((softc->changer->flags & CHANGER_SHORT_TMOUT_SCHED)==0)){
1130                         softc->changer->flags |= CHANGER_MANUAL_CALL;
1131                         cdrunchangerqueue(softc->changer);
1132                 }
1133         } else if ((softc->flags & CD_FLAG_ACTIVE)
1134                 && ((softc->flags & CD_FLAG_SCHED_ON_COMP) == 0))
1135                 xpt_schedule(periph, priority);
1136 }
1137
1138 static void
1139 cdrunchangerqueue(void *arg)
1140 {
1141         struct cd_softc *softc;
1142         struct cdchanger *changer;
1143         int called_from_timeout;
1144
1145         changer = (struct cdchanger *)arg;
1146
1147         /*
1148          * If we have NOT been called from cdstrategy() or cddone(), and
1149          * instead from a timeout routine, go ahead and clear the
1150          * timeout flag.
1151          */
1152         if ((changer->flags & CHANGER_MANUAL_CALL) == 0) {
1153                 changer->flags &= ~CHANGER_TIMEOUT_SCHED;
1154                 called_from_timeout = 1;
1155         } else
1156                 called_from_timeout = 0;
1157
1158         /* Always clear the manual call flag */
1159         changer->flags &= ~CHANGER_MANUAL_CALL;
1160
1161         /* nothing to do if the queue is empty */
1162         if (changer->devq.entries <= 0) {
1163                 return;
1164         }
1165
1166         /*
1167          * If the changer queue is frozen, that means we have an active
1168          * device.
1169          */
1170         if (changer->devq.qfrozen_cnt[0] > 0) {
1171
1172                 /*
1173                  * We always need to reset the frozen count and clear the
1174                  * active flag.
1175                  */
1176                 changer->devq.qfrozen_cnt[0]--;
1177                 changer->cur_device->flags &= ~CD_FLAG_ACTIVE;
1178                 changer->cur_device->flags &= ~CD_FLAG_SCHED_ON_COMP;
1179
1180                 if (changer->cur_device->outstanding_cmds > 0) {
1181                         changer->cur_device->flags |= CD_FLAG_SCHED_ON_COMP;
1182                         changer->cur_device->bufs_left = 
1183                                 changer->cur_device->outstanding_cmds;
1184                         if (called_from_timeout) {
1185                                 callout_reset(&changer->long_handle,
1186                                     changer_max_busy_seconds * hz,
1187                                     cdrunchangerqueue, changer);
1188                                 changer->flags |= CHANGER_TIMEOUT_SCHED;
1189                         }
1190                         return;
1191                 }
1192
1193                 /*
1194                  * Check to see whether the current device has any I/O left
1195                  * to do.  If so, requeue it at the end of the queue.  If
1196                  * not, there is no need to requeue it.
1197                  */
1198                 if (bioq_first(&changer->cur_device->bio_queue) != NULL) {
1199
1200                         changer->cur_device->pinfo.generation =
1201                                 ++changer->devq.generation;
1202                         camq_insert(&changer->devq,
1203                                 (cam_pinfo *)changer->cur_device);
1204                 } 
1205         }
1206
1207         softc = (struct cd_softc *)camq_remove(&changer->devq, CAMQ_HEAD);
1208
1209         changer->cur_device = softc;
1210
1211         changer->devq.qfrozen_cnt[0]++;
1212         softc->flags |= CD_FLAG_ACTIVE;
1213
1214         /* Just in case this device is waiting */
1215         wakeup(&softc->changer);
1216         xpt_schedule(softc->periph, CAM_PRIORITY_NORMAL);
1217
1218         /*
1219          * Get rid of any pending timeouts, and set a flag to schedule new
1220          * ones so this device gets its full time quantum.
1221          */
1222         if (changer->flags & CHANGER_TIMEOUT_SCHED) {
1223                 callout_stop(&changer->long_handle);
1224                 changer->flags &= ~CHANGER_TIMEOUT_SCHED;
1225         }
1226
1227         if (changer->flags & CHANGER_SHORT_TMOUT_SCHED) {
1228                 callout_stop(&changer->short_handle);
1229                 changer->flags &= ~CHANGER_SHORT_TMOUT_SCHED;
1230         }
1231
1232         /*
1233          * We need to schedule timeouts, but we only do this after the
1234          * first transaction has completed.  This eliminates the changer
1235          * switch time.
1236          */
1237         changer->flags |= CHANGER_NEED_TIMEOUT;
1238 }
1239
1240 static void
1241 cdchangerschedule(struct cd_softc *softc)
1242 {
1243         struct cdchanger *changer;
1244
1245         changer = softc->changer;
1246
1247         /*
1248          * If this is a changer, and this is the current device,
1249          * and this device has at least the minimum time quantum to
1250          * run, see if we can switch it out.
1251          */
1252         if ((softc->flags & CD_FLAG_ACTIVE) 
1253          && ((changer->flags & CHANGER_SHORT_TMOUT_SCHED) == 0)
1254          && ((changer->flags & CHANGER_NEED_TIMEOUT) == 0)) {
1255                 /*
1256                  * We try three things here.  The first is that we
1257                  * check to see whether the schedule on completion
1258                  * flag is set.  If it is, we decrement the number
1259                  * of buffers left, and if it's zero, we reschedule.
1260                  * Next, we check to see whether the pending buffer
1261                  * queue is empty and whether there are no
1262                  * outstanding transactions.  If so, we reschedule.
1263                  * Next, we see if the pending buffer queue is empty.
1264                  * If it is, we set the number of buffers left to
1265                  * the current active buffer count and set the
1266                  * schedule on complete flag.
1267                  */
1268                 if (softc->flags & CD_FLAG_SCHED_ON_COMP) {
1269                         if (--softc->bufs_left == 0) {
1270                                 softc->changer->flags |=
1271                                         CHANGER_MANUAL_CALL;
1272                                 softc->flags &= ~CD_FLAG_SCHED_ON_COMP;
1273                                 cdrunchangerqueue(softc->changer);
1274                         }
1275                 } else if ((bioq_first(&softc->bio_queue) == NULL)
1276                         && (softc->outstanding_cmds == 0)) {
1277                         softc->changer->flags |= CHANGER_MANUAL_CALL;
1278                         cdrunchangerqueue(softc->changer);
1279                 }
1280         } else if ((softc->changer->flags & CHANGER_NEED_TIMEOUT) 
1281                 && (softc->flags & CD_FLAG_ACTIVE)) {
1282
1283                 /*
1284                  * Now that the first transaction to this
1285                  * particular device has completed, we can go ahead
1286                  * and schedule our timeouts.
1287                  */
1288                 if ((changer->flags & CHANGER_TIMEOUT_SCHED) == 0) {
1289                         callout_reset(&changer->long_handle,
1290                             changer_max_busy_seconds * hz,
1291                             cdrunchangerqueue, changer);
1292                         changer->flags |= CHANGER_TIMEOUT_SCHED;
1293                 } else
1294                         printf("cdchangerschedule: already have a long"
1295                                " timeout!\n");
1296
1297                 if ((changer->flags & CHANGER_SHORT_TMOUT_SCHED) == 0) {
1298                         callout_reset(&changer->short_handle,
1299                             changer_min_busy_seconds * hz,
1300                             cdshorttimeout, changer);
1301                         changer->flags |= CHANGER_SHORT_TMOUT_SCHED;
1302                 } else
1303                         printf("cdchangerschedule: already have a short "
1304                                "timeout!\n");
1305
1306                 /*
1307                  * We just scheduled timeouts, no need to schedule
1308                  * more.
1309                  */
1310                 changer->flags &= ~CHANGER_NEED_TIMEOUT;
1311
1312         }
1313 }
1314
1315 static int
1316 cdrunccb(union ccb *ccb, int (*error_routine)(union ccb *ccb,
1317                                               u_int32_t cam_flags,
1318                                               u_int32_t sense_flags),
1319          u_int32_t cam_flags, u_int32_t sense_flags)
1320 {
1321         struct cd_softc *softc;
1322         struct cam_periph *periph;
1323         int error;
1324
1325         periph = xpt_path_periph(ccb->ccb_h.path);
1326         softc = (struct cd_softc *)periph->softc;
1327
1328         error = cam_periph_runccb(ccb, error_routine, cam_flags, sense_flags,
1329                                   softc->disk->d_devstat);
1330
1331         if (softc->flags & CD_FLAG_CHANGER)
1332                 cdchangerschedule(softc);
1333
1334         return(error);
1335 }
1336
1337 static union ccb *
1338 cdgetccb(struct cam_periph *periph, u_int32_t priority)
1339 {
1340         struct cd_softc *softc;
1341
1342         softc = (struct cd_softc *)periph->softc;
1343
1344         if (softc->flags & CD_FLAG_CHANGER) {
1345                 /*
1346                  * This should work the first time this device is woken up,
1347                  * but just in case it doesn't, we use a while loop.
1348                  */
1349                 while ((softc->flags & CD_FLAG_ACTIVE) == 0) {
1350                         /*
1351                          * If this changer isn't already queued, queue it up.
1352                          */
1353                         if (softc->pinfo.index == CAM_UNQUEUED_INDEX) {
1354                                 softc->pinfo.priority = CAM_PRIORITY_NORMAL;
1355                                 softc->pinfo.generation =
1356                                         ++softc->changer->devq.generation;
1357                                 camq_insert(&softc->changer->devq,
1358                                             (cam_pinfo *)softc);
1359                         }
1360                         if (((softc->changer->flags & CHANGER_TIMEOUT_SCHED)==0)
1361                          && ((softc->changer->flags & CHANGER_NEED_TIMEOUT)==0)
1362                          && ((softc->changer->flags
1363                               & CHANGER_SHORT_TMOUT_SCHED)==0)) {
1364                                 softc->changer->flags |= CHANGER_MANUAL_CALL;
1365                                 cdrunchangerqueue(softc->changer);
1366                         } else
1367                                 msleep(&softc->changer, periph->sim->mtx,
1368                                     PRIBIO, "cgticb", 0);
1369                 }
1370         }
1371         return(cam_periph_getccb(periph, priority));
1372 }
1373
1374
1375 /*
1376  * Actually translate the requested transfer into one the physical driver
1377  * can understand.  The transfer is described by a buf and will include
1378  * only one physical transfer.
1379  */
1380 static void
1381 cdstrategy(struct bio *bp)
1382 {
1383         struct cam_periph *periph;
1384         struct cd_softc *softc;
1385
1386         periph = (struct cam_periph *)bp->bio_disk->d_drv1;
1387         if (periph == NULL) {
1388                 biofinish(bp, NULL, ENXIO);
1389                 return;
1390         }
1391
1392         cam_periph_lock(periph);
1393         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdstrategy\n"));
1394
1395         softc = (struct cd_softc *)periph->softc;
1396
1397         /*
1398          * If the device has been made invalid, error out
1399          */
1400         if ((softc->flags & CD_FLAG_INVALID)) {
1401                 cam_periph_unlock(periph);
1402                 biofinish(bp, NULL, ENXIO);
1403                 return;
1404         }
1405
1406         /*
1407          * If we don't have valid media, look for it before trying to
1408          * schedule the I/O.
1409          */
1410         if ((softc->flags & CD_FLAG_VALID_MEDIA) == 0) {
1411                 int error;
1412
1413                 error = cdcheckmedia(periph);
1414                 if (error != 0) {
1415                         cam_periph_unlock(periph);
1416                         biofinish(bp, NULL, error);
1417                         return;
1418                 }
1419         }
1420
1421         /*
1422          * Place it in the queue of disk activities for this disk
1423          */
1424         bioq_disksort(&softc->bio_queue, bp);
1425
1426         /*
1427          * Schedule ourselves for performing the work.  We do things
1428          * differently for changers.
1429          */
1430         if ((softc->flags & CD_FLAG_CHANGER) == 0)
1431                 xpt_schedule(periph, CAM_PRIORITY_NORMAL);
1432         else
1433                 cdschedule(periph, CAM_PRIORITY_NORMAL);
1434
1435         cam_periph_unlock(periph);
1436         return;
1437 }
1438
1439 static void
1440 cdstart(struct cam_periph *periph, union ccb *start_ccb)
1441 {
1442         struct cd_softc *softc;
1443         struct bio *bp;
1444         struct ccb_scsiio *csio;
1445         struct scsi_read_capacity_data *rcap;
1446
1447         softc = (struct cd_softc *)periph->softc;
1448
1449         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdstart\n"));
1450
1451         switch (softc->state) {
1452         case CD_STATE_NORMAL:
1453         {
1454                 bp = bioq_first(&softc->bio_queue);
1455                 if (periph->immediate_priority <= periph->pinfo.priority) {
1456                         start_ccb->ccb_h.ccb_state = CD_CCB_WAITING;
1457
1458                         SLIST_INSERT_HEAD(&periph->ccb_list, &start_ccb->ccb_h,
1459                                           periph_links.sle);
1460                         periph->immediate_priority = CAM_PRIORITY_NONE;
1461                         wakeup(&periph->ccb_list);
1462                 } else if (bp == NULL) {
1463                         xpt_release_ccb(start_ccb);
1464                 } else {
1465                         bioq_remove(&softc->bio_queue, bp);
1466
1467                         scsi_read_write(&start_ccb->csio,
1468                                         /*retries*/ cd_retry_count,
1469                                         /* cbfcnp */ cddone,
1470                                         MSG_SIMPLE_Q_TAG,
1471                                         /* read */bp->bio_cmd == BIO_READ,
1472                                         /* byte2 */ 0,
1473                                         /* minimum_cmd_size */ 10,
1474                                         /* lba */ bp->bio_offset /
1475                                           softc->params.blksize,
1476                                         bp->bio_bcount / softc->params.blksize,
1477                                         /* data_ptr */ bp->bio_data,
1478                                         /* dxfer_len */ bp->bio_bcount,
1479                                         /* sense_len */ SSD_FULL_SIZE,
1480                                         /* timeout */ 30000);
1481                         start_ccb->ccb_h.ccb_state = CD_CCB_BUFFER_IO;
1482
1483                         
1484                         LIST_INSERT_HEAD(&softc->pending_ccbs,
1485                                          &start_ccb->ccb_h, periph_links.le);
1486                         softc->outstanding_cmds++;
1487
1488                         /* We expect a unit attention from this device */
1489                         if ((softc->flags & CD_FLAG_RETRY_UA) != 0) {
1490                                 start_ccb->ccb_h.ccb_state |= CD_CCB_RETRY_UA;
1491                                 softc->flags &= ~CD_FLAG_RETRY_UA;
1492                         }
1493
1494                         start_ccb->ccb_h.ccb_bp = bp;
1495                         bp = bioq_first(&softc->bio_queue);
1496
1497                         xpt_action(start_ccb);
1498                 }
1499                 if (bp != NULL) {
1500                         /* Have more work to do, so ensure we stay scheduled */
1501                         xpt_schedule(periph, CAM_PRIORITY_NORMAL);
1502                 }
1503                 break;
1504         }
1505         case CD_STATE_PROBE:
1506         {
1507
1508                 rcap = (struct scsi_read_capacity_data *)malloc(sizeof(*rcap),
1509                                                                 M_SCSICD,
1510                                                                 M_NOWAIT);
1511                 if (rcap == NULL) {
1512                         xpt_print(periph->path,
1513                             "cdstart: Couldn't malloc read_capacity data\n");
1514                         /* cd_free_periph??? */
1515                         break;
1516                 }
1517                 csio = &start_ccb->csio;
1518                 scsi_read_capacity(csio,
1519                                    /*retries*/ cd_retry_count,
1520                                    cddone,
1521                                    MSG_SIMPLE_Q_TAG,
1522                                    rcap,
1523                                    SSD_FULL_SIZE,
1524                                    /*timeout*/20000);
1525                 start_ccb->ccb_h.ccb_bp = NULL;
1526                 start_ccb->ccb_h.ccb_state = CD_CCB_PROBE;
1527                 xpt_action(start_ccb);
1528                 break;
1529         }
1530         }
1531 }
1532
1533 static void
1534 cddone(struct cam_periph *periph, union ccb *done_ccb)
1535
1536         struct cd_softc *softc;
1537         struct ccb_scsiio *csio;
1538
1539         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cddone\n"));
1540
1541         softc = (struct cd_softc *)periph->softc;
1542         csio = &done_ccb->csio;
1543
1544         switch (csio->ccb_h.ccb_state & CD_CCB_TYPE_MASK) {
1545         case CD_CCB_BUFFER_IO:
1546         {
1547                 struct bio      *bp;
1548                 int             error;
1549
1550                 bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
1551                 error = 0;
1552
1553                 if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1554                         int sf;
1555
1556                         if ((done_ccb->ccb_h.ccb_state & CD_CCB_RETRY_UA) != 0)
1557                                 sf = SF_RETRY_UA;
1558                         else
1559                                 sf = 0;
1560
1561                         error = cderror(done_ccb, CAM_RETRY_SELTO, sf);
1562                         if (error == ERESTART) {
1563                                 /*
1564                                  * A retry was scheuled, so
1565                                  * just return.
1566                                  */
1567                                 return;
1568                         }
1569                 }
1570
1571                 if (error != 0) {
1572                         xpt_print(periph->path,
1573                             "cddone: got error %#x back\n", error);
1574                         bioq_flush(&softc->bio_queue, NULL, EIO);
1575                         bp->bio_resid = bp->bio_bcount;
1576                         bp->bio_error = error;
1577                         bp->bio_flags |= BIO_ERROR;
1578                         if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1579                                 cam_release_devq(done_ccb->ccb_h.path,
1580                                          /*relsim_flags*/0,
1581                                          /*reduction*/0,
1582                                          /*timeout*/0,
1583                                          /*getcount_only*/0);
1584
1585                 } else {
1586                         bp->bio_resid = csio->resid;
1587                         bp->bio_error = 0;
1588                         if (bp->bio_resid != 0) {
1589                                 /*
1590                                  * Short transfer ??? 
1591                                  * XXX: not sure this is correct for partial
1592                                  * transfers at EOM
1593                                  */
1594                                 bp->bio_flags |= BIO_ERROR;
1595                         }
1596                 }
1597
1598                 LIST_REMOVE(&done_ccb->ccb_h, periph_links.le);
1599                 softc->outstanding_cmds--;
1600
1601                 if (softc->flags & CD_FLAG_CHANGER)
1602                         cdchangerschedule(softc);
1603
1604                 biofinish(bp, NULL, 0);
1605                 break;
1606         }
1607         case CD_CCB_PROBE:
1608         {
1609                 struct     scsi_read_capacity_data *rdcap;
1610                 char       announce_buf[120]; /*
1611                                                * Currently (9/30/97) the 
1612                                                * longest possible announce 
1613                                                * buffer is 108 bytes, for the 
1614                                                * first error case below.  
1615                                                * That is 39 bytes for the 
1616                                                * basic string, 16 bytes for the
1617                                                * biggest sense key (hardware 
1618                                                * error), 52 bytes for the
1619                                                * text of the largest sense 
1620                                                * qualifier valid for a CDROM,
1621                                                * (0x72, 0x03 or 0x04,
1622                                                * 0x03), and one byte for the
1623                                                * null terminating character.
1624                                                * To allow for longer strings, 
1625                                                * the announce buffer is 120
1626                                                * bytes.
1627                                                */
1628                 struct     cd_params *cdp;
1629
1630                 cdp = &softc->params;
1631
1632                 rdcap = (struct scsi_read_capacity_data *)csio->data_ptr;
1633                 
1634                 cdp->disksize = scsi_4btoul (rdcap->addr) + 1;
1635                 cdp->blksize = scsi_4btoul (rdcap->length);
1636
1637                 if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1638
1639                         snprintf(announce_buf, sizeof(announce_buf),
1640                                 "cd present [%lu x %lu byte records]",
1641                                 cdp->disksize, (u_long)cdp->blksize);
1642
1643                 } else {
1644                         int     error;
1645                         /*
1646                          * Retry any UNIT ATTENTION type errors.  They
1647                          * are expected at boot.
1648                          */
1649                         error = cderror(done_ccb, CAM_RETRY_SELTO,
1650                                         SF_RETRY_UA | SF_NO_PRINT);
1651                         if (error == ERESTART) {
1652                                 /*
1653                                  * A retry was scheuled, so
1654                                  * just return.
1655                                  */
1656                                 return;
1657                         } else if (error != 0) {
1658
1659                                 struct scsi_sense_data *sense;
1660                                 int asc, ascq;
1661                                 int sense_key, error_code;
1662                                 int have_sense;
1663                                 cam_status status;
1664                                 struct ccb_getdev cgd;
1665
1666                                 /* Don't wedge this device's queue */
1667                                 if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1668                                         cam_release_devq(done_ccb->ccb_h.path,
1669                                                  /*relsim_flags*/0,
1670                                                  /*reduction*/0,
1671                                                  /*timeout*/0,
1672                                                  /*getcount_only*/0);
1673
1674                                 status = done_ccb->ccb_h.status;
1675
1676                                 xpt_setup_ccb(&cgd.ccb_h, 
1677                                               done_ccb->ccb_h.path,
1678                                               CAM_PRIORITY_NORMAL);
1679                                 cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1680                                 xpt_action((union ccb *)&cgd);
1681
1682                                 if (((csio->ccb_h.flags & CAM_SENSE_PHYS) != 0)
1683                                  || ((csio->ccb_h.flags & CAM_SENSE_PTR) != 0)
1684                                  || ((status & CAM_AUTOSNS_VALID) == 0))
1685                                         have_sense = FALSE;
1686                                 else
1687                                         have_sense = TRUE;
1688
1689                                 if (have_sense) {
1690                                         sense = &csio->sense_data;
1691                                         scsi_extract_sense(sense, &error_code,
1692                                                            &sense_key, 
1693                                                            &asc, &ascq);
1694                                 }
1695                                 /*
1696                                  * Attach to anything that claims to be a
1697                                  * CDROM or WORM device, as long as it
1698                                  * doesn't return a "Logical unit not
1699                                  * supported" (0x25) error.
1700                                  */
1701                                 if ((have_sense) && (asc != 0x25)
1702                                  && (error_code == SSD_CURRENT_ERROR)) {
1703                                         const char *sense_key_desc;
1704                                         const char *asc_desc;
1705
1706                                         scsi_sense_desc(sense_key, asc, ascq,
1707                                                         &cgd.inq_data,
1708                                                         &sense_key_desc,
1709                                                         &asc_desc);
1710                                         snprintf(announce_buf,
1711                                             sizeof(announce_buf),
1712                                                 "Attempt to query device "
1713                                                 "size failed: %s, %s",
1714                                                 sense_key_desc,
1715                                                 asc_desc);
1716                                 } else if ((have_sense == 0) 
1717                                       && ((status & CAM_STATUS_MASK) ==
1718                                            CAM_SCSI_STATUS_ERROR)
1719                                       && (csio->scsi_status ==
1720                                           SCSI_STATUS_BUSY)) {
1721                                         snprintf(announce_buf,
1722                                             sizeof(announce_buf),
1723                                             "Attempt to query device "
1724                                             "size failed: SCSI Status: %s",
1725                                             scsi_status_string(csio));
1726                                 } else if (SID_TYPE(&cgd.inq_data) == T_CDROM) {
1727                                         /*
1728                                          * We only print out an error for
1729                                          * CDROM type devices.  For WORM
1730                                          * devices, we don't print out an
1731                                          * error since a few WORM devices
1732                                          * don't support CDROM commands.
1733                                          * If we have sense information, go
1734                                          * ahead and print it out.
1735                                          * Otherwise, just say that we 
1736                                          * couldn't attach.
1737                                          */
1738
1739                                         /*
1740                                          * Just print out the error, not
1741                                          * the full probe message, when we
1742                                          * don't attach.
1743                                          */
1744                                         if (have_sense)
1745                                                 scsi_sense_print(
1746                                                         &done_ccb->csio);
1747                                         else {
1748                                                 xpt_print(periph->path,
1749                                                     "got CAM status %#x\n",
1750                                                     done_ccb->ccb_h.status);
1751                                         }
1752                                         xpt_print(periph->path, "fatal error, "
1753                                             "failed to attach to device\n");
1754                                         /*
1755                                          * Invalidate this peripheral.
1756                                          */
1757                                         cam_periph_invalidate(periph);
1758
1759                                         announce_buf[0] = '\0';
1760                                 } else {
1761
1762                                         /*
1763                                          * Invalidate this peripheral.
1764                                          */
1765                                         cam_periph_invalidate(periph);
1766                                         announce_buf[0] = '\0';
1767                                 }
1768                         }
1769                 }
1770                 free(rdcap, M_SCSICD);
1771                 if (announce_buf[0] != '\0') {
1772                         xpt_announce_periph(periph, announce_buf);
1773                         if (softc->flags & CD_FLAG_CHANGER)
1774                                 cdchangerschedule(softc);
1775                         /*
1776                          * Create our sysctl variables, now that we know
1777                          * we have successfully attached.
1778                          */
1779                         taskqueue_enqueue(taskqueue_thread,&softc->sysctl_task);
1780                 }
1781                 softc->state = CD_STATE_NORMAL;         
1782                 /*
1783                  * Since our peripheral may be invalidated by an error
1784                  * above or an external event, we must release our CCB
1785                  * before releasing the probe lock on the peripheral.
1786                  * The peripheral will only go away once the last lock
1787                  * is removed, and we need it around for the CCB release
1788                  * operation.
1789                  */
1790                 xpt_release_ccb(done_ccb);
1791                 cam_periph_unhold(periph);
1792                 return;
1793         }
1794         case CD_CCB_WAITING:
1795         {
1796                 /* Caller will release the CCB */
1797                 CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, 
1798                           ("trying to wakeup ccbwait\n"));
1799
1800                 wakeup(&done_ccb->ccb_h.cbfcnp);
1801                 return;
1802         }
1803         default:
1804                 break;
1805         }
1806         xpt_release_ccb(done_ccb);
1807 }
1808
1809 static union cd_pages *
1810 cdgetpage(struct cd_mode_params *mode_params)
1811 {
1812         union cd_pages *page;
1813
1814         if (mode_params->cdb_size == 10)
1815                 page = (union cd_pages *)find_mode_page_10(
1816                         (struct scsi_mode_header_10 *)mode_params->mode_buf);
1817         else
1818                 page = (union cd_pages *)find_mode_page_6(
1819                         (struct scsi_mode_header_6 *)mode_params->mode_buf);
1820
1821         return (page);
1822 }
1823
1824 static int
1825 cdgetpagesize(int page_num)
1826 {
1827         int i;
1828
1829         for (i = 0; i < (sizeof(cd_page_size_table)/
1830              sizeof(cd_page_size_table[0])); i++) {
1831                 if (cd_page_size_table[i].page == page_num)
1832                         return (cd_page_size_table[i].page_size);
1833         }
1834
1835         return (-1);
1836 }
1837
1838 static int
1839 cdioctl(struct disk *dp, u_long cmd, void *addr, int flag, struct thread *td)
1840 {
1841
1842         struct  cam_periph *periph;
1843         struct  cd_softc *softc;
1844         int     nocopyout, error = 0;
1845
1846         periph = (struct cam_periph *)dp->d_drv1;
1847         if (periph == NULL)
1848                 return(ENXIO);  
1849
1850         cam_periph_lock(periph);
1851         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdioctl\n"));
1852
1853         softc = (struct cd_softc *)periph->softc;
1854
1855         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, 
1856                   ("trying to do ioctl %#lx\n", cmd));
1857
1858         if ((error = cam_periph_hold(periph, PRIBIO | PCATCH)) != 0) {
1859                 cam_periph_unlock(periph);
1860                 cam_periph_release(periph);
1861                 return (error);
1862         }
1863
1864         /*
1865          * If we don't have media loaded, check for it.  If still don't
1866          * have media loaded, we can only do a load or eject.
1867          *
1868          * We only care whether media is loaded if this is a cd-specific ioctl
1869          * (thus the IOCGROUP check below).  Note that this will break if
1870          * anyone adds any ioctls into the switch statement below that don't
1871          * have their ioctl group set to 'c'.
1872          */
1873         if (((softc->flags & CD_FLAG_VALID_MEDIA) == 0)
1874          && ((cmd != CDIOCCLOSE)
1875           && (cmd != CDIOCEJECT))
1876          && (IOCGROUP(cmd) == 'c')) {
1877                 error = cdcheckmedia(periph);
1878                 if (error != 0) {
1879                         cam_periph_unhold(periph);
1880                         cam_periph_unlock(periph);
1881                         return (error);
1882                 }
1883         }
1884         /*
1885          * Drop the lock here so later mallocs can use WAITOK.  The periph
1886          * is essentially locked still with the cam_periph_hold call above.
1887          */
1888         cam_periph_unlock(periph);
1889
1890         nocopyout = 0;
1891         switch (cmd) {
1892
1893         case CDIOCPLAYTRACKS:
1894                 {
1895                         struct ioc_play_track *args
1896                             = (struct ioc_play_track *) addr;
1897                         struct cd_mode_params params;
1898                         union cd_pages *page;
1899
1900                         params.alloc_len = sizeof(union cd_mode_data_6_10);
1901                         params.mode_buf = malloc(params.alloc_len, M_SCSICD,
1902                                                  M_WAITOK | M_ZERO);
1903
1904                         cam_periph_lock(periph);
1905                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
1906                                   ("trying to do CDIOCPLAYTRACKS\n"));
1907
1908                         error = cdgetmode(periph, &params, AUDIO_PAGE);
1909                         if (error) {
1910                                 free(params.mode_buf, M_SCSICD);
1911                                 cam_periph_unlock(periph);
1912                                 break;
1913                         }
1914                         page = cdgetpage(&params);
1915
1916                         page->audio.flags &= ~CD_PA_SOTC;
1917                         page->audio.flags |= CD_PA_IMMED;
1918                         error = cdsetmode(periph, &params);
1919                         free(params.mode_buf, M_SCSICD);
1920                         if (error) {
1921                                 cam_periph_unlock(periph);
1922                                 break;
1923                         }
1924
1925                         /*
1926                          * This was originally implemented with the PLAY
1927                          * AUDIO TRACK INDEX command, but that command was
1928                          * deprecated after SCSI-2.  Most (all?) SCSI CDROM
1929                          * drives support it but ATAPI and ATAPI-derivative
1930                          * drives don't seem to support it.  So we keep a
1931                          * cache of the table of contents and translate
1932                          * track numbers to MSF format.
1933                          */
1934                         if (softc->flags & CD_FLAG_VALID_TOC) {
1935                                 union msf_lba *sentry, *eentry;
1936                                 int st, et;
1937
1938                                 if (args->end_track <
1939                                     softc->toc.header.ending_track + 1)
1940                                         args->end_track++;
1941                                 if (args->end_track >
1942                                     softc->toc.header.ending_track + 1)
1943                                         args->end_track =
1944                                             softc->toc.header.ending_track + 1;
1945                                 st = args->start_track -
1946                                         softc->toc.header.starting_track;
1947                                 et = args->end_track -
1948                                         softc->toc.header.starting_track;
1949                                 if ((st < 0)
1950                                  || (et < 0)
1951                                  || (st > (softc->toc.header.ending_track -
1952                                      softc->toc.header.starting_track))) {
1953                                         error = EINVAL;
1954                                         break;
1955                                 }
1956                                 sentry = &softc->toc.entries[st].addr;
1957                                 eentry = &softc->toc.entries[et].addr;
1958                                 error = cdplaymsf(periph,
1959                                                   sentry->msf.minute,
1960                                                   sentry->msf.second,
1961                                                   sentry->msf.frame,
1962                                                   eentry->msf.minute,
1963                                                   eentry->msf.second,
1964                                                   eentry->msf.frame);
1965                         } else {
1966                                 /*
1967                                  * If we don't have a valid TOC, try the
1968                                  * play track index command.  It is part of
1969                                  * the SCSI-2 spec, but was removed in the
1970                                  * MMC specs.  ATAPI and ATAPI-derived
1971                                  * drives don't support it.
1972                                  */
1973                                 if (softc->quirks & CD_Q_BCD_TRACKS) {
1974                                         args->start_track =
1975                                                 bin2bcd(args->start_track);
1976                                         args->end_track =
1977                                                 bin2bcd(args->end_track);
1978                                 }
1979                                 error = cdplaytracks(periph,
1980                                                      args->start_track,
1981                                                      args->start_index,
1982                                                      args->end_track,
1983                                                      args->end_index);
1984                         }
1985                         cam_periph_unlock(periph);
1986                 }
1987                 break;
1988         case CDIOCPLAYMSF:
1989                 {
1990                         struct ioc_play_msf *args
1991                                 = (struct ioc_play_msf *) addr;
1992                         struct cd_mode_params params;
1993                         union cd_pages *page;
1994
1995                         params.alloc_len = sizeof(union cd_mode_data_6_10);
1996                         params.mode_buf = malloc(params.alloc_len, M_SCSICD,
1997                                                  M_WAITOK | M_ZERO);
1998
1999                         cam_periph_lock(periph);
2000                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2001                                   ("trying to do CDIOCPLAYMSF\n"));
2002
2003                         error = cdgetmode(periph, &params, AUDIO_PAGE);
2004                         if (error) {
2005                                 free(params.mode_buf, M_SCSICD);
2006                                 cam_periph_unlock(periph);
2007                                 break;
2008                         }
2009                         page = cdgetpage(&params);
2010
2011                         page->audio.flags &= ~CD_PA_SOTC;
2012                         page->audio.flags |= CD_PA_IMMED;
2013                         error = cdsetmode(periph, &params);
2014                         free(params.mode_buf, M_SCSICD);
2015                         if (error) {
2016                                 cam_periph_unlock(periph);
2017                                 break;
2018                         }
2019                         error = cdplaymsf(periph,
2020                                           args->start_m,
2021                                           args->start_s,
2022                                           args->start_f,
2023                                           args->end_m,
2024                                           args->end_s,
2025                                           args->end_f);
2026                         cam_periph_unlock(periph);
2027                 }
2028                 break;
2029         case CDIOCPLAYBLOCKS:
2030                 {
2031                         struct ioc_play_blocks *args
2032                                 = (struct ioc_play_blocks *) addr;
2033                         struct cd_mode_params params;
2034                         union cd_pages *page;
2035
2036                         params.alloc_len = sizeof(union cd_mode_data_6_10);
2037                         params.mode_buf = malloc(params.alloc_len, M_SCSICD,
2038                                                  M_WAITOK | M_ZERO);
2039
2040                         cam_periph_lock(periph);
2041                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2042                                   ("trying to do CDIOCPLAYBLOCKS\n"));
2043
2044
2045                         error = cdgetmode(periph, &params, AUDIO_PAGE);
2046                         if (error) {
2047                                 free(params.mode_buf, M_SCSICD);
2048                                 cam_periph_unlock(periph);
2049                                 break;
2050                         }
2051                         page = cdgetpage(&params);
2052
2053                         page->audio.flags &= ~CD_PA_SOTC;
2054                         page->audio.flags |= CD_PA_IMMED;
2055                         error = cdsetmode(periph, &params);
2056                         free(params.mode_buf, M_SCSICD);
2057                         if (error) {
2058                                 cam_periph_unlock(periph);
2059                                 break;
2060                         }
2061                         error = cdplay(periph, args->blk, args->len);
2062                         cam_periph_unlock(periph);
2063                 }
2064                 break;
2065         case CDIOCREADSUBCHANNEL_SYSSPACE:
2066                 nocopyout = 1;
2067                 /* Fallthrough */
2068         case CDIOCREADSUBCHANNEL:
2069                 {
2070                         struct ioc_read_subchannel *args
2071                                 = (struct ioc_read_subchannel *) addr;
2072                         struct cd_sub_channel_info *data;
2073                         u_int32_t len = args->data_len;
2074
2075                         data = malloc(sizeof(struct cd_sub_channel_info), 
2076                                       M_SCSICD, M_WAITOK);
2077
2078                         cam_periph_lock(periph);
2079                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2080                                   ("trying to do CDIOCREADSUBCHANNEL\n"));
2081
2082                         if ((len > sizeof(struct cd_sub_channel_info)) ||
2083                             (len < sizeof(struct cd_sub_channel_header))) {
2084                                 printf(
2085                                         "scsi_cd: cdioctl: "
2086                                         "cdioreadsubchannel: error, len=%d\n",
2087                                         len);
2088                                 error = EINVAL;
2089                                 free(data, M_SCSICD);
2090                                 cam_periph_unlock(periph);
2091                                 break;
2092                         }
2093
2094                         if (softc->quirks & CD_Q_BCD_TRACKS)
2095                                 args->track = bin2bcd(args->track);
2096
2097                         error = cdreadsubchannel(periph, args->address_format,
2098                                 args->data_format, args->track, data, len);
2099
2100                         if (error) {
2101                                 free(data, M_SCSICD);
2102                                 cam_periph_unlock(periph);
2103                                 break;
2104                         }
2105                         if (softc->quirks & CD_Q_BCD_TRACKS)
2106                                 data->what.track_info.track_number =
2107                                     bcd2bin(data->what.track_info.track_number);
2108                         len = min(len, ((data->header.data_len[0] << 8) +
2109                                 data->header.data_len[1] +
2110                                 sizeof(struct cd_sub_channel_header)));
2111                         cam_periph_unlock(periph);
2112                         if (nocopyout == 0) {
2113                                 if (copyout(data, args->data, len) != 0) {
2114                                         error = EFAULT;
2115                                 }
2116                         } else {
2117                                 bcopy(data, args->data, len);
2118                         }
2119                         free(data, M_SCSICD);
2120                 }
2121                 break;
2122
2123         case CDIOREADTOCHEADER:
2124                 {
2125                         struct ioc_toc_header *th;
2126
2127                         th = malloc(sizeof(struct ioc_toc_header), M_SCSICD,
2128                                     M_WAITOK);
2129
2130                         cam_periph_lock(periph);
2131                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2132                                   ("trying to do CDIOREADTOCHEADER\n"));
2133
2134                         error = cdreadtoc(periph, 0, 0, (u_int8_t *)th, 
2135                                           sizeof (*th), /*sense_flags*/0);
2136                         if (error) {
2137                                 free(th, M_SCSICD);
2138                                 cam_periph_unlock(periph);
2139                                 break;
2140                         }
2141                         if (softc->quirks & CD_Q_BCD_TRACKS) {
2142                                 /* we are going to have to convert the BCD
2143                                  * encoding on the cd to what is expected
2144                                  */
2145                                 th->starting_track = 
2146                                         bcd2bin(th->starting_track);
2147                                 th->ending_track = bcd2bin(th->ending_track);
2148                         }
2149                         th->len = ntohs(th->len);
2150                         bcopy(th, addr, sizeof(*th));
2151                         free(th, M_SCSICD);
2152                         cam_periph_unlock(periph);
2153                 }
2154                 break;
2155         case CDIOREADTOCENTRYS:
2156                 {
2157                         struct cd_tocdata *data;
2158                         struct cd_toc_single *lead;
2159                         struct ioc_read_toc_entry *te =
2160                                 (struct ioc_read_toc_entry *) addr;
2161                         struct ioc_toc_header *th;
2162                         u_int32_t len, readlen, idx, num;
2163                         u_int32_t starting_track = te->starting_track;
2164
2165                         data = malloc(sizeof(*data), M_SCSICD, M_WAITOK);
2166                         lead = malloc(sizeof(*lead), M_SCSICD, M_WAITOK);
2167
2168                         cam_periph_lock(periph);
2169                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2170                                   ("trying to do CDIOREADTOCENTRYS\n"));
2171
2172                         if (te->data_len < sizeof(struct cd_toc_entry)
2173                          || (te->data_len % sizeof(struct cd_toc_entry)) != 0
2174                          || (te->address_format != CD_MSF_FORMAT
2175                           && te->address_format != CD_LBA_FORMAT)) {
2176                                 error = EINVAL;
2177                                 printf("scsi_cd: error in readtocentries, "
2178                                        "returning EINVAL\n");
2179                                 free(data, M_SCSICD);
2180                                 free(lead, M_SCSICD);
2181                                 cam_periph_unlock(periph);
2182                                 break;
2183                         }
2184
2185                         th = &data->header;
2186                         error = cdreadtoc(periph, 0, 0, (u_int8_t *)th, 
2187                                           sizeof (*th), /*sense_flags*/0);
2188                         if (error) {
2189                                 free(data, M_SCSICD);
2190                                 free(lead, M_SCSICD);
2191                                 cam_periph_unlock(periph);
2192                                 break;
2193                         }
2194
2195                         if (softc->quirks & CD_Q_BCD_TRACKS) {
2196                                 /* we are going to have to convert the BCD
2197                                  * encoding on the cd to what is expected
2198                                  */
2199                                 th->starting_track =
2200                                     bcd2bin(th->starting_track);
2201                                 th->ending_track = bcd2bin(th->ending_track);
2202                         }
2203
2204                         if (starting_track == 0)
2205                                 starting_track = th->starting_track;
2206                         else if (starting_track == LEADOUT)
2207                                 starting_track = th->ending_track + 1;
2208                         else if (starting_track < th->starting_track ||
2209                                  starting_track > th->ending_track + 1) {
2210                                 printf("scsi_cd: error in readtocentries, "
2211                                        "returning EINVAL\n");
2212                                 free(data, M_SCSICD);
2213                                 free(lead, M_SCSICD);
2214                                 cam_periph_unlock(periph);
2215                                 error = EINVAL;
2216                                 break;
2217                         }
2218
2219                         /* calculate reading length without leadout entry */
2220                         readlen = (th->ending_track - starting_track + 1) *
2221                                   sizeof(struct cd_toc_entry);
2222
2223                         /* and with leadout entry */
2224                         len = readlen + sizeof(struct cd_toc_entry);
2225                         if (te->data_len < len) {
2226                                 len = te->data_len;
2227                                 if (readlen > len)
2228                                         readlen = len;
2229                         }
2230                         if (len > sizeof(data->entries)) {
2231                                 printf("scsi_cd: error in readtocentries, "
2232                                        "returning EINVAL\n");
2233                                 error = EINVAL;
2234                                 free(data, M_SCSICD);
2235                                 free(lead, M_SCSICD);
2236                                 cam_periph_unlock(periph);
2237                                 break;
2238                         }
2239                         num = len / sizeof(struct cd_toc_entry);
2240
2241                         if (readlen > 0) {
2242                                 error = cdreadtoc(periph, te->address_format,
2243                                                   starting_track,
2244                                                   (u_int8_t *)data,
2245                                                   readlen + sizeof (*th),
2246                                                   /*sense_flags*/0);
2247                                 if (error) {
2248                                         free(data, M_SCSICD);
2249                                         free(lead, M_SCSICD);
2250                                         cam_periph_unlock(periph);
2251                                         break;
2252                                 }
2253                         }
2254
2255                         /* make leadout entry if needed */
2256                         idx = starting_track + num - 1;
2257                         if (softc->quirks & CD_Q_BCD_TRACKS)
2258                                 th->ending_track = bcd2bin(th->ending_track);
2259                         if (idx == th->ending_track + 1) {
2260                                 error = cdreadtoc(periph, te->address_format,
2261                                                   LEADOUT, (u_int8_t *)lead,
2262                                                   sizeof(*lead),
2263                                                   /*sense_flags*/0);
2264                                 if (error) {
2265                                         free(data, M_SCSICD);
2266                                         free(lead, M_SCSICD);
2267                                         cam_periph_unlock(periph);
2268                                         break;
2269                                 }
2270                                 data->entries[idx - starting_track] = 
2271                                         lead->entry;
2272                         }
2273                         if (softc->quirks & CD_Q_BCD_TRACKS) {
2274                                 for (idx = 0; idx < num - 1; idx++) {
2275                                         data->entries[idx].track =
2276                                             bcd2bin(data->entries[idx].track);
2277                                 }
2278                         }
2279
2280                         cam_periph_unlock(periph);
2281                         error = copyout(data->entries, te->data, len);
2282                         free(data, M_SCSICD);
2283                         free(lead, M_SCSICD);
2284                 }
2285                 break;
2286         case CDIOREADTOCENTRY:
2287                 {
2288                         struct cd_toc_single *data;
2289                         struct ioc_read_toc_single_entry *te =
2290                                 (struct ioc_read_toc_single_entry *) addr;
2291                         struct ioc_toc_header *th;
2292                         u_int32_t track;
2293
2294                         data = malloc(sizeof(*data), M_SCSICD, M_WAITOK);
2295
2296                         cam_periph_lock(periph);
2297                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2298                                   ("trying to do CDIOREADTOCENTRY\n"));
2299
2300                         if (te->address_format != CD_MSF_FORMAT
2301                             && te->address_format != CD_LBA_FORMAT) {
2302                                 printf("error in readtocentry, "
2303                                        " returning EINVAL\n");
2304                                 free(data, M_SCSICD);
2305                                 error = EINVAL;
2306                                 cam_periph_unlock(periph);
2307                                 break;
2308                         }
2309
2310                         th = &data->header;
2311                         error = cdreadtoc(periph, 0, 0, (u_int8_t *)th,
2312                                           sizeof (*th), /*sense_flags*/0);
2313                         if (error) {
2314                                 free(data, M_SCSICD);
2315                                 cam_periph_unlock(periph);
2316                                 break;
2317                         }
2318
2319                         if (softc->quirks & CD_Q_BCD_TRACKS) {
2320                                 /* we are going to have to convert the BCD
2321                                  * encoding on the cd to what is expected
2322                                  */
2323                                 th->starting_track =
2324                                     bcd2bin(th->starting_track);
2325                                 th->ending_track = bcd2bin(th->ending_track);
2326                         }
2327                         track = te->track;
2328                         if (track == 0)
2329                                 track = th->starting_track;
2330                         else if (track == LEADOUT)
2331                                 /* OK */;
2332                         else if (track < th->starting_track ||
2333                                  track > th->ending_track + 1) {
2334                                 printf("error in readtocentry, "
2335                                        " returning EINVAL\n");
2336                                 free(data, M_SCSICD);
2337                                 error = EINVAL;
2338                                 cam_periph_unlock(periph);
2339                                 break;
2340                         }
2341
2342                         error = cdreadtoc(periph, te->address_format, track,
2343                                           (u_int8_t *)data, sizeof(*data),
2344                                           /*sense_flags*/0);
2345                         if (error) {
2346                                 free(data, M_SCSICD);
2347                                 cam_periph_unlock(periph);
2348                                 break;
2349                         }
2350
2351                         if (softc->quirks & CD_Q_BCD_TRACKS)
2352                                 data->entry.track = bcd2bin(data->entry.track);
2353                         bcopy(&data->entry, &te->entry,
2354                               sizeof(struct cd_toc_entry));
2355                         free(data, M_SCSICD);
2356                         cam_periph_unlock(periph);
2357                 }
2358                 break;
2359         case CDIOCSETPATCH:
2360                 {
2361                         struct ioc_patch *arg = (struct ioc_patch *)addr;
2362                         struct cd_mode_params params;
2363                         union cd_pages *page;
2364
2365                         params.alloc_len = sizeof(union cd_mode_data_6_10);
2366                         params.mode_buf = malloc(params.alloc_len, M_SCSICD, 
2367                                                  M_WAITOK | M_ZERO);
2368
2369                         cam_periph_lock(periph);
2370                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2371                                   ("trying to do CDIOCSETPATCH\n"));
2372
2373                         error = cdgetmode(periph, &params, AUDIO_PAGE);
2374                         if (error) {
2375                                 free(params.mode_buf, M_SCSICD);
2376                                 cam_periph_unlock(periph);
2377                                 break;
2378                         }
2379                         page = cdgetpage(&params);
2380
2381                         page->audio.port[LEFT_PORT].channels = 
2382                                 arg->patch[0];
2383                         page->audio.port[RIGHT_PORT].channels = 
2384                                 arg->patch[1];
2385                         page->audio.port[2].channels = arg->patch[2];
2386                         page->audio.port[3].channels = arg->patch[3];
2387                         error = cdsetmode(periph, &params);
2388                         free(params.mode_buf, M_SCSICD);
2389                         cam_periph_unlock(periph);
2390                 }
2391                 break;
2392         case CDIOCGETVOL:
2393                 {
2394                         struct ioc_vol *arg = (struct ioc_vol *) addr;
2395                         struct cd_mode_params params;
2396                         union cd_pages *page;
2397
2398                         params.alloc_len = sizeof(union cd_mode_data_6_10);
2399                         params.mode_buf = malloc(params.alloc_len, M_SCSICD, 
2400                                                  M_WAITOK | M_ZERO);
2401
2402                         cam_periph_lock(periph);
2403                         CAM_DEBUG(periph->path, CAM_DEBUG_SUBTRACE, 
2404                                   ("trying to do CDIOCGETVOL\n"));