/
barrier-runtime-tsansafe.c
1282 lines (1159 loc) · 45.1 KB
/
barrier-runtime-tsansafe.c
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) 2023 by Samuel Michael Squire sam@samsquire.com
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
gcc barrier-runtime-server.c -o barrier-runtime-server -O3 -luring
./barrier-runtime-server
Samuel Michael Squire's multithreaded barrier runtime
from https://github.com/samsquire/assembly
This multithreaded barrier runtime is Zero Clause BSD licenced.
Includes Samuel Michael Squire's nonblocking barrier ported from
Java to C.
see https://github.com/samsquire/multiversion-concurrency-control
for Java version
NonBlockingBarrierSynchronizationPreempt.java
This program implements synchronization without mutexes on top of data races.
I rely on the fact that there is only one thread writing and
there can be any number of readers and stale reads
don't affect correctness.
Liburing HTTP server from https://github.com/shuveb/loti-examples/blob/master/webserver_liburing.c
MIT License
Copyright (c) 2020 Shuveb Hussain
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.
*/
#include <pthread.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <liburing.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/utsname.h>
#include <ctype.h>
#include <sys/eventfd.h>
#define TIMER 0
#define WORKER 1
#define IO 2
#define EXTERNAL 3
#if __SANITIZE_THREAD__
# define TSAN_SYNCED int sync
# define TSAN_ACQUIRE(s) __atomic_load_n(&(s).sync, __ATOMIC_ACQUIRE)
# define TSAN_RELEASE(s) __atomic_store_n(&(s).sync, 0, __ATOMIC_RELEASE)
# define TSAN_ACQUIRE_PTR(s) __atomic_load_n(&(s)->sync, __ATOMIC_ACQUIRE)
# define TSAN_RELEASE_PTR(s) __atomic_store_n(&(s)->sync, 0, __ATOMIC_RELEASE)
#else
# define TSAN_SYNCED
# define TSAN_ACQUIRE(s)
# define TSAN_RELEASE(s)
# define TSAN_ACQUIRE_PTR(s)
# define TSAN_RELEASE_PTR(s)
#endif
#define DURATION 30
#define TICK 1000000L
#define QUEUE_DEPTH 256
#define READ_SZ 8192
#define EVENT_TYPE_ACCEPT 0
#define EVENT_TYPE_READ 1
#define EVENT_TYPE_WRITE 2
#define SERVER_STRING "Server: zerohttpd/0.1\r\n"
const char *unimplemented_content = \
"HTTP/1.0 400 Bad Request\r\n"
"Content-type: text/html\r\n"
"\r\n"
"<html>"
"<head>"
"<title>ZeroHTTPd: Unimplemented</title>"
"</head>"
"<body>"
"<h1>Bad Request (Unimplemented)</h1>"
"<p>Your client sent a request ZeroHTTPd did not understand and it is probably not your fault.</p>"
"</body>"
"</html>";
const char *http_404_content = \
"HTTP/1.0 404 Not Found\r\n"
"Content-type: text/html\r\n"
"\r\n"
"<html>"
"<head>"
"<title>ZeroHTTPd: Not Found</title>"
"</head>"
"<body>"
"<h1>Not Found (404)</h1>"
"<p>Your client is asking for an object that was not found on this server.</p>"
"</body>"
"</html>";
struct Buffers {
int count;
struct Buffer *buffer;
};
struct Buffer {
void * data;
int available;
TSAN_SYNCED;
};
struct Request {
int event_type;
int iovec_count;
int client_socket;
struct iovec iov[];
};
struct Mailbox {
void *lower;
void *higher;
long sent;
long received;
TSAN_SYNCED;
};
struct Data {
struct Message **messages;
long messages_count __attribute__((aligned (128)));
long messages_limit;
TSAN_SYNCED;
};
struct Message {
char * message;
long thread_index;
long task_index;
};
struct BarrierTask {
int task_index;
int rerunnable;
int arrived __attribute__((aligned (128)));
int prearrive __attribute__((aligned (128)));
long n;
long v;
int (*run)(struct BarrierTask*);
int (*protected)(struct BarrierTask*);
struct KernelThread *thread;
int thread_index;
int thread_count;
int available __attribute__((aligned (128)));
int task_count;
_Atomic int scheduled __attribute__((aligned (128)));
struct Snapshot *snapshots;
long snapshot_count;
long current_snapshot;
long ingest_count;
struct Mailbox *mailboxes;
long sends;
int sending;
int worker_count;
struct Message *message;
int next_thread;
TSAN_SYNCED; // to be visible to Tsan
};
struct TaskSnapshot {
struct timespec task_start;
struct timespec task_end;
int task;
};
struct KernelThread {
int thread_index;
int type;
int preempt_interval;
struct KernelThread *threads;
int thread_count;
int total_thread_count;
struct BarrierTask *tasks;
int task_count;
int running;
struct ProtectedState *protected_state;
struct Buffers *buffers;
struct io_uring *ring;
int _eventfd;
struct timespec *start;
struct timespec *end;
long iteration_count;
long timestamp_count;
long timestamp_limit;
struct TaskSnapshot *task_snapshot;
long task_timestamp_count;
long task_timestamp_limit;
long cycles;
TSAN_SYNCED;
};
struct ProtectedState {
long protected;
long balance;
int modcount;
TSAN_SYNCED;
};
struct Snapshot {
struct timespec start;
struct timespec end;
};
void fatal_error(const char *syscall) {
perror(syscall);
exit(1);
}
void strtolower(char *str) {
for (; *str; ++str)
*str = (char)tolower(*str);
}
void *zh_malloc(size_t size) {
void *buf = malloc(size);
if (!buf) {
fprintf(stderr, "Fatal error: unable to allocate memory.\n");
exit(1);
}
return buf;
}
const char *get_filename_ext(const char *filename) {
const char *dot = strrchr(filename, '.');
if (!dot || dot == filename)
return "";
return dot + 1;
}
void send_headers(const char *path, off_t len, struct iovec *iov) {
char small_case_path[1024];
char send_buffer[1024];
strcpy(small_case_path, path);
strtolower(small_case_path);
char *str = "HTTP/1.0 200 OK\r\n";
unsigned long slen = strlen(str);
iov[0].iov_base = zh_malloc(slen);
iov[0].iov_len = slen;
memcpy(iov[0].iov_base, str, slen);
slen = strlen(SERVER_STRING);
iov[1].iov_base = zh_malloc(slen);
iov[1].iov_len = slen;
memcpy(iov[1].iov_base, SERVER_STRING, slen);
/*
* Check the file extension for certain common types of files
* on web pages and send the appropriate content-type header.
* Since extensions can be mixed case like JPG, jpg or Jpg,
* we turn the extension into lower case before checking.
* */
const char *file_ext = get_filename_ext(small_case_path);
if (strcmp("jpg", file_ext) == 0)
strcpy(send_buffer, "Content-Type: image/jpeg\r\n");
if (strcmp("jpeg", file_ext) == 0)
strcpy(send_buffer, "Content-Type: image/jpeg\r\n");
if (strcmp("png", file_ext) == 0)
strcpy(send_buffer, "Content-Type: image/png\r\n");
if (strcmp("gif", file_ext) == 0)
strcpy(send_buffer, "Content-Type: image/gif\r\n");
if (strcmp("htm", file_ext) == 0)
strcpy(send_buffer, "Content-Type: text/html\r\n");
if (strcmp("html", file_ext) == 0)
strcpy(send_buffer, "Content-Type: text/html\r\n");
if (strcmp("js", file_ext) == 0)
strcpy(send_buffer, "Content-Type: application/javascript\r\n");
if (strcmp("css", file_ext) == 0)
strcpy(send_buffer, "Content-Type: text/css\r\n");
if (strcmp("txt", file_ext) == 0)
strcpy(send_buffer, "Content-Type: text/plain\r\n");
slen = strlen(send_buffer);
iov[2].iov_base = zh_malloc(slen);
iov[2].iov_len = slen;
memcpy(iov[2].iov_base, send_buffer, slen);
/* Send the content-length header, which is the file size in this case. */
sprintf(send_buffer, "content-length: %ld\r\n", len);
slen = strlen(send_buffer);
iov[3].iov_base = zh_malloc(slen);
iov[3].iov_len = slen;
memcpy(iov[3].iov_base, send_buffer, slen);
/*
* When the browser sees a '\r\n' sequence in a line on its own,
* it understands there are no more headers. Content may follow.
* */
strcpy(send_buffer, "\r\n");
slen = strlen(send_buffer);
iov[4].iov_base = zh_malloc(slen);
iov[4].iov_len = slen;
memcpy(iov[4].iov_base, send_buffer, slen);
}
void copy_file_contents(char *file_path, off_t file_size, struct iovec *iov) {
int fd;
char *buf = zh_malloc(file_size);
fd = open(file_path, O_RDONLY);
if (fd < 0)
fatal_error("read");
/* We should really check for short reads here */
int ret = read(fd, buf, file_size);
if (ret < file_size) {
fprintf(stderr, "Encountered a short read.\n");
}
close(fd);
iov->iov_base = buf;
iov->iov_len = file_size;
}
int add_write_request(struct Request *req, struct io_uring *ring) {
struct io_uring_sqe *sqe = io_uring_get_sqe(ring);
req->event_type = EVENT_TYPE_WRITE;
io_uring_prep_writev(sqe, req->client_socket, req->iov, req->iovec_count, 0);
io_uring_sqe_set_data(sqe, req);
io_uring_submit(ring);
return 0;
}
int add_read_request(int client_socket, struct io_uring *ring) {
struct io_uring_sqe *sqe = io_uring_get_sqe(ring);
struct Request *req = malloc(sizeof(*req) + sizeof(struct iovec));
req->iov[0].iov_base = malloc(READ_SZ);
req->iov[0].iov_len = READ_SZ;
req->event_type = EVENT_TYPE_READ;
req->client_socket = client_socket;
memset(req->iov[0].iov_base, 0, READ_SZ);
/* Linux kernel 5.5 has support for readv, but not for recv() or read() */
io_uring_prep_readv(sqe, client_socket, &req->iov[0], 1, 0);
io_uring_sqe_set_data(sqe, req);
io_uring_submit(ring);
return 0;
}
void _send_static_string_content(const char *str, int client_socket, struct io_uring *ring) {
struct Request *req = zh_malloc(sizeof(*req) + sizeof(struct iovec));
unsigned long slen = strlen(str);
req->iovec_count = 1;
req->client_socket = client_socket;
req->iov[0].iov_base = zh_malloc(slen);
req->iov[0].iov_len = slen;
memcpy(req->iov[0].iov_base, str, slen);
add_write_request(req, ring);
}
void handle_unimplemented_method(int client_socket, struct io_uring *ring) {
_send_static_string_content(unimplemented_content, client_socket, ring);
}
void handle_http_404(int client_socket, struct io_uring *ring) {
_send_static_string_content(http_404_content, client_socket, ring);
}
void handle_get_method(char *path, int client_socket, struct io_uring *ring) {
char final_path[1024];
/*
If a path ends in a trailing slash, the client probably wants the index
file inside of that directory.
*/
if (path[strlen(path) - 1] == '/') {
strcpy(final_path, "public");
strcat(final_path, path);
strcat(final_path, "index.html");
}
else {
strcpy(final_path, "public");
strcat(final_path, path);
}
/* The stat() system call will give you information about the file
* like type (regular file, directory, etc), size, etc. */
struct stat path_stat;
if (stat(final_path, &path_stat) == -1) {
printf("404 Not Found: %s (%s)\n", final_path, path);
handle_http_404(client_socket, ring);
}
else {
/* Check if this is a normal/regular file and not a directory or something else */
if (S_ISREG(path_stat.st_mode)) {
struct Request *req = zh_malloc(sizeof(*req) + (sizeof(struct iovec) * 6));
req->iovec_count = 6;
req->client_socket = client_socket;
send_headers(final_path, path_stat.st_size, req->iov);
copy_file_contents(final_path, path_stat.st_size, &req->iov[5]);
printf("200 %s %ld bytes\n", final_path, path_stat.st_size);
add_write_request(req, ring);
}
else {
handle_http_404(client_socket, ring);
printf("404 Not Found: %s\n", final_path);
}
}
}
void handle_http_method(char *method_buffer, int client_socket, struct io_uring *ring) {
char *method, *path, *saveptr;
method = strtok_r(method_buffer, " ", &saveptr);
strtolower(method);
path = strtok_r(NULL, " ", &saveptr);
if (strcmp(method, "get") == 0) {
handle_get_method(path, client_socket, ring);
}
else {
handle_unimplemented_method(client_socket, ring);
}
}
int get_line(const char *src, char *dest, int dest_sz) {
for (int i = 0; i < dest_sz; i++) {
dest[i] = src[i];
if (src[i] == '\r' && src[i+1] == '\n') {
dest[i] = '\0';
return 0;
}
}
return 1;
}
int handle_client_request(struct Request *req, struct io_uring *ring) {
char http_request[1024];
/* Get the first line, which will be the request */
if(get_line(req->iov[0].iov_base, http_request, sizeof(http_request))) {
fprintf(stderr, "Malformed request\n");
exit(1);
}
handle_http_method(http_request, req->client_socket, ring);
return 0;
}
int add_accept_request(int socket, struct sockaddr_in *client_addr,
socklen_t *client_addr_len, struct io_uring *ring) {
struct io_uring_sqe *sqe = io_uring_get_sqe(ring);
io_uring_prep_accept(sqe, socket, (struct sockaddr *) client_addr,
client_addr_len, 0);
struct Request *req = malloc(sizeof(*req));
req->event_type = EVENT_TYPE_ACCEPT;
io_uring_sqe_set_data(sqe, req);
io_uring_submit(ring);
}
void* io_thread(void *arg) {
int port = 6363;
struct KernelThread *data = arg;
struct io_uring ring = *data->ring;
io_uring_queue_init(QUEUE_DEPTH, &ring, 0);
io_uring_register_eventfd(data->ring, 0);
int sock;
struct sockaddr_in srv_addr;
sock = socket(PF_INET, SOCK_STREAM, 0);
if (sock == -1)
fatal_error("socket()");
int enable = 1;
if (setsockopt(sock,
SOL_SOCKET, SO_REUSEADDR,
&enable, sizeof(int)) < 0)
fatal_error("setsockopt(SO_REUSEADDR)");
memset(&srv_addr, 0, sizeof(srv_addr));
srv_addr.sin_family = AF_INET;
srv_addr.sin_port = htons(port);
srv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sock,
(const struct sockaddr *)&srv_addr,
sizeof(srv_addr)) < 0)
fatal_error("bind()");
if (listen(sock, 10) < 0) {
fatal_error("listen()");
}
printf("Listening on port %d\n", port);
struct io_uring_cqe *cqe;
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
add_accept_request(sock, &client_addr, &client_addr_len, &ring);
eventfd_t dummy;
struct iovec *iov = calloc(1, sizeof(struct iovec));
iov->iov_base = zh_malloc(10);
iov->iov_len = 10;
struct io_uring_sqe *sqe= io_uring_get_sqe(&ring);
io_uring_prep_readv(sqe, data->_eventfd, iov, 1, 0);
io_uring_sqe_set_data(sqe, &data->_eventfd);
io_uring_submit(&ring);
while (data->running == 1) {
printf("Looping server...\n");
int ret = io_uring_wait_cqe(&ring, &cqe);
if (cqe->user_data == 1) {
io_uring_cqe_seen(&ring, cqe);
printf("Received stop event\n");
break;
}
printf("Received wait finished\n");
struct Request *req = (struct Request *) cqe->user_data;
if (ret < 0)
fatal_error("io_uring_wait_cqe");
if (cqe->res < 0) {
fprintf(stderr, "Async request failed: %s for event: %d\n",
strerror(-cqe->res), req->event_type);
exit(1);
}
switch (req->event_type) {
case EVENT_TYPE_ACCEPT:
add_accept_request(sock, &client_addr, &client_addr_len, &ring);
add_read_request(cqe->res, &ring);
free(req);
break;
case EVENT_TYPE_READ:
if (!cqe->res) {
fprintf(stderr, "Empty request!\n");
break;
}
handle_client_request(req, &ring);
free(req->iov[0].iov_base);
free(req);
break;
case EVENT_TYPE_WRITE:
for (int i = 0; i < req->iovec_count; i++) {
free(req->iov[i].iov_base);
}
close(req->client_socket);
free(req);
break;
}
/* Mark this request as processed */
io_uring_cqe_seen(&ring, cqe);
struct io_uring_sqe *sqe= io_uring_get_sqe(&ring);
io_uring_prep_readv(sqe, data->_eventfd, iov, 1, 0);
io_uring_sqe_set_data(sqe, &data->_eventfd);
io_uring_submit(&ring);
}
printf("Finished io thread\n");
return 0;
}
void* barriered_thread(void *arg) {
struct KernelThread *data = arg;
// printf("In barrier task %d\n", data->thread_index);
int t = 0;
int waiting = 0;
while (data->running == 1) {
if (t >= data->task_count) {
t = 0;
data->cycles++;
}
// printf("%d reporting %d %d\n", data->thread_index, t, data->task_count);
for (; t < data->task_count; t++) {
// printf("%d %d\n", data->thread_index, t);
if (data->tasks[t].available == 1) {
int previous = t;
if (t > 0) {
previous = t - 1;
} else {
previous = data->task_count - 1;
}
int arrived = 0;
int prearrive = 0;
for (int thread = 0 ; thread < data->thread_count; thread++) {
TSAN_ACQUIRE(data->threads[thread].tasks[previous]);
TSAN_ACQUIRE(data->tasks[t]);
// printf("thread %d does %d %d %d == %d\n", data->thread_index, t, previous, data->threads[thread].tasks[previous].arrived, data->tasks[t].arrived);
if (data->threads[thread].tasks[previous].arrived == data->tasks[t].arrived) {
arrived++;
}
if (data->threads[thread].tasks[previous].prearrive == data->tasks[t].prearrive) {
prearrive++;
}
TSAN_RELEASE(data->threads[thread].tasks[previous]);
TSAN_RELEASE(data->tasks[t]);
}
if (prearrive == 0 || prearrive == data->thread_count) {
if (waiting == 1) {
clock_gettime(CLOCK_MONOTONIC_RAW, &data->task_snapshot[data->task_timestamp_count].task_end);
data->task_timestamp_count = (data->task_timestamp_count + 1) % data->task_timestamp_limit;
waiting = 3;
}
}
if (arrived == 0 || arrived == data->thread_count) {
TSAN_ACQUIRE(data->tasks[t]);
data->tasks[t].prearrive++;
TSAN_RELEASE(data->tasks[t]);
// we can run this task
if (t == 0 && data->timestamp_count < data->timestamp_limit) {
clock_gettime(CLOCK_MONOTONIC_RAW, &data->start[data->timestamp_count]);
}
data->tasks[t].available = 0;
// printf("In thread %d %d\n", data->thread_index, t);
data->tasks[t].run(&data->threads[data->thread_index].tasks[t]);
//if (t == data->thread_index) {
// data->tasks[t].protected(&data->threads[data->thread_index].tasks[t]);
//}
TSAN_ACQUIRE(data->tasks[t]);
data->tasks[t].arrived++;
TSAN_RELEASE(data->tasks[t]);
data->iteration_count++;
if (t == data->task_count - 1 && data->timestamp_count < data->timestamp_limit) {
clock_gettime(CLOCK_MONOTONIC_RAW, &data->end[data->timestamp_count]);
data->timestamp_count = data->timestamp_count + 1;
}
asm volatile ("mfence" ::: "memory");
if (waiting == 0) {
data->task_snapshot[data->task_timestamp_count].task = t;
clock_gettime(CLOCK_MONOTONIC_RAW, &data->task_snapshot[data->task_timestamp_count].task_start);
waiting = 1;
}
if (waiting == 3) {
waiting = 0;
}
// break;
} else {
// printf("%d %d %d\n", data->thread_index, t, arrived);
break;
}
} else {
// printf("%d not available\n", t);
}
}
}
return 0;
}
void* timer_thread(void *arg) {
long tick = TICK;
long tickseconds = 0;
// long tick = 0L;
long times = ((1000000000L*DURATION)/tick);
// long times = tickseconds * 10;
struct KernelThread *data = arg;
printf("In timer task %d\n", data->thread_index);
struct timespec rem;
struct timespec rem2;
struct timespec preempt = {
tickseconds,
tick };
struct timespec req = {
DURATION,
0 };
int y = 0;
int n = 0;
printf("Will sleep %ld times\n", times);
while (data->running && n < times) {
n++;
nanosleep(&preempt , &rem2);
// preempt tasks
for (int x = 0 ; x < data->thread_count ; x++) {
int next = (y + 1) % data->threads[x].task_count;
data->threads[x].tasks[next].scheduled = 1;
data->threads[x].tasks[y].scheduled = 0;
}
asm volatile ("mfence" ::: "memory");
y++;
if (y >= data->threads[0].task_count) {
y = 0;
}
}
printf("Finished, waiting for drain\n");
// nanosleep(&req , &rem);
for (int x = 0 ; x < data->total_thread_count ; x++) {
for (int y = 0 ; y < data->task_count ; y++) {
data->threads[x].tasks[y].sending = 0;
}
}
asm volatile ("mfence" ::: "memory");
int drained = 0;
struct timespec drainrem;
struct timespec drain = {
1,
0 };
while (drained == 0) {
// preempt tasks
for (int x = 0 ; x < data->thread_count ; x++) {
int next = (y + 1) % data->threads[x].task_count;
data->threads[x].tasks[next].scheduled = 1;
data->threads[x].tasks[y].scheduled = 0;
}
asm volatile ("mfence" ::: "memory");
y++;
if (y >= data->threads[0].task_count) {
y = 0;
}
int all_empty = 1;
for (int x = 0 ; x < data->thread_count ; x++) {
for (int y = 0 ; y < data->thread_count ; y++) {
for (int k = 0 ; k < data->thread_count; k++) {
if (((struct Data*)data->threads[x].tasks[y].mailboxes[k].lower)->messages_count > 0 || ((struct Data*)data->threads[x].tasks[y].mailboxes[k].higher)->messages_count > 0) {
all_empty = 0;
printf("%d %ld %ld left\n", k, ((struct Data*)data->threads[x].tasks[y].mailboxes[k].lower)->messages_count, ((struct Data*)data->threads[x].tasks[y].mailboxes[k].higher)->messages_count);
// printf("Someone unfinished\n");
break;
}
}
}
}
if (all_empty == 1) {
drained = 1;
} else {
nanosleep(&drain , &drainrem);
}
}
printf("Finished\n");
while (data->running) {
// nanosleep(&req , &rem);
for (int x = 0 ; x < data->total_thread_count ; x++) {
data->threads[x].running = 0;
if (data->threads[x].type == IO) {
printf("Stopping io_uring\n");
eventfd_write(data->threads[x]._eventfd, 1);
}
}
// forcefully deschedule all tasks
for (int x = 0 ; x < data->thread_count ; x++) {
for (int y = 0 ; y < data->task_count ; y++) {
data->threads[x].tasks[y].scheduled = 0;
}
}
asm volatile ("mfence" ::: "memory");
printf("Slept \n");
data->running = 0;
}
printf("Timer thread stopping\n");
return 0;
}
void * external_thread(void *arg) {
struct KernelThread *data = arg;
long micros = 1000000L;
struct timespec req = {
0,
micros };
struct timespec rem;
while (data->running == 1) {
nanosleep(&req , &rem);
// printf("External thread wakeup...\n");
for (int x = 0; x < data->buffers->count; x++) {
//printf("Writing to buffer\n");
TSAN_ACQUIRE(data->buffers->buffer[x]);
if (data->buffers->buffer[x].available == 0) {
data->buffers->buffer[x].data = "Hello world";
data->buffers->buffer[x].available = 1;
}
TSAN_RELEASE(data->buffers->buffer[x]);
}
asm volatile ("mfence" ::: "memory");
}
return 0;
}
int do_protected_write(struct BarrierTask *data) {
struct ProtectedState *protected = data->thread->protected_state;
data->v++; // thread local
// printf("Protected %d %d\n", data->task_index, data->thread_index);
TSAN_RELEASE_PTR(protected);
protected->protected++; // shared between all threads
if (protected->balance > 0) {
protected->balance -= 500; // shared between all threads
} else {
protected->balance += 500; // shared between all threads
}
TSAN_ACQUIRE_PTR(protected);
return 0;
}
int receive(struct BarrierTask *data) {
// printf("Receiving\n");
for (int n = 0 ; n < data->thread_count; n++) {
int prev = n - 1;
if (n == 0) {
prev = data->thread_count - 1;
}
// if (n == data->thread_index) { continue; }
TSAN_ACQUIRE(data->mailboxes[n]);
TSAN_ACQUIRE_PTR((struct Data*)data->mailboxes[n].lower);
struct Data *me = data->mailboxes[n].lower;
for (int x = 0 ; x < me->messages_count ; x++) {
data->sends++;
data->n++;
data->mailboxes[n].received++;
// printf("on %d from %d task %d received: %s\n", data->thread_index, n, data->task_index, me->messages[x]->message);
// __atomic_store_n(&data->sync, 0, __ATOMIC_RELEASE);
if (me->messages[x]->task_index == data->task_index && me->messages[x]->thread_index == data->thread_index) {
printf("Received message from self %b %b\n", me->messages[x]->task_index == data->task_index, me->messages[x]->thread_index == data->thread_index);
exit(1);
}
}
me->messages_count = 0;
TSAN_RELEASE(data->mailboxes[n]);
TSAN_ACQUIRE_PTR((struct Data*)data->mailboxes[n].lower);
}
}
int barriered_work(struct BarrierTask *data) {
// printf("In barrier work task %d %d\n", data->thread_index, data->task_index);
// printf("%d Arrived at task %d\n", data->thread_index, data->task_index);
long *n = &data->n;
// we are synchronized
if (data->thread_index == data->task_index) {
receive(data);
void * tmp;
// swap this all thread's write buffer with the next task
int t = data->task_index;
for (int y = 0; y < data->thread_count ; y++) {
for (int b = 0; b < data->thread_count ; b++) {
int next_task = abs((t + 1) % (data->thread_count));
TSAN_ACQUIRE(data->thread->threads[y].tasks[t].mailboxes[b]);
TSAN_ACQUIRE(data->thread->threads[b].tasks[next_task].mailboxes[y]);
tmp = data->thread->threads[y].tasks[t].mailboxes[b].higher;
// data->thread->threads[y].tasks[t].mailboxes[b].higher = data->thread->threads[b].tasks[next_task].mailboxes[y].lower;
data->thread->threads[b].tasks[next_task].mailboxes[y].lower = tmp;
TSAN_RELEASE(data->thread->threads[y].tasks[t].mailboxes[b]);
TSAN_RELEASE(data->thread->threads[b].tasks[next_task].mailboxes[y]);
}
}
asm volatile ("mfence" ::: "memory");
// printf("move my %d lower to next %d lower\n",data->task_index, next_task);
clock_gettime(CLOCK_REALTIME, &data->snapshots[data->current_snapshot].start);
TSAN_ACQUIRE_PTR(data->thread->protected_state);
int modcount = data->thread->protected_state->modcount + 1;
data->thread->protected_state->modcount = modcount;
while (data->scheduled == 1) {
data->n++;
data->protected(&data->thread->threads[data->thread_index].tasks[data->task_index]);
asm volatile ("sfence" ::: "memory");
}
if (modcount != data->thread->protected_state->modcount) {
printf("Race condition!\n");
}
TSAN_RELEASE_PTR(data->thread->protected_state);
clock_gettime(CLOCK_REALTIME, &data->snapshots[data->current_snapshot].end);
data->current_snapshot = ((data->current_snapshot + 1) % data->snapshot_count);
} else {
receive(data);
while (data->scheduled == 1) {
data->n++;
asm volatile ("sfence" ::: "memory");
}
if (data->sending == 1) {
for (int n = 0 ; n < data->thread_count; n++) {
if (n == data->thread_index) { continue; }
struct Data *them = data->mailboxes[n].higher;
TSAN_ACQUIRE_PTR(them);
// printf("Sending to thread %d\n", n);
int min = them->messages_limit;
//if (them->messages_limit < min) {
// min = them->messages_limit;
//}
for (; them->messages_count < min;) {
data->n++;
data->mailboxes[n].sent++;
them->messages[them->messages_count++] = data->message;
}
TSAN_RELEASE_PTR(them);
}
}
}
asm volatile ("mfence" ::: "memory");
return 0;
}
int barriered_work_ingest(struct BarrierTask *data) {
// printf("Ingest task\n");
for (int x = 0 ; x < data->thread->buffers->count ; x++) {
// printf("Checking buffer %d\n", data->thread->buffers->buffer[x].available);
TSAN_ACQUIRE(data->thread->buffers->buffer[x]);
if (data->thread->buffers->buffer[x].available == 1) {
data->ingest_count++;
// printf("Ingested %s\n", (char*)data->thread->buffers->buffer[x].data);
data->thread->buffers->buffer[x].available = 0;
} else {
}
TSAN_RELEASE(data->thread->buffers->buffer[x]);
}
asm volatile ("mfence" ::: "memory");
barriered_work(data);
return 0;
}
int barriered_nulltask(struct BarrierTask *data) {
// printf("In barrier null task %d %d\n", data->thread_index, data->task_index);
return 0;
}
int barriered_steal(struct BarrierTask *data) {
// printf("In barrier steal task %d %d\n", data->thread_index, data->task_index);
return 0;
}
int barriered_reset(struct BarrierTask *data) {
// printf("In barrier reset task %d %d\n", data->thread_index, data->task_index);
for (int x = 0 ; x < data->task_count ; x++) {
// printf("Resetting %d %d\n", n, x);
TSAN_ACQUIRE(data->thread->threads[data->thread_index].tasks[x]);
data->thread->threads[data->thread_index].tasks[x].arrived++;
data->thread->threads[data->thread_index].tasks[x].prearrive++;
// data->thread->tasks[x].arrived++;
data->thread->tasks[x].available = 1;
TSAN_RELEASE(data->thread->threads[data->thread_index].tasks[x]);
}
asm volatile ("mfence" ::: "memory");
return 0;
}
int after(struct timespec left, struct timespec right) {
return left.tv_sec > right.tv_sec &&
left.tv_nsec > right.tv_nsec;
}
int within(struct timespec a, struct timespec b, struct timespec c, struct timespec d) {
if (a.tv_sec <= b.tv_sec && a.tv_nsec <= b.tv_nsec &&
c.tv_sec <= d.tv_sec && c.tv_nsec <= d.tv_nsec && d.tv_sec >= c.tv_sec && d.tv_nsec >= c.tv_nsec) {
return 1;
}
return 0;
}
int overlap(struct Snapshot left, struct Snapshot right) {
if (after(left.start, right.start) && after(right.end, left.end)) {
return 1;
}
if (after(right.start, left.start) && after(left.end, right.end)) {
return 1;
}
if (within(left.start, right.start, right.end, left.end) == 1) {
return 1;
}
if (within(right.start, left.start, left.end, right.end) == 1) {
return 1;
}
return 0;
}
int verify(struct KernelThread *thread_data, int thread_count) {
for (int x = 0 ; x < thread_count; x++) {
for (int z = 0 ; z < thread_count; z++) {
if (z != x) {
for (int y = 0 ; y < thread_data[x].task_count ; y++) {
printf("Verifying thread %d\n", x);
for (int k = 0 ; k < thread_data[z].task_count; k++) {
printf("%ld %ld\n", thread_data[z].tasks[k].current_snapshot, thread_data[x].tasks[y].current_snapshot);
for (int n = 0 ; n < thread_data[x].tasks[y].current_snapshot ; n++) {
for (int m = 0 ; m < thread_data[z].tasks[k].current_snapshot ; m++) {