kernel/nata: Deal with ATA_DEV() and atadev->unit.
[dragonfly.git] / sys / dev / disk / nata / atapi-cam.c
1 /*-
2  * Copyright (c) 2001-2003 Thomas Quinot <thomas@cuivre.fr.eu.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer,
10  *    without modification, immediately at the beginning of the file.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  *
28  * $FreeBSD: src/sys/dev/ata/atapi-cam.c,v 1.44 2006/03/31 08:09:05 sos Exp $
29  */
30
31 #include "opt_ata.h"
32 #include "opt_scsi.h"
33
34 #include <sys/param.h>
35 #include <sys/bus.h>
36 #include <sys/libkern.h>
37 #include <sys/lock.h>           /* for {get,rel}_mplock() */
38 #include <sys/malloc.h>
39 #include <sys/module.h>
40 #include <sys/nata.h>
41 #include <sys/queue.h>
42 #include <sys/systm.h>
43
44 #include <sys/thread2.h>
45 #include <sys/mplock2.h>
46
47 #include <bus/cam/cam.h>
48 #include <bus/cam/cam_ccb.h>
49 #include <bus/cam/cam_periph.h>
50 #include <bus/cam/cam_sim.h>
51 #include <bus/cam/cam_xpt_sim.h>
52 #include <bus/cam/cam_debug.h>
53 #include <bus/cam/scsi/scsi_all.h>
54
55 #include "ata-all.h"
56 #include "ata_if.h"
57
58 /* private data associated with an ATA bus */
59 struct atapi_xpt_softc {
60     struct ata_device   atapi_cam_dev;  /* must be first */
61     device_t            dev;
62     device_t            parent;
63     struct ata_channel  *ata_ch;
64     struct cam_path     *path;
65     struct cam_sim      *sim;
66     int                 flags;
67 #define BUS_REGISTERED          0x01
68 #define RESOURCE_SHORTAGE       0x02
69 #define DETACHING               0x04
70
71     TAILQ_HEAD(,atapi_hcb) pending_hcbs;
72     struct ata_device   *atadev[2];
73     struct lock         state_lock;
74 };
75
76 /* hardware command descriptor block */
77 struct atapi_hcb {
78     struct atapi_xpt_softc *softc;
79     int                 unit;
80     int                 bus;
81     int                 target;
82     int                 lun;
83     union ccb           *ccb;
84     int                 flags;
85 #define QUEUED          0x0001
86 #define AUTOSENSE       0x0002
87     char                *dxfer_alloc;
88     TAILQ_ENTRY(atapi_hcb) chain;
89 };
90
91 enum reinit_reason { ATTACH, RESET };
92
93 /* Device methods */
94 static void atapi_cam_identify(device_t *dev, device_t parent);
95 static int atapi_cam_probe(device_t dev);
96 static int atapi_cam_attach(device_t dev);
97 static int atapi_cam_detach(device_t dev);
98 static int atapi_cam_reinit(device_t dev);
99
100 /* CAM XPT methods */
101 static void atapi_action(struct cam_sim *, union ccb *);
102 static void atapi_poll(struct cam_sim *);
103 static void atapi_async(void *, u_int32_t, struct cam_path *, void *);
104 static void atapi_cb(struct ata_request *);
105
106 /* Module methods */
107 static int atapi_cam_event_handler(module_t mod, int what, void *arg);
108
109 /* internal functions */
110 static void reinit_bus(struct atapi_xpt_softc *scp, enum reinit_reason reason);
111 static void setup_async_cb(struct atapi_xpt_softc *, uint32_t);
112 static void cam_rescan_callback(struct cam_periph *, union ccb *);
113 static void cam_rescan(struct cam_sim *);
114 static void free_hcb_and_ccb_done(struct atapi_hcb *, u_int32_t);
115 static struct atapi_hcb *allocate_hcb(struct atapi_xpt_softc *, int, int, union ccb *);
116 static void free_hcb(struct atapi_hcb *hcb);
117 static void free_softc(struct atapi_xpt_softc *scp);
118
119 static MALLOC_DEFINE(M_ATACAM, "ata_cam", "ATA driver CAM-XPT layer");
120
121 static device_method_t atapi_cam_methods[] = {
122         DEVMETHOD(device_identify,      atapi_cam_identify),
123         DEVMETHOD(device_probe,         atapi_cam_probe),
124         DEVMETHOD(device_attach,        atapi_cam_attach),
125         DEVMETHOD(device_detach,        atapi_cam_detach),
126         DEVMETHOD(ata_reinit,           atapi_cam_reinit),
127         DEVMETHOD_END
128 };
129
130 static driver_t atapi_cam_driver = {
131         "atapicam",
132         atapi_cam_methods,
133         sizeof(struct atapi_xpt_softc)
134 };
135
136 static devclass_t       atapi_cam_devclass;
137 DRIVER_MODULE(atapicam, ata,
138         atapi_cam_driver,
139         atapi_cam_devclass,
140         atapi_cam_event_handler,
141         /*arg*/NULL);
142 MODULE_VERSION(atapicam, 1);
143 MODULE_DEPEND(atapicam, ata, 1, 1, 1);
144 MODULE_DEPEND(atapicam, cam, 1, 1, 1);
145
146 static void
147 atapi_cam_identify(device_t *dev, device_t parent)
148 {
149         struct atapi_xpt_softc *scp =
150             kmalloc(sizeof(struct atapi_xpt_softc), M_ATACAM, M_INTWAIT|M_ZERO);
151         device_t child;
152
153         if (scp == NULL) {
154                 kprintf ("atapi_cam_identify: out of memory");
155                 return;
156         }
157
158         /* Assume one atapicam instance per parent channel instance. */
159         child = device_add_child(parent, "atapicam", -1);
160         if (child == NULL) {
161                 kprintf("atapi_cam_identify: out of memory, can't add child");
162                 kfree(scp, M_ATACAM);
163                 return;
164         }
165         scp->atapi_cam_dev.unit = -1;
166         scp->atapi_cam_dev.dev = child;
167         device_quiet(child);
168         device_set_softc(child, scp);
169 }
170
171 static int
172 atapi_cam_probe(device_t dev)
173 {
174         struct ata_device *atadev = device_get_softc (dev);
175
176         KASSERT(atadev != NULL, ("expect valid struct ata_device"));
177         if (atadev->unit < 0) {
178                 device_set_desc(dev, "ATAPI CAM Attachment");
179                 return (0);
180         } else {
181                 return ENXIO;
182         }
183 }
184
185 static int
186 atapi_cam_attach(device_t dev)
187 {
188     struct atapi_xpt_softc *scp = NULL;
189     struct cam_devq *devq = NULL;
190     struct cam_sim *sim = NULL;
191     struct cam_path *path = NULL;
192     int unit, error;
193
194     scp = (struct atapi_xpt_softc *)device_get_softc(dev);
195     if (scp == NULL) {
196         device_printf(dev, "Cannot get softc\n");
197         return ENOMEM;
198     }
199
200     lockinit(&scp->state_lock, "atapicamattach", 0, 0);
201
202     scp->dev = dev;
203     scp->parent = device_get_parent(dev);
204     scp->ata_ch = device_get_softc(scp->parent);
205     TAILQ_INIT(&scp->pending_hcbs);
206     unit = device_get_unit(dev);
207
208     if ((devq = cam_simq_alloc(16)) == NULL) {
209         error = ENOMEM;
210         goto out;
211     }
212
213     if ((sim = cam_sim_alloc(atapi_action, atapi_poll, "ata",
214                  (void *)scp, unit, &sim_mplock, 1, 1, devq)) == NULL) {
215         error = ENOMEM;
216         goto out;
217     }
218     scp->sim = sim;
219
220     if (xpt_bus_register(sim, 0) != CAM_SUCCESS) {
221         error = EINVAL;
222         goto out;
223     }
224     scp->flags |= BUS_REGISTERED;
225
226     if (xpt_create_path(&path, /*periph*/ NULL,
227                 cam_sim_path(sim), CAM_TARGET_WILDCARD,
228                 CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
229         error = ENOMEM;
230         goto out;
231     }
232     scp->path = path;
233
234     CAM_DEBUG(path, CAM_DEBUG_TRACE, ("Registered SIM for ata%d\n", unit));
235
236     setup_async_cb(scp, AC_LOST_DEVICE);
237     reinit_bus(scp, ATTACH);
238     error = 0;
239
240 out:
241     if (error != 0)
242         free_softc(scp);
243
244     return(error);
245 }
246
247 static int
248 atapi_cam_detach(device_t dev)
249 {
250     struct atapi_xpt_softc *scp = device_get_softc(dev);
251
252     get_mplock();
253     xpt_freeze_simq(scp->sim, 1 /*count*/);
254     rel_mplock();
255     lockmgr(&scp->state_lock, LK_EXCLUSIVE);
256     scp->flags |= DETACHING;
257     lockmgr(&scp->state_lock, LK_RELEASE);
258     free_softc(scp);
259     return (0);
260 }
261
262 static int
263 atapi_cam_reinit(device_t dev) {
264     struct atapi_xpt_softc *scp = device_get_softc(dev);
265
266     /*
267      * scp might be null if the bus is being reinitialised during
268      * the boot-up sequence, before the ATAPI bus is registered.
269      */
270
271     if (scp != NULL) {
272         reinit_bus(scp, RESET);
273     }
274     return 0;
275 }
276
277 static void
278 reinit_bus(struct atapi_xpt_softc *scp, enum reinit_reason reason) {
279     struct ata_device *old_atadev[2], *atadev;
280     device_t *children;
281     int nchildren, i, dev_changed;
282
283     if (device_get_children(scp->parent, &children, &nchildren) != 0) {
284         return;
285     }
286
287     lockmgr(&scp->state_lock, LK_EXCLUSIVE);
288     old_atadev[0] = scp->atadev[0];
289     old_atadev[1] = scp->atadev[1];
290     scp->atadev[0] = NULL;
291     scp->atadev[1] = NULL;
292
293     for (i = 0; i < nchildren; i++) {
294         /* XXX Does the child need to actually be attached yet? */
295         if (children[i] != NULL) {
296             atadev = device_get_softc(children[i]);
297             if ((atadev->unit == ATA_MASTER) &&
298                 (scp->ata_ch->devices & ATA_ATAPI_MASTER) != 0)
299                 scp->atadev[0] = atadev;
300             if ((atadev->unit == ATA_SLAVE) &&
301                 (scp->ata_ch->devices & ATA_ATAPI_SLAVE) != 0)
302                 scp->atadev[1] = atadev;
303         }
304     }
305     dev_changed = (old_atadev[0] != scp->atadev[0])
306             || (old_atadev[1] != scp->atadev[1]);
307     lockmgr(&scp->state_lock, LK_RELEASE);
308     kfree(children, M_TEMP);
309
310     switch (reason) {
311         case RESET:
312             xpt_async(AC_BUS_RESET, scp->path, NULL);
313
314             if (!dev_changed)
315                 break;
316
317             /*FALLTHROUGH*/
318         case ATTACH:
319             cam_rescan(scp->sim);
320             break;
321     }
322 }
323
324 static void
325 setup_async_cb(struct atapi_xpt_softc *scp, uint32_t events)
326 {
327     struct ccb_setasync csa;
328
329     get_mplock();
330     xpt_setup_ccb(&csa.ccb_h, scp->path, /*priority*/ 5);
331     csa.ccb_h.func_code = XPT_SASYNC_CB;
332     csa.event_enable = events;
333     csa.callback = &atapi_async;
334     csa.callback_arg = scp->sim;
335     xpt_action((union ccb *) &csa);
336     rel_mplock();
337 }
338
339 static void
340 atapi_action(struct cam_sim *sim, union ccb *ccb)
341 {
342     struct atapi_xpt_softc *softc = (struct atapi_xpt_softc*)cam_sim_softc(sim);
343     struct ccb_hdr *ccb_h = &ccb->ccb_h;
344     struct atapi_hcb *hcb = NULL;
345     struct ata_request *request = NULL;
346     int unit = cam_sim_unit(sim);
347     int bus = cam_sim_bus(sim);
348     int len;
349     char *buf;
350
351     switch (ccb_h->func_code) {
352     case XPT_PATH_INQ: {
353         struct ccb_pathinq *cpi = &ccb->cpi;
354         int tid = ccb_h->target_id;
355
356         cpi->version_num = 1;
357         cpi->hba_inquiry = 0;
358         cpi->target_sprt = 0;
359         cpi->hba_misc = PIM_NO_6_BYTE;
360         cpi->hba_eng_cnt = 0;
361         bzero(cpi->vuhba_flags, sizeof(cpi->vuhba_flags));
362         cpi->max_target = 1;
363         cpi->max_lun = 0;
364         cpi->async_flags = 0;
365         cpi->hpath_id = 0;
366         cpi->initiator_id = 7;
367         strncpy(cpi->sim_vid, "FreeBSD", sizeof(cpi->sim_vid));
368         strncpy(cpi->hba_vid, "ATAPI", sizeof(cpi->hba_vid));
369         strncpy(cpi->dev_name, cam_sim_name(sim), sizeof cpi->dev_name);
370         cpi->unit_number = cam_sim_unit(sim);
371         cpi->bus_id = cam_sim_bus(sim);
372         cpi->base_transfer_speed = 3300;
373         cpi->transport = XPORT_ATA;
374         cpi->transport_version = 2;
375         cpi->protocol = PROTO_SCSI;
376         cpi->protocol_version = SCSI_REV_2;
377
378         if (softc->ata_ch && tid != CAM_TARGET_WILDCARD) {
379             lockmgr(&softc->state_lock, LK_EXCLUSIVE);
380             if (softc->atadev[tid] == NULL) {
381                 ccb->ccb_h.status = CAM_DEV_NOT_THERE;
382                 xpt_done(ccb);
383                 lockmgr(&softc->state_lock, LK_RELEASE);
384                 return;
385             }
386             switch (softc->atadev[ccb_h->target_id]->mode) {
387             case ATA_PIO1:
388                 cpi->base_transfer_speed = 5200;
389                 break;
390             case ATA_PIO2:
391                 cpi->base_transfer_speed = 7000;
392                 break;
393             case ATA_PIO3:
394                 cpi->base_transfer_speed = 11000;
395                 break;
396             case ATA_PIO4:
397             case ATA_DMA:
398             case ATA_WDMA2:
399                 cpi->base_transfer_speed = 16000;
400                 break;
401             case ATA_UDMA2:
402                 cpi->base_transfer_speed = 33000;
403                 break;
404             case ATA_UDMA4:
405                 cpi->base_transfer_speed = 66000;
406                 break;
407             case ATA_UDMA5:
408                 cpi->base_transfer_speed = 100000;
409                 break;
410             case ATA_UDMA6:
411                 cpi->base_transfer_speed = 133000;
412                 break;
413             default:
414                 break;
415             }
416             lockmgr(&softc->state_lock, LK_RELEASE);
417         }
418         ccb->ccb_h.status = CAM_REQ_CMP;
419         xpt_done(ccb);
420         return;
421     }
422
423     case XPT_RESET_DEV: {
424         int tid = ccb_h->target_id;
425
426         CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_SUBTRACE, ("dev reset\n"));
427         ata_controlcmd(softc->atadev[tid]->dev, ATA_DEVICE_RESET, 0, 0, 0);
428         ccb->ccb_h.status = CAM_REQ_CMP;
429         xpt_done(ccb);
430         return;
431     }
432
433     case XPT_RESET_BUS:
434         CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_SUBTRACE, ("bus reset\n"));
435         ata_reinit(softc->parent);
436         ccb->ccb_h.status = CAM_REQ_CMP;
437         xpt_done(ccb);
438         return;
439
440     case XPT_SET_TRAN_SETTINGS:
441         /* ignore these, we're not doing SCSI here */
442         CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_SUBTRACE,
443                   ("SET_TRAN_SETTINGS not supported\n"));
444         ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
445         xpt_done(ccb);
446         return;
447
448     case XPT_GET_TRAN_SETTINGS: {
449         struct ccb_trans_settings *cts = &ccb->cts;
450         cts->protocol = PROTO_SCSI;
451         cts->protocol_version = SCSI_REV_2;
452         cts->transport = XPORT_ATA;
453         cts->transport_version = XPORT_VERSION_UNSPECIFIED;
454         cts->proto_specific.valid = 0;
455         cts->xport_specific.valid = 0;
456         /* nothing more to do */
457         ccb->ccb_h.status = CAM_REQ_CMP;
458         CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_SUBTRACE, ("GET_TRAN_SETTINGS\n"));
459         xpt_done(ccb);
460         return;
461     }
462
463     case XPT_CALC_GEOMETRY: {
464         CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_SUBTRACE, ("CALC_GEOMETRY\n"));
465         cam_calc_geometry(&ccb->ccg, /*extended*/1);
466         xpt_done(ccb);
467         return;
468     }
469
470     case XPT_SCSI_IO: {
471         struct ccb_scsiio *csio = &ccb->csio;
472         int tid = ccb_h->target_id, lid = ccb_h->target_lun;
473         int request_flags = ATA_R_QUIET | ATA_R_ATAPI;
474
475         CAM_DEBUG(ccb_h->path, CAM_DEBUG_SUBTRACE, ("XPT_SCSI_IO\n"));
476
477         lockmgr(&softc->state_lock, LK_EXCLUSIVE);
478         if (softc->flags & DETACHING) {
479             ccb->ccb_h.status = CAM_REQ_ABORTED;
480             xpt_done(ccb);
481             lockmgr(&softc->state_lock, LK_RELEASE);
482             return;
483         }
484
485         if (softc->atadev[tid] == NULL) {
486             ccb->ccb_h.status = CAM_DEV_NOT_THERE;
487             xpt_done(ccb);
488             lockmgr(&softc->state_lock, LK_RELEASE);
489             return;
490         }
491
492         /* check that this request was not aborted already */
493         if ((ccb_h->status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
494             kprintf("XPT_SCSI_IO received but already in progress?\n");
495             xpt_done(ccb);
496             lockmgr(&softc->state_lock, LK_RELEASE);
497             return;
498         }
499         if (lid > 0) {
500             CAM_DEBUG(ccb_h->path, CAM_DEBUG_SUBTRACE,
501                       ("SCSI IO received for invalid lun %d\n", lid));
502             goto action_invalid;
503         }
504         if (csio->cdb_len > sizeof request->u.atapi.ccb) {
505             CAM_DEBUG(ccb_h->path, CAM_DEBUG_SUBTRACE,
506                 ("CAM CCB too long for ATAPI"));
507             goto action_invalid;
508         }
509         if ((ccb_h->flags & CAM_SCATTER_VALID)) {
510             /* scatter-gather not supported */
511             xpt_print_path(ccb_h->path);
512             kprintf("ATAPI/CAM does not support scatter-gather yet!\n");
513             goto action_invalid;
514         }
515
516         switch (ccb_h->flags & CAM_DIR_MASK) {
517         case CAM_DIR_IN:
518              request_flags |= ATA_R_READ;
519              break;
520         case CAM_DIR_OUT:
521              request_flags |= ATA_R_WRITE;
522              break;
523         case CAM_DIR_NONE:
524              /* No flags need to be set */
525              break;
526         default:
527              device_printf(softc->dev, "unknown IO operation\n");
528              goto action_invalid;
529         }
530
531         if ((hcb = allocate_hcb(softc, unit, bus, ccb)) == NULL) {
532             kprintf("cannot allocate ATAPI/CAM hcb\n");
533             goto action_oom;
534         }
535         if ((request = ata_alloc_request()) == NULL) {
536             kprintf("cannot allocate ATAPI/CAM request\n");
537             goto action_oom;
538         }
539
540         bcopy((ccb_h->flags & CAM_CDB_POINTER) ?
541               csio->cdb_io.cdb_ptr : csio->cdb_io.cdb_bytes,
542               request->u.atapi.ccb, csio->cdb_len);
543 #ifdef CAMDEBUG
544         if (CAM_DEBUGGED(ccb_h->path, CAM_DEBUG_CDB)) {
545                 char cdb_str[(SCSI_MAX_CDBLEN * 3) + 1];
546
547                 kprintf("atapi_action: hcb@%p: %s\n", hcb,
548                        scsi_cdb_string(request->u.atapi.ccb, cdb_str, sizeof(cdb_str)));
549         }
550         if (CAM_DEBUGGED(ccb_h->path, CAM_DEBUG_SUBTRACE)) {
551                 request_flags |= ATA_R_DEBUG;
552         }
553 #endif
554
555         len = csio->dxfer_len;
556         buf = csio->data_ptr;
557
558         /* some SCSI commands require special processing */
559         switch (request->u.atapi.ccb[0]) {
560         case INQUIRY: {
561             /*
562              * many ATAPI devices seem to report more than
563              * SHORT_INQUIRY_LENGTH bytes of available INQUIRY
564              * information, but respond with some incorrect condition
565              * when actually asked for it, so we are going to pretend
566              * that only SHORT_INQUIRY_LENGTH are expected, anyway.
567              */
568             struct scsi_inquiry *inq = (struct scsi_inquiry *) &request->u.atapi.ccb[0];
569
570             if (inq->byte2 == 0 && inq->page_code == 0 &&
571                 inq->length > SHORT_INQUIRY_LENGTH) {
572                 bzero(buf, len);
573                 len = inq->length = SHORT_INQUIRY_LENGTH;
574             }
575             break;
576         }
577         case READ_6:
578             /* FALLTHROUGH */
579
580         case WRITE_6:
581             CAM_DEBUG(ccb_h->path, CAM_DEBUG_SUBTRACE,
582                       ("Translating %s into _10 equivalent\n",
583                       (request->u.atapi.ccb[0] == READ_6) ? "READ_6" : "WRITE_6"));
584             request->u.atapi.ccb[0] |= 0x20;
585             request->u.atapi.ccb[9] = request->u.atapi.ccb[5];
586             request->u.atapi.ccb[8] = request->u.atapi.ccb[4];
587             request->u.atapi.ccb[7] = 0;
588             request->u.atapi.ccb[6] = 0;
589             request->u.atapi.ccb[5] = request->u.atapi.ccb[3];
590             request->u.atapi.ccb[4] = request->u.atapi.ccb[2];
591             request->u.atapi.ccb[3] = request->u.atapi.ccb[1] & 0x1f;
592             request->u.atapi.ccb[2] = 0;
593             request->u.atapi.ccb[1] = 0;
594             break;
595         }
596
597         if ((ccb_h->flags & CAM_DIR_MASK) == CAM_DIR_IN && (len & 1)) {
598             /* ATA always transfers an even number of bytes */
599             if ((buf = hcb->dxfer_alloc
600                  = kmalloc(++len, M_ATACAM, M_INTWAIT | M_ZERO)) == NULL) {
601                 kprintf("cannot allocate ATAPI/CAM buffer\n");
602                 goto action_oom;
603             }
604         }
605
606         /*
607          * Don't allow DMA for requests with length not multiple of 16 bytes.
608          * Some ATAPI devices don't like it.
609          */
610         if ((softc->atadev[tid]->mode >= ATA_DMA) && len > 0 && !(len & 15))
611                 request_flags |= ATA_R_DMA;
612
613         request->dev = softc->atadev[tid]->dev;
614         request->driver = hcb;
615         request->data = buf;
616         request->bytecount = len;
617         request->transfersize = min(request->bytecount,
618                                 min(softc->ata_ch->dma->max_iosize, 65534));
619         request->timeout = ccb_h->timeout / 1000; /* XXX lost granularity */
620         request->callback = &atapi_cb;
621         request->flags = request_flags;
622
623         /*
624          * no retries are to be performed at the ATA level; any retries
625          * will be done by CAM .
626          */
627         request->retries = 0;
628
629         TAILQ_INSERT_TAIL(&softc->pending_hcbs, hcb, chain);
630         hcb->flags |= QUEUED;
631         ccb_h->status |= CAM_SIM_QUEUED;
632         lockmgr(&softc->state_lock, LK_RELEASE);
633
634         ata_queue_request(request);
635         return;
636     }
637
638     default:
639         CAM_DEBUG(ccb_h->path, CAM_DEBUG_SUBTRACE,
640                   ("unsupported function code 0x%02x\n", ccb_h->func_code));
641         goto action_invalid;
642     }
643
644     /* NOTREACHED */
645
646 action_oom:
647     if (request != NULL)
648         ata_free_request(request);
649     if (hcb != NULL)
650         free_hcb(hcb);
651     lockmgr(&softc->state_lock, LK_RELEASE);
652     get_mplock();
653     xpt_print_path(ccb_h->path);
654     kprintf("out of memory, freezing queue.\n");
655     softc->flags |= RESOURCE_SHORTAGE;
656     xpt_freeze_simq(sim, /*count*/ 1);
657     rel_mplock();
658     ccb_h->status = CAM_REQUEUE_REQ;
659     xpt_done(ccb);
660     return;
661
662 action_invalid:
663     lockmgr(&softc->state_lock, LK_RELEASE);
664     ccb_h->status = CAM_REQ_INVALID;
665     xpt_done(ccb);
666     return;
667 }
668
669 static void
670 atapi_poll(struct cam_sim *sim)
671 {
672     /* do nothing - we do not actually service any interrupts */
673     kprintf("atapi_poll called!\n");
674 }
675
676 static void
677 atapi_cb(struct ata_request *request)
678 {
679     struct atapi_xpt_softc *scp;
680     struct atapi_hcb *hcb;
681     struct ccb_scsiio *csio;
682     u_int32_t rc;
683
684     hcb = (struct atapi_hcb *)request->driver;
685     scp = hcb->softc;
686     csio = &hcb->ccb->csio;
687
688 #ifdef CAMDEBUG
689 # define err (request->u.atapi.sense.key)
690     if (CAM_DEBUGGED(csio->ccb_h.path, CAM_DEBUG_CDB)) {
691         kprintf("atapi_cb: hcb@%p sense = %02x: sk = %01x%s%s%s\n",
692                 hcb, err, err & 0x0f,
693                 (err & 0x80) ? ", Filemark" : "",
694                 (err & 0x40) ? ", EOM" : "",
695                 (err & 0x20) ? ", ILI" : "");
696         device_printf(request->dev,
697             "cmd %s status %02x result %02x error %02x\n",
698             ata_cmd2str(request),
699             request->status, request->result, request->error);
700     }
701 #endif
702
703     if ((hcb->flags & AUTOSENSE) != 0) {
704         rc = CAM_SCSI_STATUS_ERROR;
705         if (request->result == 0) {
706             csio->ccb_h.status |= CAM_AUTOSNS_VALID;
707         }
708     } else if (request->result != 0) {
709         if ((request->flags & ATA_R_TIMEOUT) != 0) {
710             rc = CAM_CMD_TIMEOUT;
711         } else {
712             rc = CAM_SCSI_STATUS_ERROR;
713             csio->scsi_status = SCSI_STATUS_CHECK_COND;
714
715             if ((csio->ccb_h.flags & CAM_DIS_AUTOSENSE) == 0) {
716 #if 0
717                 static const int8_t ccb[16] = { ATAPI_REQUEST_SENSE, 0, 0, 0,
718                     sizeof(struct atapi_sense), 0, 0, 0, 0, 0, 0,
719                     0, 0, 0, 0, 0 };
720
721                 bcopy (ccb, request->u.atapi.ccb, sizeof ccb);
722                 request->data = (caddr_t)&csio->sense_data;
723                 request->bytecount = sizeof(struct atapi_sense);
724                 request->transfersize = min(request->bytecount, 65534);
725                 request->timeout = csio->ccb_h.timeout / 1000;
726                 request->retries = 2;
727                 request->flags = ATA_R_QUIET|ATA_R_ATAPI|ATA_R_IMMEDIATE;
728                 hcb->flags |= AUTOSENSE;
729
730                 ata_queue_request(request);
731                 return;
732 #else
733                 /*
734                  * Use auto-sense data from the ATA layer, if it has
735                  * issued a REQUEST SENSE automatically and that operation
736                  * returned without error.
737                  */
738                 if (request->u.atapi.sense.key != 0 && request->error == 0) {
739                     bcopy (&request->u.atapi.sense, &csio->sense_data, sizeof(struct atapi_sense));
740                     csio->ccb_h.status |= CAM_AUTOSNS_VALID;
741                 }
742             }
743 #endif
744         }
745     } else {
746         rc = CAM_REQ_CMP;
747         csio->scsi_status = SCSI_STATUS_OK;
748         if (((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) &&
749             hcb->dxfer_alloc != NULL)
750         {
751             bcopy(hcb->dxfer_alloc, csio->data_ptr, csio->dxfer_len);
752         }
753     }
754
755     lockmgr(&scp->state_lock, LK_EXCLUSIVE);
756     free_hcb_and_ccb_done(hcb, rc);
757     lockmgr(&scp->state_lock, LK_RELEASE);
758
759     ata_free_request(request);
760 }
761
762 static void
763 free_hcb_and_ccb_done(struct atapi_hcb *hcb, u_int32_t status)
764 {
765     struct atapi_xpt_softc *softc;
766     union ccb *ccb;
767
768     if (hcb == NULL)
769         return;
770
771     softc = hcb->softc;
772     ccb = hcb->ccb;
773
774     /* we're about to free a hcb, so the shortage has ended */
775     if (softc->flags & RESOURCE_SHORTAGE) {
776         softc->flags &= ~RESOURCE_SHORTAGE;
777         status |= CAM_RELEASE_SIMQ;
778     }
779     free_hcb(hcb);
780     ccb->ccb_h.status =
781         status | (ccb->ccb_h.status & ~(CAM_STATUS_MASK | CAM_SIM_QUEUED));
782     xpt_done(ccb);
783 }
784
785 static void
786 atapi_async(void *callback_arg, u_int32_t code,
787              struct cam_path* path, void *arg)
788 {
789     int targ;
790
791     crit_enter();
792
793     switch (code) {
794     case AC_LOST_DEVICE:
795         targ = xpt_path_target_id(path);
796         xpt_print_path(path);
797         if (targ == -1)
798                 kprintf("Lost host adapter\n");
799         else
800                 kprintf("Lost target %d???\n", targ);
801         break;
802
803     default:
804         break;
805     }
806
807     crit_exit();
808 }
809
810 static void
811 cam_rescan_callback(struct cam_periph *periph, union ccb *ccb)
812 {
813         if (ccb->ccb_h.status != CAM_REQ_CMP) {
814             CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE,
815                       ("Rescan failed, 0x%04x\n", ccb->ccb_h.status));
816         } else {
817             CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE,
818                       ("Rescan succeeded\n"));
819         }
820         xpt_free_path(ccb->ccb_h.path);
821         kfree(ccb, M_ATACAM);
822 }
823
824 static void
825 cam_rescan(struct cam_sim *sim)
826 {
827     struct cam_path *path;
828     union ccb *ccb = kmalloc(sizeof(union ccb), M_ATACAM, M_WAITOK | M_ZERO);
829
830     get_mplock();
831     if (xpt_create_path(&path, xpt_periph, cam_sim_path(sim),
832                         CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
833         rel_mplock();
834         kfree(ccb, M_ATACAM);
835         return;
836     }
837
838     CAM_DEBUG(path, CAM_DEBUG_TRACE, ("Rescanning ATAPI bus.\n"));
839     xpt_setup_ccb(&ccb->ccb_h, path, 5/*priority (low)*/);
840     ccb->ccb_h.func_code = XPT_SCAN_BUS;
841     ccb->ccb_h.cbfcnp = cam_rescan_callback;
842     ccb->crcn.flags = CAM_FLAG_NONE;
843     xpt_action(ccb);
844     /* scan is in progress now */
845     rel_mplock();
846 }
847
848 static struct atapi_hcb *
849 allocate_hcb(struct atapi_xpt_softc *softc, int unit, int bus, union ccb *ccb)
850 {
851     struct atapi_hcb *hcb = (struct atapi_hcb *)
852         kmalloc(sizeof(struct atapi_hcb), M_ATACAM, M_INTWAIT | M_ZERO);
853
854     hcb->softc = softc;
855     hcb->unit = unit;
856     hcb->bus = bus;
857     hcb->ccb = ccb;
858     return hcb;
859 }
860
861 static void
862 free_hcb(struct atapi_hcb *hcb)
863 {
864     if ((hcb->flags & QUEUED) != 0)
865         TAILQ_REMOVE(&hcb->softc->pending_hcbs, hcb, chain);
866     if (hcb->dxfer_alloc != NULL)
867         kfree(hcb->dxfer_alloc, M_ATACAM);
868     kfree(hcb, M_ATACAM);
869 }
870
871 static void
872 free_softc(struct atapi_xpt_softc *scp)
873 {
874     struct atapi_hcb *hcb;
875
876     if (scp != NULL) {
877         lockmgr(&scp->state_lock, LK_EXCLUSIVE);
878         TAILQ_FOREACH(hcb, &scp->pending_hcbs, chain) {
879             free_hcb_and_ccb_done(hcb, CAM_UNREC_HBA_ERROR);
880         }
881         lockmgr(&scp->state_lock, LK_RELEASE);
882         get_mplock();
883         if (scp->path != NULL) {
884             setup_async_cb(scp, 0);
885             xpt_free_path(scp->path);
886         }
887         if ((scp->flags & BUS_REGISTERED) != 0) {
888             if (xpt_bus_deregister(cam_sim_path(scp->sim)) == CAM_REQ_CMP)
889                 scp->flags &= ~BUS_REGISTERED;
890         }
891         if (scp->sim != NULL) {
892             if ((scp->flags & BUS_REGISTERED) == 0)
893                 cam_sim_free(scp->sim);
894             else
895                 kprintf("Can't free %s SIM (still registered)\n",
896                        cam_sim_name(scp->sim));
897         }
898         rel_mplock();
899         lockuninit(&scp->state_lock);
900     }
901 }
902
903 static int
904 atapi_cam_event_handler(module_t mod, int what, void *arg) {
905     device_t *devlist;
906     int devcount;
907
908     switch (what) {
909         case MOD_UNLOAD:
910             if (devclass_get_devices(atapi_cam_devclass, &devlist, &devcount)
911                   != 0)
912                 return ENXIO;
913             if (devlist != NULL) {
914                 while (devlist != NULL && devcount > 0) {
915                     device_t child = devlist[--devcount];
916                     struct atapi_xpt_softc *scp = device_get_softc(child);
917
918                     device_delete_child(device_get_parent(child),child);
919                     if (scp != NULL)
920                         kfree(scp, M_ATACAM);
921                 }
922                 kfree(devlist, M_TEMP);
923             }
924             break;
925
926         default:
927             break;
928     }
929     return 0;
930 }