xref: /xnu-12377.61.12/pexpert/arm/pe_serial.c (revision 4d495c6e23c53686cf65f45067f79024cf5dcee8)
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/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 **)&reg, &reg_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 **)&reg, &reg_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_base, 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)ml_io_read32(rDOCKCHANNELS_DOCK_RDATA1(dockchannel_uart_base, 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 	ml_io_write32(rDOCKCHANNELS_AGENT_AP_INTR_CTRL(dock_agent_base),
525 	    ml_io_read32(rDOCKCHANNELS_AGENT_AP_INTR_CTRL(dock_agent_base)) & ~(0x3));
526 	ml_io_write32(rDOCKCHANNELS_AGENT_AP_INTR_STATUS(dock_agent_base),
527 	    ml_io_read32(rDOCKCHANNELS_AGENT_AP_INTR_STATUS(dock_agent_base)) | 0x3);
528 	ml_io_write32(rDOCKCHANNELS_AGENT_AP_ERR_INTR_CTRL(dock_agent_base),
529 	    ml_io_read32(rDOCKCHANNELS_AGENT_AP_ERR_INTR_CTRL(dock_agent_base)) & ~(0x3));
530 	ml_io_write32(rDOCKCHANNELS_AGENT_AP_ERR_INTR_STATUS(dock_agent_base),
531 	    ml_io_read32(rDOCKCHANNELS_AGENT_AP_ERR_INTR_STATUS(dock_agent_base)) | 0x3);
532 }
533 
534 static bool
dockchannel_disable_irq(void)535 dockchannel_disable_irq(void)
536 {
537 	const uint32_t ap_intr_ctrl = ml_io_read32(rDOCKCHANNELS_AGENT_AP_INTR_CTRL(dock_agent_base));
538 	const bool irqs_were_enabled = ap_intr_ctrl & 0x1;
539 	if (irqs_were_enabled) {
540 		ml_io_write32(rDOCKCHANNELS_AGENT_AP_INTR_CTRL(dock_agent_base), ap_intr_ctrl & ~(0x1));
541 	}
542 	return irqs_were_enabled;
543 }
544 
545 static void
dockchannel_enable_irq(void)546 dockchannel_enable_irq(void)
547 {
548 	// set interrupt to be when fifo has 255 empty
549 	ml_io_write32(rDOCKCHANNELS_DEV_WR_WATERMARK(dockchannel_uart_base, DOCKCHANNEL_UART_CHANNEL), 0xFF);
550 	ml_io_write32(rDOCKCHANNELS_AGENT_AP_INTR_CTRL(dock_agent_base),
551 	    ml_io_read32(rDOCKCHANNELS_AGENT_AP_INTR_CTRL(dock_agent_base)) | 0x1);
552 }
553 
554 static bool
dockchannel_ack_irq(void)555 dockchannel_ack_irq(void)
556 {
557 	/* First check if the IRQ is for the kernel */
558 	const uint32_t ap_intr_status = 0x1 & ml_io_read32(rDOCKCHANNELS_AGENT_AP_INTR_STATUS(dock_agent_base));
559 	if (0x1 == ap_intr_status) {
560 		/* And clear it */
561 		ml_io_write32(rDOCKCHANNELS_AGENT_AP_INTR_STATUS(dock_agent_base), ap_intr_status);
562 		return true;
563 	}
564 	return false;
565 }
566 
567 MARK_AS_HIBERNATE_TEXT static void
dockchannel_transmit_data(uint8_t c)568 dockchannel_transmit_data(uint8_t c)
569 {
570 	ml_io_write32(rDOCKCHANNELS_DEV_WDATA1(dockchannel_uart_base, DOCKCHANNEL_UART_CHANNEL), (unsigned)c);
571 
572 	if (use_sw_drain && !uart_hibernation) {
573 		os_atomic_dec(&prev_dockchannel_spaces, relaxed); // After writing a byte we have one fewer space than previously expected.
574 	}
575 }
576 
577 static unsigned int
dockchannel_receive_ready(void)578 dockchannel_receive_ready(void)
579 {
580 	return ml_io_read32(rDOCKCHANNELS_DEV_RDATA0(dockchannel_uart_base, DOCKCHANNEL_UART_CHANNEL)) & 0x7f;
581 }
582 
583 static uint8_t
dockchannel_receive_data(void)584 dockchannel_receive_data(void)
585 {
586 	return (uint8_t)((ml_io_read32(rDOCKCHANNELS_DEV_RDATA1(dockchannel_uart_base, DOCKCHANNEL_UART_CHANNEL)) >> 8) & 0xff);
587 }
588 
589 MARK_AS_HIBERNATE_TEXT static unsigned int
dockchannel_transmit_ready(void)590 dockchannel_transmit_ready(void)
591 {
592 	uint32_t spaces = ml_io_read32(rDOCKCHANNELS_DEV_WSTAT(dockchannel_uart_base, DOCKCHANNEL_UART_CHANNEL)) & dock_wstat_mask;
593 
594 	if (!uart_hibernation) {
595 		if (use_sw_drain) {
596 			if (spaces > prev_dockchannel_spaces) {
597 				// More spaces showed up. That can only mean someone read the FIFO.
598 				// Note that if the DockFIFO is empty we cannot tell if someone is listening,
599 				// we can only give them the benefit of the doubt.
600 				dockchannel_drain_deadline = mach_absolute_time() + dockchannel_stall_grace;
601 			}
602 			prev_dockchannel_spaces = spaces;
603 			return spaces || dockchannel_drain_on_stall();
604 		}
605 	}
606 
607 	return spaces;
608 }
609 
610 static void
dockchannel_init(void)611 dockchannel_init(void)
612 {
613 	if (use_sw_drain) {
614 		nanoseconds_to_absolutetime(DOCKCHANNEL_WR_MAX_STALL_US * NSEC_PER_USEC, &dockchannel_stall_grace);
615 	}
616 
617 	// Clear all interrupt enable and status bits
618 	dockchannel_clear_intr();
619 
620 	// Setup DRAIN timer
621 	ml_io_write32(rDOCKCHANNELS_DEV_DRAIN_CFG(dockchannel_uart_base, DOCKCHANNEL_UART_CHANNEL), max_dockchannel_drain_period);
622 
623 	// Drain timer doesn't get loaded with value from drain period register if fifo
624 	// is already full. Drop a character from the fifo.
625 	(void)ml_io_read32(rDOCKCHANNELS_DOCK_RDATA1(dockchannel_uart_base, DOCKCHANNEL_UART_CHANNEL));
626 }
627 
628 MARK_AS_HIBERNATE_DATA_CONST_LATE
629 static struct pe_serial_functions dockchannel_serial_functions =
630 {
631 	.init = dockchannel_init,
632 	.transmit_ready = dockchannel_transmit_ready,
633 	.transmit_data = dockchannel_transmit_data,
634 	.receive_ready = dockchannel_receive_ready,
635 	.receive_data = dockchannel_receive_data,
636 	.enable_irq = dockchannel_enable_irq,
637 	.disable_irq = dockchannel_disable_irq,
638 	.acknowledge_irq = dockchannel_ack_irq,
639 	.device = SERIAL_DOCKCHANNEL
640 };
641 
642 #endif /* DOCKCHANNEL_UART */
643 
644 /*****************************************************************************/
645 
646 #ifdef PL011_UART
647 
648 static unsigned int
pl011_uart_transmit_ready(void)649 pl011_uart_transmit_ready(void)
650 {
651 	const uartfr_t uartfr = { .raw = pl011_registers->uartfr.raw };
652 	return uartfr.txff != 1;
653 }
654 
655 static void
pl011_uart_transmit_data(uint8_t c)656 pl011_uart_transmit_data(uint8_t c)
657 {
658 	uartdr_t uartdr = { .data = c };
659 	pl011_registers->uartdr.raw = uartdr.raw;
660 }
661 
662 static unsigned int
pl011_uart_receive_ready(void)663 pl011_uart_receive_ready(void)
664 {
665 	const uartfr_t uartfr = { .raw = pl011_registers->uartfr.raw };
666 	return uartfr.rxfe != 1;
667 }
668 
669 static uint8_t
pl011_uart_receive_data(void)670 pl011_uart_receive_data(void)
671 {
672 	const uartdr_t uartdr = { .raw = pl011_registers->uartdr.raw };
673 	return uartdr.data;
674 }
675 
676 static void
pl011_uart_init(void)677 pl011_uart_init(void)
678 {
679 	// Before programming the control registers, we must first disable the UART.
680 	// We can accomplish this by manually resetting the UARTCR register.
681 	uartcr_t uartcr = { .raw = 0 };
682 	uartcr.rxe = 1; // This bit's reset value is 1.
683 	uartcr.txe = 1; // This bit's reset value is 1.
684 	pl011_registers->uartcr.raw = uartcr.raw;
685 
686 	// Configure 8-N-1 communication and enable FIFOs.
687 	uartlcr_h_t uartlcr_h = { .raw = 0 };
688 	uartlcr_h.brk = 0;
689 	uartlcr_h.pen = 0;
690 	uartlcr_h.stp2 = 0;
691 	uartlcr_h.fen = 1;
692 	uartlcr_h.wlen = 0b11;
693 	pl011_registers->uartlcr_h.raw = uartlcr_h.raw;
694 
695 	// Re-enable the UART.
696 	uartcr.uarten = 1;
697 	pl011_registers->uartcr.raw = uartcr.raw;
698 }
699 
700 SECURITY_READ_ONLY_LATE(static struct pe_serial_functions) pl011_uart_serial_functions =
701 {
702 	.init = pl011_uart_init,
703 	.transmit_ready = pl011_uart_transmit_ready,
704 	.transmit_data = pl011_uart_transmit_data,
705 	.receive_ready = pl011_uart_receive_ready,
706 	.receive_data = pl011_uart_receive_data,
707 	.device = SERIAL_PL011_UART
708 };
709 
710 static void
pl011_uart_setup(const DeviceTreeNode * const devicetree_node)711 pl011_uart_setup(const DeviceTreeNode *const devicetree_node)
712 {
713 	// Get the physical address range of the PL011 UART register block.
714 	const struct {
715 		uint64_t block_offset; // TODO: make this scale with #address-cells
716 		uint64_t block_size; // TODO: make this scale with #size-cells
717 	} *reg;
718 	unsigned int reg_size;
719 	if (SecureDTGetProperty(devicetree_node, "reg", (const void **)&reg, &reg_size) != kSuccess) {
720 		panic("Unable to find the 'reg' property on the PL011 UART devicetree node");
721 	}
722 	assert(reg_size == sizeof(*reg));
723 
724 	// Create a virtual mapping to that physical address range.
725 	const vm_offset_t soc_base_phys = pe_arm_get_soc_base_phys();
726 	pl011_registers = (pl011_registers_t *)ml_io_map(soc_base_phys + reg->block_offset, reg->block_size);
727 
728 	// Register the PL011 UART serial driver.
729 	register_serial_functions(&pl011_uart_serial_functions);
730 }
731 
732 #endif /* PL011_UART */
733 
734 /*****************************************************************************/
735 
736 /**
737  * Output @str onto every registered serial interface by polling.
738  *
739  * @param str The string to output.
740  */
741 static void uart_puts_force_poll(
742 	const char *str);
743 
744 /**
745  * Output @str onto a specific serial interface by polling.
746  *
747  * @param str The string to output.
748  * @param fns The functions to use to output the message.
749  */
750 static void uart_puts_force_poll_device(
751 	const char *str,
752 	struct pe_serial_functions *fns);
753 
754 #if HIBERNATION
755 /**
756  * Transitions the serial driver into a mode that can be run in the hibernation
757  * resume context. In this mode, the serial driver runs at a barebones level
758  * without making sure the serial devices are properly initialized or utilizing
759  * features such as the software drain timer for dockchannels.
760  *
761  * Upon the next call to serial_init (once the hibernation image has been
762  * loaded), this mode is exited and we return to the normal operation of the
763  * driver.
764  */
765 MARK_AS_HIBERNATE_TEXT void
serial_hibernation_init(void)766 serial_hibernation_init(void)
767 {
768 	uart_hibernation = true;
769 #if defined(APPLE_UART)
770 	apple_uart_registers = (apple_uart_registers_t *)gHibernateGlobals.hibUartRegPhysBase;
771 #endif /* defined(APPLE_UART) */
772 #if defined(DOCKCHANNEL_UART)
773 	dockchannel_uart_base = gHibernateGlobals.dockChannelRegPhysBase;
774 #endif /* defined(DOCKCHANNEL_UART) */
775 }
776 
777 /**
778  * Transitions the serial driver back to non-hibernation mode so it can resume
779  * normal operations. Should only be called from serial_init on a hibernation
780  * resume.
781  */
782 MARK_AS_HIBERNATE_TEXT static void
serial_hibernation_cleanup(void)783 serial_hibernation_cleanup(void)
784 {
785 	uart_hibernation = false;
786 #if defined(APPLE_UART)
787 	apple_uart_registers = (apple_uart_registers_t *)gHibernateGlobals.hibUartRegVirtBase;
788 #endif /* defined(APPLE_UART) */
789 #if defined(DOCKCHANNEL_UART)
790 	dockchannel_uart_base = gHibernateGlobals.dockChannelRegVirtBase;
791 #endif /* defined(DOCKCHANNEL_UART) */
792 }
793 #endif /* HIBERNATION */
794 
795 /**
796  * @brief This array maps "compatible" strings from the devicetree identifying
797  * different serial device drivers to their corresponding setup functions.
798  */
799 static const struct {
800 	const char *const compatible;
801 	void(*const setup)(const DeviceTreeNode * const devicetree_node);
802 } driver_setup_functions[] = {
803 #ifdef APPLE_UART
804 	{ .compatible = "uart-1,samsung", .setup = apple_uart_setup },
805 #endif // APPLE_UART
806 #ifdef DOCKCHANNEL_UART
807 	{ .compatible = "aapl,dock-channels", .setup = dockchannel_setup },
808 #endif // DOCKCHANNEL_UART
809 #ifdef PL011_UART
810 	{ .compatible = "arm,pl011", .setup = pl011_uart_setup },
811 #endif // PL011_UART
812 };
813 
814 /**
815  * Gets the phandle of the devicetree node that represents the serial device
816  * XNU has been configured (either via devicetree or bootarg) to use.
817  *
818  * @param[out] phandle If XNU has been configured with a serial device to use,
819  * then this function will populate this output parameter with a phandle.
820  *
821  * @return Whether XNU has been configured with a serial device to use. Also,
822  * whether @p phandle has been populated by this function.
823  */
824 static bool
get_serial_device_phandle(uint32_t * const phandle)825 get_serial_device_phandle(uint32_t * const phandle)
826 {
827 	// Check the "defaults" devicetree node to see whether or not a serial
828 	// device was specified. Specifically, check for the presence of a
829 	// "serial-device" phandle property.
830 	const DeviceTreeNode *defaults_node;
831 	if (SecureDTFindNodeWithStringProperty("name", "defaults", &defaults_node) != kSuccess) {
832 		panic("Unable to find the 'defaults' devicetree node.");
833 	}
834 	bool serial_device_phandle_specified = false;
835 	const uint32_t *defaults_phandle;
836 	unsigned int defaults_phandle_size;
837 	if (SecureDTGetProperty(defaults_node, "serial-device", (const void **)&defaults_phandle, &defaults_phandle_size) == kSuccess) {
838 		assert(defaults_phandle_size == sizeof(*defaults_phandle));
839 		*phandle = *defaults_phandle;
840 		serial_device_phandle_specified = true;
841 	}
842 
843 	// Allow people to manually specify a serial device phandle via bootarg.
844 	uint32_t phandle_bootarg;
845 	if (PE_parse_boot_argn("serial-device", &phandle_bootarg, sizeof(phandle_bootarg))) {
846 		*phandle = phandle_bootarg;
847 		serial_device_phandle_specified = true;
848 	}
849 
850 	// Give people an easier way to specify a serial device via bootarg (i.e.,
851 	// by giving the name of the devicetree node).
852 	const int kSerialDeviceNameMaxLen = 31;
853 	char serial_device_name_buffer[kSerialDeviceNameMaxLen + 1];
854 	if (PE_parse_boot_arg_str("serial-device-name", serial_device_name_buffer, sizeof(serial_device_name_buffer))) {
855 		// Find the devicetree node with that name.
856 		const DeviceTreeNode *serial_device_node;
857 		if (SecureDTFindNodeWithStringProperty("name", serial_device_name_buffer, &serial_device_node) != kSuccess) {
858 			panic("Unable to find a devicetree node with the name '%s'.", serial_device_name_buffer);
859 		}
860 
861 		// Get the phandle of that node.
862 		const uint32_t *node_phandle;
863 		unsigned int node_phandle_size;
864 		if (SecureDTGetProperty(serial_device_node, "AAPL,phandle", (const void **)&node_phandle, &node_phandle_size) != kSuccess) {
865 			panic("The devicetree node has no phandle. This should never happen!");
866 		}
867 		assert(node_phandle_size == sizeof(*node_phandle));
868 		*phandle = *node_phandle;
869 		serial_device_phandle_specified = true;
870 	}
871 
872 	return serial_device_phandle_specified;
873 }
874 
875 int
serial_init(void)876 serial_init(void)
877 {
878 	vm_offset_t     soc_base;
879 
880 	struct pe_serial_functions *fns = gPESF;
881 
882 	/**
883 	 * Even if the serial devices have already been initialized on cold boot,
884 	 * when coming out of a sleep/wake, they'll need to be re-initialized. Since
885 	 * the uart_initted value is kept across a sleep/wake, always re-initialize
886 	 * to be safe.
887 	 */
888 	if (uart_initted) {
889 #if HIBERNATION
890 		if (uart_hibernation) {
891 			serial_hibernation_cleanup();
892 		}
893 #endif /* HIBERNATION */
894 		while (fns != NULL) {
895 			fns->init();
896 			fns = fns->next;
897 		}
898 
899 		return gPESF != NULL;
900 	}
901 
902 	soc_base = pe_arm_get_soc_base_phys();
903 
904 	if (soc_base == 0) {
905 		uart_initted = true;
906 		return 0;
907 	}
908 
909 	PE_parse_boot_argn("disable-uart-irq", &disable_uart_irq, sizeof(disable_uart_irq));
910 
911 	// Get the phandle of the serial device XNU has been configured to use.
912 	uint32_t phandle;
913 	if (!get_serial_device_phandle(&phandle)) {
914 		// XNU has not been configured to use a serial device; return early.
915 		return 0;
916 	}
917 
918 	// Look at the "compatible" string in the devicetree node referenced by the
919 	// "serial-device" phandle property to see which driver we should use.
920 	const DeviceTreeNode *serial_device_node;
921 	if (SecureDTFindNodeWithPhandle(phandle, &serial_device_node) != kSuccess) {
922 		panic("Unable to find a devicetree node with phandle %x", phandle);
923 	}
924 	const char *compatible;
925 	unsigned int compatible_size;
926 	if (SecureDTGetProperty(serial_device_node, "compatible", (const void **)&compatible, &compatible_size) != kSuccess) {
927 		panic("The serial device devicetree node doesn't have a 'compatible' string");
928 	}
929 
930 	// Call the setup function for the identified serial device driver.
931 	bool found_matching_driver = false;
932 	const int n_drivers = sizeof(driver_setup_functions) / sizeof(driver_setup_functions[0]);
933 	for (int i = 0; i < n_drivers; i++) {
934 		if (strcmp(compatible, driver_setup_functions[i].compatible) == 0) {
935 			found_matching_driver = true;
936 			driver_setup_functions[i].setup(serial_device_node);
937 		}
938 	}
939 	if (!found_matching_driver) {
940 		panic("Unable to find serial device driver for '%s'", compatible);
941 	}
942 
943 	fns = gPESF;
944 	while (fns != NULL) {
945 		serial_do_transmit = 1;
946 		fns->init();
947 		if (fns->has_irq) {
948 			serial_irq_status |= fns->device; // serial_device_t is one-hot
949 		}
950 		fns = fns->next;
951 	}
952 
953 #if HIBERNATION
954 	/* hibernation needs to know the UART register addresses since it can't directly use this serial driver */
955 	if (dockchannel_uart_base) {
956 		gHibernateGlobals.dockChannelRegPhysBase = ml_vtophys(dockchannel_uart_base);
957 		gHibernateGlobals.dockChannelRegVirtBase = dockchannel_uart_base;
958 		gHibernateGlobals.dockChannelWstatMask = dock_wstat_mask;
959 	}
960 	if (apple_uart_registers) {
961 		gHibernateGlobals.hibUartRegPhysBase = ml_vtophys((vm_offset_t)apple_uart_registers);
962 		gHibernateGlobals.hibUartRegVirtBase = (vm_offset_t)apple_uart_registers;
963 	}
964 #endif /* HIBERNATION */
965 
966 	/* Complete. */
967 	uart_initted = true;
968 	return gPESF != NULL;
969 }
970 
971 /**
972  * Forbid or allow transmission over each serial until they receive data.
973  */
974 void
serial_set_on_demand(bool on_demand)975 serial_set_on_demand(bool on_demand)
976 {
977 	/* Enable or disable transmission. */
978 	serial_do_transmit = !on_demand;
979 
980 	/* If on-demand is enabled, report it. */
981 	if (on_demand) {
982 		uart_puts_force_poll(
983 			"On-demand serial mode selected.\n"
984 			"Waiting for user input to send logs.\n"
985 			);
986 	}
987 }
988 
989 /**
990  * Returns a deadline for the longest time the serial driver should wait for an
991  * interrupt for. This serves as a timeout for the IRQ to allow for the software
992  * drain timer that dockchannels supports.
993  *
994  * @param fns serial functions representing the device to find the deadline for
995  *
996  * @returns absolutetime deadline for this device's IRQ.
997  */
998 static uint64_t
serial_interrupt_deadline(__unused struct pe_serial_functions * fns)999 serial_interrupt_deadline(__unused struct pe_serial_functions *fns)
1000 {
1001 #if defined(DOCKCHANNEL_UART)
1002 	if (fns->device == SERIAL_DOCKCHANNEL && use_sw_drain) {
1003 		return dockchannel_drain_deadline;
1004 	}
1005 #endif
1006 
1007 	/**
1008 	 *  Default to 1.5ms for all other devices. 1.5ms was chosen as the baudrate
1009 	 * of the AppleSerialDevice is 115200, meaning that it should only take
1010 	 * ~1.5ms to drain the 16 character buffer completely.
1011 	 */
1012 	uint64_t timeout_interval;
1013 	nanoseconds_to_absolutetime(1500 * NSEC_PER_USEC, &timeout_interval);
1014 	return mach_absolute_time() + timeout_interval;
1015 }
1016 
1017 /**
1018  * Goes to sleep waiting for an interrupt from a specificed serial device.
1019  *
1020  * @param fns serial functions representing the device to wait for
1021  */
1022 static void
serial_wait_for_interrupt(struct pe_serial_functions * fns)1023 serial_wait_for_interrupt(struct pe_serial_functions *fns)
1024 {
1025 	/**
1026 	 * This block of code is set up to avoid a race condition in which the IRQ
1027 	 * is transmitted and processed by IOKit in between the time we check if the
1028 	 * device is ready to transmit and when we call thread_block. If the IRQ
1029 	 * fires in that time, thread_wakeup may have already been called in which
1030 	 * case we would be blocking and have nothing to wake us up.
1031 	 *
1032 	 * To avoid this issue, we first call assert_wait_deadline, which prepares
1033 	 * the thread to be blocked, but does not actually block the thread. After
1034 	 * this point, any call to thread_wakeup from IRQ handler will prevent
1035 	 * thread_block from actually blocking. As a performance optimization, we
1036 	 * then double check if the device is ready to transmit and if it is, then
1037 	 * we cancel the wait and just continue normally.
1038 	 */
1039 	assert_wait_deadline(fns, THREAD_UNINT, serial_interrupt_deadline(fns));
1040 	if (!fns->transmit_ready()) {
1041 		fns->enable_irq();
1042 		thread_block(THREAD_CONTINUE_NULL);
1043 	} else {
1044 		clear_wait(current_thread(), THREAD_AWAKENED);
1045 	}
1046 }
1047 
1048 /**
1049  * Transmit a character over the specified serial output device.
1050  *
1051  * @param c Character to send
1052  * @param poll Whether we should poll or wait for an interrupt.
1053  * @param force Whether we should force this over the device if output has not been enabled yet.
1054  * @param fns Functions for the device to output over.
1055  */
1056 static inline void
uart_putc_device(char c,bool poll,bool force,struct pe_serial_functions * fns)1057 uart_putc_device(char c, bool poll, bool force, struct pe_serial_functions *fns)
1058 {
1059 	if (!(serial_do_transmit || force)) {
1060 		return;
1061 	}
1062 
1063 	while (!fns->transmit_ready()) {
1064 		if (irq_available_and_ready(fns) && !poll) {
1065 			serial_wait_for_interrupt(fns);
1066 		} else {
1067 			serial_poll();
1068 		}
1069 	}
1070 	fns->transmit_data((uint8_t)c);
1071 }
1072 
1073 /**
1074  * Output a character onto every registered serial interface whose
1075  * transmission is enabled..
1076  *
1077  * @param c The character to output.
1078  * @param poll Whether the driver should poll to send the character or if it can
1079  *             wait for an interrupt
1080  */
1081 MARK_AS_HIBERNATE_TEXT void
uart_putc_options(char c,bool poll)1082 uart_putc_options(char c, bool poll)
1083 {
1084 	struct pe_serial_functions *fns = gPESF;
1085 
1086 	while (fns != NULL) {
1087 		uart_putc_device(c, poll, false, fns);
1088 		fns = fns->next;
1089 	}
1090 }
1091 
1092 /**
1093  * Output a character onto every registered serial interface whose
1094  * transmission is enabled by polling.
1095  *
1096  * @param c The character to output.
1097  */
1098 void
uart_putc(char c)1099 uart_putc(char c)
1100 {
1101 	uart_putc_options(c, true);
1102 }
1103 
1104 /**
1105  * Output @str onto every registered serial interface by polling.
1106  *
1107  * @param str The string to output.
1108  */
1109 static void
uart_puts_force_poll(const char * str)1110 uart_puts_force_poll(
1111 	const char *str)
1112 {
1113 	struct pe_serial_functions *fns = gPESF;
1114 	while (fns != NULL) {
1115 		uart_puts_force_poll_device(str, fns);
1116 		fns = fns->next;
1117 	}
1118 }
1119 
1120 /**
1121  * Output @str onto a specific serial interface by polling.
1122  *
1123  * @param str The string to output.
1124  * @param fns The functions to use to output the message.
1125  */
1126 static void
uart_puts_force_poll_device(const char * str,struct pe_serial_functions * fns)1127 uart_puts_force_poll_device(
1128 	const char *str,
1129 	struct pe_serial_functions *fns)
1130 {
1131 	char c;
1132 	while ((c = *(str++))) {
1133 		uart_putc_device(c, true, true, fns);
1134 	}
1135 }
1136 
1137 /**
1138  * Read a character from the first registered serial interface that has data
1139  * available.
1140  *
1141  * @return The character if any interfaces have data available, otherwise -1.
1142  */
1143 int
uart_getc(void)1144 uart_getc(void)
1145 {
1146 	struct pe_serial_functions *fns = gPESF;
1147 	while (fns != NULL) {
1148 		if (fns->receive_ready()) {
1149 			serial_do_transmit = 1;
1150 			return (int)fns->receive_data();
1151 		}
1152 		fns = fns->next;
1153 	}
1154 	return -1;
1155 }
1156 
1157 /**
1158  * Enables IRQs for a specific serial device and returns whether or not IRQs for
1159  * that device where enabled successfully. For a serial driver to have irqs
1160  * enabled, it must have the enable_irq, disable_irq, and acknowledge_irq
1161  * functions defined and the has_irq flag set.
1162  *
1163  * @param device Serial device to enable irqs on
1164  * @note This function should only be called from the AppleSerialShim kext
1165  */
1166 kern_return_t
serial_irq_enable(serial_device_t device)1167 serial_irq_enable(serial_device_t device)
1168 {
1169 	struct pe_serial_functions *fns = get_serial_functions(device);
1170 
1171 	if (!fns || !fns->has_irq || disable_uart_irq) {
1172 		return KERN_FAILURE;
1173 	}
1174 
1175 	serial_irq_status &= ~device;
1176 
1177 	return KERN_SUCCESS;
1178 }
1179 
1180 /**
1181  * Performs any actions needed to handle this IRQ. Wakes up the thread waiting
1182  * on the interrupt if one exists.
1183  *
1184  * @param device Serial device that generated the IRQ.
1185  * @note Interrupts will have already been cleared and disabled by serial_irq_filter.
1186  * @note This function should only be called from the AppleSerialShim kext.
1187  */
1188 kern_return_t
serial_irq_action(serial_device_t device)1189 serial_irq_action(serial_device_t device)
1190 {
1191 	struct pe_serial_functions *fns = get_serial_functions(device);
1192 
1193 	if (!fns || !fns->has_irq) {
1194 		return KERN_FAILURE;
1195 	}
1196 
1197 	/**
1198 	 * Because IRQs are enabled only when we know a thread is about to sleep, we
1199 	 * can call wake up and reasonably expect there to be a thread waiting.
1200 	 */
1201 	thread_wakeup(fns);
1202 
1203 	return KERN_SUCCESS;
1204 }
1205 
1206 /**
1207  * Returns true if the pending IRQ for device is one that can be handled by the
1208  * platform serial driver.
1209  *
1210  * @param device Serial device that generated the IRQ.
1211  * @note This function is called from a primary interrupt context and should be
1212  *       kept lightweight.
1213  * @note This function should only be called from the AppleSerialShim kext
1214  */
1215 bool
serial_irq_filter(serial_device_t device)1216 serial_irq_filter(serial_device_t device)
1217 {
1218 	struct pe_serial_functions *fns = get_serial_functions(device);
1219 
1220 	if (!fns || !fns->has_irq) {
1221 		return false;
1222 	}
1223 
1224 	/**
1225 	 * Disable IRQs until next time a thread waits for an interrupt to prevent an interrupt storm.
1226 	 */
1227 	const bool had_irqs_enabled = fns->disable_irq();
1228 	const bool was_our_interrupt = fns->acknowledge_irq();
1229 
1230 	/* Re-enable IRQs if the interrupt wasn't for us. */
1231 	if (had_irqs_enabled && !was_our_interrupt) {
1232 		fns->enable_irq();
1233 	}
1234 
1235 	return was_our_interrupt;
1236 }
1237 
1238 /**
1239  * Prepares all serial devices to go to sleep by draining the hardware FIFOs
1240  * and disabling interrupts.
1241  */
1242 void
serial_go_to_sleep(void)1243 serial_go_to_sleep(void)
1244 {
1245 	struct pe_serial_functions *fns = gPESF;
1246 	while (fns != NULL) {
1247 		if (irq_available_and_ready(fns)) {
1248 			fns->disable_irq();
1249 		}
1250 		fns = fns->next;
1251 	}
1252 
1253 #ifdef APPLE_UART
1254 	/* APPLE_UART needs to drain FIFO before sleeping */
1255 	if (get_serial_functions(SERIAL_APPLE_UART)) {
1256 		apple_uart_drain_fifo();
1257 	}
1258 #endif /* APPLE_UART */
1259 }
1260