forked from DylanZA/netbench
-
Notifications
You must be signed in to change notification settings - Fork 0
/
netbench.cpp
1595 lines (1430 loc) · 42.9 KB
/
netbench.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <boost/algorithm/string/join.hpp>
#include <boost/align/aligned_allocator.hpp>
#include <boost/core/noncopyable.hpp>
#include <string_view>
#include <thread>
#include <unordered_set>
#include <errno.h>
#include <fcntl.h>
#include <liburing.h>
#include <unistd.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <sys/times.h>
#include "sender.h"
#include "util.h"
namespace po = boost::program_options;
/*
* Network benchmark tool.
*
* This tool will benchmark network coordinator stacks. specifically looking at
* io_uring vs epoll.
* The approach is to setup a single threaded receiver, and then spawn up N
* threads with M connections. They wijll then send some requests, where a
* request is a single (host endian) 32 bit unsigned int indicating length, and
* then that number of bytes. The receiver when it collects a single "request"
* will respond with a single byte (contents unimportant). The sender can then
* treat this as a completed transaction and add it to it's stats.
*
*/
std::atomic<bool> globalShouldShutdown{false};
void intHandler(int dummy) {
if (globalShouldShutdown.load()) {
die("already should have shutdown at signal");
}
globalShouldShutdown = true;
}
enum class RxEngine { IoUring, Epoll };
struct RxConfig {
int backlog = 100000;
int max_events = 32;
int recv_size = 4096;
};
struct IoUringRxConfig : RxConfig {
bool supports_nonblock_accept = false;
bool register_ring = true;
bool provide_buffers = true;
bool fixed_files = true;
bool loop_recv = false;
int sqe_count = 64;
int cqe_count = 0;
int max_cqe_loop = 128;
int provided_buffer_count = 8000;
int fixed_file_count = 16000;
int provided_buffer_low_watermark = 2000;
int provided_buffer_compact = 1;
std::string const toString() const {
// only give the important options:
return strcat(
"fixed_files=",
fixed_files ? strcat("1 (count=", fixed_file_count, ")") : strcat("0"),
" provide_buffers=",
provide_buffers ? strcat(
"1 (count=",
provided_buffer_count,
" refill=",
provided_buffer_low_watermark,
" compact=",
provided_buffer_compact,
")")
: strcat("0"));
}
};
struct EpollRxConfig : RxConfig {};
struct Config {
std::vector<uint16_t> use_port;
bool client_only = false;
bool server_only = false;
SendOptions send_options;
bool print_rx_stats = true;
std::vector<std::string> tx;
std::vector<std::string> rx;
};
int mkBasicSock(uint16_t port, bool const isv6, int extra_flags = 0) {
struct sockaddr_in serv_addr;
struct sockaddr_in6 serv_addr6;
int fd = checkedErrno(
socket(isv6 ? AF_INET6 : AF_INET, SOCK_STREAM | extra_flags, 0),
"make socket v6=",
isv6);
doSetSockOpt<int>(fd, SOL_SOCKET, SO_REUSEADDR, 1);
if (isv6) {
doSetSockOpt<int>(fd, IPPROTO_IPV6, IPV6_V6ONLY, 1);
}
struct sockaddr* paddr;
size_t paddrlen;
if (isv6) {
memset(&serv_addr6, 0, sizeof(serv_addr6));
serv_addr6.sin6_family = AF_INET6;
serv_addr6.sin6_port = htons(port);
serv_addr6.sin6_addr = in6addr_any;
paddr = (struct sockaddr*)&serv_addr6;
paddrlen = sizeof(serv_addr6);
} else {
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
paddr = (struct sockaddr*)&serv_addr;
paddrlen = sizeof(serv_addr);
}
if (bind(fd, paddr, paddrlen)) {
int err = errno;
close(fd);
errno = err;
return -1;
}
return fd;
}
int mkServerSock(
RxConfig const& rx_cfg,
uint16_t port,
bool const isv6,
int extra_flags) {
int fd = checkedErrno(mkBasicSock(port, isv6, extra_flags));
checkedErrno(listen(fd, rx_cfg.backlog), "listen");
vlog("made sock ", fd, " v6=", isv6, " port=", port);
return fd;
}
struct io_uring mkIoUring(IoUringRxConfig const& rx_cfg) {
struct io_uring_params params;
struct io_uring ring;
memset(¶ms, 0, sizeof(params));
// default to 8x sqe_count as we are very happy to submit multiple sqe off one
// cqe (eg send,read) and this can build up quickly
int cqe_count =
rx_cfg.cqe_count <= 0 ? 8 * rx_cfg.sqe_count : rx_cfg.cqe_count;
params.flags |= IORING_SETUP_CQSIZE;
params.cq_entries = cqe_count;
checkedErrno(
io_uring_queue_init_params(rx_cfg.sqe_count, &ring, ¶ms),
"io_uring_queue_init_params");
if (rx_cfg.register_ring) {
io_uring_register_ring_fd(&ring);
}
return ring;
}
// benchmark protocol is <uint32_t length>:<payload of size length>
// response is a single byte when it is received
struct ProtocolParser {
// consume data and return number of new sends
uint32_t consume(char const* data, size_t n) {
uint32_t ret = 0;
while (n > 0) {
so_far += n;
if (!is_reading) {
uint32_t size_buff_add = std::min<uint32_t>(n, 4 - size_buff_have);
memcpy(size_buff + size_buff_have, data, size_buff_add);
size_buff_have += size_buff_add;
if (size_buff_have >= 4) {
memcpy(&is_reading, size_buff, 4);
}
}
// vlog("consume ", n, " is_reading=", is_reading);
if (is_reading && so_far >= is_reading + 4) {
data += n;
n = so_far - (is_reading + 4);
so_far = size_buff_have = is_reading = 0;
ret++;
} else {
break;
}
}
return ret;
}
uint32_t size_buff_have = 0;
char size_buff[4];
uint32_t is_reading = 0;
uint32_t so_far = 0;
};
class RxStats {
public:
RxStats(std::string const& name) : name_(name) {
auto const now = std::chrono::steady_clock::now();
started_ = lastStats_ = now;
lastClock_ = checkedErrno(times(&lastTimes_), "initial times");
}
void startWait() {
waitStarted_ = std::chrono::steady_clock::now();
}
void doneWait() {
auto now = std::chrono::steady_clock::now();
// anything under 100us seems to be very noisy
static constexpr std::chrono::microseconds kEpsilon{100};
if (now > waitStarted_ + kEpsilon) {
idle_ += (now - waitStarted_);
}
}
void doneLoop(size_t bytes, size_t requests, bool is_overflow = false) {
auto const now = std::chrono::steady_clock::now();
auto const duration = now - lastStats_;
++loops_;
if (duration >= std::chrono::seconds(1)) {
doLog(bytes, requests, now, duration, is_overflow);
}
}
private:
std::chrono::milliseconds getMs(clock_t from, clock_t to) {
return std::chrono::milliseconds(
to <= from ? 0llu : (((to - from) * 1000llu) / ticksPerSecond_));
}
void doLog(
size_t bytes,
size_t requests,
std::chrono::steady_clock::time_point now,
std::chrono::steady_clock::duration duration,
bool is_overflow) {
using namespace std::chrono;
uint64_t const millis = duration_cast<milliseconds>(duration).count();
double bps = ((bytes - lastBytes_) * 1000.0) / millis;
double rps = ((requests - lastRequests_) * 1000.0) / millis;
struct tms times_now {};
clock_t clock_now = checkedErrno(::times(×_now), "loop times");
if (requests > lastRequests_ && lastRps_) {
char buff[2048];
// use snprintf as I like the floating point formatting
int written = snprintf(
buff,
sizeof(buff),
"%s: rps:%6.2fk Bps:%6.2fM idle=%lums "
"user=%lums system=%lums wall=%lums loops=%lu%s",
name_.c_str(),
rps / 1000.0,
bps / 1000000.0,
duration_cast<milliseconds>(idle_).count(),
getMs(lastTimes_.tms_utime, times_now.tms_utime).count(),
getMs(lastTimes_.tms_stime, times_now.tms_stime).count(),
getMs(lastClock_, clock_now).count(),
loops_,
is_overflow ? " OVERFLOW" : "");
if (written >= 0) {
log(std::string_view(buff, written));
}
}
loops_ = 0;
idle_ = steady_clock::duration{0};
lastClock_ = clock_now;
lastTimes_ = times_now;
lastBytes_ = bytes;
lastRequests_ = requests;
lastStats_ = now;
lastRps_ = rps;
}
private:
std::string const& name_;
std::chrono::steady_clock::time_point started_ =
std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point lastStats_ =
std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point waitStarted;
std::chrono::steady_clock::duration totalWaited{0};
uint64_t ticksPerSecond_ = sysconf(_SC_CLK_TCK);
struct tms lastTimes_;
clock_t lastClock_;
uint64_t loops_ = 0;
std::chrono::steady_clock::time_point waitStarted_;
std::chrono::steady_clock::duration idle_{0};
size_t lastBytes_ = 0;
size_t lastRequests_ = 0;
size_t lastRps_ = 0;
};
class RunnerBase {
public:
explicit RunnerBase(std::string const& name) : name_(name) {}
std::string const& name() const {
return name_;
}
virtual void loop(std::atomic<bool>* should_shutdown) = 0;
virtual void stop() = 0;
virtual void addListenSock(int fd, bool v6) = 0;
virtual ~RunnerBase() = default;
protected:
void didRead(int x) {
bytesRx_ += x;
}
void finishedRequests(int n) {
requestsRx_ += n;
}
void newSock() {
socks_++;
if (socks_ % 100 == 0) {
vlog("add sock: now ", socks_);
}
}
void delSock() {
socks_--;
if (socks_ % 100 == 0) {
vlog("del sock: now ", socks_);
}
}
int socks() const {
return socks_;
}
size_t requestsRx_ = 0;
size_t bytesRx_ = 0;
private:
std::string const name_;
int socks_ = 0;
};
class NullRunner : public RunnerBase {
public:
explicit NullRunner(std::string const& name) : RunnerBase(name) {}
void loop(std::atomic<bool>*) override {}
void stop() override {}
void addListenSock(int fd, bool) override {
close(fd);
}
};
class BufferProvider : private boost::noncopyable {
public:
static constexpr int kBgid = 1;
explicit BufferProvider(size_t count, size_t size, int lowWatermark)
: sizePerBuffer_(addAlignment(size)), lowWatermark_(lowWatermark) {
buffer_.resize(count * sizePerBuffer_);
for (size_t i = 0; i < count; i++) {
buffers_.push_back(buffer_.data() + i * sizePerBuffer_);
}
toProvide_.reserve(128);
toProvide2_.reserve(128);
toProvide_.emplace_back(0, count);
toProvideCount_ = count;
}
size_t count() const {
return buffers_.size();
}
size_t sizePerBuffer() const {
return sizePerBuffer_;
}
size_t toProvideCount() const {
return toProvideCount_;
}
bool canProvide() const {
return toProvide_.size();
}
bool needsToProvide() const {
return toProvideCount_ > lowWatermark_;
}
void compact() {
if (toProvide_.size() <= 1) {
return;
}
std::sort(
toProvide_.begin(), toProvide_.end(), [](auto const& a, auto const& b) {
return a.start < b.start;
});
int merged = 0;
toProvide2_.clear();
toProvide2_.push_back(toProvide_[0]);
for (size_t i = 1; i < toProvide_.size(); i++) {
auto const& p = toProvide_[i];
if (!toProvide2_.back().merge(p)) {
toProvide2_.push_back(p);
} else {
++merged;
}
}
toProvide_.swap(toProvide2_);
}
void returnIndex(int i) {
if (toProvide_.empty()) {
toProvide_.emplace_back(i);
} else if (toProvide_.back().merge(i)) {
// yay, nothing to do
} else if (
toProvide_.size() >= 2 && toProvide_[toProvide_.size() - 2].merge(i)) {
// yay too, try merge these two. this accounts for out of order by 1 index
// where we receive 1,3,2. so we merge 2 into 3, and then (2,3) into 1
if (toProvide_[toProvide_.size() - 2].merge(toProvide_.back())) {
toProvide_.pop_back();
}
} else {
toProvide_.emplace_back(i);
}
++toProvideCount_;
}
void provide(struct io_uring_sqe* sqe) {
Range const& r = toProvide_.back();
io_uring_prep_provide_buffers(
sqe, buffers_[r.start], sizePerBuffer_, r.count, kBgid, r.start);
sqe->flags |= IOSQE_CQE_SKIP_SUCCESS;
toProvideCount_ -= r.count;
toProvide_.pop_back();
assert(toProvide_.size() != 0 || toProvideCount_ == 0);
}
char const* getData(int i) const {
return buffers_.at(i);
}
private:
static constexpr int kAlignment = 16;
size_t addAlignment(size_t n) {
return kAlignment * ((n + kAlignment - 1) / kAlignment);
}
struct Range {
explicit Range(int idx, int count = 1) : start(idx), count(count) {}
int start;
int count = 1;
bool merge(int idx) {
if (idx == start - 1) {
start = idx;
count++;
return true;
} else if (idx == start + count) {
count++;
return true;
} else {
return false;
}
}
bool merge(Range const& r) {
if (start + count == r.start) {
count += r.count;
return true;
} else if (r.start + r.count == start) {
count += r.count;
start = r.start;
return true;
} else {
return false;
}
}
};
size_t sizePerBuffer_;
std::vector<char, boost::alignment::aligned_allocator<char, kAlignment>>
buffer_;
std::vector<char*> buffers_;
ssize_t toProvideCount_ = 0;
int lowWatermark_;
std::vector<Range> toProvide_;
std::vector<Range> toProvide2_;
};
static constexpr int kUseBufferProviderFlag = 1;
static constexpr int kUseFixedFilesFlag = 2;
static constexpr int kLoopRecvFlag = 4;
template <size_t ReadSize = 4096, size_t Flags = 0>
struct BasicSock {
static constexpr bool kUseBufferProvider = Flags & kUseBufferProviderFlag;
static constexpr bool kUseFixedFiles = Flags & kUseFixedFilesFlag;
static constexpr bool kShouldLoop = Flags & kLoopRecvFlag;
explicit BasicSock(int fd) : fd(fd) {}
~BasicSock() {
if (!closed_) {
log("socket not closed at destruct");
}
}
uint32_t peekSend() {
return do_send;
}
void didSend(uint32_t count) {}
void addSend(struct io_uring_sqe* sqe, uint32_t len) {
if (len > ReadSize) {
die("too big send");
}
io_uring_prep_send(sqe, fd, &buff[0], len, 0);
if (kUseFixedFiles) {
sqe->flags |= IOSQE_FIXED_FILE;
}
sqe->flags |= IOSQE_CQE_SKIP_SUCCESS;
do_send -= std::min(len, do_send);
}
void addRead(struct io_uring_sqe* sqe, BufferProvider& provider) {
if (kUseBufferProvider) {
io_uring_prep_recv(sqe, fd, NULL, provider.sizePerBuffer(), 0);
sqe->flags |= IOSQE_BUFFER_SELECT;
sqe->buf_group = BufferProvider::kBgid;
} else {
io_uring_prep_recv(sqe, fd, &buff[0], sizeof(buff), 0);
}
if (kUseFixedFiles) {
sqe->flags |= IOSQE_FIXED_FILE;
}
}
void doClose() {
closed_ = true;
::close(fd);
}
void addClose(struct io_uring_sqe* sqe) {
closed_ = true;
io_uring_prep_close(sqe, fd);
sqe->flags |= IOSQE_FIXED_FILE;
io_uring_sqe_set_data(sqe, 0);
}
int didRead(size_t size, BufferProvider& provider, struct io_uring_cqe* cqe) {
// pull remaining data
int res = size;
int recycleBufferIdx = -1;
if (kUseBufferProvider) {
recycleBufferIdx = cqe->flags >> 16;
didRead(res, provider, recycleBufferIdx);
} else {
didRead(res);
}
while (kShouldLoop && res == (int)size) {
res = recv(this->fd, buff, sizeof(buff), MSG_NOSIGNAL);
if (res > 0) {
didRead(res);
}
}
return recycleBufferIdx;
}
private:
void didRead(size_t n) {
// normal read from buffer
didRead(buff, n);
}
void didRead(size_t n, BufferProvider& provider, int idx) {
// read from a provided buffer
didRead(provider.getData(idx), n);
}
void didRead(char const* b, size_t n) {
do_send += parser.consume(b, n);
}
int fd;
ProtocolParser parser;
uint32_t do_send = 0;
bool closed_ = false;
char buff[ReadSize];
};
struct ListenSock : private boost::noncopyable {
ListenSock(int fd, bool v6) : fd(fd), isv6(v6) {}
virtual ~ListenSock() {
if (!closed) {
::close(fd);
}
vlog("close ListenSock");
}
void close() {
::close(fd);
closed = true;
}
int fd;
bool isv6;
struct sockaddr_in addr;
struct sockaddr_in6 addr6;
socklen_t client_len;
bool closed = false;
int nextAcceptIdx = -1;
};
template <class TSock>
struct IOUringRunner : public RunnerBase {
explicit IOUringRunner(
Config const& cfg,
IoUringRxConfig const& rx_cfg,
std::string const& name)
: RunnerBase(name),
cfg_(cfg),
rxCfg_(rx_cfg),
ring(mkIoUring(rx_cfg)),
buffers_(
rx_cfg.provided_buffer_count,
rx_cfg.recv_size,
rx_cfg.provided_buffer_low_watermark) {
if (TSock::kUseFixedFiles && TSock::kShouldLoop) {
die("can't have fixed files and looping, "
"we don't have the fd to call recv() !");
}
cqes_.resize(rx_cfg.max_events);
if (TSock::kUseBufferProvider) {
provideBuffers(true);
submit();
}
if (TSock::kUseFixedFiles) {
std::vector<int> files(rx_cfg.fixed_file_count, -1);
checkedErrno(
io_uring_register_files(&ring, files.data(), files.size()),
"io_uring_register_files");
}
}
~IOUringRunner() {
if (socks()) {
vlog(
"IOUringRunner shutting down with ",
socks(),
" sockets still: stopping=",
stopping);
}
io_uring_queue_exit(&ring);
}
void provideBuffers(bool force) {
if (!TSock::kUseBufferProvider) {
return;
}
if (!(force || buffers_.needsToProvide())) {
return;
}
if (rxCfg_.provided_buffer_compact) {
buffers_.compact();
}
while (buffers_.canProvide()) {
auto* sqe = get_sqe();
buffers_.provide(sqe);
io_uring_sqe_set_data(sqe, NULL);
}
}
static constexpr int kAccept = 1;
static constexpr int kRead = 2;
static constexpr int kWrite = 3;
static constexpr int kIgnore = 0;
void addListenSock(int fd, bool v6) override {
listeners_++;
listenSocks_.push_back(std::make_unique<ListenSock>(fd, v6));
addAccept(listenSocks_.back().get());
}
void addAccept(ListenSock* ls) {
struct io_uring_sqe* sqe = get_sqe();
struct sockaddr* addr;
if (ls->isv6) {
ls->client_len = sizeof(ls->addr6);
addr = (struct sockaddr*)&ls->addr6;
} else {
ls->client_len = sizeof(ls->addr);
addr = (struct sockaddr*)&ls->addr;
}
if (TSock::kUseFixedFiles) {
if (ls->nextAcceptIdx >= 0) {
die("only allowed one accept at a time");
}
ls->nextAcceptIdx = nextFdIdx();
io_uring_prep_accept_direct(
sqe, ls->fd, addr, &ls->client_len, SOCK_NONBLOCK, ls->nextAcceptIdx);
} else {
io_uring_prep_accept(sqe, ls->fd, addr, &ls->client_len, SOCK_NONBLOCK);
}
io_uring_sqe_set_data(sqe, tag(ls, kAccept));
}
struct io_uring_sqe* get_sqe() {
struct io_uring_sqe* sqe = io_uring_get_sqe(&ring);
if (!sqe) {
submit();
sqe = io_uring_get_sqe(&ring);
if (!sqe) {
throw std::runtime_error("no sqe available");
}
}
++expected;
return sqe;
}
void addRead(TSock* sock) {
struct io_uring_sqe* sqe = get_sqe();
sock->addRead(sqe, buffers_);
io_uring_sqe_set_data(sqe, tag(sock, kRead));
}
void addSend(TSock* sock, uint32_t len) {
struct io_uring_sqe* sqe = get_sqe();
sock->addSend(sqe, len);
io_uring_sqe_set_data(sqe, tag(sock, kWrite));
}
void processAccept(struct io_uring_cqe* cqe) {
int fd = cqe->res;
ListenSock* ls = untag<ListenSock>(cqe->user_data);
if (fd >= 0) {
int used_fd = fd;
if (TSock::kUseFixedFiles) {
if (fd > 0) {
die("trying to use fixed files, but got given an actual fd. "
"implies that this kernel does not support this feature");
}
if (ls->nextAcceptIdx < 0) {
die("no nextAcceptIdx");
}
used_fd = ls->nextAcceptIdx;
ls->nextAcceptIdx = -1;
}
TSock* sock = new TSock(used_fd);
addRead(sock);
newSock();
} else if (!stopping) {
die("unexpected accept result ",
strerror(-fd),
"(",
fd,
") ud=",
cqe->user_data);
}
if (stopping) {
return;
} else {
if (rxCfg_.supports_nonblock_accept && !TSock::kUseFixedFiles) {
// get any outstanding sockets
struct sockaddr_in addr;
struct sockaddr_in6 addr6;
socklen_t addrlen = ls->isv6 ? sizeof(addr6) : sizeof(addr);
struct sockaddr* paddr =
ls->isv6 ? (struct sockaddr*)&addr6 : (struct sockaddr*)&addr;
while (1) {
int sock_fd = accept4(ls->fd, paddr, &addrlen, SOCK_NONBLOCK);
if (sock_fd == -1 && errno == EAGAIN) {
break;
} else if (sock_fd == -1) {
checkedErrno(sock_fd, "accept4");
}
TSock* sock = new TSock(sock_fd);
addRead(sock);
newSock();
}
}
addAccept(untag<ListenSock>(cqe->user_data));
}
}
void processRead(struct io_uring_cqe* cqe) {
int amount = cqe->res;
TSock* sock = untag<TSock>(cqe->user_data);
if (amount > 0) {
int recycleBufferIdx = sock->didRead(amount, buffers_, cqe);
if (recycleBufferIdx > 0) {
buffers_.returnIndex(recycleBufferIdx);
provideBuffers(false);
}
if (uint32_t sends = sock->peekSend(); sends > 0) {
finishedRequests(sends);
addSend(sock, sends);
}
didRead(amount);
addRead(sock);
} else if (amount <= 0) {
if (cqe->res == -ENOBUFS) {
log("not enough buffers, but will just requeue. so far have ",
++enobuffCount_);
addRead(sock);
return;
}
if (cqe->res < 0 && !stopping) {
if (cqe->res != -ECONNRESET) {
log("unexpected read: ", amount, " delete ", sock);
}
}
if (TSock::kUseFixedFiles) {
auto* sqe = get_sqe();
sock->addClose(sqe);
io_uring_sqe_set_data(sqe, NULL);
} else {
sock->doClose();
}
delete sock;
delSock();
}
}
void processCqe(struct io_uring_cqe* cqe) {
switch (get_tag(cqe->user_data)) {
case kAccept:
processAccept(cqe);
break;
case kRead:
processRead(cqe);
break;
case kWrite:
// be careful if you do something here as kRead might delete sockets.
// this is ok as we only ever have one read outstanding
// at once
if (cqe->res < 0) {
// we should track these down and make sure they only happen when the
// sender socket is closed
log("bad socket write ", cqe->res);
}
break;
case kIgnore:
break;
default:
if (cqe->user_data == LIBURING_UDATA_TIMEOUT) {
break;
}
die("unexpected completion:", cqe->user_data);
break;
}
}
void submit() {
while (expected) {
int got = io_uring_submit(&ring);
if (got != expected) {
// log("sender: expected to submit ", expected, " but did ", got);
if (got == 0) {
if (stopping) {
// assume some kind of cancel issue?
expected--;
} else {
die("literally sent nothing, wanted ", expected);
}
}
}
// log("submitted ", got);
expected -= got;
}
}
void loop(std::atomic<bool>* should_shutdown) override {
RxStats rx_stats{name()};
struct __kernel_timespec timeout;
timeout.tv_sec = 1;
timeout.tv_nsec = 0;
if (rxCfg_.register_ring) {
io_uring_register_ring_fd(&ring);
}
while (socks() || !stopping) {
provideBuffers(false /* maybe we should force? */);
submit();
rx_stats.startWait();
int wait_res = checkedErrno(
io_uring_wait_cqe_timeout(&ring, &cqes_[0], &timeout),
"wait_cqe_timeout");
rx_stats.doneWait();
if (!wait_res) {
rx_stats.doneWait();
processCqe(cqes_[0]);
io_uring_cqe_seen(&ring, cqes_[0]);
}
if (should_shutdown->load() || globalShouldShutdown.load()) {
if (stopping) {
// eh we gave it a good try
break;
}
vlog("stopping");
stop();
vlog("stopped");
timeout.tv_sec = 0;
timeout.tv_nsec = 100000000;
}
int cqe_count;
int loop_count = 0;
do {
cqe_count = io_uring_peek_batch_cqe(&ring, cqes_.data(), cqes_.size());
for (int i = 0; i < cqe_count; i++) {
processCqe(cqes_[i]);
}
io_uring_cq_advance(&ring, cqe_count);
} while (cqe_count > 0 && ++loop_count < rxCfg_.max_cqe_loop);
if (!cqe_count && stopping) {
vlog("processed ", cqe_count, " socks()=", socks());
}
if (cfg_.print_rx_stats) {
bool const is_overflow =
IO_URING_READ_ONCE(*ring.sq.kflags) & IORING_SQ_CQ_OVERFLOW;
rx_stats.doneLoop(
bytesRx_, requestsRx_, is_overflow
);
}
}
}
void stop() override {
stopping = true;
for (auto& l : listenSocks_) {
l->close();
}
}
int nextFdIdx() {
int ret = nextFdIdx_++;
if (ret >= rxCfg_.fixed_file_count) {
die("too many files, limit is ", ret);
}
return ret;
}
static inline void* tag(void* ptr, int x) {
size_t uptr;
memcpy(&uptr, &ptr, sizeof(size_t));
#ifndef NDEBUG
if (uptr & (size_t)0x0f) {
die("bad ptr");
}
if (x > 4) {
die("bad tag");
}
#endif
return (void*)(uptr | x);
}
template <class T>
static T* untag(size_t ptr) {
return (T*)(ptr & ~((size_t)0x0f));
}
static int get_tag(uint64_t ptr) {
return (int)(ptr & 0x0f);
}
Config cfg_;
IoUringRxConfig rxCfg_;
int expected = 0;
bool stopping = false;
struct io_uring ring;
BufferProvider buffers_;
std::vector<std::unique_ptr<ListenSock>> listenSocks_;
std::vector<struct io_uring_cqe*> cqes_;
int listeners_ = 0;
uint32_t enobuffCount_ = 0;
int nextFdIdx_ = 0;
};