-
Notifications
You must be signed in to change notification settings - Fork 47
/
fossilize_replay_linux.hpp
1745 lines (1538 loc) · 51.9 KB
/
fossilize_replay_linux.hpp
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
/* Copyright (c) 2019 Hans-Kristian Arntzen
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/epoll.h>
#include <sys/signalfd.h>
#include <sys/socket.h>
#include <sys/timerfd.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <limits.h>
#include <errno.h>
#include "fossilize_external_replayer.hpp"
#include "path.hpp"
#include "platform/futex_wrapper_linux.hpp"
#include <inttypes.h>
static bool write_all(int fd, const char *str)
{
// write is async-signal safe, but not stdio.
size_t len = strlen(str);
while (len)
{
ssize_t wrote = write(fd, str, len);
if (wrote <= 0)
return false;
str += wrote;
len -= wrote;
}
return true;
}
static int run_slave_process(const VulkanDevice::Options &opts,
const ThreadedReplayer::Options &replayer_opts,
const vector<const char *> &databases);
namespace Global
{
static unordered_set<Hash> faulty_spirv_modules;
static unsigned active_processes;
static unsigned running_processes;
static unsigned target_running_processes;
static int target_running_processes_static = -1;
static bool target_running_processes_io_stall = true;
static bool target_running_processes_dirty_pages = true;
static ThreadedReplayer::Options base_replayer_options;
static vector<const char *> databases;
static sigset_t old_mask;
static int signal_fd;
static int timer_fd;
static int epoll_fd;
static VulkanDevice::Options device_options;
static bool quiet_slave;
static bool control_fd_is_sentinel;
static int control_fd = -1;
static SharedControlBlock *control_block;
static int metadata_fd = -1;
static int heartbeats = 1;
}
static void remove_epoll_entry(int fd)
{
if (epoll_ctl(Global::epoll_fd, EPOLL_CTL_DEL, fd, nullptr) < 0)
LOGE("epoll_ctl() DEL failed.\n");
}
static void close_and_remove_epoll_entry(int &fd)
{
if (fd >= 0)
{
remove_epoll_entry(fd);
close(fd);
}
fd = -1;
}
struct ProcessProgress
{
unsigned start_graphics_index = 0u;
unsigned start_compute_index = 0u;
unsigned start_raytracing_index = 0u;
unsigned end_graphics_index = ~0u;
unsigned end_compute_index = ~0u;
unsigned end_raytracing_index = ~0u;
int heartbeats = -1;
pid_t pid = -1;
int crash_fd = -1;
int timer_fd = -1;
int watchdog_timer_fd = -1;
int compute_progress = -1;
int graphics_progress = -1;
int raytracing_progress = -1;
bool process_once();
bool process_shutdown(int wstatus);
bool start_child_process(vector<ProcessProgress> &siblings);
void parse_raw(const char *str);
void parse(const char *cmd);
void begin_heartbeat();
void heartbeat();
uint32_t index = 0;
bool stopped = false;
bool expect_kill = false;
char module_uuid_path[2 * VK_UUID_SIZE + 1] = {};
std::string parse_buffer;
};
void ProcessProgress::parse_raw(const char *str)
{
parse_buffer += str;
size_t n;
while ((n = parse_buffer.find_first_of('\n')) != std::string::npos)
{
auto cmd = parse_buffer.substr(0, n);
parse(cmd.c_str());
parse_buffer = parse_buffer.substr(n + 1);
}
}
void ProcessProgress::parse(const char *cmd)
{
if (strncmp(cmd, "CRASH", 5) == 0)
{
// We crashed ... Set up a timeout in case the process hangs while trying to recover.
close_and_remove_epoll_entry(timer_fd);
timer_fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC);
if (timer_fd >= 0)
{
struct itimerspec spec = {};
spec.it_value.tv_sec = 3;
if (timerfd_settime(timer_fd, 0, &spec, nullptr) < 0)
LOGE("Failed to set time with timerfd_settime.\n");
struct epoll_event event = {};
event.data.u32 = 0x80000000u | index;
event.events = EPOLLIN;
if (epoll_ctl(Global::epoll_fd, EPOLL_CTL_ADD, timer_fd, &event))
LOGE("Failed adding timer_fd to epoll_ctl().\n");
}
else
LOGE("Failed to create timerfd. Cannot support timeout for process.\n");
}
else if (strncmp(cmd, "GRAPHICS_VERR", 13) == 0 ||
strncmp(cmd, "RAYTRACE_VERR", 13) == 0 ||
strncmp(cmd, "COMPUTE_VERR", 12) == 0)
{
if (Global::control_block)
{
// Just forward the message.
char buffer[ControlBlockMessageSize] = {};
strcpy(buffer, cmd);
futex_wrapper_lock(&Global::control_block->futex_lock);
shared_control_block_write(Global::control_block, buffer, sizeof(buffer));
futex_wrapper_unlock(&Global::control_block->futex_lock);
}
}
else if (strncmp(cmd, "GRAPHICS", 8) == 0)
{
char *end = nullptr;
graphics_progress = int(strtol(cmd + 8, &end, 0));
if (end)
{
Hash graphics_pipeline = strtoull(end, nullptr, 16);
// graphics_progress tells us where to start on next iteration, but -1 was actually the pipeline index that crashed.
if (Global::control_block && graphics_progress > 0 && graphics_pipeline != 0)
{
char buffer[ControlBlockMessageSize];
sprintf(buffer, "GRAPHICS %d %" PRIx64 "\n", graphics_progress - 1, graphics_pipeline);
futex_wrapper_lock(&Global::control_block->futex_lock);
shared_control_block_write(Global::control_block, buffer, sizeof(buffer));
futex_wrapper_unlock(&Global::control_block->futex_lock);
}
}
}
else if (strncmp(cmd, "RAYTRACE", 8) == 0)
{
char *end = nullptr;
raytracing_progress = int(strtol(cmd + 8, &end, 0));
if (end)
{
Hash raytracing_pipeline = strtoull(end, nullptr, 16);
// raytracing_progress tells us where to start on next iteration, but -1 was actually the pipeline index that crashed.
if (Global::control_block && raytracing_progress > 0 && raytracing_pipeline != 0)
{
char buffer[ControlBlockMessageSize];
sprintf(buffer, "RAYTRACE %d %" PRIx64 "\n", raytracing_progress - 1, raytracing_pipeline);
futex_wrapper_lock(&Global::control_block->futex_lock);
shared_control_block_write(Global::control_block, buffer, sizeof(buffer));
futex_wrapper_unlock(&Global::control_block->futex_lock);
}
}
}
else if (strncmp(cmd, "COMPUTE", 7) == 0)
{
char *end = nullptr;
compute_progress = int(strtol(cmd + 7, &end, 0));
if (end)
{
Hash compute_pipeline = strtoull(end, nullptr, 16);
// compute_progress tells us where to start on next iteration, but -1 was actually the pipeline index that crashed.
if (Global::control_block && compute_progress > 0 && compute_pipeline)
{
char buffer[ControlBlockMessageSize];
sprintf(buffer, "COMPUTE %d %" PRIx64 "\n", compute_progress - 1, compute_pipeline);
futex_wrapper_lock(&Global::control_block->futex_lock);
shared_control_block_write(Global::control_block, buffer, sizeof(buffer));
futex_wrapper_unlock(&Global::control_block->futex_lock);
}
}
}
else if (strncmp(cmd, "MODULE_UUID", 11) == 0)
{
memcpy(module_uuid_path, cmd + 12, VK_UUID_SIZE * 2);
}
else if (strncmp(cmd, "MODULE", 6) == 0)
{
auto hash = strtoull(cmd + 6, nullptr, 16);
Global::faulty_spirv_modules.insert(hash);
if (Global::control_block)
{
Global::control_block->banned_modules.fetch_add(1, std::memory_order_relaxed);
char buffer[ControlBlockMessageSize] = {};
strcpy(buffer, cmd);
futex_wrapper_lock(&Global::control_block->futex_lock);
shared_control_block_write(Global::control_block, buffer, sizeof(buffer));
futex_wrapper_unlock(&Global::control_block->futex_lock);
}
}
else if (strncmp(cmd, "BEGIN_HEARTBEAT", 15) == 0)
{
begin_heartbeat();
}
else if (strncmp(cmd, "HEARTBEAT", 9) == 0)
{
heartbeat();
}
else
LOGE("Got unexpected message from child: %s\n", cmd);
}
bool ProcessProgress::process_once()
{
if (crash_fd < 0)
return false;
// Important to use raw FD IO here since we are not guaranteed
// to be able to read a newline here.
// This can happen if the child process started writing to the file,
// but received a SIGSTOP in the middle of writing for whatever reason.
char buffer[65];
ssize_t ret = ::read(crash_fd, buffer, sizeof(buffer) - 1);
if (ret <= 0)
return false;
buffer[ret] = '\0';
parse_raw(buffer);
return true;
}
void ProcessProgress::begin_heartbeat()
{
close_and_remove_epoll_entry(watchdog_timer_fd);
watchdog_timer_fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC);
if (watchdog_timer_fd >= 0)
{
struct itimerspec spec = {};
spec.it_value.tv_sec = 10;
if (timerfd_settime(watchdog_timer_fd, 0, &spec, nullptr) < 0)
LOGE("Failed to set time with timerfd_settime.\n");
struct epoll_event event = {};
event.data.u32 = 0x40000000u | index;
event.events = EPOLLIN;
if (epoll_ctl(Global::epoll_fd, EPOLL_CTL_ADD, watchdog_timer_fd, &event))
LOGE("Failed adding timer_fd to epoll_ctl().\n");
}
else
LOGE("Failed to create timerfd. Cannot support timeout for process.\n");
}
void ProcessProgress::heartbeat()
{
if (watchdog_timer_fd >= 0)
{
heartbeats++;
// Rearm timer
struct itimerspec spec = {};
spec.it_value.tv_sec = 10;
if (timerfd_settime(watchdog_timer_fd, 0, &spec, nullptr) < 0)
LOGE("Failed to set time with timerfd_settime.\n");
}
}
bool ProcessProgress::process_shutdown(int wstatus)
{
// Flush out all messages we got.
while (process_once());
parse_buffer.clear();
heartbeats = -1;
close_and_remove_epoll_entry(crash_fd);
// Close the timerfd.
close_and_remove_epoll_entry(timer_fd);
close_and_remove_epoll_entry(watchdog_timer_fd);
// Reap child process.
Global::active_processes--;
auto wait_pid = pid;
pid = -1;
// If application exited in normal manner, we are done.
if (WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
return false;
if (WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGKILL && expect_kill)
{
LOGI("Parent process is shutting down. Expected SIGKILL.\n");
return false;
}
if (WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGKILL)
{
// We had to kill the process early. Log this for debugging.
LOGE("Process index %u (PID: %d) failed and it had to be killed in timeout with SIGKILL.\n",
index, wait_pid);
}
// If the child did not exit in a normal manner, we failed to catch any crashing signal.
// Do not try any further.
if (!WIFEXITED(wstatus) && WIFSIGNALED(wstatus) &&
(WTERMSIG(wstatus) != SIGKILL && WTERMSIG(wstatus) != SIGSEGV))
{
LOGE("Process index %u (PID: %d) failed to terminate in a clean fashion (signal %d). We cannot continue replaying.\n",
index, wait_pid, WTERMSIG(wstatus));
if (Global::control_block)
Global::control_block->dirty_process_deaths.fetch_add(1, std::memory_order_relaxed);
return false;
}
// We might have crashed, but we never saw any progress marker.
// We do not know what to do from here, so we just terminate.
if (graphics_progress < 0 || compute_progress < 0 || raytracing_progress < 0)
{
LOGE("Child process %d terminated before we could receive progress. Cannot continue.\n",
wait_pid);
if (Global::control_block)
Global::control_block->dirty_process_deaths.fetch_add(1, std::memory_order_relaxed);
return false;
}
if (Global::control_block)
Global::control_block->clean_process_deaths.fetch_add(1, std::memory_order_relaxed);
start_graphics_index = uint32_t(graphics_progress);
start_compute_index = uint32_t(compute_progress);
start_raytracing_index = uint32_t(raytracing_progress);
if (start_graphics_index >= end_graphics_index &&
start_compute_index >= end_compute_index &&
start_raytracing_index >= end_raytracing_index)
{
LOGE("Process index %u (PID: %d) crashed, but there is nothing more to replay.\n", index, wait_pid);
return false;
}
else
{
LOGE("Process index %u (PID: %d) crashed, but will retry.\n", index, wait_pid);
LOGE(" New graphics range (%u, %u)\n", start_graphics_index, end_graphics_index);
LOGE(" New compute range (%u, %u)\n", start_compute_index, end_compute_index);
LOGE(" New raytracing range (%u, %u)\n", start_raytracing_index, end_raytracing_index);
return true;
}
}
static void send_faulty_modules_and_close(int fd)
{
for (auto &m : Global::faulty_spirv_modules)
{
char buffer[18];
sprintf(buffer, "%" PRIx64 "\n", m);
write_all(fd, buffer);
}
close(fd);
}
static bool poll_process_memory_usage(pid_t pid, ExternalReplayer::ProcessStats &stats)
{
long long values[3];
char path[1024];
snprintf(path, sizeof(path), "/proc/%d/statm", pid);
FILE *file = fopen(path, "r");
if (!file)
return false;
if (fscanf(file, "%lld %lld %lld",
&values[0], &values[1], &values[2]) != 3)
{
fclose(file);
return false;
}
fclose(file);
int64_t resident = (values[1] * getpagesize()) / (1024 * 1024);
int64_t shared = (values[2] * getpagesize()) / (1024 * 1024);
if (resident > UINT32_MAX)
resident = UINT32_MAX;
if (shared > UINT32_MAX)
shared = UINT32_MAX;
stats.resident_mib = resident;
stats.shared_mib = shared;
return true;
}
static void poll_self_child_memory_usage(const std::vector<ProcessProgress> &processes)
{
uint32_t num_processes = processes.size() + 1;
if (num_processes > MaxProcessStats)
num_processes = MaxProcessStats;
ExternalReplayer::ProcessStats stats = {};
if (!poll_process_memory_usage(getpid(), stats))
stats = {};
if (Global::control_block)
{
Global::control_block->process_reserved_memory_mib[0].store(stats.resident_mib, std::memory_order_relaxed);
Global::control_block->process_shared_memory_mib[0].store(stats.shared_mib, std::memory_order_relaxed);
Global::control_block->process_heartbeats[0].store(Global::heartbeats, std::memory_order_relaxed);
}
else
{
LOGI("Master process: %5u MiB resident, %5u MiB shared.\n", stats.resident_mib, stats.shared_mib);
}
for (uint32_t i = 1; i < num_processes; i++)
{
if (processes[i - 1].pid < 0)
stats = {};
else if (!poll_process_memory_usage(processes[i - 1].pid, stats))
stats = {};
if (Global::control_block)
{
Global::control_block->process_reserved_memory_mib[i].store(stats.resident_mib, std::memory_order_relaxed);
Global::control_block->process_shared_memory_mib[i].store(stats.shared_mib, std::memory_order_relaxed);
Global::control_block->process_heartbeats[i].store(
processes[i - 1].stopped ? 0 : processes[i - 1].heartbeats, std::memory_order_relaxed);
}
else
{
LOGI("Child process #%u: %15u MiB resident, %15u MiB shared.\n",
i - 1, stats.resident_mib, stats.shared_mib);
}
}
if (Global::control_block)
{
Global::control_block->num_running_processes.store(Global::running_processes, std::memory_order_relaxed);
Global::control_block->num_processes_memory_stats.store(num_processes, std::memory_order_release);
}
}
bool ProcessProgress::start_child_process(vector<ProcessProgress> &siblings)
{
graphics_progress = -1;
compute_progress = -1;
raytracing_progress = -1;
stopped = false;
if (start_graphics_index >= end_graphics_index &&
start_compute_index >= end_compute_index &&
start_raytracing_index >= end_raytracing_index)
{
// Nothing to do.
return true;
}
int crash_fds[2];
int input_fds[2];
if (pipe(crash_fds) < 0)
return false;
if (pipe(input_fds) < 0)
return false;
pid_t new_pid = fork(); // Fork off a child.
if (new_pid > 0)
{
// We're the parent, keep track of the process in a thread to avoid a lot of complex multiplexing code.
crash_fd = crash_fds[0];
pid = new_pid;
heartbeats = 1;
send_faulty_modules_and_close(input_fds[1]);
close(crash_fds[1]);
close(input_fds[0]);
Global::active_processes++;
epoll_event event = {};
event.data.u32 = index;
event.events = EPOLLIN | EPOLLRDHUP;
if (epoll_ctl(Global::epoll_fd, EPOLL_CTL_ADD, crash_fd, &event) < 0)
{
LOGE("Failed to add file to epoll.\n");
return false;
}
return true;
}
else if (new_pid == 0)
{
// Close various FDs we won't use.
close(Global::signal_fd);
close(Global::epoll_fd);
close(Global::timer_fd);
close(crash_fds[0]);
close(input_fds[1]);
if (Global::control_fd >= 0)
close(Global::control_fd);
// We're the child process.
// Unblock the signal mask.
if (pthread_sigmask(SIG_SETMASK, &Global::old_mask, nullptr) != 0)
return EXIT_FAILURE;
// Make sure we don't hold unrelated epoll sensitive FDs open.
for (auto &sibling : siblings)
{
if (&sibling == this)
continue;
if (sibling.crash_fd >= 0)
{
::close(sibling.crash_fd);
sibling.crash_fd = -1;
}
if (sibling.timer_fd >= 0)
{
close(sibling.timer_fd);
sibling.timer_fd = -1;
}
if (sibling.watchdog_timer_fd >= 0)
{
close(sibling.watchdog_timer_fd);
sibling.watchdog_timer_fd = -1;
}
}
// Override stdin/stdout.
if (dup2(crash_fds[1], STDOUT_FILENO) < 0)
return EXIT_FAILURE;
if (dup2(input_fds[0], STDIN_FILENO) < 0)
return EXIT_FAILURE;
close(crash_fds[1]);
close(input_fds[0]);
// Redirect stderr to /dev/null if the child process is supposed to be quiet.
if (Global::quiet_slave)
{
int fd_dev_null = open("/dev/null", O_WRONLY);
if (fd_dev_null >= 0)
{
dup2(fd_dev_null, STDERR_FILENO);
close(fd_dev_null);
}
}
// Run the slave process.
auto copy_opts = Global::base_replayer_options;
copy_opts.start_graphics_index = start_graphics_index;
copy_opts.end_graphics_index = end_graphics_index;
copy_opts.start_compute_index = start_compute_index;
copy_opts.end_compute_index = end_compute_index;
copy_opts.start_raytracing_index = start_raytracing_index;
copy_opts.end_raytracing_index = end_raytracing_index;
copy_opts.control_block = Global::control_block;
if (!copy_opts.on_disk_pipeline_cache_path.empty() && index != 0)
{
copy_opts.on_disk_pipeline_cache_path += ".";
copy_opts.on_disk_pipeline_cache_path += std::to_string(index);
}
if (!copy_opts.on_disk_validation_cache_path.empty() && index != 0)
{
copy_opts.on_disk_validation_cache_path += ".";
copy_opts.on_disk_validation_cache_path += std::to_string(index);
}
if (!copy_opts.pipeline_stats_path.empty() && index != 0)
{
copy_opts.pipeline_stats_path += ".";
copy_opts.pipeline_stats_path += std::to_string(index);
}
if (!copy_opts.on_disk_module_identifier_path.empty() && index != 0)
{
copy_opts.on_disk_module_identifier_path += ".";
copy_opts.on_disk_module_identifier_path += std::to_string(index);
}
exit(run_slave_process(Global::device_options, copy_opts, Global::databases));
}
else
return false;
}
struct StallState
{
int32_t dirty_pages_mib = 0;
int64_t io_stalled_us = 0;
int64_t timestamp_ns = 0;
};
static bool get_dirty_page_info(StallState &state)
{
FILE *file = fopen("/proc/meminfo", "r");
if (!file)
{
if (Global::control_block)
Global::control_block->dirty_pages_mib.store(-1, std::memory_order_relaxed);
return false;
}
bool got_dirty = false;
char buffer[1024];
while (fgets(buffer, sizeof(buffer), file))
{
if (strncmp(buffer, "Dirty:", 6) == 0)
{
errno = 0;
auto dirty_pages_kb = strtoll(buffer + 6, nullptr, 10);
if (errno == 0)
{
state.dirty_pages_mib = dirty_pages_kb / 1024;
if (Global::control_block)
Global::control_block->dirty_pages_mib.store(state.dirty_pages_mib, std::memory_order_relaxed);
got_dirty = true;
}
}
}
if (!got_dirty && Global::control_block)
Global::control_block->dirty_pages_mib.store(-1, std::memory_order_relaxed);
fclose(file);
return got_dirty;
}
static bool get_stall_info(const char *path, int64_t &total_us)
{
FILE *file = fopen(path, "r");
if (!file)
return false;
bool ret = false;
char buffer[1024];
if (fgets(buffer, sizeof(buffer), file))
{
if (strncmp(buffer, "some ", 5) == 0)
{
const char *total = strstr(buffer, "total=");
if (total)
{
errno = 0;
total_us = strtoull(total + 6, nullptr, 10);
ret = errno == 0;
}
}
}
fclose(file);
return ret;
}
static bool poll_stall_information(StallState &state)
{
if (!get_dirty_page_info(state))
state.dirty_pages_mib = -1;
if (!get_stall_info("/proc/pressure/io", state.io_stalled_us))
state.io_stalled_us = -1;
timespec ts = {};
if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0)
return false;
state.timestamp_ns = ts.tv_sec * 1000000000ll + ts.tv_nsec;
return true;
}
static void manage_thrashing_behavior(std::vector<ProcessProgress> &child_processes,
StallState &old_state, const StallState &new_state)
{
// It is quite easy to overload the system with IO if we're not careful, so check for this.
float delta_us = 1e-3f * float(new_state.timestamp_ns - old_state.timestamp_ns);
float io_stall_us = float(new_state.io_stalled_us - old_state.io_stalled_us);
int32_t delta_dirty_pages_mib = 0;
if (new_state.dirty_pages_mib >= 0 && old_state.dirty_pages_mib >= 0)
delta_dirty_pages_mib = new_state.dirty_pages_mib - old_state.dirty_pages_mib;
float io_stall_ratio = -1.0f;
if (new_state.io_stalled_us >= 0 && old_state.io_stalled_us >= 0)
io_stall_ratio = io_stall_us / delta_us;
io_stall_ratio = std::min(1.0f, io_stall_ratio);
unsigned target_running_processes = Global::running_processes;
// Some heuristics here.
bool go_down = false;
bool go_up = false;
if (Global::target_running_processes_dirty_pages)
{
if (delta_dirty_pages_mib > 50)
{
// If we (or someone else) created more than 50 MiB of dirty data in this tick,
// we should lower number of processes.
go_down = true;
}
else if (delta_dirty_pages_mib < -10)
{
// Dirty pages is going down, can increase CPU load now.
go_up = true;
}
}
// IO stalls usually means someone is hammering IO.
// We don't want to contribute to that.
if (Global::target_running_processes_io_stall && io_stall_ratio >= 0.0f)
{
if (io_stall_ratio > 0.3f)
go_down = true;
else if (io_stall_ratio < 0.1f)
go_up = true;
}
// Ensure forward progress. Make at least one process active
// if we have had a period of complete sleep.
if (target_running_processes == 0)
go_up = true;
if (go_down && target_running_processes)
target_running_processes--;
else if (go_up)
target_running_processes++;
if (Global::control_block)
{
Global::control_block->io_stall_percentage.store(
io_stall_ratio < 0.0f ? -1 : int32_t(io_stall_ratio * 100.0f),
std::memory_order_relaxed);
}
old_state = new_state;
target_running_processes = std::min<unsigned>(target_running_processes, child_processes.size());
Global::target_running_processes = target_running_processes;
}
static void update_target_running_processes(std::vector<ProcessProgress> &child_processes)
{
if (Global::target_running_processes_static >= 0)
{
Global::target_running_processes = Global::target_running_processes_static;
Global::target_running_processes = std::min<unsigned>(Global::target_running_processes, child_processes.size());
}
Global::running_processes = 0;
for (auto &process : child_processes)
if (process.pid > 0 && !process.stopped)
Global::running_processes++;
if (Global::running_processes > Global::target_running_processes)
{
// Put processes to sleep.
unsigned to_stop = Global::running_processes - Global::target_running_processes;
size_t num_processes = child_processes.size();
for (size_t i = 0; i < num_processes && to_stop; i++)
{
if (child_processes[i].pid >= 0 && !child_processes[i].stopped && !child_processes[i].expect_kill)
{
if (::kill(child_processes[i].pid, SIGSTOP) == 0)
{
to_stop--;
child_processes[i].stopped = true;
Global::running_processes--;
}
}
}
}
else if (Global::running_processes < Global::target_running_processes)
{
// Wake up sleeping processes.
unsigned to_wake_up = Global::target_running_processes - Global::running_processes;
size_t num_processes = child_processes.size();
for (size_t i = 0; i < num_processes && to_wake_up; i++)
{
if (child_processes[i].pid > 0 && child_processes[i].stopped && !child_processes[i].expect_kill)
{
// Re-arm any timers before waking up to avoid potential scenario where
// we hit watchdog timer right after waking up child process.
child_processes[i].heartbeat();
if (::kill(child_processes[i].pid, SIGCONT) == 0)
{
to_wake_up--;
child_processes[i].stopped = false;
Global::running_processes++;
}
}
}
}
}
static void handle_control_command(const char *command)
{
if (strncmp(command, "RUNNING_TARGET", 14) == 0)
{
errno = 0;
Global::target_running_processes_static = strtol(command + 14, nullptr, 10);
if (errno)
Global::target_running_processes_static = -1;
}
else if (strcmp(command, "IO_STALL_AUTO_ADJUST ON") == 0)
Global::target_running_processes_io_stall = true;
else if (strcmp(command, "IO_STALL_AUTO_ADJUST OFF") == 0)
Global::target_running_processes_io_stall = false;
else if (strcmp(command, "DIRTY_PAGE_BLOAT_AUTO_ADJUST ON") == 0)
Global::target_running_processes_dirty_pages = true;
else if (strcmp(command, "DIRTY_PAGE_BLOAT_AUTO_ADJUST OFF") == 0)
Global::target_running_processes_dirty_pages = false;
else if (strcmp(command, "DETACH") == 0)
Global::control_fd_is_sentinel = false;
else
LOGE("Unrecognized control command: %s.\n", command);
}
static void shutdown_processes(std::vector<ProcessProgress> &child_processes)
{
for (auto &child_process : child_processes)
{
if (child_process.pid >= 0)
{
child_process.stopped = false;
child_process.expect_kill = true;
kill(child_process.pid, SIGKILL);
}
}
}
static void handle_control_commands(std::vector<ProcessProgress> &child_processes)
{
char buffer[4096];
ssize_t ret;
while ((ret = ::recv(Global::control_fd, buffer, sizeof(buffer) - 1, 0)) > 0)
{
buffer[ret] = '\0';
handle_control_command(buffer);
}
bool close_fd = false;
if (ret == 0)
{
if (Global::control_fd_is_sentinel)
{
LOGI("Parent process closed control FD with no notification, terminating early ...\n");
shutdown_processes(child_processes);
}
close_fd = true;
}
else if (errno != EAGAIN)
close_fd = true;
if (close_fd)
close_and_remove_epoll_entry(Global::control_fd);
}
static bool poll_children_process_states(vector<ProcessProgress> &child_processes)
{
// We'll only receive one SIGCHLD signal, even if multiple processes
// completed at the same time.
// Use the typical waitpid loop to reap every process.
pid_t pid = 0;
int wstatus = 0;
while ((pid = waitpid(-1, &wstatus, WNOHANG)) > 0)
{
auto itr = find_if(begin(child_processes), end(child_processes),
[&](const ProcessProgress &progress)
{
return progress.pid == pid;
});
// Child process can receive SIGCONT/SIGSTOP which is benign.
// This should normally only happen when the process is being debugged.
if (!WIFEXITED(wstatus) && !WIFSIGNALED(wstatus))
continue;
if (itr != end(child_processes))
{
if (itr->process_shutdown(wstatus) && !itr->start_child_process(child_processes))
{
LOGE("Failed to start child process.\n");
return false;
}
update_target_running_processes(child_processes);
}
else
LOGE("Got SIGCHLD from unknown process PID %d.\n", pid);
}
return true;
}
static int run_master_process(const VulkanDevice::Options &opts,
const ThreadedReplayer::Options &replayer_opts,
const vector<const char *> &databases,
const char *whitelist, uint32_t whitelist_mask,
bool quiet_slave, int shmem_fd, int control_fd)
{
Global::quiet_slave = quiet_slave;
Global::device_options = opts;
Global::base_replayer_options = replayer_opts;
Global::databases = databases;
unsigned processes = replayer_opts.num_threads;
// Split shader cache overhead across all processes.
Global::base_replayer_options.shader_cache_size_mb /= max(Global::base_replayer_options.num_threads, 1u);
Global::base_replayer_options.num_threads = 1;
// Try to map the shared control block.
if (shmem_fd >= 0)
{
LOGI("Attempting to map shmem block.\n");
struct stat s = {};
if (fstat(shmem_fd, &s) >= 0)
{
void *mapped = mmap(nullptr, s.st_size, PROT_READ | PROT_WRITE,
MAP_SHARED, shmem_fd, 0);
if (mapped != MAP_FAILED)
{
const auto is_pot = [](size_t size) { return (size & (size - 1)) == 0; };
// Detect some obvious shenanigans.
Global::control_block = static_cast<SharedControlBlock *>(mapped);
if (Global::control_block->version_cookie != ControlBlockMagic ||
Global::control_block->ring_buffer_offset < sizeof(SharedControlBlock) ||
Global::control_block->ring_buffer_size == 0 ||
!is_pot(Global::control_block->ring_buffer_size) ||
Global::control_block->ring_buffer_offset + Global::control_block->ring_buffer_size > size_t(s.st_size))
{
LOGE("Control block is corrupt.\n");
munmap(mapped, s.st_size);
Global::control_block = nullptr;