/
ThreadManForUser.java
4636 lines (3953 loc) · 198 KB
/
ThreadManForUser.java
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
/*
This file is part of jpcsp.
Jpcsp is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Jpcsp is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Jpcsp. If not, see <http://www.gnu.org/licenses/>.
*/
package jpcsp.HLE.modules;
import static jpcsp.Allegrex.Common._a0;
import static jpcsp.Allegrex.Common._a1;
import static jpcsp.Allegrex.Common._a2;
import static jpcsp.Allegrex.Common._a3;
import static jpcsp.Allegrex.Common._s0;
import static jpcsp.Allegrex.Common._sp;
import static jpcsp.Allegrex.Common._t0;
import static jpcsp.Allegrex.Common._v0;
import static jpcsp.Allegrex.Common._zr;
import static jpcsp.Emulator.exitCalled;
import static jpcsp.HLE.HLEModuleManager.HLESyscallNid;
import static jpcsp.HLE.Modules.ModuleMgrForUserModule;
import static jpcsp.HLE.kernel.managers.SceUidManager.hasUidPurpose;
import static jpcsp.HLE.kernel.types.SceKernelErrors.ERROR_KERNEL_ILLEGAL_ARGUMENT;
import static jpcsp.HLE.kernel.types.SceKernelErrors.ERROR_KERNEL_ILLEGAL_PRIORITY;
import static jpcsp.HLE.kernel.types.SceKernelErrors.ERROR_KERNEL_ILLEGAL_THREAD;
import static jpcsp.HLE.kernel.types.SceKernelErrors.ERROR_KERNEL_NOT_FOUND_ALARM;
import static jpcsp.HLE.kernel.types.SceKernelErrors.ERROR_KERNEL_NOT_FOUND_THREAD;
import static jpcsp.HLE.kernel.types.SceKernelErrors.ERROR_KERNEL_NOT_FOUND_THREAD_EVENT_HANDLER;
import static jpcsp.HLE.kernel.types.SceKernelErrors.ERROR_KERNEL_NOT_FOUND_VTIMER;
import static jpcsp.HLE.kernel.types.SceKernelErrors.ERROR_KERNEL_THREAD_ALREADY_DORMANT;
import static jpcsp.HLE.kernel.types.SceKernelErrors.ERROR_KERNEL_THREAD_ALREADY_SUSPEND;
import static jpcsp.HLE.kernel.types.SceKernelErrors.ERROR_KERNEL_THREAD_IS_NOT_DORMANT;
import static jpcsp.HLE.kernel.types.SceKernelErrors.ERROR_KERNEL_THREAD_IS_NOT_SUSPEND;
import static jpcsp.HLE.kernel.types.SceKernelErrors.ERROR_KERNEL_THREAD_IS_TERMINATED;
import static jpcsp.HLE.kernel.types.SceKernelErrors.ERROR_KERNEL_WAIT_STATUS_RELEASED;
import static jpcsp.HLE.kernel.types.SceKernelErrors.ERROR_KERNEL_WAIT_TIMEOUT;
import static jpcsp.HLE.kernel.types.SceKernelErrors.ERROR_OUT_OF_MEMORY;
import static jpcsp.HLE.kernel.types.SceKernelThreadEventHandlerInfo.THREAD_EVENT_CREATE;
import static jpcsp.HLE.kernel.types.SceKernelThreadEventHandlerInfo.THREAD_EVENT_DELETE;
import static jpcsp.HLE.kernel.types.SceKernelThreadEventHandlerInfo.THREAD_EVENT_EXIT;
import static jpcsp.HLE.kernel.types.SceKernelThreadEventHandlerInfo.THREAD_EVENT_START;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.JPCSP_WAIT_AUDIO;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.JPCSP_WAIT_CTRL;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.JPCSP_WAIT_DISPLAY_VBLANK;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.JPCSP_WAIT_GE_LIST;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.JPCSP_WAIT_NET;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.JPCSP_WAIT_UMD;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.JPCSP_WAIT_USB;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.PSP_THREAD_ATTR_KERNEL;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.PSP_THREAD_ATTR_USER;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.PSP_THREAD_READY;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.PSP_THREAD_RUNNING;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.PSP_THREAD_STOPPED;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.PSP_THREAD_SUSPEND;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.PSP_THREAD_WAITING;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.PSP_THREAD_WAITING_SUSPEND;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.PSP_WAIT_DELAY;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.PSP_WAIT_EVENTFLAG;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.PSP_WAIT_MSGPIPE;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.PSP_WAIT_MUTEX;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.PSP_WAIT_NONE;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.PSP_WAIT_SLEEP;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.PSP_WAIT_THREAD_END;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.PSP_WAIT_FPL;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.PSP_WAIT_LWMUTEX;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.PSP_WAIT_MBX;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.PSP_WAIT_SEMA;
import static jpcsp.HLE.kernel.types.SceKernelThreadInfo.PSP_WAIT_VPL;
import static jpcsp.HLE.kernel.types.SceModule.PSP_MODULE_KERNEL;
import static jpcsp.HLE.modules.SysMemUserForUser.KERNEL_PARTITION_ID;
import static jpcsp.HLE.modules.SysMemUserForUser.USER_PARTITION_ID;
import static jpcsp.Memory.addressMask;
import static jpcsp.MemoryMap.END_KERNEL;
import static jpcsp.MemoryMap.START_KERNEL;
import static jpcsp.util.HLEUtilities.ADDIU;
import static jpcsp.util.HLEUtilities.B;
import static jpcsp.util.HLEUtilities.JR;
import static jpcsp.util.HLEUtilities.LUI;
import static jpcsp.util.HLEUtilities.MOVE;
import static jpcsp.util.HLEUtilities.ORI;
import static jpcsp.util.HLEUtilities.SYSCALL;
import static jpcsp.util.Utilities.alignUp;
import static jpcsp.util.Utilities.hasFlag;
import static jpcsp.util.Utilities.writeStringZ;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import jpcsp.Emulator;
import jpcsp.Memory;
import jpcsp.MemoryMap;
import jpcsp.Processor;
import jpcsp.Allegrex.CpuState;
import jpcsp.Allegrex.Decoder;
import jpcsp.Allegrex.compiler.RuntimeContext;
import jpcsp.Debugger.DumpDebugState;
import jpcsp.HLE.BufferInfo;
import jpcsp.HLE.BufferInfo.LengthInfo;
import jpcsp.HLE.BufferInfo.Usage;
import jpcsp.HLE.CanBeNull;
import jpcsp.HLE.HLEFunction;
import jpcsp.HLE.HLEModule;
import jpcsp.HLE.HLEUnimplemented;
import jpcsp.HLE.Modules;
import jpcsp.HLE.PspString;
import jpcsp.HLE.SceKernelErrorException;
import jpcsp.HLE.StringInfo;
import jpcsp.HLE.TPointer;
import jpcsp.HLE.TPointer32;
import jpcsp.HLE.TPointer64;
import jpcsp.HLE.kernel.Managers;
import jpcsp.HLE.kernel.managers.IntrManager;
import jpcsp.HLE.kernel.managers.SceUidManager;
import jpcsp.HLE.kernel.managers.SystemTimeManager;
import jpcsp.HLE.kernel.types.IAction;
import jpcsp.HLE.kernel.types.IWaitStateChecker;
import jpcsp.HLE.kernel.types.SceKernelAlarmInfo;
import jpcsp.HLE.kernel.types.SceKernelCallbackInfo;
import jpcsp.HLE.kernel.types.SceKernelErrors;
import jpcsp.HLE.kernel.types.SceKernelLMOption;
import jpcsp.HLE.kernel.types.SceKernelSystemStatus;
import jpcsp.HLE.kernel.types.SceKernelThreadEventHandlerInfo;
import jpcsp.HLE.kernel.types.SceKernelThreadInfo;
import jpcsp.HLE.kernel.types.SceKernelThreadOptParam;
import jpcsp.HLE.kernel.types.SceKernelTls;
import jpcsp.HLE.kernel.types.SceKernelVTimerInfo;
import jpcsp.HLE.kernel.types.SceModule;
import jpcsp.HLE.kernel.types.ThreadWaitInfo;
import jpcsp.HLE.kernel.types.pspBaseCallback;
import jpcsp.HLE.kernel.types.SceKernelThreadInfo.RegisteredCallbacks;
import jpcsp.HLE.modules.SysMemUserForUser.SysMemInfo;
import jpcsp.memory.IMemoryReader;
import jpcsp.memory.IMemoryWriter;
import jpcsp.memory.MemoryReader;
import jpcsp.memory.MemoryWriter;
import jpcsp.scheduler.Scheduler;
import jpcsp.util.DurationStatistics;
import jpcsp.util.HLEUtilities;
import org.apache.log4j.Logger;
import jpcsp.HLE.CheckArgument;
/*
* Thread scheduling on PSP:
* - when a thread having a higher priority than the current thread, switches to the
* READY state, the current thread is interrupted immediately and is loosing the
* RUNNING state. The new thread then moves to the RUNNING state.
* - when a thread having the same or a lower priority than the current thread,
* switches to the READY state, the current thread is not interrupted and is keeping
* the RUNNING state.
* - a RUNNING thread can only yield to a thread having the same priority by calling
* sceKernelRotateThreadReadyQueue(0).
* - the clock precision when interrupting a RUNNING thread is about 200 microseconds.
* i.e., it can take up to 200us when a high priority thread moves to the READY
* state before it changes to the RUNNING state.
* - sceKernelStartThread is always resuming the thread dispatching.
*
* Thread scheduling on Jpcsp:
* - the rules for moving between states are implemented in hleChangeThreadState()
* - the rules for choosing the thread in the RUNNING state are implemented in
* hleRescheduleCurrentThread()
* - the clock precision for interrupting a RUNNING thread is about 1000 microseconds.
* This is due to a restriction of the Java timers used by the Thread.sleep() methods.
* Even the Thread.sleep(millis, nanos) seems to have the same restriction
* (at least on windows).
* - preemptive scheduling is implemented in RuntimeContext by a separate
* Java thread (RuntimeSyncThread). This thread sets the flag RuntimeContext.wantSync
* when a scheduler action has to be executed. This flag is checked by the compiled
* code at each back branch (i.e. a branch to a lower address, usually a loop).
*
* Test application:
* - taskScheduler.prx: testing the scheduler rules between threads having higher,
* lower or the same priority.
* The clock precision of 200us on the PSP can be observed here.
*/
public class ThreadManForUser extends HLEModule {
public static Logger log = Modules.getLogger("ThreadManForUser");
private HashMap<Integer, SceKernelThreadInfo> threadMap;
private HashMap<Integer, SceKernelThreadEventHandlerInfo> threadEventHandlers;
private LinkedList<SceKernelThreadInfo> readyThreads;
private SceKernelThreadInfo currentThread;
private SceKernelThreadInfo idle0, idle1;
public Statistics statistics;
private boolean dispatchThreadEnabled;
private static final int SCE_KERNEL_DISPATCHTHREAD_STATE_DISABLED = 0;
private static final int SCE_KERNEL_DISPATCHTHREAD_STATE_ENABLED = 1;
private static final String rootThreadName = "root";
// The PSP seems to have a resolution of 200us
protected static final int THREAD_DELAY_MINIMUM_MICROS = 200;
protected static final int CALLBACKID_REGISTER = _s0;
protected CallbackManager callbackManager = new CallbackManager();
public static int INTERNAL_THREAD_ADDRESS_START = MemoryMap.START_USERSPACE;
public static int INTERNAL_THREAD_ADDRESS_SIZE = 0x100;
public static int INTERNAL_THREAD_ADDRESS_END = INTERNAL_THREAD_ADDRESS_START + INTERNAL_THREAD_ADDRESS_SIZE;
public static int THREAD_EXIT_HANDLER_ADDRESS;
public static int CALLBACK_EXIT_HANDLER_ADDRESS;
private HashMap<Integer, pspBaseCallback> callbackMap;
private static final boolean LOG_CONTEXT_SWITCHING = true;
private static final boolean LOG_INSTRUCTIONS = false;
private int freeInternalUserMemoryStart;
private int freeInternalUserMemoryEnd;
// see sceKernelGetThreadmanIdList
public final static int SCE_KERNEL_TMID_Thread = 1;
public final static int SCE_KERNEL_TMID_Semaphore = 2;
public final static int SCE_KERNEL_TMID_EventFlag = 3;
public final static int SCE_KERNEL_TMID_Mbox = 4;
public final static int SCE_KERNEL_TMID_Vpl = 5;
public final static int SCE_KERNEL_TMID_Fpl = 6;
public final static int SCE_KERNEL_TMID_Mpipe = 7;
public final static int SCE_KERNEL_TMID_Callback = 8;
public final static int SCE_KERNEL_TMID_ThreadEventHandler = 9;
public final static int SCE_KERNEL_TMID_Alarm = 10;
public final static int SCE_KERNEL_TMID_VTimer = 11;
public final static int SCE_KERNEL_TMID_Mutex = 12;
public final static int SCE_KERNEL_TMID_LwMutex = 13;
public final static int SCE_KERNEL_TMID_SleepThread = 64;
public final static int SCE_KERNEL_TMID_DelayThread = 65;
public final static int SCE_KERNEL_TMID_SuspendThread = 66;
public final static int SCE_KERNEL_TMID_DormantThread = 67;
protected static final int INTR_NUMBER = IntrManager.PSP_SYSTIMER0_INTR;
protected Map<Integer, SceKernelAlarmInfo> alarms;
protected Map<Integer, SceKernelVTimerInfo> vtimers;
protected boolean needThreadReschedule;
protected WaitThreadEndWaitStateChecker waitThreadEndWaitStateChecker;
protected TimeoutThreadWaitStateChecker timeoutThreadWaitStateChecker;
protected SleepThreadWaitStateChecker sleepThreadWaitStateChecker;
public final static int PSP_ATTR_ADDR_HIGH = 0x4000;
protected HashMap<Integer, SceKernelTls> tlsMap;
public static class Statistics {
private ArrayList<ThreadStatistics> threads = new ArrayList<ThreadStatistics>();
public long allCycles = 0;
public long startTimeMillis;
public long endTimeMillis;
public long allCpuMillis = 0;
public Statistics() {
startTimeMillis = System.currentTimeMillis();
}
public void exit() {
endTimeMillis = System.currentTimeMillis();
}
public long getDurationMillis() {
return endTimeMillis - startTimeMillis;
}
private void addThreadStatistics(SceKernelThreadInfo thread) {
if (!DurationStatistics.collectStatistics) {
return;
}
ThreadStatistics threadStatistics = new ThreadStatistics();
threadStatistics.name = thread.name;
threadStatistics.runClocks = thread.runClocks;
threads.add(threadStatistics);
allCycles += thread.runClocks;
if (thread.javaThreadId > 0) {
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
if (threadMXBean.isThreadCpuTimeEnabled()) {
long threadCpuTimeNanos = thread.javaThreadCpuTimeNanos;
if (threadCpuTimeNanos < 0) {
threadCpuTimeNanos = threadMXBean.getThreadCpuTime(thread.javaThreadId);
}
if (threadCpuTimeNanos > 0) {
allCpuMillis += threadCpuTimeNanos / 1000000L;
}
}
}
}
private static class ThreadStatistics implements Comparable<ThreadStatistics> {
public String name;
public long runClocks;
@Override
public int compareTo(ThreadStatistics o) {
return -(Long.valueOf(runClocks).compareTo(o.runClocks));
}
public String getQuotedName() {
return "'" + name + "'";
}
}
}
public static class CallbackManager {
private Map<Integer, Callback> callbacks;
private int currentCallbackId;
public void Initialize() {
callbacks = new HashMap<Integer, Callback>();
currentCallbackId = 1;
}
public void addCallback(Callback callback) {
callbacks.put(callback.getId(), callback);
}
public Callback remove(int id) {
Callback callback = callbacks.remove(id);
return callback;
}
public int getNewCallbackId() {
return currentCallbackId++;
}
}
public static class Callback {
private int id;
private int address;
private int[] parameters;
private int gp;
private int savedIdRegister;
private int savedRa;
private int savedPc;
private int savedGp;
private int savedV0;
private int savedV1;
private IAction afterAction;
private boolean returnVoid;
private boolean preserveCpuState;
private CpuState savedCpuState;
public Callback(int id, int address, int[] parameters, int gp, IAction afterAction, boolean returnVoid, boolean preserveCpuState) {
this.id = id;
this.address = address;
this.parameters = parameters;
this.gp = gp;
this.afterAction = afterAction;
this.returnVoid = returnVoid;
this.preserveCpuState = preserveCpuState;
}
public int getId() {
return id;
}
public void execute(SceKernelThreadInfo thread) {
CpuState cpu = thread.cpuContext;
savedIdRegister = cpu.getRegister(CALLBACKID_REGISTER);
savedRa = cpu._ra;
savedPc = cpu.pc;
savedGp = cpu._gp;
savedV0 = cpu._v0;
savedV1 = cpu._v1;
if (preserveCpuState) {
savedCpuState = new CpuState(cpu);
}
// Copy parameters ($a0, $a1, ...) to the cpu
if (parameters != null) {
for (int i = 0; i < parameters.length; i++) {
cpu.setRegister(_a0 + i, parameters[i]);
}
}
cpu._gp = gp;
cpu.setRegister(CALLBACKID_REGISTER, id);
cpu._ra = CALLBACK_EXIT_HANDLER_ADDRESS;
cpu.pc = address;
RuntimeContext.executeCallback();
}
public void executeExit(CpuState cpu) {
cpu.setRegister(CALLBACKID_REGISTER, savedIdRegister);
cpu._gp = savedGp;
cpu._ra = savedRa;
cpu.pc = savedPc;
if (afterAction != null) {
afterAction.execute();
}
if (preserveCpuState) {
cpu.copy(savedCpuState);
} else {
// Do we need to restore $v0/$v1?
if (returnVoid) {
cpu._v0 = savedV0;
cpu._v1 = savedV1;
}
}
}
public void setAfterAction(IAction afterAction) {
this.afterAction = afterAction;
}
@Override
public String toString() {
return String.format("Callback address=0x%08X, id=%d, returnVoid=%b, preserveCpuState=%b", address, getId(), returnVoid, preserveCpuState);
}
}
private class AfterCallAction implements IAction {
private SceKernelThreadInfo thread;
private int status;
private int waitType;
private int waitId;
private ThreadWaitInfo threadWaitInfo;
private boolean doCallbacks;
private IAction afterAction;
public AfterCallAction(SceKernelThreadInfo thread, IAction afterAction) {
this.thread = thread;
status = thread.status;
waitType = thread.waitType;
waitId = thread.waitId;
threadWaitInfo = new ThreadWaitInfo(thread.wait);
doCallbacks = thread.doCallbacks;
this.afterAction = afterAction;
}
@Override
public void execute() {
boolean restoreWaitState = true;
// After calling a callback, check if the waiting state of the thread
// is still valid, i.e. if the thread must continue to wait or if the
// wait condition has been reached.
if (threadWaitInfo.waitStateChecker != null) {
if (!threadWaitInfo.waitStateChecker.continueWaitState(thread, threadWaitInfo)) {
restoreWaitState = false;
}
}
if (restoreWaitState) {
if (status == PSP_THREAD_RUNNING) {
doCallbacks = false;
}
if (log.isDebugEnabled()) {
log.debug(String.format("AfterCallAction: restoring wait state for thread '%s' to %s, %s, doCallbacks %b", thread.toString(), SceKernelThreadInfo.getStatusName(status), SceKernelThreadInfo.getWaitName(waitType, waitId, threadWaitInfo, status), doCallbacks));
}
// Restore the wait state of the thread
thread.waitType = waitType;
thread.waitId = waitId;
thread.wait.copy(threadWaitInfo);
hleChangeThreadState(thread, status);
} else if (thread.isRunning()) {
if (log.isDebugEnabled()) {
log.debug(String.format("AfterCallAction: leaving thread in RUNNING state: %s", thread));
}
doCallbacks = false;
} else if (!thread.isReady()) {
if (log.isDebugEnabled()) {
log.debug(String.format("AfterCallAction: set thread to READY state: %s", thread));
}
hleChangeThreadState(thread, PSP_THREAD_READY);
doCallbacks = false;
} else {
if (log.isDebugEnabled()) {
log.debug(String.format("AfterCallAction: leaving thread in READY state: %s", thread));
}
doCallbacks = false;
}
thread.doCallbacks = doCallbacks;
hleRescheduleCurrentThread();
if (afterAction != null) {
afterAction.execute();
}
}
}
public class TimeoutThreadAction implements IAction {
private SceKernelThreadInfo thread;
public TimeoutThreadAction(SceKernelThreadInfo thread) {
this.thread = thread;
}
@Override
public void execute() {
hleThreadWaitTimeout(thread);
}
}
public class TimeoutThreadWaitStateChecker implements IWaitStateChecker {
@Override
public boolean continueWaitState(SceKernelThreadInfo thread, ThreadWaitInfo wait) {
// Waiting forever?
if (wait.forever) {
return true;
}
if (wait.microTimeTimeout <= Emulator.getClock().microTime()) {
hleThreadWaitTimeout(thread);
return false;
}
// The waitTimeoutAction has been deleted by hleChangeThreadState while
// leaving the WAIT state. It has to be restored.
if (wait.waitTimeoutAction == null) {
wait.waitTimeoutAction = new TimeoutThreadAction(thread);
}
return true;
}
}
public class DeleteThreadAction implements IAction {
private SceKernelThreadInfo thread;
public DeleteThreadAction(SceKernelThreadInfo thread) {
this.thread = thread;
}
@Override
public void execute() {
hleDeleteThread(thread);
}
}
public class WaitThreadEndWaitStateChecker implements IWaitStateChecker {
@Override
public boolean continueWaitState(SceKernelThreadInfo thread, ThreadWaitInfo wait) {
// Check if the thread has to continue its wait state or if the thread
// has exited during the callback execution.
SceKernelThreadInfo threadEnd = getThreadById(wait.ThreadEnd_id);
if (threadEnd == null) {
// The thread has completely disappeared during the callback execution...
thread.cpuContext._v0 = ERROR_KERNEL_NOT_FOUND_THREAD;
return false;
}
if (threadEnd.isStopped()) {
// Return exit status of stopped thread
thread.cpuContext._v0 = threadEnd.exitStatus;
return false;
}
return true;
}
}
public static class SleepThreadWaitStateChecker implements IWaitStateChecker {
@Override
public boolean continueWaitState(SceKernelThreadInfo thread, ThreadWaitInfo wait) {
if (thread.wakeupCount > 0) {
// sceKernelWakeupThread() has been called while the thread was waiting
thread.wakeupCount--;
// Return 0
thread.cpuContext._v0 = 0;
return false;
}
return true;
}
}
/**
* A callback is deleted when its return value is non-zero.
*/
private class CheckCallbackReturnValue implements IAction {
private SceKernelThreadInfo thread;
private int callbackUid;
public CheckCallbackReturnValue(SceKernelThreadInfo thread, int callbackUid) {
this.thread = thread;
this.callbackUid = callbackUid;
}
@Override
public void execute() {
int callbackReturnValue = thread.cpuContext._v0;
if (callbackReturnValue != 0) {
if (log.isDebugEnabled()) {
log.debug(String.format("Callback uid=0x%X has returned value 0x%08X: deleting the callback", callbackUid, callbackReturnValue));
}
hleKernelDeleteCallback(callbackUid);
}
}
}
private static class AfterSceKernelExtendThreadStackAction implements IAction {
private SceKernelThreadInfo thread;
private int savedPc;
private int savedSp;
private int savedRa;
private int returnValue;
private SysMemInfo extendedStackSysMemInfo;
public AfterSceKernelExtendThreadStackAction(SceKernelThreadInfo thread, int savedPc, int savedSp, int savedRa, SysMemInfo extendedStackSysMemInfo) {
this.thread = thread;
this.savedPc = savedPc;
this.savedSp = savedSp;
this.savedRa = savedRa;
this.extendedStackSysMemInfo = extendedStackSysMemInfo;
}
@Override
public void execute() {
CpuState cpu = Emulator.getProcessor().cpu;
if (log.isDebugEnabled()) {
log.debug(String.format("AfterSceKernelExtendThreadStackAction savedSp=0x%08X, savedRa=0x%08X, $v0=0x%08X", savedSp, savedRa, cpu._v0));
}
cpu.pc = savedPc;
cpu._sp = savedSp;
cpu._ra = savedRa;
returnValue = cpu._v0;
// The return value in $v0 of the entryAdd is passed back as return value
// of sceKernelExtendThreadStack.
thread.freeExtendedStack(extendedStackSysMemInfo);
}
public int getReturnValue() {
return returnValue;
}
}
public ThreadManForUser() {
}
@Override
public void start() {
currentThread = null;
threadMap = new HashMap<Integer, SceKernelThreadInfo>();
threadEventHandlers = new HashMap<Integer, SceKernelThreadEventHandlerInfo>();
readyThreads = new LinkedList<SceKernelThreadInfo>();
statistics = new Statistics();
callbackMap = new HashMap<Integer, pspBaseCallback>();
callbackManager.Initialize();
reserveInternalMemory();
installIdleThreads();
installThreadExitHandler();
installCallbackExitHandler();
alarms = new HashMap<Integer, SceKernelAlarmInfo>();
vtimers = new HashMap<Integer, SceKernelVTimerInfo>();
dispatchThreadEnabled = true;
needThreadReschedule = true;
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
if (threadMXBean.isThreadCpuTimeSupported()) {
threadMXBean.setThreadCpuTimeEnabled(true);
}
waitThreadEndWaitStateChecker = new WaitThreadEndWaitStateChecker();
timeoutThreadWaitStateChecker = new TimeoutThreadWaitStateChecker();
sleepThreadWaitStateChecker = new SleepThreadWaitStateChecker();
tlsMap = new HashMap<Integer, SceKernelTls>();
super.start();
}
@Override
public void stop() {
alarms = null;
vtimers = null;
for (SceKernelThreadInfo thread : threadMap.values()) {
terminateThread(thread);
}
super.stop();
}
public Iterator<SceKernelThreadInfo> iterator() {
return threadMap.values().iterator();
}
public Iterator<SceKernelThreadInfo> iteratorByPriority() {
Collection<SceKernelThreadInfo> c = threadMap.values();
List<SceKernelThreadInfo> list = new LinkedList<SceKernelThreadInfo>(c);
Collections.sort(list, idle0); // We need an instance of SceKernelThreadInfo for the comparator, so we use idle0
return list.iterator();
}
public SceKernelThreadInfo getRootThread(SceModule module) {
if (threadMap != null) {
for (SceKernelThreadInfo thread : threadMap.values()) {
if (rootThreadName.equals(thread.name) && (module == null || thread.moduleid == module.modid)) {
return thread;
}
}
}
return null;
}
/** call this when resetting the emulator
* @param entry_addr entry from ELF header
* @param attr from sceModuleInfo ELF section header */
public void Initialise(SceModule module, int entry_addr, int attr, String pspfilename, int moduleid, int gp, boolean fromSyscall) {
// Create a thread the program will run inside
// The stack size seems to be 0x40000 when starting the application from the VSH
// and smaller when starting the application with sceKernelLoadExec() - guess: 0x8000.
// This could not be reproduced on a PSP.
int rootStackSize = (fromSyscall ? 0x8000 : 0x40000);
// Use the module_start_thread_stacksize when this information was present in the ELF file
if (module != null && module.module_start_thread_stacksize > 0) {
rootStackSize = module.module_start_thread_stacksize;
}
// For a kernel module, the stack is allocated in the kernel partition
int rootMpidStack = module != null && module.mpiddata > 0 ? module.mpiddata : USER_PARTITION_ID;
int rootInitPriority = 0x20;
if (moduleid >= 0) {
int startModuleOptionsLength = 20;
int startModuleOptionsAddr = allocateInternalUserMemory(startModuleOptionsLength);
TPointer startModuleOptionsPtr = new TPointer(getMemory(), startModuleOptionsAddr);
startModuleOptionsPtr.setValue32(0, startModuleOptionsLength);
SceKernelLMOption startModuleOptions = new SceKernelLMOption();
startModuleOptions.mpidText = module != null ? module.mpidtext : USER_PARTITION_ID;
startModuleOptions.mpidData = module != null ? module.mpiddata : USER_PARTITION_ID;
startModuleOptions.flags = IoFileMgrForUser.PSP_O_RDONLY;
startModuleOptions.position = SysMemUserForUser.PSP_SMEM_Low;
startModuleOptions.write(startModuleOptionsPtr);
int numberInstructions = 11;
int rootThreadMemorySize = numberInstructions * 4;
int rootThreadAddr = allocateInternalUserMemory(rootThreadMemorySize);
IMemoryWriter memoryWriter = MemoryWriter.getMemoryWriter(rootThreadAddr, rootThreadMemorySize, 4);
memoryWriter.writeNext(ADDIU(_sp, _sp, -16));
memoryWriter.writeNext(MOVE(_a2, _a1));
memoryWriter.writeNext(MOVE(_a1, _a0));
memoryWriter.writeNext(ADDIU(_a0, _zr, moduleid));
memoryWriter.writeNext(MOVE(_a3, _zr));
memoryWriter.writeNext(LUI(_t0, startModuleOptionsAddr >>> 16));
memoryWriter.writeNext(ORI(_t0, _t0, startModuleOptionsAddr & 0xFFFF));
memoryWriter.writeNext(SYSCALL(ModuleMgrForUserModule, "sceKernelStartModule"));
memoryWriter.writeNext(ADDIU(_sp, _sp, 16));
memoryWriter.writeNext(JR());
memoryWriter.writeNext(MOVE(_v0, _zr));
memoryWriter.flush();
if (log.isDebugEnabled()) {
log.debug(String.format("Root thread entry using sceKernelStartModule 0x%08X replacing 0x%08X", rootThreadAddr, entry_addr));
}
entry_addr = rootThreadAddr;
// Start the root thread with a lower priority (i.e. higher priority value)
// so that optional plug-in modules have time to properly initialize
rootInitPriority = 0x30;
} else {
// Use the module_start_thread_priority when this information was present in the ELF file
if (module != null && module.module_start_thread_priority > 0) {
rootInitPriority = module.module_start_thread_priority;
}
}
SceKernelThreadInfo rootThread = new SceKernelThreadInfo(rootThreadName, entry_addr, rootInitPriority, rootStackSize, attr, rootMpidStack);
if (log.isDebugEnabled()) {
log.debug(String.format("Creating root thread: uid=0x%X, entry=0x%08X, priority=%d, stackSize=0x%X, attr=0x%X", rootThread.uid, entry_addr, rootInitPriority, rootStackSize, attr));
}
rootThread.moduleid = moduleid;
threadMap.put(rootThread.uid, rootThread);
// Set user mode bit if kernel mode bit is not present
if (!rootThread.isKernelMode()) {
rootThread.attr |= PSP_THREAD_ATTR_USER;
}
// Setup args by copying them onto the stack
hleKernelSetThreadArguments(rootThread, pspfilename);
// Setup threads $gp
rootThread.cpuContext._gp = gp;
idle0.cpuContext._gp = gp;
idle1.cpuContext._gp = gp;
hleChangeThreadState(rootThread, PSP_THREAD_READY);
hleRescheduleCurrentThread();
}
public void hleKernelSetThreadArguments(SceKernelThreadInfo thread, String argument) {
if (argument != null) {
int address = prepareThreadArguments(thread, argument.length() + 1);
writeStringZ(Memory.getInstance(), address, argument);
}
}
public void hleKernelSetThreadArguments(SceKernelThreadInfo thread, byte[] argument, int argumentSize) {
int address = prepareThreadArguments(thread, argumentSize);
IMemoryWriter memoryWriter = MemoryWriter.getMemoryWriter(address, argumentSize, 1);
for (int i = 0; i < argumentSize; i++) {
memoryWriter.writeNext(argument[i] & 0xFF);
}
memoryWriter.flush();
}
public void hleKernelSetThreadArguments(SceKernelThreadInfo thread, TPointer argumentAddr, int argumentSize) {
int address = prepareThreadArguments(thread, argumentAddr.isNull() ? -1 : argumentSize);
if (argumentAddr.isNotNull()) {
TPointer destinationAddr = new TPointer(getMemory(), address);
destinationAddr.memcpy(argumentAddr, argumentSize);
}
}
private int prepareThreadArguments(SceKernelThreadInfo thread, int argumentSize) {
// 256 bytes padding between user data top and real stack top
int address = (thread.getStackAddr() + thread.stackSize - 0x100) - ((argumentSize + 0xF) & ~0xF);
if (argumentSize < 0) {
// Set the pointer to NULL when none is provided
thread.cpuContext._a0 = 0; // a0 = user data len
thread.cpuContext._a1 = 0; // a1 = pointer to arg data in stack
} else {
thread.cpuContext._a0 = argumentSize; // a0 = user data len
thread.cpuContext._a1 = address; // a1 = pointer to arg data in stack
}
// 64 bytes padding between program stack top and user data
thread.cpuContext._sp = address - 0x40;
return address;
}
private void reserveInternalMemory() {
// This memory is always reserved on a real PSP
int internalUserMemorySize = 0x4000;
SysMemInfo rootMemInfo = Modules.SysMemUserForUserModule.malloc(SysMemUserForUser.USER_PARTITION_ID, "ThreadMan-RootMem", SysMemUserForUser.PSP_SMEM_Addr, internalUserMemorySize, MemoryMap.START_USERSPACE);
freeInternalUserMemoryStart = rootMemInfo.addr;
freeInternalUserMemoryEnd = freeInternalUserMemoryStart + internalUserMemorySize;
}
public int allocateInternalUserMemory(int size) {
// Align on a multiple of 4 bytes
size = alignUp(size, 3);
if (freeInternalUserMemoryStart + size > freeInternalUserMemoryEnd) {
log.error(String.format("allocateInternalUserMemory not enough free memory available, requested size=0x%X, available size=0x%X", size, freeInternalUserMemoryEnd - freeInternalUserMemoryStart));
return 0;
}
int allocatedMem = freeInternalUserMemoryStart;
freeInternalUserMemoryStart += size;
if (log.isDebugEnabled()) {
log.debug(String.format("allocateInternalUserMemory size=0x%X returning 0x%08X, remaining free size=0x%X", size, allocatedMem, freeInternalUserMemoryEnd - freeInternalUserMemoryStart));
}
return allocatedMem;
}
/**
* Generate 2 idle threads which can toggle between each other when there are no ready threads
*/
private void installIdleThreads() {
int IDLE_THREAD_ADDRESS = HLEUtilities.getInstance().allocateInternalMemory(12);
IMemoryWriter memoryWriter = MemoryWriter.getMemoryWriter(IDLE_THREAD_ADDRESS, 12, 4);
memoryWriter.writeNext(MOVE(_a0, _zr));
memoryWriter.writeNext(B(-2));
memoryWriter.writeNext(SYSCALL(this, "sceKernelDelayThread"));
memoryWriter.flush();
int idleThreadStackSize = 0x1000;
// Lowest allowed priority is 0x77, so we are fine at 0x7F.
// Allocate a stack because interrupts can be processed by the
// idle thread, using its stack.
// The stack is allocated into the reservedMem area.
idle0 = new SceKernelThreadInfo("idle0", IDLE_THREAD_ADDRESS | 0x80000000, 0x7F, 0, PSP_THREAD_ATTR_KERNEL, KERNEL_PARTITION_ID);
idle0.setSystemStack(allocateInternalUserMemory(idleThreadStackSize), idleThreadStackSize);
idle0.reset();
idle0.exitStatus = ERROR_KERNEL_THREAD_IS_NOT_DORMANT;
threadMap.put(idle0.uid, idle0);
hleChangeThreadState(idle0, PSP_THREAD_READY);
idle1 = new SceKernelThreadInfo("idle1", IDLE_THREAD_ADDRESS | 0x80000000, 0x7F, 0, PSP_THREAD_ATTR_KERNEL, KERNEL_PARTITION_ID);
idle1.setSystemStack(allocateInternalUserMemory(idleThreadStackSize), idleThreadStackSize);
idle1.reset();
idle1.exitStatus = ERROR_KERNEL_THREAD_IS_NOT_DORMANT;
threadMap.put(idle1.uid, idle1);
hleChangeThreadState(idle1, PSP_THREAD_READY);
}
private void installThreadExitHandler() {
THREAD_EXIT_HANDLER_ADDRESS = HLEUtilities.getInstance().allocateInternalMemory(12);
IMemoryWriter memoryWriter = MemoryWriter.getMemoryWriter(THREAD_EXIT_HANDLER_ADDRESS, 12, 4);
memoryWriter.writeNext(MOVE(_a0, _v0));
memoryWriter.writeNext(JR());
memoryWriter.writeNext(SYSCALL(this, "hleKernelExitThread"));
memoryWriter.flush();
}
private void installCallbackExitHandler() {
CALLBACK_EXIT_HANDLER_ADDRESS = HLEUtilities.getInstance().installHLESyscall(this, "hleKernelExitCallback");
}
/** to be called when exiting the emulation */
public void exit() {
if (threadMap != null) {
// Delete all the threads to collect statistics
deleteAllThreads();
log.info("----------------------------- ThreadMan exit -----------------------------");
if (DurationStatistics.collectStatistics) {
statistics.exit();
log.info(String.format("ThreadMan Statistics (%,d cycles in %.3fs):", statistics.allCycles, statistics.getDurationMillis() / 1000.0));
Collections.sort(statistics.threads);
for (Statistics.ThreadStatistics threadStatistics : statistics.threads) {
double percentage = 0;
if (statistics.allCycles != 0) {
percentage = (threadStatistics.runClocks / (double) statistics.allCycles) * 100;
}
log.info(String.format(" Thread %-30s %,12d cycles (%5.2f%%)", threadStatistics.getQuotedName(), threadStatistics.runClocks, percentage));
}
}
}
}
/** To be called from the main emulation loop
* This is only used when running in interpreter mode,
* i.e. it is no longer used when the Compiler is enabled.
*/
public void step() {
if (LOG_INSTRUCTIONS) {
if (log.isTraceEnabled()) {
CpuState cpu = Emulator.getProcessor().cpu;
if (!isIdleThread(currentThread) && cpu.pc != 0) {
int address = cpu.pc - 4;
int opcode = Memory.getInstance().read32(address);
log.trace(String.format("Executing %08X %s", address, Decoder.instruction(opcode).disasm(address, opcode)));
}
}
}
if (currentThread != null) {
currentThread.runClocks++;
} else if (!exitCalled()) {
// We always need to be in a thread! we shouldn't get here.
log.error("No ready threads!");
}
}
private void internalContextSwitch(SceKernelThreadInfo newThread) {
if (currentThread != null) {
// Switch out old thread
if (currentThread.status == PSP_THREAD_RUNNING) {
hleChangeThreadState(currentThread, PSP_THREAD_READY);
}
// save registers
currentThread.saveContext();
}
if (newThread != null) {
// Switch in new thread
hleChangeThreadState(newThread, PSP_THREAD_RUNNING);
// restore registers
newThread.restoreContext();
if (LOG_CONTEXT_SWITCHING && log.isDebugEnabled() && !isIdleThread(newThread)) {
log.debug(String.format("----- %s, now=%d", newThread, Emulator.getClock().microTime()));
}
} else {
// When running under compiler mode this gets triggered by exit()
if (!exitCalled()) {
DumpDebugState.dumpDebugState();
log.info("No ready threads - pausing emulator. caller:" + getCallingFunction());
Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNKNOWN);
}