-
Notifications
You must be signed in to change notification settings - Fork 103
/
sock.c
1854 lines (1663 loc) · 49.5 KB
/
sock.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
/**
* Synchronous Socket API.
*
* Copyright (C) 2014 NatSys Lab. (info@natsys-lab.com).
* Copyright (C) 2015-2023 Tempesta Technologies, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59
* Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <linux/irq_work.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/tempesta.h>
#include <net/protocol.h>
#include <net/inet_common.h>
#include <net/ip6_route.h>
#undef DEBUG
#if DBG_SS > 0
#define DEBUG DBG_SS
#endif
#include "lib/str.h"
#include "addr.h"
#include "log.h"
#include "procfs.h"
#include "sync_socket.h"
#include "tempesta_fw.h"
#include "work_queue.h"
#include "http_limits.h"
typedef enum {
SS_SEND,
SS_CLOSE,
SS_SHUTDOWN,
} SsAction;
typedef struct {
struct sock *sk;
struct sk_buff *skb_head;
int flags;
SsAction action;
unsigned long __unused[1];
} SsWork;
/**
* Backlog for synchronous close operations. Uses turnstile to keep order with
* ring-buffer work queue. The work queue tail is used as a ticket for the
* turnstile. The backlog is used in slow path if the-ring buffer work queue
* is full.
*
* @head - head of backlog queue;
* @lock - synchronization for the backlog (MPSC);
* @turn - last pop()'ed node ticket value, used to decide where to pop()
* a next item from without locking;
* @size - current backlog queue size, just for statistics;
*/
typedef struct {
struct list_head head;
spinlock_t lock;
long turn;
size_t size;
} SsCloseBacklog;
/**
* Node of close backlog.
*
* @ticket - the work ticket used in turnstile to order items from the
* backlog with ring-buffer items;
* @list - list entry in the backlog;
* @sw - work descriptor to perform.
*/
typedef struct {
long ticket;
struct list_head list;
SsWork sw;
} SsCblNode;
/* Socket states are needed at high support levels. */
#if defined(DEBUG) && (DEBUG >= 2)
static const char *ss_statename[] = {
"Unused", "Established", "Syn Sent", "Syn Recv",
"Fin Wait 1", "Fin Wait 2", "Time Wait", "Close",
"Close Wait", "Last ACK", "Listen", "Closing"
};
#endif
#ifdef CONFIG_DEBUG_SPINLOCK
#define TFW_VALIDATE_SK_LOCK_OWNER(sk) \
BUG_ON(sk->sk_lock.slock.rlock.owner_cpu != raw_smp_processor_id())
#else
#define TFW_VALIDATE_SK_LOCK_OWNER(sk)
#endif
/**
* Constants for active socket operations.
* SS uses downcalls (SS functions calls from Tempesta layer) and upcalls
* (SS callbacks), but all of them are executed in softirq context.
* Meantime, system shutdown is performed in process context.
* So __ss_act_cnt and the constants at the below are used to count number of
* upcalls and downcalls on the fly and synchronize shutdown process with the
* calls: the shutdown process must wait until all the calls finished and
* no new calls can be executed.
*
* __ss_act_cnt is per-CPU, but any given connection can increase it on one CPU
* and decrease on another - that's fine we do use only the sum of all per-CPU
* values.
*
* However, softirqs can call SS down- or upcall any time. Moreover, there could
* be an ingress packet for some Tempesta's socket and it initiates new
* Tempesta's calls in softirq. So to guarantee shutdown process convergence we
* firstly finish all new established connections activity using
* SS_V_ACT_NEWCONN and next we wait for finishing all active connections
* using SS_V_ACT_LIVECONN.
*/
#define SS_V_ACT_NEWCONN 0x0000000000000001UL
#define SS_M_ACT_NEWCONN 0x00000000ffffffffUL
#define SS_V_ACT_LIVECONN 0x0000000100000000UL
#define SS_ACT_SHIFT 32
static bool __ss_active = false;
static unsigned int __wq_size = 0;
static DEFINE_PER_CPU(atomic64_t, __ss_act_cnt) ____cacheline_aligned
= ATOMIC_INIT(0);
static DEFINE_PER_CPU(TfwRBQueue, si_wq);
static DEFINE_PER_CPU(struct irq_work, ipi_work);
/*
* llist can not be used since llist_del_first() returns the newest added
* item, while we need FIFO queue. Not a big deal - we use it only at slow
* path.
*/
static DEFINE_PER_CPU(SsCloseBacklog, close_backlog);
static struct kmem_cache *ss_cbacklog_cache;
static void
ss_sk_incoming_cpu_update(struct sock *sk)
{
if (sk->sk_incoming_cpu == -1)
sk->sk_incoming_cpu = raw_smp_processor_id();
}
/**
* Enters critical section synchronized with ss_synchronize().
* Active networking operations which involves SS callback calls must be
* protected by the guard: don't enter the section if the system is about
* to shutdown. The only exception is closing activity - this is the only
* activity allowed in progress of shutdown process.
*
* Returns zero (SS_OK) if we're in critical section and SS_BAD if shutdown
* process in progress and we can't enter the section.
*/
static int
ss_active_guard_enter(unsigned long val)
{
atomic64_t *acnt = this_cpu_ptr(&__ss_act_cnt);
/*
* Don't race with ss_wait_newconn() and ss_synchronize() on the __ss_act_cnt
* if we commited to shutdown.
*/
if (unlikely(!READ_ONCE(__ss_active)))
return SS_BAD;
atomic64_add(val, acnt);
/*
* If ss_stop() and the whole ss_wait_newconn() or ss_synchronize() were
* called between __ss_active check above and the addition, then revert
* the addtion on the second check.
*/
if (unlikely(!READ_ONCE(__ss_active))) {
atomic64_sub(val, acnt);
return SS_BAD;
}
return SS_OK;
}
static void
ss_active_guard_exit(unsigned long val)
{
atomic64_sub(val, this_cpu_ptr(&__ss_act_cnt));
}
static void
ss_conn_drop_guard_exit(struct sock *sk)
{
SS_CONN_TYPE(sk) &= ~(Conn_Closing | Conn_Shutdown);
SS_CALL(connection_drop, sk);
if (sk->sk_security)
tfw_classify_conn_close(sk);
ss_active_guard_exit(SS_V_ACT_LIVECONN);
}
static void
ss_ipi(struct irq_work *work)
{
TfwRBQueue *wq = &per_cpu(si_wq, smp_processor_id());
clear_bit(TFW_QUEUE_IPI, &wq->flags);
raise_softirq(NET_TX_SOFTIRQ);
}
/**
* The socket can move from one CPU to another, so we have to pass @cpu as
* a parameter to guarantee that we use work queue and backlog for the same
* CPU.
*/
static int
ss_turnstile_push(long ticket, SsWork *sw, int cpu)
{
struct irq_work *iw = &per_cpu(ipi_work, cpu);
SsCloseBacklog *cb = &per_cpu(close_backlog, cpu);
TfwRBQueue *wq = &per_cpu(si_wq, cpu);
SsCblNode *cn;
cn = kmem_cache_alloc(ss_cbacklog_cache, GFP_ATOMIC);
if (!cn)
return -ENOMEM;
cn->ticket = ticket;
memcpy(&cn->sw, sw, sizeof(*sw));
spin_lock_bh(&cb->lock);
list_add_tail(&cn->list, &cb->head);
cb->size++;
if (cb->turn > ticket)
cb->turn = ticket;
spin_unlock_bh(&cb->lock);
/*
* We do not need explicit memory barriers after
* spinlock operation.
*/
if (test_bit(TFW_QUEUE_IPI, &wq->flags))
tfw_raise_softirq(cpu, iw, ss_ipi);
return 0;
}
static void
ss_turnstile_update_turn(SsCloseBacklog *cb)
{
if (list_empty(&cb->head)) {
cb->turn = LONG_MAX;
} else {
SsCblNode *cn = list_first_entry(&cb->head, SsCblNode, list);
cb->turn = cn->ticket;
}
}
static void
ss_backlog_validate_cleanup(int cpu)
{
SsCloseBacklog *cb = &per_cpu(close_backlog, cpu);
WARN_ON(!list_empty(&cb->head));
WARN_ON(cb->size);
WARN_ON(cb->turn != LONG_MAX);
}
static long
ss_wq_push(SsWork *sw, int cpu)
{
TfwRBQueue *wq = &per_cpu(si_wq, cpu);
struct irq_work *iw = &per_cpu(ipi_work, cpu);
long r;
r = tfw_wq_push(wq, sw, cpu, iw, ss_ipi);
if (r)
TFW_INC_STAT_BH(ss.wq_full);
return r;
}
static int
ss_wq_pop(TfwRBQueue *wq, SsWork *sw, long *ticket)
{
SsCloseBacklog *cb = this_cpu_ptr(&close_backlog);
/*
* Since backlog is used for closing only, items from the work queue
* are fetched first.
*/
if (!*ticket && !tfw_wq_pop_ticket(wq, sw, ticket))
return 0;
/*
* @turn stores @wq->head value of a next item to insert (the position
* was unavailable when we tried it), so if we fetched i'th item last
* time, then now we should fetch (i + 1)'th item from the backlog.
* While there are many producers, they have different head views and
* they can put the items to the backlog with wrong order. Thus, we
* should fetch all the items with small enough tickets.
*/
if (*ticket + 1 >= cb->turn) {
SsCblNode *cn = NULL;
spin_lock(&cb->lock);
if (!list_empty(&cb->head)) {
cn = list_first_entry(&cb->head, SsCblNode, list);
list_del(&cn->list);
ss_turnstile_update_turn(cb);
cb->size--;
}
spin_unlock(&cb->lock);
if (cn) {
memcpy_fast(sw, &cn->sw, sizeof(*sw));
kmem_cache_free(ss_cbacklog_cache, cn);
return 0;
}
}
return tfw_wq_pop_ticket(wq, sw, ticket);
}
static size_t
ss_wq_size(int cpu)
{
TfwRBQueue *wq = &per_cpu(si_wq, cpu);
SsCloseBacklog *cb = &per_cpu(close_backlog, cpu);
return tfw_wq_size(wq) + cb->size;
}
static size_t
ss_wq_local_size(TfwRBQueue *wq)
{
SsCloseBacklog *cb = this_cpu_ptr(&close_backlog);
return tfw_wq_size(wq) + cb->size;
}
/*
* Socket is in a usable state that allows processing
* and sending of HTTP messages. This function must
* be used consistently across all involved functions.
*/
static bool
ss_sock_active(struct sock *sk)
{
return (1 << sk->sk_state) & (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT);
}
/*
* ------------------------------------------------------------------------
* Server and client connections handling
* ------------------------------------------------------------------------
*/
/**
* The simplified version of sk_forced_mem_schedule().
* We use the forced version of the socket accounting function to send the
* data ASAP - we can't wait for memory as process context does.
*/
static void
ss_forced_mem_schedule(struct sock *sk, int size)
{
int amt;
if (size <= sk->sk_forward_alloc)
return;
amt = sk_mem_pages(size);
sk->sk_forward_alloc += amt * SK_MEM_QUANTUM;
sk_memory_allocated_add(sk, amt);
}
/**
* @skb_head can be invalid after the function call, don't try to use it.
*/
static void
ss_do_send(struct sock *sk, struct sk_buff **skb_head, int flags)
{
struct tcp_sock *tp = tcp_sk(sk);
struct sk_buff *skb, *head = *skb_head;
int size, mss = tcp_send_mss(sk, &size, MSG_DONTWAIT);
unsigned int mark = (*skb_head)->mark;
T_DBG3("[%d]: %s: sk=%pK queue_empty=%d send_head=%pK"
" sk_state=%d mss=%d size=%d\n",
smp_processor_id(), __func__,
sk, tcp_write_queue_empty(sk), tcp_send_head(sk),
sk->sk_state, mss, size);
/* If the socket is inactive, there's no recourse. Drop the data. */
if (unlikely(!ss_sock_active(sk))) {
ss_skb_queue_purge(skb_head);
return;
}
while ((skb = ss_skb_dequeue(skb_head))) {
/*
* Zero-sized SKBs may appear when the message headers (or any
* other contents) are modified or deleted by Tempesta. Drop
* these SKBs.
*/
if (!skb->len) {
T_DBG3("[%d]: %s: drop skb=%pK data_len=%u len=%u\n",
smp_processor_id(), __func__,
skb, skb->data_len, skb->len);
kfree_skb(skb);
continue;
}
ss_skb_init_for_xmit(skb);
if (flags & SS_F_ENCRYPT) {
skb_set_tfw_tls_type(skb, SS_SKB_F2TYPE(flags));
if (skb == head)
skb_set_tfw_flags(skb, SS_F_HTTP2_FRAME_START);
}
/* Propagate mark of message head skb.*/
skb->mark = mark;
T_DBG3("[%d]: %s: entail sk=%pK skb=%pK data_len=%u len=%u"
" truesize=%u mark=%u tls_type=%x\n",
smp_processor_id(), __func__, sk,
skb, skb->data_len, skb->len, skb->truesize, skb->mark,
skb_tfw_tls_type(skb));
ss_forced_mem_schedule(sk, skb->truesize);
skb_entail(sk, skb);
tp->write_seq += skb->len;
TCP_SKB_CB(skb)->end_seq += skb->len;
}
T_DBG3("[%d]: %s: sk=%p send_head=%p sk_state=%d flags=%x\n",
smp_processor_id(), __func__,
sk, tcp_send_head(sk), sk->sk_state, flags);
/*
* If connection close flag is specified, then @ss_do_close is used to
* set FIN on final SKB and push all pending frames to the stack.
*/
if (flags & SS_F_CONN_CLOSE)
return;
tcp_push(sk, MSG_DONTWAIT, mss, TCP_NAGLE_OFF|TCP_NAGLE_PUSH, size);
}
/**
* Directly insert all skbs from @skb_head into @sk TCP write queue regardless
* write buffer size. This allows directly forward modified packets without
* copying. See do_tcp_sendpages() and tcp_sendmsg() in linux/net/ipv4/tcp.c.
*
* Can be called in softirq context as well as from kernel thread.
*/
int
ss_send(struct sock *sk, struct sk_buff **skb_head, int flags)
{
int cpu, r = 0;
struct sk_buff *skb, *twin_skb;
SsWork sw = {
.sk = sk,
.flags = flags,
.action = SS_SEND,
};
BUG_ON(!sk);
/* The queue could be purged in previous call. */
if (unlikely(!*skb_head))
return 0;
cpu = sk->sk_incoming_cpu;
T_DBG3("[%d]: %s: sk=%p (cpu=%d) state=%s\n",
smp_processor_id(), __func__, sk, cpu,
ss_statename[sk->sk_state]);
/*
* This isn't reliable check, but rather just an optimization to
* avoid expensive work queue operations.
*/
if (unlikely(!ss_sock_active(sk))) {
T_DBG2("Attempt to send on inactive socket %p\n", sk);
ss_skb_queue_purge(skb_head);
return -EBADF;
}
/*
* Remove the skbs from Tempesta lists if we won't use them,
* or copy them if they're going to be used by Tempesta during
* and after the transmission.
*/
if (flags & SS_F_KEEP_SKB) {
skb = *skb_head;
do {
/* tcp_transmit_skb() will clone the skb. */
twin_skb = pskb_copy_for_clone(skb, GFP_ATOMIC);
if (!twin_skb) {
T_WARN("Unable to copy an egress SKB.\n");
r = -ENOMEM;
goto err;
}
ss_skb_queue_tail(&sw.skb_head, twin_skb);
skb = skb->next;
} while (skb != *skb_head);
} else {
sw.skb_head = *skb_head;
*skb_head = NULL;
}
/*
* Schedule the socket for TX softirq processing.
* Only part of list pointed by @skb_head could be passed to send queue.
*
* We can't transmit the data escaping the queueing because we have to
* order transmissions and other CPUs can push data to transmit for
* the socket while current CPU was servicing other sockets.
*
* Synchronous operations with the work queue are used to avoid memory
* leakage, so we never use synchronous sending.
*/
sock_hold(sk);
if (ss_wq_push(&sw, cpu)) {
T_DBG2("Cannot schedule socket %p for transmission"
" (queue size %d)\n", sk,
tfw_wq_size(&per_cpu(si_wq, cpu)));
sock_put(sk);
r = -EBUSY;
goto err;
}
return 0;
err:
ss_skb_queue_purge(&sw.skb_head);
return r;
}
EXPORT_SYMBOL(ss_send);
/**
* This is main body of the socket close function in Sync Sockets.
*
* inet_release() can sleep (as well as tcp_close()), so we make our own
* non-sleepable socket closing.
*
* This function must be used only for data sockets.
* Use standard sock_release() for listening sockets.
*
* In most cases it is called in softirq context and from ksoftirqd which
* processes data from the socket (RSS and RPS distribute packets that way).
*
* Note: it used to be called in process context as well, at the time when
* Tempesta starts or stops. That's not the case right now, but it may change.
*
* Called with locked socket.
*/
static void
ss_do_close(struct sock *sk, int flags)
{
struct sk_buff *skb;
int data_was_unread = 0;
T_DBG2("[%d]: Close socket %p (%s): account=%d refcnt=%u\n",
smp_processor_id(), sk, ss_statename[sk->sk_state],
sk_has_account(sk), refcount_read(&sk->sk_refcnt));
assert_spin_locked(&sk->sk_lock.slock);
TFW_VALIDATE_SK_LOCK_OWNER(sk);
WARN_ON_ONCE(!in_softirq());
WARN_ON_ONCE(sk->sk_state == TCP_LISTEN);
/* We must return immediately, so LINGER option is meaningless. */
WARN_ON_ONCE(sock_flag(sk, SOCK_LINGER));
/* We don't support virtual containers, so TCP_REPAIR is prohibited. */
WARN_ON_ONCE(tcp_sk(sk)->repair);
/* The socket must have atomic allocation mask. */
WARN_ON_ONCE(!(sk->sk_allocation & GFP_ATOMIC));
/*
* We use the spin lock only since we're working in softirq, however
* the rest of the TCP/IP stack relies that the closing code sets
* sk->sk_lock.owned, e.g. tcp_tasklet_func(), so set the lock owner.
*/
sk->sk_lock.owned = 1;
/* The below is mostly copy-paste from tcp_close(), 5.10.35. */
sk->sk_shutdown = SHUTDOWN_MASK;
while ((skb = __skb_dequeue(&sk->sk_receive_queue))) {
u32 len = TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq;
if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
len--;
data_was_unread += len;
T_DBG3("[%d]: free rcv skb %p\n", smp_processor_id(), skb);
__kfree_skb(skb);
}
sk_mem_reclaim(sk);
if (sk->sk_state == TCP_CLOSE)
goto adjudge_to_death;
if (data_was_unread || (flags & __SS_F_RST)) {
if ((flags & __SS_F_RST)) {
sk->sk_err = ECONNRESET;
} else {
NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONCLOSE);
}
tcp_set_state(sk, TCP_CLOSE);
tcp_send_active_reset(sk, sk->sk_allocation);
} else if (tcp_close_state(sk)) {
tcp_send_fin(sk);
}
adjudge_to_death:
sock_hold(sk);
sock_orphan(sk);
/*
* An adoption of release_sock() for our sleep-less tcp_close() version.
*
* SS sockets are processed in softirq only,
* so backlog queue should be empty.
*/
WARN_ON(sk->sk_backlog.tail);
tcp_release_cb(sk);
sk->sk_lock.owned = 0;
if (waitqueue_active(&sk->sk_lock.wq))
wake_up(&sk->sk_lock.wq);
percpu_counter_inc(sk->sk_prot->orphan_count);
if (sk->sk_state == TCP_FIN_WAIT2) {
const int tmo = tcp_fin_time(sk);
if (tmo > TCP_TIMEWAIT_LEN) {
inet_csk_reset_keepalive_timer(sk, tmo - TCP_TIMEWAIT_LEN);
} else {
tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
return;
}
}
if (sk->sk_state != TCP_CLOSE) {
sk_mem_reclaim(sk);
if (tcp_check_oom(sk, 0)) {
tcp_set_state(sk, TCP_CLOSE);
tcp_send_active_reset(sk, GFP_ATOMIC);
__NET_INC_STATS(sock_net(sk),
LINUX_MIB_TCPABORTONMEMORY);
}
}
if (sk->sk_state == TCP_CLOSE) {
struct request_sock *req;
req = rcu_dereference_protected(tcp_sk(sk)->fastopen_rsk,
lockdep_sock_is_held(sk));
if (req)
reqsk_fastopen_remove(sk, req, false);
if (flags & __SS_F_RST)
/*
* Evict all data for transmission since we might never
* have enough window from the malicious/misbehaving client.
* Receive queue is purged in inet_csk_destroy_sock().
*/
tcp_write_queue_purge(sk);
inet_csk_destroy_sock(sk);
}
}
/**
* This function is for internal Sync Sockets use only. It's called under the
* socket lock taken by the kernel, and in the context of the socket that is
* being closed.
*
* This is unintentional connection closing, usually due to some data errors.
* This is not socket error, but still must lead to connection failovering
* for server sockets.
*/
static void
ss_linkerror(struct sock *sk)
{
ss_do_close(sk, 0);
/*
* In case when ss_do_close is called for TCP_FIN_WAIT2
* tcp_done() is called from tcp_time_wait() and connection
* is drooped inside ss_do_close().
*/
if (sk->sk_user_data)
ss_conn_drop_guard_exit(sk);
sock_put(sk); /* paired with ss_do_close() */
}
/**
* The function should be called with SS_F_SYNC flag whenever possible to
* improve performance. Without SS_F_SYNC the return value must be checked
* and the call must be repeated in case of bad return value.
* Note, that SS_F_SYNC doesn't mean that the socket will be closed immediately,
* but rather it guarantees that the socket will be closed and the caller can
* not care about return value.
*/
static int
ss_close_or_shutdown(struct sock *sk, int action, int flags)
{
int cpu;
long ticket;
SsWork sw = {
.sk = sk,
.flags = flags,
.action = action,
};
if (unlikely(!sk))
return SS_OK;
ss_sk_incoming_cpu_update(sk);
cpu = sk->sk_incoming_cpu;
sock_hold(sk);
ticket = ss_wq_push(&sw, cpu);
if (!ticket)
return SS_OK;
if (!(flags & SS_F_SYNC))
goto err;
/*
* Slow path: the system is overloaded, but we have to close the socket,
* so use locked linked list with a turnstile to keep works order.
*/
if (ss_turnstile_push(ticket, &sw, cpu)) {
T_WARN("Cannot schedule socket %p for closing\n", sk);
goto err;
}
return SS_OK;
err:
sock_put(sk);
return SS_BAD;
}
int
ss_shutdown(struct sock *sk, int flags)
{
return ss_close_or_shutdown(sk, SS_SHUTDOWN, flags);
}
EXPORT_SYMBOL(ss_shutdown);
int
ss_close(struct sock *sk, int flags)
{
return ss_close_or_shutdown(sk, SS_CLOSE, flags);
}
EXPORT_SYMBOL(ss_close);
/*
* Process a single SKB.
*/
static int
ss_tcp_process_skb(struct sock *sk, struct sk_buff *skb, int *processed)
{
bool tcp_fin;
int r = 0, offset, count;
void *conn;
struct sk_buff *skb_head = NULL;
struct tcp_sock *tp = tcp_sk(sk);
#define ADJUST_PROCESSED_SKB(skb, tp, count, offset, processed) \
do { \
count = skb->len - offset; \
tp->copied_seq += count; \
*processed += count; \
} while(0)
/* Calculate the offset into the SKB. */
offset = tp->copied_seq - TCP_SKB_CB(skb)->seq;
if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)
offset--;
/* SKB may be freed in processing. Save the flag. */
tcp_fin = TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN;
if (ss_skb_unroll(&skb_head, skb)) {
tp->copied_seq += tcp_fin;
ADJUST_PROCESSED_SKB(skb, tp, count, offset, processed);
__kfree_skb(skb);
return SS_BAD;
}
while ((skb = ss_skb_dequeue(&skb_head))) {
WARN_ON_ONCE(skb->tail_lock);
WARN_ON_ONCE(skb_has_frag_list(skb));
WARN_ON_ONCE(skb->sk);
/*
* Some SKBs may have dev, however tempesta uses dev to store
* own flags, thus clear it.
*/
skb->dev = NULL;
if (unlikely(offset >= skb->len)) {
offset -= skb->len;
__kfree_skb(skb);
continue;
}
/*
* TCP can ship an skb with overlapped seqnos, so we have to
* work with the offset to avoid probably costly skb_pull().
*/
ADJUST_PROCESSED_SKB(skb, tp, count, offset, processed);
if (unlikely(offset > 0 &&
ss_skb_chop_head_tail(NULL, skb, offset, 0) != 0))
{
r = SS_BAD;
goto out;
}
offset = 0;
conn = sk->sk_user_data;
/*
* If @sk_user_data is unset, then this connection
* had been dropped in a parallel thread. Dropping
* a connection is serialized with the socket lock.
* The receive queue must be empty in that case,
* and the execution path should never reach here.
*/
BUG_ON(conn == NULL);
r = SS_CALL(connection_recv, conn, skb);
if (r < 0) {
T_DBG2("[%d]: Processing error: sk=%pK r=%d\n",
smp_processor_id(), sk, r);
goto out; /* connection must be dropped */
}
}
out:
if (tcp_fin) {
T_DBG2("Received data FIN on sk=%p, cpu=%d\n",
sk, smp_processor_id());
++tp->copied_seq;
if (!r)
r = SS_BAD;
}
while ((skb = ss_skb_dequeue(&skb_head))) {
if (unlikely(offset >= skb->len)) {
offset -= skb->len;
__kfree_skb(skb);
continue;
}
/*
* We should adjust tp->copied_seq for all incoming skbs.
* otherwise socket hung, because copied_seq is a head
* of yet unread data, and we don't update it all new skbs
* will be skipped (because its sequence number is greater
* then copied_seq). They will stay in socket received
* queue and we catch kernel BUG in some places.
*/
ADJUST_PROCESSED_SKB(skb, tp, count, offset, processed);
offset = 0;
__kfree_skb(skb);
}
return r;
#undef ADJUST_PROCESSED_SKB
}
/**
* Receive data on TCP socket. Very similar to standard tcp_recvmsg().
*
* We can't use standard tcp_read_sock() with our actor callback, because
* tcp_read_sock() calls __kfree_skb() through sk_eat_skb() which is good
* for copying data from skb, but we need to manage skb's ourselves.
*
* TODO #873 process URG.
*/
static int
ss_tcp_process_data(struct sock *sk)
{
int r = 0, count, processed = 0;
unsigned int skb_len, skb_seq;
struct sk_buff *skb, *tmp;
struct tcp_sock *tp = tcp_sk(sk);
skb_queue_walk_safe(&sk->sk_receive_queue, skb, tmp) {
if (unlikely(before(tp->copied_seq, TCP_SKB_CB(skb)->seq))) {
T_WARN("recvmsg bug: TCP sequence gap at seq %X"
" recvnxt %X\n",
tp->copied_seq, TCP_SKB_CB(skb)->seq);
goto out;
}
__skb_unlink(skb, &sk->sk_receive_queue);
skb_orphan(skb);
WARN_ON_ONCE(skb_shared(skb));
/* Save the original len and seq for reporting. */
skb_len = skb->len;
skb_seq = TCP_SKB_CB(skb)->seq;
count = 0;
r = ss_tcp_process_skb(sk, skb, &count);
processed += count;
if (r < 0)
break;
if (!count)
T_WARN("recvmsg bug: overlapping TCP segment at %X"
" seq %X rcvnxt %X len %x\n",
tp->copied_seq, skb_seq, tp->rcv_nxt,
skb_len);
}
out:
/*
* Recalculate an appropriate TCP receive buffer space
* and send ACK to a client with the new window.
*/
tcp_rcv_space_adjust(sk);
if (processed)
tcp_cleanup_rbuf(sk, processed);
return r;
}
/*
* ------------------------------------------------------------------------
* Socket callbacks
* ------------------------------------------------------------------------
*/
/*
* Called when a new data received on the socket.
* Called under bh_lock_sock(sk) (see tcp_v4_rcv()).
*/
static void
ss_tcp_data_ready(struct sock *sk)
{
int flags;
int (*action)(struct sock *sk, int flags);
bool was_stopped = (SS_CONN_TYPE(sk) & Conn_Stop);
T_DBG3("[%d]: %s: sk=%p state=%s\n",
smp_processor_id(), __func__, sk, ss_statename[sk->sk_state]);
assert_spin_locked(&sk->sk_lock.slock);
TFW_VALIDATE_SK_LOCK_OWNER(sk);
if (!skb_queue_empty(&sk->sk_error_queue)) {
/*
* Error packet received.
* See sock_queue_err_skb() in linux/net/core/skbuff.c.
*/
T_ERR("error data in socket %p\n", sk);
return;
}
if (skb_queue_empty(&sk->sk_receive_queue)) {
/*
* Check for URG data.
* TODO #873: shouldn't we do it in ss_tcp_process_data()?
*/
struct tcp_sock *tp = tcp_sk(sk);
if (tp->urg_data & TCP_URG_VALID) {
tp->urg_data = 0;
T_DBG3("[%d]: urgent data in socket %p\n",
smp_processor_id(), sk);
}
}
switch (ss_tcp_process_data(sk)) {
case SS_OK:
case SS_POSTPONE:
case SS_DROP:
return;
case SS_BLOCK_WITH_FIN:
flags = SS_F_SYNC;
action = ss_close;
break;
case SS_BLOCK_WITH_RST:
flags = SS_F_ABORT_FORCE;
action = ss_close;
break;
case SS_BAD:
flags = SS_F_SYNC;
action = ss_shutdown;
break;
default:
BUG();
}
if (was_stopped) {
/*
* In case of errors for already stopped connections
* we should immediately close them with TCP RST.
*/
flags = SS_F_ABORT_FORCE;
action = ss_close;
}
/*
* Close connection in case of internal errors,
* banned packets, or FIN in the received packet,
* and only if it's not on hold until explicitly
* closed.
*
* ss_close() is responsible for calling