-
Notifications
You must be signed in to change notification settings - Fork 51
/
fio.c
11987 lines (10455 loc) · 363 KB
/
fio.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: Boaz Segev, 2018-2019
License: MIT
Feel free to copy, use and enjoy according to the license provided.
***************************************************************************** */
#ifdef __MINGW32__
/** iodine/ruby specific, don use: #define FD_SETSIZE 1024 */
#define FIO_FORCE_MALLOC 1
#define FIO_DISABLE_HOT_RESTART 1
#endif
#include <fio.h>
#define FIO_INCLUDE_STR
#include <fio.h>
#define FIO_FORCE_MALLOC_TMP 1
#define FIO_INCLUDE_LINKED_LIST
#include <fio.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <pthread.h>
#ifndef __MINGW32__
#include <sys/mman.h>
#endif
#include <unistd.h>
#ifndef __MINGW32__
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <poll.h>
#include <sys/ioctl.h>
#include <sys/resource.h>
#include <sys/socket.h>
#endif
#include <sys/stat.h>
#include <sys/types.h>
#ifndef __MINGW32__
#include <sys/un.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#endif
#ifdef __MINGW32__
#include <windef.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#endif
#if HAVE_OPENSSL
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#endif
#if HAVE_OPENSSL
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#endif
/* force poll for testing? */
#ifndef FIO_ENGINE_POLL
#define FIO_ENGINE_POLL 0
#endif
#if !FIO_ENGINE_POLL && !FIO_ENGINE_EPOLL && !FIO_ENGINE_KQUEUE && !FIO_ENGINE_WSAPOLL
#if defined(__linux__)
#define FIO_ENGINE_EPOLL 1
#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
defined(__OpenBSD__) || defined(__bsdi__) || defined(__DragonFly__)
#define FIO_ENGINE_KQUEUE 1
#elif defined(__MINGW32__)
#define FIO_ENGINE_WSAPOLL 1
#else
#define FIO_ENGINE_POLL 1
#endif
#endif
/* for kqueue and epoll only */
#ifndef FIO_POLL_MAX_EVENTS
#define FIO_POLL_MAX_EVENTS 64
#endif
#ifndef FIO_POLL_TICK
#define FIO_POLL_TICK 1000
#endif
#ifndef FIO_USE_URGENT_QUEUE
#ifndef __MINGW32__
#define FIO_USE_URGENT_QUEUE 1
#endif
#endif
#ifndef DEBUG_SPINLOCK
#define DEBUG_SPINLOCK 0
#endif
/* Slowloris mitigation (must be less than 1<<16) */
#ifndef FIO_SLOWLORIS_LIMIT
#define FIO_SLOWLORIS_LIMIT (1 << 10)
#endif
#ifndef FIO_TLS_WEAK
#define FIO_TLS_WEAK __attribute__((weak))
#endif
/* Mitigates MAP_ANONYMOUS not being defined on older versions of MacOS */
#if !defined(MAP_ANONYMOUS)
#if defined(MAP_ANON)
#define MAP_ANONYMOUS MAP_ANON
#else
#define MAP_ANONYMOUS 0
#endif
#endif
/* *****************************************************************************
Windows support functions
***************************************************************************** */
#ifdef __MINGW32__
#define WIFEXITED(s) (!((s)&0xFF))
#define WEXITSTATUS(s) (((s)>>8)&0xFF)
FARPROC accept_ptr;
FARPROC bind_ptr;
FARPROC closesocket_ptr;
FARPROC connect_ptr;
FARPROC getsockopt_ptr;
FARPROC ioctlsocket_ptr;
FARPROC listen_ptr;
FARPROC recv_ptr;
FARPROC send_ptr;
FARPROC setsockopt_ptr;
FARPROC socket_ptr;
int fork() {
fprintf(stderr, "fork() is not supported on Windows.\n");
errno = ENOSYS;
return -1;
}
int ioctl (int fd, u_long request, int* argp) {
int error;
u_long flags;
flags = *argp;
error = ioctlsocket_ptr(fd, request, &flags);
if (error > 0) { return -1; }
else { return 0; }
}
int kill(int pid, int sig) {
/* Credit to Jan Biedermann (GitHub: @janbiedermann) */
HANDLE handle;
DWORD status;
if (sig < 0 || sig >= NSIG) {
errno = EINVAL;
return -1;
}
#ifdef SIGCONT
if (sig == SIGCONT) {
errno = ENOSYS;
return -1;
}
#endif
if (pid == -1)
pid = 0;
if (!pid)
handle = GetCurrentProcess();
else
handle =
OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION, FALSE, pid);
if (!handle)
goto something_went_wrong;
switch (sig) {
case SIGKILL:
case SIGTERM:
case SIGINT: /* terminate */
if (!TerminateProcess(handle, 1))
goto something_went_wrong;
break;
case 0: /* check status */
if (!GetExitCodeProcess(handle, &status))
goto something_went_wrong;
if (status != STILL_ACTIVE) {
errno = ESRCH;
goto cleanup_after_error;
}
break;
default: /* not supported? */
errno = ENOSYS;
goto cleanup_after_error;
}
if (pid) {
CloseHandle(handle);
}
return 0;
something_went_wrong:
switch (GetLastError()) {
case ERROR_INVALID_PARAMETER:
errno = ESRCH;
break;
case ERROR_ACCESS_DENIED:
errno = EPERM;
if (handle && GetExitCodeProcess(handle, &status) && status != STILL_ACTIVE)
errno = ESRCH;
break;
default:
errno = GetLastError();
}
cleanup_after_error:
if (handle && pid)
CloseHandle(handle);
return -1;
}
ssize_t pread(int fd, void *buf, size_t count, off_t offset) {
/* Credit to Jan Biedermann (GitHub: @janbiedermann) */
ssize_t bytes_read = 0;
HANDLE handle = (HANDLE)_get_osfhandle(fd);
if (handle == INVALID_HANDLE_VALUE)
goto bad_file;
OVERLAPPED overlapped = {0};
if (offset > 0)
overlapped.Offset = offset;
if (ReadFile(handle, buf, count, (u_long *)&bytes_read, &overlapped))
return bytes_read;
if (GetLastError() == ERROR_HANDLE_EOF)
return bytes_read;
errno = EIO;
return -1;
bad_file:
errno = EBADF;
return -1;
}
ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset) {
/* Credit to Jan Biedermann (GitHub: @janbiedermann) */
ssize_t bytes_written = 0;
HANDLE handle = (HANDLE)_get_osfhandle(fd);
if (handle == INVALID_HANDLE_VALUE)
goto bad_file;
OVERLAPPED overlapped = {0};
if (offset > 0)
overlapped.Offset = offset;
if (WriteFile(handle, buf, count, (u_long *)&bytes_written, &overlapped))
return bytes_written;
errno = EIO;
return -1;
bad_file:
errno = EBADF;
return -1;
}
pid_t wait(int *stat_loc) {
fprintf(stderr, "wait() is not supported on Windows.\n");
errno = ENOSYS;
return -1;
}
pid_t waitpid(pid_t pid, int *stat_loc, int options) {
fprintf(stderr, "waitpid() is not supported on Windows.\n");
errno = ENOSYS;
return -1;
}
#endif
/* *****************************************************************************
Event deferring (declarations)
***************************************************************************** */
static void deferred_on_close(void *uuid_, void *pr_);
static void deferred_on_shutdown(void *arg, void *arg2);
static void deferred_on_ready(void *arg, void *arg2);
static void deferred_on_data(void *uuid, void *arg2);
static void deferred_ping(void *arg, void *arg2);
/* *****************************************************************************
Section Start Marker
Main State Machine Data Structures
***************************************************************************** */
typedef void (*fio_uuid_link_fn)(void *);
#define FIO_SET_NAME fio_uuid_links
#define FIO_SET_OBJ_TYPE fio_uuid_link_fn
#define FIO_SET_OBJ_COMPARE(o1, o2) 1
#include <fio.h>
/** User-space socket buffer data */
typedef struct fio_packet_s fio_packet_s;
struct fio_packet_s {
fio_packet_s *next;
int (*write_func)(int fd, struct fio_packet_s *packet);
void (*dealloc)(void *buffer);
union {
void *buffer;
intptr_t fd;
} data;
uintptr_t offset;
uintptr_t length;
};
/** Connection data (fd_data) */
typedef struct {
/* current data to be send */
fio_packet_s *packet;
/** the last packet in the queue. */
fio_packet_s **packet_last;
/* Data sent so far */
size_t sent;
/* fd protocol */
fio_protocol_s *protocol;
/* timer handler */
time_t active;
/** The number of pending packets that are in the queue. */
uint16_t packet_count;
/* timeout settings */
uint8_t timeout;
/* indicates that the fd should be considered scheduled (added to poll) */
fio_lock_i scheduled;
/* protocol lock */
fio_lock_i protocol_lock;
/* used to convert `fd` to `uuid` and validate connections */
uint8_t counter;
/* socket lock */
fio_lock_i sock_lock;
/** Connection is open */
uint8_t open;
/** indicated that the connection should be closed. */
uint8_t close;
/** peer address length */
uint8_t addr_len;
/** peer address */
uint8_t addr[48];
/** RW hooks. */
fio_rw_hook_s *rw_hooks;
/** RW udata. */
void *rw_udata;
/* Objects linked to the UUID */
fio_uuid_links_s links;
#ifdef __MINGW32__
/* Winsock operating system socket handle */
SOCKET socket_handle;
int osffd;
#endif
} fio_fd_data_s;
typedef struct {
struct timespec last_cycle;
/* connection capacity */
uint32_t capa;
/* connections counted towards shutdown (NOT while running) */
uint32_t connection_count;
/* thread list */
fio_ls_s thread_ids;
/* active workers */
uint16_t workers;
/* timer handler */
uint16_t threads;
/* timeout review loop flag */
uint8_t need_review;
/* spinning down process */
uint8_t volatile active;
/* worker process flag - true also for single process */
uint8_t is_worker;
/* polling and global lock */
fio_lock_i lock;
/* The highest active fd with a protocol object */
uint32_t max_protocol_fd;
/* timer handler */
pid_t parent;
#if FIO_ENGINE_POLL || FIO_ENGINE_WSAPOLL
struct pollfd *poll;
#endif
fio_fd_data_s info[];
} fio_data_s;
/** The logging level */
#if DEBUG
int FIO_LOG_LEVEL = FIO_LOG_LEVEL_DEBUG;
#else
int FIO_LOG_LEVEL = FIO_LOG_LEVEL_INFO;
#endif
static fio_data_s *fio_data = NULL;
/* used for protocol locking by task type. */
typedef struct {
fio_lock_i locks[3];
unsigned rsv : 8;
} protocol_metadata_s;
/* used for accessing the protocol locking in a safe byte aligned way. */
union protocol_metadata_union_u {
size_t opaque;
protocol_metadata_s meta;
};
#define fd_data(fd) (fio_data->info[(uintptr_t)(fd)])
#define uuid_data(uuid) fd_data(fio_uuid2fd((uuid)))
#define fd2uuid(fd) \
((intptr_t)((((uintptr_t)(fd)) << 8) | fd_data((fd)).counter))
/**
* Returns the maximum number of open files facil.io can handle per worker
* process.
*
* Total OS limits might apply as well but aren't shown.
*
* The value of 0 indicates either that the facil.io library wasn't initialized
* yet or that it's resources were released.
*/
size_t fio_capa(void) {
if (fio_data)
return fio_data->capa;
return 0;
}
/* *****************************************************************************
Packet allocation (for socket's user-buffer)
***************************************************************************** */
static inline void fio_packet_free(fio_packet_s *packet) {
packet->dealloc(packet->data.buffer);
fio_free(packet);
}
static inline fio_packet_s *fio_packet_alloc(void) {
fio_packet_s *packet = fio_malloc(sizeof(*packet));
FIO_ASSERT_ALLOC(packet);
return packet;
}
/* *****************************************************************************
Core Connection Data Clearing
***************************************************************************** */
/* resets connection data, marking it as either open or closed. */
static inline int fio_clear_fd(intptr_t fd, uint8_t is_open) {
fio_packet_s *packet;
fio_protocol_s *protocol;
fio_rw_hook_s *rw_hooks;
void *rw_udata;
fio_uuid_links_s links;
fio_lock(&(fd_data(fd).sock_lock));
links = fd_data(fd).links;
packet = fd_data(fd).packet;
protocol = fd_data(fd).protocol;
rw_hooks = fd_data(fd).rw_hooks;
rw_udata = fd_data(fd).rw_udata;
#ifdef __MINGW32__
SOCKET socket_handle = fd_data(fd).socket_handle;
int osffd = fd_data(fd).osffd;
#endif
fd_data(fd) = (fio_fd_data_s){
.open = is_open,
.sock_lock = fd_data(fd).sock_lock,
.protocol_lock = fd_data(fd).protocol_lock,
.rw_hooks = (fio_rw_hook_s *)&FIO_DEFAULT_RW_HOOKS,
.counter = fd_data(fd).counter + 1,
.packet_last = &fd_data(fd).packet,
#ifdef __MINGW32__
.socket_handle = socket_handle,
.osffd = osffd,
#endif
};
if (is_open && fio_data->max_protocol_fd < fd) {
fio_data->max_protocol_fd = fd;
} else {
while (fio_data->max_protocol_fd &&
!fd_data(fio_data->max_protocol_fd).open)
--fio_data->max_protocol_fd;
}
fio_unlock(&(fd_data(fd).sock_lock));
if (rw_hooks && rw_hooks->cleanup)
rw_hooks->cleanup(rw_udata);
while (packet) {
fio_packet_s *tmp = packet;
packet = packet->next;
fio_packet_free(tmp);
}
if (fio_uuid_links_count(&links)) {
FIO_SET_FOR_LOOP(&links, pos) {
if (pos->hash)
pos->obj((void *)pos->hash);
}
}
fio_uuid_links_free(&links);
if (protocol && protocol->on_close) {
fio_defer(deferred_on_close, (void *)fd2uuid(fd), protocol);
}
// FIO_LOG_DEBUG("FD %d re-initialized (state: %p-%s).", (int)fd,
// (void *)fd2uuid(fd), (is_open ? "open" : "closed"));
return 0;
}
static inline void fio_force_close_in_poll(intptr_t uuid) {
uuid_data(uuid).close = 2;
fio_force_close(uuid);
}
/* *****************************************************************************
Protocol Locking and UUID validation
***************************************************************************** */
/* Macro for accessing the protocol locking / metadata. */
#define prt_meta(prt) (((union protocol_metadata_union_u *)(&(prt)->rsv))->meta)
/** locks a connection's protocol returns a pointer that need to be unlocked. */
inline static fio_protocol_s *protocol_try_lock(intptr_t fd,
enum fio_protocol_lock_e type) {
errno = 0;
if (fio_trylock(&fd_data(fd).protocol_lock))
goto would_block;
fio_protocol_s *pr = fd_data(fd).protocol;
if (!pr) {
fio_unlock(&fd_data(fd).protocol_lock);
goto invalid;
}
if (fio_trylock(&prt_meta(pr).locks[type])) {
fio_unlock(&fd_data(fd).protocol_lock);
goto would_block;
}
fio_unlock(&fd_data(fd).protocol_lock);
return pr;
would_block:
errno = EWOULDBLOCK;
return NULL;
invalid:
errno = EBADF;
return NULL;
}
/** See `fio_protocol_try_lock` for details. */
inline static void protocol_unlock(fio_protocol_s *pr,
enum fio_protocol_lock_e type) {
fio_unlock(&prt_meta(pr).locks[type]);
}
/** returns 1 if the UUID is valid and 0 if it isn't. */
#define uuid_is_valid(uuid) \
((intptr_t)(uuid) >= 0 && \
((uint32_t)fio_uuid2fd((uuid))) < fio_data->capa && \
((uintptr_t)(uuid)&0xFF) == uuid_data((uuid)).counter)
/* public API. */
fio_protocol_s *fio_protocol_try_lock(intptr_t uuid,
enum fio_protocol_lock_e type) {
if (!uuid_is_valid(uuid)) {
errno = EBADF;
return NULL;
}
return protocol_try_lock(fio_uuid2fd(uuid), type);
}
/* public API. */
void fio_protocol_unlock(fio_protocol_s *pr, enum fio_protocol_lock_e type) {
protocol_unlock(pr, type);
}
/* *****************************************************************************
UUID validation and state
***************************************************************************** */
/* public API. */
intptr_t fio_fd2uuid(int fd) {
if (fd < 0 || (size_t)fd >= fio_data->capa)
return -1;
if (!fd_data(fd).open) {
fio_lock(&fd_data(fd).protocol_lock);
fio_clear_fd(fd, 1);
fio_unlock(&fd_data(fd).protocol_lock);
}
return fd2uuid(fd);
}
/* public API. */
int fio_is_valid(intptr_t uuid) { return uuid_is_valid(uuid); }
/* public API. */
int fio_is_closed(intptr_t uuid) {
return !uuid_is_valid(uuid) || !uuid_data(uuid).open || uuid_data(uuid).close;
}
void fio_stop(void) {
if (fio_data)
fio_data->active = 0;
}
/* public API. */
int16_t fio_is_running(void) { return fio_data && fio_data->active; }
/* public API. */
struct timespec fio_last_tick(void) {
return fio_data->last_cycle;
}
#define touchfd(fd) fd_data((fd)).active = fio_data->last_cycle.tv_sec
/* public API. */
void fio_touch(intptr_t uuid) {
if (uuid_is_valid(uuid))
touchfd(fio_uuid2fd(uuid));
}
/* public API. */
fio_str_info_s fio_peer_addr(intptr_t uuid) {
if (fio_is_closed(uuid) || !uuid_data(uuid).addr_len)
return (fio_str_info_s){.data = NULL, .len = 0, .capa = 0};
return (fio_str_info_s){.data = (char *)uuid_data(uuid).addr,
.len = uuid_data(uuid).addr_len,
.capa = 0};
}
/**
* Writes the local machine address (qualified host name) to the buffer.
*
* Returns the amount of data written (excluding the NUL byte).
*
* `limit` is the maximum number of bytes in the buffer, including the NUL byte.
*
* If the returned value == limit - 1, the result might have been truncated.
*
* If 0 is returned, an erro might have occured (see `errno`) and the contents
* of `dest` is undefined.
*/
size_t fio_local_addr(char *dest, size_t limit) {
if (gethostname(dest, limit))
return 0;
struct addrinfo hints, *info;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // don't care IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
hints.ai_flags = AI_CANONNAME; // get cannonical name
if (getaddrinfo(dest, "http", &hints, &info) != 0)
return 0;
for (struct addrinfo *pos = info; pos; pos = pos->ai_next) {
if (pos->ai_canonname) {
size_t len = strlen(pos->ai_canonname);
if (len >= limit)
len = limit - 1;
memcpy(dest, pos->ai_canonname, len);
dest[len] = 0;
freeaddrinfo(info);
return len;
}
}
freeaddrinfo(info);
return 0;
}
/* *****************************************************************************
UUID attachments (linking objects to the UUID's lifetime)
***************************************************************************** */
/* public API. */
void fio_uuid_link(intptr_t uuid, void *obj, void (*on_close)(void *obj)) {
if (!uuid_is_valid(uuid))
goto invalid;
fio_lock(&uuid_data(uuid).sock_lock);
if (!uuid_is_valid(uuid))
goto locked_invalid;
fio_uuid_links_overwrite(&uuid_data(uuid).links, (uintptr_t)obj, on_close,
NULL);
fio_unlock(&uuid_data(uuid).sock_lock);
return;
locked_invalid:
fio_unlock(&uuid_data(uuid).sock_lock);
invalid:
errno = EBADF;
on_close(obj);
}
/* public API. */
int fio_uuid_unlink(intptr_t uuid, void *obj) {
if (!uuid_is_valid(uuid))
goto invalid;
fio_lock(&uuid_data(uuid).sock_lock);
if (!uuid_is_valid(uuid))
goto locked_invalid;
/* default object comparison is always true */
int ret =
fio_uuid_links_remove(&uuid_data(uuid).links, (uintptr_t)obj, NULL, NULL);
if (ret)
errno = ENOTCONN;
fio_unlock(&uuid_data(uuid).sock_lock);
return ret;
locked_invalid:
fio_unlock(&uuid_data(uuid).sock_lock);
invalid:
errno = EBADF;
return -1;
}
/* *****************************************************************************
Section Start Marker
Default Thread / Fork handler
And Concurrency Helpers
***************************************************************************** */
/**
OVERRIDE THIS to replace the default `fork` implementation.
Behaves like the system's `fork`.
*/
#pragma weak fio_fork
int __attribute__((weak)) fio_fork(void) { return fork(); }
/**
* OVERRIDE THIS to replace the default pthread implementation.
*
* Accepts a pointer to a function and a single argument that should be executed
* within a new thread.
*
* The function should allocate memory for the thread object and return a
* pointer to the allocated memory that identifies the thread.
*
* On error NULL should be returned.
*/
#pragma weak fio_thread_new
void *__attribute__((weak))
fio_thread_new(void *(*thread_func)(void *), void *arg) {
pthread_t *thread = malloc(sizeof(*thread));
FIO_ASSERT_ALLOC(thread);
if (pthread_create(thread, NULL, thread_func, arg))
goto error;
return thread;
error:
free(thread);
return NULL;
}
/**
* OVERRIDE THIS to replace the default pthread implementation.
*
* Frees the memory associated with a thread identifier (allows the thread to
* run it's course, just the identifier is freed).
*/
#pragma weak fio_thread_free
void __attribute__((weak)) fio_thread_free(void *p_thr) {
if (*((pthread_t *)p_thr)) {
pthread_detach(*((pthread_t *)p_thr));
}
free(p_thr);
}
/**
* OVERRIDE THIS to replace the default pthread implementation.
*
* Accepts a pointer returned from `fio_thread_new` (should also free any
* allocated memory) and joins the associated thread.
*
* Return value is ignored.
*/
#pragma weak fio_thread_join
int __attribute__((weak)) fio_thread_join(void *p_thr) {
if (!p_thr || !(*((pthread_t *)p_thr)))
return -1;
pthread_join(*((pthread_t *)p_thr), NULL);
*((pthread_t *)p_thr) = (pthread_t)NULL;
free(p_thr);
return 0;
}
/* *****************************************************************************
Suspending and renewing thread execution (signaling events)
***************************************************************************** */
#ifndef DEFER_THROTTLE
#define DEFER_THROTTLE 2097148UL
#endif
#ifndef FIO_DEFER_THROTTLE_LIMIT
#define FIO_DEFER_THROTTLE_LIMIT 134217472UL
#endif
/**
* The polling throttling model will use pipes to suspend and resume threads...
*
* However, it seems the approach is currently broken, at least on macOS.
* I don't know why.
*
* If polling is disabled, the progressive throttling model will be used.
*
* The progressive throttling makes concurrency and parallelism likely, but uses
* progressive nano-sleep throttling system that is less exact.
*/
#ifndef FIO_DEFER_THROTTLE_POLL
#ifdef __MINGW32__
#define FIO_DEFER_THROTTLE_POLL 1
#else
#define FIO_DEFER_THROTTLE_POLL 0
#endif
#endif
typedef struct fio_thread_queue_s {
fio_ls_embd_s node;
#ifdef __MINGW32__
HANDLE handle;
int in_list;
#else
int fd_wait; /* used for waiting (read signal) */
int fd_signal; /* used for signalling (write) */
#endif
} fio_thread_queue_s;
fio_ls_embd_s fio_thread_queue = FIO_LS_INIT(fio_thread_queue);
fio_lock_i fio_thread_lock = FIO_LOCK_INIT;
static pthread_key_t fio_thread_data_key;
static pthread_once_t fio_thread_data_once = PTHREAD_ONCE_INIT;
static void init_fio_thread_data_key(void) {
pthread_key_create(&fio_thread_data_key, free);
}
static void init_fio_thread_data_ptr(void) {
fio_thread_queue_s *fio_thread_data = malloc(sizeof(fio_thread_queue_s));
FIO_ASSERT_ALLOC(fio_thread_data);
memset(fio_thread_data, 0, sizeof(fio_thread_queue_s));
#ifdef __MINGW32__
fio_thread_data->handle = INVALID_HANDLE_VALUE;
#else
fio_thread_data->fd_wait = -1;
fio_thread_data->fd_signal = -1;
#endif
pthread_setspecific(fio_thread_data_key, fio_thread_data);
}
FIO_FUNC inline void fio_thread_make_suspendable(void) {
pthread_once(&fio_thread_data_once, init_fio_thread_data_key);
fio_thread_queue_s *fio_thread_data = (fio_thread_queue_s *)pthread_getspecific(fio_thread_data_key);
if (!fio_thread_data) {
init_fio_thread_data_ptr();
fio_thread_data = (fio_thread_queue_s *)pthread_getspecific(fio_thread_data_key);
}
#ifdef __MINGW32__
/** create automatically reseting event */
fio_thread_data->handle = CreateEvent(NULL, FALSE, FALSE, TEXT("thread signal"));
fio_thread_data->in_list = 0;
#else
if (fio_thread_data->fd_signal >= 0)
return;
int fd[2] = {0, 0};
int ret = pipe(fd);
FIO_ASSERT(ret == 0, "`pipe` failed.");
FIO_ASSERT(fio_set_non_block(fd[0]) == 0,
"(fio) couldn't set internal pipe to non-blocking mode.");
FIO_ASSERT(fio_set_non_block(fd[1]) == 0,
"(fio) couldn't set internal pipe to non-blocking mode.");
fio_thread_data->fd_wait = fd[0];
fio_thread_data->fd_signal = fd[1];
#endif
}
FIO_FUNC inline void fio_thread_cleanup(void) {
fio_thread_queue_s *fio_thread_data = (fio_thread_queue_s *)pthread_getspecific(fio_thread_data_key);
#ifdef __MINGW32__
HANDLE h = fio_thread_data->handle;
fio_thread_data->handle = INVALID_HANDLE_VALUE;
CloseHandle(h);
#else
if (fio_thread_data->fd_signal < 0)
return;
close(fio_thread_data->fd_wait);
close(fio_thread_data->fd_signal);
fio_thread_data->fd_wait = -1;
fio_thread_data->fd_signal = -1;
#endif
}
/* suspend thread execution (might be resumed unexpectedly) */
FIO_FUNC void fio_thread_suspend(void) {
fio_thread_queue_s *fio_thread_data = (fio_thread_queue_s *)pthread_getspecific(fio_thread_data_key);
#ifdef __MINGW32__
fio_lock(&fio_thread_lock);
/** don't add thread to queue if its already in there
* to prevent queue breakage
* can happen if WaitForSingleObject returns for other reasons */
if (!fio_thread_data->in_list) {
fio_ls_embd_push(&fio_thread_queue, &fio_thread_data->node);
fio_thread_data->in_list = 1;
}
fio_unlock(&fio_thread_lock);
WaitForSingleObject(fio_thread_data->handle, 500);
#else
fio_lock(&fio_thread_lock);
fio_ls_embd_push(&fio_thread_queue, &fio_thread_data->node);
fio_unlock(&fio_thread_lock);
struct pollfd list = {
.events = (POLLPRI | POLLIN),
.fd = fio_thread_data->fd_wait,
};
if (poll(&list, 1, 5000) > 0) {
/* thread was removed from the list through signal */
uint64_t data;
int r = read(fio_thread_data->fd_wait, &data, sizeof(data));
(void)r;
} else {
/* remove self from list */
fio_lock(&fio_thread_lock);
fio_ls_embd_remove(&fio_thread_data->node);
fio_unlock(&fio_thread_lock);
}
#endif
}
/* wake up a single thread */
FIO_FUNC void fio_thread_signal(void) {
#ifdef __MINGW32__
fio_lock(&fio_thread_lock);
fio_thread_queue_s *t = (fio_thread_queue_s *)fio_ls_embd_shift(&fio_thread_queue);
if (t) {
t->in_list = 0;
fio_unlock(&fio_thread_lock);
SetEvent(t->handle);
} else {
fio_unlock(&fio_thread_lock);
}
#else
fio_thread_queue_s *t;
int fd = -2;
fio_lock(&fio_thread_lock);
t = (fio_thread_queue_s *)fio_ls_embd_shift(&fio_thread_queue);
if (t)
fd = t->fd_signal;
fio_unlock(&fio_thread_lock);
if (fd >= 0) {
uint64_t data = 1;
int r = write(fd, (void *)&data, sizeof(data));
(void)r;
} else if (fd == -1) {
/* hardly the best way, but there's a thread sleeping on air */
kill(getpid(), SIGCONT);
}
#endif
}
/* wake up all threads */
FIO_FUNC void fio_thread_broadcast(void) {
while (fio_ls_embd_any(&fio_thread_queue)) {
fio_thread_signal();
}
}