xref: /qemu/hw/char/riscv_htif.c (revision 5db05230)
1 /*
2  * QEMU RISC-V Host Target Interface (HTIF) Emulation
3  *
4  * Copyright (c) 2016-2017 Sagar Karandikar, sagark@eecs.berkeley.edu
5  * Copyright (c) 2017-2018 SiFive, Inc.
6  *
7  * This provides HTIF device emulation for QEMU. At the moment this allows
8  * for identical copies of bbl/linux to run on both spike and QEMU.
9  *
10  * This program is free software; you can redistribute it and/or modify it
11  * under the terms and conditions of the GNU General Public License,
12  * version 2 or later, as published by the Free Software Foundation.
13  *
14  * This program is distributed in the hope it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
17  * more details.
18  *
19  * You should have received a copy of the GNU General Public License along with
20  * this program.  If not, see <http://www.gnu.org/licenses/>.
21  */
22 
23 #include "qemu/osdep.h"
24 #include "qapi/error.h"
25 #include "qemu/log.h"
26 #include "hw/char/riscv_htif.h"
27 #include "hw/char/serial.h"
28 #include "chardev/char.h"
29 #include "chardev/char-fe.h"
30 #include "qemu/timer.h"
31 #include "qemu/error-report.h"
32 #include "exec/address-spaces.h"
33 #include "exec/tswap.h"
34 #include "sysemu/dma.h"
35 #include "sysemu/runstate.h"
36 
37 #define RISCV_DEBUG_HTIF 0
38 #define HTIF_DEBUG(fmt, ...)                                                   \
39     do {                                                                       \
40         if (RISCV_DEBUG_HTIF) {                                                \
41             qemu_log_mask(LOG_TRACE, "%s: " fmt "\n", __func__, ##__VA_ARGS__);\
42         }                                                                      \
43     } while (0)
44 
45 #define HTIF_DEV_SHIFT          56
46 #define HTIF_CMD_SHIFT          48
47 
48 #define HTIF_DEV_SYSTEM         0
49 #define HTIF_DEV_CONSOLE        1
50 
51 #define HTIF_SYSTEM_CMD_SYSCALL 0
52 #define HTIF_CONSOLE_CMD_GETC   0
53 #define HTIF_CONSOLE_CMD_PUTC   1
54 
55 /* PK system call number */
56 #define PK_SYS_WRITE            64
57 
58 const char *sig_file;
59 uint8_t line_size = 16;
60 
61 static uint64_t fromhost_addr, tohost_addr, begin_sig_addr, end_sig_addr;
62 
63 void htif_symbol_callback(const char *st_name, int st_info, uint64_t st_value,
64                           uint64_t st_size)
65 {
66     if (strcmp("fromhost", st_name) == 0) {
67         fromhost_addr = st_value;
68         if (st_size != 8) {
69             error_report("HTIF fromhost must be 8 bytes");
70             exit(1);
71         }
72     } else if (strcmp("tohost", st_name) == 0) {
73         tohost_addr = st_value;
74         if (st_size != 8) {
75             error_report("HTIF tohost must be 8 bytes");
76             exit(1);
77         }
78     } else if (strcmp("begin_signature", st_name) == 0) {
79         begin_sig_addr = st_value;
80     } else if (strcmp("end_signature", st_name) == 0) {
81         end_sig_addr = st_value;
82     }
83 }
84 
85 /*
86  * Called by the char dev to see if HTIF is ready to accept input.
87  */
88 static int htif_can_recv(void *opaque)
89 {
90     return 1;
91 }
92 
93 /*
94  * Called by the char dev to supply input to HTIF console.
95  * We assume that we will receive one character at a time.
96  */
97 static void htif_recv(void *opaque, const uint8_t *buf, int size)
98 {
99     HTIFState *s = opaque;
100 
101     if (size != 1) {
102         return;
103     }
104 
105     /*
106      * TODO - we need to check whether mfromhost is zero which indicates
107      *        the device is ready to receive. The current implementation
108      *        will drop characters
109      */
110 
111     uint64_t val_written = s->pending_read;
112     uint64_t resp = 0x100 | *buf;
113 
114     s->fromhost = (val_written >> 48 << 48) | (resp << 16 >> 16);
115 }
116 
117 /*
118  * Called by the char dev to supply special events to the HTIF console.
119  * Not used for HTIF.
120  */
121 static void htif_event(void *opaque, QEMUChrEvent event)
122 {
123 
124 }
125 
126 static int htif_be_change(void *opaque)
127 {
128     HTIFState *s = opaque;
129 
130     qemu_chr_fe_set_handlers(&s->chr, htif_can_recv, htif_recv, htif_event,
131         htif_be_change, s, NULL, true);
132 
133     return 0;
134 }
135 
136 /*
137  * See below the tohost register format.
138  *
139  * Bits 63:56 indicate the "device".
140  * Bits 55:48 indicate the "command".
141  *
142  * Device 0 is the syscall device, which is used to emulate Unixy syscalls.
143  * It only implements command 0, which has two subfunctions:
144  * - If bit 0 is clear, then bits 47:0 represent a pointer to a struct
145  *   describing the syscall.
146  * - If bit 1 is set, then bits 47:1 represent an exit code, with a zero
147  *   value indicating success and other values indicating failure.
148  *
149  * Device 1 is the blocking character device.
150  * - Command 0 reads a character
151  * - Command 1 writes a character from the 8 LSBs of tohost
152  *
153  * For RV32, the tohost register is zero-extended, so only device=0 and
154  * command=0 (i.e. HTIF syscalls/exit codes) are supported.
155  */
156 static void htif_handle_tohost_write(HTIFState *s, uint64_t val_written)
157 {
158     uint8_t device = val_written >> HTIF_DEV_SHIFT;
159     uint8_t cmd = val_written >> HTIF_CMD_SHIFT;
160     uint64_t payload = val_written & 0xFFFFFFFFFFFFULL;
161     int resp = 0;
162 
163     HTIF_DEBUG("mtohost write: device: %d cmd: %d what: %02" PRIx64
164         " -payload: %016" PRIx64 "\n", device, cmd, payload & 0xFF, payload);
165 
166     /*
167      * Currently, there is a fixed mapping of devices:
168      * 0: riscv-tests Pass/Fail Reporting Only (no syscall proxy)
169      * 1: Console
170      */
171     if (unlikely(device == HTIF_DEV_SYSTEM)) {
172         /* frontend syscall handler, shutdown and exit code support */
173         if (cmd == HTIF_SYSTEM_CMD_SYSCALL) {
174             if (payload & 0x1) {
175                 /* exit code */
176                 int exit_code = payload >> 1;
177 
178                 /*
179                  * Dump signature data if sig_file is specified and
180                  * begin/end_signature symbols exist.
181                  */
182                 if (sig_file && begin_sig_addr && end_sig_addr) {
183                     uint64_t sig_len = end_sig_addr - begin_sig_addr;
184                     char *sig_data = g_malloc(sig_len);
185                     dma_memory_read(&address_space_memory, begin_sig_addr,
186                                     sig_data, sig_len, MEMTXATTRS_UNSPECIFIED);
187                     FILE *signature = fopen(sig_file, "w");
188                     if (signature == NULL) {
189                         error_report("Unable to open %s with error %s",
190                                      sig_file, strerror(errno));
191                         exit(1);
192                     }
193 
194                     for (int i = 0; i < sig_len; i += line_size) {
195                         for (int j = line_size; j > 0; j--) {
196                             if (i + j <= sig_len) {
197                                 fprintf(signature, "%02x",
198                                         sig_data[i + j - 1] & 0xff);
199                             } else {
200                                 fprintf(signature, "%02x", 0);
201                             }
202                         }
203                         fprintf(signature, "\n");
204                     }
205 
206                     fclose(signature);
207                     g_free(sig_data);
208                 }
209 
210                 qemu_system_shutdown_request_with_code(
211                     SHUTDOWN_CAUSE_GUEST_SHUTDOWN, exit_code);
212                 return;
213             } else {
214                 uint64_t syscall[8];
215                 cpu_physical_memory_read(payload, syscall, sizeof(syscall));
216                 if (tswap64(syscall[0]) == PK_SYS_WRITE &&
217                     tswap64(syscall[1]) == HTIF_DEV_CONSOLE &&
218                     tswap64(syscall[3]) == HTIF_CONSOLE_CMD_PUTC) {
219                     uint8_t ch;
220                     cpu_physical_memory_read(tswap64(syscall[2]), &ch, 1);
221                     qemu_chr_fe_write(&s->chr, &ch, 1);
222                     resp = 0x100 | (uint8_t)payload;
223                 } else {
224                     qemu_log_mask(LOG_UNIMP,
225                                   "pk syscall proxy not supported\n");
226                 }
227             }
228         } else {
229             qemu_log("HTIF device %d: unknown command\n", device);
230         }
231     } else if (likely(device == HTIF_DEV_CONSOLE)) {
232         /* HTIF Console */
233         if (cmd == HTIF_CONSOLE_CMD_GETC) {
234             /* this should be a queue, but not yet implemented as such */
235             s->pending_read = val_written;
236             s->tohost = 0; /* clear to indicate we read */
237             return;
238         } else if (cmd == HTIF_CONSOLE_CMD_PUTC) {
239             uint8_t ch = (uint8_t)payload;
240             qemu_chr_fe_write(&s->chr, &ch, 1);
241             resp = 0x100 | (uint8_t)payload;
242         } else {
243             qemu_log("HTIF device %d: unknown command\n", device);
244         }
245     } else {
246         qemu_log("HTIF unknown device or command\n");
247         HTIF_DEBUG("device: %d cmd: %d what: %02" PRIx64
248             " payload: %016" PRIx64, device, cmd, payload & 0xFF, payload);
249     }
250     /*
251      * Latest bbl does not set fromhost to 0 if there is a value in tohost.
252      * With this code enabled, qemu hangs waiting for fromhost to go to 0.
253      * With this code disabled, qemu works with bbl priv v1.9.1 and v1.10.
254      * HTIF needs protocol documentation and a more complete state machine.
255      *
256      *  while (!s->fromhost_inprogress &&
257      *      s->fromhost != 0x0) {
258      *  }
259      */
260     s->fromhost = (val_written >> 48 << 48) | (resp << 16 >> 16);
261     s->tohost = 0; /* clear to indicate we read */
262 }
263 
264 #define TOHOST_OFFSET1      (s->tohost_offset)
265 #define TOHOST_OFFSET2      (s->tohost_offset + 4)
266 #define FROMHOST_OFFSET1    (s->fromhost_offset)
267 #define FROMHOST_OFFSET2    (s->fromhost_offset + 4)
268 
269 /* CPU wants to read an HTIF register */
270 static uint64_t htif_mm_read(void *opaque, hwaddr addr, unsigned size)
271 {
272     HTIFState *s = opaque;
273     if (addr == TOHOST_OFFSET1) {
274         return s->tohost & 0xFFFFFFFF;
275     } else if (addr == TOHOST_OFFSET2) {
276         return (s->tohost >> 32) & 0xFFFFFFFF;
277     } else if (addr == FROMHOST_OFFSET1) {
278         return s->fromhost & 0xFFFFFFFF;
279     } else if (addr == FROMHOST_OFFSET2) {
280         return (s->fromhost >> 32) & 0xFFFFFFFF;
281     } else {
282         qemu_log("Invalid htif read: address %016" PRIx64 "\n",
283             (uint64_t)addr);
284         return 0;
285     }
286 }
287 
288 /* CPU wrote to an HTIF register */
289 static void htif_mm_write(void *opaque, hwaddr addr,
290                           uint64_t value, unsigned size)
291 {
292     HTIFState *s = opaque;
293     if (addr == TOHOST_OFFSET1) {
294         if (s->tohost == 0x0) {
295             s->allow_tohost = 1;
296             s->tohost = value & 0xFFFFFFFF;
297         } else {
298             s->allow_tohost = 0;
299         }
300     } else if (addr == TOHOST_OFFSET2) {
301         if (s->allow_tohost) {
302             s->tohost |= value << 32;
303             htif_handle_tohost_write(s, s->tohost);
304         }
305     } else if (addr == FROMHOST_OFFSET1) {
306         s->fromhost_inprogress = 1;
307         s->fromhost = value & 0xFFFFFFFF;
308     } else if (addr == FROMHOST_OFFSET2) {
309         s->fromhost |= value << 32;
310         s->fromhost_inprogress = 0;
311     } else {
312         qemu_log("Invalid htif write: address %016" PRIx64 "\n",
313             (uint64_t)addr);
314     }
315 }
316 
317 static const MemoryRegionOps htif_mm_ops = {
318     .read = htif_mm_read,
319     .write = htif_mm_write,
320 };
321 
322 HTIFState *htif_mm_init(MemoryRegion *address_space, Chardev *chr,
323                         uint64_t nonelf_base, bool custom_base)
324 {
325     uint64_t base, size, tohost_offset, fromhost_offset;
326 
327     if (custom_base) {
328         fromhost_addr = nonelf_base;
329         tohost_addr = nonelf_base + 8;
330     } else {
331         if (!fromhost_addr || !tohost_addr) {
332             error_report("Invalid HTIF fromhost or tohost address");
333             exit(1);
334         }
335     }
336 
337     base = MIN(tohost_addr, fromhost_addr);
338     size = MAX(tohost_addr + 8, fromhost_addr + 8) - base;
339     tohost_offset = tohost_addr - base;
340     fromhost_offset = fromhost_addr - base;
341 
342     HTIFState *s = g_new0(HTIFState, 1);
343     s->tohost_offset = tohost_offset;
344     s->fromhost_offset = fromhost_offset;
345     s->pending_read = 0;
346     s->allow_tohost = 0;
347     s->fromhost_inprogress = 0;
348     qemu_chr_fe_init(&s->chr, chr, &error_abort);
349     qemu_chr_fe_set_handlers(&s->chr, htif_can_recv, htif_recv, htif_event,
350         htif_be_change, s, NULL, true);
351 
352     memory_region_init_io(&s->mmio, NULL, &htif_mm_ops, s,
353                           TYPE_HTIF_UART, size);
354     memory_region_add_subregion_overlap(address_space, base,
355                                         &s->mmio, 1);
356 
357     return s;
358 }
359