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