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