-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathptlxen.cpp
2698 lines (2222 loc) · 83.9 KB
/
ptlxen.cpp
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
//
// PTLsim: Cycle Accurate x86-64 Simulator
// Toplevel control and kernel interface to Xen inside the user domain
//
// Copyright 1999-2008 Matt T. Yourst <yourst@yourst.com>
//
#include <globals.h>
#include <superstl.h>
#include <ptlxen.h>
#include <mm.h>
#include <ptlsim.h>
#include <stats.h>
#define __INSIDE_PTLSIM__
#include <ptlcalls.h>
//
// Xen hypercalls
//
#define __STR(x) #x
#define STR(x) __STR(x)
#define _hypercall0(type, name) \
({ \
long __res; \
ptlsim_hypercall_histogram[__HYPERVISOR_##name]++; \
asm volatile ( \
"call hypercall_page + ("STR(__HYPERVISOR_##name)" * 32)"\
: "=a" (__res) \
: \
: "memory" ); \
(type)__res; \
})
#define _hypercall1(type, name, a1) \
({ \
long __res, __ign1; \
ptlsim_hypercall_histogram[__HYPERVISOR_##name]++; \
asm volatile ( \
"call hypercall_page + ("STR(__HYPERVISOR_##name)" * 32)"\
: "=a" (__res), "=D" (__ign1) \
: "1" ((long)(a1)) \
: "memory" ); \
(type)__res; \
})
#define _hypercall2(type, name, a1, a2) \
({ \
long __res, __ign1, __ign2; \
ptlsim_hypercall_histogram[__HYPERVISOR_##name]++; \
asm volatile ( \
"call hypercall_page + ("STR(__HYPERVISOR_##name)" * 32)"\
: "=a" (__res), "=D" (__ign1), "=S" (__ign2) \
: "1" ((long)(a1)), "2" ((long)(a2)) \
: "memory" ); \
(type)__res; \
})
#define _hypercall3(type, name, a1, a2, a3) \
({ \
long __res, __ign1, __ign2, __ign3; \
ptlsim_hypercall_histogram[__HYPERVISOR_##name]++; \
asm volatile ( \
"call hypercall_page + ("STR(__HYPERVISOR_##name)" * 32)"\
: "=a" (__res), "=D" (__ign1), "=S" (__ign2), \
"=d" (__ign3) \
: "1" ((long)(a1)), "2" ((long)(a2)), \
"3" ((long)(a3)) \
: "memory" ); \
(type)__res; \
})
#define _hypercall4(type, name, a1, a2, a3, a4) \
({ \
long __res, __ign1, __ign2, __ign3; \
ptlsim_hypercall_histogram[__HYPERVISOR_##name]++; \
asm volatile ( \
"movq %7,%%r10; " \
"call hypercall_page + ("STR(__HYPERVISOR_##name)" * 32)"\
: "=a" (__res), "=D" (__ign1), "=S" (__ign2), \
"=d" (__ign3) \
: "1" ((long)(a1)), "2" ((long)(a2)), \
"3" ((long)(a3)), "g" ((long)(a4)) \
: "memory", "r10" ); \
(type)__res; \
})
#define _hypercall5(type, name, a1, a2, a3, a4, a5) \
({ \
long __res, __ign1, __ign2, __ign3; \
ptlsim_hypercall_histogram[__HYPERVISOR_##name]++; \
asm volatile ( \
"movq %7,%%r10; movq %8,%%r8; " \
"call hypercall_page + ("STR(__HYPERVISOR_##name)" * 32)"\
: "=a" (__res), "=D" (__ign1), "=S" (__ign2), \
"=d" (__ign3) \
: "1" ((long)(a1)), "2" ((long)(a2)), \
"3" ((long)(a3)), "g" ((long)(a4)), \
"g" ((long)(a5)) \
: "memory", "r10", "r8" ); \
(type)__res; \
})
W64 ptlsim_hypercall_histogram[64];
W64 guest_hypercall_histogram[64];
static inline W64 do_xen_hypercall(W64 hypercall, W64 arg1, W64 arg2, W64 arg3, W64 arg4, W64 arg5, W64 arg6) {
W64 rc;
W64 addr = (PTLSIM_HYPERCALL_PAGE_VIRT_BASE + (hypercall * 32));
asm volatile ("movq %[arg4],%%r10\n"
"movq %[arg5],%%r8\n"
"movq %[arg6],%%r9\n"
"call %%rax\n"
: "=a" (rc)
: "a" (addr), "D" ((W64)(arg1)), "S" ((W64)(arg2)),
"d" ((W64)(arg3)), [arg4] "g" ((W64)(arg4)), [arg5] "g" ((W64)(arg5)),
[arg6] "g" ((W64)(arg6))
: "r11", "rcx", "memory", "r8", "r10", "r9");
return rc;
}
int HYPERVISOR_set_trap_table(trap_info_t *table) {
return _hypercall1(int, set_trap_table, table);
}
int HYPERVISOR_mmu_update(mmu_update_t *req, int count, int *success_count, domid_t domid) {
return _hypercall4(int, mmu_update, req, count, success_count, domid);
}
int HYPERVISOR_set_gdt(unsigned long *frame_list, int entries) {
return _hypercall2(int, set_gdt, frame_list, entries);
}
int HYPERVISOR_stack_switch(unsigned long ss, unsigned long esp) {
return _hypercall2(int, stack_switch, ss, esp);
}
int HYPERVISOR_set_callbacks(unsigned long event_address, unsigned long failsafe_address, unsigned long syscall_address) {
return _hypercall3(int, set_callbacks, event_address, failsafe_address, syscall_address);
}
int HYPERVISOR_fpu_taskswitch(int set) {
return _hypercall1(int, fpu_taskswitch, set);
}
int HYPERVISOR_sched_op_compat(int cmd, unsigned long arg) {
return _hypercall2(int, sched_op_compat, cmd, arg);
}
int HYPERVISOR_domctl_op(xen_domctl_t *domctl_op) {
domctl_op->interface_version = XEN_DOMCTL_INTERFACE_VERSION;
return _hypercall1(int, domctl, domctl_op);
}
int HYPERVISOR_set_debugreg(int reg, unsigned long value) {
return _hypercall2(int, set_debugreg, reg, value);
}
unsigned long HYPERVISOR_get_debugreg(int reg) {
return _hypercall1(unsigned long, get_debugreg, reg);
}
int HYPERVISOR_update_descriptor(unsigned long ma, unsigned long word) {
return _hypercall2(int, update_descriptor, ma, word);
}
int HYPERVISOR_memory_op(unsigned int cmd, void *arg) {
return _hypercall2(int, memory_op, cmd, arg);
}
int HYPERVISOR_multicall(void *call_list, int nr_calls) {
return _hypercall2(int, multicall, call_list, nr_calls);
}
int HYPERVISOR_update_va_mapping(unsigned long va, pte_t new_val, unsigned long flags) {
return _hypercall3(int, update_va_mapping, va, new_val, flags);
}
long HYPERVISOR_set_timer_op(u64 abs_nsecs) {
return _hypercall1(long, set_timer_op, abs_nsecs);
}
// HYPERVISOR_event_channel_op_compat
int HYPERVISOR_xen_version(int cmd, void *arg) {
return _hypercall2(int, xen_version, cmd, arg);
}
int HYPERVISOR_console_io(int cmd, int count, char *str) {
return _hypercall3(int, console_io, cmd, count, str);
}
// HYPERVISOR_physdev_op_compat()
int HYPERVISOR_grant_table_op(unsigned int cmd, void *uop, unsigned int count) {
return _hypercall3(int, grant_table_op, cmd, uop, count);
}
int HYPERVISOR_vm_assist(unsigned int cmd, unsigned int type) {
return _hypercall2(int, vm_assist, cmd, type);
}
int HYPERVISOR_update_va_mapping_otherdomain(unsigned long va, pte_t new_val, unsigned long flags, domid_t domid) {
return _hypercall4(int, update_va_mapping_otherdomain, va, new_val, flags, domid);
}
// iret
int HYPERVISOR_vcpu_op(int cmd, int vcpuid, void *extra_args) {
return _hypercall3(int, vcpu_op, cmd, vcpuid, extra_args);
}
int HYPERVISOR_set_segment_base(int reg, unsigned long value) {
return _hypercall2(int, set_segment_base, reg, value);
}
int HYPERVISOR_mmuext_op(struct mmuext_op *op, int count, int *success_count, domid_t domid) {
return _hypercall4(int, mmuext_op, op, count, success_count, domid);
}
// acm_op
int HYPERVISOR_nmi_op(unsigned long op, void *arg) {
return _hypercall2(int, nmi_op, op, arg);
}
int HYPERVISOR_sched_op(int cmd, void *arg) {
return _hypercall2(int, sched_op, cmd, arg);
}
int HYPERVISOR_callback_op(int cmd, void *arg) {
return _hypercall2(int, callback_op, cmd, arg);
}
int HYPERVISOR_xenoprof_op(int op, void *arg) {
return _hypercall2(int, xenoprof_op, op, arg);
}
int HYPERVISOR_event_channel_op(int cmd, void *arg) {
return _hypercall2(int, event_channel_op, cmd, arg);
}
int HYPERVISOR_physdev_op(int cmd, void *arg) {
return _hypercall2(int, physdev_op, cmd, arg);
}
int xen_sched_block() {
return HYPERVISOR_sched_op(SCHEDOP_block, NULL);
}
int xen_sched_yield() {
return HYPERVISOR_sched_op(SCHEDOP_yield, NULL);
}
int xen_sched_timer(u64 nsecs) {
nsecs += shinfo.vcpu_info[0].time.system_time;
HYPERVISOR_set_timer_op(nsecs);
return 0;
}
int xen_sched_poll(int port, u64 nsecs) {
evtchn_port_t ports[1];
ports[0] = port;
sched_poll_t op;
op.ports.p = ports;
op.nr_ports = 1;
op.timeout = shinfo.vcpu_info[0].time.system_time + nsecs;
return HYPERVISOR_sched_op(SCHEDOP_poll, &op);
}
int xen_shutdown_domain(int reason) {
sched_shutdown_t shutdown;
shutdown.reason = reason;
return HYPERVISOR_sched_op(SCHEDOP_shutdown, &reason);
}
int current_vcpuid() {
W64 rsp = (W64)get_rsp();
W64 pervcpu = (W64)bootinfo.per_vcpu_stack_base;
int vcpuid = 0;
bool is_secondary_stack = inrange(rsp, pervcpu, (pervcpu + (PAGE_SIZE * MAX_CONTEXTS) - 1));
if (is_secondary_stack) vcpuid = ((rsp - pervcpu) >> 12);
return vcpuid;
}
W64 early_boot_log_seqid = 0;
void early_boot_log(const void* data, int length) {
const char* p = (const char*)data;
char* log_buffer_base = (char*)(PTLSIM_VIRT_BASE + (PTLSIM_LOGBUF_PAGE_PFN * PAGE_SIZE));
bootinfo.logbuf_spinlock.acquire();
early_boot_log_seqid++;
stringbuf sb; sb.reset(); sb << early_boot_log_seqid, ": ";
int n = strlen((char*)sb);
foreach (i, n) {
log_buffer_base[bootinfo.logbuf_tail] = ((char*)(sb))[i];
bootinfo.logbuf_tail = (bootinfo.logbuf_tail + 1) % PTLSIM_LOGBUF_SIZE;
}
foreach (i, length) {
log_buffer_base[bootinfo.logbuf_tail] = p[i];
bootinfo.logbuf_tail = (bootinfo.logbuf_tail + 1) % PTLSIM_LOGBUF_SIZE;
}
bootinfo.logbuf_spinlock.release();
}
//
// Host calls to PTLmon
//
W64 hostreq_calls = 0;
W64 hostreq_spins = 0;
W64s synchronous_host_call(const PTLsimHostCall& call, bool spin, bool ignorerc) {
int vcpuid = current_vcpuid();
if (vcpuid != 0) asm volatile("int3");
stringbuf sb;
int rc;
hostreq_calls++;
memcpy(&bootinfo.hostreq, &call, sizeof(PTLsimHostCall));
bootinfo.hostreq.ready = 0;
unmask_evtchn(bootinfo.hostcall_port);
if likely (real_timer_port[vcpuid] >= 0) unmask_evtchn(real_timer_port[vcpuid]);
sti();
evtchn_send_t sendop;
sendop.port = bootinfo.hostcall_port;
rc = HYPERVISOR_event_channel_op(EVTCHNOP_send, &sendop);
if (ignorerc) return 0;
//
// We need to block here since we need an event to clear the hostcall
// pending bit. However, for switching to native mode, we should NOT
// block, since if we race with pause() in PTLmon and lose, the domain
// will be in the Xen "blocked" state when setvcpucontext is called
// by PTLmon, but setvcpucontext does not save/restore the blocked
// state. Hence the target VCPU will remain blocked forever. To avoid
// this, we specify spin = true for these calls.
//
barrier();
while (!bootinfo.hostreq.ready) {
barrier();
if unlikely (!spin) {
hostreq_spins++;
xen_sched_block();
}
barrier();
}
assert(bootinfo.hostreq.ready);
return bootinfo.hostreq.rc;
}
void enable_breakout_insn() {
vcpu_breakout_insn_action_t breakout;
breakout.flags = BREAKOUT_NOTIFY_PORT | BREAKOUT_PAUSE_DOMAIN;
breakout.insn[0] = 0x0f;
breakout.insn[1] = 0x37;
breakout.insn_length = 2;
breakout.notify_port = bootinfo.breakout_port;
foreach (i, contextcount) {
int rc = HYPERVISOR_vcpu_op(VCPUOP_set_breakout_insn_action, i, &breakout);
logfile << " Enabled breakout insn on vcpu ", i, " -> port ", breakout.notify_port, " (rc ", rc, ")", endl, flush;
}
}
void disable_breakout_insn() {
vcpu_breakout_insn_action_t breakout;
setzero(breakout);
foreach (i, contextcount) {
int rc = HYPERVISOR_vcpu_op(VCPUOP_set_breakout_insn_action, i, &breakout);
logfile << " Disabled breakout insn on vcpu ", i, " -> port ", breakout.notify_port, " (rc ", rc, ")", endl, flush;
}
};
//
// Switch PTLsim to native mode by swapping in context <ctx>,
// and saving the current PTLsim context back to <ctx>.
//
// When this call returns (i.e. we switch back to simulation mode),
// <ctx> is filled with the new user context we interrupted, and
// the PTLsim register state is restored, allowing us to return
// exactly where we left off.
//
int switch_to_native(bool pause = false) {
flush_stats();
logfile.flush();
cerr.flush();
//
// Switch back to the PTLsim root page table before going native,
// so the monitor saves that as the cr3 value to restore when
// we context switch back into PTLsim later on.
//
// If we do not do this, the guest kernel may try to reuse
// the current cr3 mfn as a data page, and hence it will be
// invalid if we try to use it as our root later on.
//
// switch_page_table(bootinfo.toplevel_page_table_mfn);
enable_breakout_insn();
// Linux kernels expect this to be re-enabled:
HYPERVISOR_vm_assist(VMASST_CMD_enable, VMASST_TYPE_writable_pagetables);
virtualize_time_for_native_mode();
PTLsimHostCall call;
call.op = PTLSIM_HOST_SWITCH_TO_NATIVE;
call.ready = 0;
call.switch_to_native.pause = pause;
flush_cache();
flush_tlb();
perfctrs_start();
int rc = synchronous_host_call(call, true);
perfctrs_stop();
HYPERVISOR_vm_assist(VMASST_CMD_disable, VMASST_TYPE_writable_pagetables);
return rc;
}
//
// Shutdown PTLsim and the domain
//
int shutdown(int reason) {
if (reason != SHUTDOWN_crash) shutdown_subsystems();
flush_stats();
logfile.close();
cerr.close();
PTLsimHostCall call;
call.op = PTLSIM_HOST_SHUTDOWN;
call.ready = 0;
call.shutdown.reason = reason;
// Linux kernels expect this to be re-enabled:
HYPERVISOR_vm_assist(VMASST_CMD_enable, VMASST_TYPE_writable_pagetables);
int rc = synchronous_host_call(call, false, true);
xen_shutdown_domain(reason);
// (never returns)
return rc;
}
//
// Get one request, blocking until one is ready
//
W64 accept_upcall(char* buf, size_t count, bool blocking = 1) {
PTLsimHostCall call;
call.op = PTLSIM_HOST_ACCEPT_UPCALL;
call.ready = 0;
call.accept_upcall.buf = xferpage;
call.accept_upcall.length = min(count, size_t(PTLSIM_XFER_PAGES_SIZE));
call.accept_upcall.blocking = blocking;
int rc = synchronous_host_call(call);
if (rc) {
count = min(count, size_t(PTLSIM_XFER_PAGES_SIZE-1));
memcpy(buf, xferpage, count);
buf[count] = 0;
cerr << "Processing ", buf, endl, flush;
}
return rc;
}
W64 accept_upcall_nonblocking(char* buf, size_t count) {
return accept_upcall(buf, count, 0);
}
//
// Complete a request and notify any blocked waiters
//
int complete_upcall(W64 uuid) {
// cerr << "Complete upcall for uuid ", uuid, endl, flush;
PTLsimHostCall call;
call.op = PTLSIM_HOST_COMPLETE_UPCALL;
call.ready = 0;
call.complete_upcall.uuid = uuid;
return synchronous_host_call(call);
}
//
// Inject an upcall into the monitor for later readout
//
W64 inject_upcall(const char* buf, size_t count, bool flushing) {
if (flushing) {
PTLsimHostCall call;
logfile << "inject_upcall: flushing upcall queue...", endl, flush;
call.op = PTLSIM_HOST_FLUSH_UPCALL_QUEUE;
call.flush_upcall_queue.uuid_limit = 0;
int n = synchronous_host_call(call);
logfile << "inject_upcall: Flushed ", n, " pending commands", endl, flush;
//
// check_for_async_sim_break() will check bootinfo.abort_request
// on the next pass through, and stop the run if we just flushed
// the queue.
//
bootinfo.abort_request = 1;
}
PTLsimHostCall call;
logfile << "inject_upcall: '", buf, "'", endl, flush;
count = min(count, size_t(PTLSIM_XFER_PAGES_SIZE));
memcpy(xferpage, buf, count);
call.op = PTLSIM_HOST_INJECT_UPCALL;
call.ready = 0;
call.inject_upcall.buf = xferpage;
call.inject_upcall.length = min(count, size_t(PTLSIM_XFER_PAGES_SIZE));
call.inject_upcall.flush = 0;
return synchronous_host_call(call);
}
//
// Linux-like system calls passed back to PTLmon via hostcall mechanism
//
#undef declare_syscall0
#undef declare_syscall1
#undef declare_syscall2
#undef declare_syscall3
#undef declare_syscall4
#undef declare_syscall5
#undef declare_syscall6
#define declare_syscall0(sysid,type,name) type name(void) { \
return (type)synchronous_host_call(PTLsimHostCall(sysid)); }
#define declare_syscall1(sysid,type,name,type1,arg1) type name(type1 arg1) { \
return (type)synchronous_host_call(PTLsimHostCall(sysid, (W64)arg1)); }
#define declare_syscall2(sysid,type,name,type1,arg1,type2,arg2) asmlinkage type name(type1 arg1,type2 arg2) { \
return (type)synchronous_host_call(PTLsimHostCall(sysid, (W64)arg1, (W64)arg2)); }
#define declare_syscall3(sysid,type,name,type1,arg1,type2,arg2,type3,arg3) type name(type1 arg1,type2 arg2,type3 arg3) { \
return (type)synchronous_host_call(PTLsimHostCall(sysid, (W64)arg1, (W64)arg2, (W64)arg3)); }
#define declare_syscall4(sysid,type,name,type1,arg1,type2,arg2,type3,arg3,type4,arg4) asmlinkage type name (type1 arg1, type2 arg2, type3 arg3, type4 arg4) { \
return (type)synchronous_host_call(PTLsimHostCall(sysid, (W64)arg1, (W64)arg2, (W64)arg3, (W64)arg4)); }
#define declare_syscall5(sysid,type,name,type1,arg1,type2,arg2,type3,arg3,type4,arg4,type5,arg5) \
type name (type1 arg1,type2 arg2,type3 arg3,type4 arg4,type5 arg5) { \
return (type)synchronous_host_call(PTLsimHostCall(sysid, (W64)arg1, (W64)arg2, (W64)arg3, (W64)arg4, (W64)arg5)); }
#define declare_syscall6(sysid,type,name,type1,arg1,type2,arg2,type3,arg3,type4,arg4,type5,arg5,type6,arg6) \
type name (type1 arg1,type2 arg2,type3 arg3,type4 arg4,type5 arg5,type6 arg6) { \
return (type)synchronous_host_call(PTLsimHostCall(sysid, (W64)arg1, (W64)arg2, (W64)arg3, (W64)arg4, (W64)arg5, (W64)arg6)); }
declare_syscall3(__NR_lseek, W64, sys_seek, int, fd, W64, offset, unsigned int, origin);
declare_syscall3(__NR_open, int, sys_open_thunk, const char*, pathname, int, flags, int, mode);
asmlinkage int sys_open(const char* pathname, int flags, int mode) {
strncpy(xferpage, pathname, PTLSIM_XFER_PAGES_SIZE);
return sys_open_thunk(xferpage, flags, mode);
}
declare_syscall1(__NR_close, int, sys_close, int, fd);
declare_syscall3(__NR_read, ssize_t, sys_read_thunk, int, fd, void*, buf, size_t, count);
asmlinkage ssize_t sys_read(int fd, void* buf, size_t count) {
char* p = (char*)buf;
size_t realcount = 0;
int rc;
while (count) {
rc = sys_read_thunk(fd, xferpage, min(count, size_t(PTLSIM_XFER_PAGES_SIZE)));
if (rc < 0) return rc;
memcpy(p, xferpage, rc);
count -= rc;
realcount += rc;
p += rc;
if (rc < PAGE_SIZE) break;
}
return realcount;
}
declare_syscall3(__NR_write, ssize_t, sys_write_thunk, int, fd, const void*, buf, size_t, count);
asmlinkage ssize_t sys_write(int fd, const void* buf, size_t count) {
char* p = (char*)buf;
size_t realcount = 0;
int rc;
while (count) {
size_t n = min(count, size_t(PTLSIM_XFER_PAGES_SIZE));
memcpy(xferpage, p, n);
rc = sys_write_thunk(fd, xferpage, n);
if (rc < 0) return rc;
count -= rc;
realcount += rc;
p += rc;
if (rc < PAGE_SIZE) break;
}
return realcount;
}
declare_syscall1(__NR_unlink, int, sys_unlink_thunk, const char*, pathname);
asmlinkage int sys_unlink(const char* pathname) {
strncpy(xferpage, pathname, PTLSIM_XFER_PAGES_SIZE);
return sys_unlink_thunk(xferpage);
}
declare_syscall2(__NR_rename, int, sys_rename_thunk, const char*, oldpath, const char*, newpath);
asmlinkage int sys_rename(const char* oldpath, const char* newpath) {
strncpy(xferpage + 0, oldpath, 2048);
strncpy(xferpage + 2048, newpath, 2048);
return sys_rename_thunk(xferpage + 0, xferpage + 2048);
}
declare_syscall0(__NR_getpid, pid_t, sys_getpid);
declare_syscall0(__NR_gettid, pid_t, sys_gettid);
declare_syscall1(__NR_uname, int, sys_uname_thunk, struct utsname*, buf);
asmlinkage int sys_uname(struct utsname* buf) {
utsname* unamebuf = (utsname*)xferpage;
int rc = sys_uname_thunk(unamebuf);
if ((!rc) && buf) memcpy(buf, unamebuf, sizeof(utsname));
return rc;
}
declare_syscall3(__NR_readlink, int, sys_readlink_thunk, const char*, path, char*, buf, size_t, bufsiz);
asmlinkage int sys_readlink(const char *path, char *buf, size_t bufsiz) {
strncpy(xferpage + 0, path, 2048);
int rc = sys_readlink_thunk(xferpage + 0, xferpage + 2048, min(bufsiz, (size_t)2048));
if (rc >= 0) memcpy(buf, xferpage + 2048, rc);
return rc;
}
declare_syscall2(__NR_nanosleep, int, do_nanosleep, const timespec*, req, timespec*, rem);
asmlinkage int sys_gettimeofday(struct timeval* tv, struct timezone* tz) {
tv->tv_sec = shinfo.wc_sec;
tv->tv_usec = shinfo.wc_nsec / 1000;
return 0;
}
asmlinkage time_t sys_time(time_t* t) {
W64 sec = shinfo.wc_sec;
if (t) *t = sec;
return sec;
}
W64 sys_nanosleep(W64 nsec) {
timespec* reqrem = (timespec*)xferpage;
reqrem->tv_sec = (W64)nsec / 1000000000ULL;
reqrem->tv_nsec = (W64)nsec % 1000000000ULL;
do_nanosleep(reqrem, reqrem+1);
return ((W64)reqrem[1].tv_sec * 1000000000ULL) + (W64)reqrem[1].tv_nsec;
}
void* sys_mmap(void* start, size_t length, int prot, int flags, int fd, W64 offset) {
// Not supported on the bare hardware
return (void*)(Waddr)0xffffffffffffffffULL;
}
//
// Trap and Exception Handling
//
asmlinkage {
void divide_error();
void debug();
void int3();
void overflow();
void bounds();
void invalid_op();
void device_not_available();
void coprocessor_segment_overrun();
void invalid_tss();
void segment_not_present();
void stack_segment();
void general_protection();
void page_fault();
void coprocessor_error();
void simd_coprocessor_error();
void alignment_check();
void spurious_interrupt_bug();
void machine_check();
};
void print_regs(ostream& os, const W64* regs) {
foreach (i, ARCHREG_COUNT) {
os << " ", padstring(arch_reg_names[i], -6), " 0x", hexstring(regs[i], 64);
if ((i % 4) == (4-1)) os << endl;
}
}
void print_stack(ostream& os, Waddr sp) {
W64* p = (W64*)sp;
os << "Stack trace back from ", (void*)sp, ":", endl, flush;
foreach (i, 256) {
if ((i % 8) == 0) os << " ", &p[i], ":";
os << " ", hexstring(p[i], 64);
if ((i % 8) == 7) os << endl;
}
os << flush;
}
asmlinkage void ptl_internal_trap(int trapid, const char* name, W64* regs) {
cerr << endl;
cerr << "PTLsim Internal Error: unhandled trap ", trapid, " (", name, "): error code ", hexstring(regs[REG_ar1], 32), endl;
cerr << "Registers:", endl;
print_regs(cerr, regs);
cerr << flush;
print_stack(cerr, regs[REG_rsp]);
if (logfile) {
logfile << "PTLsim Internal Error: unhandled trap ", trapid, " (", name, "): error code ", hexstring(regs[REG_ar1], 32), endl;
logfile << "Registers:", endl;
print_regs(logfile, regs);
print_stack(logfile, regs[REG_rsp]);
logfile << flush;
}
logfile.close();
cerr.flush();
cout.flush();
shutdown(SHUTDOWN_crash);
}
#define DO_ERROR(trapid, str, name) asmlinkage void do_##name(W64* regs) { ptl_internal_trap(trapid, str, regs); }
//
// These exceptions are not handled by PTLsim. If they occur
// during simulation mode, something is seriously wrong.
//
DO_ERROR(0, "divide error", divide_error);
DO_ERROR(3, "int3", int3);
DO_ERROR(4, "overflow", overflow);
DO_ERROR(5, "bounds", bounds);
DO_ERROR(6, "invalid opcode", invalid_op);
DO_ERROR(7, "device not available", device_not_available);
DO_ERROR(11, "segment not present", segment_not_present);
DO_ERROR(12, "stack segment", stack_segment);
DO_ERROR(13, "general protection", general_protection);
asmlinkage void do_page_fault(W64* regs);
DO_ERROR(16, "fpu", coprocessor_error);
DO_ERROR(19, "sse", simd_coprocessor_error);
asmlinkage void xen_event_callback_entry();
asmlinkage void divide_error_entry();
asmlinkage void int3_entry();
asmlinkage void overflow_entry();
asmlinkage void bounds_entry();
asmlinkage void invalid_op_entry();
asmlinkage void device_not_available_entry();
asmlinkage void segment_not_present_entry();
asmlinkage void stack_segment_entry();
asmlinkage void general_protection_entry();
asmlinkage void page_fault_entry();
asmlinkage void coprocessor_error_entry();
asmlinkage void simd_coprocessor_error_entry();
static trap_info_t trap_table[] = {
{ 0, 0, FLAT_KERNEL_CS, (Waddr)÷_error_entry },
{ 3, 0, FLAT_KERNEL_CS, (Waddr)&int3_entry },
{ 4, 0, FLAT_KERNEL_CS, (Waddr)&overflow_entry },
{ 5, 0, FLAT_KERNEL_CS, (Waddr)&bounds_entry },
{ 6, 0, FLAT_KERNEL_CS, (Waddr)&invalid_op_entry },
{ 7, 0, FLAT_KERNEL_CS, (Waddr)&device_not_available_entry },
{ 11, 0, FLAT_KERNEL_CS, (Waddr)&segment_not_present_entry },
{ 12, 0, FLAT_KERNEL_CS, (Waddr)&stack_segment_entry },
{ 13, 0, FLAT_KERNEL_CS, (Waddr)&general_protection_entry },
{ 14, 0, FLAT_KERNEL_CS, (Waddr)&page_fault_entry },
{ 16, 0, FLAT_KERNEL_CS, (Waddr)&coprocessor_error_entry },
{ 19, 0, FLAT_KERNEL_CS, (Waddr)&simd_coprocessor_error_entry},
{ 0, 0, 0, 0 }
};
bool lowlevel_init_done = 0;
asmlinkage void assert_fail(const char *__assertion, const char *__file, unsigned int __line, const char *__function) {
// use two stringbufs to avoid allocating any memory:
stringbuf sb1, sb2;
sb1 << endl, "Assert ", __assertion, " failed in ", __file, ":", __line, " (", __function, ") from ", getcaller();
sb2 << " at ", sim_cycle, " cycles, ", total_user_insns_committed, " commits, ", iterations, " iterations", endl;
if (!lowlevel_init_done) {
sys_write(2, sb1, strlen(sb1));
sys_write(2, sb2, strlen(sb2));
asm("mov %[ra],%%rax; ud2a;" : : [ra] "r" (getcaller()));
}
cerr << sb1, sb2, flush;
if (logfile) {
logfile << sb1, sb2, flush;
PTLsimMachine* machine = PTLsimMachine::getcurrent();
if (machine) machine->dump_state(logfile);
logfile.close();
}
// Make sure the ring buffer is flushed too:
ptl_mm_flush_logging();
cerr.flush();
cout.flush();
// Force crash here:
asm("ud2a");
for (;;) { }
}
//
// Tracking of cycles and instructions in each mode
//
W64 cycles_at_last_mode_switch = 0;
W64 insns_at_last_mode_switch = 0;
void reset_mode_switch_delta_cycles_and_insns(W64& delta_cycles, W64& delta_insns) {
delta_cycles = (sim_cycle - cycles_at_last_mode_switch);
delta_insns = (total_user_insns_committed - insns_at_last_mode_switch);
cycles_at_last_mode_switch = sim_cycle;
insns_at_last_mode_switch = total_user_insns_committed;
}
void update_pre_run_stats() {
cycles_at_last_mode_switch = sim_cycle;
insns_at_last_mode_switch = total_user_insns_committed;
}
//
// x86 Specific Functions
//
// idx must be between 0 and 8191 (i.e. 65535 >> 3)
bool Context::gdt_entry_valid(W16 idx) {
if ((idx >= FIRST_RESERVED_GDT_ENTRY) && (idx < (FIRST_RESERVED_GDT_ENTRY + (PAGE_SIZE / sizeof(SegmentDescriptor)))))
return true;
return (idx < gdtsize);
}
void* gdt_page;
mfn_t gdt_mfn;
SegmentDescriptor Context::get_gdt_entry(W16 idx) {
if (!idx)
return SegmentDescriptor(0);
if ((idx >> 9) == FIRST_RESERVED_GDT_PAGE)
return *(const SegmentDescriptor*)((byte*)gdt_page + (lowbits(idx, 9) * 8));
if (idx >= gdtsize)
return SegmentDescriptor(0);
mfn_t mfn = gdtpages[idx >> 9];
return *(const SegmentDescriptor*)phys_to_mapped_virt((mfn << 12) + (lowbits(idx, 9) * 8));
}
void Context::flush_tlb(bool propagate_flush_to_model) {
if (logable(5)) logfile << "[vcpu ", vcpuid, "] flush_tlb() called from ", getcaller(), endl;
foreach (i, lengthof(cached_pte_virt)) {
cached_pte_virt[i] = 0xffffffffffffffffULL;
cached_pte[i] = 0;
}
if unlikely (!propagate_flush_to_model) return;
PTLsimMachine* machine = PTLsimMachine::getcurrent();
if likely (machine) machine->flush_tlb(*this);
}
void Context::flush_tlb_virt(Waddr virtaddr, bool propagate_flush_to_model) {
if (logable(5)) logfile << "[vcpu ", vcpuid, "] flush_tlb(", (void*)virtaddr, ") called from ", getcaller(), endl;
int slot = lowbits(virtaddr >> 12, log2(PTE_CACHE_SIZE));
if (cached_pte_virt[slot] == floor(virtaddr, PAGE_SIZE)) {
cached_pte_virt[slot] = 0xffffffffffffffffULL;
cached_pte[slot] = 0;
}
if unlikely (!propagate_flush_to_model) return;
PTLsimMachine* machine = PTLsimMachine::getcurrent();
if likely (machine) machine->flush_tlb_virt(*this, virtaddr);
}
int Context::write_segreg(unsigned int segid, W16 selector) {
assert(segid < SEGID_COUNT);
int idx = selector >> 3; // mask out the dpl bits and turn into index
if (idx == 0) {
//
// It's perfectly legal to load a null selector, especially in x86-64 mode,
// where most segments (except cs, fs, gs) are ignored.
//
// The processor is supposed to deliver a fault (seg_not_present or stack_fault)
// the first time the null selector is actually used.
//
if (logable(4)) {
logfile << "write_segreg(", segid, ", 0x", hexstring(selector, 16), " (idx ", idx, ")): load null segment", endl;
}
seg[segid].selector = 0;
reload_segment_descriptor(segid, selector);
return 0;
}
if (!gdt_entry_valid(idx)) {
if (logable(4)) {
logfile << "write_segreg(", segid, ", 0x", hexstring(selector, 16), " (idx ", idx, ")): gdt entry ", idx, " is invalid (gdt size? ", gdtsize, ")", endl;
}
return EXCEPTION_x86_gp_fault;
}
SegmentDescriptor desc = get_gdt_entry(idx);
int cs_dpl = (kernel_mode) ? 0 : 3;
if (desc.dpl < cs_dpl) {
if (logable(4)) {
logfile << "write_segreg(", segid, ", 0x", hexstring(selector, 16), " (idx ", idx, ")): gdt entry ", idx, " had incompatible DPL (desc dpl ", desc.dpl, " vs current dpl ", cs_dpl, ")", endl;
logfile << " gdt entry was: ", desc, endl;
}
return EXCEPTION_x86_gp_fault;
}
if (!desc.p) {
if (logable(4)) {
logfile << "write_segreg(", segid, ", 0x", hexstring(selector, 16), " (idx ", idx, ")): gdt entry ", idx, " is not present", endl;
logfile << " gdt entry was: ", desc, endl;
}
// return (segid == SEGID_SS) ? EXCEPTION_x86_stack_fault : EXCEPTION_x86_seg_not_present;
// Technically this is supposed to be a seg not present fault, but K8 in x86-64 mode seems to signal a GP fault instead:
return EXCEPTION_x86_gp_fault;
}
reload_segment_descriptor(segid, selector);
if (logable(4)) {
logfile << "write_segreg(", segid, ", 0x", hexstring(selector, 16), " (idx ", idx, ")): gdt entry ", idx, " validated", endl;
logfile << " gdt entry was: ", desc, endl;
}
return 0;
}
void Context::swapgs() {
// This is equivalent to swapgs instruction:
if (logable(4)) logfile << " swapgs: update gsbase old ", (void*)(Waddr)seg[SEGID_GS].base, " => new ", (void*)(Waddr)swapgs_base, endl;
W64 temp = seg[SEGID_GS].base;
seg[SEGID_GS].base = swapgs_base;
swapgs_base = temp;
}
void Context::reload_segment_descriptor(unsigned int segid, W16 selector) {
SegmentDescriptorCache& s = seg[segid];
s.selector = selector;
switch (segid) {
case SEGID_CS:
s = get_gdt_entry(seg[SEGID_CS].selector >> 3);
use32 = s.use32;
use64 = s.use64;
virt_addr_mask = (use64 ? 0xffffffffffffffffULL : 0x00000000ffffffffULL);
break;
case SEGID_SS:
case SEGID_DS:
case SEGID_ES:
if (use64)
s.flatten();
else s = get_gdt_entry(seg[segid].selector >> 3);
break;
case SEGID_FS:
case SEGID_GS:
s = get_gdt_entry(seg[segid].selector >> 3);
if (use64) s.limit = 0xffffffffffffffffULL;