1 /*-
2  * Copyright (c) 2012 NetApp, Inc.
3  * Copyright (c) 2013 Neel Natu <neel@freebsd.org>
4  * Copyright (c) 2018-2024 Intel Corporation.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  * $FreeBSD$
28  */
29 
30 #include <types.h>
31 #include <pci.h>
32 #include <uart16550.h>
33 #include <console.h>
34 #include <vuart.h>
35 #include <vmcs9900.h>
36 #include <asm/guest/vm.h>
37 #include <logmsg.h>
38 
39 /**
40  * @addtogroup vp-dm_vperipheral
41  *
42  * @{
43  */
44 
45 /**
46  * @file
47  * @brief Implementation of virtual UART device.
48  *
49  * This file implements all the APIs to support virtual UART device. It also defines some helper functions to simulate
50  * the device that are commonly used in this file.
51  */
52 
53 #define init_vuart_lock(vu)	spinlock_init(&((vu)->lock))
54 #define obtain_vuart_lock(vu, flags)	spinlock_irqsave_obtain(&((vu)->lock), &(flags))
55 #define release_vuart_lock(vu, flags)	spinlock_irqrestore_release(&((vu)->lock), (flags))
56 
reset_fifo(struct vuart_fifo * fifo)57 static inline void reset_fifo(struct vuart_fifo *fifo)
58 {
59 	fifo->rindex = 0U;
60 	fifo->windex = 0U;
61 	fifo->num = 0U;
62 }
63 
fifo_putchar(struct vuart_fifo * fifo,char ch)64 static inline void fifo_putchar(struct vuart_fifo *fifo, char ch)
65 {
66 	fifo->buf[fifo->windex] = ch;
67 	if (fifo->num < fifo->size) {
68 		fifo->windex = (fifo->windex + 1U) % fifo->size;
69 		fifo->num++;
70 	} else {
71 		fifo->rindex = (fifo->rindex + 1U) % fifo->size;
72 		fifo->windex = (fifo->windex + 1U) % fifo->size;
73 	}
74 }
75 
fifo_getchar(struct vuart_fifo * fifo)76 static inline char fifo_getchar(struct vuart_fifo *fifo)
77 {
78 	char c = -1;
79 
80 	if (fifo->num > 0U) {
81 		c = fifo->buf[fifo->rindex];
82 		fifo->rindex = (fifo->rindex + 1U) % fifo->size;
83 		fifo->num--;
84 	}
85 	return c;
86 }
87 
fifo_numchars(const struct vuart_fifo * fifo)88 static inline uint32_t fifo_numchars(const struct vuart_fifo *fifo)
89 {
90 	return fifo->num;
91 }
92 
fifo_isfull(const struct vuart_fifo * fifo)93 static inline bool fifo_isfull(const struct vuart_fifo *fifo)
94 {
95 	bool ret = false;
96 	/* When the FIFO has less than 16 empty bytes, it should be
97 	 * mask as full. As when the 16550 driver in OS receive the
98 	 * THRE interrupt, it will directly send 16 bytes without
99 	 * checking the LSR(THRE) */
100 
101 	/* Desired value should be 16 bytes, but to improve
102 	 * fault-tolerant, enlarge 16 to 64. So that even the THRE
103 	 * interrupt is raised by mistake, only if it less than 4
104 	 * times, data in FIFO will not be overwritten. */
105 	if ((fifo->size - fifo->num) < 64U) {
106 		ret = true;
107 	}
108 	return ret;
109 }
110 
vuart_putchar(struct acrn_vuart * vu,char ch)111 void vuart_putchar(struct acrn_vuart *vu, char ch)
112 {
113 	uint64_t rflags;
114 
115 	obtain_vuart_lock(vu, rflags);
116 	fifo_putchar(&vu->rxfifo, ch);
117 	release_vuart_lock(vu, rflags);
118 }
119 
vuart_getchar(struct acrn_vuart * vu)120 char vuart_getchar(struct acrn_vuart *vu)
121 {
122 	uint64_t rflags;
123 	char c;
124 
125 	obtain_vuart_lock(vu, rflags);
126 	c = fifo_getchar(&vu->txfifo);
127 	release_vuart_lock(vu, rflags);
128 	return c;
129 }
130 
init_fifo(struct acrn_vuart * vu)131 static inline void init_fifo(struct acrn_vuart *vu)
132 {
133 	vu->txfifo.buf = vu->vuart_tx_buf;
134 	vu->rxfifo.buf = vu->vuart_rx_buf;
135 	vu->txfifo.size = TX_BUF_SIZE;
136 	vu->rxfifo.size = RX_BUF_SIZE;
137 	reset_fifo(&(vu->txfifo));
138 	reset_fifo(&(vu->rxfifo));
139 }
140 
141 /*
142  * The IIR returns a prioritized interrupt reason:
143  * - receive data available
144  * - transmit holding register empty
145  *
146  * Return an interrupt reason if one is available.
147  */
vuart_intr_reason(const struct acrn_vuart * vu)148 static uint8_t vuart_intr_reason(const struct acrn_vuart *vu)
149 {
150 	uint8_t ret;
151 
152 	if (((vu->lsr & (LSR_OE | LSR_BI)) != 0U) && ((vu->ier & IER_ELSI) != 0U)) {
153 		ret = IIR_RLS;
154 	} else if ((fifo_numchars(&vu->rxfifo) > 0U) && ((vu->ier & IER_ERBFI) != 0U)) {
155 		ret = IIR_RXRDY;
156 	} else if (vu->thre_int_pending && ((vu->ier & IER_ETBEI) != 0U)) {
157 		ret = IIR_TXRDY;
158 	} else if(((vu->msr & MSR_DELTA_MASK) != 0U) && ((vu->ier & IER_EMSC) != 0U)) {
159 		ret = IIR_MLSC;
160 	} else {
161 		ret = IIR_NOPEND;
162 	}
163 	return ret;
164 }
165 
find_vuart_by_port(struct acrn_vm * vm,uint16_t offset)166 static struct acrn_vuart *find_vuart_by_port(struct acrn_vm *vm, uint16_t offset)
167 {
168 	uint8_t i;
169 	struct acrn_vuart *vu, *ret_vu = NULL;
170 
171 	/* TODO: support pci vuart find */
172 	for (i = 0U; i < MAX_VUART_NUM_PER_VM; i++) {
173 		vu = &vm->vuart[i];
174 		if ((vu->active) && (vu->port_base == (offset & ~0x7U))) {
175 			ret_vu = vu;
176 			break;
177 		}
178 	}
179 	return ret_vu;
180 }
181 
vuart_trigger_level_intr(const struct acrn_vuart * vu,bool assert)182 static void vuart_trigger_level_intr(const struct acrn_vuart *vu, bool assert)
183 {
184 	union ioapic_rte rte;
185 	uint32_t operation;
186 
187 	vioapic_get_rte(vu->vm, vu->irq, &rte);
188 
189 	/* TODO:
190 	 * Here should assert vuart irq according to vCOM1_IRQ polarity.
191 	 * The best way is to get the polarity info from ACPI table.
192 	 * Here we just get the info from vioapic configuration.
193 	 * based on this, we can still have irq storm during guest
194 	 * modify the vioapic setting, as it's only for debug uart,
195 	 * we want to make it as an known issue.
196 	 */
197 	if (rte.bits.intr_polarity == IOAPIC_RTE_INTPOL_ALO) {
198 		operation = assert ? GSI_SET_LOW : GSI_SET_HIGH;
199 	} else {
200 		operation = assert ? GSI_SET_HIGH : GSI_SET_LOW;
201 	}
202 
203 	vpic_set_irqline(vm_pic(vu->vm), vu->irq, operation);
204 	vioapic_set_irqline_lock(vu->vm, vu->irq, operation);
205 }
206 
207 /*
208  * Toggle the COM port's intr pin depending on whether or not we have an
209  * interrupt condition to report to the processor.
210  */
vuart_toggle_intr(const struct acrn_vuart * vu)211 void vuart_toggle_intr(const struct acrn_vuart *vu)
212 {
213 	uint8_t intr_reason;
214 
215 	intr_reason = vuart_intr_reason(vu);
216 
217 	if ((vu->vdev != NULL) && (intr_reason != IIR_NOPEND)) {
218 		/* FIXME: Toggle is for level trigger interrupt, for edge trigger need refine the logic later. */
219 		trigger_vmcs9900_msix(vu->vdev);
220 	} else if (intr_reason != IIR_NOPEND) {
221 		vuart_trigger_level_intr(vu, true);
222 	} else {
223 		vuart_trigger_level_intr(vu, false);
224 	}
225 }
226 
send_to_target(struct acrn_vuart * vu,uint8_t value_u8)227 static bool send_to_target(struct acrn_vuart *vu, uint8_t value_u8)
228 {
229 	uint64_t rflags;
230 	bool ret = false;
231 
232 	obtain_vuart_lock(vu, rflags);
233 	if (vu->active) {
234 		fifo_putchar(&vu->rxfifo, (char)value_u8);
235 		if (fifo_isfull(&vu->rxfifo)) {
236 			ret = true;
237 		}
238 		vuart_toggle_intr(vu);
239 	}
240 	release_vuart_lock(vu, rflags);
241 	return ret;
242 }
243 
get_modem_status(uint8_t mcr)244 static uint8_t get_modem_status(uint8_t mcr)
245 {
246 	uint8_t msr;
247 
248 	if ((mcr & MCR_LOOPBACK) != 0U) {
249 		/*
250 		 * In the loopback mode certain bits from the MCR are
251 		 * reflected back into MSR.
252 		 */
253 		msr = 0U;
254 		if ((mcr & MCR_RTS) != 0U) {
255 			msr |= MSR_CTS;
256 		}
257 		if ((mcr & MCR_DTR) != 0U) {
258 			msr |= MSR_DSR;
259 		}
260 		if ((mcr & MCR_OUT1) != 0U) {
261 			msr |= MSR_RI;
262 		}
263 		if ((mcr & MCR_OUT2) != 0U) {
264 			msr |= MSR_DCD;
265 		}
266 	} else {
267 		/*
268 		 * Always assert DCD and DSR so tty open doesn't block
269 		 * even if CLOCAL is turned off.
270 		 */
271 		msr = MSR_DCD | MSR_DSR;
272 	}
273 	return msr;
274 }
275 
update_modem_status(uint8_t new_msr,uint8_t old_msr)276 static uint8_t update_modem_status(uint8_t new_msr, uint8_t old_msr)
277 {
278 	uint8_t update_msr = old_msr;
279 	/*
280 	 * Detect if there has been any change between the
281 	 * previous and the new value of MSR. If there is
282 	 * then assert the appropriate MSR delta bit.
283 	 */
284 	if (((new_msr & MSR_CTS) ^ (old_msr & MSR_CTS)) != 0U) {
285 		update_msr |= MSR_DCTS;
286 	}
287 	if (((new_msr & MSR_DSR) ^ (old_msr & MSR_DSR)) != 0U) {
288 		update_msr |= MSR_DDSR;
289 	}
290 	if (((new_msr & MSR_DCD) ^ (old_msr & MSR_DCD)) != 0U) {
291 		update_msr |= MSR_DDCD;
292 	}
293 	if (((new_msr & MSR_RI) == 0U) && ((old_msr & MSR_RI) != 0U)) {
294 		update_msr |= MSR_TERI;
295 	}
296 	update_msr &= MSR_DELTA_MASK;
297 	update_msr |= new_msr;
298 
299 	return update_msr;
300 }
301 
302 /*
303  * @pre: vu != NULL
304  */
write_reg(struct acrn_vuart * vu,uint16_t reg,uint8_t value_u8)305 static void write_reg(struct acrn_vuart *vu, uint16_t reg, uint8_t value_u8)
306 {
307 	uint8_t msr;
308 	uint64_t rflags;
309 
310 	obtain_vuart_lock(vu, rflags);
311 	/*
312 	 * Take care of the special case DLAB accesses first
313 	 */
314 	if (((vu->lcr & LCR_DLAB) != 0U) && (reg == UART16550_DLL)) {
315 		vu->dll = value_u8;
316 	} else if (((vu->lcr & LCR_DLAB) != 0U) && (reg == UART16550_DLM)) {
317 		vu->dlh = value_u8;
318 	} else {
319 		switch (reg) {
320 		case UART16550_THR:
321 			if ((vu->mcr & MCR_LOOPBACK) != 0U) {
322 				fifo_putchar(&vu->rxfifo, (char)value_u8);
323 				vu->lsr |= LSR_OE;
324 			} else {
325 				fifo_putchar(&vu->txfifo, (char)value_u8);
326 			}
327 			vu->thre_int_pending = true;
328 			break;
329 		case UART16550_IER:
330 			if (((vu->ier & IER_ETBEI) == 0U) && ((value_u8 & IER_ETBEI) != 0U)) {
331 				vu->thre_int_pending = true;
332 			}
333 			/*
334 			 * Apply mask so that bits 4-7 are 0
335 			 * Also enables bits 0-3 only if they're 1
336 			 */
337 			vu->ier = value_u8 & 0x0FU;
338 			break;
339 		case UART16550_FCR:
340 			/*
341 			 * The FCR_ENABLE bit must be '1' for the programming
342 			 * of other FCR bits to be effective.
343 			 */
344 			if ((value_u8 & FCR_FIFOE) == 0U) {
345 				vu->fcr = 0U;
346 			} else {
347 				if ((value_u8 & FCR_RFR) != 0U) {
348 					reset_fifo(&vu->rxfifo);
349 				}
350 				vu->fcr = value_u8 & (FCR_FIFOE | FCR_DMA | FCR_RX_MASK);
351 			}
352 			break;
353 		case UART16550_LCR:
354 			vu->lcr = value_u8;
355 			break;
356 		case UART16550_MCR:
357 			/* Apply mask so that bits 5-7 are 0 */
358 			vu->mcr = value_u8 & 0x1FU;
359 			msr = get_modem_status(vu->mcr);
360 			/*
361 			 * Update the value of MSR while retaining the delta
362 			 * bits.
363 			 */
364 			vu->msr = update_modem_status(msr, vu->msr);
365 			break;
366 		case UART16550_LSR:
367 			/*
368 			 * Line status register is not meant to be written to
369 			 * during normal operation.
370 			 */
371 			break;
372 		case UART16550_MSR:
373 			/*
374 			 * As far as I can tell MSR is a read-only register.
375 			 */
376 			break;
377 		case UART16550_SCR:
378 			vu->scr = value_u8;
379 			break;
380 		default:
381 			/*
382 			 * For the reg that is not handled (either a read-only
383 			 * register or an invalid register), ignore the write to it.
384 			 * Gracefully return if prior case clauses have not been met.
385 			 */
386 			break;
387 		}
388 	}
389 	vuart_toggle_intr(vu);
390 	release_vuart_lock(vu, rflags);
391 }
392 
393 /**
394  * @brief Write a value to a register in the virtual UART.
395  *
396  * This function writes a 8-bit value to a specified register in the virtual UART (vUART). It is a basic function used
397  * for port I/O write or MMIO write.
398  *
399  * - When the following conditions are met, data is sent to the target vUART's RXFIFO:
400  *   1) The target vUART exists for the specified vUART, which is used for communication.
401  *   2) The accessed register is the THR (Transmitter Holding Register).
402  *   3) Loopback mode is not enabled.
403  *   4) DLAB (Divisor Latch Access Bit) is not set.
404  *   - Additionally, to ensure reliable communication, it raises the THRE interrupt (indicating that more data can be
405  *     processed) only if the target vUART's RXFIFO is not full.
406  * - If these conditions are not met, the virtual registers specified by the offset are updated according to the 16550
407  *   UART specification.
408  *
409  * @param[inout] vu The virtual UART structure to which the register value is to be written.
410  * @param[in] offset The offset of the register within the vUART.
411  * @param[in] value_u8 The 8-bit value to be written to the register.
412  *
413  * @return None
414  *
415  * @pre vu != NULL
416  *
417  * @post N/A
418  */
vuart_write_reg(struct acrn_vuart * vu,uint16_t offset,uint8_t value_u8)419 void vuart_write_reg(struct acrn_vuart *vu, uint16_t offset, uint8_t value_u8)
420 {
421 	struct acrn_vuart *target_vu = NULL;
422 	uint64_t rflags;
423 
424 	target_vu = vu->target_vu;
425 
426 	if (((vu->mcr & MCR_LOOPBACK) == 0U) && ((vu->lcr & LCR_DLAB) == 0U)
427 		&& (offset == UART16550_THR) && (target_vu != NULL)) {
428 		if (!send_to_target(target_vu, value_u8)) {
429 			/* FIFO is not full, raise THRE interrupt */
430 			obtain_vuart_lock(vu, rflags);
431 			vu->thre_int_pending = true;
432 			vuart_toggle_intr(vu);
433 			release_vuart_lock(vu, rflags);
434 		}
435 	} else {
436 		write_reg(vu, offset, value_u8);
437 	}
438 }
439 
440 /**
441  * @brief Write a value to a port in the legacy virtual UART.
442  *
443  * This function writes a value to the legacy virtual UART (vUART) based on the specified port address. It is used to
444  * handle I/O port write operations in the VM by updating the vUART's register. This function is typically called when
445  * the vCPU needs to write data to the vUART during emulation of I/O port operations.
446  *
447  * - Based on the specified port address, it first finds the vUART device within the VM corresponding to the given vCPU.
448  * - If the vUART is found, the value is written to the corresponding register. For detailed write operations, refer to
449  *   vuart_write_reg().
450  * - If the vUART is not found, the write operation is ignored.
451  *
452  * @param[inout] vcpu A pointer to the vCPU that initiates the write operation.
453  * @param[in] offset_arg The port address to write to.
454  * @param[in] width The width of the write operation (unused in this function).
455  * @param[in] value The value to be written to the register.
456  *
457  * @return Always returns true.
458  *
459  * @pre vcpu != NULL
460  * @pre vcpu->vm != NULL
461  *
462  * @post N/A
463  */
vuart_write(struct acrn_vcpu * vcpu,uint16_t offset_arg,__unused size_t width,uint32_t value)464 static bool vuart_write(struct acrn_vcpu *vcpu, uint16_t offset_arg,
465 			__unused size_t width, uint32_t value)
466 {
467 	uint16_t offset = offset_arg;
468 	struct acrn_vuart *vu = find_vuart_by_port(vcpu->vm, offset);
469 	uint8_t value_u8 = (uint8_t)value;
470 
471 	if (vu != NULL) {
472 		offset -= vu->port_base;
473 		vuart_write_reg(vu, offset, value_u8);
474 	}
475 	return true;
476 }
477 
notify_target(const struct acrn_vuart * vu)478 static void notify_target(const struct acrn_vuart *vu)
479 {
480 	struct acrn_vuart *t_vu;
481 	uint64_t rflags;
482 
483 	if (vu != NULL) {
484 		t_vu = vu->target_vu;
485 		if ((t_vu != NULL) && !fifo_isfull(&vu->rxfifo)) {
486 			obtain_vuart_lock(t_vu, rflags);
487 			t_vu->thre_int_pending = true;
488 			vuart_toggle_intr(t_vu);
489 			release_vuart_lock(t_vu, rflags);
490 		}
491 	}
492 }
493 
494 /**
495  * @brief Read a register from the virtual UART.
496  *
497  * This function returns the 8-bit value of a specified register. It is a basic function used for port I/O read or MMIO
498  * read. The registers in the UART will affect each other, such as reading the LSR register will clear some bits in it.
499  * This function carefully simulates this behavior.
500  *
501  * - If the DLAB bit in LCR is set, only the DLL and DLH registers are accessed. Other registers are considered as 0.
502  * - Otherwise, according to the UART16550 specification, set and read the corresponding register. For registers greater
503  *   than 0x07 (SCR), the value will be 0xFF.
504  * - It will toggle the interrupt.
505  * - For communication vUART, when the data in FIFO is read out (read from RBR), it will notify the target vUART to send
506  *   more data.
507  * - Finally, it will return the value of the specified register.
508  *
509  * @param[inout] vu Pointer to the virtual UART device.
510  * @param[in] offset The specified offset of the register to read.
511  *
512  * @return The value of the specified register.
513  *
514  * @pre vu != NULL
515  *
516  * @post N/A
517  */
vuart_read_reg(struct acrn_vuart * vu,uint16_t offset)518 uint8_t vuart_read_reg(struct acrn_vuart *vu, uint16_t offset)
519 {
520 	struct acrn_vuart *t_vu;
521 	uint8_t iir, reg = 0U, intr_reason;
522 	uint64_t rflags;
523 
524 	t_vu = vu->target_vu;
525 	obtain_vuart_lock(vu, rflags);
526 	/*
527 	 * Take care of the special case DLAB accesses first
528 	 */
529 	if ((vu->lcr & LCR_DLAB) != 0U) {
530 		if (offset == UART16550_DLL) {
531 			reg = vu->dll;
532 		} else if (offset == UART16550_DLM) {
533 			reg = vu->dlh;
534 		} else {
535 			reg = 0U;
536 		}
537 	} else {
538 		switch (offset) {
539 		case UART16550_RBR:
540 			vu->lsr &= ~LSR_OE;
541 			reg = (uint8_t)fifo_getchar(&vu->rxfifo);
542 			break;
543 		case UART16550_IER:
544 			reg = vu->ier;
545 			break;
546 		case UART16550_IIR:
547 			iir = ((vu->fcr & FCR_FIFOE) != 0U) ? IIR_FIFO_MASK : 0U;
548 			intr_reason = vuart_intr_reason(vu);
549 			/*
550 			 * Deal with side effects of reading the IIR register
551 			 */
552 			if (intr_reason == IIR_TXRDY) {
553 				vu->thre_int_pending = false;
554 			}
555 			iir |= intr_reason;
556 			reg = iir;
557 			break;
558 		case UART16550_LCR:
559 			reg = vu->lcr;
560 			break;
561 		case UART16550_MCR:
562 			reg = vu->mcr;
563 			break;
564 		case UART16550_LSR:
565 			if (t_vu != NULL) {
566 				if (!fifo_isfull(&t_vu->rxfifo)) {
567 					vu->lsr |= LSR_TEMT | LSR_THRE;
568 				}
569 			} else {
570 				vu->lsr |= LSR_TEMT | LSR_THRE;
571 			}
572 			/* Check for new receive data */
573 			if (fifo_numchars(&vu->rxfifo) > 0U) {
574 				vu->lsr |= LSR_DR;
575 			} else {
576 				vu->lsr &= ~LSR_DR;
577 			}
578 			reg = vu->lsr;
579 			/* The LSR_OE bit is cleared on LSR read */
580 			vu->lsr &= ~(LSR_OE | LSR_BI);
581 			break;
582 		case UART16550_MSR:
583 			/*
584 			 * MSR delta bits are cleared on read
585 			 */
586 			reg = vu->msr;
587 			vu->msr &= ~MSR_DELTA_MASK;
588 			break;
589 		case UART16550_SCR:
590 			reg = vu->scr;
591 			break;
592 		default:
593 			reg = 0xFFU;
594 			break;
595 		}
596 	}
597 	vuart_toggle_intr(vu);
598 	release_vuart_lock(vu, rflags);
599 
600 	/* For commnunication vuart, when the data in FIFO is read out, should
601 	 * notify the target vuart to send more data. */
602 	if (offset == UART16550_RBR) {
603 		notify_target(vu);
604 	}
605 
606 	return reg;
607 }
608 
609 /**
610  * @brief Read a value from a port in the legacy virtual UART.
611  *
612  * This function reads a value from the legacy virtual UART (vUART) based on the specified port address. It is used to
613  * handle I/O port read operations in the VM by retrieving the value from the vUART's registers. This function is
614  * typically called when the vCPU needs to read data from the vUART during emulation of I/O port operations.
615  *
616  * - Based on the specified port address, it first finds the vUART device within the VM corresponding to the given vCPU.
617  * - If the vUART is found, the value is read from the corresponding virtual register and stored in the vCPU's PIO
618  *   request. For detailed read operations, refer to vuart_read_reg().
619  * - If the vUART is not found, the vCPU's PIO request remains unchanged.
620  *
621  * @param[inout] vcpu A pointer to the vCPU that initiates the read operation.
622  * @param[in] offset_arg The port address to read from.
623  * @param[in] width The width of the read operation (unused in this function).
624  *
625  * @return Always returns true.
626  *
627  * @pre vcpu != NULL
628  * @pre vcpu->vm != NULL
629  *
630  * @post N/A
631  */
vuart_read(struct acrn_vcpu * vcpu,uint16_t offset_arg,__unused size_t width)632 static bool vuart_read(struct acrn_vcpu *vcpu, uint16_t offset_arg, __unused size_t width)
633 {
634 	uint16_t offset = offset_arg;
635 	struct acrn_vuart *vu = find_vuart_by_port(vcpu->vm, offset);
636 	struct acrn_pio_request *pio_req = &vcpu->req.reqs.pio_request;
637 
638 	if (vu != NULL) {
639 		offset -= vu->port_base;
640 		pio_req->value = (uint32_t)vuart_read_reg(vu, offset);
641 	}
642 
643 	return true;
644 }
645 
646 /*
647  * @pre: vuart_idx < MAX_VUART_NUM_PER_VM
648  */
vuart_register_io_handler(struct acrn_vm * vm,uint16_t port_base,uint32_t vuart_idx)649 static bool vuart_register_io_handler(struct acrn_vm *vm, uint16_t port_base, uint32_t vuart_idx)
650 {
651 	bool ret = true;
652 
653 	struct vm_io_range range = {
654 		.base = port_base,
655 		.len = 8U
656 	};
657 	if (vuart_idx < MAX_VUART_NUM_PER_VM) {
658 		register_pio_emulation_handler(vm, UART_PIO_IDX0 + vuart_idx, &range, vuart_read, vuart_write);
659 	} else {
660 		printf("Not support vuart index %d, will not register \n", vuart_idx);
661 		ret = false;
662 	}
663 	return ret;
664 }
665 
setup_vuart(struct acrn_vm * vm,uint16_t vuart_idx)666 static void setup_vuart(struct acrn_vm *vm, uint16_t vuart_idx)
667 {
668 	uint32_t divisor;
669 	struct acrn_vuart *vu = &vm->vuart[vuart_idx];
670 
671 	/* Set baud rate*/
672 	divisor = (UART_CLOCK_RATE / BAUD_115200) >> 4U;
673 	vu->dll = (uint8_t)divisor;
674 	vu->dlh = (uint8_t)(divisor >> 8U);
675 	vu->vm = vm;
676 	init_fifo(vu);
677 	init_vuart_lock(vu);
678 	vu->thre_int_pending = true;
679 	vu->ier = 0U;
680 	vuart_toggle_intr(vu);
681 	vu->target_vu = NULL;
682 }
683 
find_active_target_vuart(const struct vuart_config * vu_config)684 static struct acrn_vuart *find_active_target_vuart(const struct vuart_config *vu_config)
685 {
686 	struct acrn_vm *target_vm = NULL;
687 	struct acrn_vuart *target_vu = NULL, *ret_vu = NULL;
688 	uint16_t target_vmid, target_vuid;
689 
690 	target_vmid = vu_config->t_vuart.vm_id;
691 	target_vuid = vu_config->t_vuart.vuart_id;
692 
693 	if ((target_vmid < CONFIG_MAX_VM_NUM) && (target_vuid < MAX_VUART_NUM_PER_VM)) {
694 		target_vm = get_vm_from_vmid(target_vmid);
695 		target_vu = &target_vm->vuart[target_vuid];
696 
697 		if ((target_vu != NULL) && (target_vu->active)) {
698 			ret_vu = target_vu;
699 		}
700 	}
701 
702 	return ret_vu;
703 }
704 
vuart_setup_connection(struct acrn_vm * vm,const struct vuart_config * vu_config,uint16_t vuart_idx)705 static void vuart_setup_connection(struct acrn_vm *vm,
706 		const struct vuart_config *vu_config, uint16_t vuart_idx)
707 {
708 	struct acrn_vuart *vu, *t_vu;
709 
710 	vu = &vm->vuart[vuart_idx];
711 	if (vu->active) {
712 		t_vu = find_active_target_vuart(vu_config);
713 		if ((t_vu != NULL) && (t_vu->target_vu == NULL)) {
714 			vu->target_vu = t_vu;
715 			t_vu->target_vu = vu;
716 		}
717 	}
718 }
719 
vuart_deinit_connection(struct acrn_vuart * vu)720 static void vuart_deinit_connection(struct acrn_vuart *vu)
721 {
722 	struct acrn_vuart *t_vu = vu->target_vu;
723 
724 	t_vu->target_vu = NULL;
725 	vu->target_vu = NULL;
726 }
727 
728 /**
729  * @brief Check if any of the vUARTs in the given VM uses the specified INTx interrupt.
730  *
731  * This function checks whether the INTx interrupt is already used by vUART. It's usually used when the hypervisor
732  * tries to add a new INTx remapping.
733  *
734  * It will check all the vUARTs in the VM to see if any of them uses the specified INTx interrupt. If any of the vUARTs
735  * is active and using the specified INTx interrupt, the function will return true. Otherwise, it will return false.
736  *
737  * @param[in] vm Pointer to the VM.
738  * @param[in] intx_gsi The INTx interrupt number to check against the vUART configurations.
739  *
740  * @return A boolean value indicating if any of the vUARTs in the VM uses the specified INTx interrupt.
741  *
742  * @retval true If any of the vUARTs in the VM uses the specified INTx interrupt.
743  * @retval false If none of the vUARTs in the VM uses the specified INTx interrupt.
744  *
745  * @pre vm != NULL
746  *
747  * @post N/A
748  */
is_vuart_intx(const struct acrn_vm * vm,uint32_t intx_gsi)749 bool is_vuart_intx(const struct acrn_vm *vm, uint32_t intx_gsi)
750 {
751 	uint8_t i;
752 	bool ret = false;
753 
754 	for (i = 0U; i < MAX_VUART_NUM_PER_VM; i++) {
755 		if ((vm->vuart[i].active) && (vm->vuart[i].irq == intx_gsi)) {
756 			ret = true;
757 		}
758 	}
759 	return ret;
760 }
761 
762 /**
763  * @brief Initialize legacy virtual UART devices.
764  *
765  * This function initializes the legacy virtual UARTs (vUARTs) in hypervisor. A vUART is emulated as a 16550 UART device
766  * and can exchange data between the hypervisor and a VM or between two VMs. It sets up the necessary configurations and
767  * resources required for the vUARTs to function correctly. This function is usually called during VM creation.
768  *
769  * A VM can have several vUARTs (including legacy and PCI vUARTs). The first vUART is used for the VM console, and the
770  * rest are used for communication between VMs. Every legacy vUART device defined in the vUART configuration list is
771  * initialized and configured. It will also register port I/O handlers for every vUART device and set up the connection
772  * between vUARTs for communication.
773  *
774  * @param[inout] vm Pointer to the VM that owns the vUART devices.
775  * @param[in] vu_config Pointer to the vUART configuration structure list that contains the configuration information.
776  *
777  * @return None
778  *
779  * @pre vm != NULL
780  * @pre vu_config != NULL
781  *
782  * @post N/A
783  */
init_legacy_vuarts(struct acrn_vm * vm,const struct vuart_config * vu_config)784 void init_legacy_vuarts(struct acrn_vm *vm, const struct vuart_config *vu_config)
785 {
786 	uint8_t i;
787 	struct acrn_vuart *vu;
788 
789 	for (i = 0U; i < MAX_VUART_NUM_PER_VM; i++) {
790 		if ((vu_config[i].type == VUART_LEGACY_PIO) &&
791 				(vu_config[i].addr.port_base != INVALID_COM_BASE)) {
792 			vu = &vm->vuart[i];
793 			setup_vuart(vm, i);
794 			vu->port_base = vu_config[i].addr.port_base;
795 			vu->irq = vu_config[i].irq;
796 			if (vuart_register_io_handler(vm, vu->port_base, i) != 0U) {
797 				vu->active = true;
798 				vu->escaping = false;
799 			}
800 			/*
801 			 * The first vuart is used for VM console.
802 			 * The rest of vuarts are used for connection.
803 			 */
804 			if (i != 0U) {
805 				vuart_setup_connection(vm, &vu_config[i], i);
806 			}
807 		}
808 	}
809 }
810 
811 /**
812  * @brief Deinitialize legacy virtual UART devices.
813  *
814  * This function deinitializes the legacy virtual UARTs (vUARTs) in hypervisor. It cleans up the resources and
815  * configurations that were set up for the vUARTs during initialization. This function should be called when the vUARTs
816  * are no longer needed, such as when a VM is being destroyed.
817  *
818  * The function will deinitialize all vUARTs associated with the given VM. It will set the active flag to false and
819  * remove the connection between vUARTs for communication.
820  *
821  * @param[inout] vm Pointer to the VM that owns the vUART devices.
822  *
823  * @return None
824  *
825  * @pre vm != NULL
826  *
827  * @post N/A
828  */
deinit_legacy_vuarts(struct acrn_vm * vm)829 void deinit_legacy_vuarts(struct acrn_vm *vm)
830 {
831 	uint8_t i;
832 
833 	for (i = 0U; i < MAX_VUART_NUM_PER_VM; i++) {
834 		if (vm->vuart[i].port_base != INVALID_COM_BASE) {
835 			vm->vuart[i].active = false;
836 			vm->vuart[i].escaping = false;
837 			if (vm->vuart[i].target_vu != NULL) {
838 				vuart_deinit_connection(&vm->vuart[i]);
839 			}
840 		}
841 	}
842 }
843 
844 /**
845  * @brief Initialize a PCI virtual UART device.
846  *
847  * This function initializes a PCI-based virtual UART (vUART) in hypervisor. A MCS9900 controller is emulated as a PCI
848  * device, and the vUART device is a part of the MCS9900 controller. This function is usually called during the VM
849  * creation and after the MCS9900 controller device is initialized.
850  *
851  * A VM can have several vUARTs (including legacy and PCI vUARTs). The first vUART is used for the VM console, and the
852  * rest are used for communication between VMs. The PCI vUARTs are only used for communication between VMs for now. It
853  * will initialize the vUART associated with the given PCI device and set up the connection between vUARTs for
854  * communication.
855  *
856  * @param[inout] vdev Pointer to the PCI device that owns the vUART.
857  *
858  * @return None
859  *
860  * @pre vdev != NULL
861  *
862  * @post N/A
863  */
init_pci_vuart(struct pci_vdev * vdev)864 void init_pci_vuart(struct pci_vdev *vdev)
865 {
866 	struct acrn_vuart *vu = vdev->priv_data;
867 	struct acrn_vm_pci_dev_config *pci_cfg = vdev->pci_dev_config;
868 	uint16_t idx = pci_cfg->vuart_idx;
869 	struct acrn_vm *vm = container_of(vdev->vpci, struct acrn_vm, vpci);
870 	struct acrn_vm_config *vm_cfg = get_vm_config(vm->vm_id);
871 
872 	setup_vuart(vm, idx);
873 	vu->vdev = vdev;
874 	vm_cfg->vuart[idx].type = VUART_PCI;
875 	vm_cfg->vuart[idx].t_vuart.vm_id = pci_cfg->t_vuart.vm_id;
876 	vm_cfg->vuart[idx].t_vuart.vuart_id = pci_cfg->t_vuart.vuart_id;
877 
878 	vu->active = true;
879 	vu->escaping = false;
880 	if (pci_cfg->vuart_idx != 0U) {
881 		vuart_setup_connection(vm, &vm_cfg->vuart[idx], idx);
882 	}
883 
884 }
885 
886 /**
887  * @brief Deinitialize a PCI virtual UART device.
888  *
889  * This function deinitializes a PCI virtual UART (vUART) in hypervisor. It cleans up the resources and configurations
890  * that were set up for the vUART during initialization. This function should be called when the vUART is no longer
891  * needed, such as when a VM is being destroyed.
892  *
893  * The function will deinitialize the vUART associated with the given PCI device. It will set the active flag to false
894  * and remove the connection between vUARTs for communication.
895  *
896  * @param[inout] vdev Pointer to the PCI device that owns the vUART.
897  *
898  * @return None
899  *
900  * @pre vdev != NULL
901  *
902  * @post N/A
903  */
deinit_pci_vuart(struct pci_vdev * vdev)904 void deinit_pci_vuart(struct pci_vdev *vdev)
905 {
906 	struct acrn_vuart *vu = vdev->priv_data;
907 
908 	vu->active = false;
909 	vu->escaping = false;
910 	if (vu->target_vu != NULL) {
911 		vuart_deinit_connection(vu);
912 	}
913 }
914 
915 /**
916  * @}
917  */