1 /*
2  * (C) Copyright 2004, Psyent Corporation <www.psyent.com>
3  * Scott McNutt <smcnutt@psyent.com>
4  *
5  * SPDX-License-Identifier:	GPL-2.0+
6  */
7 
8 #include <common.h>
9 #include <watchdog.h>
10 #include <asm/io.h>
11 #include <linux/compiler.h>
12 #include <serial.h>
13 
14 typedef volatile struct {
15 	unsigned	data;			/* Data register */
16 	unsigned	control;		/* Control register */
17 } nios_jtag_t;
18 
19 /* data register */
20 #define NIOS_JTAG_RVALID	(1<<15)		/* Read valid */
21 #define NIOS_JTAG_DATA(d)	((d)&0x0ff)	/* Read data */
22 #define NIOS_JTAG_RAVAIL(d)	((d)>>16)	/* Read space avail */
23 
24 /* control register */
25 #define NIOS_JTAG_RE		(1 << 0)	/* read intr enable */
26 #define NIOS_JTAG_WE		(1 << 1)	/* write intr enable */
27 #define NIOS_JTAG_RI		(1 << 8)	/* read intr pending */
28 #define NIOS_JTAG_WI		(1 << 9)	/* write intr pending*/
29 #define NIOS_JTAG_AC		(1 << 10)	/* activity indicator */
30 #define NIOS_JTAG_RRDY		(1 << 12)	/* read available */
31 #define NIOS_JTAG_WSPACE(d)	((d)>>16)	/* Write space avail */
32 
33 DECLARE_GLOBAL_DATA_PTR;
34 
35 /*------------------------------------------------------------------
36  * JTAG acts as the serial port
37  *-----------------------------------------------------------------*/
38 static nios_jtag_t *jtag = (nios_jtag_t *)CONFIG_SYS_NIOS_CONSOLE;
39 
40 static void altera_jtag_serial_setbrg(void)
41 {
42 }
43 
44 static int altera_jtag_serial_init(void)
45 {
46 	return 0;
47 }
48 
49 static void altera_jtag_serial_putc(char c)
50 {
51 	while (1) {
52 		unsigned st = readl(&jtag->control);
53 		if (NIOS_JTAG_WSPACE(st))
54 			break;
55 #ifdef CONFIG_ALTERA_JTAG_UART_BYPASS
56 		if (!(st & NIOS_JTAG_AC)) /* no connection */
57 			return;
58 #endif
59 		WATCHDOG_RESET();
60 	}
61 	writel ((unsigned char)c, &jtag->data);
62 }
63 
64 static int altera_jtag_serial_tstc(void)
65 {
66 	return ( readl (&jtag->control) & NIOS_JTAG_RRDY);
67 }
68 
69 static int altera_jtag_serial_getc(void)
70 {
71 	int c;
72 	unsigned val;
73 
74 	while (1) {
75 		WATCHDOG_RESET ();
76 		val = readl (&jtag->data);
77 		if (val & NIOS_JTAG_RVALID)
78 			break;
79 	}
80 	c = val & 0x0ff;
81 	return (c);
82 }
83 
84 static struct serial_device altera_jtag_serial_drv = {
85 	.name	= "altera_jtag_uart",
86 	.start	= altera_jtag_serial_init,
87 	.stop	= NULL,
88 	.setbrg	= altera_jtag_serial_setbrg,
89 	.putc	= altera_jtag_serial_putc,
90 	.puts	= default_serial_puts,
91 	.getc	= altera_jtag_serial_getc,
92 	.tstc	= altera_jtag_serial_tstc,
93 };
94 
95 void altera_jtag_serial_initialize(void)
96 {
97 	serial_register(&altera_jtag_serial_drv);
98 }
99 
100 __weak struct serial_device *default_serial_console(void)
101 {
102 	return &altera_jtag_serial_drv;
103 }
104