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