-
Notifications
You must be signed in to change notification settings - Fork 3
/
netbench.cpp
2273 lines (2023 loc) · 61.5 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 <numeric>
#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/mman.h>
#include <sys/socket.h>
#include <sys/times.h>
#include "control.h"
#include "sender.h"
#include "socket.h"
#include "util.h"
namespace po = boost::program_options;
namespace {
#ifndef __NR_io_uring_enter
static constexpr int __NR_io_uring_enter = 426;
#endif
#ifndef __NR_io_uring_register
static constexpr int __NR_io_uring_register = 427;
#endif
static inline int ____sys_io_uring_enter2(
int fd,
unsigned to_submit,
unsigned min_complete,
unsigned flags,
sigset_t* sig,
int sz) {
int ret;
ret =
syscall(__NR_io_uring_enter, fd, to_submit, min_complete, flags, sig, sz);
return (ret < 0) ? -errno : ret;
}
} // namespace
/*
* 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;
bool recvmsg = false;
size_t workload = 0;
std::string description;
std::string describe() const {
if (description.empty()) {
return toString();
}
return description;
}
virtual std::string const toString() const {
// only give the important options:
auto is_default = [this](auto RxConfig::*x) {
RxConfig base;
return this->*x == base.*x;
};
return strcat(
is_default(&RxConfig::recvmsg) ? "" : strcat(" recvmsg=", recvmsg),
is_default(&RxConfig::workload) ? "" : strcat(" workload=", workload));
}
};
struct IoUringRxConfig : RxConfig {
bool supports_nonblock_accept = false;
bool register_ring = true;
int provide_buffers = 2;
bool fixed_files = true;
int sqe_count = 64;
int cqe_count = 0;
int max_cqe_loop = 256 * 32;
int provided_buffer_count = 8000;
int fixed_file_count = 16000;
int provided_buffer_low_watermark = -1;
int provided_buffer_compact = 1;
bool huge_pages = false;
int multishot_recv = 1;
bool defer_taskrun = false;
// not for actual user updating, but dependent on the kernel:
unsigned int cqe_skip_success_flag = 0;
std::string const toString() const override {
// only give the important options:
auto is_default = [this](auto IoUringRxConfig::*x) {
IoUringRxConfig base;
return this->*x == base.*x;
};
return strcat(
RxConfig::toString(),
(!is_default(&IoUringRxConfig::fixed_files) ||
!is_default(&IoUringRxConfig::fixed_file_count))
? strcat(
" fixed_files=",
fixed_files ? strcat("1 (count=", fixed_file_count, ")")
: strcat("0"))
: "",
is_default(&IoUringRxConfig::provide_buffers)
? ""
: strcat(" provide_buffers=", provide_buffers),
is_default(&IoUringRxConfig::provided_buffer_count)
? ""
: strcat(" provided_buffer_count=", provided_buffer_count),
is_default(&IoUringRxConfig::sqe_count)
? ""
: strcat(" sqe_count=", sqe_count),
is_default(&IoUringRxConfig::cqe_count)
? ""
: strcat(" cqe_count=", cqe_count),
is_default(&IoUringRxConfig::max_cqe_loop)
? ""
: strcat(" max_cqe_loop=", max_cqe_loop),
is_default(&IoUringRxConfig::huge_pages)
? ""
: strcat(" huge_pages=", huge_pages),
is_default(&IoUringRxConfig::defer_taskrun)
? ""
: strcat(" defer_taskrun=", defer_taskrun),
is_default(&IoUringRxConfig::multishot_recv)
? ""
: strcat(" multishot_recv=", multishot_recv));
}
};
struct EpollRxConfig : RxConfig {
bool batch_send = false;
std::string const toString() const override {
// only give the important options:
auto is_default = [this](auto EpollRxConfig::*x) {
EpollRxConfig base;
return this->*x == base.*x;
};
return strcat(
RxConfig::toString(),
is_default(&EpollRxConfig::batch_send)
? ""
: strcat(" batch_send=", batch_send));
}
};
struct Config {
std::vector<uint16_t> use_port;
uint16_t control_port = 0;
bool client_only = false;
bool server_only = false;
GlobalSendOptions send_options;
bool print_rx_stats = true;
bool print_read_stats = true;
std::vector<std::string> tx;
std::vector<std::string> rx;
};
int mkServerSock(
RxConfig const& rx_cfg,
uint16_t port,
bool const isv6,
int extra_flags) {
int fd = checkedErrno(mkBoundSock(port, isv6, extra_flags));
checkedErrno(listen(fd, rx_cfg.backlog), "listen");
vlog("made sock ", fd, " v6=", isv6, " port=", port);
return fd;
}
std::pair<struct io_uring, IoUringRxConfig> mkIoUring(
IoUringRxConfig const& rx_cfg) {
struct io_uring_params params;
struct io_uring ring;
memset(¶ms, 0, sizeof(params));
// default to Nx 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 ? 128 * rx_cfg.sqe_count : rx_cfg.cqe_count;
unsigned int newer_flags =
IORING_SETUP_SUBMIT_ALL | IORING_SETUP_COOP_TASKRUN;
params.flags = newer_flags;
params.flags |= IORING_SETUP_CQSIZE;
if (rx_cfg.defer_taskrun) {
params.flags |= IORING_SETUP_DEFER_TASKRUN;
params.flags |= IORING_SETUP_SINGLE_ISSUER;
params.flags |= IORING_SETUP_R_DISABLED;
}
params.cq_entries = cqe_count;
int ret = io_uring_queue_init_params(rx_cfg.sqe_count, &ring, ¶ms);
if (ret < 0) {
log("trying init again without COOP_TASKRUN or SUBMIT_ALL");
params.flags = params.flags & (~newer_flags);
checkedErrno(
io_uring_queue_init_params(rx_cfg.sqe_count, &ring, ¶ms),
"io_uring_queue_init_params");
}
if (rx_cfg.register_ring) {
checkedErrno(io_uring_register_ring_fd(&ring), "register ring fd");
}
auto ret_cfg = rx_cfg;
if (params.features & IORING_FEAT_CQE_SKIP) {
ret_cfg.cqe_skip_success_flag = IOSQE_CQE_SKIP_SUCCESS;
}
return std::make_pair(ring, std::move(ret_cfg));
}
void runWorkload(RxConfig const& cfg, uint32_t consumed) {
if (!cfg.workload)
return;
runWorkload(consumed, cfg.workload);
}
struct ConsumeResults {
size_t to_write = 0;
uint32_t count = 0;
ConsumeResults& operator+=(ConsumeResults const& rhs) {
to_write += rhs.to_write;
count += rhs.count;
return *this;
}
};
// 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
ConsumeResults consume(char const* data, size_t n) {
ConsumeResults ret;
while (n > 0) {
so_far += n;
if (!is_reading[0]) {
if (likely(n >= sizeof(is_reading) && size_buff_have == 0)) {
size_buff_have = sizeof(is_reading);
memcpy(&is_reading, data, sizeof(is_reading));
} else {
uint32_t size_buff_add =
std::min<uint32_t>(n, sizeof(is_reading) - size_buff_have);
memcpy(size_buff + size_buff_have, data, size_buff_add);
size_buff_have += size_buff_add;
if (size_buff_have >= sizeof(is_reading)) {
memcpy(&is_reading, size_buff, sizeof(is_reading));
}
}
}
if (is_reading[0] && so_far >= is_reading[0] + sizeof(is_reading)) {
data += n;
n = so_far - (is_reading[0] + sizeof(is_reading));
ret.to_write += is_reading[1];
ret.count++;
so_far = size_buff_have = 0;
memset(&is_reading, 0, sizeof(is_reading));
} else {
break;
}
}
return ret;
}
uint32_t size_buff_have = 0;
std::array<uint32_t, 2> is_reading = {{0}};
char size_buff[sizeof(is_reading)];
uint32_t so_far = 0;
};
class RxStats {
public:
RxStats(std::string const& name, bool countReads)
: name_(name), countReads_(countReads) {
auto const now = std::chrono::steady_clock::now();
started_ = lastStats_ = now;
lastClock_ = checkedErrno(times(&lastTimes_), "initial times");
if (countReads_) {
reads_.reserve(32000);
}
}
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,
unsigned int reads,
bool is_overflow = false) {
auto const now = std::chrono::steady_clock::now();
auto const duration = now - lastStats_;
++loops_;
if (is_overflow) {
++overflows_;
}
if (countReads_) {
reads_.push_back(reads);
}
if (duration >= std::chrono::seconds(1)) {
doLog(bytes, requests, now, duration);
}
}
private:
std::chrono::milliseconds getMs(clock_t from, clock_t to) {
return std::chrono::milliseconds(
to <= from ? 0llu : (((to - from) * 1000llu) / ticksPerSecond_));
}
template <size_t N>
int getReadStats(std::array<char, N>& arr) {
if (!reads_.size()) {
return 0;
}
std::sort(reads_.begin(), reads_.end());
size_t tot = std::accumulate(reads_.begin(), reads_.end(), size_t(0));
double avg = tot / (double)reads_.size();
unsigned int p10 = reads_[reads_.size() / 10];
unsigned int p50 = reads_[reads_.size() / 2];
unsigned int p90 = reads_[(int)(reads_.size() * 0.9)];
return snprintf(
arr.data(),
arr.size(),
" read_per_loop: p10=%u p50=%u p90=%u avg=%.2f",
p10,
p50,
p90,
avg);
}
void doLog(
size_t bytes,
size_t requests,
std::chrono::steady_clock::time_point now,
std::chrono::steady_clock::duration duration) {
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 overflows=%lu",
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_,
overflows_);
if (written >= 0) {
std::array<char, 2048> read_stats_buf;
std::string_view read_stats;
if (countReads_) {
read_stats = std::string_view(
read_stats_buf.data(), getReadStats(read_stats_buf));
reads_.clear();
}
log(std::string_view(buff, written), read_stats);
}
}
loops_ = overflows_ = 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_;
bool const countReads_;
std::vector<unsigned int> reads_;
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;
uint64_t overflows_ = 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 start() {}
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 BufferProviderV1 : private boost::noncopyable {
public:
static constexpr int kBgid = 1;
explicit BufferProviderV1(IoUringRxConfig const& rx_cfg)
: sizePerBuffer_(addAlignment(rx_cfg.recv_size)),
lowWatermark_(rx_cfg.provided_buffer_low_watermark) {
auto count = rx_cfg.provided_buffer_count;
buffer_.resize(count * sizePerBuffer_);
for (ssize_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 initialRegister(struct io_uring*) {}
void compact() {
if (toProvide_.size() <= 1) {
return;
} else if (toProvide_.size() == 2) {
// actually a common case due to the way the kernel internals work
if (toProvide_[0].merge(toProvide_[1])) {
toProvide_.pop_back();
}
return;
}
auto was = toProvide_.size();
std::sort(
toProvide_.begin(), toProvide_.end(), [](auto const& a, auto const& b) {
return a.sortable < b.sortable;
});
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);
}
}
toProvide_.swap(toProvide2_);
if (unlikely(isVerbose())) {
vlog("compact() was ", was, " now ", toProvide_.size());
for (auto const& t : toProvide_) {
vlog("...", t.start, " count=", t.count);
}
}
}
void returnIndex(uint16_t 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(uint16_t i) const {
return buffers_[i];
}
private:
static constexpr int kAlignment = 32;
size_t addAlignment(size_t n) {
return kAlignment * ((n + kAlignment - 1) / kAlignment);
}
struct Range {
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
explicit Range(uint16_t idx, uint16_t count = 1)
: count(count), start(idx) {}
#else
explicit Range(uint16_t idx, uint16_t count = 1)
: start(idx), count(count) {}
#endif
union {
struct {
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
uint16_t count;
uint16_t start;
#else
uint16_t start;
uint16_t count;
#endif
};
uint32_t sortable; // big endian might need to swap these around
};
bool merge(uint16_t 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_;
};
class BufferProviderV2 : private boost::noncopyable {
private:
public:
static constexpr int kBgid = 1;
static constexpr size_t kHugePageMask = (1LLU << 21) - 1; // 2MB
static constexpr size_t kBufferAlignMask = 31LLU;
explicit BufferProviderV2(IoUringRxConfig const& rx_cfg)
: count_(rx_cfg.provided_buffer_count),
sizePerBuffer_(addAlignment(rx_cfg.recv_size)) {
ringSize_ = 1;
ringMask_ = 0;
while (ringSize_ < count_) {
ringSize_ *= 2;
}
ringMask_ = io_uring_buf_ring_mask(ringSize_);
int extra_mmap_flags = 0;
char* buffer_base;
ringMemSize_ = ringSize_ * sizeof(struct io_uring_buf);
ringMemSize_ = (ringMemSize_ + kBufferAlignMask) & (~kBufferAlignMask);
bufferMmapSize_ = count_ * sizePerBuffer_ + ringMemSize_;
size_t page_mask = 4095;
if (rx_cfg.huge_pages) {
bufferMmapSize_ = (bufferMmapSize_ + kHugePageMask) & (~kHugePageMask);
extra_mmap_flags |= MAP_HUGETLB;
page_mask = kHugePageMask;
checkHugePages(bufferMmapSize_ / (1 + kHugePageMask));
}
bufferMmap_ = mmap(
NULL,
bufferMmapSize_,
PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE | extra_mmap_flags,
-1,
0);
vlog(
"mmap buffer size=",
bufferMmapSize_,
" ring size=",
ringMemSize_,
" pages=",
bufferMmapSize_ / (1 + page_mask));
if (bufferMmap_ == MAP_FAILED) {
auto errnoCopy = errno;
die("unable to allocate pages of size ",
bufferMmapSize_,
": ",
strerror(errnoCopy));
}
buffer_base = (char*)bufferMmap_ + ringMemSize_;
ring_ = (struct io_uring_buf_ring*)bufferMmap_;
io_uring_buf_ring_init(ring_);
for (size_t i = 0; i < count_; i++) {
buffers_.push_back(buffer_base + i * sizePerBuffer_);
}
if (count_ >= std::numeric_limits<uint16_t>::max()) {
die("buffer count too large: ", count_);
}
for (uint16_t i = 0; i < count_; i++) {
ring_->bufs[i] = {};
populate(ring_->bufs[i], i);
}
tailCached_ = count_;
io_uring_smp_store_release(&ring_->tail, tailCached_);
vlog(
"ring address=",
ring_,
" ring size=",
ringSize_,
" buffer count=",
count_,
" ring_mask=",
ringMask_,
" tail now ",
tailCached_);
}
~BufferProviderV2() {
munmap(bufferMmap_, bufferMmapSize_);
}
size_t count() const {
return count_;
}
size_t sizePerBuffer() const {
return sizePerBuffer_;
}
size_t toProvideCount() const {
return cachedIndices;
}
bool canProvide() const {
return false;
}
bool needsToProvide() const {
return false;
}
void compact() {}
inline void populate(struct io_uring_buf& b, uint16_t i) {
b.bid = i;
b.addr = (__u64)getData(i);
// can we assume kernel doesnt touch len or resv?
b.len = sizePerBuffer_;
// b.resv = 0;
}
void returnIndex(uint16_t i) {
indices[cachedIndices++] = i;
if (likely(cachedIndices < indices.size())) {
return;
}
cachedIndices = 0;
for (uint16_t idx : indices) {
populate(ring_->bufs[(tailCached_ & ringMask_)], idx);
++tailCached_;
}
io_uring_smp_store_release(&ring_->tail, tailCached_);
}
void provide(struct io_uring_sqe*) {}
char const* getData(uint16_t i) const {
return buffers_[i];
}
void initialRegister(struct io_uring* ring) {
struct io_uring_buf_reg reg;
memset(®, 0, sizeof(reg));
reg.ring_addr = (__u64)ring_;
reg.ring_entries = ringSize_;
reg.bgid = kBgid;
checkedErrno(io_uring_register_buf_ring(ring, ®, 0), "register pbuf");
}
private:
static constexpr int kAlignment = 32;
size_t addAlignment(size_t n) {
return kAlignment * ((n + kAlignment - 1) / kAlignment);
}
size_t count_;
size_t sizePerBuffer_;
size_t bufferMmapSize_ = 0;
void* bufferMmap_ = nullptr;
std::vector<char*> buffers_;
uint16_t tailCached_ = 0;
size_t ringMemSize_;
uint32_t ringSize_;
uint32_t ringMask_;
uint32_t cachedIndices = 0;
struct io_uring_buf_ring* ring_;
std::array<uint16_t, 32> indices;
};
static constexpr int kUseBufferProviderFlag = 1;
static constexpr int kUseBufferProviderV2Flag = 2;
int providedBufferIdx(struct io_uring_cqe* cqe) {
if (!(cqe->flags & IORING_CQE_F_BUFFER)) {
return -1;
}
return cqe->flags >> 16;
}
template <size_t ReadSize = 4096, size_t Flags = 0>
struct BasicSock {
static constexpr int kUseBufferProviderVersion =
(Flags & kUseBufferProviderV2Flag) ? 2
: (Flags & kUseBufferProviderFlag) ? 1
: 0;
using TBufferProvider = std::conditional_t<
kUseBufferProviderVersion == 2,
BufferProviderV2,
BufferProviderV1>;
bool isFixedFiles() const {
return cfg_.fixed_files;
}
bool isMultiShotRecv() const {
return cfg_.multishot_recv;
}
explicit BasicSock(IoUringRxConfig const& cfg, int fd) : cfg_(cfg), fd_(fd) {
if (cfg_.recvmsg) {
memset(&recvmsgHdr_, 0, sizeof(recvmsgHdr_));
memset(&recvmsgHdrIoVec_, 0, sizeof(recvmsgHdrIoVec_));
recvmsgHdr_.msg_iov = &recvmsgHdrIoVec_;
recvmsgHdrIoVec_.iov_base = &buff[0];
recvmsgHdrIoVec_.iov_len = ReadSize;
if (isMultiShotRecv() || kUseBufferProviderVersion > 0) {
recvmsgHdr_.msg_iovlen = 0;
} else {
recvmsgHdr_.msg_iovlen = 1;
}
}
}
~BasicSock() {
if (!closed_) {
log("socket not closed at destruct");
}
}
int fd() const {
return fd_;
}
ConsumeResults const& peekSend() {
return do_send;
}
void didSend() {
do_send = {};
}
void addSend(struct io_uring_sqe* sqe, unsigned char* b, uint32_t len) {
io_uring_prep_send(sqe, fd_, b, len, MSG_WAITALL);
if (isFixedFiles()) {
sqe->flags |= IOSQE_FIXED_FILE;
}
sqe->flags |= cfg_.cqe_skip_success_flag;
}
void addRead(struct io_uring_sqe* sqe, TBufferProvider& provider) {
if (kUseBufferProviderVersion) {
size_t const size = isMultiShotRecv() ? 0LLU : provider.sizePerBuffer();
if (cfg_.recvmsg) {
io_uring_prep_recvmsg(sqe, fd_, &recvmsgHdr_, 0);
if (isMultiShotRecv()) {
sqe->ioprio |= IORING_RECV_MULTISHOT;
}
} else {
if (isMultiShotRecv()) {
io_uring_prep_recv_multishot(sqe, fd_, NULL, size, 0);
} else {
io_uring_prep_recv(sqe, fd_, NULL, size, 0);
}
}
sqe->flags |= IOSQE_BUFFER_SELECT;
sqe->buf_group = TBufferProvider::kBgid;
} else if (cfg_.recvmsg) {
io_uring_prep_recvmsg(sqe, fd_, &recvmsgHdr_, 0);
} else {
io_uring_prep_recv(sqe, fd_, &buff[0], sizeof(buff), 0);
}
if (isFixedFiles()) {
sqe->flags |= IOSQE_FIXED_FILE;
}
}
bool closing() const {
return closed_;
}
void doClose() {
closed_ = true;
::close(fd_);
}
void addClose(struct io_uring_sqe* sqe) {
closed_ = true;
if (isFixedFiles())
io_uring_prep_close_direct(sqe, fd_);
else
io_uring_prep_close(sqe, fd_);
}
struct DidReadResult {
explicit DidReadResult(int amount, int idx)
: amount(amount), recycleBufferIdx(idx) {}
int amount;
int recycleBufferIdx;
};
DidReadResult didRead(TBufferProvider& provider, struct io_uring_cqe* cqe) {
// pull remaining data
int res = cqe->res;
if (res <= 0) {
return DidReadResult(res, -1);
}
if (kUseBufferProviderVersion) {
int recycleBufferIdx = providedBufferIdx(cqe);
auto* data = provider.getData(recycleBufferIdx);
if (isMultiShotRecv() && cfg_.recvmsg) {
if (recycleBufferIdx < 0) {
die("bad recycleBufferIdx");
}
if (!data) {
die("bad data");
}
auto* m = io_uring_recvmsg_validate((void*)data, res, &recvmsgHdr_);
if (!m) {
return DidReadResult(0, recycleBufferIdx);
}
res = io_uring_recvmsg_payload_length(m, cqe->res, &recvmsgHdr_);
data = (const char*)io_uring_recvmsg_payload(m, &recvmsgHdr_);
}