xref: /netbsd-src/sys/dev/mca/edc_mca.c (revision 53b02e147d4ed531c0d2a5ca9b3e8026ba3e99b5)
1 /*	$NetBSD: edc_mca.c,v 1.54 2021/08/07 16:19:13 thorpej Exp $	*/
2 
3 /*
4  * Copyright (c) 2001 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Jaromir Dolecek.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * Driver for MCA ESDI controllers and disks conforming to IBM DASD
34  * spec.
35  *
36  * The driver was written with DASD Storage Interface Specification
37  * for MCA rev. 2.2 in hands, thanks to Scott Telford <st@epcc.ed.ac.uk>.
38  *
39  * TODO:
40  * - improve error recovery
41  *   Issue soft reset on error or timeout?
42  * - test with > 1 disk (this is supported by some controllers)
43  * - test with > 1 ESDI controller in machine; shared interrupts
44  *   necessary for this to work should be supported - edc_intr() specifically
45  *   checks if the interrupt is for this controller
46  */
47 
48 #include <sys/cdefs.h>
49 __KERNEL_RCSID(0, "$NetBSD: edc_mca.c,v 1.54 2021/08/07 16:19:13 thorpej Exp $");
50 
51 #include <sys/param.h>
52 #include <sys/systm.h>
53 #include <sys/buf.h>
54 #include <sys/bufq.h>
55 #include <sys/errno.h>
56 #include <sys/device.h>
57 #include <sys/malloc.h>
58 #include <sys/endian.h>
59 #include <sys/disklabel.h>
60 #include <sys/disk.h>
61 #include <sys/syslog.h>
62 #include <sys/proc.h>
63 #include <sys/vnode.h>
64 #include <sys/kernel.h>
65 #include <sys/kthread.h>
66 #include <sys/rndsource.h>
67 
68 #include <sys/bus.h>
69 #include <sys/intr.h>
70 
71 #include <dev/mca/mcareg.h>
72 #include <dev/mca/mcavar.h>
73 #include <dev/mca/mcadevs.h>
74 
75 #include <dev/mca/edcreg.h>
76 #include <dev/mca/edvar.h>
77 #include <dev/mca/edcvar.h>
78 
79 #include "locators.h"
80 
81 #define EDC_ATTN_MAXTRIES	10000	/* How many times check for unbusy */
82 #define EDC_MAX_CMD_RES_LEN	8
83 
84 struct edc_mca_softc {
85 	device_t sc_dev;
86 
87 	bus_space_tag_t	sc_iot;
88 	bus_space_handle_t sc_ioh;
89 
90 	/* DMA related stuff */
91 	bus_dma_tag_t sc_dmat;		/* DMA tag as passed by parent */
92 	bus_dmamap_t  sc_dmamap_xfer;	/* transfer dma map */
93 
94 	void	*sc_ih;				/* interrupt handle */
95 
96 	int	sc_flags;
97 #define	DASD_QUIET	0x01		/* don't dump cmd error info */
98 
99 #define DASD_MAXDEVS	8
100 	struct ed_softc *sc_ed[DASD_MAXDEVS];
101 	int sc_maxdevs;			/* max number of disks attached to this
102 					 * controller */
103 
104 	/* I/O results variables */
105 	volatile int sc_stat;
106 #define	STAT_START	0
107 #define	STAT_ERROR	1
108 #define	STAT_DONE	2
109 	volatile int sc_resblk;		/* residual block count */
110 
111 	/* CMD status block - only set & used in edc_intr() */
112 	u_int16_t status_block[EDC_MAX_CMD_RES_LEN];
113 };
114 
115 int	edc_mca_probe(device_t, cfdata_t, void *);
116 void	edc_mca_attach(device_t, device_t, void *);
117 
118 CFATTACH_DECL_NEW(edc_mca, sizeof(struct edc_mca_softc),
119     edc_mca_probe, edc_mca_attach, NULL, NULL);
120 
121 static int	edc_intr(void *);
122 static void	edc_dump_status_block(struct edc_mca_softc *,
123 		    u_int16_t *, int);
124 static int	edc_do_attn(struct edc_mca_softc *, int, int, int);
125 static void	edc_cmd_wait(struct edc_mca_softc *, int, int);
126 static void	edcworker(void *);
127 
128 int
129 edc_mca_probe(device_t parent, cfdata_t match, void *aux)
130 {
131 	struct mca_attach_args *ma = aux;
132 
133 	switch (ma->ma_id) {
134 	case MCA_PRODUCT_IBM_ESDIC:
135 	case MCA_PRODUCT_IBM_ESDIC_IG:
136 		return (1);
137 	default:
138 		return (0);
139 	}
140 }
141 
142 void
143 edc_mca_attach(device_t parent, device_t self, void *aux)
144 {
145 	struct edc_mca_softc *sc = device_private(self);
146 	struct mca_attach_args *ma = aux;
147 	struct ed_attach_args eda;
148 	int pos2, pos3, pos4;
149 	int irq, drq, iobase;
150 	const char *typestr;
151 	int devno, error;
152 	int locs[EDCCF_NLOCS];
153 
154 	sc->sc_dev = self;
155 
156 	pos2 = mca_conf_read(ma->ma_mc, ma->ma_slot, 2);
157 	pos3 = mca_conf_read(ma->ma_mc, ma->ma_slot, 3);
158 	pos4 = mca_conf_read(ma->ma_mc, ma->ma_slot, 4);
159 
160 	/*
161 	 * POS register 2: (adf pos0)
162 	 *
163 	 * 7 6 5 4 3 2 1 0
164 	 *   \ \____/  \ \__ enable: 0=adapter disabled, 1=adapter enabled
165 	 *    \     \   \___ Primary/Alternate Port Addresses:
166 	 *     \     \		0=0x3510-3517 1=0x3518-0x351f
167 	 *      \     \_____ DMA Arbitration Level: 0101=5 0110=6 0111=7
168 	 *       \              0000=0 0001=1 0011=3 0100=4
169 	 *        \_________ Fairness On/Off: 1=On 0=Off
170 	 *
171 	 * POS register 3: (adf pos1)
172 	 *
173 	 * 7 6 5 4 3 2 1 0
174 	 * 0 0 \_/
175 	 *       \__________ DMA Burst Pacing Interval: 10=24ms 11=31ms
176 	 *                     01=16ms 00=Burst Disabled
177 	 *
178 	 * POS register 4: (adf pos2)
179 	 *
180 	 * 7 6 5 4 3 2 1 0
181 	 *           \_/ \__ DMA Pacing Control: 1=Disabled 0=Enabled
182 	 *             \____ Time to Release: 1X=6ms 01=3ms 00=Immediate
183 	 *
184 	 * IRQ is fixed to 14 (0x0e).
185 	 */
186 
187 	switch (ma->ma_id) {
188 	case MCA_PRODUCT_IBM_ESDIC:
189 		typestr = "IBM ESDI Fixed Disk Controller";
190 		break;
191 	case MCA_PRODUCT_IBM_ESDIC_IG:
192 		typestr = "IBM Integ. ESDI Fixed Disk & Controller";
193 		break;
194 	default:
195 		typestr = NULL;
196 		break;
197 	}
198 
199 	irq = ESDIC_IRQ;
200 	iobase = (pos2 & IO_IS_ALT) ? ESDIC_IOALT : ESDIC_IOPRM;
201 	drq = (pos2 & DRQ_MASK) >> 2;
202 
203 	aprint_naive("\n");
204 	aprint_normal(": slot %d irq %d drq %d: %s\n", ma->ma_slot+1,
205 		irq, drq, typestr);
206 
207 #ifdef DIAGNOSTIC
208 	/*
209 	 * It's not strictly necessary to check this, machine configuration
210 	 * utility uses only valid addresses.
211 	 */
212 	if (drq == 2 || drq >= 8) {
213 		aprint_error_dev(sc->sc_dev,
214 		    "invalid DMA Arbitration Level %d\n", drq);
215 		return;
216 	}
217 #endif
218 
219 	aprint_normal_dev(self, "Fairness %s, Release %s, ",
220 		(pos2 & FAIRNESS_ENABLE) ? "On" : "Off",
221 		(pos4 & RELEASE_1) ? "6ms"
222 				: ((pos4 & RELEASE_2) ? "3ms" : "Immediate")
223 		);
224 	if ((pos4 & PACING_CTRL_DISABLE) == 0) {
225 		static const char * const pacint[] =
226 			{ "disabled", "16ms", "24ms", "31ms"};
227 		aprint_normal("DMA burst pacing interval %s\n",
228 			pacint[(pos3 & PACING_INT_MASK) >> 4]);
229 	} else
230 		aprint_normal("DMA pacing control disabled\n");
231 
232 	sc->sc_iot = ma->ma_iot;
233 
234 	if (bus_space_map(sc->sc_iot, iobase,
235 	    ESDIC_REG_NPORTS, 0, &sc->sc_ioh)) {
236 		aprint_error_dev(sc->sc_dev, "couldn't map registers\n");
237 		return;
238 	}
239 
240 	sc->sc_ih = mca_intr_establish(ma->ma_mc, irq, IPL_BIO, edc_intr, sc);
241 	if (sc->sc_ih == NULL) {
242 		aprint_error_dev(sc->sc_dev,
243 		    "couldn't establish interrupt handler\n");
244 		return;
245 	}
246 
247 	/* Create a MCA DMA map, used for data transfer */
248 	sc->sc_dmat = ma->ma_dmat;
249 	if ((error = mca_dmamap_create(sc->sc_dmat, MAXPHYS,
250 	    BUS_DMA_NOWAIT | BUS_DMA_ALLOCNOW | MCABUS_DMA_16BIT,
251 	    &sc->sc_dmamap_xfer, drq)) != 0){
252 		aprint_error_dev(sc->sc_dev,
253 		    "couldn't create DMA map - error %d\n", error);
254 		return;
255 	}
256 
257 	/*
258 	 * Integrated ESDI controller supports only one disk, other
259 	 * controllers support two disks.
260 	 */
261 	if (ma->ma_id == MCA_PRODUCT_IBM_ESDIC_IG)
262 		sc->sc_maxdevs = 1;
263 	else
264 		sc->sc_maxdevs = 2;
265 
266 	/*
267 	 * Reset controller and attach individual disks. ed attach routine
268 	 * uses polling so that this works with interrupts disabled.
269 	 */
270 
271 	/* Do a reset to ensure sane state after warm boot. */
272 	if (bus_space_read_1(sc->sc_iot, sc->sc_ioh, BSR) & BSR_BUSY) {
273 		/* hard reset */
274 		aprint_normal_dev(self, "controller busy, "
275 		    "performing hardware reset ...\n");
276 		bus_space_write_1(sc->sc_iot, sc->sc_ioh, BCR,
277 			BCR_INT_ENABLE|BCR_RESET);
278 	} else {
279 		/* "SOFT" reset */
280 		edc_do_attn(sc, ATN_RESET_ATTACHMENT, DASD_DEVNO_CONTROLLER,0);
281 	}
282 
283 	/*
284 	 * Since interrupts are disabled, it's necessary
285 	 * to detect the interrupt request and call edc_intr()
286 	 * explicitly. See also edc_run_cmd().
287 	 */
288 	while (bus_space_read_1(sc->sc_iot, sc->sc_ioh, BSR) & BSR_BUSY) {
289 		if (bus_space_read_1(sc->sc_iot, sc->sc_ioh, BSR) & BSR_INTR)
290 			edc_intr(sc);
291 
292 		delay(100);
293 	}
294 
295 	/* be quiet during probes */
296 	sc->sc_flags |= DASD_QUIET;
297 
298 	/* check for attached disks */
299 	for (devno = 0; devno < sc->sc_maxdevs; devno++) {
300 		eda.edc_drive = devno;
301 		locs[EDCCF_DRIVE] = devno;
302 
303 		sc->sc_ed[devno] = device_private(
304 		    config_found(self, &eda, NULL,
305 				 CFARGS(.submatch = config_stdsubmatch,
306 					.locators = locs)));
307 
308 		/* If initialization did not succeed, NULL the pointer. */
309 		if (sc->sc_ed[devno]
310 		    && (sc->sc_ed[devno]->sc_flags & EDF_INIT) == 0)
311 			sc->sc_ed[devno] = NULL;
312 	}
313 
314 	/* enable full error dumps again */
315 	sc->sc_flags &= ~DASD_QUIET;
316 
317 	/*
318 	 * Check if there are any disks attached. If not, disestablish
319 	 * the interrupt.
320 	 */
321 	for (devno = 0; devno < sc->sc_maxdevs; devno++) {
322 		if (sc->sc_ed[devno])
323 			break;
324 	}
325 
326 	if (devno == sc->sc_maxdevs) {
327 		aprint_error("%s: disabling controller (no drives attached)\n",
328 			device_xname(sc->sc_dev));
329 		mca_intr_disestablish(ma->ma_mc, sc->sc_ih);
330 		return;
331 	}
332 
333 	/*
334 	 * Run the worker thread.
335 	 */
336 	config_pending_incr(self);
337 	if ((error = kthread_create(PRI_NONE, 0, NULL, edcworker, sc, NULL,
338 	    "%s", device_xname(sc->sc_dev)))) {
339 		aprint_error_dev(sc->sc_dev,
340 		    "cannot spawn worker thread: errno=%d\n", error);
341 		panic("edc_mca_attach");
342 	}
343 }
344 
345 void
346 edc_add_disk(struct edc_mca_softc *sc, struct ed_softc *ed)
347 {
348 	sc->sc_ed[ed->sc_devno] = ed;
349 }
350 
351 static int
352 edc_intr(void *arg)
353 {
354 	struct edc_mca_softc *sc = arg;
355 	u_int8_t isr, intr_id;
356 	u_int16_t sifr;
357 	int cmd = -1, devno;
358 
359 	/*
360 	 * Check if the interrupt was for us.
361 	 */
362 	if ((bus_space_read_1(sc->sc_iot, sc->sc_ioh, BSR) & BSR_INTR) == 0)
363 		return (0);
364 
365 	/*
366 	 * Read ISR to find out interrupt type. This also clears the interrupt
367 	 * condition and BSR_INTR flag. Accordings to docs interrupt ID of 0, 2
368 	 * and 4 are reserved and not used.
369 	 */
370 	isr = bus_space_read_1(sc->sc_iot, sc->sc_ioh, ISR);
371 	intr_id = isr & ISR_INTR_ID_MASK;
372 
373 #ifdef EDC_DEBUG
374 	if (intr_id == 0 || intr_id == 2 || intr_id == 4) {
375 		aprint_error_dev(sc->sc_dev, "bogus interrupt id %d\n",
376 			(int) intr_id);
377 		return (0);
378 	}
379 #endif
380 
381 	/* Get number of device whose intr this was */
382 	devno = (isr & 0xe0) >> 5;
383 
384 	/*
385 	 * Get Status block. Higher byte always says how long the status
386 	 * block is, rest is device number and command code.
387 	 * Check the status block length against our supported maximum length
388 	 * and fetch the data.
389 	 */
390 	if (bus_space_read_1(sc->sc_iot, sc->sc_ioh,BSR) & BSR_SIFR_FULL) {
391 		size_t len;
392 		int i;
393 
394 		sifr = le16toh(bus_space_read_2(sc->sc_iot, sc->sc_ioh, SIFR));
395 		len = (sifr & 0xff00) >> 8;
396 #ifdef DEBUG
397 		if (len > EDC_MAX_CMD_RES_LEN)
398 			panic("%s: maximum Status Length exceeded: %d > %d",
399 				device_xname(sc->sc_dev),
400 				len, EDC_MAX_CMD_RES_LEN);
401 #endif
402 
403 		/* Get command code */
404 		cmd = sifr & SIFR_CMD_MASK;
405 
406 		/* Read whole status block */
407 		sc->status_block[0] = sifr;
408 		for(i=1; i < len; i++) {
409 			while((bus_space_read_1(sc->sc_iot, sc->sc_ioh, BSR)
410 				& BSR_SIFR_FULL) == 0)
411 				;
412 
413 			sc->status_block[i] = le16toh(
414 				bus_space_read_2(sc->sc_iot, sc->sc_ioh, SIFR));
415 		}
416 		/* zero out rest */
417 		if (i < EDC_MAX_CMD_RES_LEN) {
418 			memset(&sc->status_block[i], 0,
419 				(EDC_MAX_CMD_RES_LEN-i)*sizeof(u_int16_t));
420 		}
421 	}
422 
423 	switch (intr_id) {
424 	case ISR_DATA_TRANSFER_RDY:
425 		/*
426 		 * Ready to do DMA. The DMA controller has already been
427 		 * setup, now just kick disk controller to do the transfer.
428 		 */
429 		bus_space_write_1(sc->sc_iot, sc->sc_ioh, BCR,
430 			BCR_INT_ENABLE|BCR_DMA_ENABLE);
431 		break;
432 
433 	case ISR_COMPLETED:
434 	case ISR_COMPLETED_WITH_ECC:
435 	case ISR_COMPLETED_RETRIES:
436 	case ISR_COMPLETED_WARNING:
437 		/*
438 		 * Copy device config data if appropriate. sc->sc_ed[]
439 		 * entry might be NULL during probe.
440 		 */
441 		if (cmd == CMD_GET_DEV_CONF && sc->sc_ed[devno]) {
442 			memcpy(sc->sc_ed[devno]->sense_data, sc->status_block,
443 				sizeof(sc->sc_ed[devno]->sense_data));
444 		}
445 
446 		sc->sc_stat = STAT_DONE;
447 		break;
448 
449 	case ISR_RESET_COMPLETED:
450 	case ISR_ABORT_COMPLETED:
451 		/* nothing to do */
452 		break;
453 
454 	case ISR_ATTN_ERROR:
455 		/*
456 		 * Basically, this means driver bug or something seriously
457 		 * hosed. panic rather than extending the lossage.
458 		 * No status block available, so no further info.
459 		 */
460 		panic("%s: dev %d: attention error",
461 			device_xname(sc->sc_dev),
462 			devno);
463 		/* NOTREACHED */
464 		break;
465 
466 	default:
467 		if ((sc->sc_flags & DASD_QUIET) == 0)
468 			edc_dump_status_block(sc, sc->status_block, intr_id);
469 
470 		sc->sc_stat = STAT_ERROR;
471 		break;
472 	}
473 
474 	/*
475 	 * Unless the interrupt is for Data Transfer Ready or
476 	 * Attention Error, finish by assertion EOI. This makes
477 	 * attachment aware the interrupt is processed and system
478 	 * is ready to accept another one.
479 	 */
480 	if (intr_id != ISR_DATA_TRANSFER_RDY && intr_id != ISR_ATTN_ERROR)
481 		edc_do_attn(sc, ATN_END_INT, devno, intr_id);
482 
483 	/* If Read or Write Data, wakeup worker thread to finish it */
484 	if (intr_id != ISR_DATA_TRANSFER_RDY) {
485 	    	if (cmd == CMD_READ_DATA || cmd == CMD_WRITE_DATA)
486 			sc->sc_resblk = sc->status_block[SB_RESBLKCNT_IDX];
487 		wakeup(sc);
488 	}
489 
490 	return (1);
491 }
492 
493 /*
494  * This follows the exact order for Attention Request as
495  * written in DASD Storage Interface Specification MC (Rev 2.2).
496  */
497 static int
498 edc_do_attn(struct edc_mca_softc *sc, int attn_type, int devno, int intr_id)
499 {
500 	int tries;
501 
502 	/* 1. Disable interrupts in BCR. */
503 	bus_space_write_1(sc->sc_iot, sc->sc_ioh, BCR, 0);
504 
505 	/*
506 	 * 2. Assure NOT BUSY and NO INTERRUPT PENDING, unless acknowledging
507 	 *    a RESET COMPLETED interrupt.
508 	 */
509 	if (intr_id != ISR_RESET_COMPLETED) {
510 #ifdef EDC_DEBUG
511 		if (attn_type == ATN_CMD_REQ
512 		    && (bus_space_read_1(sc->sc_iot, sc->sc_ioh, BSR)
513 			    & BSR_INT_PENDING))
514 			panic("%s: edc int pending", device_xname(sc->sc_dev));
515 #endif
516 
517 		for(tries=1; tries < EDC_ATTN_MAXTRIES; tries++) {
518 			if ((bus_space_read_1(sc->sc_iot, sc->sc_ioh, BSR)
519 			     & BSR_BUSY) == 0)
520 				break;
521 		}
522 
523 		if (tries == EDC_ATTN_MAXTRIES) {
524 			printf("%s: edc_do_attn: timeout waiting for "
525 			    "attachment to become available\n",
526 			    device_xname(sc->sc_ed[devno]->sc_dev));
527 			return (EIO);
528 		}
529 	}
530 
531 	/*
532 	 * 3. Write proper DEVICE NUMBER and Attention number to ATN.
533 	 */
534 	bus_space_write_1(sc->sc_iot, sc->sc_ioh, ATN, attn_type | (devno<<5));
535 
536 	/*
537 	 * 4. Enable interrupts via BCR.
538 	 */
539 	bus_space_write_1(sc->sc_iot, sc->sc_ioh, BCR, BCR_INT_ENABLE);
540 
541 	return (0);
542 }
543 
544 /*
545  * Wait until command is processed, timeout after 'secs' seconds.
546  * We use mono_time, since we don't need actual RTC, just time
547  * interval.
548  */
549 static void
550 edc_cmd_wait(struct edc_mca_softc *sc, int secs, int poll)
551 {
552 	int val;
553 
554 	if (!poll) {
555 		int s;
556 
557 		/* Not polling, can sleep. Sleep until we are awakened,
558 		 * but maximum secs seconds.
559 		 */
560 		s = splbio();
561 		if (sc->sc_stat != STAT_DONE)
562 			(void) tsleep(sc, PRIBIO, "edcwcmd", secs * hz);
563 		splx(s);
564 	}
565 
566 	/* Wait until the command is completely finished */
567 	while((val = bus_space_read_1(sc->sc_iot, sc->sc_ioh, BSR))
568 	    & BSR_CMD_INPROGRESS) {
569 		if (poll && (val & BSR_INTR))
570 			edc_intr(sc);
571 	}
572 }
573 
574 /*
575  * Command controller to execute specified command on a device.
576  */
577 int
578 edc_run_cmd(struct edc_mca_softc *sc, int cmd, int devno,
579     u_int16_t cmd_args[], int cmd_len, int poll)
580 {
581 	int i, error, tries;
582 	u_int16_t cmd0;
583 
584 	sc->sc_stat = STAT_START;
585 
586 	/* Do Attention Request for Command Request. */
587 	if ((error = edc_do_attn(sc, ATN_CMD_REQ, devno, 0)))
588 		return (error);
589 
590 	/*
591 	 * Construct the command. The bits are like this:
592 	 *
593 	 * 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
594 	 *  \_/   0  0       1 0 \__/   \_____/
595 	 *    \    \__________/     \         \_ Command Code (see CMD_*)
596 	 *     \              \      \__ Device: 0 common, 7 controller
597 	 *      \              \__ Options: reserved, bit 10=cache bypass bit
598 	 *       \_ Type: 00=2B, 01=4B, 10 and 11 reserved
599 	 *
600 	 * We always use device 0 or 1, so difference is made only by Command
601 	 * Code, Command Options and command length.
602 	 */
603 	cmd0 = ((cmd_len == 4) ? (CIFR_LONG_CMD) : 0)
604 		| (devno <<  5)
605 		| (cmd_args[0] << 8) | cmd;
606 	cmd_args[0] = cmd0;
607 
608 	/*
609 	 * Write word of CMD to the CIFR. This sets "Command
610 	 * Interface Register Full (CMD IN)" in BSR. Once the attachment
611 	 * detects it, it reads the word and clears CMD IN. This all should
612 	 * be quite fast, so don't sleep in !poll case neither.
613 	 */
614 	for(i=0; i < cmd_len; i++) {
615 		bus_space_write_2(sc->sc_iot, sc->sc_ioh, CIFR,
616 			htole16(cmd_args[i]));
617 
618 		/* Wait until CMD IN is cleared. */
619 		tries = 0;
620 		for(; (bus_space_read_1(sc->sc_iot, sc->sc_ioh, BSR)
621 		    & BSR_CIFR_FULL) && tries < 10000 ; tries++)
622 			delay(poll ? 1000 : 1);
623 			;
624 
625 		if (tries == 10000
626 		    && bus_space_read_1(sc->sc_iot, sc->sc_ioh, BSR)
627 		       & BSR_CIFR_FULL) {
628 			aprint_error_dev(sc->sc_dev,
629 			    "device too slow to accept command %d\n", cmd);
630 			return (EIO);
631 		}
632 	}
633 
634 	/* Wait for command to complete, but maximum 15 seconds. */
635 	edc_cmd_wait(sc, 15, poll);
636 
637 	return ((sc->sc_stat != STAT_DONE) ? EIO : 0);
638 }
639 
640 #ifdef EDC_DEBUG
641 static const char * const edc_commands[] = {
642 	"Invalid Command",
643 	"Read Data",
644 	"Write Data",
645 	"Read Verify",
646 	"Write with Verify",
647 	"Seek",
648 	"Park Head",
649 	"Get Command Complete Status",
650 	"Get Device Status",
651 	"Get Device Configuration",
652 	"Get POS Information",
653 	"Translate RBA",
654 	"Write Attachment Buffer",
655 	"Read Attachment Buffer",
656 	"Run Diagnostic Test",
657 	"Get Diagnostic Status Block",
658 	"Get MFG Header",
659 	"Format Unit",
660 	"Format Prepare",
661 	"Set MAX RBA",
662 	"Set Power Saving Mode",
663 	"Power Conservation Command",
664 };
665 
666 static const char * const edc_cmd_status[256] = {
667 	"Reserved",
668 	"Command completed successfully",
669 	"Reserved",
670 	"Command completed successfully with ECC applied",
671 	"Reserved",
672 	"Command completed successfully with retries",
673 	"Format Command partially completed",	/* Status available */
674 	"Command completed successfully with ECC and retries",
675 	"Command completed with Warning", 	/* Command Error is available */
676 	"Aborted",
677 	"Reset completed",
678 	"Data Transfer Ready",		/* No Status Block available */
679 	"Command terminated with failure",	/* Device Error is available */
680 	"DMA Error",			/* Retry entire command as recovery */
681 	"Command Block Error",
682 	"Attention Error (Illegal Attention Code)",
683 	/* 0x14 - 0xff reserved */
684 };
685 
686 static const char * const edc_cmd_error[256] = {
687 	"No Error",
688 	"Invalid parameter in the command block",
689 	"Reserved",
690 	"Command not supported",
691 	"Command Aborted per request",
692 	"Reserved",
693 	"Command rejected",	/* Attachment diagnostic failure */
694 	"Format Rejected",	/* Prepare Format command is required */
695 	"Format Error (Primary Map is not readable)",
696 	"Format Error (Secondary map is not readable)",
697 	"Format Error (Diagnostic Failure)",
698 	"Format Warning (Secondary Map Overflow)",
699 	"Reserved"
700 	"Format Error (Host Checksum Error)",
701 	"Reserved",
702 	"Format Warning (Push table overflow)",
703 	"Format Warning (More pushes than allowed)",
704 	"Reserved",
705 	"Format Warning (Error during verifying)",
706 	"Invalid device number for the command",
707 	/* 0x14-0xff reserved */
708 };
709 
710 static const char * const edc_dev_errors[] = {
711 	"No Error",
712 	"Seek Fault",	/* Device report */
713 	"Interface Fault (Parity, Attn, or Cmd Complete Error)",
714 	"Block not found (ID not found)",
715 	"Block not found (AM not found)",
716 	"Data ECC Error (hard error)",
717 	"ID CRC Error",
718 	"RBA Out of Range",
719 	"Reserved",
720 	"Defective Block",
721 	"Reserved",
722 	"Selection Error",
723 	"Reserved",
724 	"Write Fault",
725 	"No index or sector pulse",
726 	"Device Not Ready",
727 	"Seek Error",	/* Attachment report */
728 	"Bad Format",
729 	"Volume Overflow",
730 	"No Data AM Found",
731 	"Block not found (No ID AM or ID CRC error occurred)",
732 	"Reserved",
733 	"Reserved",
734 	"No ID found on track (ID search)",
735 	/* 0x19 - 0xff reserved */
736 };
737 #endif /* EDC_DEBUG */
738 
739 static void
740 edc_dump_status_block(struct edc_mca_softc *sc, u_int16_t *status_block,
741     int intr_id)
742 {
743 #ifdef EDC_DEBUG
744 	printf("%s: Command: %s, Status: %s (intr %d)\n",
745 		device_xname(sc->sc_dev),
746 		edc_commands[status_block[0] & 0x1f],
747 		edc_cmd_status[SB_GET_CMD_STATUS(status_block)],
748 		intr_id
749 		);
750 #else
751 	printf("%s: Command: %d, Status: %d (intr %d)\n",
752 		device_xname(sc->sc_dev),
753 		status_block[0] & 0x1f,
754 		SB_GET_CMD_STATUS(status_block),
755 		intr_id
756 		);
757 #endif
758 	printf("%s: # left blocks: %u, last processed RBA: %u\n",
759 		device_xname(sc->sc_dev),
760 		status_block[SB_RESBLKCNT_IDX],
761 		(status_block[5] << 16) | status_block[4]);
762 
763 	if (intr_id == ISR_COMPLETED_WARNING) {
764 #ifdef EDC_DEBUG
765 		aprint_error_dev(sc->sc_dev, "Command Error Code: %s\n",
766 			edc_cmd_error[status_block[1] & 0xff]);
767 #else
768 		aprint_error_dev(sc->sc_dev, "Command Error Code: %d\n",
769 			status_block[1] & 0xff);
770 #endif
771 	}
772 
773 	if (intr_id == ISR_CMD_FAILED) {
774 #ifdef EDC_DEBUG
775 		char buf[100];
776 
777 		printf("%s: Device Error Code: %s\n",
778 			device_xname(sc->sc_dev),
779 			edc_dev_errors[status_block[2] & 0xff]);
780 		snprintb(buf, sizeof(buf),
781 			"\20"
782 			"\01SeekOrCmdComplete"
783 			"\02Track0Flag"
784 			"\03WriteFault"
785 			"\04Selected"
786 			"\05Ready"
787 			"\06Reserved0"
788 			"\07STANDBY"
789 			"\010Reserved0", (status_block[2] & 0xff00) >> 8);
790 
791 		printf("%s: Device Status: %s\n",
792 			device_xname(sc->sc_dev), buf);
793 #else
794 		printf("%s: Device Error Code: %d, Device Status: %d\n",
795 			device_xname(sc->sc_dev),
796 			status_block[2] & 0xff,
797 			(status_block[2] & 0xff00) >> 8);
798 #endif
799 	}
800 }
801 /*
802  * Main worker thread function.
803  */
804 void
805 edcworker(void *arg)
806 {
807 	struct edc_mca_softc *sc = (struct edc_mca_softc *) arg;
808 	struct ed_softc *ed;
809 	struct buf *bp;
810 	int i, error;
811 
812 	config_pending_decr(sc->sc_dev);
813 
814 	for(;;) {
815 		/* Wait until awakened */
816 		(void) tsleep(sc, PRIBIO, "edcidle", 0);
817 
818 		for(i=0; i<sc->sc_maxdevs; ) {
819 			if ((ed = sc->sc_ed[i]) == NULL) {
820 				i++;
821 				continue;
822 			}
823 
824 			/* Is there a buf for us ? */
825 			mutex_enter(&ed->sc_q_lock);
826 			if ((bp = bufq_get(ed->sc_q)) == NULL) {
827 				mutex_exit(&ed->sc_q_lock);
828 				i++;
829 				continue;
830 			}
831 			mutex_exit(&ed->sc_q_lock);
832 
833 			/* Instrumentation. */
834 			disk_busy(&ed->sc_dk);
835 
836 			error = edc_bio(sc, ed, bp->b_data, bp->b_bcount,
837 				bp->b_rawblkno, (bp->b_flags & B_READ), 0);
838 
839 			if (error) {
840 				bp->b_error = error;
841 			} else {
842 				/* Set resid, most commonly to zero. */
843 				bp->b_resid = sc->sc_resblk * DEV_BSIZE;
844 			}
845 
846 			disk_unbusy(&ed->sc_dk, (bp->b_bcount - bp->b_resid),
847 			    (bp->b_flags & B_READ));
848 			rnd_add_uint32(&ed->rnd_source, bp->b_blkno);
849 			biodone(bp);
850 		}
851 	}
852 }
853 
854 int
855 edc_bio(struct edc_mca_softc *sc, struct ed_softc *ed, void *data,
856 	size_t bcount, daddr_t rawblkno, int isread, int poll)
857 {
858 	u_int16_t cmd_args[4];
859 	int error=0, fl;
860 	u_int16_t track;
861 	u_int16_t cyl;
862 	u_int8_t head;
863 	u_int8_t sector;
864 
865 	mca_disk_busy();
866 
867 	/* set WAIT and R/W flag appropriately for the DMA transfer */
868 	fl = ((poll) ? BUS_DMA_NOWAIT : BUS_DMA_WAITOK)
869 		| ((isread) ? BUS_DMA_READ : BUS_DMA_WRITE);
870 
871 	/* Load the buffer for DMA transfer. */
872 	if ((error = bus_dmamap_load(sc->sc_dmat, sc->sc_dmamap_xfer, data,
873 	    bcount, NULL, BUS_DMA_STREAMING|fl))) {
874 		printf("%s: ed_bio: unable to load DMA buffer - error %d\n",
875 			device_xname(ed->sc_dev), error);
876 		goto out;
877 	}
878 
879 	bus_dmamap_sync(sc->sc_dmat, sc->sc_dmamap_xfer, 0,
880 		bcount, (isread) ? BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE);
881 
882 	track = rawblkno / ed->sectors;
883 	head = track % ed->heads;
884 	cyl = track / ed->heads;
885 	sector = rawblkno % ed->sectors;
886 
887 	/* Read or Write Data command */
888 	cmd_args[0] = 2;	/* Options 0000010 */
889 	cmd_args[1] = bcount / DEV_BSIZE;
890 	cmd_args[2] = ((cyl & 0x1f) << 11) | (head << 5) | sector;
891 	cmd_args[3] = ((cyl & 0x3E0) >> 5);
892 	error = edc_run_cmd(sc,
893 			(isread) ? CMD_READ_DATA : CMD_WRITE_DATA,
894 			ed->sc_devno, cmd_args, 4, poll);
895 
896 	/* Sync the DMA memory */
897 	if (!error)  {
898 		bus_dmamap_sync(sc->sc_dmat, sc->sc_dmamap_xfer, 0, bcount,
899 			(isread)? BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
900 	}
901 
902 	/* We are done, unload buffer from DMA map */
903 	bus_dmamap_unload(sc->sc_dmat, sc->sc_dmamap_xfer);
904 
905     out:
906 	mca_disk_unbusy();
907 
908 	return (error);
909 }
910