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