-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathriscv.c
More file actions
1694 lines (1482 loc) · 48.3 KB
/
Copy pathriscv.c
File metadata and controls
1694 lines (1482 loc) · 48.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* rv32emu is freely redistributable under the MIT License. See the file
* "LICENSE" for information on usage and redistribution of this file.
*/
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#if RV32_HAS(SYSTEM_MMIO)
#include <termios.h>
#include "dtc/libfdt/libfdt.h"
#endif
#if !defined(_WIN32) && !defined(_WIN64)
#include <unistd.h>
#define FILENO(x) fileno(x)
#else
#define FILENO(x) _fileno(x)
#define STDIN_FILENO FILENO(stdin)
#define STDOUT_FILENO FILENO(stdout)
#define STDERR_FILENO FILENO(stderr)
#endif
#if defined(__EMSCRIPTEN__)
#include "em_runtime.h"
#endif
#include "elf.h"
#include "mpool.h"
#include "riscv.h"
#include "riscv_private.h"
#include "utils.h"
#if RV32_HAS(JIT)
#if RV32_HAS(T2C)
#include <pthread.h>
#endif
#include "cache.h"
#include "jit.h"
#define CODE_CACHE_SIZE (4 * 1024 * 1024)
#endif
#define BLOCK_IR_MAP_CAPACITY_BITS 10
#if !RV32_HAS(JIT)
/* initialize the block map */
static void block_map_init(block_map_t *map, const uint8_t bits)
{
map->block_capacity = 1 << bits;
map->size = 0;
map->map = calloc(map->block_capacity, sizeof(struct block *));
assert(map->map);
}
/* clear all block in the block map */
void block_map_clear(riscv_t *rv)
{
block_map_t *map = &rv->block_map;
for (uint32_t i = 0; i < map->block_capacity; i++) {
block_t *block = map->map[i];
if (!block)
continue;
uint32_t idx;
rv_insn_t *ir, *next;
for (idx = 0, ir = block->ir_head; idx < block->n_insn;
idx++, ir = next) {
if (ir->fuse)
mpool_free(rv->fuse_mp, ir->fuse);
free(ir->branch_table);
next = ir->next;
mpool_free(rv->block_ir_mp, ir);
}
mpool_free(rv->block_mp, block);
map->map[i] = NULL;
}
map->size = 0;
/* clear L1 direct-mapped block cache - use invalid tags to avoid
* false hits on PC=0 edge case. Separated arrays: tags first for
* cache-efficient miss detection, ptrs zeroed with memset.
*/
for (int i = 0; i < BLOCK_L1_SIZE; i++)
rv->block_l1.tags[i] = BLOCK_L1_INVALID_TAG;
memset(rv->block_l1.ptrs, 0, sizeof(rv->block_l1.ptrs));
}
static void block_map_destroy(riscv_t *rv)
{
block_map_clear(rv);
free(rv->block_map.map);
mpool_destroy(rv->block_mp);
mpool_destroy(rv->block_ir_mp);
mpool_destroy(rv->fuse_mp);
}
#endif
bool rv_set_pc(riscv_t *rv, riscv_word_t pc)
{
assert(rv);
#if RV32_HAS(EXT_C)
if (pc & 1)
#else
if (pc & 3)
#endif
return false;
rv->PC = pc;
return true;
}
riscv_word_t rv_get_pc(riscv_t *rv)
{
assert(rv);
return rv->PC;
}
void rv_set_reg(riscv_t *rv, uint32_t reg, riscv_word_t in)
{
assert(rv);
if (reg < N_RV_REGS && reg != rv_reg_zero)
rv->X[reg] = in;
}
riscv_word_t rv_get_reg(riscv_t *rv, uint32_t reg)
{
assert(rv);
if (reg < N_RV_REGS)
return rv->X[reg];
return ~0U;
}
/* Remap standard stream
*
* @rv: riscv
* @fsp: a list of pair of mapping from fd to FILE *
* @fsp_size: list size
*
* Note: fd inside fsp should be 0 or 1 or 2 only
*/
void rv_remap_stdstream(riscv_t *rv, fd_stream_pair_t *fsp, uint32_t fsp_size)
{
assert(rv);
vm_attr_t *attr = PRIV(rv);
assert(attr && attr->fd_map);
for (uint32_t i = 0; i < fsp_size; i++) {
int fd = fsp[i].fd;
FILE *file = fsp[i].file;
if (!file)
continue;
if (fd != STDIN_FILENO && fd != STDOUT_FILENO && fd != STDERR_FILENO)
continue;
/* check if standard stream refered by fd exists or not */
map_iter_t it;
map_find(attr->fd_map, &it, &fd);
if (it.node) /* found, remove first */
map_erase(attr->fd_map, &it);
map_insert(attr->fd_map, &fd, &file);
/* store new fd to make the vm_attr_t consistent */
int new_fd = FILENO(file);
assert(new_fd != -1);
if (fd == STDIN_FILENO)
attr->fd_stdin = new_fd;
else if (fd == STDOUT_FILENO) {
attr->fd_stdout = new_fd;
rv_log_set_stdout_stream(file);
} else
attr->fd_stderr = new_fd;
}
}
#define MEMIO(op) on_mem_##op
#define IO_HANDLER_IMPL(type, op, RW) \
static IIF(RW)( \
/* W */ void MEMIO(op)(UNUSED riscv_t * rv, riscv_word_t addr, \
riscv_##type##_t data), \
/* R */ riscv_##type##_t MEMIO(op)(UNUSED riscv_t * rv, \
riscv_word_t addr)) \
{ \
IIF(RW)(memory_##op(addr, (uint8_t *) &data), \
return memory_##op(addr)); \
}
#if !RV32_HAS(SYSTEM)
#define R 0
#define W 1
IO_HANDLER_IMPL(word, ifetch, R)
IO_HANDLER_IMPL(word, read_w, R)
IO_HANDLER_IMPL(half, read_s, R)
IO_HANDLER_IMPL(byte, read_b, R)
IO_HANDLER_IMPL(word, write_w, W)
IO_HANDLER_IMPL(half, write_s, W)
IO_HANDLER_IMPL(byte, write_b, W)
#undef R
#undef W
#endif
#if RV32_HAS(T2C)
static pthread_t t2c_thread;
static void *t2c_runloop(void *arg)
{
riscv_t *rv = (riscv_t *) arg;
pthread_mutex_lock(&rv->wait_queue_lock);
while (!rv->quit) {
/* Wait for work or quit signal */
while (list_empty(&rv->wait_queue) && !rv->quit)
pthread_cond_wait(&rv->wait_queue_cond, &rv->wait_queue_lock);
if (rv->quit)
break;
/* Extract work item while holding the lock */
queue_entry_t *entry =
list_last_entry(&rv->wait_queue, queue_entry_t, list);
list_del_init(&entry->list);
pthread_mutex_unlock(&rv->wait_queue_lock);
/* Perform compilation with minimal lock contention.
*
* Lock strategy: Hold cache_lock only when accessing shared data:
* 1. Initial lookup and validation (short)
* 2. Final jit_cache update (short)
*
* The expensive LLVM compilation runs without holding cache_lock,
* allowing SFENCE.VMA/FENCE.I to proceed with minimal latency.
* If the block is invalidated during compilation, we detect this
* via the invalidated flag and discard the compiled result.
*/
pthread_mutex_lock(&rv->cache_lock);
/* Look up block from cache using the key (might have been evicted) */
uint32_t pc = (uint32_t) entry->key;
block_t *block = (block_t *) cache_get(rv->block_cache, pc, false);
#if RV32_HAS(SYSTEM)
/* Verify SATP matches (for system mode) */
uint32_t satp = (uint32_t) (entry->key >> 32);
if (block && block->satp != satp)
block = NULL;
#endif
/* Compile only if block still exists in cache */
if (block)
t2c_compile(rv, block, &rv->cache_lock);
else
pthread_mutex_unlock(&rv->cache_lock);
free(entry);
pthread_mutex_lock(&rv->wait_queue_lock);
}
pthread_mutex_unlock(&rv->wait_queue_lock);
return NULL;
}
static bool rv_spawn_t2c(riscv_t *rv)
{
rv->jit_cache = jit_cache_init();
if (!rv->jit_cache) {
rv_log_fatal("Failed to initialize JIT cache");
goto fail_jit_cache;
}
rv->inline_cache = inline_cache_init();
if (!rv->inline_cache) {
rv_log_fatal("Failed to initialize inline cache");
goto fail_inline_cache;
}
rv->quit = false;
/* prepare wait queue. */
pthread_mutex_init(&rv->wait_queue_lock, NULL);
pthread_mutex_init(&rv->cache_lock, NULL);
pthread_cond_init(&rv->wait_queue_cond, NULL);
INIT_LIST_HEAD(&rv->wait_queue);
/* Activate the background compilation thread.
* Use larger stack (8MB) to handle deep recursion in t2c_trace_ebb
* and LLVM's internal stack usage during compilation.
*/
pthread_attr_t t2c_attr;
pthread_attr_init(&t2c_attr);
pthread_attr_setstacksize(&t2c_attr, 8 * 1024 * 1024); /* 8MB stack */
pthread_create(&t2c_thread, &t2c_attr, t2c_runloop, rv);
pthread_attr_destroy(&t2c_attr);
return true;
fail_inline_cache:
jit_cache_exit(rv->jit_cache);
rv->jit_cache = NULL;
fail_jit_cache:
cache_free(rv->block_cache);
rv->block_cache = NULL;
return false;
}
void rv_destroy_t2c(riscv_t *rv)
{
/* Signal the thread to quit */
pthread_mutex_lock(&rv->wait_queue_lock);
rv->quit = true;
pthread_cond_signal(&rv->wait_queue_cond);
pthread_mutex_unlock(&rv->wait_queue_lock);
pthread_join(t2c_thread, NULL);
/* Clean up any remaining entries in wait queue */
queue_entry_t *entry, *safe;
list_for_each_entry_safe (entry, safe, &rv->wait_queue, list) {
list_del(&entry->list);
free(entry);
}
pthread_mutex_destroy(&rv->wait_queue_lock);
pthread_mutex_destroy(&rv->cache_lock);
pthread_cond_destroy(&rv->wait_queue_cond);
jit_cache_exit(rv->jit_cache);
inline_cache_exit(rv->inline_cache);
/* Dispose LLVM engines for all remaining blocks before freeing cache */
clear_cache_hot(rv->block_cache, t2c_dispose_block_engine);
}
#endif
#if RV32_HAS(SYSTEM_MMIO)
/* Map a file into memory at the specified location.
* If max_size > 0, validates that file size does not exceed max_size.
* Returns the actual file size on success, or -1 when file exceeds max_size
* (caller handles the error message). Other errors cause program exit.
*/
static off_t map_file(char **ram_loc, const char *name, off_t max_size)
{
int fd = open(name, O_RDONLY);
if (fd < 0)
goto fail;
/* get file size */
struct stat st;
if (fstat(fd, &st) < 0)
goto cleanup;
/* Validate file size if max_size constraint is specified */
if (max_size > 0 && st.st_size > max_size) {
close(fd);
return -1; /* Caller handles the error message */
}
#if HAVE_MMAP
/* Remap file to memory region. Emscripten/Windows use fallback read path
* since they don't support mmap with location hints.
*/
*ram_loc = mmap(*ram_loc, st.st_size, PROT_READ | PROT_WRITE,
MAP_FIXED | MAP_PRIVATE, fd, 0);
if (*ram_loc == MAP_FAILED)
goto cleanup;
#else
if (read(fd, *ram_loc, st.st_size) != st.st_size) {
free(*ram_loc);
goto cleanup;
}
#endif
/*
* The kernel selects a nearby page boundary and attempts to create
* the mapping.
*/
*ram_loc += st.st_size;
close(fd);
return st.st_size;
cleanup:
close(fd);
fail:
rv_log_fatal("map_file() %s failed: %s", name, strerror(errno));
exit(EXIT_FAILURE);
}
#define ALIGN_FDT(x) (((x) + (FDT_TAGSIZE) - 1) & ~((FDT_TAGSIZE) - 1))
static char *realloc_property(char *fdt,
int nodeoffset,
const char *name,
int newlen)
{
int delta = 0;
int oldlen = 0;
if (!fdt_get_property(fdt, nodeoffset, name, &oldlen))
/* strings + property header */
delta = sizeof(struct fdt_property) + strlen(name) + 1;
if (newlen > oldlen)
/* actual value in off_struct */
delta += ALIGN_FDT(newlen) - ALIGN_FDT(oldlen);
int new_sz = fdt_totalsize(fdt) + delta;
/* Assume the pre-allocated RAM is enough here, so we
* don't realloc any memory for fdt */
fdt_open_into(fdt, fdt, new_sz);
return fdt;
}
void load_dtb(char **ram_loc, vm_attr_t *attr)
{
#include "minimal_dtb.h"
char *bootargs = attr->data.system.bootargs;
char **vblk = attr->data.system.vblk_device;
bool vrng_enabled = attr->data.system.vrng_enabled;
char *blob = *ram_loc;
char *buf;
size_t len;
int node, err;
int totalsize;
#define DTB_EXPAND_SIZE 1024 /* or more if needed */
/* Allocate enough memory for DTB + extra room */
size_t minimal_len = ARRAY_SIZE(minimal);
void *dtb_buf = calloc(minimal_len + DTB_EXPAND_SIZE, sizeof(uint8_t));
assert(dtb_buf);
/* Expand it to a usable DTB blob */
err = fdt_open_into(minimal, dtb_buf, minimal_len + DTB_EXPAND_SIZE);
if (err < 0) {
rv_log_error("fdt_open_into fails\n");
exit(EXIT_FAILURE);
}
if (bootargs) {
node = fdt_path_offset(dtb_buf, "/chosen");
assert(node > 0);
len = strlen(bootargs);
buf = malloc(len + 1);
assert(buf);
memcpy(buf, bootargs, len);
buf[len] = 0;
err = fdt_setprop(dtb_buf, node, "bootargs", buf, len + 1);
if (err == -FDT_ERR_NOSPACE) {
dtb_buf = realloc_property(dtb_buf, node, "bootargs", len);
err = fdt_setprop(dtb_buf, node, "bootargs", buf, len);
}
free(buf);
assert(!err);
}
/* Remove the rtc node if it is not enabled during compile time */
#if !RV32_HAS(GOLDFISH_RTC)
const char *rtc_path = fdt_get_alias(dtb_buf, "rtc0");
assert(rtc_path);
node = fdt_path_offset(dtb_buf, rtc_path);
assert(node > 0);
err = fdt_del_node(dtb_buf, node);
if (err < 0)
rv_log_warn("Failed to remove rtc node from DTB");
#endif
if (vblk || vrng_enabled) {
int node = fdt_path_offset(dtb_buf, "/soc@F0000000");
assert(node >= 0);
uint32_t base_addr = 0x4000000;
uint32_t addr_offset = 0x100000;
uint32_t size = 0x200;
uint32_t next_addr = base_addr;
uint32_t next_irq = 1;
/* scan existing nodes to get next addr and irq */
int subnode;
fdt_for_each_subnode(subnode, dtb_buf, node)
{
const char *name = fdt_get_name(dtb_buf, subnode, NULL);
assert(name);
char *at_pos = strchr(name, '@');
assert(at_pos);
char *endptr;
uint32_t addr = strtoul(at_pos + 1, &endptr, 16);
if (endptr == at_pos + 1) {
attr->vblk_cnt = 0;
rv_log_error(
"Invalid unit-address in node: %s, skipping virtio blocks "
"MMIO",
name);
goto dtb_end;
}
if (addr == next_addr)
next_addr = addr + addr_offset;
const fdt32_t *irq_prop =
fdt_getprop(dtb_buf, subnode, "interrupts", NULL);
if (irq_prop) {
uint32_t irq = fdt32_to_cpu(*irq_prop);
if (irq == next_irq)
next_irq = irq + 1;
}
}
/* set IRQ for virtio block, see devices/virtio.h */
attr->vblk_irq_base = next_irq;
/* set the VBLK MMIO valid range */
attr->vblk_mmio_base_hi = next_addr >> 20;
attr->vblk_mmio_max_hi = attr->vblk_mmio_base_hi + attr->vblk_cnt - 1;
/* adding new virtio block nodes */
for (int i = 0; i < attr->vblk_cnt; i++) {
uint32_t new_addr = next_addr + i * addr_offset;
uint32_t new_irq = next_irq + i;
char node_name[32];
snprintf(node_name, sizeof(node_name), "virtio@%x", new_addr);
int subnode = fdt_add_subnode(dtb_buf, node, node_name);
if (subnode == -FDT_ERR_NOSPACE) {
rv_log_warn("add subnode no space!\n");
}
assert(subnode >= 0);
/* compatible = "virtio,mmio" */
assert(fdt_setprop_string(dtb_buf, subnode, "compatible",
"virtio,mmio") == 0);
/* reg = <new_addr size> */
uint32_t reg[2] = {cpu_to_fdt32(new_addr), cpu_to_fdt32(size)};
assert(fdt_setprop(dtb_buf, subnode, "reg", reg, sizeof(reg)) == 0);
/* interrupts = <new_irq> */
uint32_t irq = cpu_to_fdt32(new_irq);
assert(fdt_setprop(dtb_buf, subnode, "interrupts", &irq,
sizeof(irq)) == 0);
}
if (vrng_enabled) {
uint32_t new_addr = next_addr + attr->vblk_cnt * addr_offset;
uint32_t new_irq = next_irq + attr->vblk_cnt;
attr->vrng_mmio_base_hi = new_addr >> 20;
attr->vrng_irq = new_irq;
char node_name[32];
snprintf(node_name, sizeof(node_name), "virtio@%x", new_addr);
int subnode = fdt_add_subnode(dtb_buf, node, node_name);
if (subnode == -FDT_ERR_NOSPACE)
rv_log_warn("add virtio-rng subnode no space!\n");
assert(subnode >= 0);
assert(fdt_setprop_string(dtb_buf, subnode, "compatible",
"virtio,mmio") == 0);
uint32_t reg[2] = {cpu_to_fdt32(new_addr), cpu_to_fdt32(size)};
assert(fdt_setprop(dtb_buf, subnode, "reg", reg, sizeof(reg)) == 0);
uint32_t irq = cpu_to_fdt32(new_irq);
assert(fdt_setprop(dtb_buf, subnode, "interrupts", &irq,
sizeof(irq)) == 0);
}
}
dtb_end:
memcpy(blob, dtb_buf, minimal_len + DTB_EXPAND_SIZE);
free(dtb_buf);
totalsize = fdt_totalsize(blob);
*ram_loc += totalsize;
return;
}
/*
* The control mode flag for keyboard.
*
* ICANON: Enable canonical mode.
* ECHO: Echo input characters.
* ISIG: When any of the characters INTR, QUIT,
* SUSP, or DSUSP are received, generate the
* corresponding signal.
*
* It is essential to re-enable ISIG upon exit.
* Otherwise, the default signal handler will
* not catch the signal. E.g., SIGINT generated by
* CTRL + c.
*
*/
#define TERMIOS_C_CFLAG (ICANON | ECHO | ISIG)
static void reset_keyboard_input()
{
struct termios term;
tcgetattr(0, &term);
term.c_lflag |= TERMIOS_C_CFLAG;
tcsetattr(0, TCSANOW, &term);
}
/* Asynchronous communication to capture all keyboard input for the VM. */
static void capture_keyboard_input()
{
/* Hook exit, because we want to re-enable default control modes. */
atexit(reset_keyboard_input);
struct termios term;
tcgetattr(0, &term);
term.c_lflag &= ~TERMIOS_C_CFLAG;
tcsetattr(0, TCSANOW, &term);
}
#endif
#if RV32_HAS(SYSTEM_MMIO)
/*
*
* atexit() registers void (*)(void) callbacks, so no parameters can be passed.
* Memory must be freed at runtime. block_map_clear() requires a RISC-V instance
* and runs in interpreter mode. Instead of modifying its signature, access the
* global RISC-V instance in main.c with external linkage.
*
*/
extern riscv_t *rv;
static void rv_async_block_clear()
{
#if !RV32_HAS(JIT)
if (rv && rv->block_map.size)
block_map_clear(rv);
#else /* TODO: JIT mode */
return;
#endif /* !RV32_HAS(JIT) */
}
static void rv_fsync_device()
{
if (!rv)
return;
vm_attr_t *attr = PRIV(rv);
/*
* mmap_fallback, may need to write and sync the device
*
* vblk is optional, so it could be NULL
*/
if (attr->vblk_cnt) {
for (int i = 0; i < attr->vblk_cnt; i++) {
virtio_blk_state_t *vblk = attr->vblk[i];
if (vblk->disk_fd >= 3) {
if (vblk->device_features & VIRTIO_BLK_F_RO) /* readonly */
goto end;
if (pwrite(vblk->disk_fd, vblk->disk, vblk->disk_size, 0) ==
-1) {
rv_log_error("pwrite block device failed: %s",
strerror(errno));
return;
}
if (fsync(vblk->disk_fd) == -1) {
rv_log_error("fsync block device failed: %s",
strerror(errno));
return;
}
rv_log_info("Sync block device OK");
end:
close(vblk->disk_fd);
}
vblk_delete(vblk);
}
free(attr->vblk);
free(attr->disk);
}
if (attr->vrng) {
vrng_delete(attr->vrng);
attr->vrng = NULL;
}
}
#endif /* RV32_HAS(SYSTEM_MMIO) */
riscv_t *rv_create(riscv_user_t rv_attr)
{
assert(rv_attr);
riscv_t *rv = calloc(1, sizeof(riscv_t));
if (!rv)
return NULL;
assert(rv);
#if RV32_HAS(SYSTEM_MMIO)
/* register cleaning callback for CTRL+a+x exit */
atexit(rv_async_block_clear);
/* register device sync callback for CTRL+a+x exit */
atexit(rv_fsync_device);
#endif
/* copy over the attr */
rv->data = rv_attr;
return rv_cold_reboot(rv, 0U) ? rv : NULL;
}
#if !RV32_HAS(SYSTEM_MMIO)
/*
* TODO: enable to trace Linux kernel symbol
*/
static void rv_run_and_trace(riscv_t *rv)
{
assert(rv);
vm_attr_t *attr = PRIV(rv);
assert(attr && attr->data.user.elf_program);
attr->cycle_per_step = 1;
const char UNUSED *prog_name = attr->data.user.elf_program;
elf_t *elf = elf_new();
assert(elf && elf_open(elf, prog_name));
for (; !rv_has_halted(rv);) { /* run until the flag is done */
/* trace execution */
uint32_t pc = rv_get_pc(rv);
const char *sym = elf_find_symbol(elf, pc);
rv_log_trace("%08x %s", pc, (sym ? sym : ""));
rv_step(rv); /* step instructions */
}
elf_delete(elf);
}
#endif
#if RV32_HAS(GDBSTUB)
/* Run the RISC-V emulator as gdbstub */
void rv_debug(riscv_t *rv);
#endif
void rv_profile(riscv_t *rv, char *out_file_path);
void rv_run(riscv_t *rv)
{
assert(rv);
vm_attr_t *attr = PRIV(rv);
assert(attr &&
#if RV32_HAS(SYSTEM_MMIO)
attr->data.system.kernel && attr->data.system.initrd
#else
attr->data.user.elf_program
#endif
);
if (!(attr->run_flag & (RV_RUN_TRACE | RV_RUN_GDBSTUB))) {
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop_arg(rv_step, (void *) rv, 0, 1);
#else
/* default main loop */
for (; !rv_has_halted(rv);) /* run until the flag is done */
rv_step(rv); /* step instructions */
#endif
}
#if !RV32_HAS(SYSTEM_MMIO)
else if (attr->run_flag & RV_RUN_TRACE)
rv_run_and_trace(rv);
#endif
#if RV32_HAS(GDBSTUB)
else if (attr->run_flag & RV_RUN_GDBSTUB)
rv_debug(rv);
#endif
if (attr->run_flag & RV_RUN_PROFILE) {
assert(attr->profile_output_file);
rv_profile(rv, attr->profile_output_file);
}
}
void rv_halt(riscv_t *rv)
{
rv->halt = true;
}
/* Common hart reset logic shared by cold and warm reboot */
static void rv_reset_hart(riscv_t *rv, riscv_word_t pc)
{
assert(rv);
/* Reset general-purpose registers */
memset(rv->X, 0, sizeof(uint32_t) * N_RV_REGS);
/* Reset timer */
rv->timer = 0;
/* Reset privilege mode */
#if RV32_HAS(SYSTEM)
/*
* System simulation defaults to S-mode as
* it does not rely on M-mode software like OpenSBI.
*/
rv->priv_mode = RV_PRIV_S_MODE;
#else
/* ISA simulation defaults to M-mode */
rv->priv_mode = RV_PRIV_M_MODE;
#endif
#if RV32_HAS(SYSTEM)
/* Not being trap */
rv->is_trapped = false;
/* reset the csrs (full system emulation) */
rv->csr_cycle = 0;
rv->csr_time[0] = 0;
rv->csr_time[1] = 0;
rv->csr_mstatus = 0;
rv->csr_mtvec = 0;
rv->csr_misa = 0;
rv->csr_mtval = 0;
rv->csr_mcause = 0;
rv->csr_mscratch = 0;
rv->csr_mepc = 0;
rv->csr_mip = 0;
rv->csr_mie = 0;
rv->csr_mideleg = 0;
rv->csr_medeleg = 0;
rv->csr_mvendorid = 0;
rv->csr_marchid = 0;
rv->csr_mimpid = 0;
rv->csr_mbadaddr = 0;
rv->csr_sstatus = 0;
rv->csr_stvec = 0;
rv->csr_sip = 0;
rv->csr_sie = 0;
rv->csr_scounteren = 0;
rv->csr_sscratch = 0;
rv->csr_sepc = 0;
rv->csr_scause = 0;
rv->csr_stval = 0;
/* Reset address translation: clear SATP and flush both TLBs to prevent
* stale translations from previous execution.
*/
rv->csr_satp = 0;
memset(rv->dtlb, 0, sizeof(rv->dtlb));
memset(rv->itlb, 0, sizeof(rv->itlb));
#else
/* reset the csrs (baremetal) */
rv->csr_mtvec = 0;
rv->csr_mstatus = 0;
rv->csr_cycle = 0;
rv->csr_misa = 0;
rv->csr_mtval = 0;
rv->csr_mcause = 0;
rv->csr_mscratch = 0;
rv->csr_mepc = 0;
rv->csr_mip = 0;
rv->csr_mie = 0;
rv->csr_mideleg = 0;
rv->csr_medeleg = 0;
rv->csr_mvendorid = 0;
rv->csr_marchid = 0;
rv->csr_mimpid = 0;
rv->csr_mbadaddr = 0;
#endif
#if RV32_HAS(SYSTEM)
rv->timer_offset = 0;
#endif
rv->csr_misa |= MISA_SUPER | MISA_USER;
rv->csr_mvendorid = RV_MVENDORID;
rv->csr_marchid = RV_MARCHID;
rv->csr_mimpid = RV_MIMPID;
#if !RV32_HAS(RV32E)
rv->csr_misa |= MISA_I;
#else
rv->csr_misa |= MISA_E;
#endif
#if RV32_HAS(EXT_A)
rv->csr_misa |= MISA_A;
#endif
#if RV32_HAS(EXT_C)
rv->csr_misa |= MISA_C;
#endif
#if RV32_HAS(EXT_F)
rv->csr_misa |= MISA_F;
/* Reset float registers */
for (int i = 0; i < N_RV_REGS; i++)
rv->F[i].v = 0;
rv->csr_fcsr = 0;
#endif
#if RV32_HAS(EXT_M)
rv->csr_misa |= MISA_M;
#endif
#if RV32_HAS(EXT_V)
rv->csr_vstart = 0;
rv->csr_vxsat = 0;
rv->csr_vxrm = 0;
rv->csr_vcsr = 0;
rv->csr_vl = 0;
/* Boot with vtype.vill=1 so any vector op before the first vsetvli
* traps; this matches Linux/QEMU convention and avoids quietly running
* with the implicit (vlmul=1, sew=8) configuration that csr_vtype=0
* would imply.
*/
rv->csr_vtype = 1U << 31;
rv->csr_vlenb = VLEN / 8;
#endif
/* Not being halted */
rv->halt = false;
/* Set the reset address */
rv->PC = pc;
#if !RV32_HAS(SYSTEM) || (RV32_HAS(SYSTEM) && RV32_HAS(ELF_LOADER))
/* Setup argc/argv for ELF programs */
vm_attr_t *attr = PRIV(rv);
#if !RV32_HAS(SYSTEM_MMIO)
int argc = attr->argc;
char **args = attr->argv;
memory_t *mem = attr->mem;
#endif
/* set the reset address */
rv->PC = pc;
#ifdef __EMSCRIPTEN__
rv->wasm_block_depth = WASM_BLOCK_LIMIT;
rv->next_insn = NULL;
#ifdef WASM_DEBUG_BLOCKS
rv->max_block_depth_seen = 0;
rv->yield_soft_count = 0;
rv->yield_hard_count = 0;
rv->total_depth_at_yield = 0;
#endif
#endif
/* set the default stack pointer */
rv->X[rv_reg_sp] =
attr->mem_size - attr->stack_size - attr->args_offset_size;
/* User-mode: Store 'argc' and 'args' of the target program in 'state->mem'.
* System-mode: Skip this - kernel boot doesn't use argc/argv.
*
* memory layout of arguments as below:
* -----------------------
* | NULL |
* ----------------------- * | envp[n] |
* -----------------------
* | envp[n - 1] |
* -----------------------
* | ... |
* -----------------------
* | envp[0] |
* -----------------------
* | NULL |
* -----------------------
* | args[n] |
* -----------------------
* | args[n - 1] |
* -----------------------
* | ... |
* -----------------------
* | args[0] |
* -----------------------
* | argc |
* -----------------------
*
* TODO: access to envp
*/
#if !RV32_HAS(SYSTEM_MMIO)
/* copy args to RAM */
uintptr_t args_size = (1 + argc + 1) * sizeof(uint32_t);
uintptr_t args_bottom = attr->mem_size - attr->stack_size;
uintptr_t args_top = args_bottom - args_size;
args_top &= -16;
/* argc */
uintptr_t *args_p = (uintptr_t *) args_top;
assert(memory_write(mem, (uintptr_t) args_p, (void *) &argc, sizeof(int)));
args_p++;
/* args */
/* used for calculating the offset of args when pushing to stack */
size_t args_space[256];
size_t args_space_idx = 0;
size_t args_len;
size_t args_len_total = 0;
for (int i = 0; i < argc; i++) {
const char *arg = args[i];
args_len = strlen(arg);
assert(memory_write(mem, (uintptr_t) args_p, (void *) arg,