1 /*
2 * Copyright (c) 2000-2020 Apple Inc. All rights reserved.
3 *
4 * This file contains the low-level serial drivers used on ARM/ARM64 devices.
5 * The generic serial console code in osfmk/console/serial_console.c will call
6 * into this code to transmit and receive serial data.
7 *
8 * Logging can be performed on multiple serial interfaces at once through a
9 * method called serial multiplexing. This is implemented by enumerating which
10 * serial interfaces are available on boot and registering them into a linked
11 * list of interfaces pointed to by gPESF. When outputting or receiving
12 * characters, each interface is queried in turn.
13 *
14 * Please view doc/arm_serial.md for an in-depth description of these drivers.
15 */
16 #include <kern/clock.h>
17 #include <kern/debug.h>
18 #include <libkern/OSBase.h>
19 #include <libkern/section_keywords.h>
20 #include <mach/mach_time.h>
21 #include <machine/atomic.h>
22 #include <machine/machine_routines.h>
23 #include <pexpert/pexpert.h>
24 #include <pexpert/protos.h>
25 #include <pexpert/device_tree.h>
26 #include <pexpert/arm/consistent_debug.h>
27 #include <pexpert/arm64/board_config.h>
28 #include <arm64/proc_reg.h>
29 #include <pexpert/arm/protos.h>
30 #include <kern/sched_prim.h>
31 #ifdef PL011_UART
32 #include <pexpert/arm/pl011.h>
33 #endif /* PL011_UART */
34 #if HIBERNATION
35 #include <machine/pal_hibernate.h>
36 #endif /* HIBERNATION */
37
38 struct pe_serial_functions {
39 /* Initialize the underlying serial hardware. */
40 void (*init) (void);
41
42 /* Return a non-zero value if the serial interface is ready to send more data. */
43 unsigned int (*transmit_ready) (void);
44
45 /* Write a single byte of data to serial. */
46 void (*transmit_data) (uint8_t c);
47
48 /* Return a non-zero value if there's a byte of data available. */
49 unsigned int (*receive_ready) (void);
50
51 /* Read a single byte from serial. */
52 uint8_t (*receive_data) (void);
53
54 /* Enables IRQs from this device. */
55 void (*enable_irq) (void);
56
57 /* Disables IRQs from this device and reports whether IRQs were enabled. */
58 bool (*disable_irq) (void);
59
60 /* Clears this device's IRQs targeting this agent, returning true if at least one IRQ was cleared. */
61 bool (*acknowledge_irq) (void);
62
63 /**
64 * Whether this serial driver can handle irqs. This value should be set by
65 * querying the device tree to see if the serial device has interrupts
66 * associated with it.
67 *
68 * For a device to support IRQs:
69 * - enable_irq, disable_irq, and acknowledge_irq must be non-null
70 * - The AppleSerialShim kext must be able to match to the serial device
71 * in the IORegistry and call serial_enable_irq with the proper
72 * serial_device_t
73 * - The device tree entry for the serial device should have an interrupt
74 * associated with it.
75 */
76 bool has_irq;
77
78 /* enum identifying which serial device these functions belong to. */
79 serial_device_t device;
80
81 /* Pointer to the next serial interface in the linked-list. */
82 struct pe_serial_functions *next;
83 };
84
85 MARK_AS_HIBERNATE_DATA_CONST_LATE static struct pe_serial_functions* gPESF = NULL;
86
87 /**
88 * Whether uart has been initialized already. This value is kept across a
89 * sleep/wake cycle so we know we need to reinitialize when serial_init is
90 * called again after wake.
91 */
92 MARK_AS_HIBERNATE_DATA static bool uart_initted = false;
93
94 /* Whether uart should run in simple mode that works during hibernation resume. */
95 MARK_AS_HIBERNATE_DATA bool uart_hibernation = false;
96
97 /** Set <=> transmission is authorized.
98 * Always set, unless SERIALMODE_ON_DEMAND is provided at boot,
99 * and no data has yet been received.
100 * Originaly meant to be a per-pe_serial_functions variable,
101 * but the data protection on the structs prevents it. */
102 static bool serial_do_transmit = 1;
103
104 /**
105 * Used to track if all IRQs have been initialized. Each bit of this variable
106 * represents whether or not a serial device that reports supporting IRQs has
107 * been initialized yet (1 -> not initialized, 0 -> initialized)
108 */
109 static uint32_t serial_irq_status = 0;
110
111 /**
112 * Set by the 'disable-uart-irq' boot-arg to force serial IRQs into polling mode
113 * by preventing the serial driver shim kext from registering itself with
114 * serial_enable_irq.
115 */
116 static bool disable_uart_irq = 0;
117
118 static void
register_serial_functions(struct pe_serial_functions * fns)119 register_serial_functions(struct pe_serial_functions *fns)
120 {
121 fns->next = gPESF;
122 gPESF = fns;
123 }
124
125 /**
126 * Indicates whether or not a given device's irqs have been set up by calling
127 * serial_enable_irq for that particular device.
128 *
129 * @param device_fns Serial functions for the device that is being checked
130 * @return Whether or not the irqs have been initialized for that device
131 */
132 static bool
irq_initialized(struct pe_serial_functions * device_fns)133 irq_initialized(struct pe_serial_functions *device_fns)
134 {
135 return (serial_irq_status & device_fns->device) == 0;
136 }
137
138 /**
139 * Indicates whether or not a given device supports irqs and if they are ready
140 * to be used.
141 *
142 * @param device_fns Serial functions for the device that is being checked
143 * @return Whether or not the device can and will send IRQs.
144 */
145 static bool
irq_available_and_ready(struct pe_serial_functions * device_fns)146 irq_available_and_ready(struct pe_serial_functions *device_fns)
147 {
148 return device_fns->has_irq && irq_initialized(device_fns);
149 }
150
151 /**
152 * Searches through the global serial functions list and returns the serial function for a particular device
153 *
154 * @param device The device identifier to search for
155 * @return Serial functions for the specified device
156 */
157 static struct pe_serial_functions *
get_serial_functions(serial_device_t device)158 get_serial_functions(serial_device_t device)
159 {
160 struct pe_serial_functions *fns = gPESF;
161 while (fns != NULL) {
162 if (fns->device == device) {
163 return fns;
164 }
165 fns = fns->next;
166 }
167 return NULL;
168 }
169
170 /**
171 * The action to take when polling and waiting for a serial device to be ready
172 * for output. On ARM64, takes a WFE because the WFE timeout will wake us up in
173 * the worst case. On ARMv7 devices, we need to hot poll.
174 */
175 static inline void
serial_poll(void)176 serial_poll(void)
177 {
178 #if __arm64__
179 if (!uart_hibernation) {
180 __builtin_arm_wfe();
181 }
182 #endif
183 }
184
185 /**
186 * This ensures that if we have a future product that supports hibernation, but
187 * doesn't support either UART serial or dock-channels, then hibernation will
188 * gracefully fall back to the serial method that is supported.
189 */
190 #if HIBERNATION || defined(APPLE_UART)
191 MARK_AS_HIBERNATE_DATA static volatile apple_uart_registers_t *apple_uart_registers = 0;
192 #endif /* HIBERNATION || defined(APPLE_UART) */
193
194 #if HIBERNATION || defined(DOCKCHANNEL_UART)
195 MARK_AS_HIBERNATE_DATA static vm_offset_t dockchannel_uart_base = 0;
196 #endif /* HIBERNATION || defined(DOCKCHANNEL_UART) */
197
198 #ifdef PL011_UART
199 static volatile pl011_registers_t *pl011_registers = NULL;
200 #endif /* PL011_UART */
201
202 /*****************************************************************************/
203
204 #ifdef APPLE_UART
205 static void apple_uart_set_baud_rate(uint32_t baud_rate);
206
207 /**
208 * The Apple UART is configured to use 115200-8-N-1 communication.
209 */
210 static void
apple_uart_init(void)211 apple_uart_init(void)
212 {
213 ucon_t ucon = { .raw = 0 };
214 // Use NCLK (which is constant) instead of PCLK (which is variable).
215 ucon.clock_selection = UCON_CLOCK_SELECTION_NCLK;
216 ucon.transmit_mode = UCON_TRANSMIT_MODE_INTERRUPT_OR_POLLING;
217 ucon.receive_mode = UCON_RECEIVE_MODE_INTERRUPT_OR_POLLING;
218 ml_io_write32((uintptr_t) &apple_uart_registers->ucon, ucon.raw);
219
220 // Configure 8-N-1 communication.
221 ulcon_t ulcon = { .raw = 0 };
222 ulcon.word_length = ULCON_WORD_LENGTH_8_BITS;
223 ulcon.parity_mode = ULCON_PARITY_MODE_NONE;
224 ulcon.number_of_stop_bits = ULCON_STOP_BITS_1;
225 ml_io_write32((uintptr_t) &apple_uart_registers->ulcon, ulcon.raw);
226
227 apple_uart_set_baud_rate(115200);
228
229 // Enable and reset FIFOs.
230 ufcon_t ufcon = { .raw = 0 };
231 ufcon.fifo_enable = 1;
232 ufcon.tx_fifo_reset = 1;
233 ufcon.rx_fifo_reset = 1;
234 ml_io_write32((uintptr_t) &apple_uart_registers->ufcon, ufcon.raw);
235 }
236
237 static void
apple_uart_enable_irq(void)238 apple_uart_enable_irq(void)
239 {
240 // Set the Tx FIFO interrupt trigger level to 0 bytes so interrupts occur when
241 // the Tx FIFO is completely empty; this leads to higher Tx throughput.
242 ufcon_t ufcon = { .raw = ml_io_read32((uintptr_t) &apple_uart_registers->ufcon) };
243 ufcon.tx_fifo_interrupt_trigger_level_dma_watermark = UFCON_TX_FIFO_ITL_0_BYTES;
244 ml_io_write32((uintptr_t) &apple_uart_registers->ufcon, ufcon.raw);
245
246 // Enable Tx interrupts.
247 ucon_t ucon = { .raw = ml_io_read32((uintptr_t) &apple_uart_registers->ucon) };
248 ucon.transmit_interrupt = 1;
249 ml_io_write32((uintptr_t) &apple_uart_registers->ucon, ucon.raw);
250 }
251
252 static bool
apple_uart_disable_irq(void)253 apple_uart_disable_irq(void)
254 {
255 /* Disables Tx interrupts */
256 ucon_t ucon = { .raw = ml_io_read32((uintptr_t) &apple_uart_registers->ucon) };
257 const bool irqs_were_enabled = ucon.transmit_interrupt;
258
259 if (irqs_were_enabled) {
260 ucon.transmit_interrupt = 0;
261 ml_io_write32((uintptr_t) &apple_uart_registers->ucon, ucon.raw);
262 }
263
264 return irqs_were_enabled;
265 }
266
267 static bool
apple_uart_ack_irq(void)268 apple_uart_ack_irq(void)
269 {
270 utrstat_t utrstat = { .raw = 0 };
271 utrstat.transmit_interrupt_status = 1;
272 ml_io_write32((uintptr_t) &apple_uart_registers->utrstat, utrstat.raw);
273 return true;
274 }
275
276 static inline bool
apple_uart_fifo_is_empty(void)277 apple_uart_fifo_is_empty(void)
278 {
279 const ufstat_t ufstat = { .raw = ml_io_read32((uintptr_t) &apple_uart_registers->ufstat) };
280 return !(ufstat.tx_fifo_full || ufstat.tx_fifo_count);
281 }
282
283 static void
apple_uart_drain_fifo(void)284 apple_uart_drain_fifo(void)
285 {
286 while (!apple_uart_fifo_is_empty()) {
287 serial_poll();
288 }
289 }
290
291 static void
apple_uart_set_baud_rate(uint32_t baud_rate)292 apple_uart_set_baud_rate(uint32_t baud_rate)
293 {
294 // Maximum error tolerated from the target baud rate (measured in percentage
295 // points). Anything greater than this will trigger a kernel panic because
296 // UART communication will not be reliable.
297 const float kMaxErrorPercentage = 2.75;
298
299 // The acceptable sample rate range; higher sample rates are typically more
300 // desirable because you can more quickly detect the start bit.
301 const int kMinSampleRate = 10;
302 const int kMaxSampleRate = 16;
303
304 // Find the first configuration that achieves the target baud rate accuracy,
305 // starting with the highest sample rate.
306 const float kSourceClock = gPEClockFrequencyInfo.fix_frequency_hz;
307 int ubr_div = 0;
308 int sample_rate = 0;
309 bool found_configuration = false;
310 for (int _sample_rate = kMaxSampleRate; _sample_rate >= kMinSampleRate; _sample_rate--) {
311 const float ideal_ubr_div = (kSourceClock / (baud_rate * _sample_rate)) - 1;
312 if ((ideal_ubr_div - (int)ideal_ubr_div) < 0.00001f) {
313 // The ideal baud rate divisor is (basically) attainable.
314 ubr_div = (int)ideal_ubr_div;
315 sample_rate = _sample_rate;
316 found_configuration = true;
317 break;
318 } else {
319 // The ideal baud rate divisor is not attainable; try rounding.
320 const int ubr_div_rounded_down = (int)ideal_ubr_div;
321 const int ubr_div_rounded_up = ubr_div_rounded_down + 1;
322 const float higher_baud_rate = kSourceClock / ((ubr_div_rounded_down + 1) * _sample_rate);
323 const float lower_baud_rate = kSourceClock / ((ubr_div_rounded_up + 1) * _sample_rate);
324 if ((((higher_baud_rate - baud_rate) / baud_rate) * 100) < kMaxErrorPercentage) {
325 ubr_div = ubr_div_rounded_down;
326 sample_rate = _sample_rate;
327 found_configuration = true;
328 break;
329 }
330 if ((((baud_rate - lower_baud_rate) / baud_rate) * 100) < kMaxErrorPercentage) {
331 ubr_div = ubr_div_rounded_up;
332 sample_rate = _sample_rate;
333 found_configuration = true;
334 break;
335 }
336 }
337 }
338
339 if (!found_configuration) {
340 panic("Unable to find a configuration for the UART that would result in a nominal baud rate close enough to %u", baud_rate);
341 }
342
343 // Found an acceptable configuration; write this to the register.
344 ubrdiv_t ubrdiv = { .raw = 0 };
345 ubrdiv.sample_rate = 16 - sample_rate;
346 assert((0 <= ubr_div) && (ubr_div <= UINT16_MAX));
347 ubrdiv.ubr_div = ubr_div;
348 ml_io_write32((uintptr_t) &apple_uart_registers->ubrdiv, ubrdiv.raw);
349 }
350
351 MARK_AS_HIBERNATE_TEXT static unsigned int
apple_uart_transmit_ready(void)352 apple_uart_transmit_ready(void)
353 {
354 ufstat_t ufstat = { .raw = ml_io_read32((uintptr_t) &apple_uart_registers->ufstat) };
355 return !ufstat.tx_fifo_full;
356 }
357
358 MARK_AS_HIBERNATE_TEXT static void
apple_uart_transmit_data(uint8_t c)359 apple_uart_transmit_data(uint8_t c)
360 {
361 utxh_t utxh = { .txdata = c };
362 ml_io_write32((uintptr_t) &apple_uart_registers->utxh, utxh.raw);
363 }
364
365 static unsigned int
apple_uart_receive_ready(void)366 apple_uart_receive_ready(void)
367 {
368 ufstat_t ufstat = { .raw = ml_io_read32((uintptr_t) &apple_uart_registers->ufstat) };
369 return ufstat.rx_fifo_full || ufstat.rx_fifo_count;
370 }
371
372 static uint8_t
apple_uart_receive_data(void)373 apple_uart_receive_data(void)
374 {
375 urxh_t urxh = { .raw = ml_io_read32((uintptr_t) &apple_uart_registers->urxh) };
376 return urxh.rxdata;
377 }
378
379 MARK_AS_HIBERNATE_DATA_CONST_LATE
380 static struct pe_serial_functions apple_serial_functions =
381 {
382 .init = apple_uart_init,
383 .transmit_ready = apple_uart_transmit_ready,
384 .transmit_data = apple_uart_transmit_data,
385 .receive_ready = apple_uart_receive_ready,
386 .receive_data = apple_uart_receive_data,
387 .enable_irq = apple_uart_enable_irq,
388 .disable_irq = apple_uart_disable_irq,
389 .acknowledge_irq = apple_uart_ack_irq,
390 .device = SERIAL_APPLE_UART
391 };
392
393 static void
apple_uart_setup(const DeviceTreeNode * const devicetree_node)394 apple_uart_setup(const DeviceTreeNode *const devicetree_node)
395 {
396 // Get the physical address range of the Apple UART register block.
397 const struct {
398 uint64_t block_offset; // TODO: make this scale with #address-cells
399 uint64_t block_size; // TODO: make this scale with #size-cells
400 } *reg;
401 unsigned int reg_size;
402 if (SecureDTGetProperty(devicetree_node, "reg", (const void **)®, ®_size) != kSuccess) {
403 panic("Unable to find the 'reg' property on the Apple UART devicetree node");
404 }
405 assert(reg_size == sizeof(*reg));
406
407 // Create a virtual mapping to that physical address range.
408 const vm_offset_t soc_base_phys = pe_arm_get_soc_base_phys();
409 apple_uart_registers = (apple_uart_registers_t *)ml_io_map(soc_base_phys + reg->block_offset, reg->block_size);
410
411 // Check if interrupts are supported.
412 const void *unused;
413 unsigned int unused_size;
414 if (SecureDTGetProperty(devicetree_node, "interrupts", &unused, &unused_size) == kSuccess) {
415 apple_serial_functions.has_irq = true;
416 }
417
418 // Register the Apple UART serial driver.
419 register_serial_functions(&apple_serial_functions);
420 }
421
422 #endif /* APPLE_UART */
423
424 /*****************************************************************************/
425
426 #ifdef DOCKCHANNEL_UART
427 #define DOCKCHANNEL_WR_MAX_STALL_US (30*1000)
428
429 static vm_offset_t dock_agent_base;
430 static uint32_t max_dockchannel_drain_period;
431 static uint64_t dockchannel_drain_deadline; // Deadline for external agent to drain before a software drain occurs
432 static bool use_sw_drain;
433 static uint32_t dock_wstat_mask;
434 static uint64_t prev_dockchannel_spaces; // Previous w_stat level of the DockChannel.
435 static uint64_t dockchannel_stall_grace;
436 MARK_AS_HIBERNATE_DATA static bool use_sw_drain;
437 MARK_AS_HIBERNATE_DATA static uint32_t dock_wstat_mask;
438
439 // forward reference
440 static struct pe_serial_functions dockchannel_serial_functions;
441
442 //=======================
443 // Local funtions
444 //=======================
445
446 static void
dockchannel_setup(const DeviceTreeNode * const devicetree_node)447 dockchannel_setup(const DeviceTreeNode *const devicetree_node)
448 {
449 // Get the physical address ranges of the Dock Channels register blocks.
450 const struct {
451 uint64_t channels_block_offset; // TODO: make this scale with #address-cells
452 uint64_t channels_block_size; // TODO: make this scale with #size-cells
453 uint64_t agents_block_offset; // TODO: make this scale with #address-cells
454 uint64_t agents_block_size; // TODO: make this scale with #size-cells
455 } *reg;
456 unsigned int reg_size;
457 if (SecureDTGetProperty(devicetree_node, "reg", (const void **)®, ®_size) != kSuccess) {
458 panic("Unable to find the 'reg' property on the Dock Channels devicetree node");
459 }
460 assert(reg_size == sizeof(*reg));
461
462 // Create virtual mappings for those physical address rangess.
463 const vm_offset_t soc_base_phys = pe_arm_get_soc_base_phys();
464 dockchannel_uart_base = ml_io_map(soc_base_phys + reg->channels_block_offset, reg->channels_block_size);
465 dock_agent_base = ml_io_map(soc_base_phys + reg->agents_block_offset, reg->agents_block_size);
466
467 // Configure various Dock Channels settings.
468 const uint32_t *max_aop_clk;
469 unsigned int max_aop_clk_size;
470 if (SecureDTGetProperty(devicetree_node, "max-aop-clk", (const void **)&max_aop_clk, &max_aop_clk_size) == kSuccess) {
471 assert(max_aop_clk_size == sizeof(*max_aop_clk));
472 max_dockchannel_drain_period = (uint32_t)(*max_aop_clk * 0.03);
473 } else {
474 max_dockchannel_drain_period = (uint32_t)DOCKCHANNEL_DRAIN_PERIOD;
475 }
476 const uint32_t *enable_sw_drain;
477 unsigned int enable_sw_drain_size;
478 if (SecureDTGetProperty(devicetree_node, "enable-sw-drain", (const void **)&enable_sw_drain, &enable_sw_drain_size) == kSuccess) {
479 assert(enable_sw_drain_size == sizeof(*enable_sw_drain));
480 use_sw_drain = *enable_sw_drain;
481 } else {
482 use_sw_drain = 0;
483 }
484 const uint32_t *_dock_wstat_mask;
485 unsigned int dock_wstat_mask_size;
486 if (SecureDTGetProperty(devicetree_node, "dock-wstat-mask", (const void **)&_dock_wstat_mask, &dock_wstat_mask_size) == kSuccess) {
487 assert(dock_wstat_mask_size == sizeof(*_dock_wstat_mask));
488 dock_wstat_mask = *_dock_wstat_mask;
489 } else {
490 dock_wstat_mask = 0x1ff;
491 }
492 const void *unused;
493 unsigned int unused_size;
494 if (SecureDTGetProperty(devicetree_node, "interrupts", &unused, &unused_size) == kSuccess) {
495 dockchannel_serial_functions.has_irq = true;
496 }
497 prev_dockchannel_spaces = rDOCKCHANNELS_DEV_WSTAT(DOCKCHANNEL_UART_CHANNEL) & dock_wstat_mask;
498 dockchannel_drain_deadline = mach_absolute_time() + dockchannel_stall_grace;
499
500 // Register the Dock Channels serial driver.
501 register_serial_functions(&dockchannel_serial_functions);
502 }
503
504 static int
dockchannel_drain_on_stall()505 dockchannel_drain_on_stall()
506 {
507 // Called when DockChannel runs out of spaces.
508 // Check if the DockChannel reader has stalled. If so, empty the DockChannel ourselves.
509 // Return number of bytes drained.
510
511 if (mach_absolute_time() >= dockchannel_drain_deadline) {
512 // It's been more than DOCKCHANEL_WR_MAX_STALL_US and nobody read from the FIFO
513 // Drop a character.
514 (void)rDOCKCHANNELS_DOCK_RDATA1(DOCKCHANNEL_UART_CHANNEL);
515 os_atomic_inc(&prev_dockchannel_spaces, relaxed);
516 return 1;
517 }
518 return 0;
519 }
520
521 static void
dockchannel_clear_intr(void)522 dockchannel_clear_intr(void)
523 {
524 rDOCKCHANNELS_AGENT_AP_INTR_CTRL &= ~(0x3);
525 rDOCKCHANNELS_AGENT_AP_INTR_STATUS |= 0x3;
526 rDOCKCHANNELS_AGENT_AP_ERR_INTR_CTRL &= ~(0x3);
527 rDOCKCHANNELS_AGENT_AP_ERR_INTR_STATUS |= 0x3;
528 }
529
530 static bool
dockchannel_disable_irq(void)531 dockchannel_disable_irq(void)
532 {
533 const uint32_t ap_intr_ctrl = rDOCKCHANNELS_AGENT_AP_INTR_CTRL;
534 const bool irqs_were_enabled = ap_intr_ctrl & 0x1;
535 if (irqs_were_enabled) {
536 rDOCKCHANNELS_AGENT_AP_INTR_CTRL = ap_intr_ctrl & ~(0x1);
537 }
538 return irqs_were_enabled;
539 }
540
541 static void
dockchannel_enable_irq(void)542 dockchannel_enable_irq(void)
543 {
544 // set interrupt to be when fifo has 255 empty
545 rDOCKCHANNELS_DEV_WR_WATERMARK(DOCKCHANNEL_UART_CHANNEL) = 0xFF;
546 rDOCKCHANNELS_AGENT_AP_INTR_CTRL |= 0x1;
547 }
548
549 static bool
dockchannel_ack_irq(void)550 dockchannel_ack_irq(void)
551 {
552 /* First check if the IRQ is for the kernel */
553 if (rDOCKCHANNELS_AGENT_AP_INTR_STATUS & 0x1) {
554 rDOCKCHANNELS_AGENT_AP_INTR_STATUS |= 0x1;
555 return true;
556 }
557 return false;
558 }
559
560 MARK_AS_HIBERNATE_TEXT static void
dockchannel_transmit_data(uint8_t c)561 dockchannel_transmit_data(uint8_t c)
562 {
563 rDOCKCHANNELS_DEV_WDATA1(DOCKCHANNEL_UART_CHANNEL) = (unsigned)c;
564
565 if (use_sw_drain && !uart_hibernation) {
566 os_atomic_dec(&prev_dockchannel_spaces, relaxed); // After writing a byte we have one fewer space than previously expected.
567 }
568 }
569
570 static unsigned int
dockchannel_receive_ready(void)571 dockchannel_receive_ready(void)
572 {
573 return rDOCKCHANNELS_DEV_RDATA0(DOCKCHANNEL_UART_CHANNEL) & 0x7f;
574 }
575
576 static uint8_t
dockchannel_receive_data(void)577 dockchannel_receive_data(void)
578 {
579 return (uint8_t)((rDOCKCHANNELS_DEV_RDATA1(DOCKCHANNEL_UART_CHANNEL) >> 8) & 0xff);
580 }
581
582 MARK_AS_HIBERNATE_TEXT static unsigned int
dockchannel_transmit_ready(void)583 dockchannel_transmit_ready(void)
584 {
585 uint32_t spaces = rDOCKCHANNELS_DEV_WSTAT(DOCKCHANNEL_UART_CHANNEL) & dock_wstat_mask;
586
587 if (!uart_hibernation) {
588 if (use_sw_drain) {
589 if (spaces > prev_dockchannel_spaces) {
590 // More spaces showed up. That can only mean someone read the FIFO.
591 // Note that if the DockFIFO is empty we cannot tell if someone is listening,
592 // we can only give them the benefit of the doubt.
593 dockchannel_drain_deadline = mach_absolute_time() + dockchannel_stall_grace;
594 }
595 prev_dockchannel_spaces = spaces;
596 return spaces || dockchannel_drain_on_stall();
597 }
598 }
599
600 return spaces;
601 }
602
603 static void
dockchannel_init(void)604 dockchannel_init(void)
605 {
606 if (use_sw_drain) {
607 nanoseconds_to_absolutetime(DOCKCHANNEL_WR_MAX_STALL_US * NSEC_PER_USEC, &dockchannel_stall_grace);
608 }
609
610 // Clear all interrupt enable and status bits
611 dockchannel_clear_intr();
612
613 // Setup DRAIN timer
614 rDOCKCHANNELS_DEV_DRAIN_CFG(DOCKCHANNEL_UART_CHANNEL) = max_dockchannel_drain_period;
615
616 // Drain timer doesn't get loaded with value from drain period register if fifo
617 // is already full. Drop a character from the fifo.
618 rDOCKCHANNELS_DOCK_RDATA1(DOCKCHANNEL_UART_CHANNEL);
619 }
620
621 MARK_AS_HIBERNATE_DATA_CONST_LATE
622 static struct pe_serial_functions dockchannel_serial_functions =
623 {
624 .init = dockchannel_init,
625 .transmit_ready = dockchannel_transmit_ready,
626 .transmit_data = dockchannel_transmit_data,
627 .receive_ready = dockchannel_receive_ready,
628 .receive_data = dockchannel_receive_data,
629 .enable_irq = dockchannel_enable_irq,
630 .disable_irq = dockchannel_disable_irq,
631 .acknowledge_irq = dockchannel_ack_irq,
632 .device = SERIAL_DOCKCHANNEL
633 };
634
635 #endif /* DOCKCHANNEL_UART */
636
637 /*****************************************************************************/
638
639 #ifdef PL011_UART
640
641 static unsigned int
pl011_uart_transmit_ready(void)642 pl011_uart_transmit_ready(void)
643 {
644 const uartfr_t uartfr = { .raw = pl011_registers->uartfr.raw };
645 return uartfr.txff != 1;
646 }
647
648 static void
pl011_uart_transmit_data(uint8_t c)649 pl011_uart_transmit_data(uint8_t c)
650 {
651 uartdr_t uartdr = { .data = c };
652 pl011_registers->uartdr.raw = uartdr.raw;
653 }
654
655 static unsigned int
pl011_uart_receive_ready(void)656 pl011_uart_receive_ready(void)
657 {
658 const uartfr_t uartfr = { .raw = pl011_registers->uartfr.raw };
659 return uartfr.rxfe != 1;
660 }
661
662 static uint8_t
pl011_uart_receive_data(void)663 pl011_uart_receive_data(void)
664 {
665 const uartdr_t uartdr = { .raw = pl011_registers->uartdr.raw };
666 return uartdr.data;
667 }
668
669 static void
pl011_uart_init(void)670 pl011_uart_init(void)
671 {
672 // Before programming the control registers, we must first disable the UART.
673 // We can accomplish this by manually resetting the UARTCR register.
674 uartcr_t uartcr = { .raw = 0 };
675 uartcr.rxe = 1; // This bit's reset value is 1.
676 uartcr.txe = 1; // This bit's reset value is 1.
677 pl011_registers->uartcr.raw = uartcr.raw;
678
679 // Configure 8-N-1 communication and enable FIFOs.
680 uartlcr_h_t uartlcr_h = { .raw = 0 };
681 uartlcr_h.brk = 0;
682 uartlcr_h.pen = 0;
683 uartlcr_h.stp2 = 0;
684 uartlcr_h.fen = 1;
685 uartlcr_h.wlen = 0b11;
686 pl011_registers->uartlcr_h.raw = uartlcr_h.raw;
687
688 // Re-enable the UART.
689 uartcr.uarten = 1;
690 pl011_registers->uartcr.raw = uartcr.raw;
691 }
692
693 SECURITY_READ_ONLY_LATE(static struct pe_serial_functions) pl011_uart_serial_functions =
694 {
695 .init = pl011_uart_init,
696 .transmit_ready = pl011_uart_transmit_ready,
697 .transmit_data = pl011_uart_transmit_data,
698 .receive_ready = pl011_uart_receive_ready,
699 .receive_data = pl011_uart_receive_data,
700 .device = SERIAL_PL011_UART
701 };
702
703 static void
pl011_uart_setup(const DeviceTreeNode * const devicetree_node)704 pl011_uart_setup(const DeviceTreeNode *const devicetree_node)
705 {
706 // Get the physical address range of the PL011 UART register block.
707 const struct {
708 uint64_t block_offset; // TODO: make this scale with #address-cells
709 uint64_t block_size; // TODO: make this scale with #size-cells
710 } *reg;
711 unsigned int reg_size;
712 if (SecureDTGetProperty(devicetree_node, "reg", (const void **)®, ®_size) != kSuccess) {
713 panic("Unable to find the 'reg' property on the PL011 UART devicetree node");
714 }
715 assert(reg_size == sizeof(*reg));
716
717 // Create a virtual mapping to that physical address range.
718 const vm_offset_t soc_base_phys = pe_arm_get_soc_base_phys();
719 pl011_registers = (pl011_registers_t *)ml_io_map(soc_base_phys + reg->block_offset, reg->block_size);
720
721 // Register the PL011 UART serial driver.
722 register_serial_functions(&pl011_uart_serial_functions);
723 }
724
725 #endif /* PL011_UART */
726
727 /*****************************************************************************/
728
729 /**
730 * Output @str onto every registered serial interface by polling.
731 *
732 * @param str The string to output.
733 */
734 static void uart_puts_force_poll(
735 const char *str);
736
737 /**
738 * Output @str onto a specific serial interface by polling.
739 *
740 * @param str The string to output.
741 * @param fns The functions to use to output the message.
742 */
743 static void uart_puts_force_poll_device(
744 const char *str,
745 struct pe_serial_functions *fns);
746
747 #if HIBERNATION
748 /**
749 * Transitions the serial driver into a mode that can be run in the hibernation
750 * resume context. In this mode, the serial driver runs at a barebones level
751 * without making sure the serial devices are properly initialized or utilizing
752 * features such as the software drain timer for dockchannels.
753 *
754 * Upon the next call to serial_init (once the hibernation image has been
755 * loaded), this mode is exited and we return to the normal operation of the
756 * driver.
757 */
758 MARK_AS_HIBERNATE_TEXT void
serial_hibernation_init(void)759 serial_hibernation_init(void)
760 {
761 uart_hibernation = true;
762 #if defined(APPLE_UART)
763 apple_uart_registers = (apple_uart_registers_t *)gHibernateGlobals.hibUartRegPhysBase;
764 #endif /* defined(APPLE_UART) */
765 #if defined(DOCKCHANNEL_UART)
766 dockchannel_uart_base = gHibernateGlobals.dockChannelRegPhysBase;
767 #endif /* defined(DOCKCHANNEL_UART) */
768 }
769
770 /**
771 * Transitions the serial driver back to non-hibernation mode so it can resume
772 * normal operations. Should only be called from serial_init on a hibernation
773 * resume.
774 */
775 MARK_AS_HIBERNATE_TEXT static void
serial_hibernation_cleanup(void)776 serial_hibernation_cleanup(void)
777 {
778 uart_hibernation = false;
779 #if defined(APPLE_UART)
780 apple_uart_registers = (apple_uart_registers_t *)gHibernateGlobals.hibUartRegVirtBase;
781 #endif /* defined(APPLE_UART) */
782 #if defined(DOCKCHANNEL_UART)
783 dockchannel_uart_base = gHibernateGlobals.dockChannelRegVirtBase;
784 #endif /* defined(DOCKCHANNEL_UART) */
785 }
786 #endif /* HIBERNATION */
787
788 /**
789 * @brief This array maps "compatible" strings from the devicetree identifying
790 * different serial device drivers to their corresponding setup functions.
791 */
792 static const struct {
793 const char *const compatible;
794 void(*const setup)(const DeviceTreeNode * const devicetree_node);
795 } driver_setup_functions[] = {
796 #ifdef APPLE_UART
797 { .compatible = "uart-1,samsung", .setup = apple_uart_setup },
798 #endif // APPLE_UART
799 #ifdef DOCKCHANNEL_UART
800 { .compatible = "aapl,dock-channels", .setup = dockchannel_setup },
801 #endif // DOCKCHANNEL_UART
802 #ifdef PL011_UART
803 { .compatible = "arm,pl011", .setup = pl011_uart_setup },
804 #endif // PL011_UART
805 };
806
807 int
serial_init(void)808 serial_init(void)
809 {
810 vm_offset_t soc_base;
811
812 struct pe_serial_functions *fns = gPESF;
813
814 /**
815 * Even if the serial devices have already been initialized on cold boot,
816 * when coming out of a sleep/wake, they'll need to be re-initialized. Since
817 * the uart_initted value is kept across a sleep/wake, always re-initialize
818 * to be safe.
819 */
820 if (uart_initted) {
821 #if HIBERNATION
822 if (uart_hibernation) {
823 serial_hibernation_cleanup();
824 }
825 #endif /* HIBERNATION */
826 while (fns != NULL) {
827 fns->init();
828 fns = fns->next;
829 }
830
831 return gPESF != NULL;
832 }
833
834 soc_base = pe_arm_get_soc_base_phys();
835
836 if (soc_base == 0) {
837 uart_initted = true;
838 return 0;
839 }
840
841 PE_parse_boot_argn("disable-uart-irq", &disable_uart_irq, sizeof(disable_uart_irq));
842
843 // Check the "defaults" devicetree node to see whether or not a serial
844 // device was specified. Specifically, check for the presence of a
845 // "serial-device" phandle property.
846 const DeviceTreeNode *defaults_node;
847 if (SecureDTFindNodeWithStringProperty("name", "defaults", &defaults_node) != kSuccess) {
848 panic("Unable to find the 'defaults' devicetree node.");
849 }
850 bool serial_device_phandle_specified = false;
851 const uint32_t *phandle;
852 unsigned int phandle_size;
853 if (SecureDTGetProperty(defaults_node, "serial-device", (const void **)&phandle, &phandle_size) == kSuccess) {
854 assert(phandle_size == sizeof(*phandle));
855 serial_device_phandle_specified = true;
856 }
857
858 // Allow people to manually specify a serial device phandle via bootarg.
859 uint32_t phandle_bootarg;
860 if (PE_parse_boot_argn("serial-device", &phandle_bootarg, sizeof(phandle_bootarg))) {
861 phandle = &phandle_bootarg;
862 serial_device_phandle_specified = true;
863 }
864
865 // Return early if no serial device phandle was specified either in the
866 // devicetree or via bootarg.
867 if (!serial_device_phandle_specified) {
868 return 0;
869 }
870
871 // Look at the "compatible" string in the devicetree node referenced by the
872 // "serial-device" phandle property to see which driver we should use.
873 const DeviceTreeNode *serial_device_node;
874 if (SecureDTFindNodeWithPhandle(*phandle, &serial_device_node) != kSuccess) {
875 panic("Unable to find a devicetree node with phandle %x", *phandle);
876 }
877 const char *compatible;
878 unsigned int compatible_size;
879 if (SecureDTGetProperty(serial_device_node, "compatible", (const void **)&compatible, &compatible_size) != kSuccess) {
880 panic("The serial device devicetree node doesn't have a 'compatible' string");
881 }
882
883 // Call the setup function for the identified serial device driver.
884 bool found_matching_driver = false;
885 const int n_drivers = sizeof(driver_setup_functions) / sizeof(driver_setup_functions[0]);
886 for (int i = 0; i < n_drivers; i++) {
887 if (strcmp(compatible, driver_setup_functions[i].compatible) == 0) {
888 found_matching_driver = true;
889 driver_setup_functions[i].setup(serial_device_node);
890 }
891 }
892 if (!found_matching_driver) {
893 panic("Unable to find serial device driver for '%s'", compatible);
894 }
895
896 fns = gPESF;
897 while (fns != NULL) {
898 serial_do_transmit = 1;
899 fns->init();
900 if (fns->has_irq) {
901 serial_irq_status |= fns->device; // serial_device_t is one-hot
902 }
903 fns = fns->next;
904 }
905
906 #if HIBERNATION
907 /* hibernation needs to know the UART register addresses since it can't directly use this serial driver */
908 if (dockchannel_uart_base) {
909 gHibernateGlobals.dockChannelRegPhysBase = ml_vtophys(dockchannel_uart_base);
910 gHibernateGlobals.dockChannelRegVirtBase = dockchannel_uart_base;
911 gHibernateGlobals.dockChannelWstatMask = dock_wstat_mask;
912 }
913 if (apple_uart_registers) {
914 gHibernateGlobals.hibUartRegPhysBase = ml_vtophys((vm_offset_t)apple_uart_registers);
915 gHibernateGlobals.hibUartRegVirtBase = (vm_offset_t)apple_uart_registers;
916 }
917 #endif /* HIBERNATION */
918
919 /* Complete. */
920 uart_initted = true;
921 return gPESF != NULL;
922 }
923
924 /**
925 * Forbid or allow transmission over each serial until they receive data.
926 */
927 void
serial_set_on_demand(bool on_demand)928 serial_set_on_demand(bool on_demand)
929 {
930 /* Enable or disable transmission. */
931 serial_do_transmit = !on_demand;
932
933 /* If on-demand is enabled, report it. */
934 if (on_demand) {
935 uart_puts_force_poll(
936 "On-demand serial mode selected.\n"
937 "Waiting for user input to send logs.\n"
938 );
939 }
940 }
941
942 /**
943 * Returns a deadline for the longest time the serial driver should wait for an
944 * interrupt for. This serves as a timeout for the IRQ to allow for the software
945 * drain timer that dockchannels supports.
946 *
947 * @param fns serial functions representing the device to find the deadline for
948 *
949 * @returns absolutetime deadline for this device's IRQ.
950 */
951 static uint64_t
serial_interrupt_deadline(__unused struct pe_serial_functions * fns)952 serial_interrupt_deadline(__unused struct pe_serial_functions *fns)
953 {
954 #if defined(DOCKCHANNEL_UART)
955 if (fns->device == SERIAL_DOCKCHANNEL && use_sw_drain) {
956 return dockchannel_drain_deadline;
957 }
958 #endif
959
960 /**
961 * Default to 1.5ms for all other devices. 1.5ms was chosen as the baudrate
962 * of the AppleSerialDevice is 115200, meaning that it should only take
963 * ~1.5ms to drain the 16 character buffer completely.
964 */
965 uint64_t timeout_interval;
966 nanoseconds_to_absolutetime(1500 * NSEC_PER_USEC, &timeout_interval);
967 return mach_absolute_time() + timeout_interval;
968 }
969
970 /**
971 * Goes to sleep waiting for an interrupt from a specificed serial device.
972 *
973 * @param fns serial functions representing the device to wait for
974 */
975 static void
serial_wait_for_interrupt(struct pe_serial_functions * fns)976 serial_wait_for_interrupt(struct pe_serial_functions *fns)
977 {
978 /**
979 * This block of code is set up to avoid a race condition in which the IRQ
980 * is transmitted and processed by IOKit in between the time we check if the
981 * device is ready to transmit and when we call thread_block. If the IRQ
982 * fires in that time, thread_wakeup may have already been called in which
983 * case we would be blocking and have nothing to wake us up.
984 *
985 * To avoid this issue, we first call assert_wait_deadline, which prepares
986 * the thread to be blocked, but does not actually block the thread. After
987 * this point, any call to thread_wakeup from IRQ handler will prevent
988 * thread_block from actually blocking. As a performance optimization, we
989 * then double check if the device is ready to transmit and if it is, then
990 * we cancel the wait and just continue normally.
991 */
992 assert_wait_deadline(fns, THREAD_UNINT, serial_interrupt_deadline(fns));
993 if (!fns->transmit_ready()) {
994 fns->enable_irq();
995 thread_block(THREAD_CONTINUE_NULL);
996 } else {
997 clear_wait(current_thread(), THREAD_AWAKENED);
998 }
999 }
1000
1001 /**
1002 * Transmit a character over the specified serial output device.
1003 *
1004 * @param c Character to send
1005 * @param poll Whether we should poll or wait for an interrupt.
1006 * @param force Whether we should force this over the device if output has not been enabled yet.
1007 * @param fns Functions for the device to output over.
1008 */
1009 static inline void
uart_putc_device(char c,bool poll,bool force,struct pe_serial_functions * fns)1010 uart_putc_device(char c, bool poll, bool force, struct pe_serial_functions *fns)
1011 {
1012 if (!(serial_do_transmit || force)) {
1013 return;
1014 }
1015
1016 while (!fns->transmit_ready()) {
1017 if (irq_available_and_ready(fns) && !poll) {
1018 serial_wait_for_interrupt(fns);
1019 } else {
1020 serial_poll();
1021 }
1022 }
1023 fns->transmit_data((uint8_t)c);
1024 }
1025
1026 /**
1027 * Output a character onto every registered serial interface whose
1028 * transmission is enabled..
1029 *
1030 * @param c The character to output.
1031 * @param poll Whether the driver should poll to send the character or if it can
1032 * wait for an interrupt
1033 */
1034 MARK_AS_HIBERNATE_TEXT void
uart_putc_options(char c,bool poll)1035 uart_putc_options(char c, bool poll)
1036 {
1037 struct pe_serial_functions *fns = gPESF;
1038
1039 while (fns != NULL) {
1040 uart_putc_device(c, poll, false, fns);
1041 fns = fns->next;
1042 }
1043 }
1044
1045 /**
1046 * Output a character onto every registered serial interface whose
1047 * transmission is enabled by polling.
1048 *
1049 * @param c The character to output.
1050 */
1051 void
uart_putc(char c)1052 uart_putc(char c)
1053 {
1054 uart_putc_options(c, true);
1055 }
1056
1057 /**
1058 * Output @str onto every registered serial interface by polling.
1059 *
1060 * @param str The string to output.
1061 */
1062 static void
uart_puts_force_poll(const char * str)1063 uart_puts_force_poll(
1064 const char *str)
1065 {
1066 struct pe_serial_functions *fns = gPESF;
1067 while (fns != NULL) {
1068 uart_puts_force_poll_device(str, fns);
1069 fns = fns->next;
1070 }
1071 }
1072
1073 /**
1074 * Output @str onto a specific serial interface by polling.
1075 *
1076 * @param str The string to output.
1077 * @param fns The functions to use to output the message.
1078 */
1079 static void
uart_puts_force_poll_device(const char * str,struct pe_serial_functions * fns)1080 uart_puts_force_poll_device(
1081 const char *str,
1082 struct pe_serial_functions *fns)
1083 {
1084 char c;
1085 while ((c = *(str++))) {
1086 uart_putc_device(c, true, true, fns);
1087 }
1088 }
1089
1090 /**
1091 * Read a character from the first registered serial interface that has data
1092 * available.
1093 *
1094 * @return The character if any interfaces have data available, otherwise -1.
1095 */
1096 int
uart_getc(void)1097 uart_getc(void)
1098 {
1099 struct pe_serial_functions *fns = gPESF;
1100 while (fns != NULL) {
1101 if (fns->receive_ready()) {
1102 serial_do_transmit = 1;
1103 return (int)fns->receive_data();
1104 }
1105 fns = fns->next;
1106 }
1107 return -1;
1108 }
1109
1110 /**
1111 * Enables IRQs for a specific serial device and returns whether or not IRQs for
1112 * that device where enabled successfully. For a serial driver to have irqs
1113 * enabled, it must have the enable_irq, disable_irq, and acknowledge_irq
1114 * functions defined and the has_irq flag set.
1115 *
1116 * @param device Serial device to enable irqs on
1117 * @note This function should only be called from the AppleSerialShim kext
1118 */
1119 kern_return_t
serial_irq_enable(serial_device_t device)1120 serial_irq_enable(serial_device_t device)
1121 {
1122 struct pe_serial_functions *fns = get_serial_functions(device);
1123
1124 if (!fns || !fns->has_irq || disable_uart_irq) {
1125 return KERN_FAILURE;
1126 }
1127
1128 serial_irq_status &= ~device;
1129
1130 return KERN_SUCCESS;
1131 }
1132
1133 /**
1134 * Performs any actions needed to handle this IRQ. Wakes up the thread waiting
1135 * on the interrupt if one exists.
1136 *
1137 * @param device Serial device that generated the IRQ.
1138 * @note Interrupts will have already been cleared and disabled by serial_irq_filter.
1139 * @note This function should only be called from the AppleSerialShim kext.
1140 */
1141 kern_return_t
serial_irq_action(serial_device_t device)1142 serial_irq_action(serial_device_t device)
1143 {
1144 struct pe_serial_functions *fns = get_serial_functions(device);
1145
1146 if (!fns || !fns->has_irq) {
1147 return KERN_FAILURE;
1148 }
1149
1150 /**
1151 * Because IRQs are enabled only when we know a thread is about to sleep, we
1152 * can call wake up and reasonably expect there to be a thread waiting.
1153 */
1154 thread_wakeup(fns);
1155
1156 return KERN_SUCCESS;
1157 }
1158
1159 /**
1160 * Returns true if the pending IRQ for device is one that can be handled by the
1161 * platform serial driver.
1162 *
1163 * @param device Serial device that generated the IRQ.
1164 * @note This function is called from a primary interrupt context and should be
1165 * kept lightweight.
1166 * @note This function should only be called from the AppleSerialShim kext
1167 */
1168 bool
serial_irq_filter(serial_device_t device)1169 serial_irq_filter(serial_device_t device)
1170 {
1171 struct pe_serial_functions *fns = get_serial_functions(device);
1172
1173 if (!fns || !fns->has_irq) {
1174 return false;
1175 }
1176
1177 /**
1178 * Disable IRQs until next time a thread waits for an interrupt to prevent an interrupt storm.
1179 */
1180 const bool had_irqs_enabled = fns->disable_irq();
1181 const bool was_our_interrupt = fns->acknowledge_irq();
1182
1183 /* Re-enable IRQs if the interrupt wasn't for us. */
1184 if (had_irqs_enabled && !was_our_interrupt) {
1185 fns->enable_irq();
1186 }
1187
1188 return was_our_interrupt;
1189 }
1190
1191 /**
1192 * Prepares all serial devices to go to sleep by draining the hardware FIFOs
1193 * and disabling interrupts.
1194 */
1195 void
serial_go_to_sleep(void)1196 serial_go_to_sleep(void)
1197 {
1198 struct pe_serial_functions *fns = gPESF;
1199 while (fns != NULL) {
1200 if (irq_available_and_ready(fns)) {
1201 fns->disable_irq();
1202 }
1203 fns = fns->next;
1204 }
1205
1206 #ifdef APPLE_UART
1207 /* APPLE_UART needs to drain FIFO before sleeping */
1208 if (get_serial_functions(SERIAL_APPLE_UART)) {
1209 apple_uart_drain_fifo();
1210 }
1211 #endif /* APPLE_UART */
1212 }
1213