-
Notifications
You must be signed in to change notification settings - Fork 407
/
proxy.c
2528 lines (2180 loc) · 64.6 KB
/
proxy.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
/* SPDX-License-Identifier: MIT */
/*
* Sample program that can act either as a packet sink, where it just receives
* packets and doesn't do anything with them, or it can act as a proxy where it
* receives packets and then sends them to a new destination. The proxy can
* be unidirectional (-B0), or bi-direction (-B1).
*
* Examples:
*
* Act as a proxy, listening on port 4444, and send data to 192.168.2.6 on port
* 4445. Use multishot receive, DEFER_TASKRUN, and fixed files
*
* ./proxy -m1 -r4444 -H 192.168.2.6 -p4445
*
* Same as above, but utilize send bundles (-C1, requires -u1 send_ring) as well
* with ring provided send buffers, and recv bundles (-c1).
*
* ./proxy -m1 -c1 -u1 -C1 -r4444 -H 192.168.2.6 -p4445
*
* Act as a bi-directional proxy, listening on port 8888, and send data back
* and forth between host and 192.168.2.6 on port 22. Use multishot receive,
* DEFER_TASKRUN, fixed files, and buffers of size 1500.
*
* ./proxy -m1 -B1 -b1500 -r8888 -H 192.168.2.6 -p22
*
* Act a sink, listening on port 4445, using multishot receive, DEFER_TASKRUN,
* and fixed files:
*
* ./proxy -m1 -s1 -r4445
*
* Run with -h to see a list of options, and their defaults.
*
* (C) 2024 Jens Axboe <[email protected]>
*
*/
#include <fcntl.h>
#include <stdint.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>
#include <sys/mman.h>
#include <linux/mman.h>
#include <locale.h>
#include <assert.h>
#include <pthread.h>
#include <liburing.h>
#include "proxy.h"
#include "helpers.h"
/*
* Will go away once/if bundles are upstreamed and we put the generic
* definitions in the kernel header.
*/
#ifndef IORING_RECVSEND_BUNDLE
#define IORING_RECVSEND_BUNDLE (1U << 4)
#endif
#ifndef IORING_FEAT_SEND_BUF_SELECT
#define IORING_FEAT_SEND_BUF_SELECT (1U << 14)
#endif
static int cur_bgid = 1;
static int nr_conns;
static int open_conns;
static long page_size;
static unsigned long event_loops;
static unsigned long events;
static int recv_mshot = 1;
static int sqpoll;
static int defer_tw = 1;
static int is_sink;
static int fixed_files = 1;
static char *host = "192.168.3.2";
static int send_port = 4445;
static int receive_port = 4444;
static int buf_size = 32;
static int buf_ring_inc;
static int bidi;
static int ipv6;
static int napi;
static int napi_timeout;
static int wait_batch = 1;
static int wait_usec = 1000000;
static int rcv_msg;
static int snd_msg;
static int snd_zc;
static int send_ring = -1;
static int snd_bundle;
static int rcv_bundle;
static int use_huge;
static int ext_stat;
static int verbose;
static int nr_bufs = 256;
static int br_mask;
static int ring_size = 128;
static pthread_mutex_t thread_lock;
static struct timeval last_housekeeping;
/*
* For sendmsg/recvmsg. recvmsg just has a single vec, sendmsg will have
* two vecs - one that is currently submitted and being sent, and one that
* is being prepared. When a new sendmsg is issued, we'll swap which one we
* use. For send, even though we don't pass in the iovec itself, we use the
* vec to serialize the sends to avoid reordering.
*/
struct msg_vec {
struct iovec *iov;
/* length of allocated vec */
int vec_size;
/* length currently being used */
int iov_len;
/* only for send, current index we're processing */
int cur_iov;
};
struct io_msg {
struct msghdr msg;
struct msg_vec vecs[2];
/* current msg_vec being prepared */
int vec_index;
};
/*
* Per socket stats per connection. For bi-directional, we'll have both
* sends and receives on each socket, this helps track them separately.
* For sink or one directional, each of the two stats will be only sends
* or receives, not both.
*/
struct conn_dir {
int index;
int pending_shutdown;
int pending_send;
int pending_recv;
int snd_notif;
int out_buffers;
int rcv, rcv_shrt, rcv_enobufs, rcv_mshot;
int snd, snd_shrt, snd_enobufs, snd_busy, snd_mshot;
int snd_next_bid;
int rcv_next_bid;
int *rcv_bucket;
int *snd_bucket;
unsigned long in_bytes, out_bytes;
/* only ever have a single recv pending */
struct io_msg io_rcv_msg;
/* one send that is inflight, and one being prepared for the next one */
struct io_msg io_snd_msg;
};
enum {
CONN_F_STARTED = 1,
CONN_F_DISCONNECTING = 2,
CONN_F_DISCONNECTED = 4,
CONN_F_PENDING_SHUTDOWN = 8,
CONN_F_STATS_SHOWN = 16,
CONN_F_END_TIME = 32,
CONN_F_REAPED = 64,
};
/*
* buffer ring belonging to a connection
*/
struct conn_buf_ring {
struct io_uring_buf_ring *br;
void *buf;
int bgid;
};
struct conn {
struct io_uring ring;
/* receive side buffer ring, new data arrives here */
struct conn_buf_ring in_br;
/* if send_ring is used, outgoing data to send */
struct conn_buf_ring out_br;
int tid;
int in_fd, out_fd;
int pending_cancels;
int flags;
struct conn_dir cd[2];
struct timeval start_time, end_time;
union {
struct sockaddr_in addr;
struct sockaddr_in6 addr6;
};
pthread_t thread;
pthread_barrier_t startup_barrier;
};
#define MAX_CONNS 1024
static struct conn conns[MAX_CONNS];
#define vlog(str, ...) do { \
if (verbose) \
printf(str, ##__VA_ARGS__); \
} while (0)
static int prep_next_send(struct io_uring *ring, struct conn *c,
struct conn_dir *cd, int fd);
static void *thread_main(void *data);
static struct conn *cqe_to_conn(struct io_uring_cqe *cqe)
{
struct userdata ud = { .val = cqe->user_data };
return &conns[ud.op_tid & TID_MASK];
}
static struct conn_dir *cqe_to_conn_dir(struct conn *c,
struct io_uring_cqe *cqe)
{
int fd = cqe_to_fd(cqe);
return &c->cd[fd != c->in_fd];
}
static int other_dir_fd(struct conn *c, int fd)
{
if (c->in_fd == fd)
return c->out_fd;
return c->in_fd;
}
/* currently active msg_vec */
static struct msg_vec *msg_vec(struct io_msg *imsg)
{
return &imsg->vecs[imsg->vec_index];
}
static struct msg_vec *snd_msg_vec(struct conn_dir *cd)
{
return msg_vec(&cd->io_snd_msg);
}
/*
* Goes from accept new connection -> create socket, connect to end
* point, prepare recv, on receive do send (unless sink). If either ends
* disconnects, we transition to shutdown and then close.
*/
enum {
__ACCEPT = 1,
__SOCK = 2,
__CONNECT = 3,
__RECV = 4,
__RECVMSG = 5,
__SEND = 6,
__SENDMSG = 7,
__SHUTDOWN = 8,
__CANCEL = 9,
__CLOSE = 10,
__FD_PASS = 11,
__NOP = 12,
__STOP = 13,
};
struct error_handler {
const char *name;
int (*error_fn)(struct error_handler *, struct io_uring *, struct io_uring_cqe *);
};
static int recv_error(struct error_handler *err, struct io_uring *ring,
struct io_uring_cqe *cqe);
static int send_error(struct error_handler *err, struct io_uring *ring,
struct io_uring_cqe *cqe);
static int default_error(struct error_handler *err,
struct io_uring __attribute__((__unused__)) *ring,
struct io_uring_cqe *cqe)
{
struct conn *c = cqe_to_conn(cqe);
fprintf(stderr, "%d: %s error %s\n", c->tid, err->name, strerror(-cqe->res));
fprintf(stderr, "fd=%d, bid=%d\n", cqe_to_fd(cqe), cqe_to_bid(cqe));
return 1;
}
/*
* Move error handling out of the normal handling path, cleanly separating
* them. If an opcode doesn't need any error handling, set it to NULL. If
* it wants to stop the connection at that point and not do anything else,
* then the default handler can be used. Only receive has proper error
* handling, as we can get -ENOBUFS which is not a fatal condition. It just
* means we need to wait on buffer replenishing before re-arming the receive.
*/
static struct error_handler error_handlers[] = {
{ .name = "NULL", .error_fn = NULL, },
{ .name = "ACCEPT", .error_fn = default_error, },
{ .name = "SOCK", .error_fn = default_error, },
{ .name = "CONNECT", .error_fn = default_error, },
{ .name = "RECV", .error_fn = recv_error, },
{ .name = "RECVMSG", .error_fn = recv_error, },
{ .name = "SEND", .error_fn = send_error, },
{ .name = "SENDMSG", .error_fn = send_error, },
{ .name = "SHUTDOWN", .error_fn = NULL, },
{ .name = "CANCEL", .error_fn = NULL, },
{ .name = "CLOSE", .error_fn = NULL, },
{ .name = "FD_PASS", .error_fn = default_error, },
{ .name = "NOP", .error_fn = NULL, },
{ .name = "STOP", .error_fn = default_error, },
};
static void free_buffer_ring(struct io_uring *ring, struct conn_buf_ring *cbr)
{
if (!cbr->br)
return;
io_uring_free_buf_ring(ring, cbr->br, nr_bufs, cbr->bgid);
cbr->br = NULL;
if (use_huge)
munmap(cbr->buf, buf_size * nr_bufs);
else
free(cbr->buf);
}
static void free_buffer_rings(struct io_uring *ring, struct conn *c)
{
free_buffer_ring(ring, &c->in_br);
free_buffer_ring(ring, &c->out_br);
}
/*
* Setup a ring provided buffer ring for each connection. If we get -ENOBUFS
* on receive, for multishot receive we'll wait for half the provided buffers
* to be returned by pending sends, then re-arm the multishot receive. If
* this happens too frequently (see enobufs= stat), then the ring size is
* likely too small. Use -nXX to make it bigger. See recv_enobufs().
*
* The alternative here would be to use the older style provided buffers,
* where you simply setup a buffer group and use SQEs with
* io_urign_prep_provide_buffers() to add to the pool. But that approach is
* slower and has been deprecated by using the faster ring provided buffers.
*/
static int setup_recv_ring(struct io_uring *ring, struct conn *c)
{
struct conn_buf_ring *cbr = &c->in_br;
int br_flags = 0;
int ret, i;
size_t len;
void *ptr;
len = buf_size * nr_bufs;
if (use_huge) {
cbr->buf = mmap(NULL, len, PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_HUGETLB|MAP_HUGE_2MB|MAP_ANONYMOUS,
-1, 0);
if (cbr->buf == MAP_FAILED) {
perror("mmap");
return 1;
}
} else {
if (posix_memalign(&cbr->buf, page_size, len)) {
perror("posix memalign");
return 1;
}
}
if (buf_ring_inc)
br_flags = IOU_PBUF_RING_INC;
cbr->br = io_uring_setup_buf_ring(ring, nr_bufs, cbr->bgid, br_flags, &ret);
if (!cbr->br) {
fprintf(stderr, "Buffer ring register failed %d\n", ret);
return 1;
}
ptr = cbr->buf;
for (i = 0; i < nr_bufs; i++) {
vlog("%d: add bid %d, data %p\n", c->tid, i, ptr);
io_uring_buf_ring_add(cbr->br, ptr, buf_size, i, br_mask, i);
ptr += buf_size;
}
io_uring_buf_ring_advance(cbr->br, nr_bufs);
printf("%d: recv buffer ring bgid %d, bufs %d\n", c->tid, cbr->bgid, nr_bufs);
return 0;
}
/*
* If 'send_ring' is used and the kernel supports it, we can skip serializing
* sends as the data will be ordered regardless. This reduces the send handling
* complexity, as buffers can always be added to the outgoing ring and will be
* processed in the order in which they were added.
*/
static int setup_send_ring(struct io_uring *ring, struct conn *c)
{
struct conn_buf_ring *cbr = &c->out_br;
int br_flags = 0;
int ret;
if (buf_ring_inc)
br_flags = IOU_PBUF_RING_INC;
cbr->br = io_uring_setup_buf_ring(ring, nr_bufs, cbr->bgid, br_flags, &ret);
if (!cbr->br) {
fprintf(stderr, "Buffer ring register failed %d\n", ret);
return 1;
}
printf("%d: send buffer ring bgid %d, bufs %d\n", c->tid, cbr->bgid, nr_bufs);
return 0;
}
static int setup_send_zc(struct io_uring *ring, struct conn *c)
{
struct iovec *iovs;
void *buf;
int i, ret;
if (snd_msg)
return 0;
buf = c->in_br.buf;
iovs = calloc(nr_bufs, sizeof(struct iovec));
for (i = 0; i < nr_bufs; i++) {
iovs[i].iov_base = buf;
iovs[i].iov_len = buf_size;
buf += buf_size;
}
ret = io_uring_register_buffers(ring, iovs, nr_bufs);
if (ret) {
fprintf(stderr, "failed registering buffers: %d\n", ret);
free(iovs);
return ret;
}
free(iovs);
return 0;
}
/*
* Setup an input and output buffer ring.
*/
static int setup_buffer_rings(struct io_uring *ring, struct conn *c)
{
int ret;
/* no locking needed on cur_bgid, parent serializes setup */
c->in_br.bgid = cur_bgid++;
c->out_br.bgid = cur_bgid++;
c->out_br.br = NULL;
ret = setup_recv_ring(ring, c);
if (ret)
return ret;
if (is_sink)
return 0;
if (snd_zc) {
ret = setup_send_zc(ring, c);
if (ret)
return ret;
}
if (send_ring) {
ret = setup_send_ring(ring, c);
if (ret) {
free_buffer_ring(ring, &c->in_br);
return ret;
}
}
return 0;
}
struct bucket_stat {
int nr_packets;
int count;
};
static int stat_cmp(const void *p1, const void *p2)
{
const struct bucket_stat *b1 = p1;
const struct bucket_stat *b2 = p2;
if (b1->count < b2->count)
return 1;
else if (b1->count > b2->count)
return -1;
return 0;
}
static void show_buckets(struct conn_dir *cd)
{
unsigned long snd_total, rcv_total;
struct bucket_stat *rstat, *sstat;
int i;
if (!cd->rcv_bucket || !cd->snd_bucket)
return;
rstat = calloc(nr_bufs + 1, sizeof(struct bucket_stat));
sstat = calloc(nr_bufs + 1, sizeof(struct bucket_stat));
snd_total = rcv_total = 0;
for (i = 0; i <= nr_bufs; i++) {
snd_total += cd->snd_bucket[i];
sstat[i].nr_packets = i;
sstat[i].count = cd->snd_bucket[i];
rcv_total += cd->rcv_bucket[i];
rstat[i].nr_packets = i;
rstat[i].count = cd->rcv_bucket[i];
}
if (!snd_total && !rcv_total) {
free(sstat);
free(rstat);
}
if (snd_total)
qsort(sstat, nr_bufs, sizeof(struct bucket_stat), stat_cmp);
if (rcv_total)
qsort(rstat, nr_bufs, sizeof(struct bucket_stat), stat_cmp);
printf("\t Packets per recv/send:\n");
for (i = 0; i <= nr_bufs; i++) {
double snd_prc = 0.0, rcv_prc = 0.0;
if (!rstat[i].count && !sstat[i].count)
continue;
if (rstat[i].count)
rcv_prc = 100.0 * (rstat[i].count / (double) rcv_total);
if (sstat[i].count)
snd_prc = 100.0 * (sstat[i].count / (double) snd_total);
printf("\t bucket(%3d/%3d): rcv=%u (%.2f%%) snd=%u (%.2f%%)\n",
rstat[i].nr_packets, sstat[i].nr_packets,
rstat[i].count, rcv_prc,
sstat[i].count, snd_prc);
}
free(sstat);
free(rstat);
}
static void __show_stats(struct conn *c)
{
unsigned long msec, qps;
unsigned long bytes, bw;
struct conn_dir *cd;
int i;
if (c->flags & (CONN_F_STATS_SHOWN | CONN_F_REAPED))
return;
if (!(c->flags & CONN_F_STARTED))
return;
if (!(c->flags & CONN_F_END_TIME))
gettimeofday(&c->end_time, NULL);
msec = (c->end_time.tv_sec - c->start_time.tv_sec) * 1000;
msec += (c->end_time.tv_usec - c->start_time.tv_usec) / 1000;
qps = 0;
for (i = 0; i < 2; i++)
qps += c->cd[i].rcv + c->cd[i].snd;
if (!qps)
return;
if (msec)
qps = (qps * 1000) / msec;
printf("Conn %d/(in_fd=%d, out_fd=%d): qps=%lu, msec=%lu\n", c->tid,
c->in_fd, c->out_fd, qps, msec);
bytes = 0;
for (i = 0; i < 2; i++) {
cd = &c->cd[i];
if (!cd->in_bytes && !cd->out_bytes && !cd->snd && !cd->rcv)
continue;
bytes += cd->in_bytes;
bytes += cd->out_bytes;
printf("\t%3d: rcv=%u (short=%u, enobufs=%d), snd=%u (short=%u,"
" busy=%u, enobufs=%d)\n", i, cd->rcv, cd->rcv_shrt,
cd->rcv_enobufs, cd->snd, cd->snd_shrt, cd->snd_busy,
cd->snd_enobufs);
printf("\t : in_bytes=%lu (Kb %lu), out_bytes=%lu (Kb %lu)\n",
cd->in_bytes, cd->in_bytes >> 10,
cd->out_bytes, cd->out_bytes >> 10);
printf("\t : mshot_rcv=%d, mshot_snd=%d\n", cd->rcv_mshot,
cd->snd_mshot);
show_buckets(cd);
}
if (msec) {
bytes *= 8UL;
bw = bytes / 1000;
bw /= msec;
printf("\tBW=%'luMbit\n", bw);
}
c->flags |= CONN_F_STATS_SHOWN;
}
static void show_stats(void)
{
float events_per_loop = 0.0;
static int stats_shown;
int i;
if (stats_shown)
return;
if (events)
events_per_loop = (float) events / (float) event_loops;
printf("Event loops: %lu, events %lu, events per loop %.2f\n", event_loops,
events, events_per_loop);
for (i = 0; i < MAX_CONNS; i++) {
struct conn *c = &conns[i];
__show_stats(c);
}
stats_shown = 1;
}
static void sig_int(int __attribute__((__unused__)) sig)
{
printf("\n");
show_stats();
exit(1);
}
/*
* Special cased for SQPOLL only, as we don't control when SQEs are consumed if
* that is used. Hence we may need to wait for the SQPOLL thread to keep up
* until we can get a new SQE. All other cases will break immediately, with a
* fresh SQE.
*
* If we grossly undersized our SQ ring, getting a NULL sqe can happen even
* for the !SQPOLL case if we're handling a lot of CQEs in our event loop
* and multishot isn't used. We can do io_uring_submit() to flush what we
* have here. Only caveat here is that if linked requests are used, SQEs
* would need to be allocated upfront as a link chain is only valid within
* a single submission cycle.
*/
static struct io_uring_sqe *get_sqe(struct io_uring *ring)
{
struct io_uring_sqe *sqe;
do {
sqe = io_uring_get_sqe(ring);
if (sqe)
break;
if (!sqpoll)
io_uring_submit(ring);
else
io_uring_sqring_wait(ring);
} while (1);
return sqe;
}
/*
* See __encode_userdata() for how we encode sqe->user_data, which is passed
* back as cqe->user_data at completion time.
*/
static void encode_userdata(struct io_uring_sqe *sqe, struct conn *c, int op,
int bid, int fd)
{
__encode_userdata(sqe, c->tid, op, bid, fd);
}
static void __submit_receive(struct io_uring *ring, struct conn *c,
struct conn_dir *cd, int fd)
{
struct conn_buf_ring *cbr = &c->in_br;
struct io_uring_sqe *sqe;
vlog("%d: submit receive fd=%d\n", c->tid, fd);
assert(!cd->pending_recv);
cd->pending_recv = 1;
/*
* For both recv and multishot receive, we use the ring provided
* buffers. These are handed to the application ahead of time, and
* are consumed when a receive triggers. Note that the address and
* length of the receive are set to NULL/0, and we assign the
* sqe->buf_group to tell the kernel which buffer group ID to pick
* a buffer from. Finally, IOSQE_BUFFER_SELECT is set to tell the
* kernel that we want a buffer picked for this request, we are not
* passing one in with the request.
*/
sqe = get_sqe(ring);
if (rcv_msg) {
struct io_msg *imsg = &cd->io_rcv_msg;
struct msghdr *msg = &imsg->msg;
memset(msg, 0, sizeof(*msg));
msg->msg_iov = msg_vec(imsg)->iov;
msg->msg_iovlen = msg_vec(imsg)->iov_len;
if (recv_mshot) {
cd->rcv_mshot++;
io_uring_prep_recvmsg_multishot(sqe, fd, &imsg->msg, 0);
} else {
io_uring_prep_recvmsg(sqe, fd, &imsg->msg, 0);
}
} else {
if (recv_mshot) {
cd->rcv_mshot++;
io_uring_prep_recv_multishot(sqe, fd, NULL, 0, 0);
} else {
io_uring_prep_recv(sqe, fd, NULL, 0, 0);
}
}
encode_userdata(sqe, c, __RECV, 0, fd);
sqe->buf_group = cbr->bgid;
sqe->flags |= IOSQE_BUFFER_SELECT;
if (fixed_files)
sqe->flags |= IOSQE_FIXED_FILE;
if (rcv_bundle)
sqe->ioprio |= IORING_RECVSEND_BUNDLE;
}
/*
* One directional just arms receive on our in_fd
*/
static void submit_receive(struct io_uring *ring, struct conn *c)
{
__submit_receive(ring, c, &c->cd[0], c->in_fd);
}
/*
* Bi-directional arms receive on both in and out fd
*/
static void submit_bidi_receive(struct io_uring *ring, struct conn *c)
{
__submit_receive(ring, c, &c->cd[0], c->in_fd);
__submit_receive(ring, c, &c->cd[1], c->out_fd);
}
/*
* We hit -ENOBUFS, which means that we ran out of buffers in our current
* provided buffer group. This can happen if there's an imbalance between the
* receives coming in and the sends being processed, particularly with multishot
* receive as they can trigger very quickly. If this happens, defer arming a
* new receive until we've replenished half of the buffer pool by processing
* pending sends.
*/
static void recv_enobufs(struct io_uring *ring, struct conn *c,
struct conn_dir *cd, int fd)
{
vlog("%d: enobufs hit\n", c->tid);
cd->rcv_enobufs++;
/*
* If we're a sink, mark rcv as rearm. If we're not, then mark us as
* needing a rearm for receive and send. The completing send will
* kick the recv rearm.
*/
if (!is_sink) {
int do_recv_arm = 1;
if (!cd->pending_send)
do_recv_arm = !prep_next_send(ring, c, cd, fd);
if (do_recv_arm)
__submit_receive(ring, c, &c->cd[0], c->in_fd);
} else {
__submit_receive(ring, c, &c->cd[0], c->in_fd);
}
}
/*
* Kill this socket - submit a shutdown and link a close to it. We don't
* care about shutdown status, so mark it as not needing to post a CQE unless
* it fails.
*/
static void queue_shutdown_close(struct io_uring *ring, struct conn *c, int fd)
{
struct io_uring_sqe *sqe1, *sqe2;
/*
* On the off chance that we run out of SQEs after the first one,
* grab two upfront. This it to prevent our link not working if
* get_sqe() ends up doing submissions to free up an SQE, as links
* are not valid across separate submissions.
*/
sqe1 = get_sqe(ring);
sqe2 = get_sqe(ring);
io_uring_prep_shutdown(sqe1, fd, SHUT_RDWR);
if (fixed_files)
sqe1->flags |= IOSQE_FIXED_FILE;
sqe1->flags |= IOSQE_IO_LINK | IOSQE_CQE_SKIP_SUCCESS;
encode_userdata(sqe1, c, __SHUTDOWN, 0, fd);
if (fixed_files)
io_uring_prep_close_direct(sqe2, fd);
else
io_uring_prep_close(sqe2, fd);
encode_userdata(sqe2, c, __CLOSE, 0, fd);
}
/*
* This connection is going away, queue a cancel for any pending recv, for
* example, we have pending for this ring. For completeness, we issue a cancel
* for any request we have pending for both in_fd and out_fd.
*/
static void queue_cancel(struct io_uring *ring, struct conn *c)
{
struct io_uring_sqe *sqe;
int flags = 0;
if (fixed_files)
flags |= IORING_ASYNC_CANCEL_FD_FIXED;
sqe = get_sqe(ring);
io_uring_prep_cancel_fd(sqe, c->in_fd, flags);
encode_userdata(sqe, c, __CANCEL, 0, c->in_fd);
c->pending_cancels++;
if (c->out_fd != -1) {
sqe = get_sqe(ring);
io_uring_prep_cancel_fd(sqe, c->out_fd, flags);
encode_userdata(sqe, c, __CANCEL, 0, c->out_fd);
c->pending_cancels++;
}
io_uring_submit(ring);
}
static int pending_shutdown(struct conn *c)
{
return c->cd[0].pending_shutdown + c->cd[1].pending_shutdown;
}
static bool should_shutdown(struct conn *c)
{
int i;
if (!pending_shutdown(c))
return false;
if (is_sink)
return true;
if (!bidi)
return c->cd[0].in_bytes == c->cd[1].out_bytes;
for (i = 0; i < 2; i++) {
if (c->cd[0].rcv != c->cd[1].snd)
return false;
if (c->cd[1].rcv != c->cd[0].snd)
return false;
}
return true;
}
/*
* Close this connection - send a ring message to the connection with intent
* to stop. When the client gets the message, it will initiate the stop.
*/
static void __close_conn(struct io_uring *ring, struct conn *c)
{
struct io_uring_sqe *sqe;
uint64_t user_data;
printf("Client %d: queueing stop\n", c->tid);
user_data = __raw_encode(c->tid, __STOP, 0, 0);
sqe = io_uring_get_sqe(ring);
io_uring_prep_msg_ring(sqe, c->ring.ring_fd, 0, user_data, 0);
encode_userdata(sqe, c, __NOP, 0, 0);
io_uring_submit(ring);
}
static void close_cd(struct conn *c, struct conn_dir *cd)
{
cd->pending_shutdown = 1;
if (cd->pending_send)
return;
if (!(c->flags & CONN_F_PENDING_SHUTDOWN)) {
gettimeofday(&c->end_time, NULL);
c->flags |= CONN_F_PENDING_SHUTDOWN | CONN_F_END_TIME;
}
}
/*
* We're done with this buffer, add it back to our pool so the kernel is
* free to use it again.
*/
static int replenish_buffer(struct conn_buf_ring *cbr, int bid, int offset)
{
void *this_buf = cbr->buf + bid * buf_size;
assert(bid < nr_bufs);
io_uring_buf_ring_add(cbr->br, this_buf, buf_size, bid, br_mask, offset);
return buf_size;
}
/*
* Iterate buffers from '*bid' and with a total size of 'bytes' and add them
* back to our receive ring so they can be reused for new receives.
*/
static int replenish_buffers(struct conn *c, int *bid, int bytes)
{
struct conn_buf_ring *cbr = &c->in_br;
int nr_packets = 0;
while (bytes) {
int this_len = replenish_buffer(cbr, *bid, nr_packets);
if (this_len > bytes)
this_len = bytes;
bytes -= this_len;
*bid = (*bid + 1) & (nr_bufs - 1);
nr_packets++;
}
io_uring_buf_ring_advance(cbr->br, nr_packets);
return nr_packets;
}
static void free_mvec(struct msg_vec *mvec)
{
free(mvec->iov);
mvec->iov = NULL;
}
static void init_mvec(struct msg_vec *mvec)
{
memset(mvec, 0, sizeof(*mvec));
mvec->iov = malloc(sizeof(struct iovec));
mvec->vec_size = 1;
}
static void init_msgs(struct conn_dir *cd)
{
memset(&cd->io_snd_msg, 0, sizeof(cd->io_snd_msg));
memset(&cd->io_rcv_msg, 0, sizeof(cd->io_rcv_msg));
init_mvec(&cd->io_snd_msg.vecs[0]);
init_mvec(&cd->io_snd_msg.vecs[1]);
init_mvec(&cd->io_rcv_msg.vecs[0]);
}
static void free_msgs(struct conn_dir *cd)
{
free_mvec(&cd->io_snd_msg.vecs[0]);
free_mvec(&cd->io_snd_msg.vecs[1]);
free_mvec(&cd->io_rcv_msg.vecs[0]);
}
/*
* Multishot accept completion triggered. If we're acting as a sink, we're
* good to go. Just issue a receive for that case. If we're acting as a proxy,
* then start opening a socket that we can use to connect to the other end.
*/
static int handle_accept(struct io_uring *ring, struct io_uring_cqe *cqe)
{
struct conn *c;
int i;
if (nr_conns == MAX_CONNS) {
fprintf(stderr, "max clients reached %d\n", nr_conns);
return 1;
}
/* main thread handles this, which is obviously serialized */
c = &conns[nr_conns];
c->tid = nr_conns++;
c->in_fd = -1;
c->out_fd = -1;
for (i = 0; i < 2; i++) {
struct conn_dir *cd = &c->cd[i];
cd->index = i;
cd->snd_next_bid = -1;
cd->rcv_next_bid = -1;
if (ext_stat) {
cd->rcv_bucket = calloc(nr_bufs + 1, sizeof(int));
cd->snd_bucket = calloc(nr_bufs + 1, sizeof(int));
}
init_msgs(cd);
}