xref: /openbsd/sys/arch/macppc/dev/adb.c (revision cecf84d4)
1 /*	$OpenBSD: adb.c,v 1.39 2013/08/10 08:13:32 mpi Exp $	*/
2 /*	$NetBSD: adb.c,v 1.6 1999/08/16 06:28:09 tsubai Exp $	*/
3 /*	$NetBSD: adb_direct.c,v 1.14 2000/06/08 22:10:45 tsubai Exp $	*/
4 
5 /*
6  * Copyright (C) 1996, 1997 John P. Wittkoski
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *  This product includes software developed by John P. Wittkoski.
20  * 4. The name of the author may not be used to endorse or promote products
21  *    derived from this software without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 /*-
36  * Copyright (C) 1994	Bradley A. Grantham
37  * All rights reserved.
38  *
39  * Redistribution and use in source and binary forms, with or without
40  * modification, are permitted provided that the following conditions
41  * are met:
42  * 1. Redistributions of source code must retain the above copyright
43  *    notice, this list of conditions and the following disclaimer.
44  * 2. Redistributions in binary form must reproduce the above copyright
45  *    notice, this list of conditions and the following disclaimer in the
46  *    documentation and/or other materials provided with the distribution.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
49  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
50  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
51  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
52  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
53  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
54  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
55  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
56  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
57  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
58  */
59 
60 /*
61  * This code is rather messy, but I don't have time right now
62  * to clean it up as much as I would like.
63  * But it works, so I'm happy. :-) jpw
64  */
65 
66 /*
67  * TO DO:
68  *  - We could reduce the time spent in the adb_intr_* routines
69  *    by having them save the incoming and outgoing data directly
70  *    in the adbInbound and adbOutbound queues, as it would reduce
71  *    the number of times we need to copy the data around. It
72  *    would also make the code more readable and easier to follow.
73  *  - (Related to above) Use the header part of adbCommand to
74  *    reduce the number of copies we have to do of the data.
75  *  - (Related to above) Actually implement the adbOutbound queue.
76  *    This is fairly easy once you switch all the intr routines
77  *    over to using adbCommand structs directly.
78  *  - There is a bug in the state machine of adb_intr_cuda
79  *    code that causes hangs, especially on 030 machines, probably
80  *    because of some timing issues. Because I have been unable to
81  *    determine the exact cause of this bug, I used the timeout function
82  *    to check for and recover from this condition. If anyone finds
83  *    the actual cause of this bug, the calls to timeout and the
84  *    adb_cuda_tickle routine can be removed.
85  */
86 
87 #include <sys/param.h>
88 #include <sys/device.h>
89 #include <sys/fcntl.h>
90 #include <sys/poll.h>
91 #include <sys/selinfo.h>
92 #include <sys/proc.h>
93 #include <sys/signalvar.h>
94 #include <sys/timeout.h>
95 #include <sys/systm.h>
96 
97 #include <machine/autoconf.h>
98 #include <machine/cpu.h>
99 #include <dev/ofw/openfirm.h>
100 
101 #include <dev/adb/adb.h>
102 #include <macppc/dev/adbvar.h>
103 #include <macppc/dev/pm_direct.h>
104 #include <macppc/dev/viareg.h>
105 
106 #include "apm.h"
107 
108 #define printf_intr printf
109 
110 #ifdef DEBUG
111 #ifndef ADB_DEBUG
112 #define ADB_DEBUG
113 #endif
114 #endif
115 
116 int	adb_polling;		/* Are we polling?  (Debugger mode) */
117 #ifdef ADB_DEBUG
118 int	adb_debug;		/* Output debugging messages */
119 #endif /* ADB_DEBUG */
120 
121 /* some misc. leftovers */
122 #define vPB		0x0000
123 #define vPB3		0x08
124 #define vPB4		0x10
125 #define vPB5		0x20
126 #define vSR_INT		0x04
127 #define vSR_OUT		0x10
128 
129 /* the type of ADB action that we are currently performing */
130 #define ADB_ACTION_NOTREADY	0x1	/* has not been initialized yet */
131 #define ADB_ACTION_IDLE		0x2	/* the bus is currently idle */
132 #define ADB_ACTION_OUT		0x3	/* sending out a command */
133 #define ADB_ACTION_IN		0x4	/* receiving data */
134 
135 /*
136  * Shortcuts for setting or testing the VIA bit states.
137  * Not all shortcuts are used for every type of ADB hardware.
138  */
139 #define ADB_SET_STATE_IDLE_CUDA()   via_reg_or(VIA1, vBufB, (vPB4 | vPB5))
140 #define ADB_SET_STATE_TIP()	    via_reg_and(VIA1, vBufB, ~vPB5)
141 #define ADB_CLR_STATE_TIP() 	    via_reg_or(VIA1, vBufB, vPB5)
142 #define ADB_TOGGLE_STATE_ACK_CUDA() via_reg_xor(VIA1, vBufB, vPB4)
143 #define ADB_SET_STATE_ACKOFF_CUDA() via_reg_or(VIA1, vBufB, vPB4)
144 #define ADB_SET_SR_INPUT()	    via_reg_and(VIA1, vACR, ~vSR_OUT)
145 #define ADB_SET_SR_OUTPUT()	    via_reg_or(VIA1, vACR, vSR_OUT)
146 #define ADB_SR()		    read_via_reg(VIA1, vSR)
147 #define ADB_VIA_INTR_ENABLE()	    write_via_reg(VIA1, vIER, 0x84)
148 #define ADB_VIA_INTR_DISABLE()	    write_via_reg(VIA1, vIER, 0x04)
149 #define ADB_VIA_CLR_INTR()	    write_via_reg(VIA1, vIFR, 0x04)
150 #define ADB_INTR_IS_OFF		   (vPB3 == (read_via_reg(VIA1, vBufB) & vPB3))
151 #define ADB_INTR_IS_ON		   (0 == (read_via_reg(VIA1, vBufB) & vPB3))
152 #define ADB_SR_INTR_IS_ON	   (vSR_INT == (read_via_reg(VIA1, \
153 						vIFR) & vSR_INT))
154 
155 /*
156  * This is the delay that is required (in uS) between certain
157  * ADB transactions. The actual timing delay for for each uS is
158  * calculated at boot time to account for differences in machine speed.
159  */
160 #define ADB_DELAY	150
161 
162 /*
163  * Maximum ADB message length; includes space for data, result, and
164  * device code - plus a little for safety.
165  */
166 #define ADB_MAX_MSG_LENGTH	16
167 #define ADB_MAX_HDR_LENGTH	8
168 
169 #define ADB_QUEUE		32
170 #define ADB_TICKLE_TICKS	4
171 
172 /*
173  * Eventually used for two separate queues, the queue between
174  * the upper and lower halves, and the outgoing packet queue.
175  */
176 struct adbCommand {
177 	u_char	header[ADB_MAX_HDR_LENGTH];	/* not used yet */
178 	u_char	data[ADB_MAX_MSG_LENGTH];	/* packet data only */
179 	u_char	*saveBuf;	/* where to save result */
180 	u_char	*compRout;	/* completion routine pointer */
181 	u_char	*compData;	/* completion routine data pointer */
182 	u_int	cmd;		/* the original command for this data */
183 	u_int	unsol;		/* 1 if packet was unsolicited */
184 	u_int	ack_only;	/* 1 for no special processing */
185 };
186 
187 /*
188  * A few variables that we need and their initial values.
189  */
190 int	adbHardware = ADB_HW_UNKNOWN;
191 int	adbActionState = ADB_ACTION_NOTREADY;
192 int	adbWaiting;		/* waiting for return data from the device */
193 int	adbWriteDelay;		/* working on (or waiting to do) a write */
194 
195 int	adbWaitingCmd;		/* ADB command we are waiting for */
196 u_char	*adbBuffer;		/* pointer to user data area */
197 void	*adbCompRout;		/* pointer to the completion routine */
198 void	*adbCompData;		/* pointer to the completion routine data */
199 int	adbStarting = 1;	/* doing adb_reinit so do polling differently */
200 
201 u_char	adbInputBuffer[ADB_MAX_MSG_LENGTH];	/* data input buffer */
202 u_char	adbOutputBuffer[ADB_MAX_MSG_LENGTH];	/* data output buffer */
203 
204 int	adbSentChars;		/* how many characters we have sent */
205 
206 struct	adbCommand adbInbound[ADB_QUEUE];	/* incoming queue */
207 int	adbInCount;			/* how many packets in in queue */
208 int	adbInHead;			/* head of in queue */
209 int	adbInTail;			/* tail of in queue */
210 
211 int	tickle_count;			/* how many tickles seen for this packet? */
212 int	tickle_serial;			/* the last packet tickled */
213 int	adb_cuda_serial;		/* the current packet */
214 struct	timeout adb_cuda_timeout;
215 struct	timeout adb_softintr_timeout;
216 int	adbempty;			/* nonzero if no adb devices */
217 
218 extern struct cfdriver adb_cd;
219 
220 volatile u_char *Via1Base;
221 
222 /*
223  * The following are private routines.
224  */
225 #ifdef ADB_DEBUG
226 void	print_single(u_char *);
227 #endif
228 void	adb_intr_cuda(void);
229 void	adb_soft_intr(void);
230 int	send_adb_cuda(u_char *, u_char *, void *, void *, int);
231 void	adb_cuda_tickle(void);
232 void	adb_pass_up(struct adbCommand *);
233 void	adb_op_comprout(caddr_t, caddr_t, int);
234 void	adb_reinit(struct adb_softc *);
235 int	count_adbs(struct adb_softc *);
236 int	get_ind_adb_info(struct adb_softc *, ADBDataBlock *, int);
237 int	get_adb_info(ADBDataBlock *, int);
238 int	adb_op(Ptr, Ptr, Ptr, short);
239 void	adb_hw_setup(void);
240 int	adb_cmd_result(u_char *);
241 void	setsoftadb(void);
242 
243 int	adb_intr(void *arg);
244 void	adb_cuda_autopoll(void);
245 void 	adb_cuda_fileserver_mode(void);
246 
247 #ifdef ADB_DEBUG
248 /*
249  * print_single
250  * Diagnostic display routine. Displays the hex values of the
251  * specified elements of the u_char. The length of the "string"
252  * is in [0].
253  */
254 void
255 print_single(str)
256 	u_char *str;
257 {
258 	int x;
259 
260 	if (str == NULL) {
261 		printf_intr("no data - null pointer\n");
262 		return;
263 	}
264 	if (*str == '\0') {
265 		printf_intr("nothing returned\n");
266 		return;
267 	}
268 	if (*str > 20) {
269 		printf_intr("ADB: ACK > 20 no way!\n");
270 		*str = 20;
271 	}
272 	printf_intr("(length=0x%x):", *str);
273 	for (x = 1; x <= *str; x++)
274 		printf_intr("  0x%02x", str[x]);
275 	printf_intr("\n");
276 }
277 #endif
278 
279 void
280 adb_cuda_tickle(void)
281 {
282 	volatile int s;
283 
284 	if (adbActionState == ADB_ACTION_IN) {
285 		if (tickle_serial == adb_cuda_serial) {
286 			if (++tickle_count > 0) {
287 				s = splhigh();
288 				adbActionState = ADB_ACTION_IDLE;
289 				adbInputBuffer[0] = 0;
290 				ADB_SET_STATE_IDLE_CUDA();
291 				splx(s);
292 			}
293 		} else {
294 			tickle_serial = adb_cuda_serial;
295 			tickle_count = 0;
296 		}
297 	} else {
298 		tickle_serial = adb_cuda_serial;
299 		tickle_count = 0;
300 	}
301 
302 	timeout_add(&adb_cuda_timeout, ADB_TICKLE_TICKS);
303 }
304 
305 /*
306  * called when when an adb interrupt happens
307  *
308  * Cuda version of adb_intr
309  * TO DO: do we want to add some calls to intr_dispatch() here to
310  * grab serial interrupts?
311  */
312 void
313 adb_intr_cuda(void)
314 {
315 	volatile int i, ending;
316 	volatile unsigned int s;
317 	struct adbCommand packet;
318 
319 	s = splhigh();		/* can't be too careful - might be called */
320 				/* from a routine, NOT an interrupt */
321 
322 	ADB_VIA_CLR_INTR();	/* clear interrupt */
323 	ADB_VIA_INTR_DISABLE();	/* disable ADB interrupt on IIs. */
324 
325 switch_start:
326 	switch (adbActionState) {
327 	case ADB_ACTION_IDLE:
328 		/*
329 		 * This is an unexpected packet, so grab the first (dummy)
330 		 * byte, set up the proper vars, and tell the chip we are
331 		 * starting to receive the packet by setting the TIP bit.
332 		 */
333 		adbInputBuffer[1] = ADB_SR();
334 		adb_cuda_serial++;
335 		if (ADB_INTR_IS_OFF)	/* must have been a fake start */
336 			break;
337 
338 		ADB_SET_SR_INPUT();
339 		ADB_SET_STATE_TIP();
340 
341 		adbInputBuffer[0] = 1;
342 		adbActionState = ADB_ACTION_IN;
343 #ifdef ADB_DEBUG
344 		if (adb_debug)
345 			printf_intr("idle 0x%02x ", adbInputBuffer[1]);
346 #endif
347 		break;
348 
349 	case ADB_ACTION_IN:
350 		adbInputBuffer[++adbInputBuffer[0]] = ADB_SR();
351 		/* intr off means this is the last byte (end of frame) */
352 		if (ADB_INTR_IS_OFF)
353 			ending = 1;
354 		else
355 			ending = 0;
356 
357 		if (1 == ending) {	/* end of message? */
358 #ifdef ADB_DEBUG
359 			if (adb_debug) {
360 				printf_intr("in end 0x%02x ",
361 				    adbInputBuffer[adbInputBuffer[0]]);
362 				print_single(adbInputBuffer);
363 			}
364 #endif
365 
366 			/*
367 			 * Are we waiting AND does this packet match what we
368 			 * are waiting for AND is it coming from either the
369 			 * ADB or RTC/PRAM sub-device? This section _should_
370 			 * recognize all ADB and RTC/PRAM type commands, but
371 			 * there may be more... NOTE: commands are always at
372 			 * [4], even for RTC/PRAM commands.
373 			 */
374 			/* set up data for adb_pass_up */
375 			memcpy(packet.data, adbInputBuffer, adbInputBuffer[0] + 1);
376 
377 			if ((adbWaiting == 1) &&
378 			    (adbInputBuffer[4] == adbWaitingCmd) &&
379 			    ((adbInputBuffer[2] == 0x00) ||
380 			    (adbInputBuffer[2] == 0x01))) {
381 				packet.saveBuf = adbBuffer;
382 				packet.compRout = adbCompRout;
383 				packet.compData = adbCompData;
384 				packet.unsol = 0;
385 				packet.ack_only = 0;
386 				adb_pass_up(&packet);
387 
388 				adbWaitingCmd = 0;	/* reset "waiting" vars */
389 				adbWaiting = 0;
390 				adbBuffer = NULL;
391 				adbCompRout = NULL;
392 				adbCompData = NULL;
393 			} else {
394 				packet.unsol = 1;
395 				packet.ack_only = 0;
396 				adb_pass_up(&packet);
397 			}
398 
399 
400 			/* reset vars and signal the end of this frame */
401 			adbActionState = ADB_ACTION_IDLE;
402 			adbInputBuffer[0] = 0;
403 			ADB_SET_STATE_IDLE_CUDA();
404 			/*ADB_SET_SR_INPUT();*/
405 
406 			/*
407 			 * If there is something waiting to be sent out,
408 			 * the set everything up and send the first byte.
409 			 */
410 			if (adbWriteDelay == 1) {
411 				delay(ADB_DELAY);	/* required */
412 				adbSentChars = 0;
413 				adbActionState = ADB_ACTION_OUT;
414 				/*
415 				 * If the interrupt is on, we were too slow
416 				 * and the chip has already started to send
417 				 * something to us, so back out of the write
418 				 * and start a read cycle.
419 				 */
420 				if (ADB_INTR_IS_ON) {
421 					ADB_SET_SR_INPUT();
422 					ADB_SET_STATE_IDLE_CUDA();
423 					adbSentChars = 0;
424 					adbActionState = ADB_ACTION_IDLE;
425 					adbInputBuffer[0] = 0;
426 					break;
427 				}
428 				/*
429 				 * If we got here, it's ok to start sending
430 				 * so load the first byte and tell the chip
431 				 * we want to send.
432 				 */
433 				ADB_SET_STATE_TIP();
434 				ADB_SET_SR_OUTPUT();
435 				write_via_reg(VIA1, vSR, adbOutputBuffer[adbSentChars + 1]);
436 			}
437 		} else {
438 			ADB_TOGGLE_STATE_ACK_CUDA();
439 #ifdef ADB_DEBUG
440 			if (adb_debug)
441 				printf_intr("in 0x%02x ",
442 				    adbInputBuffer[adbInputBuffer[0]]);
443 #endif
444 		}
445 		break;
446 
447 	case ADB_ACTION_OUT:
448 		i = ADB_SR();	/* reset SR-intr in IFR */
449 #ifdef ADB_DEBUG
450 		if (adb_debug)
451 			printf_intr("intr out 0x%02x ", i);
452 #endif
453 
454 		adbSentChars++;
455 		if (ADB_INTR_IS_ON) {	/* ADB intr low during write */
456 #ifdef ADB_DEBUG
457 			if (adb_debug)
458 				printf_intr("intr was on ");
459 #endif
460 			ADB_SET_SR_INPUT();	/* make sure SR is set to IN */
461 			ADB_SET_STATE_IDLE_CUDA();
462 			adbSentChars = 0;	/* must start all over */
463 			adbActionState = ADB_ACTION_IDLE;	/* new state */
464 			adbInputBuffer[0] = 0;
465 			adbWriteDelay = 1;	/* must retry when done with
466 						 * read */
467 			delay(ADB_DELAY);
468 			goto switch_start;	/* process next state right
469 						 * now */
470 			break;
471 		}
472 		if (adbOutputBuffer[0] == adbSentChars) {	/* check for done */
473 			if (0 == adb_cmd_result(adbOutputBuffer)) {	/* do we expect data
474 									 * back? */
475 				adbWaiting = 1;	/* signal waiting for return */
476 				adbWaitingCmd = adbOutputBuffer[2];	/* save waiting command */
477 			} else {	/* no talk, so done */
478 				/* set up stuff for adb_pass_up */
479 				memcpy(packet.data, adbInputBuffer, adbInputBuffer[0] + 1);
480 				packet.saveBuf = adbBuffer;
481 				packet.compRout = adbCompRout;
482 				packet.compData = adbCompData;
483 				packet.cmd = adbWaitingCmd;
484 				packet.unsol = 0;
485 				packet.ack_only = 1;
486 				adb_pass_up(&packet);
487 
488 				/* reset "waiting" vars, just in case */
489 				adbWaitingCmd = 0;
490 				adbBuffer = NULL;
491 				adbCompRout = NULL;
492 				adbCompData = NULL;
493 			}
494 
495 			adbWriteDelay = 0;	/* done writing */
496 			adbActionState = ADB_ACTION_IDLE;	/* signal bus is idle */
497 			ADB_SET_SR_INPUT();
498 			ADB_SET_STATE_IDLE_CUDA();
499 #ifdef ADB_DEBUG
500 			if (adb_debug)
501 				printf_intr("write done ");
502 #endif
503 		} else {
504 			write_via_reg(VIA1, vSR, adbOutputBuffer[adbSentChars + 1]);	/* send next byte */
505 			ADB_TOGGLE_STATE_ACK_CUDA();	/* signal byte ready to
506 							 * shift */
507 #ifdef ADB_DEBUG
508 			if (adb_debug)
509 				printf_intr("toggle ");
510 #endif
511 		}
512 		break;
513 
514 	case ADB_ACTION_NOTREADY:
515 #ifdef ADB_DEBUG
516 		if (adb_debug)
517 			printf_intr("adb: not yet initialized\n");
518 #endif
519 		break;
520 
521 	default:
522 		;
523 #ifdef ADB_DEBUG
524 		if (adb_debug)
525 			printf_intr("intr: unknown ADB state\n");
526 #endif
527 	}
528 
529 	ADB_VIA_INTR_ENABLE();	/* enable ADB interrupt on IIs. */
530 
531 	splx(s);		/* restore */
532 }
533 
534 
535 int
536 send_adb_cuda(u_char * in, u_char * buffer, void *compRout, void *data, int
537 	command)
538 {
539 	int s, len;
540 
541 #ifdef ADB_DEBUG
542 	if (adb_debug)
543 		printf_intr("SEND\n");
544 #endif
545 
546 	if (adbActionState == ADB_ACTION_NOTREADY)
547 		return 1;
548 
549 	/* Don't interrupt while we are messing with the ADB */
550 	s = splhigh();
551 
552 	if ((adbActionState == ADB_ACTION_IDLE) &&	/* ADB available? */
553 	    (ADB_INTR_IS_OFF)) {	/* and no incoming interrupt? */
554 	} else
555 		if (adbWriteDelay == 0)	/* it's busy, but is anything waiting? */
556 			adbWriteDelay = 1;	/* if no, then we'll "queue"
557 						 * it up */
558 		else {
559 			splx(s);
560 			return 1;	/* really busy! */
561 		}
562 
563 #ifdef ADB_DEBUG
564 	if (adb_debug)
565 		printf_intr("QUEUE\n");
566 #endif
567 	if ((long)in == (long)0) {	/* need to convert? */
568 		if ((command & 0x0c) == 0x08)	/* copy addl data ONLY if
569 						 * doing a listen! */
570 			len = buffer[0];	/* length of additional data */
571 		else
572 			len = 0;/* no additional data */
573 
574 		adbOutputBuffer[0] = 2 + len;	/* dev. type + command + addl.
575 						 * data */
576 		adbOutputBuffer[1] = 0x00;	/* mark as an ADB command */
577 		adbOutputBuffer[2] = (u_char)command;	/* load command */
578 
579 		/* copy additional output data, if any */
580 		memcpy(adbOutputBuffer + 3, buffer + 1, len);
581 	} else
582 		/* if data ready, just copy over */
583 		memcpy(adbOutputBuffer, in, in[0] + 2);
584 
585 	adbSentChars = 0;	/* nothing sent yet */
586 	adbBuffer = buffer;	/* save buffer to know where to save result */
587 	adbCompRout = compRout;	/* save completion routine pointer */
588 	adbCompData = data;	/* save completion routine data pointer */
589 	adbWaitingCmd = adbOutputBuffer[2];	/* save wait command */
590 
591 	if (adbWriteDelay != 1) {	/* start command now? */
592 #ifdef ADB_DEBUG
593 		if (adb_debug)
594 			printf_intr("out start NOW");
595 #endif
596 		delay(ADB_DELAY);
597 		adbActionState = ADB_ACTION_OUT;	/* set next state */
598 		ADB_SET_SR_OUTPUT();	/* set shift register for OUT */
599 		write_via_reg(VIA1, vSR, adbOutputBuffer[adbSentChars + 1]);	/* load byte for output */
600 		ADB_SET_STATE_ACKOFF_CUDA();
601 		ADB_SET_STATE_TIP();	/* tell ADB that we want to send */
602 	}
603 	adbWriteDelay = 1;	/* something in the write "queue" */
604 
605 	splx(s);
606 
607 	if ((s & (1 << 18)) || adb_polling) /* XXX were VIA1 interrupts blocked ? */
608 		/* poll until byte done */
609 		while ((adbActionState != ADB_ACTION_IDLE) || (ADB_INTR_IS_ON)
610 		    || (adbWaiting == 1))
611 			if (ADB_SR_INTR_IS_ON) {	/* wait for "interrupt" */
612 				adb_intr_cuda();	/* process it */
613 				if (cold)
614 					delay(ADB_DELAY);
615 				adb_soft_intr();
616 			}
617 
618 	return 0;
619 }
620 
621 /*
622  * Called when when an adb interrupt happens.
623  * This routine simply transfers control over to the appropriate
624  * code for the machine we are running on.
625  */
626 int
627 adb_intr(void *arg)
628 {
629 	switch (adbHardware) {
630 	case ADB_HW_PMU:
631 		pm_intr();
632 		break;
633 
634 	case ADB_HW_CUDA:
635 		adb_intr_cuda();
636 		break;
637 	}
638 	return 1;
639 }
640 
641 
642 /*
643  * adb_pass_up is called by the interrupt-time routines.
644  * It takes the raw packet data that was received from the
645  * device and puts it into the queue that the upper half
646  * processes. It then signals for a soft ADB interrupt which
647  * will eventually call the upper half routine (adb_soft_intr).
648  *
649  * If in->unsol is 0, then this is either the notification
650  * that the packet was sent (on a LISTEN, for example), or the
651  * response from the device (on a TALK). The completion routine
652  * is called only if the user specified one.
653  *
654  * If in->unsol is 1, then this packet was unsolicited and
655  * so we look up the device in the ADB device table to determine
656  * what its default service routine is.
657  *
658  * If in->ack_only is 1, then we really only need to call
659  * the completion routine, so don't do any other stuff.
660  *
661  * Note that in->data contains the packet header AND data,
662  * while adbInbound[]->data contains ONLY data.
663  *
664  * Note: Called only at interrupt time. Assumes this.
665  */
666 void
667 adb_pass_up(struct adbCommand *in)
668 {
669 	int start = 0, len = 0, cmd = 0;
670 	ADBDataBlock block;
671 
672 	if (adbInCount >= ADB_QUEUE) {
673 #ifdef ADB_DEBUG
674 		if (adb_debug)
675 			printf_intr("adb: ring buffer overflow\n");
676 #endif
677 		return;
678 	}
679 
680 	if (in->ack_only) {
681 		len = in->data[0];
682 		cmd = in->cmd;
683 		start = 0;
684 	} else {
685 		switch (adbHardware) {
686 		case ADB_HW_CUDA:
687 			/* If it's unsolicited, accept only ADB data for now */
688 			if (in->unsol)
689 				if (0 != in->data[2])
690 					return;
691 			cmd = in->data[4];
692 			if (in->data[0] < 5)
693 				len = 0;
694 			else
695 				len = in->data[0]-4;
696 			start = 4;
697 			break;
698 
699 		case ADB_HW_PMU:
700 			cmd = in->data[1];
701 			if (in->data[0] < 2)
702 				len = 0;
703 			else
704 				len = in->data[0]-1;
705 			start = 1;
706 			break;
707 
708 		case ADB_HW_UNKNOWN:
709 			return;
710 		}
711 
712 		/* Make sure there is a valid device entry for this device */
713 		if (in->unsol) {
714 			/* ignore unsolicited data during adbreinit */
715 			if (adbStarting)
716 				return;
717 			/* get device's comp. routine and data area */
718 			if (-1 == get_adb_info(&block, ADB_CMDADDR(cmd)))
719 				return;
720 		}
721 	}
722 
723 	/*
724  	 * If this is an unsolicited packet, we need to fill in
725  	 * some info so adb_soft_intr can process this packet
726  	 * properly. If it's not unsolicited, then use what
727  	 * the caller sent us.
728  	 */
729 	if (in->unsol) {
730 		adbInbound[adbInTail].compRout = (void *)block.dbServiceRtPtr;
731 		adbInbound[adbInTail].compData = (void *)block.dbDataAreaAddr;
732 		adbInbound[adbInTail].saveBuf = (void *)adbInbound[adbInTail].data;
733 	} else {
734 		adbInbound[adbInTail].compRout = (void *)in->compRout;
735 		adbInbound[adbInTail].compData = (void *)in->compData;
736 		adbInbound[adbInTail].saveBuf = (void *)in->saveBuf;
737 	}
738 
739 #ifdef ADB_DEBUG
740 	if (adb_debug && in->data[1] == 2)
741 		printf_intr("adb: caught error\n");
742 #endif
743 
744 	/* copy the packet data over */
745 	/*
746 	 * TO DO: If the *_intr routines fed their incoming data
747 	 * directly into an adbCommand struct, which is passed to
748 	 * this routine, then we could eliminate this copy.
749 	 */
750 	memcpy(adbInbound[adbInTail].data + 1, in->data + start + 1, len);
751 	adbInbound[adbInTail].data[0] = len;
752 	adbInbound[adbInTail].cmd = cmd;
753 
754 	adbInCount++;
755 	if (++adbInTail >= ADB_QUEUE)
756 		adbInTail = 0;
757 
758 	/*
759 	 * If the debugger is running, call upper half manually.
760 	 * Otherwise, trigger a soft interrupt to handle the rest later.
761 	 */
762 	if (adb_polling)
763 		adb_soft_intr();
764 	else
765 		setsoftadb();
766 }
767 
768 
769 /*
770  * Called to process the packets after they have been
771  * placed in the incoming queue.
772  *
773  */
774 void
775 adb_soft_intr(void)
776 {
777 	int s;
778 	int cmd = 0;
779 	u_char *buffer;
780 	u_char *comprout;
781 	u_char *compdata;
782 
783 /*delay(2*ADB_DELAY);*/
784 
785 	while (adbInCount) {
786 #ifdef ADB_DEBUG
787 		if (adb_debug & 0x80)
788 			printf_intr("%x %x %x ",
789 			    adbInCount, adbInHead, adbInTail);
790 #endif
791 		/* get the data we need from the queue */
792 		buffer = adbInbound[adbInHead].saveBuf;
793 		comprout = adbInbound[adbInHead].compRout;
794 		compdata = adbInbound[adbInHead].compData;
795 		cmd = adbInbound[adbInHead].cmd;
796 
797 		/* copy over data to data area if it's valid */
798 		/*
799 		 * Note that for unsol packets we don't want to copy the
800 		 * data anywhere, so buffer was already set to 0.
801 		 * For ack_only buffer was set to 0, so don't copy.
802 		 */
803 		if (buffer)
804 			memcpy(buffer, adbInbound[adbInHead].data,
805 			    adbInbound[adbInHead].data[0] + 1);
806 
807 #ifdef ADB_DEBUG
808 			if (adb_debug & 0x80) {
809 				printf_intr("%p %p %p %x ",
810 				    buffer, comprout, compdata, (short)cmd);
811 				printf_intr("buf: ");
812 				print_single(adbInbound[adbInHead].data);
813 			}
814 #endif
815 		/*
816 		 * Remove the packet from the queue before calling
817                  * the completion routine, so that the completion
818                  * routine can reentrantly process the queue.  For
819                  * example, this happens when polling is turned on
820                  * by entering the debuger by keystroke.
821                  */
822 		s = splhigh();
823 		adbInCount--;
824 		if (++adbInHead >= ADB_QUEUE)
825 			adbInHead = 0;
826 		splx(s);
827 
828 		/* call default completion routine if it's valid */
829 		if (comprout) {
830 			((int (*)(u_char *, u_char *, int)) comprout)
831 			    (buffer, compdata, cmd);
832 		}
833 
834 	}
835 }
836 
837 
838 /*
839  * This is my version of the ADBOp routine. It mainly just calls the
840  * hardware-specific routine.
841  *
842  *   data 	: pointer to data area to be used by compRout
843  *   compRout	: completion routine
844  *   buffer	: for LISTEN: points to data to send - MAX 8 data bytes,
845  *		  byte 0 = # of bytes
846  *		: for TALK: points to place to save return data
847  *   command	: the adb command to send
848  *   result	: 0 = success
849  *		: -1 = could not complete
850  */
851 int
852 adb_op(Ptr buffer, Ptr compRout, Ptr data, short command)
853 {
854 	int result;
855 
856 	switch (adbHardware) {
857 	case ADB_HW_PMU:
858 		result = pm_adb_op((u_char *)buffer, (void *)compRout,
859 		    (void *)data, (int)command);
860 
861 		if (result == 0)
862 			return 0;
863 		else
864 			return -1;
865 		break;
866 
867 	case ADB_HW_CUDA:
868 		result = send_adb_cuda((u_char *)0, (u_char *)buffer,
869 		    (void *)compRout, (void *)data, (int)command);
870 		if (result == 0)
871 			return 0;
872 		else
873 			return -1;
874 		break;
875 
876 	default:
877 		return -1;
878 	}
879 }
880 
881 
882 /*
883  * adb_hw_setup
884  * This routine sets up the possible machine specific hardware
885  * config (mainly VIA settings) for the various models.
886  */
887 void
888 adb_hw_setup(void)
889 {
890 	volatile int i;
891 
892 	switch (adbHardware) {
893 
894 	case ADB_HW_PMU:
895 		/*
896 		 * XXX - really PM_VIA_CLR_INTR - should we put it in
897 		 * pm_direct.h?
898 		 */
899 		write_via_reg(VIA1, vIFR, 0x90);	/* clear interrupt */
900 		break;
901 
902 	case ADB_HW_CUDA:
903 		via_reg_or(VIA1, vDirB, 0x30);	/* register B bits 4 and 5:
904 						 * outputs */
905 		via_reg_and(VIA1, vDirB, 0xf7);	/* register B bit 3: input */
906 		via_reg_and(VIA1, vACR, ~vSR_OUT);	/* make sure SR is set
907 							 * to IN */
908 		write_via_reg(VIA1, vACR, (read_via_reg(VIA1, vACR) | 0x0c) & ~0x10);
909 		adbActionState = ADB_ACTION_IDLE;	/* used by all types of
910 							 * hardware */
911 		write_via_reg(VIA1, vIER, 0x84);/* make sure VIA interrupts
912 						 * are on */
913 		ADB_SET_STATE_IDLE_CUDA();	/* set ADB bus state to idle */
914 
915 		/* sort of a device reset */
916 		i = ADB_SR();	/* clear interrupt */
917 		ADB_VIA_INTR_DISABLE();	/* no interrupts while clearing */
918 		ADB_SET_STATE_IDLE_CUDA();	/* reset state to idle */
919 		delay(ADB_DELAY);
920 		ADB_SET_STATE_TIP();	/* signal start of frame */
921 		delay(ADB_DELAY);
922 		ADB_TOGGLE_STATE_ACK_CUDA();
923 		delay(ADB_DELAY);
924 		ADB_CLR_STATE_TIP();
925 		delay(ADB_DELAY);
926 		ADB_SET_STATE_IDLE_CUDA();	/* back to idle state */
927 		i = ADB_SR();	/* clear interrupt */
928 		ADB_VIA_INTR_ENABLE();	/* ints ok now */
929 		break;
930 
931 	case ADB_HW_UNKNOWN:
932 	default:
933 		write_via_reg(VIA1, vIER, 0x04);/* turn interrupts off - TO
934 						 * DO: turn PB ints off? */
935 		break;
936 	}
937 }
938 
939 /*
940  * adb_reinit sets up the adb stuff
941  *
942  */
943 void
944 adb_reinit(struct adb_softc *sc)
945 {
946 	u_char send_string[ADB_MAX_MSG_LENGTH];
947 	ADBDataBlock data;	/* temp. holder for getting device info */
948 	volatile int i, x;
949 	int s;
950 	int command;
951 	int result;
952 	int saveptr;		/* point to next free relocation address */
953 	int device;
954 	int nonewtimes;		/* times thru loop w/o any new devices */
955 	int ADBNumDevices = 0;
956 
957 	/* Make sure we are not interrupted while building the table. */
958 	if (adbHardware != ADB_HW_PMU)	/* ints must be on for PB? */
959 		s = splhigh();
960 
961 	/* Let intr routines know we are running reinit */
962 	adbStarting = 1;
963 
964 	/*
965 	 * Initialize the ADB table.  For now, we'll always use the same table
966 	 * that is defined at the beginning of this file - no mallocs.
967 	 */
968 	for (i = 0; i < 16; i++)
969 		sc->sc_devtable[i].handler_id = 0;
970 
971 	adb_hw_setup();		/* init the VIA bits and hard reset ADB */
972 
973 	delay(1000);
974 
975 	/* send an ADB reset first */
976 	adb_op_sync((Ptr)0, (short)0x00);
977 	delay(200000);
978 
979 	/*
980 	 * Probe for ADB devices. Probe devices 1-15 quickly to determine
981 	 * which device addresses are in use and which are free. For each
982 	 * address that is in use, move the device at that address to a higher
983 	 * free address. Continue doing this at that address until no device
984 	 * responds at that address. Then move the last device that was moved
985 	 * back to the original address. Do this for the remaining addresses
986 	 * that we determined were in use.
987 	 *
988 	 * When finished, do this entire process over again with the updated
989 	 * list of in use addresses. Do this until no new devices have been
990 	 * found in 20 passes though the in use address list. (This probably
991 	 * seems long and complicated, but it's the best way to detect multiple
992 	 * devices at the same address - sometimes it takes a couple of tries
993 	 * before the collision is detected.)
994 	 */
995 
996 	/* initial scan through the devices */
997 	for (i = 1; i < 16; i++) {
998 		send_string[0] = 0;
999 		command = ADBTALK(i, 3);
1000 		result = adb_op_sync((Ptr)send_string, (short)command);
1001 
1002 		if (send_string[0] != 0) {
1003 			/* check for valid device handler */
1004 			switch (send_string[2]) {
1005 			case 0:
1006 			case 0xfd:
1007 			case 0xfe:
1008 			case 0xff:
1009 				continue;	/* invalid, skip */
1010 			}
1011 
1012 			/* found a device */
1013 			++ADBNumDevices;
1014 			KASSERT(ADBNumDevices < 16);
1015 			sc->sc_devtable[ADBNumDevices].handler_id =
1016 				(int)send_string[2];
1017 			sc->sc_devtable[ADBNumDevices].orig_addr = i;
1018 			sc->sc_devtable[ADBNumDevices].curr_addr = i;
1019 			sc->sc_devtable[ADBNumDevices].data = NULL;
1020 			sc->sc_devtable[ADBNumDevices].handler = NULL;
1021 		}
1022 	}
1023 
1024 	/* find highest unused address */
1025 	for (saveptr = 15; saveptr > 0; saveptr--)
1026 		if (-1 == get_adb_info(&data, saveptr))
1027 			break;
1028 
1029 #ifdef ADB_DEBUG
1030 	if (adb_debug & 0x80) {
1031 		printf_intr("first free is: 0x%02x\n", saveptr);
1032 		printf_intr("devices: %i\n", ADBNumDevices);
1033 	}
1034 #endif
1035 
1036 	nonewtimes = 0;		/* no loops w/o new devices */
1037 	while (saveptr > 0 && nonewtimes++ < 11) {
1038 		for (i = 1; i <= ADBNumDevices; i++) {
1039 			device = sc->sc_devtable[i].curr_addr;
1040 #ifdef ADB_DEBUG
1041 			if (adb_debug & 0x80)
1042 				printf_intr("moving device 0x%02x to 0x%02x "
1043 				    "(index 0x%02x)  ", device, saveptr, i);
1044 #endif
1045 
1046 			/* send TALK R3 to address */
1047 			command = ADBTALK(device, 3);
1048 			adb_op_sync((Ptr)send_string, (short)command);
1049 
1050 			/* move device to higher address */
1051 			command = ADBLISTEN(device, 3);
1052 			send_string[0] = 2;
1053 			send_string[1] = (u_char)(saveptr | 0x60);
1054 			send_string[2] = 0xfe;
1055 			adb_op_sync((Ptr)send_string, (short)command);
1056 			delay(500);
1057 
1058 			/* send TALK R3 - anything at new address? */
1059 			command = ADBTALK(saveptr, 3);
1060 			adb_op_sync((Ptr)send_string, (short)command);
1061 			delay(500);
1062 
1063 			if (send_string[0] == 0) {
1064 #ifdef ADB_DEBUG
1065 				if (adb_debug & 0x80)
1066 					printf_intr("failed, continuing\n");
1067 #endif
1068 				continue;
1069 			}
1070 
1071 			/* send TALK R3 - anything at old address? */
1072 			command = ADBTALK(device, 3);
1073 			result = adb_op_sync((Ptr)send_string, (short)command);
1074 			if (send_string[0] != 0) {
1075 				/* check for valid device handler */
1076 				switch (send_string[2]) {
1077 				case 0:
1078 				case 0xfd:
1079 				case 0xfe:
1080 				case 0xff:
1081 					continue;	/* invalid, skip */
1082 				}
1083 
1084 				/* new device found */
1085 				/* update data for previously moved device */
1086 				sc->sc_devtable[i].curr_addr = saveptr;
1087 #ifdef ADB_DEBUG
1088 				if (adb_debug & 0x80)
1089 					printf_intr("old device at index %i\n",i);
1090 #endif
1091 				/* add new device in table */
1092 #ifdef ADB_DEBUG
1093 				if (adb_debug & 0x80)
1094 					printf_intr("new device found\n");
1095 #endif
1096 				if (saveptr > ADBNumDevices) {
1097 					++ADBNumDevices;
1098 					KASSERT(ADBNumDevices < 16);
1099 				}
1100 				sc->sc_devtable[ADBNumDevices].handler_id =
1101 					(int)send_string[2];
1102 				sc->sc_devtable[ADBNumDevices].orig_addr = device;
1103 				sc->sc_devtable[ADBNumDevices].curr_addr = device;
1104 				/* These will be set correctly in adbsys.c */
1105 				/* Until then, unsol. data will be ignored. */
1106 				sc->sc_devtable[ADBNumDevices].data = NULL;
1107 				sc->sc_devtable[ADBNumDevices].handler = NULL;
1108 				/* find next unused address */
1109 				for (x = saveptr; x > 0; x--) {
1110 					if (-1 == get_adb_info(&data, x)) {
1111 						saveptr = x;
1112 						break;
1113 					}
1114 				}
1115 				if (x == 0)
1116 					saveptr = 0;
1117 #ifdef ADB_DEBUG
1118 				if (adb_debug & 0x80)
1119 					printf_intr("new free is 0x%02x\n",
1120 					    saveptr);
1121 #endif
1122 				nonewtimes = 0;
1123 			} else {
1124 #ifdef ADB_DEBUG
1125 				if (adb_debug & 0x80)
1126 					printf_intr("moving back...\n");
1127 #endif
1128 				/* move old device back */
1129 				command = ADBLISTEN(saveptr, 3);
1130 				send_string[0] = 2;
1131 				send_string[1] = (u_char)(device | 0x60);
1132 				send_string[2] = 0xfe;
1133 				adb_op_sync((Ptr)send_string, (short)command);
1134 				delay(1000);
1135 			}
1136 		}
1137 	}
1138 
1139 #ifdef ADB_DEBUG
1140 	if (adb_debug) {
1141 		for (i = 1; i <= ADBNumDevices; i++) {
1142 			x = get_ind_adb_info(sc, &data, i);
1143 			if (x != -1)
1144 				printf_intr("index 0x%x, addr 0x%x, type 0x%x\n",
1145 				    i, x, data.devType);
1146 		}
1147 	}
1148 #endif
1149 
1150 #ifdef ADB_DEBUG
1151 	if (adb_debug) {
1152 		if (0 == ADBNumDevices)	/* tell user if no devices found */
1153 			printf_intr("adb: no devices found\n");
1154 	}
1155 #endif
1156 
1157 	adbStarting = 0;	/* not starting anymore */
1158 #ifdef ADB_DEBUG
1159 	if (adb_debug)
1160 		printf_intr("adb: adb_reinit complete\n");
1161 #endif
1162 
1163 	if (adbHardware == ADB_HW_CUDA) {
1164 		timeout_set(&adb_cuda_timeout, (void *)adb_cuda_tickle, NULL);
1165 		timeout_add(&adb_cuda_timeout, ADB_TICKLE_TICKS);
1166 	}
1167 
1168 	if (adbHardware != ADB_HW_PMU)	/* ints must be on for PB? */
1169 		splx(s);
1170 }
1171 
1172 
1173 /*
1174  * adb_cmd_result
1175  *
1176  * This routine lets the caller know whether the specified adb command string
1177  * should expect a returned result, such as a TALK command.
1178  *
1179  * returns: 0 if a result should be expected
1180  *          1 if a result should NOT be expected
1181  */
1182 int
1183 adb_cmd_result(u_char *in)
1184 {
1185 	switch (adbHardware) {
1186 	case ADB_HW_CUDA:
1187 		/* was it an ADB talk command? */
1188 		if ((in[1] == 0x00) && ((in[2] & 0x0c) == 0x0c))
1189 			return 0;
1190 		/* was it an RTC/PRAM read date/time? */
1191 		if ((in[1] == 0x01) && (in[2] == 0x03))
1192 			return 0;
1193 		return 1;
1194 
1195 	case ADB_HW_PMU:
1196 		return 1;
1197 
1198 	default:
1199 		return 1;
1200 	}
1201 }
1202 
1203 
1204 /*
1205  * adb_op_sync
1206  *
1207  * This routine does exactly what the adb_op routine does, except that after
1208  * the adb_op is called, it waits until the return value is present before
1209  * returning.
1210  */
1211 int
1212 adb_op_sync(Ptr buffer, short command)
1213 {
1214 	int tmout;
1215 	int result;
1216 	volatile int flag = 0;
1217 
1218 	result = adb_op(buffer, (void *)adb_op_comprout,
1219 	    (void *)&flag, command);	/* send command */
1220 	if (result == 0) {		/* send ok? */
1221 		/*
1222 		 * Total time to wait is calculated as follows:
1223 		 *  - Tlt (stop to start time): 260 usec
1224 		 *  - start bit: 100 usec
1225 		 *  - up to 8 data bytes: 64 * 100 usec = 6400 usec
1226 		 *  - stop bit (with SRQ): 140 usec
1227 		 * Total: 6900 usec
1228 		 *
1229 		 * This is the total time allowed by the specification.  Any
1230 		 * device that doesn't conform to this will fail to operate
1231 		 * properly on some Apple systems.  In spite of this we
1232 		 * double the time to wait; some Cuda-based apparently
1233 		 * queues some commands and allows the main CPU to continue
1234 		 * processing (radical concept, eh?).  To be safe, allow
1235 		 * time for two complete ADB transactions to occur.
1236 		 */
1237 		for (tmout = 13800; !flag && tmout >= 10; tmout -= 10)
1238 			delay(10);
1239 		if (!flag && tmout > 0)
1240 			delay(tmout);
1241 
1242 		if (!flag)
1243 			result = -2;
1244 	}
1245 
1246 	return result;
1247 }
1248 
1249 
1250 /*
1251  * adb_op_comprout
1252  *
1253  * This function is used by the adb_op_sync routine so it knows when the
1254  * function is done.
1255  */
1256 void
1257 adb_op_comprout(caddr_t buffer, caddr_t compdata, int cmd)
1258 {
1259 	*(int *)compdata = 0x01;		/* update flag value */
1260 }
1261 
1262 int
1263 count_adbs(struct adb_softc *sc)
1264 {
1265 	int i;
1266 	int found;
1267 
1268 	found = 0;
1269 
1270 	for (i = 1; i < 16; i++)
1271 		if (0 != sc->sc_devtable[i].handler_id)
1272 			found++;
1273 
1274 	return found;
1275 }
1276 
1277 int
1278 get_ind_adb_info(struct adb_softc *sc, ADBDataBlock * info, int index)
1279 {
1280 	if ((index < 1) || (index > 15))	/* check range 1-15 */
1281 		return (-1);
1282 
1283 #ifdef ADB_DEBUG
1284 	if (adb_debug & 0x80)
1285 		printf_intr("index 0x%x handler id 0x%x\n", index,
1286 		    sc->sc_devtable[index].handler_id);
1287 #endif
1288 	if (0 == sc->sc_devtable[index].handler_id)	/* make sure it's a valid entry */
1289 		return (-1);
1290 
1291 	info->devType = sc->sc_devtable[index].handler_id;
1292 	info->origADBAddr = sc->sc_devtable[index].orig_addr;
1293 	info->dbServiceRtPtr = (Ptr)sc->sc_devtable[index].handler;
1294 	info->dbDataAreaAddr = (Ptr)sc->sc_devtable[index].data;
1295 
1296 	return (sc->sc_devtable[index].curr_addr);
1297 }
1298 
1299 int
1300 get_adb_info(ADBDataBlock * info, int adbAddr)
1301 {
1302 	struct adb_softc *sc = adb_cd.cd_devs[0];
1303 	int i;
1304 
1305 	if (sc == NULL)
1306 		return (-1);
1307 
1308 	if ((adbAddr < 1) || (adbAddr > 15))	/* check range 1-15 */
1309 		return (-1);
1310 
1311 	for (i = 1; i < 15; i++)
1312 		if (sc->sc_devtable[i].curr_addr == adbAddr) {
1313 			info->devType = sc->sc_devtable[i].handler_id;
1314 			info->origADBAddr = sc->sc_devtable[i].orig_addr;
1315 			info->dbServiceRtPtr = (Ptr)sc->sc_devtable[i].handler;
1316 			info->dbDataAreaAddr = sc->sc_devtable[i].data;
1317 			return 0;	/* found */
1318 		}
1319 
1320 	return (-1);		/* not found */
1321 }
1322 
1323 int
1324 set_adb_info(ADBSetInfoBlock * info, int adbAddr)
1325 {
1326 	struct adb_softc *sc = adb_cd.cd_devs[0];
1327 	int i;
1328 
1329 	if (sc == NULL)
1330 		return (-1);
1331 
1332 	if ((adbAddr < 1) || (adbAddr > 15))	/* check range 1-15 */
1333 		return (-1);
1334 
1335 	for (i = 1; i < 15; i++)
1336 		if (sc->sc_devtable[i].curr_addr == adbAddr) {
1337 			sc->sc_devtable[i].handler =
1338 			    (void *)(info->siServiceRtPtr);
1339 			sc->sc_devtable[i].data = info->siDataAreaAddr;
1340 			return 0;	/* found */
1341 		}
1342 
1343 	return (-1);		/* not found */
1344 
1345 }
1346 
1347 /* caller should really use machine-independent version: getPramTime */
1348 /* this version does pseudo-adb access only */
1349 int
1350 adb_read_date_time(time_t *time)
1351 {
1352 	u_char output[ADB_MAX_MSG_LENGTH];
1353 	int result;
1354 	int retcode;
1355 	volatile int flag = 0;
1356 	u_int32_t t;
1357 
1358 	switch (adbHardware) {
1359 	case ADB_HW_PMU:
1360 		pm_read_date_time(time);
1361 		retcode = 0;
1362 		break;
1363 
1364 	case ADB_HW_CUDA:
1365 		output[0] = 0x02;	/* 2 byte message */
1366 		output[1] = 0x01;	/* to pram/rtc device */
1367 		output[2] = 0x03;	/* read date/time */
1368 		result = send_adb_cuda((u_char *)output, (u_char *)output,
1369 		    (void *)adb_op_comprout, (void *)&flag, (int)0);
1370 		if (result != 0) {	/* exit if not sent */
1371 			retcode = -1;
1372 			break;
1373 		}
1374 
1375 		while (0 == flag)	/* wait for result */
1376 			;
1377 
1378 		delay(20); /* completion occurs too soon? */
1379 		memcpy(&t, output + 1, sizeof(t));
1380 		*time = (time_t)t;
1381 		retcode = 0;
1382 		break;
1383 
1384 	case ADB_HW_UNKNOWN:
1385 	default:
1386 		retcode = -1;
1387 		break;
1388 	}
1389 	if (retcode == 0) {
1390 #define DIFF19041970 2082844800
1391 		*time -= DIFF19041970;
1392 
1393 	} else {
1394 		*time = 0;
1395 	}
1396 	return retcode;
1397 }
1398 
1399 /* caller should really use machine-independent version: setPramTime */
1400 /* this version does pseudo-adb access only */
1401 int
1402 adb_set_date_time(time_t time)
1403 {
1404 	u_char output[ADB_MAX_MSG_LENGTH];
1405 	int result;
1406 	volatile int flag = 0;
1407 	u_int32_t t;
1408 
1409 	time += DIFF19041970;
1410 	switch (adbHardware) {
1411 
1412 	case ADB_HW_CUDA:
1413 		t = time;		/* XXX eventually truncates */
1414 
1415 		output[0] = 0x06;	/* 6 byte message */
1416 		output[1] = 0x01;	/* to pram/rtc device */
1417 		output[2] = 0x09;	/* set date/time */
1418 		output[3] = (u_char)(t >> 24);
1419 		output[4] = (u_char)(t >> 16);
1420 		output[5] = (u_char)(t >> 8);
1421 		output[6] = (u_char)(t);
1422 		result = send_adb_cuda((u_char *)output, (u_char *)0,
1423 		    (void *)adb_op_comprout, (void *)&flag, (int)0);
1424 		if (result != 0)	/* exit if not sent */
1425 			return -1;
1426 
1427 		while (0 == flag)	/* wait for send to finish */
1428 			;
1429 
1430 		return 0;
1431 
1432 	case ADB_HW_PMU:
1433 		pm_set_date_time(time);
1434 		return 0;
1435 
1436 	default:
1437 		return -1;
1438 	}
1439 }
1440 
1441 
1442 int
1443 adb_poweroff(void)
1444 {
1445 	u_char output[ADB_MAX_MSG_LENGTH];
1446 	int result;
1447 
1448 	adb_polling = 1;
1449 
1450 	switch (adbHardware) {
1451 	case ADB_HW_PMU:
1452 		/* Clear the wake on AC loss event */
1453 		pmu_fileserver_mode(0);
1454 		pm_adb_poweroff();
1455 
1456 		for (;;);		/* wait for power off */
1457 
1458 		return 0;
1459 
1460 	case ADB_HW_CUDA:
1461 		output[0] = 0x02;	/* 2 byte message */
1462 		output[1] = 0x01;	/* to pram/rtc/soft-power device */
1463 		output[2] = 0x0a;	/* set poweroff */
1464 		result = send_adb_cuda((u_char *)output, (u_char *)0,
1465 		    (void *)0, (void *)0, (int)0);
1466 		if (result != 0)	/* exit if not sent */
1467 			return -1;
1468 
1469 		for (;;);		/* wait for power off */
1470 
1471 		return 0;
1472 
1473 	default:
1474 		return -1;
1475 	}
1476 }
1477 
1478 void
1479 setsoftadb()
1480 {
1481 	if (!timeout_initialized(&adb_softintr_timeout))
1482 		timeout_set(&adb_softintr_timeout, (void *)adb_soft_intr, NULL);
1483 	timeout_add(&adb_softintr_timeout, 1);
1484 }
1485 
1486 void
1487 adb_cuda_autopoll()
1488 {
1489 	volatile int flag = 0;
1490 	int result;
1491 	u_char output[16];
1492 
1493 	output[0] = 0x03;	/* 3-byte message */
1494 	output[1] = 0x01;	/* to pram/rtc/soft-power device */
1495 	output[2] = 0x01;	/* cuda autopoll */
1496 	output[3] = 0x01;
1497 	result = send_adb_cuda(output, output, adb_op_comprout,
1498 	    (void *)&flag, 0);
1499 	if (result != 0)	/* exit if not sent */
1500 		return;
1501 
1502 	while (flag == 0);	/* wait for result */
1503 }
1504 
1505 void
1506 adb_cuda_fileserver_mode()
1507 {
1508 	volatile int flag = 0;
1509 	int result;
1510 	u_char output[16];
1511 
1512 	output[0] = 0x03;	/* 3-byte message */
1513 	output[1] = 0x01; 	/* to pram/rtc device/soft-power device */
1514 	output[2] = 0x13;	/* cuda file server mode */
1515 	output[3] = 0x01;	/* True - Turn on after AC loss */
1516 
1517 	result = send_adb_cuda(output, output, adb_op_comprout,
1518 	    (void *)&flag, 0);
1519 	if (result != 0)
1520 		return;
1521 
1522 	while (flag == 0);
1523 }
1524 
1525 void
1526 adb_restart()
1527 {
1528 	int result;
1529 	u_char output[16];
1530 
1531 	adb_polling = 1;
1532 
1533 	switch (adbHardware) {
1534 	case ADB_HW_CUDA:
1535 		output[0] = 0x02;	/* 2 byte message */
1536 		output[1] = 0x01;	/* to pram/rtc/soft-power device */
1537 		output[2] = 0x11;	/* restart */
1538 		result = send_adb_cuda((u_char *)output, (u_char *)0,
1539 				       (void *)0, (void *)0, (int)0);
1540 		if (result != 0)	/* exit if not sent */
1541 			return;
1542 		while (1);		/* not return */
1543 
1544 	case ADB_HW_PMU:
1545 		pm_adb_restart();
1546 		while (1);		/* not return */
1547 	}
1548 }
1549 
1550 /*
1551  * Driver definition.
1552  */
1553 
1554 int	adbmatch(struct device *, void *, void *);
1555 void	adbattach(struct device *, struct device *, void *);
1556 
1557 struct cfattach adb_ca = {
1558 	sizeof(struct adb_softc), adbmatch, adbattach
1559 };
1560 
1561 int
1562 adbmatch(struct device *parent, void *cf, void *aux)
1563 {
1564 	struct confargs *ca = aux;
1565 
1566 	if (ca->ca_nreg < 8)
1567 		return 0;
1568 
1569 	if (ca->ca_nintr < 4)
1570 		return 0;
1571 
1572 	if (strcmp(ca->ca_name, "via-cuda") == 0)
1573 		return 1;
1574 
1575 	if (strcmp(ca->ca_name, "via-pmu") == 0)
1576 		return 1;
1577 
1578 	return 0;
1579 }
1580 
1581 void
1582 adbattach(struct device *parent, struct device *self, void *aux)
1583 {
1584 	struct adb_softc *sc = (struct adb_softc *)self;
1585 	struct confargs *ca = aux;
1586 	struct confargs nca;
1587 	char name[32];
1588 	int node;
1589 	ADBDataBlock adbdata;
1590 	struct adb_attach_args aa_args;
1591 	int totaladbs;
1592 	int adbindex, adbaddr;
1593 
1594 	ca->ca_reg[0] += ca->ca_baseaddr;
1595 
1596 	sc->sc_regbase = mapiodev(ca->ca_reg[0], ca->ca_reg[1]);
1597 	Via1Base = sc->sc_regbase;
1598 
1599 	if (strcmp(ca->ca_name, "via-cuda") == 0)
1600 		adbHardware = ADB_HW_CUDA;
1601 	else if (strcmp(ca->ca_name, "via-pmu") == 0) {
1602 		adbHardware = ADB_HW_PMU;
1603 
1604 		/*
1605 		 * Bus reset can take a long time if no adb devices are
1606 		 * connected, e.g. on a Mac Mini; so check for an adb
1607 		 * child in the OF tree to speed up pm_adb_op().
1608 		 */
1609 		adbempty = 1;
1610 		for (node = OF_child(ca->ca_node); node; node = OF_peer(node)) {
1611 			if (OF_getprop(node, "name", name, sizeof name) <= 0)
1612 				continue;
1613 			if (strcmp(name, "adb") == 0) {
1614 				adbempty = 0;
1615 				break;
1616 			}
1617 		}
1618 	}
1619 
1620 	adb_polling = 1;
1621 	if (!adbempty) {
1622 		adb_reinit(sc);
1623 		totaladbs = count_adbs(sc);
1624 		printf(": irq %d, %s, %d target%s", ca->ca_intr[0], ca->ca_name,
1625 		    totaladbs, (totaladbs == 1) ? "" : "s");
1626 	}
1627 	printf("\n");
1628 
1629 	mac_intr_establish(parent, ca->ca_intr[0], IST_LEVEL, IPL_HIGH,
1630 	    adb_intr, sc, sc->sc_dev.dv_xname);
1631 
1632 	/* init powerpc globals which control RTC functionality */
1633 	time_read = adb_read_date_time;
1634 	time_write = adb_set_date_time;
1635 
1636 #if NAPM > 0
1637 	if (adbHardware == ADB_HW_PMU) {
1638 		/* Magic for signalling the apm driver to match. */
1639 		nca.ca_name = "apm";
1640 		nca.ca_node = node;
1641 		config_found(self, &nca, NULL);
1642 	}
1643 #endif
1644 
1645 	/* Attach I2C controller. */
1646 	for (node = OF_child(ca->ca_node); node; node = OF_peer(node)) {
1647 		if (OF_getprop(node, "name", name, sizeof name) <= 0)
1648 			continue;
1649 		if (strcmp(name, "pmu-i2c") == 0) {
1650 			nca.ca_name = "piic";
1651 			nca.ca_node = node;
1652 			config_found(self, &nca, NULL);
1653 		}
1654 	}
1655 
1656 	if (adbHardware == ADB_HW_CUDA)
1657 		adb_cuda_fileserver_mode();
1658 	if (adbHardware == ADB_HW_PMU)
1659 		pmu_fileserver_mode(1);
1660 
1661 	/*
1662 	 * XXX If the machine doesn't have an ADB bus (PowerBook5,6+)
1663 	 * yes it sounds stupid to attach adb(4), but don't try to send
1664 	 * ADB commands otherwise the PMU may shutdown the machine...
1665 	 */
1666 	if (adbempty)
1667 		return;
1668 
1669 	/* for each ADB device */
1670 	for (adbindex = 1; adbindex <= totaladbs; adbindex++) {
1671 		/* Get the ADB information */
1672 		adbaddr = get_ind_adb_info(sc, &adbdata, adbindex);
1673 
1674 		aa_args.name = adb_device_name;
1675 		aa_args.origaddr = adbdata.origADBAddr;
1676 		aa_args.adbaddr = adbaddr;
1677 		aa_args.handler_id = adbdata.devType;
1678 
1679 		(void)config_found(self, &aa_args, adbprint);
1680 	}
1681 
1682 	if (adbHardware == ADB_HW_CUDA)
1683 		adb_cuda_autopoll();
1684 	adb_polling = 0;
1685 }
1686