xref: /dragonfly/sys/dev/disk/nata/ata-all.c (revision d4ef6694)
1 /*-
2  * Copyright (c) 1998 - 2006 Søren Schmidt <sos@FreeBSD.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  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  *
26  * $FreeBSD: src/sys/dev/ata/ata-all.c,v 1.279 2007/02/23 16:25:08 jhb Exp $
27  */
28 
29 #include "opt_ata.h"
30 
31 #include <sys/param.h>
32 #include <sys/bus.h>
33 #include <sys/callout.h>
34 #include <sys/conf.h>
35 #include <sys/ctype.h>
36 #include <sys/device.h>
37 #include <sys/endian.h>
38 #include <sys/kernel.h>
39 #include <sys/libkern.h>
40 #include <sys/lock.h>		/* for {get,rel}_mplock() */
41 #include <sys/malloc.h>
42 #include <sys/module.h>
43 #include <sys/nata.h>
44 #include <sys/objcache.h>
45 #include <sys/queue.h>
46 #include <sys/sysctl.h>
47 #include <sys/systm.h>
48 
49 #include <sys/spinlock2.h>
50 #include <sys/mplock2.h>
51 
52 #include "ata-all.h"
53 #include "ata_if.h"
54 
55 /* device structure */
56 static  d_ioctl_t       ata_ioctl;
57 static struct dev_ops ata_ops = {
58 	{ "ata", 159, 0 },
59 	.d_open =	nullopen,
60 	.d_close =	nullclose,
61 	.d_ioctl =	ata_ioctl,
62 };
63 
64 /* prototypes */
65 #if 0
66 static void ata_boot_attach(void);
67 #endif
68 static device_t ata_add_child(device_t, struct ata_device *, int);
69 static int ata_getparam(struct ata_device *, int);
70 static void bswap(int8_t *, int);
71 static void btrim(int8_t *, int);
72 static void bpack(int8_t *, int8_t *, int);
73 
74 /* global vars */
75 MALLOC_DEFINE(M_ATA, "ata_generic", "ATA driver generic layer");
76 int (*ata_raid_ioctl_func)(u_long cmd, caddr_t data) = NULL;
77 devclass_t ata_devclass;
78 struct objcache *ata_request_cache;
79 struct objcache *ata_composite_cache;
80 struct objcache_malloc_args ata_request_malloc_args = {
81 	sizeof(struct ata_request), M_ATA };
82 struct objcache_malloc_args ata_composite_malloc_args = {
83 	sizeof(struct ata_composite), M_ATA };
84 int ata_wc = 1;
85 
86 /* local vars */
87 static int ata_dma = 1;
88 static int atapi_dma = 1;
89 
90 /* sysctl vars */
91 SYSCTL_NODE(_hw, OID_AUTO, ata, CTLFLAG_RD, 0, "ATA driver parameters");
92 TUNABLE_INT("hw.ata.ata_dma", &ata_dma);
93 SYSCTL_INT(_hw_ata, OID_AUTO, ata_dma, CTLFLAG_RW, &ata_dma, 0,
94 	   "ATA disk DMA mode control");
95 TUNABLE_INT("hw.ata.atapi_dma", &atapi_dma);
96 SYSCTL_INT(_hw_ata, OID_AUTO, atapi_dma, CTLFLAG_RW, &atapi_dma, 0,
97 	   "ATAPI device DMA mode control");
98 TUNABLE_INT("hw.ata.wc", &ata_wc);
99 SYSCTL_INT(_hw_ata, OID_AUTO, ata_wc, CTLFLAG_RW, &ata_wc, 0,
100 	   "ATA disk write caching");
101 
102 /*
103  * newbus device interface related functions
104  */
105 int
106 ata_probe(device_t dev)
107 {
108     return 0;
109 }
110 
111 int
112 ata_attach(device_t dev)
113 {
114     struct ata_channel *ch = device_get_softc(dev);
115     int error, rid;
116 
117     /* check that we have a virgin channel to attach */
118     if (ch->r_irq)
119 	return EEXIST;
120 
121     /* initialize the softc basics */
122     ch->dev = dev;
123     ch->state = ATA_IDLE;
124     spin_init(&ch->state_mtx, "ataattach_state");
125     spin_init(&ch->queue_mtx, "ataattach_queue");
126     ata_queue_init(ch);
127 
128     /* reset the controller HW, the channel and device(s) */
129     while (ATA_LOCKING(dev, ATA_LF_LOCK) != ch->unit)
130 	tsleep(&error, 0, "ataatch", 1);
131     ATA_RESET(dev);
132     ATA_LOCKING(dev, ATA_LF_UNLOCK);
133 
134     /* setup interrupt delivery */
135     rid = ATA_IRQ_RID;
136     ch->r_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
137 				       RF_SHAREABLE | RF_ACTIVE);
138     if (!ch->r_irq) {
139 	device_printf(dev, "unable to allocate interrupt\n");
140 	return ENXIO;
141     }
142     if ((error = bus_setup_intr(dev, ch->r_irq, ATA_INTR_FLAGS,
143 				(driver_intr_t *)ata_interrupt, ch, &ch->ih,
144 				NULL))) {
145 	device_printf(dev, "unable to setup interrupt\n");
146 	return error;
147     }
148 
149     /* probe and attach devices on this channel unless we are in early boot */
150     ata_identify(dev);
151     return 0;
152 }
153 
154 int
155 ata_detach(device_t dev)
156 {
157     struct ata_channel *ch = device_get_softc(dev);
158     device_t *children;
159     int nchildren, i;
160 
161     /* check that we have a valid channel to detach */
162     if (!ch->r_irq)
163 	return ENXIO;
164 
165     /* grap the channel lock so no new requests gets launched */
166     spin_lock(&ch->state_mtx);
167     ch->state |= ATA_STALL_QUEUE;
168     spin_unlock(&ch->state_mtx);
169 
170     /* detach & delete all children */
171     if (!device_get_children(dev, &children, &nchildren)) {
172 	for (i = 0; i < nchildren; i++)
173 	    if (children[i])
174 		device_delete_child(dev, children[i]);
175 	kfree(children, M_TEMP);
176     }
177 
178     /* release resources */
179     bus_teardown_intr(dev, ch->r_irq, ch->ih);
180     bus_release_resource(dev, SYS_RES_IRQ, ATA_IRQ_RID, ch->r_irq);
181     ch->r_irq = NULL;
182     spin_uninit(&ch->state_mtx);
183     spin_uninit(&ch->queue_mtx);
184     return 0;
185 }
186 
187 int
188 ata_reinit(device_t dev)
189 {
190     struct ata_channel *ch = device_get_softc(dev);
191     struct ata_request *request;
192     device_t *children;
193     int nchildren, i;
194 
195     /* check that we have a valid channel to reinit */
196     if (!ch || !ch->r_irq)
197 	return ENXIO;
198 
199     if (bootverbose)
200 	device_printf(dev, "reiniting channel ..\n");
201 
202     /* poll for locking the channel */
203     while (ATA_LOCKING(dev, ATA_LF_LOCK) != ch->unit)
204 	tsleep(&dev, 0, "atarini", 1);
205 
206     /* catch eventual request in ch->running */
207     spin_lock(&ch->state_mtx);
208     if ((request = ch->running))
209 	callout_stop(&request->callout);
210     ch->running = NULL;
211 
212     /* unconditionally grap the channel lock */
213     ch->state |= ATA_STALL_QUEUE;
214     spin_unlock(&ch->state_mtx);
215 
216     /* reset the controller HW, the channel and device(s) */
217     ATA_RESET(dev);
218 
219     /* reinit the children and delete any that fails */
220     if (!device_get_children(dev, &children, &nchildren)) {
221 	get_mplock();
222 	for (i = 0; i < nchildren; i++) {
223 	    /* did any children go missing ? */
224 	    if (children[i] && device_is_attached(children[i]) &&
225 		ATA_REINIT(children[i])) {
226 		/*
227 		 * if we had a running request and its device matches
228 		 * this child we need to inform the request that the
229 		 * device is gone.
230 		 */
231 		if (request && request->dev == children[i]) {
232 		    request->result = ENXIO;
233 		    device_printf(request->dev, "FAILURE - device detached\n");
234 
235 		    /* if not timeout finish request here */
236 		    if (!(request->flags & ATA_R_TIMEOUT))
237 			    ata_finish(request);
238 		    request = NULL;
239 		}
240 		device_delete_child(dev, children[i]);
241 	    }
242 	}
243 	kfree(children, M_TEMP);
244 	rel_mplock();
245     }
246 
247     /* if we still have a good request put it on the queue again */
248     if (request && !(request->flags & ATA_R_TIMEOUT)) {
249 	device_printf(request->dev,
250 		      "WARNING - %s requeued due to channel reset",
251 		      ata_cmd2str(request));
252 	if (!(request->flags & (ATA_R_ATAPI | ATA_R_CONTROL)))
253 	    kprintf(" LBA=%ju", request->u.ata.lba);
254 	kprintf("\n");
255 	request->flags |= ATA_R_REQUEUE;
256 	ata_queue_request(request);
257     }
258 
259     /* we're done release the channel for new work */
260     spin_lock(&ch->state_mtx);
261     ch->state = ATA_IDLE;
262     spin_unlock(&ch->state_mtx);
263     ATA_LOCKING(dev, ATA_LF_UNLOCK);
264 
265     if (bootverbose)
266 	device_printf(dev, "reinit done ..\n");
267 
268     /* kick off requests on the queue */
269     ata_start(dev);
270     return 0;
271 }
272 
273 int
274 ata_suspend(device_t dev)
275 {
276     struct ata_channel *ch;
277 
278     /* check for valid device */
279     if (!dev || !(ch = device_get_softc(dev)))
280 	return ENXIO;
281 
282     /* wait for the channel to be IDLE or detached before suspending */
283     while (ch->r_irq) {
284 	spin_lock(&ch->state_mtx);
285 	if (ch->state == ATA_IDLE) {
286 	    ch->state = ATA_ACTIVE;
287 	    spin_unlock(&ch->state_mtx);
288 	    break;
289 	}
290 	spin_unlock(&ch->state_mtx);
291 	tsleep(ch, 0, "atasusp", hz/10);
292     }
293     ATA_LOCKING(dev, ATA_LF_UNLOCK);
294     return 0;
295 }
296 
297 int
298 ata_resume(device_t dev)
299 {
300     struct ata_channel *ch;
301     int error;
302 
303     /* check for valid device */
304     if (!dev || !(ch = device_get_softc(dev)))
305 	return ENXIO;
306 
307     /* reinit the devices, we dont know what mode/state they are in */
308     error = ata_reinit(dev);
309 
310     /* kick off requests on the queue */
311     ata_start(dev);
312     return error;
313 }
314 
315 int
316 ata_interrupt(void *data)
317 {
318     struct ata_channel *ch = (struct ata_channel *)data;
319     struct ata_request *request;
320 
321     spin_lock(&ch->state_mtx);
322     do {
323 	/*
324 	 * Ignore interrupt if its not for us.  This may also have the
325 	 * side effect of processing events unrelated to I/O requests.
326 	 */
327 	if (ch->hw.status && !ch->hw.status(ch->dev))
328 	    break;
329 
330 	/*
331 	 * Check if we have a running request, and make sure it has been
332 	 * completely queued.  Otherwise the channel status may indicate
333 	 * not-busy when, in fact, the command had not yet been issued.
334 	 */
335 	if ((request = ch->running) == NULL)
336 	    break;
337 	if ((request->flags & ATA_R_HWCMDQUEUED) == 0) {
338 	    kprintf("ata_interrupt: early interrupt\n");
339 	    break;
340 	}
341 
342 	ATA_DEBUG_RQ(request, "interrupt");
343 
344 	/* safetycheck for the right state */
345 	if (ch->state == ATA_IDLE) {
346 	    device_printf(request->dev, "interrupt on idle channel ignored\n");
347 	    break;
348 	}
349 
350 	/*
351 	 * we have the HW locks, so end the transaction for this request
352 	 * if it finishes immediately otherwise wait for next interrupt
353 	 */
354 	if (ch->hw.end_transaction(request) == ATA_OP_FINISHED) {
355 	    ch->running = NULL;
356 	    if (ch->state == ATA_ACTIVE)
357 		ch->state = ATA_IDLE;
358 	    spin_unlock(&ch->state_mtx);
359 	    ATA_LOCKING(ch->dev, ATA_LF_UNLOCK);
360 	    ata_finish(request);
361 	    return 1;
362 	}
363     } while (0);
364     spin_unlock(&ch->state_mtx);
365     return 0;
366 }
367 
368 /*
369  * device related interfaces
370  */
371 static int
372 ata_ioctl(struct dev_ioctl_args *ap)
373 {
374     device_t device, *children;
375     struct ata_ioc_devices *devices = (struct ata_ioc_devices *)ap->a_data;
376     int *value = (int *)ap->a_data;
377     int i, nchildren, error = ENOTTY;
378 
379     switch (ap->a_cmd) {
380     case IOCATAGMAXCHANNEL:
381 	*value = devclass_get_maxunit(ata_devclass);
382 	error = 0;
383 	break;
384 
385     case IOCATAREINIT:
386 	if (*value > devclass_get_maxunit(ata_devclass) ||
387 	    !(device = devclass_get_device(ata_devclass, *value)))
388 	    return ENXIO;
389 	error = ata_reinit(device);
390 	ata_start(device);
391 	break;
392 
393     case IOCATAATTACH:
394 	if (*value > devclass_get_maxunit(ata_devclass) ||
395 	    !(device = devclass_get_device(ata_devclass, *value)))
396 	    return ENXIO;
397 	/* XXX SOS should enable channel HW on controller */
398 	error = ata_attach(device);
399 	break;
400 
401     case IOCATADETACH:
402 	if (*value > devclass_get_maxunit(ata_devclass) ||
403 	    !(device = devclass_get_device(ata_devclass, *value)))
404 	    return ENXIO;
405 	error = ata_detach(device);
406 	/* XXX SOS should disable channel HW on controller */
407 	break;
408 
409     case IOCATADEVICES:
410 	if (devices->channel > devclass_get_maxunit(ata_devclass) ||
411 	    !(device = devclass_get_device(ata_devclass, devices->channel)))
412 	    return ENXIO;
413 	bzero(devices->name[0], 32);
414 	bzero(&devices->params[0], sizeof(struct ata_params));
415 	bzero(devices->name[1], 32);
416 	bzero(&devices->params[1], sizeof(struct ata_params));
417 	if (!device_get_children(device, &children, &nchildren)) {
418 	    for (i = 0; i < nchildren; i++) {
419 		if (children[i] && device_is_attached(children[i])) {
420 		    struct ata_device *atadev = device_get_softc(children[i]);
421 
422 		    if (atadev->unit == ATA_MASTER) {
423 			strncpy(devices->name[0],
424 				device_get_nameunit(children[i]), 32);
425 			bcopy(&atadev->param, &devices->params[0],
426 			      sizeof(struct ata_params));
427 		    }
428 		    if (atadev->unit == ATA_SLAVE) {
429 			strncpy(devices->name[1],
430 				device_get_nameunit(children[i]), 32);
431 			bcopy(&atadev->param, &devices->params[1],
432 			      sizeof(struct ata_params));
433 		    }
434 		}
435 	    }
436 	    kfree(children, M_TEMP);
437 	    error = 0;
438 	}
439 	else
440 	    error = ENODEV;
441 	break;
442 
443     default:
444 	if (ata_raid_ioctl_func)
445 	    error = ata_raid_ioctl_func(ap->a_cmd, ap->a_data);
446     }
447     return error;
448 }
449 
450 int
451 ata_device_ioctl(device_t dev, u_long cmd, caddr_t data)
452 {
453     struct ata_device *atadev = device_get_softc(dev);
454     struct ata_ioc_request *ioc_request = (struct ata_ioc_request *)data;
455     struct ata_params *params = (struct ata_params *)data;
456     int *mode = (int *)data;
457     struct ata_request *request;
458     caddr_t buf;
459     int error;
460 
461     switch (cmd) {
462     case IOCATAREQUEST:
463 	if (!(buf = kmalloc(ioc_request->count, M_ATA, M_WAITOK | M_NULLOK))) {
464 	    return ENOMEM;
465 	}
466 	if (!(request = ata_alloc_request())) {
467 	    kfree(buf, M_ATA);
468 	    return  ENOMEM;
469 	}
470 	if (ioc_request->flags & ATA_CMD_WRITE) {
471 	    error = copyin(ioc_request->data, buf, ioc_request->count);
472 	    if (error) {
473 		kfree(buf, M_ATA);
474 		ata_free_request(request);
475 		return error;
476 	    }
477 	}
478 	request->dev = dev;
479 	if (ioc_request->flags & ATA_CMD_ATAPI) {
480 	    request->flags = ATA_R_ATAPI;
481 	    bcopy(ioc_request->u.atapi.ccb, request->u.atapi.ccb, 16);
482 	}
483 	else {
484 	    request->u.ata.command = ioc_request->u.ata.command;
485 	    request->u.ata.feature = ioc_request->u.ata.feature;
486 	    request->u.ata.lba = ioc_request->u.ata.lba;
487 	    request->u.ata.count = ioc_request->u.ata.count;
488 	}
489 	request->timeout = ioc_request->timeout;
490 	request->data = buf;
491 	request->bytecount = ioc_request->count;
492 	request->transfersize = request->bytecount;
493 	if (ioc_request->flags & ATA_CMD_CONTROL)
494 	    request->flags |= ATA_R_CONTROL;
495 	if (ioc_request->flags & ATA_CMD_READ)
496 	    request->flags |= ATA_R_READ;
497 	if (ioc_request->flags & ATA_CMD_WRITE)
498 	    request->flags |= ATA_R_WRITE;
499 	ata_queue_request(request);
500 	if (request->flags & ATA_R_ATAPI) {
501 	    bcopy(&request->u.atapi.sense, &ioc_request->u.atapi.sense,
502 		  sizeof(struct atapi_sense));
503 	}
504 	else {
505 	    ioc_request->u.ata.command = request->u.ata.command;
506 	    ioc_request->u.ata.feature = request->u.ata.feature;
507 	    ioc_request->u.ata.lba = request->u.ata.lba;
508 	    ioc_request->u.ata.count = request->u.ata.count;
509 	}
510 	ioc_request->error = request->result;
511 	if (ioc_request->flags & ATA_CMD_READ)
512 	    error = copyout(buf, ioc_request->data, ioc_request->count);
513 	else
514 	    error = 0;
515 	kfree(buf, M_ATA);
516 	ata_free_request(request);
517 	return error;
518 
519     case IOCATAGPARM:
520 	ata_getparam(atadev, 0);
521 	bcopy(&atadev->param, params, sizeof(struct ata_params));
522 	return 0;
523 
524     case IOCATASMODE:
525 	atadev->mode = *mode;
526 	ATA_SETMODE(device_get_parent(dev), dev);
527 	return 0;
528 
529     case IOCATAGMODE:
530 	*mode = atadev->mode;
531 	return 0;
532     default:
533 	return ENOTTY;
534     }
535 }
536 
537 #if 0
538 
539 static void
540 ata_boot_attach(void)
541 {
542     struct ata_channel *ch;
543     int ctlr;
544 
545     get_mplock();
546 
547     /* kick of probe and attach on all channels */
548     for (ctlr = 0; ctlr < devclass_get_maxunit(ata_devclass); ctlr++) {
549 	if ((ch = devclass_get_softc(ata_devclass, ctlr))) {
550 	    ata_identify(ch->dev);
551 	}
552     }
553 
554     rel_mplock();
555 }
556 
557 #endif
558 
559 
560 /*
561  * misc support functions
562  */
563 static device_t
564 ata_add_child(device_t parent, struct ata_device *atadev, int unit)
565 {
566     device_t child;
567 
568     if ((child = device_add_child(parent, NULL, unit))) {
569 	device_set_softc(child, atadev);
570 	device_quiet(child);
571 	atadev->dev = child;
572 	atadev->max_iosize = DEV_BSIZE;
573 	atadev->mode = ATA_PIO_MAX;
574     }
575     return child;
576 }
577 
578 static int
579 ata_getparam(struct ata_device *atadev, int init)
580 {
581     struct ata_channel *ch = device_get_softc(device_get_parent(atadev->dev));
582     struct ata_request *request;
583     u_int8_t command = 0;
584     int error = ENOMEM, retries = 2;
585 
586     if (ch->devices &
587 	(atadev->unit == ATA_MASTER ? ATA_ATA_MASTER : ATA_ATA_SLAVE))
588 	command = ATA_ATA_IDENTIFY;
589     if (ch->devices &
590 	(atadev->unit == ATA_MASTER ? ATA_ATAPI_MASTER : ATA_ATAPI_SLAVE))
591 	command = ATA_ATAPI_IDENTIFY;
592     if (!command)
593 	return ENXIO;
594 
595     while (retries-- > 0 && error) {
596 	if (!(request = ata_alloc_request()))
597 	    break;
598 	request->dev = atadev->dev;
599 	request->timeout = 1;
600 	request->retries = 0;
601 	request->u.ata.command = command;
602 	request->flags = (ATA_R_READ|ATA_R_AT_HEAD|ATA_R_DIRECT|ATA_R_QUIET);
603 	request->data = (void *)&atadev->param;
604 	request->bytecount = sizeof(struct ata_params);
605 	request->donecount = 0;
606 	request->transfersize = DEV_BSIZE;
607 	ata_queue_request(request);
608 	error = request->result;
609 	ata_free_request(request);
610     }
611 
612     if (!error && (isprint(atadev->param.model[0]) ||
613 		   isprint(atadev->param.model[1]))) {
614 	struct ata_params *atacap = &atadev->param;
615 	char buffer[64];
616 	int16_t *ptr;
617 
618 	for (ptr = (int16_t *)atacap;
619 	     ptr < (int16_t *)atacap + sizeof(struct ata_params)/2; ptr++) {
620 	    *ptr = le16toh(*ptr);
621 	}
622 	if (!(!strncmp(atacap->model, "FX", 2) ||
623 	      !strncmp(atacap->model, "NEC", 3) ||
624 	      !strncmp(atacap->model, "Pioneer", 7) ||
625 	      !strncmp(atacap->model, "SHARP", 5))) {
626 	    bswap(atacap->model, sizeof(atacap->model));
627 	    bswap(atacap->revision, sizeof(atacap->revision));
628 	    bswap(atacap->serial, sizeof(atacap->serial));
629 	}
630 	btrim(atacap->model, sizeof(atacap->model));
631 	bpack(atacap->model, atacap->model, sizeof(atacap->model));
632 	btrim(atacap->revision, sizeof(atacap->revision));
633 	bpack(atacap->revision, atacap->revision, sizeof(atacap->revision));
634 	btrim(atacap->serial, sizeof(atacap->serial));
635 	bpack(atacap->serial, atacap->serial, sizeof(atacap->serial));
636 
637 	if (bootverbose)
638 	    kprintf("ata%d-%s: pio=%s wdma=%s udma=%s cable=%s wire\n",
639 		   device_get_unit(ch->dev),
640 		   atadev->unit == ATA_MASTER ? "master" : "slave",
641 		   ata_mode2str(ata_pmode(atacap)),
642 		   ata_mode2str(ata_wmode(atacap)),
643 		   ata_mode2str(ata_umode(atacap)),
644 		   (atacap->hwres & ATA_CABLE_ID) ? "80":"40");
645 
646 	if (init) {
647 	    ksprintf(buffer, "%.40s/%.8s", atacap->model, atacap->revision);
648 	    device_set_desc_copy(atadev->dev, buffer);
649 	    if ((atadev->param.config & ATA_PROTO_ATAPI) &&
650 		(atadev->param.config != ATA_CFA_MAGIC1) &&
651 		(atadev->param.config != ATA_CFA_MAGIC2)) {
652 		if (atapi_dma && ch->dma &&
653 		    (atadev->param.config & ATA_DRQ_MASK) != ATA_DRQ_INTR &&
654 		    ata_umode(&atadev->param) >= ATA_UDMA2)
655 		    atadev->mode = ATA_DMA_MAX;
656 	    }
657 	    else {
658 		if (ata_dma && ch->dma &&
659 		    (ata_umode(&atadev->param) > 0 ||
660 		     ata_wmode(&atadev->param) > 0))
661 		    atadev->mode = ATA_DMA_MAX;
662 	    }
663 	}
664     }
665     else {
666 	if (!error)
667 	    error = ENXIO;
668     }
669     return error;
670 }
671 
672 int
673 ata_identify(device_t dev)
674 {
675     struct ata_channel *ch = device_get_softc(dev);
676     struct ata_device *master = NULL, *slave = NULL;
677     device_t master_child = NULL, slave_child = NULL;
678     int master_unit = -1, slave_unit = -1;
679 
680     if (ch->devices & (ATA_ATA_MASTER | ATA_ATAPI_MASTER)) {
681 	if (!(master = kmalloc(sizeof(struct ata_device),
682 			      M_ATA, M_INTWAIT | M_ZERO))) {
683 	    device_printf(dev, "out of memory\n");
684 	    return ENOMEM;
685 	}
686 	master->unit = ATA_MASTER;
687     }
688     if (ch->devices & (ATA_ATA_SLAVE | ATA_ATAPI_SLAVE)) {
689 	if (!(slave = kmalloc(sizeof(struct ata_device),
690 			     M_ATA, M_INTWAIT | M_ZERO))) {
691 	    kfree(master, M_ATA);
692 	    device_printf(dev, "out of memory\n");
693 	    return ENOMEM;
694 	}
695 	slave->unit = ATA_SLAVE;
696     }
697 
698 #ifdef ATA_STATIC_ID
699     if (ch->devices & ATA_ATA_MASTER)
700 	master_unit = (device_get_unit(dev) << 1);
701 #endif
702     if (master && !(master_child = ata_add_child(dev, master, master_unit))) {
703 	kfree(master, M_ATA);
704 	master = NULL;
705     }
706 #ifdef ATA_STATIC_ID
707     if (ch->devices & ATA_ATA_SLAVE)
708 	slave_unit = (device_get_unit(dev) << 1) + 1;
709 #endif
710     if (slave && !(slave_child = ata_add_child(dev, slave, slave_unit))) {
711 	kfree(slave, M_ATA);
712 	slave = NULL;
713     }
714 
715     if (slave && ata_getparam(slave, 1)) {
716 	device_delete_child(dev, slave_child);
717 	kfree(slave, M_ATA);
718     }
719     if (master && ata_getparam(master, 1)) {
720 	device_delete_child(dev, master_child);
721 	kfree(master, M_ATA);
722     }
723 
724     bus_generic_probe(dev);
725     bus_generic_attach(dev);
726     return 0;
727 }
728 
729 void
730 ata_default_registers(device_t dev)
731 {
732     struct ata_channel *ch = device_get_softc(dev);
733 
734     /* fill in the defaults from whats setup already */
735     ch->r_io[ATA_ERROR].res = ch->r_io[ATA_FEATURE].res;
736     ch->r_io[ATA_ERROR].offset = ch->r_io[ATA_FEATURE].offset;
737     ch->r_io[ATA_IREASON].res = ch->r_io[ATA_COUNT].res;
738     ch->r_io[ATA_IREASON].offset = ch->r_io[ATA_COUNT].offset;
739     ch->r_io[ATA_STATUS].res = ch->r_io[ATA_COMMAND].res;
740     ch->r_io[ATA_STATUS].offset = ch->r_io[ATA_COMMAND].offset;
741     ch->r_io[ATA_ALTSTAT].res = ch->r_io[ATA_CONTROL].res;
742     ch->r_io[ATA_ALTSTAT].offset = ch->r_io[ATA_CONTROL].offset;
743 }
744 
745 void
746 ata_modify_if_48bit(struct ata_request *request)
747 {
748     struct ata_channel *ch = device_get_softc(device_get_parent(request->dev));
749     struct ata_device *atadev = device_get_softc(request->dev);
750 
751     atadev->flags &= ~ATA_D_48BIT_ACTIVE;
752 
753     if ((request->u.ata.lba + request->u.ata.count >= ATA_MAX_28BIT_LBA ||
754 	 request->u.ata.count > 256) &&
755 	atadev->param.support.command2 & ATA_SUPPORT_ADDRESS48) {
756 
757 	/* translate command into 48bit version */
758 	switch (request->u.ata.command) {
759 	case ATA_READ:
760 	    request->u.ata.command = ATA_READ48;
761 	    break;
762 	case ATA_READ_MUL:
763 	    request->u.ata.command = ATA_READ_MUL48;
764 	    break;
765 	case ATA_READ_DMA:
766 	    if (ch->flags & ATA_NO_48BIT_DMA) {
767 		if (request->transfersize > DEV_BSIZE)
768 		    request->u.ata.command = ATA_READ_MUL48;
769 		else
770 		    request->u.ata.command = ATA_READ48;
771 		request->flags &= ~ATA_R_DMA;
772 	    }
773 	    else
774 		request->u.ata.command = ATA_READ_DMA48;
775 	    break;
776 	case ATA_READ_DMA_QUEUED:
777 	    if (ch->flags & ATA_NO_48BIT_DMA) {
778 		if (request->transfersize > DEV_BSIZE)
779 		    request->u.ata.command = ATA_READ_MUL48;
780 		else
781 		    request->u.ata.command = ATA_READ48;
782 		request->flags &= ~ATA_R_DMA;
783 	    }
784 	    else
785 		request->u.ata.command = ATA_READ_DMA_QUEUED48;
786 	    break;
787 	case ATA_WRITE:
788 	    request->u.ata.command = ATA_WRITE48;
789 	    break;
790 	case ATA_WRITE_MUL:
791 	    request->u.ata.command = ATA_WRITE_MUL48;
792 	    break;
793 	case ATA_WRITE_DMA:
794 	    if (ch->flags & ATA_NO_48BIT_DMA) {
795 		if (request->transfersize > DEV_BSIZE)
796 		    request->u.ata.command = ATA_WRITE_MUL48;
797 		else
798 		    request->u.ata.command = ATA_WRITE48;
799 		request->flags &= ~ATA_R_DMA;
800 	    }
801 	    else
802 		request->u.ata.command = ATA_WRITE_DMA48;
803 	    break;
804 	case ATA_WRITE_DMA_QUEUED:
805 	    if (ch->flags & ATA_NO_48BIT_DMA) {
806 		if (request->transfersize > DEV_BSIZE)
807 		    request->u.ata.command = ATA_WRITE_MUL48;
808 		else
809 		    request->u.ata.command = ATA_WRITE48;
810 		request->u.ata.command = ATA_WRITE48;
811 		request->flags &= ~ATA_R_DMA;
812 	    }
813 	    else
814 		request->u.ata.command = ATA_WRITE_DMA_QUEUED48;
815 	    break;
816 	case ATA_FLUSHCACHE:
817 	    request->u.ata.command = ATA_FLUSHCACHE48;
818 	    break;
819 	case ATA_READ_NATIVE_MAX_ADDDRESS:
820 	    request->u.ata.command = ATA_READ_NATIVE_MAX_ADDDRESS48;
821 	    break;
822 	case ATA_SET_MAX_ADDRESS:
823 	    request->u.ata.command = ATA_SET_MAX_ADDRESS48;
824 	    break;
825 	default:
826 	    return;
827 	}
828 	atadev->flags |= ATA_D_48BIT_ACTIVE;
829     }
830 }
831 
832 void
833 ata_udelay(int interval)
834 {
835     /*
836      * We can't use tsleep here, because we might be called from callout
837      * context.
838      */
839     if (1 || interval < (1000000/hz))
840 	DELAY(interval);
841     else
842 	tsleep(&interval, 0, "ataslp", 1 + interval / (1000000 / hz));
843 }
844 
845 char *
846 ata_mode2str(int mode)
847 {
848     switch (mode) {
849     case -1: return "UNSUPPORTED";
850     case ATA_PIO0: return "PIO0";
851     case ATA_PIO1: return "PIO1";
852     case ATA_PIO2: return "PIO2";
853     case ATA_PIO3: return "PIO3";
854     case ATA_PIO4: return "PIO4";
855     case ATA_WDMA0: return "WDMA0";
856     case ATA_WDMA1: return "WDMA1";
857     case ATA_WDMA2: return "WDMA2";
858     case ATA_UDMA0: return "UDMA16";
859     case ATA_UDMA1: return "UDMA25";
860     case ATA_UDMA2: return "UDMA33";
861     case ATA_UDMA3: return "UDMA40";
862     case ATA_UDMA4: return "UDMA66";
863     case ATA_UDMA5: return "UDMA100";
864     case ATA_UDMA6: return "UDMA133";
865     case ATA_SA150: return "SATA150";
866     case ATA_SA300: return "SATA300";
867     case ATA_USB: return "USB";
868     case ATA_USB1: return "USB1";
869     case ATA_USB2: return "USB2";
870     default:
871 	if (mode & ATA_DMA_MASK)
872 	    return "BIOSDMA";
873 	else
874 	    return "BIOSPIO";
875     }
876 }
877 
878 int
879 ata_pmode(struct ata_params *ap)
880 {
881     if (ap->atavalid & ATA_FLAG_64_70) {
882 	if (ap->apiomodes & 0x02)
883 	    return ATA_PIO4;
884 	if (ap->apiomodes & 0x01)
885 	    return ATA_PIO3;
886     }
887     if (ap->mwdmamodes & 0x04)
888 	return ATA_PIO4;
889     if (ap->mwdmamodes & 0x02)
890 	return ATA_PIO3;
891     if (ap->mwdmamodes & 0x01)
892 	return ATA_PIO2;
893     if ((ap->retired_piomode & ATA_RETIRED_PIO_MASK) == 0x200)
894 	return ATA_PIO2;
895     if ((ap->retired_piomode & ATA_RETIRED_PIO_MASK) == 0x100)
896 	return ATA_PIO1;
897     if ((ap->retired_piomode & ATA_RETIRED_PIO_MASK) == 0x000)
898 	return ATA_PIO0;
899     return ATA_PIO0;
900 }
901 
902 int
903 ata_wmode(struct ata_params *ap)
904 {
905     if (ap->mwdmamodes & 0x04)
906 	return ATA_WDMA2;
907     if (ap->mwdmamodes & 0x02)
908 	return ATA_WDMA1;
909     if (ap->mwdmamodes & 0x01)
910 	return ATA_WDMA0;
911     return -1;
912 }
913 
914 int
915 ata_umode(struct ata_params *ap)
916 {
917     if (ap->atavalid & ATA_FLAG_88) {
918 	if (ap->udmamodes & 0x40)
919 	    return ATA_UDMA6;
920 	if (ap->udmamodes & 0x20)
921 	    return ATA_UDMA5;
922 	if (ap->udmamodes & 0x10)
923 	    return ATA_UDMA4;
924 	if (ap->udmamodes & 0x08)
925 	    return ATA_UDMA3;
926 	if (ap->udmamodes & 0x04)
927 	    return ATA_UDMA2;
928 	if (ap->udmamodes & 0x02)
929 	    return ATA_UDMA1;
930 	if (ap->udmamodes & 0x01)
931 	    return ATA_UDMA0;
932     }
933     return -1;
934 }
935 
936 int
937 ata_limit_mode(device_t dev, int mode, int maxmode)
938 {
939     struct ata_device *atadev = device_get_softc(dev);
940 
941     if (maxmode && mode > maxmode)
942 	mode = maxmode;
943 
944     if (mode >= ATA_UDMA0 && ata_umode(&atadev->param) > 0)
945 	return min(mode, ata_umode(&atadev->param));
946 
947     if (mode >= ATA_WDMA0 && ata_wmode(&atadev->param) > 0)
948 	return min(mode, ata_wmode(&atadev->param));
949 
950     if (mode > ata_pmode(&atadev->param))
951 	return min(mode, ata_pmode(&atadev->param));
952 
953     return mode;
954 }
955 
956 static void
957 bswap(int8_t *buf, int len)
958 {
959     u_int16_t *ptr = (u_int16_t*)(buf + len);
960 
961     while (--ptr >= (u_int16_t*)buf)
962 	*ptr = ntohs(*ptr);
963 }
964 
965 static void
966 btrim(int8_t *buf, int len)
967 {
968     int8_t *ptr;
969 
970     for (ptr = buf; ptr < buf+len; ++ptr)
971 	if (!*ptr || *ptr == '_')
972 	    *ptr = ' ';
973     for (ptr = buf + len - 1; ptr >= buf && *ptr == ' '; --ptr)
974 	*ptr = 0;
975 }
976 
977 static void
978 bpack(int8_t *src, int8_t *dst, int len)
979 {
980     int i, j, blank;
981 
982     for (i = j = blank = 0 ; i < len; i++) {
983 	if (blank && src[i] == ' ') continue;
984 	if (blank && src[i] != ' ') {
985 	    dst[j++] = src[i];
986 	    blank = 0;
987 	    continue;
988 	}
989 	if (src[i] == ' ') {
990 	    blank = 1;
991 	    if (i == 0)
992 		continue;
993 	}
994 	dst[j++] = src[i];
995     }
996     if (j < len)
997 	dst[j] = 0x00;
998 }
999 
1000 
1001 /*
1002  * module handeling
1003  */
1004 static int
1005 ata_module_event_handler(module_t mod, int what, void *arg)
1006 {
1007     /* static because we need the reference at destruction time */
1008     static cdev_t atacdev;
1009 
1010     switch (what) {
1011     case MOD_LOAD:
1012 	/* register controlling device */
1013 	atacdev = make_dev(&ata_ops, 0, UID_ROOT, GID_OPERATOR, 0600, "ata");
1014 	reference_dev(atacdev);
1015 	return 0;
1016 
1017     case MOD_UNLOAD:
1018 	/* deregister controlling device */
1019 	destroy_dev(atacdev);
1020 	dev_ops_remove_all(&ata_ops);
1021 	return 0;
1022 
1023     default:
1024 	return EOPNOTSUPP;
1025     }
1026 }
1027 
1028 static moduledata_t ata_moduledata = { "ata", ata_module_event_handler, NULL };
1029 DECLARE_MODULE(ata, ata_moduledata, SI_SUB_CONFIGURE, SI_ORDER_SECOND);
1030 MODULE_VERSION(ata, 1);
1031 
1032 /*
1033  * Construct a completely zero'ed ata_request. On objcache_put(), an
1034  * ata_request object is also zero'ed, so objcache_get() is guaranteed to give
1035  * completely zero'ed objects without spending too much time.
1036  */
1037 static boolean_t
1038 ata_request_cache_ctor(void *obj, void *private, int ocflags)
1039 {
1040     struct ata_request *arp = obj;
1041 
1042     bzero(arp, sizeof(struct ata_request));
1043     return(TRUE);
1044 }
1045 
1046 /*
1047  * Construct a completely zero'ed ata_composite. On objcache_put(), an
1048  * ata_composite object is also zero'ed, so objcache_get() is guaranteed to give
1049  * completely zero'ed objects without spending too much time.
1050  */
1051 static boolean_t
1052 ata_composite_cache_ctor(void *obj, void *private, int ocflags)
1053 {
1054     struct ata_composite *acp = obj;
1055 
1056     bzero(acp, sizeof(struct ata_composite));
1057     return(TRUE);
1058 }
1059 
1060 static void
1061 ata_init(void)
1062 {
1063     ata_request_cache = objcache_create("ata_request", 0, 0,
1064 					ata_request_cache_ctor, NULL, NULL,
1065 					objcache_malloc_alloc,
1066 					objcache_malloc_free,
1067 					&ata_request_malloc_args);
1068     ata_composite_cache = objcache_create("ata_composite", 0, 0,
1069 					  ata_composite_cache_ctor, NULL, NULL,
1070 					  objcache_malloc_alloc,
1071 					  objcache_malloc_free,
1072 					  &ata_composite_malloc_args);
1073 }
1074 SYSINIT(ata_register, SI_SUB_DRIVERS, SI_ORDER_SECOND, ata_init, NULL);
1075 
1076 static void
1077 ata_uninit(void)
1078 {
1079     objcache_destroy(ata_composite_cache);
1080     objcache_destroy(ata_request_cache);
1081 }
1082 SYSUNINIT(ata_unregister, SI_SUB_DRIVERS, SI_ORDER_SECOND, ata_uninit, NULL);
1083