1 // Copyright 2016 The Fuchsia Authors
2 // Copyright (c) 2009 Corey Tabaka
3 //
4 // Use of this source code is governed by a MIT-style
5 // license that can be found in the LICENSE file or at
6 // https://opensource.org/licenses/MIT
7 
8 #include <arch/x86.h>
9 #include <arch/x86/apic.h>
10 #include <bits.h>
11 #include <dev/interrupt.h>
12 #include <kernel/cmdline.h>
13 #include <kernel/spinlock.h>
14 #include <kernel/thread.h>
15 #include <kernel/timer.h>
16 #include <lib/cbuf.h>
17 #include <lib/debuglog.h>
18 #include <lk/init.h>
19 #include <platform.h>
20 #include <platform/console.h>
21 #include <platform/debug.h>
22 #include <platform/pc.h>
23 #include <platform/pc/bootloader.h>
24 #include <reg.h>
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <trace.h>
30 #include <vm/physmap.h>
31 #include <zircon/time.h>
32 #include <zircon/types.h>
33 
34 #include "platform_p.h"
35 
36 static const int uart_baud_rate = 115200;
37 static int uart_io_port = 0x3f8;
38 static uint64_t uart_mem_addr = 0;
39 static uint32_t uart_irq = ISA_IRQ_SERIAL1;
40 
41 cbuf_t console_input_buf;
42 static bool output_enabled = false;
43 uint32_t uart_fifo_depth;
44 
45 // tx driven irq
46 static bool uart_tx_irq_enabled = false;
47 static event_t uart_dputc_event = EVENT_INITIAL_VALUE(uart_dputc_event, true,
48                                                       EVENT_FLAG_AUTOUNSIGNAL);
49 static spin_lock_t uart_spinlock = SPIN_LOCK_INITIAL_VALUE;
50 
uart_read(uint8_t reg)51 static uint8_t uart_read(uint8_t reg) {
52     if (uart_mem_addr) {
53         return (uint8_t)readl(uart_mem_addr + 4 * reg);
54     } else {
55         return (uint8_t)inp((uint16_t)(uart_io_port + reg));
56     }
57 }
58 
uart_write(uint8_t reg,uint8_t val)59 static void uart_write(uint8_t reg, uint8_t val) {
60     if (uart_mem_addr) {
61         writel(val, uart_mem_addr + 4 * reg);
62     } else {
63         outp((uint16_t)(uart_io_port + reg), val);
64     }
65 }
66 
uart_irq_handler(void * arg)67 static interrupt_eoi uart_irq_handler(void *arg) {
68     spin_lock(&uart_spinlock);
69 
70     // see why we have gotten an irq
71     for (;;) {
72         uint8_t iir = uart_read(2);
73         if (BIT(iir, 0))
74             break; // no valid interrupt
75 
76         // 3 bit identification field
77         uint ident = BITS(iir, 3, 0);
78         switch (ident) {
79         case 0b0100:
80         case 0b1100: {
81             // rx fifo is non empty, drain it
82             unsigned char c = uart_read(0);
83             cbuf_write_char(&console_input_buf, c);
84             break;
85         }
86         case 0b0010:
87             // transmitter is empty, signal any waiting senders
88             event_signal(&uart_dputc_event, true);
89             // disable the tx irq
90             uart_write(1, (1<<0)); // just rx interrupt enable
91             break;
92         case 0b0110: // receiver line status
93             uart_read(5); // read the LSR
94             break;
95         default:
96             spin_unlock(&uart_spinlock);
97             panic("UART: unhandled ident %#x\n", ident);
98         }
99     }
100 
101     spin_unlock(&uart_spinlock);
102     return IRQ_EOI_DEACTIVATE;
103 }
104 
platform_drain_debug_uart_rx(void)105 static void platform_drain_debug_uart_rx(void) {
106     while (uart_read(5) & (1<<0)) {
107         unsigned char c = uart_read(0);
108         cbuf_write_char(&console_input_buf, c);
109     }
110 }
111 
112 static constexpr TimerSlack kSlack{ZX_MSEC(1), TIMER_SLACK_CENTER};
113 
114 // for devices where the uart rx interrupt doesn't seem to work
uart_rx_poll(timer_t * t,zx_time_t now,void * arg)115 static void uart_rx_poll(timer_t* t, zx_time_t now, void* arg) {
116     zx_time_t deadline = zx_time_add_duration(now, ZX_MSEC(10));
117     timer_set(t, deadline, kSlack, uart_rx_poll, NULL);
118     platform_drain_debug_uart_rx();
119 }
120 
121 void platform_debug_start_uart_timer();
122 
platform_debug_start_uart_timer(void)123 void platform_debug_start_uart_timer(void) {
124     static timer_t uart_rx_poll_timer;
125     static bool started = false;
126 
127     if (!started) {
128         started = true;
129         timer_init(&uart_rx_poll_timer);
130         timer_set(&uart_rx_poll_timer, zx_time_add_duration(current_time(), ZX_MSEC(10)),
131                   kSlack, uart_rx_poll, NULL);
132     }
133 }
134 
init_uart()135 static void init_uart() {
136     /* configure the uart */
137     int divisor = 115200 / uart_baud_rate;
138 
139     /* get basic config done so that tx functions */
140     uart_write(1, 0);                                  // mask all irqs
141     uart_write(3, 0x80);                               // set up to load divisor latch
142     uart_write(0, static_cast<uint8_t>(divisor));      // lsb
143     uart_write(1, static_cast<uint8_t>(divisor >> 8)); // msb
144     uart_write(3, 3);                                  // 8N1
145     // enable FIFO, rx FIFO reset, tx FIFO reset, 16750 64 byte fifo enable,
146     // Rx FIFO irq trigger level at 14-bytes
147     uart_write(2, 0xe7);
148     // Drive flow control bits high since we don't actively manage them
149     uart_write(4, 0x3);
150 
151     /* figure out the fifo depth */
152     uint8_t fcr = uart_read(2);
153     if (BITS_SHIFT(fcr, 7, 6) == 3 && BIT(fcr, 5)) {
154         // this is a 16750
155         uart_fifo_depth = 64;
156     } else if (BITS_SHIFT(fcr, 7, 6) == 3) {
157         // this is a 16550A
158         uart_fifo_depth = 16;
159     } else {
160         uart_fifo_depth = 1;
161     }
162 }
163 
platform_serial_enabled()164 bool platform_serial_enabled() {
165     return bootloader.uart.type != ZBI_UART_NONE;
166 }
167 
168 // This just initializes the default serial console to be disabled.
169 // It's in a function rather than just a compile-time assignment to the
170 // bootloader structure because our C++ compiler doesn't support non-trivial
171 // designated initializers.
pc_init_debug_default_early()172 void pc_init_debug_default_early() {
173     bootloader.uart.type = ZBI_UART_NONE;
174 }
175 
handle_serial_cmdline()176 static void handle_serial_cmdline() {
177     const char* serial_mode = cmdline_get("kernel.serial");
178     if (serial_mode == NULL) {
179         return;
180     }
181     if (!strcmp(serial_mode, "none")) {
182         bootloader.uart.type = ZBI_UART_NONE;
183         return;
184     }
185     if (!strcmp(serial_mode, "legacy")) {
186         bootloader.uart.type = ZBI_UART_PC_PORT;
187         bootloader.uart.base = 0x3f8;
188         bootloader.uart.irq = ISA_IRQ_SERIAL1;
189         return;
190     }
191 
192     // type can be "ioport" or "mmio"
193     constexpr size_t kMaxTypeLen = 6 + 1;
194     char type_buf[kMaxTypeLen];
195     // Addr can be up to 32 characters (numeric in any base strtoul will take),
196     // and + 1 for \0
197     constexpr size_t kMaxAddrLen = 32 + 1;
198     char addr_buf[kMaxAddrLen];
199 
200     char* endptr;
201     const char* addr_start;
202     const char* irq_start;
203     size_t addr_len, type_len;
204     unsigned long irq_val;
205 
206     addr_start = strchr(serial_mode, ',');
207     if (addr_start == nullptr) {
208         goto bail;
209     }
210     addr_start++;
211     irq_start = strchr(addr_start, ',');
212     if (irq_start == nullptr) {
213         goto bail;
214     }
215     irq_start++;
216 
217     // Parse out the type part
218     type_len = addr_start - serial_mode - 1;
219     if (type_len + 1 > kMaxTypeLen) {
220         goto bail;
221     }
222     memcpy(type_buf, serial_mode, type_len);
223     type_buf[type_len] = 0;
224     if (!strcmp(type_buf, "ioport")) {
225         bootloader.uart.type = ZBI_UART_PC_PORT;
226     } else if (!strcmp(type_buf, "mmio")) {
227         bootloader.uart.type = ZBI_UART_PC_MMIO;
228     } else {
229         goto bail;
230     }
231 
232     // Parse out the address part
233     addr_len = irq_start - addr_start - 1;
234     if (addr_len + 1 > kMaxAddrLen) {
235         goto bail;
236     }
237     memcpy(addr_buf, addr_start, addr_len);
238     addr_buf[addr_len] = 0;
239     bootloader.uart.base = strtoul(addr_buf, &endptr, 0);
240     if (endptr != addr_buf + addr_len) {
241         goto bail;
242     }
243 
244     // Parse out the IRQ part
245     irq_val = strtoul(irq_start, &endptr, 0);
246     if (*endptr != '\0' || irq_val > UINT32_MAX) {
247         goto bail;
248     }
249     // For now, we don't support non-ISA IRQs
250     if (irq_val >= NUM_ISA_IRQS) {
251         goto bail;
252     }
253     bootloader.uart.irq = static_cast<uint32_t>(irq_val);
254     return;
255 
256 bail:
257     bootloader.uart.type = ZBI_UART_NONE;
258     return;
259 }
260 
pc_init_debug_early()261 void pc_init_debug_early() {
262     handle_serial_cmdline();
263 
264     switch (bootloader.uart.type) {
265     case ZBI_UART_PC_PORT:
266         uart_io_port = static_cast<uint32_t>(bootloader.uart.base);
267         uart_irq = bootloader.uart.irq;
268         break;
269     case ZBI_UART_PC_MMIO:
270         uart_mem_addr = (uint64_t)paddr_to_physmap(bootloader.uart.base);
271         uart_irq = bootloader.uart.irq;
272         break;
273     case ZBI_UART_NONE: // fallthrough
274     default:
275         bootloader.uart.type = ZBI_UART_NONE;
276         return;
277     }
278 
279     init_uart();
280 
281     output_enabled = true;
282 
283     dprintf(INFO, "UART: FIFO depth %u\n", uart_fifo_depth);
284 }
285 
pc_init_debug(void)286 void pc_init_debug(void) {
287     bool tx_irq_driven = false;
288     /* finish uart init to get rx going */
289     cbuf_initialize(&console_input_buf, 1024);
290 
291     if (!platform_serial_enabled()) {
292         // Need to bail after initializing the input_buf to prevent uninitialized
293         // access to it.
294         return;
295     }
296 
297     if ((uart_irq == 0) || cmdline_get_bool("kernel.debug_uart_poll", false) ||
298         dlog_bypass()) {
299         printf("debug-uart: polling enabled\n");
300         platform_debug_start_uart_timer();
301     } else {
302         uart_irq = apic_io_isa_to_global(static_cast<uint8_t>(uart_irq));
303         zx_status_t status = register_int_handler(uart_irq, uart_irq_handler, NULL);
304         DEBUG_ASSERT(status == ZX_OK);
305         unmask_interrupt(uart_irq);
306 
307         uart_write(1, (1<<0)); // enable receive data available interrupt
308 
309         // modem control register: Auxiliary Output 2 is another IRQ enable bit
310         const uint8_t mcr = uart_read(4);
311         uart_write(4, mcr | 0x8);
312         printf("UART: started IRQ driven RX\n");
313         tx_irq_driven = true;
314     }
315     if (tx_irq_driven) {
316         // start up tx driven output
317         printf("UART: started IRQ driven TX\n");
318         uart_tx_irq_enabled = true;
319     }
320 }
321 
pc_suspend_debug(void)322 void pc_suspend_debug(void) {
323     output_enabled = false;
324 }
325 
pc_resume_debug(void)326 void pc_resume_debug(void) {
327     if (platform_serial_enabled()) {
328         init_uart();
329         output_enabled = true;
330     }
331 }
332 
333 /*
334  * This is called when the FIFO is detected to be empty. So we can write an
335  * entire FIFO's worth of bytes. Much more efficient than writing 1 byte
336  * at a time (and then checking for FIFO to drain).
337  */
debug_platform_tx_FIFO_bytes(const char * str,size_t * len,bool * copied_CR,size_t * wrote_bytes,bool map_NL)338 static char *debug_platform_tx_FIFO_bytes(const char *str, size_t *len,
339                                           bool *copied_CR,
340                                           size_t *wrote_bytes,
341                                           bool map_NL)
342 {
343     size_t i, copy_bytes;;
344     char *s = (char *)str;
345 
346     copy_bytes = MIN(uart_fifo_depth, *len);
347     for (i = 0 ; i < copy_bytes ; i++) {
348         if (*s == '\n' && map_NL && !*copied_CR) {
349             uart_write(0, '\r');
350             *copied_CR = true;
351             if (++i == copy_bytes)
352                 break;
353             uart_write(0, '\n');
354         } else {
355             uart_write(0, *s);
356             *copied_CR = false;
357         }
358         s++;
359         (*len)--;
360     }
361     if (wrote_bytes != NULL)
362         *wrote_bytes = i;
363     return s;
364 }
365 
366 /*
367  * dputs() Tx is either polling driven (if the caller is non-preemptible
368  * or earlyboot or panic) or blocking (and irq driven).
369  * TODO - buffered Tx support may be a win, (lopri but worth investigating)
370  * When we do that dputs() can be completely asynchronous, and return when
371  * the write has been (atomically) deposited into the buffer, except when
372  * we run out of room in the Tx buffer (rare) - we'd either need to spin
373  * (if non-blocking) or block waiting for space in the Tx buffer (adding
374  * support to optionally block in cbuf_write_char() would be easiest way
375  * to achieve that).
376  *
377  * block : Blocking vs Non-Blocking
378  * map_NL : If true, map a '\n' to '\r'+'\n'
379  */
platform_dputs(const char * str,size_t len,bool block,bool map_NL)380 static void platform_dputs(const char* str, size_t len,
381                            bool block, bool map_NL) {
382     spin_lock_saved_state_t state;
383     bool copied_CR = false;
384     size_t wrote;
385 
386     // drop strings if we haven't initialized the uart yet
387     if (unlikely(!output_enabled))
388         return;
389     if (!uart_tx_irq_enabled)
390         block = false;
391     spin_lock_irqsave(&uart_spinlock, state);
392     while (len > 0) {
393         // Is FIFO empty ?
394         while (!(uart_read(5) & (1<<5))) {
395             if (block) {
396                 /*
397                  * We want to Tx more and FIFO is empty, re-enable
398                  * Tx interrupts before blocking.
399                  */
400                 uart_write(1, (1<<0)|(1<<1)); // rx and tx interrupt enable
401                 spin_unlock_irqrestore(&uart_spinlock, state);
402                 event_wait(&uart_dputc_event);
403             } else {
404                 spin_unlock_irqrestore(&uart_spinlock, state);
405                 arch_spinloop_pause();
406             }
407             spin_lock_irqsave(&uart_spinlock, state);
408         }
409         // Fifo is completely empty now, we can shove an entire
410         // fifo's worth of Tx...
411         str = debug_platform_tx_FIFO_bytes(str, &len, &copied_CR,
412                                            &wrote, map_NL);
413         if (block && wrote > 0) {
414             // If blocking/irq driven wakeps, enable rx/tx intrs
415             uart_write(1, (1<<0)|(1<<1)); // rx and tx interrupt enable
416         }
417     }
418     spin_unlock_irqrestore(&uart_spinlock, state);
419 }
420 
platform_dputs_thread(const char * str,size_t len)421 void platform_dputs_thread(const char* str, size_t len) {
422     if (platform_serial_enabled()) {
423         platform_dputs(str, len, true, true);
424     }
425 }
426 
platform_dputs_irq(const char * str,size_t len)427 void platform_dputs_irq(const char* str, size_t len) {
428     if (platform_serial_enabled()) {
429         platform_dputs(str, len, false, true);
430     }
431 }
432 
433 // polling versions of debug uart read/write
debug_uart_getc_poll(char * c)434 static int debug_uart_getc_poll(char *c) {
435     // if there is a character available, read it
436     if (uart_read(5) & (1<<0)) {
437         *c = uart_read(0);
438         return 0;
439     }
440 
441     return -1;
442 }
443 
debug_uart_putc_poll(char c)444 static void debug_uart_putc_poll(char c) {
445     // while the fifo is non empty, spin
446     while (!(uart_read(5) & (1<<6))) {
447         arch_spinloop_pause();
448     }
449     uart_write(0, c);
450 }
451 
452 
platform_dgetc(char * c,bool wait)453 int platform_dgetc(char* c, bool wait) {
454     if (platform_serial_enabled()) {
455         return static_cast<int>(cbuf_read_char(&console_input_buf, c, wait));
456     }
457     return ZX_ERR_NOT_SUPPORTED;
458 }
459 
460 // panic time polling IO for the panic shell
platform_pputc(char c)461 void platform_pputc(char c) {
462     if (platform_serial_enabled()) {
463         if (c == '\n')
464             debug_uart_putc_poll('\r');
465         debug_uart_putc_poll(c);
466     }
467 }
468 
platform_pgetc(char * c,bool wait)469 int platform_pgetc(char *c, bool wait) {
470     if (platform_serial_enabled()) {
471         return debug_uart_getc_poll(c);
472     }
473     return ZX_ERR_NOT_SUPPORTED;
474 }
475 
476 /*
477  * Called on start of a panic.
478  * When we do Tx buffering, drain the Tx buffer here in polling mode.
479  * Turn off Tx interrupts, so force Tx be polling from this point
480  */
platform_debug_panic_start(void)481 void platform_debug_panic_start(void) {
482     uart_tx_irq_enabled = false;
483 }
484