blob: f9b3689e1e4b1d9de99d9f9523679525d36bc5a8 [file] [log] [blame]
b.liue9582032025-04-17 19:18:16 +08001/* SPDX-License-Identifier: GPL-2.0-or-later */
2/*
3 * INET An implementation of the TCP/IP protocol suite for the LINUX
4 * operating system. INET is implemented using the BSD Socket
5 * interface as the means of communication with the user level.
6 *
7 * Definitions for the AF_INET socket handler.
8 *
9 * Version: @(#)sock.h 1.0.4 05/13/93
10 *
11 * Authors: Ross Biro
12 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
13 * Corey Minyard <wf-rch!minyard@relay.EU.net>
14 * Florian La Roche <flla@stud.uni-sb.de>
15 *
16 * Fixes:
17 * Alan Cox : Volatiles in skbuff pointers. See
18 * skbuff comments. May be overdone,
19 * better to prove they can be removed
20 * than the reverse.
21 * Alan Cox : Added a zapped field for tcp to note
22 * a socket is reset and must stay shut up
23 * Alan Cox : New fields for options
24 * Pauline Middelink : identd support
25 * Alan Cox : Eliminate low level recv/recvfrom
26 * David S. Miller : New socket lookup architecture.
27 * Steve Whitehouse: Default routines for sock_ops
28 * Arnaldo C. Melo : removed net_pinfo, tp_pinfo and made
29 * protinfo be just a void pointer, as the
30 * protocol specific parts were moved to
31 * respective headers and ipv4/v6, etc now
32 * use private slabcaches for its socks
33 * Pedro Hortas : New flags field for socket options
34 */
35#ifndef _SOCK_H
36#define _SOCK_H
37
38#include <linux/hardirq.h>
39#include <linux/kernel.h>
40#include <linux/list.h>
41#include <linux/list_nulls.h>
42#include <linux/timer.h>
43#include <linux/cache.h>
44#include <linux/bitops.h>
45#include <linux/lockdep.h>
46#include <linux/netdevice.h>
47#include <linux/skbuff.h> /* struct sk_buff */
48#include <linux/mm.h>
49#include <linux/security.h>
50#include <linux/slab.h>
51#include <linux/uaccess.h>
52#include <linux/page_counter.h>
53#include <linux/memcontrol.h>
54#include <linux/static_key.h>
55#include <linux/sched.h>
56#include <linux/wait.h>
57#include <linux/cgroup-defs.h>
58#include <linux/rbtree.h>
59#include <linux/filter.h>
60#include <linux/rculist_nulls.h>
61#include <linux/poll.h>
62
63#include <linux/atomic.h>
64#include <linux/refcount.h>
65#include <net/dst.h>
66#include <net/checksum.h>
67#include <net/tcp_states.h>
68#include <linux/net_tstamp.h>
69#include <net/smc.h>
70#include <net/l3mdev.h>
71#include <linux/android_kabi.h>
72#include <linux/android_vendor.h>
73
74/*
75 * This structure really needs to be cleaned up.
76 * Most of it is for TCP, and not used by any of
77 * the other protocols.
78 */
79
80/* Define this to get the SOCK_DBG debugging facility. */
81#define SOCK_DEBUGGING
82#ifdef SOCK_DEBUGGING
83#define SOCK_DEBUG(sk, msg...) do { if ((sk) && sock_flag((sk), SOCK_DBG)) \
84 printk(KERN_DEBUG msg); } while (0)
85#else
86/* Validate arguments and do nothing */
87static inline __printf(2, 3)
88void SOCK_DEBUG(const struct sock *sk, const char *msg, ...)
89{
90}
91#endif
92
93/* This is the per-socket lock. The spinlock provides a synchronization
94 * between user contexts and software interrupt processing, whereas the
95 * mini-semaphore synchronizes multiple users amongst themselves.
96 */
97typedef struct {
98 spinlock_t slock;
99 int owned;
100 wait_queue_head_t wq;
101 /*
102 * We express the mutex-alike socket_lock semantics
103 * to the lock validator by explicitly managing
104 * the slock as a lock variant (in addition to
105 * the slock itself):
106 */
107#ifdef CONFIG_DEBUG_LOCK_ALLOC
108 struct lockdep_map dep_map;
109#endif
110} socket_lock_t;
111
112struct sock;
113struct proto;
114struct net;
115
116typedef __u32 __bitwise __portpair;
117typedef __u64 __bitwise __addrpair;
118
119/**
120 * struct sock_common - minimal network layer representation of sockets
121 * @skc_daddr: Foreign IPv4 addr
122 * @skc_rcv_saddr: Bound local IPv4 addr
123 * @skc_hash: hash value used with various protocol lookup tables
124 * @skc_u16hashes: two u16 hash values used by UDP lookup tables
125 * @skc_dport: placeholder for inet_dport/tw_dport
126 * @skc_num: placeholder for inet_num/tw_num
127 * @skc_family: network address family
128 * @skc_state: Connection state
129 * @skc_reuse: %SO_REUSEADDR setting
130 * @skc_reuseport: %SO_REUSEPORT setting
131 * @skc_bound_dev_if: bound device index if != 0
132 * @skc_bind_node: bind hash linkage for various protocol lookup tables
133 * @skc_portaddr_node: second hash linkage for UDP/UDP-Lite protocol
134 * @skc_prot: protocol handlers inside a network family
135 * @skc_net: reference to the network namespace of this socket
136 * @skc_node: main hash linkage for various protocol lookup tables
137 * @skc_nulls_node: main hash linkage for TCP/UDP/UDP-Lite protocol
138 * @skc_tx_queue_mapping: tx queue number for this connection
139 * @skc_rx_queue_mapping: rx queue number for this connection
140 * @skc_flags: place holder for sk_flags
141 * %SO_LINGER (l_onoff), %SO_BROADCAST, %SO_KEEPALIVE,
142 * %SO_OOBINLINE settings, %SO_TIMESTAMPING settings
143 * @skc_incoming_cpu: record/match cpu processing incoming packets
144 * @skc_refcnt: reference count
145 *
146 * This is the minimal network layer representation of sockets, the header
147 * for struct sock and struct inet_timewait_sock.
148 */
149struct sock_common {
150 /* skc_daddr and skc_rcv_saddr must be grouped on a 8 bytes aligned
151 * address on 64bit arches : cf INET_MATCH()
152 */
153 union {
154 __addrpair skc_addrpair;
155 struct {
156 __be32 skc_daddr;
157 __be32 skc_rcv_saddr;
158 };
159 };
160 union {
161 unsigned int skc_hash;
162 __u16 skc_u16hashes[2];
163 };
164 /* skc_dport && skc_num must be grouped as well */
165 union {
166 __portpair skc_portpair;
167 struct {
168 __be16 skc_dport;
169 __u16 skc_num;
170 };
171 };
172
173 unsigned short skc_family;
174 volatile unsigned char skc_state;
175 unsigned char skc_reuse:4;
176 unsigned char skc_reuseport:1;
177 unsigned char skc_ipv6only:1;
178 unsigned char skc_net_refcnt:1;
179 int skc_bound_dev_if;
180 union {
181 struct hlist_node skc_bind_node;
182 struct hlist_node skc_portaddr_node;
183 };
184 struct proto *skc_prot;
185 possible_net_t skc_net;
186
187#if IS_ENABLED(CONFIG_IPV6)
188 struct in6_addr skc_v6_daddr;
189 struct in6_addr skc_v6_rcv_saddr;
190#endif
191
192 atomic64_t skc_cookie;
193
194 /* following fields are padding to force
195 * offset(struct sock, sk_refcnt) == 128 on 64bit arches
196 * assuming IPV6 is enabled. We use this padding differently
197 * for different kind of 'sockets'
198 */
199 union {
200 unsigned long skc_flags;
201 struct sock *skc_listener; /* request_sock */
202 struct inet_timewait_death_row *skc_tw_dr; /* inet_timewait_sock */
203 };
204 /*
205 * fields between dontcopy_begin/dontcopy_end
206 * are not copied in sock_copy()
207 */
208 /* private: */
209 int skc_dontcopy_begin[0];
210 /* public: */
211 union {
212 struct hlist_node skc_node;
213 struct hlist_nulls_node skc_nulls_node;
214 };
215 unsigned short skc_tx_queue_mapping;
216#ifdef CONFIG_XPS
217 unsigned short skc_rx_queue_mapping;
218#endif
219 union {
220 int skc_incoming_cpu;
221 u32 skc_rcv_wnd;
222 u32 skc_tw_rcv_nxt; /* struct tcp_timewait_sock */
223 };
224
225 refcount_t skc_refcnt;
226 /* private: */
227 int skc_dontcopy_end[0];
228 union {
229 u32 skc_rxhash;
230 u32 skc_window_clamp;
231 u32 skc_tw_snd_nxt; /* struct tcp_timewait_sock */
232 };
233 /* public: */
234};
235
236struct bpf_sk_storage;
237
238/**
239 * struct sock - network layer representation of sockets
240 * @__sk_common: shared layout with inet_timewait_sock
241 * @sk_shutdown: mask of %SEND_SHUTDOWN and/or %RCV_SHUTDOWN
242 * @sk_userlocks: %SO_SNDBUF and %SO_RCVBUF settings
243 * @sk_lock: synchronizer
244 * @sk_kern_sock: True if sock is using kernel lock classes
245 * @sk_rcvbuf: size of receive buffer in bytes
246 * @sk_wq: sock wait queue and async head
247 * @sk_rx_dst: receive input route used by early demux
248 * @sk_dst_cache: destination cache
249 * @sk_dst_pending_confirm: need to confirm neighbour
250 * @sk_policy: flow policy
251 * @sk_receive_queue: incoming packets
252 * @sk_wmem_alloc: transmit queue bytes committed
253 * @sk_tsq_flags: TCP Small Queues flags
254 * @sk_write_queue: Packet sending queue
255 * @sk_omem_alloc: "o" is "option" or "other"
256 * @sk_wmem_queued: persistent queue size
257 * @sk_forward_alloc: space allocated forward
258 * @sk_napi_id: id of the last napi context to receive data for sk
259 * @sk_ll_usec: usecs to busypoll when there is no data
260 * @sk_allocation: allocation mode
261 * @sk_pacing_rate: Pacing rate (if supported by transport/packet scheduler)
262 * @sk_pacing_status: Pacing status (requested, handled by sch_fq)
263 * @sk_max_pacing_rate: Maximum pacing rate (%SO_MAX_PACING_RATE)
264 * @sk_sndbuf: size of send buffer in bytes
265 * @__sk_flags_offset: empty field used to determine location of bitfield
266 * @sk_padding: unused element for alignment
267 * @sk_no_check_tx: %SO_NO_CHECK setting, set checksum in TX packets
268 * @sk_no_check_rx: allow zero checksum in RX packets
269 * @sk_route_caps: route capabilities (e.g. %NETIF_F_TSO)
270 * @sk_route_nocaps: forbidden route capabilities (e.g NETIF_F_GSO_MASK)
271 * @sk_gso_type: GSO type (e.g. %SKB_GSO_TCPV4)
272 * @sk_gso_max_size: Maximum GSO segment size to build
273 * @sk_gso_max_segs: Maximum number of GSO segments
274 * @sk_pacing_shift: scaling factor for TCP Small Queues
275 * @sk_lingertime: %SO_LINGER l_linger setting
276 * @sk_backlog: always used with the per-socket spinlock held
277 * @sk_callback_lock: used with the callbacks in the end of this struct
278 * @sk_error_queue: rarely used
279 * @sk_prot_creator: sk_prot of original sock creator (see ipv6_setsockopt,
280 * IPV6_ADDRFORM for instance)
281 * @sk_err: last error
282 * @sk_err_soft: errors that don't cause failure but are the cause of a
283 * persistent failure not just 'timed out'
284 * @sk_drops: raw/udp drops counter
285 * @sk_ack_backlog: current listen backlog
286 * @sk_max_ack_backlog: listen backlog set in listen()
287 * @sk_uid: user id of owner
288 * @sk_priority: %SO_PRIORITY setting
289 * @sk_type: socket type (%SOCK_STREAM, etc)
290 * @sk_protocol: which protocol this socket belongs in this network family
291 * @sk_peer_pid: &struct pid for this socket's peer
292 * @sk_peer_cred: %SO_PEERCRED setting
293 * @sk_rcvlowat: %SO_RCVLOWAT setting
294 * @sk_rcvtimeo: %SO_RCVTIMEO setting
295 * @sk_sndtimeo: %SO_SNDTIMEO setting
296 * @sk_txhash: computed flow hash for use on transmit
297 * @sk_filter: socket filtering instructions
298 * @sk_timer: sock cleanup timer
299 * @sk_stamp: time stamp of last packet received
300 * @sk_stamp_seq: lock for accessing sk_stamp on 32 bit architectures only
301 * @sk_tsflags: SO_TIMESTAMPING socket options
302 * @sk_tskey: counter to disambiguate concurrent tstamp requests
303 * @sk_zckey: counter to order MSG_ZEROCOPY notifications
304 * @sk_socket: Identd and reporting IO signals
305 * @sk_user_data: RPC layer private data. Write-protected by @sk_callback_lock.
306 * @sk_frag: cached page frag
307 * @sk_peek_off: current peek_offset value
308 * @sk_send_head: front of stuff to transmit
309 * @sk_security: used by security modules
310 * @sk_mark: generic packet mark
311 * @sk_cgrp_data: cgroup data for this cgroup
312 * @sk_memcg: this socket's memory cgroup association
313 * @sk_write_pending: a write to stream socket waits to start
314 * @sk_wait_pending: number of threads blocked on this socket
315 * @sk_state_change: callback to indicate change in the state of the sock
316 * @sk_data_ready: callback to indicate there is data to be processed
317 * @sk_write_space: callback to indicate there is bf sending space available
318 * @sk_error_report: callback to indicate errors (e.g. %MSG_ERRQUEUE)
319 * @sk_backlog_rcv: callback to process the backlog
320 * @sk_destruct: called at sock freeing time, i.e. when all refcnt == 0
321 * @sk_reuseport_cb: reuseport group container
322 * @sk_rcu: used during RCU grace period
323 * @sk_clockid: clockid used by time-based scheduling (SO_TXTIME)
324 * @sk_txtime_deadline_mode: set deadline mode for SO_TXTIME
325 * @sk_txtime_unused: unused txtime flags
326 */
327struct sock {
328 /*
329 * Now struct inet_timewait_sock also uses sock_common, so please just
330 * don't add nothing before this first member (__sk_common) --acme
331 */
332 struct sock_common __sk_common;
333#define sk_node __sk_common.skc_node
334#define sk_nulls_node __sk_common.skc_nulls_node
335#define sk_refcnt __sk_common.skc_refcnt
336#define sk_tx_queue_mapping __sk_common.skc_tx_queue_mapping
337#ifdef CONFIG_XPS
338#define sk_rx_queue_mapping __sk_common.skc_rx_queue_mapping
339#endif
340
341#define sk_dontcopy_begin __sk_common.skc_dontcopy_begin
342#define sk_dontcopy_end __sk_common.skc_dontcopy_end
343#define sk_hash __sk_common.skc_hash
344#define sk_portpair __sk_common.skc_portpair
345#define sk_num __sk_common.skc_num
346#define sk_dport __sk_common.skc_dport
347#define sk_addrpair __sk_common.skc_addrpair
348#define sk_daddr __sk_common.skc_daddr
349#define sk_rcv_saddr __sk_common.skc_rcv_saddr
350#define sk_family __sk_common.skc_family
351#define sk_state __sk_common.skc_state
352#define sk_reuse __sk_common.skc_reuse
353#define sk_reuseport __sk_common.skc_reuseport
354#define sk_ipv6only __sk_common.skc_ipv6only
355#define sk_net_refcnt __sk_common.skc_net_refcnt
356#define sk_bound_dev_if __sk_common.skc_bound_dev_if
357#define sk_bind_node __sk_common.skc_bind_node
358#define sk_prot __sk_common.skc_prot
359#define sk_net __sk_common.skc_net
360#define sk_v6_daddr __sk_common.skc_v6_daddr
361#define sk_v6_rcv_saddr __sk_common.skc_v6_rcv_saddr
362#define sk_cookie __sk_common.skc_cookie
363#define sk_incoming_cpu __sk_common.skc_incoming_cpu
364#define sk_flags __sk_common.skc_flags
365#define sk_rxhash __sk_common.skc_rxhash
366
367 socket_lock_t sk_lock;
368 atomic_t sk_drops;
369 int sk_rcvlowat;
370 struct sk_buff_head sk_error_queue;
371 struct sk_buff *sk_rx_skb_cache;
372 struct sk_buff_head sk_receive_queue;
373 /*
374 * The backlog queue is special, it is always used with
375 * the per-socket spinlock held and requires low latency
376 * access. Therefore we special case it's implementation.
377 * Note : rmem_alloc is in this structure to fill a hole
378 * on 64bit arches, not because its logically part of
379 * backlog.
380 */
381 struct {
382 atomic_t rmem_alloc;
383 int len;
384 struct sk_buff *head;
385 struct sk_buff *tail;
386 } sk_backlog;
387#define sk_rmem_alloc sk_backlog.rmem_alloc
388
389 int sk_forward_alloc;
390#ifdef CONFIG_NET_RX_BUSY_POLL
391 unsigned int sk_ll_usec;
392 /* ===== mostly read cache line ===== */
393 unsigned int sk_napi_id;
394#endif
395 int sk_rcvbuf;
396 int sk_wait_pending;
397
398 struct sk_filter __rcu *sk_filter;
399 union {
400 struct socket_wq __rcu *sk_wq;
401 struct socket_wq *sk_wq_raw;
402 };
403#ifdef CONFIG_XFRM
404 struct xfrm_policy __rcu *sk_policy[2];
405#endif
406 struct dst_entry __rcu *sk_rx_dst;
407 struct dst_entry __rcu *sk_dst_cache;
408 atomic_t sk_omem_alloc;
409 int sk_sndbuf;
410
411 /* ===== cache line for TX ===== */
412 int sk_wmem_queued;
413 refcount_t sk_wmem_alloc;
414 unsigned long sk_tsq_flags;
415 union {
416 struct sk_buff *sk_send_head;
417 struct rb_root tcp_rtx_queue;
418 };
419 struct sk_buff *sk_tx_skb_cache;
420 struct sk_buff_head sk_write_queue;
421 __s32 sk_peek_off;
422 int sk_write_pending;
423 __u32 sk_dst_pending_confirm;
424 u32 sk_pacing_status; /* see enum sk_pacing */
425 long sk_sndtimeo;
426 struct timer_list sk_timer;
427 __u32 sk_priority;
428 __u32 sk_mark;
429 unsigned long sk_pacing_rate; /* bytes per second */
430 unsigned long sk_max_pacing_rate;
431 struct page_frag sk_frag;
432 netdev_features_t sk_route_caps;
433 netdev_features_t sk_route_nocaps;
434 netdev_features_t sk_route_forced_caps;
435 int sk_gso_type;
436 unsigned int sk_gso_max_size;
437 gfp_t sk_allocation;
438 __u32 sk_txhash;
439
440 /*
441 * Because of non atomicity rules, all
442 * changes are protected by socket lock.
443 */
444 unsigned int __sk_flags_offset[0];
445#ifdef __BIG_ENDIAN_BITFIELD
446#define SK_FL_PROTO_SHIFT 16
447#define SK_FL_PROTO_MASK 0x00ff0000
448
449#define SK_FL_TYPE_SHIFT 0
450#define SK_FL_TYPE_MASK 0x0000ffff
451#else
452#define SK_FL_PROTO_SHIFT 8
453#define SK_FL_PROTO_MASK 0x0000ff00
454
455#define SK_FL_TYPE_SHIFT 16
456#define SK_FL_TYPE_MASK 0xffff0000
457#endif
458
459 unsigned int sk_padding : 1,
460 sk_kern_sock : 1,
461 sk_no_check_tx : 1,
462 sk_no_check_rx : 1,
463 sk_userlocks : 4,
464 sk_protocol : 8,
465 sk_type : 16;
466#define SK_PROTOCOL_MAX U8_MAX
467 u16 sk_gso_max_segs;
468 u8 sk_pacing_shift;
469 unsigned long sk_lingertime;
470 struct proto *sk_prot_creator;
471 rwlock_t sk_callback_lock;
472 int sk_err,
473 sk_err_soft;
474 u32 sk_ack_backlog;
475 u32 sk_max_ack_backlog;
476 kuid_t sk_uid;
477#if IS_ENABLED(CONFIG_DEBUG_SPINLOCK) || IS_ENABLED(CONFIG_DEBUG_LOCK_ALLOC)
478 spinlock_t sk_peer_lock;
479#else
480 /* sk_peer_lock is in the ANDROID_KABI_RESERVE(1) field below */
481#endif
482 struct pid *sk_peer_pid;
483 const struct cred *sk_peer_cred;
484
485 long sk_rcvtimeo;
486 ktime_t sk_stamp;
487#if BITS_PER_LONG==32
488 seqlock_t sk_stamp_seq;
489#endif
490 u16 sk_tsflags;
491 u8 sk_shutdown;
492 u32 sk_tskey;
493 atomic_t sk_zckey;
494
495 u8 sk_clockid;
496 u8 sk_txtime_deadline_mode : 1,
497 sk_txtime_report_errors : 1,
498 sk_txtime_unused : 6;
499
500 struct socket *sk_socket;
501 void *sk_user_data;
502#ifdef CONFIG_SECURITY
503 void *sk_security;
504#endif
505 struct sock_cgroup_data sk_cgrp_data;
506 struct mem_cgroup *sk_memcg;
507 void (*sk_state_change)(struct sock *sk);
508 void (*sk_data_ready)(struct sock *sk);
509 void (*sk_write_space)(struct sock *sk);
510 void (*sk_error_report)(struct sock *sk);
511 int (*sk_backlog_rcv)(struct sock *sk,
512 struct sk_buff *skb);
513#ifdef CONFIG_SOCK_VALIDATE_XMIT
514 struct sk_buff* (*sk_validate_xmit_skb)(struct sock *sk,
515 struct net_device *dev,
516 struct sk_buff *skb);
517#endif
518 void (*sk_destruct)(struct sock *sk);
519 struct sock_reuseport __rcu *sk_reuseport_cb;
520#ifdef CONFIG_BPF_SYSCALL
521 struct bpf_sk_storage __rcu *sk_bpf_storage;
522#endif
523 struct rcu_head sk_rcu;
524
525#if IS_ENABLED(CONFIG_DEBUG_SPINLOCK) || IS_ENABLED(CONFIG_DEBUG_LOCK_ALLOC)
526 ANDROID_KABI_RESERVE(1);
527#else
528 ANDROID_KABI_USE(1, spinlock_t sk_peer_lock);
529#endif
530 ANDROID_KABI_RESERVE(2);
531 ANDROID_KABI_RESERVE(3);
532 ANDROID_KABI_RESERVE(4);
533 ANDROID_KABI_RESERVE(5);
534 ANDROID_KABI_RESERVE(6);
535 ANDROID_KABI_RESERVE(7);
536 ANDROID_KABI_RESERVE(8);
537
538 ANDROID_OEM_DATA(1);
539};
540
541enum sk_pacing {
542 SK_PACING_NONE = 0,
543 SK_PACING_NEEDED = 1,
544 SK_PACING_FQ = 2,
545};
546
547#define __sk_user_data(sk) ((*((void __rcu **)&(sk)->sk_user_data)))
548
549#define rcu_dereference_sk_user_data(sk) rcu_dereference(__sk_user_data((sk)))
550#define rcu_assign_sk_user_data(sk, ptr) rcu_assign_pointer(__sk_user_data((sk)), ptr)
551
552/*
553 * SK_CAN_REUSE and SK_NO_REUSE on a socket mean that the socket is OK
554 * or not whether his port will be reused by someone else. SK_FORCE_REUSE
555 * on a socket means that the socket will reuse everybody else's port
556 * without looking at the other's sk_reuse value.
557 */
558
559#define SK_NO_REUSE 0
560#define SK_CAN_REUSE 1
561#define SK_FORCE_REUSE 2
562
563int sk_set_peek_off(struct sock *sk, int val);
564
565static inline int sk_peek_offset(struct sock *sk, int flags)
566{
567 if (unlikely(flags & MSG_PEEK)) {
568 return READ_ONCE(sk->sk_peek_off);
569 }
570
571 return 0;
572}
573
574static inline void sk_peek_offset_bwd(struct sock *sk, int val)
575{
576 s32 off = READ_ONCE(sk->sk_peek_off);
577
578 if (unlikely(off >= 0)) {
579 off = max_t(s32, off - val, 0);
580 WRITE_ONCE(sk->sk_peek_off, off);
581 }
582}
583
584static inline void sk_peek_offset_fwd(struct sock *sk, int val)
585{
586 sk_peek_offset_bwd(sk, -val);
587}
588
589/*
590 * Hashed lists helper routines
591 */
592static inline struct sock *sk_entry(const struct hlist_node *node)
593{
594 return hlist_entry(node, struct sock, sk_node);
595}
596
597static inline struct sock *__sk_head(const struct hlist_head *head)
598{
599 return hlist_entry(head->first, struct sock, sk_node);
600}
601
602static inline struct sock *sk_head(const struct hlist_head *head)
603{
604 return hlist_empty(head) ? NULL : __sk_head(head);
605}
606
607static inline struct sock *__sk_nulls_head(const struct hlist_nulls_head *head)
608{
609 return hlist_nulls_entry(head->first, struct sock, sk_nulls_node);
610}
611
612static inline struct sock *sk_nulls_head(const struct hlist_nulls_head *head)
613{
614 return hlist_nulls_empty(head) ? NULL : __sk_nulls_head(head);
615}
616
617static inline struct sock *sk_next(const struct sock *sk)
618{
619 return hlist_entry_safe(sk->sk_node.next, struct sock, sk_node);
620}
621
622static inline struct sock *sk_nulls_next(const struct sock *sk)
623{
624 return (!is_a_nulls(sk->sk_nulls_node.next)) ?
625 hlist_nulls_entry(sk->sk_nulls_node.next,
626 struct sock, sk_nulls_node) :
627 NULL;
628}
629
630static inline bool sk_unhashed(const struct sock *sk)
631{
632 return hlist_unhashed(&sk->sk_node);
633}
634
635static inline bool sk_hashed(const struct sock *sk)
636{
637 return !sk_unhashed(sk);
638}
639
640static inline void sk_node_init(struct hlist_node *node)
641{
642 node->pprev = NULL;
643}
644
645static inline void sk_nulls_node_init(struct hlist_nulls_node *node)
646{
647 node->pprev = NULL;
648}
649
650static inline void __sk_del_node(struct sock *sk)
651{
652 __hlist_del(&sk->sk_node);
653}
654
655/* NB: equivalent to hlist_del_init_rcu */
656static inline bool __sk_del_node_init(struct sock *sk)
657{
658 if (sk_hashed(sk)) {
659 __sk_del_node(sk);
660 sk_node_init(&sk->sk_node);
661 return true;
662 }
663 return false;
664}
665
666/* Grab socket reference count. This operation is valid only
667 when sk is ALREADY grabbed f.e. it is found in hash table
668 or a list and the lookup is made under lock preventing hash table
669 modifications.
670 */
671
672static __always_inline void sock_hold(struct sock *sk)
673{
674 refcount_inc(&sk->sk_refcnt);
675}
676
677/* Ungrab socket in the context, which assumes that socket refcnt
678 cannot hit zero, f.e. it is true in context of any socketcall.
679 */
680static __always_inline void __sock_put(struct sock *sk)
681{
682 refcount_dec(&sk->sk_refcnt);
683}
684
685static inline bool sk_del_node_init(struct sock *sk)
686{
687 bool rc = __sk_del_node_init(sk);
688
689 if (rc) {
690 /* paranoid for a while -acme */
691 WARN_ON(refcount_read(&sk->sk_refcnt) == 1);
692 __sock_put(sk);
693 }
694 return rc;
695}
696#define sk_del_node_init_rcu(sk) sk_del_node_init(sk)
697
698static inline bool __sk_nulls_del_node_init_rcu(struct sock *sk)
699{
700 if (sk_hashed(sk)) {
701 hlist_nulls_del_init_rcu(&sk->sk_nulls_node);
702 return true;
703 }
704 return false;
705}
706
707static inline bool sk_nulls_del_node_init_rcu(struct sock *sk)
708{
709 bool rc = __sk_nulls_del_node_init_rcu(sk);
710
711 if (rc) {
712 /* paranoid for a while -acme */
713 WARN_ON(refcount_read(&sk->sk_refcnt) == 1);
714 __sock_put(sk);
715 }
716 return rc;
717}
718
719static inline void __sk_add_node(struct sock *sk, struct hlist_head *list)
720{
721 hlist_add_head(&sk->sk_node, list);
722}
723
724static inline void sk_add_node(struct sock *sk, struct hlist_head *list)
725{
726 sock_hold(sk);
727 __sk_add_node(sk, list);
728}
729
730static inline void sk_add_node_rcu(struct sock *sk, struct hlist_head *list)
731{
732 sock_hold(sk);
733 if (IS_ENABLED(CONFIG_IPV6) && sk->sk_reuseport &&
734 sk->sk_family == AF_INET6)
735 hlist_add_tail_rcu(&sk->sk_node, list);
736 else
737 hlist_add_head_rcu(&sk->sk_node, list);
738}
739
740static inline void sk_add_node_tail_rcu(struct sock *sk, struct hlist_head *list)
741{
742 sock_hold(sk);
743 hlist_add_tail_rcu(&sk->sk_node, list);
744}
745
746static inline void __sk_nulls_add_node_rcu(struct sock *sk, struct hlist_nulls_head *list)
747{
748 hlist_nulls_add_head_rcu(&sk->sk_nulls_node, list);
749}
750
751static inline void __sk_nulls_add_node_tail_rcu(struct sock *sk, struct hlist_nulls_head *list)
752{
753 hlist_nulls_add_tail_rcu(&sk->sk_nulls_node, list);
754}
755
756static inline void sk_nulls_add_node_rcu(struct sock *sk, struct hlist_nulls_head *list)
757{
758 sock_hold(sk);
759 __sk_nulls_add_node_rcu(sk, list);
760}
761
762static inline void __sk_del_bind_node(struct sock *sk)
763{
764 __hlist_del(&sk->sk_bind_node);
765}
766
767static inline void sk_add_bind_node(struct sock *sk,
768 struct hlist_head *list)
769{
770 hlist_add_head(&sk->sk_bind_node, list);
771}
772
773#define sk_for_each(__sk, list) \
774 hlist_for_each_entry(__sk, list, sk_node)
775#define sk_for_each_rcu(__sk, list) \
776 hlist_for_each_entry_rcu(__sk, list, sk_node)
777#define sk_nulls_for_each(__sk, node, list) \
778 hlist_nulls_for_each_entry(__sk, node, list, sk_nulls_node)
779#define sk_nulls_for_each_rcu(__sk, node, list) \
780 hlist_nulls_for_each_entry_rcu(__sk, node, list, sk_nulls_node)
781#define sk_for_each_from(__sk) \
782 hlist_for_each_entry_from(__sk, sk_node)
783#define sk_nulls_for_each_from(__sk, node) \
784 if (__sk && ({ node = &(__sk)->sk_nulls_node; 1; })) \
785 hlist_nulls_for_each_entry_from(__sk, node, sk_nulls_node)
786#define sk_for_each_safe(__sk, tmp, list) \
787 hlist_for_each_entry_safe(__sk, tmp, list, sk_node)
788#define sk_for_each_bound(__sk, list) \
789 hlist_for_each_entry(__sk, list, sk_bind_node)
790#define sk_for_each_bound_safe(__sk, tmp, list) \
791 hlist_for_each_entry_safe(__sk, tmp, list, sk_bind_node)
792
793/**
794 * sk_for_each_entry_offset_rcu - iterate over a list at a given struct offset
795 * @tpos: the type * to use as a loop cursor.
796 * @pos: the &struct hlist_node to use as a loop cursor.
797 * @head: the head for your list.
798 * @offset: offset of hlist_node within the struct.
799 *
800 */
801#define sk_for_each_entry_offset_rcu(tpos, pos, head, offset) \
802 for (pos = rcu_dereference(hlist_first_rcu(head)); \
803 pos != NULL && \
804 ({ tpos = (typeof(*tpos) *)((void *)pos - offset); 1;}); \
805 pos = rcu_dereference(hlist_next_rcu(pos)))
806
807static inline struct user_namespace *sk_user_ns(struct sock *sk)
808{
809 /* Careful only use this in a context where these parameters
810 * can not change and must all be valid, such as recvmsg from
811 * userspace.
812 */
813 return sk->sk_socket->file->f_cred->user_ns;
814}
815
816/* Sock flags */
817enum sock_flags {
818 SOCK_DEAD,
819 SOCK_DONE,
820 SOCK_URGINLINE,
821 SOCK_KEEPOPEN,
822 SOCK_LINGER,
823 SOCK_DESTROY,
824 SOCK_BROADCAST,
825 SOCK_TIMESTAMP,
826 SOCK_ZAPPED,
827 SOCK_USE_WRITE_QUEUE, /* whether to call sk->sk_write_space in sock_wfree */
828 SOCK_DBG, /* %SO_DEBUG setting */
829 SOCK_RCVTSTAMP, /* %SO_TIMESTAMP setting */
830 SOCK_RCVTSTAMPNS, /* %SO_TIMESTAMPNS setting */
831 SOCK_LOCALROUTE, /* route locally only, %SO_DONTROUTE setting */
832 SOCK_QUEUE_SHRUNK, /* write queue has been shrunk recently */
833 SOCK_MEMALLOC, /* VM depends on this socket for swapping */
834 SOCK_TIMESTAMPING_RX_SOFTWARE, /* %SOF_TIMESTAMPING_RX_SOFTWARE */
835 SOCK_FASYNC, /* fasync() active */
836 SOCK_RXQ_OVFL,
837 SOCK_ZEROCOPY, /* buffers from userspace */
838 SOCK_WIFI_STATUS, /* push wifi status to userspace */
839 SOCK_NOFCS, /* Tell NIC not to do the Ethernet FCS.
840 * Will use last 4 bytes of packet sent from
841 * user-space instead.
842 */
843 SOCK_FILTER_LOCKED, /* Filter cannot be changed anymore */
844 SOCK_SELECT_ERR_QUEUE, /* Wake select on error queue */
845 SOCK_RCU_FREE, /* wait rcu grace period in sk_destruct() */
846 SOCK_TXTIME,
847 SOCK_XDP, /* XDP is attached */
848 SOCK_TSTAMP_NEW, /* Indicates 64 bit timestamps always */
849};
850
851#define SK_FLAGS_TIMESTAMP ((1UL << SOCK_TIMESTAMP) | (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE))
852
853static inline void sock_copy_flags(struct sock *nsk, struct sock *osk)
854{
855 nsk->sk_flags = osk->sk_flags;
856}
857
858static inline void sock_set_flag(struct sock *sk, enum sock_flags flag)
859{
860 __set_bit(flag, &sk->sk_flags);
861}
862
863static inline void sock_reset_flag(struct sock *sk, enum sock_flags flag)
864{
865 __clear_bit(flag, &sk->sk_flags);
866}
867
868static inline bool sock_flag(const struct sock *sk, enum sock_flags flag)
869{
870 return test_bit(flag, &sk->sk_flags);
871}
872
873#ifdef CONFIG_NET
874DECLARE_STATIC_KEY_FALSE(memalloc_socks_key);
875static inline int sk_memalloc_socks(void)
876{
877 return static_branch_unlikely(&memalloc_socks_key);
878}
879
880void __receive_sock(struct file *file);
881#else
882
883static inline int sk_memalloc_socks(void)
884{
885 return 0;
886}
887
888static inline void __receive_sock(struct file *file)
889{ }
890#endif
891
892static inline gfp_t sk_gfp_mask(const struct sock *sk, gfp_t gfp_mask)
893{
894 return gfp_mask | (sk->sk_allocation & __GFP_MEMALLOC);
895}
896
897static inline void sk_acceptq_removed(struct sock *sk)
898{
899 WRITE_ONCE(sk->sk_ack_backlog, sk->sk_ack_backlog - 1);
900}
901
902static inline void sk_acceptq_added(struct sock *sk)
903{
904 WRITE_ONCE(sk->sk_ack_backlog, sk->sk_ack_backlog + 1);
905}
906
907static inline bool sk_acceptq_is_full(const struct sock *sk)
908{
909 return READ_ONCE(sk->sk_ack_backlog) > READ_ONCE(sk->sk_max_ack_backlog);
910}
911
912/*
913 * Compute minimal free write space needed to queue new packets.
914 */
915static inline int sk_stream_min_wspace(const struct sock *sk)
916{
917 return READ_ONCE(sk->sk_wmem_queued) >> 1;
918}
919
920static inline int sk_stream_wspace(const struct sock *sk)
921{
922 return READ_ONCE(sk->sk_sndbuf) - READ_ONCE(sk->sk_wmem_queued);
923}
924
925static inline void sk_wmem_queued_add(struct sock *sk, int val)
926{
927 WRITE_ONCE(sk->sk_wmem_queued, sk->sk_wmem_queued + val);
928}
929
930void sk_stream_write_space(struct sock *sk);
931
932/* OOB backlog add */
933static inline void __sk_add_backlog(struct sock *sk, struct sk_buff *skb)
934{
935 /* dont let skb dst not refcounted, we are going to leave rcu lock */
936 skb_dst_force(skb);
937
938 if (!sk->sk_backlog.tail)
939 WRITE_ONCE(sk->sk_backlog.head, skb);
940 else
941 sk->sk_backlog.tail->next = skb;
942
943 WRITE_ONCE(sk->sk_backlog.tail, skb);
944 skb->next = NULL;
945}
946
947/*
948 * Take into account size of receive queue and backlog queue
949 * Do not take into account this skb truesize,
950 * to allow even a single big packet to come.
951 */
952static inline bool sk_rcvqueues_full(const struct sock *sk, unsigned int limit)
953{
954 unsigned int qsize = sk->sk_backlog.len + atomic_read(&sk->sk_rmem_alloc);
955
956 return qsize > limit;
957}
958
959/* The per-socket spinlock must be held here. */
960static inline __must_check int sk_add_backlog(struct sock *sk, struct sk_buff *skb,
961 unsigned int limit)
962{
963 if (sk_rcvqueues_full(sk, limit))
964 return -ENOBUFS;
965
966 /*
967 * If the skb was allocated from pfmemalloc reserves, only
968 * allow SOCK_MEMALLOC sockets to use it as this socket is
969 * helping free memory
970 */
971 if (skb_pfmemalloc(skb) && !sock_flag(sk, SOCK_MEMALLOC))
972 return -ENOMEM;
973
974 __sk_add_backlog(sk, skb);
975 sk->sk_backlog.len += skb->truesize;
976 return 0;
977}
978
979int __sk_backlog_rcv(struct sock *sk, struct sk_buff *skb);
980
981static inline int sk_backlog_rcv(struct sock *sk, struct sk_buff *skb)
982{
983 if (sk_memalloc_socks() && skb_pfmemalloc(skb))
984 return __sk_backlog_rcv(sk, skb);
985
986 return sk->sk_backlog_rcv(sk, skb);
987}
988
989static inline void sk_incoming_cpu_update(struct sock *sk)
990{
991 int cpu = raw_smp_processor_id();
992
993 if (unlikely(READ_ONCE(sk->sk_incoming_cpu) != cpu))
994 WRITE_ONCE(sk->sk_incoming_cpu, cpu);
995}
996
997static inline void sock_rps_record_flow_hash(__u32 hash)
998{
999#ifdef CONFIG_RPS
1000 struct rps_sock_flow_table *sock_flow_table;
1001
1002 rcu_read_lock();
1003 sock_flow_table = rcu_dereference(rps_sock_flow_table);
1004 rps_record_sock_flow(sock_flow_table, hash);
1005 rcu_read_unlock();
1006#endif
1007}
1008
1009static inline void sock_rps_record_flow(const struct sock *sk)
1010{
1011#ifdef CONFIG_RPS
1012 if (static_branch_unlikely(&rfs_needed)) {
1013 /* Reading sk->sk_rxhash might incur an expensive cache line
1014 * miss.
1015 *
1016 * TCP_ESTABLISHED does cover almost all states where RFS
1017 * might be useful, and is cheaper [1] than testing :
1018 * IPv4: inet_sk(sk)->inet_daddr
1019 * IPv6: ipv6_addr_any(&sk->sk_v6_daddr)
1020 * OR an additional socket flag
1021 * [1] : sk_state and sk_prot are in the same cache line.
1022 */
1023 if (sk->sk_state == TCP_ESTABLISHED) {
1024 /* This READ_ONCE() is paired with the WRITE_ONCE()
1025 * from sock_rps_save_rxhash() and sock_rps_reset_rxhash().
1026 */
1027 sock_rps_record_flow_hash(READ_ONCE(sk->sk_rxhash));
1028 }
1029 }
1030#endif
1031}
1032
1033static inline void sock_rps_save_rxhash(struct sock *sk,
1034 const struct sk_buff *skb)
1035{
1036#ifdef CONFIG_RPS
1037 /* The following WRITE_ONCE() is paired with the READ_ONCE()
1038 * here, and another one in sock_rps_record_flow().
1039 */
1040 if (unlikely(READ_ONCE(sk->sk_rxhash) != skb->hash))
1041 WRITE_ONCE(sk->sk_rxhash, skb->hash);
1042#endif
1043}
1044
1045static inline void sock_rps_reset_rxhash(struct sock *sk)
1046{
1047#ifdef CONFIG_RPS
1048 /* Paired with READ_ONCE() in sock_rps_record_flow() */
1049 WRITE_ONCE(sk->sk_rxhash, 0);
1050#endif
1051}
1052
1053#define sk_wait_event(__sk, __timeo, __condition, __wait) \
1054 ({ int __rc; \
1055 __sk->sk_wait_pending++; \
1056 release_sock(__sk); \
1057 __rc = __condition; \
1058 if (!__rc) { \
1059 *(__timeo) = wait_woken(__wait, \
1060 TASK_INTERRUPTIBLE, \
1061 *(__timeo)); \
1062 } \
1063 sched_annotate_sleep(); \
1064 lock_sock(__sk); \
1065 __sk->sk_wait_pending--; \
1066 __rc = __condition; \
1067 __rc; \
1068 })
1069
1070int sk_stream_wait_connect(struct sock *sk, long *timeo_p);
1071int sk_stream_wait_memory(struct sock *sk, long *timeo_p);
1072void sk_stream_wait_close(struct sock *sk, long timeo_p);
1073int sk_stream_error(struct sock *sk, int flags, int err);
1074void sk_stream_kill_queues(struct sock *sk);
1075void sk_set_memalloc(struct sock *sk);
1076void sk_clear_memalloc(struct sock *sk);
1077
1078void __sk_flush_backlog(struct sock *sk);
1079
1080static inline bool sk_flush_backlog(struct sock *sk)
1081{
1082 if (unlikely(READ_ONCE(sk->sk_backlog.tail))) {
1083 __sk_flush_backlog(sk);
1084 return true;
1085 }
1086 return false;
1087}
1088
1089int sk_wait_data(struct sock *sk, long *timeo, const struct sk_buff *skb);
1090
1091struct request_sock_ops;
1092struct timewait_sock_ops;
1093struct inet_hashinfo;
1094struct raw_hashinfo;
1095struct smc_hashinfo;
1096struct module;
1097
1098/*
1099 * caches using SLAB_TYPESAFE_BY_RCU should let .next pointer from nulls nodes
1100 * un-modified. Special care is taken when initializing object to zero.
1101 */
1102static inline void sk_prot_clear_nulls(struct sock *sk, int size)
1103{
1104 if (offsetof(struct sock, sk_node.next) != 0)
1105 memset(sk, 0, offsetof(struct sock, sk_node.next));
1106 memset(&sk->sk_node.pprev, 0,
1107 size - offsetof(struct sock, sk_node.pprev));
1108}
1109
1110/* Networking protocol blocks we attach to sockets.
1111 * socket layer -> transport layer interface
1112 */
1113struct proto {
1114 void (*close)(struct sock *sk,
1115 long timeout);
1116 int (*pre_connect)(struct sock *sk,
1117 struct sockaddr *uaddr,
1118 int addr_len);
1119 int (*connect)(struct sock *sk,
1120 struct sockaddr *uaddr,
1121 int addr_len);
1122 int (*disconnect)(struct sock *sk, int flags);
1123
1124 struct sock * (*accept)(struct sock *sk, int flags, int *err,
1125 bool kern);
1126
1127 int (*ioctl)(struct sock *sk, int cmd,
1128 unsigned long arg);
1129 int (*init)(struct sock *sk);
1130 void (*destroy)(struct sock *sk);
1131 void (*shutdown)(struct sock *sk, int how);
1132 int (*setsockopt)(struct sock *sk, int level,
1133 int optname, char __user *optval,
1134 unsigned int optlen);
1135 int (*getsockopt)(struct sock *sk, int level,
1136 int optname, char __user *optval,
1137 int __user *option);
1138 void (*keepalive)(struct sock *sk, int valbool);
1139#ifdef CONFIG_COMPAT
1140 int (*compat_setsockopt)(struct sock *sk,
1141 int level,
1142 int optname, char __user *optval,
1143 unsigned int optlen);
1144 int (*compat_getsockopt)(struct sock *sk,
1145 int level,
1146 int optname, char __user *optval,
1147 int __user *option);
1148 int (*compat_ioctl)(struct sock *sk,
1149 unsigned int cmd, unsigned long arg);
1150#endif
1151 int (*sendmsg)(struct sock *sk, struct msghdr *msg,
1152 size_t len);
1153 int (*recvmsg)(struct sock *sk, struct msghdr *msg,
1154 size_t len, int noblock, int flags,
1155 int *addr_len);
1156 int (*sendpage)(struct sock *sk, struct page *page,
1157 int offset, size_t size, int flags);
1158 int (*bind)(struct sock *sk,
1159 struct sockaddr *uaddr, int addr_len);
1160
1161 int (*backlog_rcv) (struct sock *sk,
1162 struct sk_buff *skb);
1163
1164 void (*release_cb)(struct sock *sk);
1165
1166 /* Keeping track of sk's, looking them up, and port selection methods. */
1167 int (*hash)(struct sock *sk);
1168 void (*unhash)(struct sock *sk);
1169 void (*rehash)(struct sock *sk);
1170 int (*get_port)(struct sock *sk, unsigned short snum);
1171
1172 /* Keeping track of sockets in use */
1173#ifdef CONFIG_PROC_FS
1174 unsigned int inuse_idx;
1175#endif
1176
1177 bool (*stream_memory_free)(const struct sock *sk, int wake);
1178 bool (*stream_memory_read)(const struct sock *sk);
1179 /* Memory pressure */
1180 void (*enter_memory_pressure)(struct sock *sk);
1181 void (*leave_memory_pressure)(struct sock *sk);
1182 atomic_long_t *memory_allocated; /* Current allocated memory. */
1183 struct percpu_counter *sockets_allocated; /* Current number of sockets. */
1184 /*
1185 * Pressure flag: try to collapse.
1186 * Technical note: it is used by multiple contexts non atomically.
1187 * Make sure to use READ_ONCE()/WRITE_ONCE() for all reads/writes.
1188 * All the __sk_mem_schedule() is of this nature: accounting
1189 * is strict, actions are advisory and have some latency.
1190 */
1191 unsigned long *memory_pressure;
1192 long *sysctl_mem;
1193
1194 int *sysctl_wmem;
1195 int *sysctl_rmem;
1196 u32 sysctl_wmem_offset;
1197 u32 sysctl_rmem_offset;
1198
1199 int max_header;
1200 bool no_autobind;
1201
1202 struct kmem_cache *slab;
1203 unsigned int obj_size;
1204 slab_flags_t slab_flags;
1205 unsigned int useroffset; /* Usercopy region offset */
1206 unsigned int usersize; /* Usercopy region size */
1207
1208 struct percpu_counter *orphan_count;
1209
1210 struct request_sock_ops *rsk_prot;
1211 struct timewait_sock_ops *twsk_prot;
1212
1213 union {
1214 struct inet_hashinfo *hashinfo;
1215 struct udp_table *udp_table;
1216 struct raw_hashinfo *raw_hash;
1217 struct smc_hashinfo *smc_hash;
1218 } h;
1219
1220 struct module *owner;
1221
1222 char name[32];
1223
1224 struct list_head node;
1225#ifdef SOCK_REFCNT_DEBUG
1226 atomic_t socks;
1227#endif
1228 int (*diag_destroy)(struct sock *sk, int err);
1229} __randomize_layout;
1230
1231int proto_register(struct proto *prot, int alloc_slab);
1232void proto_unregister(struct proto *prot);
1233int sock_load_diag_module(int family, int protocol);
1234
1235#ifdef SOCK_REFCNT_DEBUG
1236static inline void sk_refcnt_debug_inc(struct sock *sk)
1237{
1238 atomic_inc(&sk->sk_prot->socks);
1239}
1240
1241static inline void sk_refcnt_debug_dec(struct sock *sk)
1242{
1243 atomic_dec(&sk->sk_prot->socks);
1244 printk(KERN_DEBUG "%s socket %p released, %d are still alive\n",
1245 sk->sk_prot->name, sk, atomic_read(&sk->sk_prot->socks));
1246}
1247
1248static inline void sk_refcnt_debug_release(const struct sock *sk)
1249{
1250 if (refcount_read(&sk->sk_refcnt) != 1)
1251 printk(KERN_DEBUG "Destruction of the %s socket %p delayed, refcnt=%d\n",
1252 sk->sk_prot->name, sk, refcount_read(&sk->sk_refcnt));
1253}
1254#else /* SOCK_REFCNT_DEBUG */
1255#define sk_refcnt_debug_inc(sk) do { } while (0)
1256#define sk_refcnt_debug_dec(sk) do { } while (0)
1257#define sk_refcnt_debug_release(sk) do { } while (0)
1258#endif /* SOCK_REFCNT_DEBUG */
1259
1260static inline bool __sk_stream_memory_free(const struct sock *sk, int wake)
1261{
1262 if (READ_ONCE(sk->sk_wmem_queued) >= READ_ONCE(sk->sk_sndbuf))
1263 return false;
1264
1265 return sk->sk_prot->stream_memory_free ?
1266 sk->sk_prot->stream_memory_free(sk, wake) : true;
1267}
1268
1269static inline bool sk_stream_memory_free(const struct sock *sk)
1270{
1271 return __sk_stream_memory_free(sk, 0);
1272}
1273
1274static inline bool __sk_stream_is_writeable(const struct sock *sk, int wake)
1275{
1276 return sk_stream_wspace(sk) >= sk_stream_min_wspace(sk) &&
1277 __sk_stream_memory_free(sk, wake);
1278}
1279
1280static inline bool sk_stream_is_writeable(const struct sock *sk)
1281{
1282 return __sk_stream_is_writeable(sk, 0);
1283}
1284
1285static inline int sk_under_cgroup_hierarchy(struct sock *sk,
1286 struct cgroup *ancestor)
1287{
1288#ifdef CONFIG_SOCK_CGROUP_DATA
1289 return cgroup_is_descendant(sock_cgroup_ptr(&sk->sk_cgrp_data),
1290 ancestor);
1291#else
1292 return -ENOTSUPP;
1293#endif
1294}
1295
1296static inline bool sk_has_memory_pressure(const struct sock *sk)
1297{
1298 return sk->sk_prot->memory_pressure != NULL;
1299}
1300
1301static inline bool sk_under_global_memory_pressure(const struct sock *sk)
1302{
1303 return sk->sk_prot->memory_pressure &&
1304 !!READ_ONCE(*sk->sk_prot->memory_pressure);
1305}
1306
1307static inline bool sk_under_memory_pressure(const struct sock *sk)
1308{
1309 if (!sk->sk_prot->memory_pressure)
1310 return false;
1311
1312 if (mem_cgroup_sockets_enabled && sk->sk_memcg &&
1313 mem_cgroup_under_socket_pressure(sk->sk_memcg))
1314 return true;
1315
1316 return !!READ_ONCE(*sk->sk_prot->memory_pressure);
1317}
1318
1319static inline long
1320sk_memory_allocated(const struct sock *sk)
1321{
1322 return atomic_long_read(sk->sk_prot->memory_allocated);
1323}
1324
1325static inline long
1326sk_memory_allocated_add(struct sock *sk, int amt)
1327{
1328 return atomic_long_add_return(amt, sk->sk_prot->memory_allocated);
1329}
1330
1331static inline void
1332sk_memory_allocated_sub(struct sock *sk, int amt)
1333{
1334 atomic_long_sub(amt, sk->sk_prot->memory_allocated);
1335}
1336
1337static inline void sk_sockets_allocated_dec(struct sock *sk)
1338{
1339 percpu_counter_dec(sk->sk_prot->sockets_allocated);
1340}
1341
1342static inline void sk_sockets_allocated_inc(struct sock *sk)
1343{
1344 percpu_counter_inc(sk->sk_prot->sockets_allocated);
1345}
1346
1347static inline u64
1348sk_sockets_allocated_read_positive(struct sock *sk)
1349{
1350 return percpu_counter_read_positive(sk->sk_prot->sockets_allocated);
1351}
1352
1353static inline int
1354proto_sockets_allocated_sum_positive(struct proto *prot)
1355{
1356 return percpu_counter_sum_positive(prot->sockets_allocated);
1357}
1358
1359static inline long
1360proto_memory_allocated(struct proto *prot)
1361{
1362 return atomic_long_read(prot->memory_allocated);
1363}
1364
1365static inline bool
1366proto_memory_pressure(struct proto *prot)
1367{
1368 if (!prot->memory_pressure)
1369 return false;
1370 return !!READ_ONCE(*prot->memory_pressure);
1371}
1372
1373
1374#ifdef CONFIG_PROC_FS
1375/* Called with local bh disabled */
1376void sock_prot_inuse_add(struct net *net, struct proto *prot, int inc);
1377int sock_prot_inuse_get(struct net *net, struct proto *proto);
1378int sock_inuse_get(struct net *net);
1379#else
1380static inline void sock_prot_inuse_add(struct net *net, struct proto *prot,
1381 int inc)
1382{
1383}
1384#endif
1385
1386
1387/* With per-bucket locks this operation is not-atomic, so that
1388 * this version is not worse.
1389 */
1390static inline int __sk_prot_rehash(struct sock *sk)
1391{
1392 sk->sk_prot->unhash(sk);
1393 return sk->sk_prot->hash(sk);
1394}
1395
1396/* About 10 seconds */
1397#define SOCK_DESTROY_TIME (10*HZ)
1398
1399/* Sockets 0-1023 can't be bound to unless you are superuser */
1400#define PROT_SOCK 1024
1401
1402#define SHUTDOWN_MASK 3
1403#define RCV_SHUTDOWN 1
1404#define SEND_SHUTDOWN 2
1405
1406#define SOCK_SNDBUF_LOCK 1
1407#define SOCK_RCVBUF_LOCK 2
1408#define SOCK_BINDADDR_LOCK 4
1409#define SOCK_BINDPORT_LOCK 8
1410
1411struct socket_alloc {
1412 struct socket socket;
1413 struct inode vfs_inode;
1414};
1415
1416static inline struct socket *SOCKET_I(struct inode *inode)
1417{
1418 return &container_of(inode, struct socket_alloc, vfs_inode)->socket;
1419}
1420
1421static inline struct inode *SOCK_INODE(struct socket *socket)
1422{
1423 return &container_of(socket, struct socket_alloc, socket)->vfs_inode;
1424}
1425
1426/*
1427 * Functions for memory accounting
1428 */
1429int __sk_mem_raise_allocated(struct sock *sk, int size, int amt, int kind);
1430int __sk_mem_schedule(struct sock *sk, int size, int kind);
1431void __sk_mem_reduce_allocated(struct sock *sk, int amount);
1432void __sk_mem_reclaim(struct sock *sk, int amount);
1433
1434/* We used to have PAGE_SIZE here, but systems with 64KB pages
1435 * do not necessarily have 16x time more memory than 4KB ones.
1436 */
1437#define SK_MEM_QUANTUM 4096
1438#define SK_MEM_QUANTUM_SHIFT ilog2(SK_MEM_QUANTUM)
1439#define SK_MEM_SEND 0
1440#define SK_MEM_RECV 1
1441
1442/* sysctl_mem values are in pages, we convert them in SK_MEM_QUANTUM units */
1443static inline long sk_prot_mem_limits(const struct sock *sk, int index)
1444{
1445 long val = READ_ONCE(sk->sk_prot->sysctl_mem[index]);
1446
1447#if PAGE_SIZE > SK_MEM_QUANTUM
1448 val <<= PAGE_SHIFT - SK_MEM_QUANTUM_SHIFT;
1449#elif PAGE_SIZE < SK_MEM_QUANTUM
1450 val >>= SK_MEM_QUANTUM_SHIFT - PAGE_SHIFT;
1451#endif
1452 return val;
1453}
1454
1455static inline int sk_mem_pages(int amt)
1456{
1457 return (amt + SK_MEM_QUANTUM - 1) >> SK_MEM_QUANTUM_SHIFT;
1458}
1459
1460static inline bool sk_has_account(struct sock *sk)
1461{
1462 /* return true if protocol supports memory accounting */
1463 return !!sk->sk_prot->memory_allocated;
1464}
1465
1466static inline bool sk_wmem_schedule(struct sock *sk, int size)
1467{
1468 if (!sk_has_account(sk))
1469 return true;
1470 return size <= sk->sk_forward_alloc ||
1471 __sk_mem_schedule(sk, size, SK_MEM_SEND);
1472}
1473
1474static inline bool
1475sk_rmem_schedule(struct sock *sk, struct sk_buff *skb, int size)
1476{
1477 if (!sk_has_account(sk))
1478 return true;
1479 return size<= sk->sk_forward_alloc ||
1480 __sk_mem_schedule(sk, size, SK_MEM_RECV) ||
1481 skb_pfmemalloc(skb);
1482}
1483
1484static inline void sk_mem_reclaim(struct sock *sk)
1485{
1486 if (!sk_has_account(sk))
1487 return;
1488 if (sk->sk_forward_alloc >= SK_MEM_QUANTUM)
1489 __sk_mem_reclaim(sk, sk->sk_forward_alloc);
1490}
1491
1492static inline void sk_mem_reclaim_partial(struct sock *sk)
1493{
1494 if (!sk_has_account(sk))
1495 return;
1496 if (sk->sk_forward_alloc > SK_MEM_QUANTUM)
1497 __sk_mem_reclaim(sk, sk->sk_forward_alloc - 1);
1498}
1499
1500static inline void sk_mem_charge(struct sock *sk, int size)
1501{
1502 if (!sk_has_account(sk))
1503 return;
1504 sk->sk_forward_alloc -= size;
1505}
1506
1507static inline void sk_mem_uncharge(struct sock *sk, int size)
1508{
1509 if (!sk_has_account(sk))
1510 return;
1511 sk->sk_forward_alloc += size;
1512
1513 /* Avoid a possible overflow.
1514 * TCP send queues can make this happen, if sk_mem_reclaim()
1515 * is not called and more than 2 GBytes are released at once.
1516 *
1517 * If we reach 2 MBytes, reclaim 1 MBytes right now, there is
1518 * no need to hold that much forward allocation anyway.
1519 */
1520 if (unlikely(sk->sk_forward_alloc >= 1 << 21))
1521 __sk_mem_reclaim(sk, 1 << 20);
1522}
1523
1524DECLARE_STATIC_KEY_FALSE(tcp_tx_skb_cache_key);
1525static inline void sk_wmem_free_skb(struct sock *sk, struct sk_buff *skb)
1526{
1527 sock_set_flag(sk, SOCK_QUEUE_SHRUNK);
1528 sk_wmem_queued_add(sk, -skb->truesize);
1529 sk_mem_uncharge(sk, skb->truesize);
1530 if (static_branch_unlikely(&tcp_tx_skb_cache_key) &&
1531 !sk->sk_tx_skb_cache && !skb_cloned(skb)) {
1532 skb_zcopy_clear(skb, true);
1533 sk->sk_tx_skb_cache = skb;
1534 return;
1535 }
1536 __kfree_skb(skb);
1537}
1538
1539static inline void sock_release_ownership(struct sock *sk)
1540{
1541 if (sk->sk_lock.owned) {
1542 sk->sk_lock.owned = 0;
1543
1544 /* The sk_lock has mutex_unlock() semantics: */
1545 mutex_release(&sk->sk_lock.dep_map, 1, _RET_IP_);
1546 }
1547}
1548
1549/*
1550 * Macro so as to not evaluate some arguments when
1551 * lockdep is not enabled.
1552 *
1553 * Mark both the sk_lock and the sk_lock.slock as a
1554 * per-address-family lock class.
1555 */
1556#define sock_lock_init_class_and_name(sk, sname, skey, name, key) \
1557do { \
1558 sk->sk_lock.owned = 0; \
1559 init_waitqueue_head(&sk->sk_lock.wq); \
1560 spin_lock_init(&(sk)->sk_lock.slock); \
1561 debug_check_no_locks_freed((void *)&(sk)->sk_lock, \
1562 sizeof((sk)->sk_lock)); \
1563 lockdep_set_class_and_name(&(sk)->sk_lock.slock, \
1564 (skey), (sname)); \
1565 lockdep_init_map(&(sk)->sk_lock.dep_map, (name), (key), 0); \
1566} while (0)
1567
1568#ifdef CONFIG_LOCKDEP
1569static inline bool lockdep_sock_is_held(const struct sock *sk)
1570{
1571 return lockdep_is_held(&sk->sk_lock) ||
1572 lockdep_is_held(&sk->sk_lock.slock);
1573}
1574#endif
1575
1576void lock_sock_nested(struct sock *sk, int subclass);
1577
1578static inline void lock_sock(struct sock *sk)
1579{
1580 lock_sock_nested(sk, 0);
1581}
1582
1583void __release_sock(struct sock *sk);
1584void release_sock(struct sock *sk);
1585
1586/* BH context may only use the following locking interface. */
1587#define bh_lock_sock(__sk) spin_lock(&((__sk)->sk_lock.slock))
1588#define bh_lock_sock_nested(__sk) \
1589 spin_lock_nested(&((__sk)->sk_lock.slock), \
1590 SINGLE_DEPTH_NESTING)
1591#define bh_unlock_sock(__sk) spin_unlock(&((__sk)->sk_lock.slock))
1592
1593bool lock_sock_fast(struct sock *sk);
1594/**
1595 * unlock_sock_fast - complement of lock_sock_fast
1596 * @sk: socket
1597 * @slow: slow mode
1598 *
1599 * fast unlock socket for user context.
1600 * If slow mode is on, we call regular release_sock()
1601 */
1602static inline void unlock_sock_fast(struct sock *sk, bool slow)
1603{
1604 if (slow)
1605 release_sock(sk);
1606 else
1607 spin_unlock_bh(&sk->sk_lock.slock);
1608}
1609
1610/* Used by processes to "lock" a socket state, so that
1611 * interrupts and bottom half handlers won't change it
1612 * from under us. It essentially blocks any incoming
1613 * packets, so that we won't get any new data or any
1614 * packets that change the state of the socket.
1615 *
1616 * While locked, BH processing will add new packets to
1617 * the backlog queue. This queue is processed by the
1618 * owner of the socket lock right before it is released.
1619 *
1620 * Since ~2.3.5 it is also exclusive sleep lock serializing
1621 * accesses from user process context.
1622 */
1623
1624static inline void sock_owned_by_me(const struct sock *sk)
1625{
1626#ifdef CONFIG_LOCKDEP
1627 WARN_ON_ONCE(!lockdep_sock_is_held(sk) && debug_locks);
1628#endif
1629}
1630
1631static inline void sock_not_owned_by_me(const struct sock *sk)
1632{
1633#ifdef CONFIG_LOCKDEP
1634 WARN_ON_ONCE(lockdep_sock_is_held(sk) && debug_locks);
1635#endif
1636}
1637
1638static inline bool sock_owned_by_user(const struct sock *sk)
1639{
1640 sock_owned_by_me(sk);
1641 return sk->sk_lock.owned;
1642}
1643
1644static inline bool sock_owned_by_user_nocheck(const struct sock *sk)
1645{
1646 return sk->sk_lock.owned;
1647}
1648
1649/* no reclassification while locks are held */
1650static inline bool sock_allow_reclassification(const struct sock *csk)
1651{
1652 struct sock *sk = (struct sock *)csk;
1653
1654 return !sk->sk_lock.owned && !spin_is_locked(&sk->sk_lock.slock);
1655}
1656
1657struct sock *sk_alloc(struct net *net, int family, gfp_t priority,
1658 struct proto *prot, int kern);
1659void sk_free(struct sock *sk);
1660void sk_destruct(struct sock *sk);
1661struct sock *sk_clone_lock(const struct sock *sk, const gfp_t priority);
1662void sk_free_unlock_clone(struct sock *sk);
1663
1664struct sk_buff *sock_wmalloc(struct sock *sk, unsigned long size, int force,
1665 gfp_t priority);
1666void __sock_wfree(struct sk_buff *skb);
1667void sock_wfree(struct sk_buff *skb);
1668struct sk_buff *sock_omalloc(struct sock *sk, unsigned long size,
1669 gfp_t priority);
1670void skb_orphan_partial(struct sk_buff *skb);
1671void sock_rfree(struct sk_buff *skb);
1672void sock_efree(struct sk_buff *skb);
1673#ifdef CONFIG_INET
1674void sock_edemux(struct sk_buff *skb);
1675#else
1676#define sock_edemux sock_efree
1677#endif
1678
1679int sock_setsockopt(struct socket *sock, int level, int op,
1680 char __user *optval, unsigned int optlen);
1681
1682int sock_getsockopt(struct socket *sock, int level, int op,
1683 char __user *optval, int __user *optlen);
1684int sock_gettstamp(struct socket *sock, void __user *userstamp,
1685 bool timeval, bool time32);
1686struct sk_buff *sock_alloc_send_skb(struct sock *sk, unsigned long size,
1687 int noblock, int *errcode);
1688struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
1689 unsigned long data_len, int noblock,
1690 int *errcode, int max_page_order);
1691void *sock_kmalloc(struct sock *sk, int size, gfp_t priority);
1692void sock_kfree_s(struct sock *sk, void *mem, int size);
1693void sock_kzfree_s(struct sock *sk, void *mem, int size);
1694void sk_send_sigurg(struct sock *sk);
1695
1696struct sockcm_cookie {
1697 u64 transmit_time;
1698 u32 mark;
1699 u16 tsflags;
1700};
1701
1702static inline void sockcm_init(struct sockcm_cookie *sockc,
1703 const struct sock *sk)
1704{
1705 *sockc = (struct sockcm_cookie) { .tsflags = sk->sk_tsflags };
1706}
1707
1708int __sock_cmsg_send(struct sock *sk, struct msghdr *msg, struct cmsghdr *cmsg,
1709 struct sockcm_cookie *sockc);
1710int sock_cmsg_send(struct sock *sk, struct msghdr *msg,
1711 struct sockcm_cookie *sockc);
1712
1713/*
1714 * Functions to fill in entries in struct proto_ops when a protocol
1715 * does not implement a particular function.
1716 */
1717int sock_no_bind(struct socket *, struct sockaddr *, int);
1718int sock_no_connect(struct socket *, struct sockaddr *, int, int);
1719int sock_no_socketpair(struct socket *, struct socket *);
1720int sock_no_accept(struct socket *, struct socket *, int, bool);
1721int sock_no_getname(struct socket *, struct sockaddr *, int);
1722int sock_no_ioctl(struct socket *, unsigned int, unsigned long);
1723int sock_no_listen(struct socket *, int);
1724int sock_no_shutdown(struct socket *, int);
1725int sock_no_getsockopt(struct socket *, int , int, char __user *, int __user *);
1726int sock_no_setsockopt(struct socket *, int, int, char __user *, unsigned int);
1727int sock_no_sendmsg(struct socket *, struct msghdr *, size_t);
1728int sock_no_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t len);
1729int sock_no_recvmsg(struct socket *, struct msghdr *, size_t, int);
1730int sock_no_mmap(struct file *file, struct socket *sock,
1731 struct vm_area_struct *vma);
1732ssize_t sock_no_sendpage(struct socket *sock, struct page *page, int offset,
1733 size_t size, int flags);
1734ssize_t sock_no_sendpage_locked(struct sock *sk, struct page *page,
1735 int offset, size_t size, int flags);
1736
1737/*
1738 * Functions to fill in entries in struct proto_ops when a protocol
1739 * uses the inet style.
1740 */
1741int sock_common_getsockopt(struct socket *sock, int level, int optname,
1742 char __user *optval, int __user *optlen);
1743int sock_common_recvmsg(struct socket *sock, struct msghdr *msg, size_t size,
1744 int flags);
1745int sock_common_setsockopt(struct socket *sock, int level, int optname,
1746 char __user *optval, unsigned int optlen);
1747int compat_sock_common_getsockopt(struct socket *sock, int level,
1748 int optname, char __user *optval, int __user *optlen);
1749int compat_sock_common_setsockopt(struct socket *sock, int level,
1750 int optname, char __user *optval, unsigned int optlen);
1751
1752void sk_common_release(struct sock *sk);
1753
1754/*
1755 * Default socket callbacks and setup code
1756 */
1757
1758/* Initialise core socket variables using an explicit uid. */
1759void sock_init_data_uid(struct socket *sock, struct sock *sk, kuid_t uid);
1760
1761/* Initialise core socket variables.
1762 * Assumes struct socket *sock is embedded in a struct socket_alloc.
1763 */
1764void sock_init_data(struct socket *sock, struct sock *sk);
1765
1766/*
1767 * Socket reference counting postulates.
1768 *
1769 * * Each user of socket SHOULD hold a reference count.
1770 * * Each access point to socket (an hash table bucket, reference from a list,
1771 * running timer, skb in flight MUST hold a reference count.
1772 * * When reference count hits 0, it means it will never increase back.
1773 * * When reference count hits 0, it means that no references from
1774 * outside exist to this socket and current process on current CPU
1775 * is last user and may/should destroy this socket.
1776 * * sk_free is called from any context: process, BH, IRQ. When
1777 * it is called, socket has no references from outside -> sk_free
1778 * may release descendant resources allocated by the socket, but
1779 * to the time when it is called, socket is NOT referenced by any
1780 * hash tables, lists etc.
1781 * * Packets, delivered from outside (from network or from another process)
1782 * and enqueued on receive/error queues SHOULD NOT grab reference count,
1783 * when they sit in queue. Otherwise, packets will leak to hole, when
1784 * socket is looked up by one cpu and unhasing is made by another CPU.
1785 * It is true for udp/raw, netlink (leak to receive and error queues), tcp
1786 * (leak to backlog). Packet socket does all the processing inside
1787 * BR_NETPROTO_LOCK, so that it has not this race condition. UNIX sockets
1788 * use separate SMP lock, so that they are prone too.
1789 */
1790
1791/* Ungrab socket and destroy it, if it was the last reference. */
1792static inline void sock_put(struct sock *sk)
1793{
1794 if (refcount_dec_and_test(&sk->sk_refcnt))
1795 sk_free(sk);
1796}
1797/* Generic version of sock_put(), dealing with all sockets
1798 * (TCP_TIMEWAIT, TCP_NEW_SYN_RECV, ESTABLISHED...)
1799 */
1800void sock_gen_put(struct sock *sk);
1801
1802int __sk_receive_skb(struct sock *sk, struct sk_buff *skb, const int nested,
1803 unsigned int trim_cap, bool refcounted);
1804static inline int sk_receive_skb(struct sock *sk, struct sk_buff *skb,
1805 const int nested)
1806{
1807 return __sk_receive_skb(sk, skb, nested, 1, true);
1808}
1809
1810static inline void sk_tx_queue_set(struct sock *sk, int tx_queue)
1811{
1812 /* sk_tx_queue_mapping accept only upto a 16-bit value */
1813 if (WARN_ON_ONCE((unsigned short)tx_queue >= USHRT_MAX))
1814 return;
1815 /* Paired with READ_ONCE() in sk_tx_queue_get() and
1816 * other WRITE_ONCE() because socket lock might be not held.
1817 */
1818 WRITE_ONCE(sk->sk_tx_queue_mapping, tx_queue);
1819}
1820
1821#define NO_QUEUE_MAPPING USHRT_MAX
1822
1823static inline void sk_tx_queue_clear(struct sock *sk)
1824{
1825 /* Paired with READ_ONCE() in sk_tx_queue_get() and
1826 * other WRITE_ONCE() because socket lock might be not held.
1827 */
1828 WRITE_ONCE(sk->sk_tx_queue_mapping, NO_QUEUE_MAPPING);
1829}
1830
1831static inline int sk_tx_queue_get(const struct sock *sk)
1832{
1833 if (sk) {
1834 /* Paired with WRITE_ONCE() in sk_tx_queue_clear()
1835 * and sk_tx_queue_set().
1836 */
1837 int val = READ_ONCE(sk->sk_tx_queue_mapping);
1838
1839 if (val != NO_QUEUE_MAPPING)
1840 return val;
1841 }
1842 return -1;
1843}
1844
1845static inline void sk_rx_queue_set(struct sock *sk, const struct sk_buff *skb)
1846{
1847#ifdef CONFIG_XPS
1848 if (skb_rx_queue_recorded(skb)) {
1849 u16 rx_queue = skb_get_rx_queue(skb);
1850
1851 if (WARN_ON_ONCE(rx_queue == NO_QUEUE_MAPPING))
1852 return;
1853
1854 sk->sk_rx_queue_mapping = rx_queue;
1855 }
1856#endif
1857}
1858
1859static inline void sk_rx_queue_clear(struct sock *sk)
1860{
1861#ifdef CONFIG_XPS
1862 sk->sk_rx_queue_mapping = NO_QUEUE_MAPPING;
1863#endif
1864}
1865
1866#ifdef CONFIG_XPS
1867static inline int sk_rx_queue_get(const struct sock *sk)
1868{
1869 if (sk && sk->sk_rx_queue_mapping != NO_QUEUE_MAPPING)
1870 return sk->sk_rx_queue_mapping;
1871
1872 return -1;
1873}
1874#endif
1875
1876static inline void sk_set_socket(struct sock *sk, struct socket *sock)
1877{
1878 sk->sk_socket = sock;
1879}
1880
1881static inline wait_queue_head_t *sk_sleep(struct sock *sk)
1882{
1883 BUILD_BUG_ON(offsetof(struct socket_wq, wait) != 0);
1884 return &rcu_dereference_raw(sk->sk_wq)->wait;
1885}
1886/* Detach socket from process context.
1887 * Announce socket dead, detach it from wait queue and inode.
1888 * Note that parent inode held reference count on this struct sock,
1889 * we do not release it in this function, because protocol
1890 * probably wants some additional cleanups or even continuing
1891 * to work with this socket (TCP).
1892 */
1893static inline void sock_orphan(struct sock *sk)
1894{
1895 write_lock_bh(&sk->sk_callback_lock);
1896 sock_set_flag(sk, SOCK_DEAD);
1897 sk_set_socket(sk, NULL);
1898 sk->sk_wq = NULL;
1899 write_unlock_bh(&sk->sk_callback_lock);
1900}
1901
1902static inline void sock_graft(struct sock *sk, struct socket *parent)
1903{
1904 WARN_ON(parent->sk);
1905 write_lock_bh(&sk->sk_callback_lock);
1906 rcu_assign_pointer(sk->sk_wq, &parent->wq);
1907 parent->sk = sk;
1908 sk_set_socket(sk, parent);
1909 sk->sk_uid = SOCK_INODE(parent)->i_uid;
1910 security_sock_graft(sk, parent);
1911 write_unlock_bh(&sk->sk_callback_lock);
1912}
1913
1914kuid_t sock_i_uid(struct sock *sk);
1915unsigned long __sock_i_ino(struct sock *sk);
1916unsigned long sock_i_ino(struct sock *sk);
1917
1918static inline kuid_t sock_net_uid(const struct net *net, const struct sock *sk)
1919{
1920 return sk ? sk->sk_uid : make_kuid(net->user_ns, 0);
1921}
1922
1923static inline u32 net_tx_rndhash(void)
1924{
1925 u32 v = prandom_u32();
1926
1927 return v ?: 1;
1928}
1929
1930static inline void sk_set_txhash(struct sock *sk)
1931{
1932 /* This pairs with READ_ONCE() in skb_set_hash_from_sk() */
1933 WRITE_ONCE(sk->sk_txhash, net_tx_rndhash());
1934}
1935
1936static inline void sk_rethink_txhash(struct sock *sk)
1937{
1938 if (sk->sk_txhash)
1939 sk_set_txhash(sk);
1940}
1941
1942static inline struct dst_entry *
1943__sk_dst_get(struct sock *sk)
1944{
1945 return rcu_dereference_check(sk->sk_dst_cache,
1946 lockdep_sock_is_held(sk));
1947}
1948
1949static inline struct dst_entry *
1950sk_dst_get(struct sock *sk)
1951{
1952 struct dst_entry *dst;
1953
1954 rcu_read_lock();
1955 dst = rcu_dereference(sk->sk_dst_cache);
1956 if (dst && !atomic_inc_not_zero(&dst->__refcnt))
1957 dst = NULL;
1958 rcu_read_unlock();
1959 return dst;
1960}
1961
1962static inline void dst_negative_advice(struct sock *sk)
1963{
1964 struct dst_entry *dst = __sk_dst_get(sk);
1965
1966 sk_rethink_txhash(sk);
1967
1968 if (dst && dst->ops->negative_advice)
1969 dst->ops->negative_advice(sk, dst);
1970}
1971
1972static inline void
1973__sk_dst_set(struct sock *sk, struct dst_entry *dst)
1974{
1975 struct dst_entry *old_dst;
1976
1977 sk_tx_queue_clear(sk);
1978 WRITE_ONCE(sk->sk_dst_pending_confirm, 0);
1979 old_dst = rcu_dereference_protected(sk->sk_dst_cache,
1980 lockdep_sock_is_held(sk));
1981 rcu_assign_pointer(sk->sk_dst_cache, dst);
1982 dst_release(old_dst);
1983}
1984
1985static inline void
1986sk_dst_set(struct sock *sk, struct dst_entry *dst)
1987{
1988 struct dst_entry *old_dst;
1989
1990 sk_tx_queue_clear(sk);
1991 WRITE_ONCE(sk->sk_dst_pending_confirm, 0);
1992 old_dst = xchg((__force struct dst_entry **)&sk->sk_dst_cache, dst);
1993 dst_release(old_dst);
1994}
1995
1996static inline void
1997__sk_dst_reset(struct sock *sk)
1998{
1999 __sk_dst_set(sk, NULL);
2000}
2001
2002static inline void
2003sk_dst_reset(struct sock *sk)
2004{
2005 sk_dst_set(sk, NULL);
2006}
2007
2008struct dst_entry *__sk_dst_check(struct sock *sk, u32 cookie);
2009
2010struct dst_entry *sk_dst_check(struct sock *sk, u32 cookie);
2011
2012static inline void sk_dst_confirm(struct sock *sk)
2013{
2014 if (!READ_ONCE(sk->sk_dst_pending_confirm))
2015 WRITE_ONCE(sk->sk_dst_pending_confirm, 1);
2016}
2017
2018static inline void sock_confirm_neigh(struct sk_buff *skb, struct neighbour *n)
2019{
2020 if (skb_get_dst_pending_confirm(skb)) {
2021 struct sock *sk = skb->sk;
2022 unsigned long now = jiffies;
2023
2024 /* avoid dirtying neighbour */
2025 if (READ_ONCE(n->confirmed) != now)
2026 WRITE_ONCE(n->confirmed, now);
2027 if (sk && READ_ONCE(sk->sk_dst_pending_confirm))
2028 WRITE_ONCE(sk->sk_dst_pending_confirm, 0);
2029 }
2030}
2031
2032bool sk_mc_loop(struct sock *sk);
2033
2034static inline bool sk_can_gso(const struct sock *sk)
2035{
2036 return net_gso_ok(sk->sk_route_caps, sk->sk_gso_type);
2037}
2038
2039void sk_setup_caps(struct sock *sk, struct dst_entry *dst);
2040
2041static inline void sk_nocaps_add(struct sock *sk, netdev_features_t flags)
2042{
2043 sk->sk_route_nocaps |= flags;
2044 sk->sk_route_caps &= ~flags;
2045}
2046
2047static inline int skb_do_copy_data_nocache(struct sock *sk, struct sk_buff *skb,
2048 struct iov_iter *from, char *to,
2049 int copy, int offset)
2050{
2051 if (skb->ip_summed == CHECKSUM_NONE) {
2052 __wsum csum = 0;
2053 if (!csum_and_copy_from_iter_full(to, copy, &csum, from))
2054 return -EFAULT;
2055 skb->csum = csum_block_add(skb->csum, csum, offset);
2056 } else if (sk->sk_route_caps & NETIF_F_NOCACHE_COPY) {
2057 if (!copy_from_iter_full_nocache(to, copy, from))
2058 return -EFAULT;
2059 } else if (!copy_from_iter_full(to, copy, from))
2060 return -EFAULT;
2061
2062 return 0;
2063}
2064
2065static inline int skb_add_data_nocache(struct sock *sk, struct sk_buff *skb,
2066 struct iov_iter *from, int copy)
2067{
2068 int err, offset = skb->len;
2069
2070 err = skb_do_copy_data_nocache(sk, skb, from, skb_put(skb, copy),
2071 copy, offset);
2072 if (err)
2073 __skb_trim(skb, offset);
2074
2075 return err;
2076}
2077
2078static inline int skb_copy_to_page_nocache(struct sock *sk, struct iov_iter *from,
2079 struct sk_buff *skb,
2080 struct page *page,
2081 int off, int copy)
2082{
2083 int err;
2084
2085 err = skb_do_copy_data_nocache(sk, skb, from, page_address(page) + off,
2086 copy, skb->len);
2087 if (err)
2088 return err;
2089
2090 skb->len += copy;
2091 skb->data_len += copy;
2092 skb->truesize += copy;
2093 sk_wmem_queued_add(sk, copy);
2094 sk_mem_charge(sk, copy);
2095 return 0;
2096}
2097
2098/**
2099 * sk_wmem_alloc_get - returns write allocations
2100 * @sk: socket
2101 *
2102 * Returns sk_wmem_alloc minus initial offset of one
2103 */
2104static inline int sk_wmem_alloc_get(const struct sock *sk)
2105{
2106 return refcount_read(&sk->sk_wmem_alloc) - 1;
2107}
2108
2109/**
2110 * sk_rmem_alloc_get - returns read allocations
2111 * @sk: socket
2112 *
2113 * Returns sk_rmem_alloc
2114 */
2115static inline int sk_rmem_alloc_get(const struct sock *sk)
2116{
2117 return atomic_read(&sk->sk_rmem_alloc);
2118}
2119
2120/**
2121 * sk_has_allocations - check if allocations are outstanding
2122 * @sk: socket
2123 *
2124 * Returns true if socket has write or read allocations
2125 */
2126static inline bool sk_has_allocations(const struct sock *sk)
2127{
2128 return sk_wmem_alloc_get(sk) || sk_rmem_alloc_get(sk);
2129}
2130
2131/**
2132 * skwq_has_sleeper - check if there are any waiting processes
2133 * @wq: struct socket_wq
2134 *
2135 * Returns true if socket_wq has waiting processes
2136 *
2137 * The purpose of the skwq_has_sleeper and sock_poll_wait is to wrap the memory
2138 * barrier call. They were added due to the race found within the tcp code.
2139 *
2140 * Consider following tcp code paths::
2141 *
2142 * CPU1 CPU2
2143 * sys_select receive packet
2144 * ... ...
2145 * __add_wait_queue update tp->rcv_nxt
2146 * ... ...
2147 * tp->rcv_nxt check sock_def_readable
2148 * ... {
2149 * schedule rcu_read_lock();
2150 * wq = rcu_dereference(sk->sk_wq);
2151 * if (wq && waitqueue_active(&wq->wait))
2152 * wake_up_interruptible(&wq->wait)
2153 * ...
2154 * }
2155 *
2156 * The race for tcp fires when the __add_wait_queue changes done by CPU1 stay
2157 * in its cache, and so does the tp->rcv_nxt update on CPU2 side. The CPU1
2158 * could then endup calling schedule and sleep forever if there are no more
2159 * data on the socket.
2160 *
2161 */
2162static inline bool skwq_has_sleeper(struct socket_wq *wq)
2163{
2164 return wq && wq_has_sleeper(&wq->wait);
2165}
2166
2167/**
2168 * sock_poll_wait - place memory barrier behind the poll_wait call.
2169 * @filp: file
2170 * @sock: socket to wait on
2171 * @p: poll_table
2172 *
2173 * See the comments in the wq_has_sleeper function.
2174 */
2175static inline void sock_poll_wait(struct file *filp, struct socket *sock,
2176 poll_table *p)
2177{
2178 if (!poll_does_not_wait(p)) {
2179 poll_wait(filp, &sock->wq.wait, p);
2180 /* We need to be sure we are in sync with the
2181 * socket flags modification.
2182 *
2183 * This memory barrier is paired in the wq_has_sleeper.
2184 */
2185 smp_mb();
2186 }
2187}
2188
2189static inline void skb_set_hash_from_sk(struct sk_buff *skb, struct sock *sk)
2190{
2191 /* This pairs with WRITE_ONCE() in sk_set_txhash() */
2192 u32 txhash = READ_ONCE(sk->sk_txhash);
2193
2194 if (txhash) {
2195 skb->l4_hash = 1;
2196 skb->hash = txhash;
2197 }
2198}
2199
2200void skb_set_owner_w(struct sk_buff *skb, struct sock *sk);
2201
2202/*
2203 * Queue a received datagram if it will fit. Stream and sequenced
2204 * protocols can't normally use this as they need to fit buffers in
2205 * and play with them.
2206 *
2207 * Inlined as it's very short and called for pretty much every
2208 * packet ever received.
2209 */
2210static inline void skb_set_owner_r(struct sk_buff *skb, struct sock *sk)
2211{
2212 skb_orphan(skb);
2213 skb->sk = sk;
2214 skb->destructor = sock_rfree;
2215 atomic_add(skb->truesize, &sk->sk_rmem_alloc);
2216 sk_mem_charge(sk, skb->truesize);
2217}
2218
2219static inline __must_check bool skb_set_owner_sk_safe(struct sk_buff *skb, struct sock *sk)
2220{
2221 if (sk && refcount_inc_not_zero(&sk->sk_refcnt)) {
2222 skb_orphan(skb);
2223 skb->destructor = sock_efree;
2224 skb->sk = sk;
2225 return true;
2226 }
2227 return false;
2228}
2229
2230static inline struct sk_buff *skb_clone_and_charge_r(struct sk_buff *skb, struct sock *sk)
2231{
2232 skb = skb_clone(skb, sk_gfp_mask(sk, GFP_ATOMIC));
2233 if (skb) {
2234 if (sk_rmem_schedule(sk, skb, skb->truesize)) {
2235 skb_set_owner_r(skb, sk);
2236 return skb;
2237 }
2238 __kfree_skb(skb);
2239 }
2240 return NULL;
2241}
2242
2243void sk_reset_timer(struct sock *sk, struct timer_list *timer,
2244 unsigned long expires);
2245
2246void sk_stop_timer(struct sock *sk, struct timer_list *timer);
2247
2248void sk_stop_timer_sync(struct sock *sk, struct timer_list *timer);
2249
2250int __sk_queue_drop_skb(struct sock *sk, struct sk_buff_head *sk_queue,
2251 struct sk_buff *skb, unsigned int flags,
2252 void (*destructor)(struct sock *sk,
2253 struct sk_buff *skb));
2254int __sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb);
2255int sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb);
2256
2257int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb);
2258struct sk_buff *sock_dequeue_err_skb(struct sock *sk);
2259
2260/*
2261 * Recover an error report and clear atomically
2262 */
2263
2264static inline int sock_error(struct sock *sk)
2265{
2266 int err;
2267 if (likely(!sk->sk_err))
2268 return 0;
2269 err = xchg(&sk->sk_err, 0);
2270 return -err;
2271}
2272
2273static inline unsigned long sock_wspace(struct sock *sk)
2274{
2275 int amt = 0;
2276
2277 if (!(sk->sk_shutdown & SEND_SHUTDOWN)) {
2278 amt = sk->sk_sndbuf - refcount_read(&sk->sk_wmem_alloc);
2279 if (amt < 0)
2280 amt = 0;
2281 }
2282 return amt;
2283}
2284
2285/* Note:
2286 * We use sk->sk_wq_raw, from contexts knowing this
2287 * pointer is not NULL and cannot disappear/change.
2288 */
2289static inline void sk_set_bit(int nr, struct sock *sk)
2290{
2291 if ((nr == SOCKWQ_ASYNC_NOSPACE || nr == SOCKWQ_ASYNC_WAITDATA) &&
2292 !sock_flag(sk, SOCK_FASYNC))
2293 return;
2294
2295 set_bit(nr, &sk->sk_wq_raw->flags);
2296}
2297
2298static inline void sk_clear_bit(int nr, struct sock *sk)
2299{
2300 if ((nr == SOCKWQ_ASYNC_NOSPACE || nr == SOCKWQ_ASYNC_WAITDATA) &&
2301 !sock_flag(sk, SOCK_FASYNC))
2302 return;
2303
2304 clear_bit(nr, &sk->sk_wq_raw->flags);
2305}
2306
2307static inline void sk_wake_async(const struct sock *sk, int how, int band)
2308{
2309 if (sock_flag(sk, SOCK_FASYNC)) {
2310 rcu_read_lock();
2311 sock_wake_async(rcu_dereference(sk->sk_wq), how, band);
2312 rcu_read_unlock();
2313 }
2314}
2315
2316/* Since sk_{r,w}mem_alloc sums skb->truesize, even a small frame might
2317 * need sizeof(sk_buff) + MTU + padding, unless net driver perform copybreak.
2318 * Note: for send buffers, TCP works better if we can build two skbs at
2319 * minimum.
2320 */
2321#define TCP_SKB_MIN_TRUESIZE (2048 + SKB_DATA_ALIGN(sizeof(struct sk_buff)))
2322
2323#define SOCK_MIN_SNDBUF (TCP_SKB_MIN_TRUESIZE * 2)
2324#define SOCK_MIN_RCVBUF TCP_SKB_MIN_TRUESIZE
2325
2326static inline void sk_stream_moderate_sndbuf(struct sock *sk)
2327{
2328 u32 val;
2329
2330 if (sk->sk_userlocks & SOCK_SNDBUF_LOCK)
2331 return;
2332
2333 val = min(sk->sk_sndbuf, sk->sk_wmem_queued >> 1);
2334
2335 WRITE_ONCE(sk->sk_sndbuf, max_t(u32, val, SOCK_MIN_SNDBUF));
2336}
2337
2338struct sk_buff *sk_stream_alloc_skb(struct sock *sk, int size, gfp_t gfp,
2339 bool force_schedule);
2340
2341/**
2342 * sk_page_frag - return an appropriate page_frag
2343 * @sk: socket
2344 *
2345 * Use the per task page_frag instead of the per socket one for
2346 * optimization when we know that we're in the normal context and owns
2347 * everything that's associated with %current.
2348 *
2349 * gfpflags_allow_blocking() isn't enough here as direct reclaim may nest
2350 * inside other socket operations and end up recursing into sk_page_frag()
2351 * while it's already in use.
2352 */
2353static inline struct page_frag *sk_page_frag(struct sock *sk)
2354{
2355 if (gfpflags_normal_context(sk->sk_allocation))
2356 return &current->task_frag;
2357
2358 return &sk->sk_frag;
2359}
2360
2361bool sk_page_frag_refill(struct sock *sk, struct page_frag *pfrag);
2362
2363/*
2364 * Default write policy as shown to user space via poll/select/SIGIO
2365 */
2366static inline bool sock_writeable(const struct sock *sk)
2367{
2368 return refcount_read(&sk->sk_wmem_alloc) < (READ_ONCE(sk->sk_sndbuf) >> 1);
2369}
2370
2371static inline gfp_t gfp_any(void)
2372{
2373 return in_softirq() ? GFP_ATOMIC : GFP_KERNEL;
2374}
2375
2376static inline long sock_rcvtimeo(const struct sock *sk, bool noblock)
2377{
2378 return noblock ? 0 : sk->sk_rcvtimeo;
2379}
2380
2381static inline long sock_sndtimeo(const struct sock *sk, bool noblock)
2382{
2383 return noblock ? 0 : sk->sk_sndtimeo;
2384}
2385
2386static inline int sock_rcvlowat(const struct sock *sk, int waitall, int len)
2387{
2388 int v = waitall ? len : min_t(int, READ_ONCE(sk->sk_rcvlowat), len);
2389
2390 return v ?: 1;
2391}
2392
2393/* Alas, with timeout socket operations are not restartable.
2394 * Compare this to poll().
2395 */
2396static inline int sock_intr_errno(long timeo)
2397{
2398 return timeo == MAX_SCHEDULE_TIMEOUT ? -ERESTARTSYS : -EINTR;
2399}
2400
2401struct sock_skb_cb {
2402 u32 dropcount;
2403};
2404
2405/* Store sock_skb_cb at the end of skb->cb[] so protocol families
2406 * using skb->cb[] would keep using it directly and utilize its
2407 * alignement guarantee.
2408 */
2409#define SOCK_SKB_CB_OFFSET ((FIELD_SIZEOF(struct sk_buff, cb) - \
2410 sizeof(struct sock_skb_cb)))
2411
2412#define SOCK_SKB_CB(__skb) ((struct sock_skb_cb *)((__skb)->cb + \
2413 SOCK_SKB_CB_OFFSET))
2414
2415#define sock_skb_cb_check_size(size) \
2416 BUILD_BUG_ON((size) > SOCK_SKB_CB_OFFSET)
2417
2418static inline void
2419sock_skb_set_dropcount(const struct sock *sk, struct sk_buff *skb)
2420{
2421 SOCK_SKB_CB(skb)->dropcount = sock_flag(sk, SOCK_RXQ_OVFL) ?
2422 atomic_read(&sk->sk_drops) : 0;
2423}
2424
2425static inline void sk_drops_add(struct sock *sk, const struct sk_buff *skb)
2426{
2427 int segs = max_t(u16, 1, skb_shinfo(skb)->gso_segs);
2428
2429 atomic_add(segs, &sk->sk_drops);
2430}
2431
2432static inline ktime_t sock_read_timestamp(struct sock *sk)
2433{
2434#if BITS_PER_LONG==32
2435 unsigned int seq;
2436 ktime_t kt;
2437
2438 do {
2439 seq = read_seqbegin(&sk->sk_stamp_seq);
2440 kt = sk->sk_stamp;
2441 } while (read_seqretry(&sk->sk_stamp_seq, seq));
2442
2443 return kt;
2444#else
2445 return READ_ONCE(sk->sk_stamp);
2446#endif
2447}
2448
2449static inline void sock_write_timestamp(struct sock *sk, ktime_t kt)
2450{
2451#if BITS_PER_LONG==32
2452 write_seqlock(&sk->sk_stamp_seq);
2453 sk->sk_stamp = kt;
2454 write_sequnlock(&sk->sk_stamp_seq);
2455#else
2456 WRITE_ONCE(sk->sk_stamp, kt);
2457#endif
2458}
2459
2460void __sock_recv_timestamp(struct msghdr *msg, struct sock *sk,
2461 struct sk_buff *skb);
2462void __sock_recv_wifi_status(struct msghdr *msg, struct sock *sk,
2463 struct sk_buff *skb);
2464
2465static inline void
2466sock_recv_timestamp(struct msghdr *msg, struct sock *sk, struct sk_buff *skb)
2467{
2468 ktime_t kt = skb->tstamp;
2469 struct skb_shared_hwtstamps *hwtstamps = skb_hwtstamps(skb);
2470
2471 /*
2472 * generate control messages if
2473 * - receive time stamping in software requested
2474 * - software time stamp available and wanted
2475 * - hardware time stamps available and wanted
2476 */
2477 if (sock_flag(sk, SOCK_RCVTSTAMP) ||
2478 (sk->sk_tsflags & SOF_TIMESTAMPING_RX_SOFTWARE) ||
2479 (kt && sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE) ||
2480 (hwtstamps->hwtstamp &&
2481 (sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE)))
2482 __sock_recv_timestamp(msg, sk, skb);
2483 else
2484 sock_write_timestamp(sk, kt);
2485
2486 if (sock_flag(sk, SOCK_WIFI_STATUS) && skb->wifi_acked_valid)
2487 __sock_recv_wifi_status(msg, sk, skb);
2488}
2489
2490void __sock_recv_ts_and_drops(struct msghdr *msg, struct sock *sk,
2491 struct sk_buff *skb);
2492
2493#define SK_DEFAULT_STAMP (-1L * NSEC_PER_SEC)
2494static inline void sock_recv_ts_and_drops(struct msghdr *msg, struct sock *sk,
2495 struct sk_buff *skb)
2496{
2497#define FLAGS_TS_OR_DROPS ((1UL << SOCK_RXQ_OVFL) | \
2498 (1UL << SOCK_RCVTSTAMP))
2499#define TSFLAGS_ANY (SOF_TIMESTAMPING_SOFTWARE | \
2500 SOF_TIMESTAMPING_RAW_HARDWARE)
2501
2502 if (sk->sk_flags & FLAGS_TS_OR_DROPS || sk->sk_tsflags & TSFLAGS_ANY)
2503 __sock_recv_ts_and_drops(msg, sk, skb);
2504 else if (unlikely(sock_flag(sk, SOCK_TIMESTAMP)))
2505 sock_write_timestamp(sk, skb->tstamp);
2506 else if (unlikely(sock_read_timestamp(sk) == SK_DEFAULT_STAMP))
2507 sock_write_timestamp(sk, 0);
2508}
2509
2510void __sock_tx_timestamp(__u16 tsflags, __u8 *tx_flags);
2511
2512/**
2513 * _sock_tx_timestamp - checks whether the outgoing packet is to be time stamped
2514 * @sk: socket sending this packet
2515 * @tsflags: timestamping flags to use
2516 * @tx_flags: completed with instructions for time stamping
2517 * @tskey: filled in with next sk_tskey (not for TCP, which uses seqno)
2518 *
2519 * Note: callers should take care of initial ``*tx_flags`` value (usually 0)
2520 */
2521static inline void _sock_tx_timestamp(struct sock *sk, __u16 tsflags,
2522 __u8 *tx_flags, __u32 *tskey)
2523{
2524 if (unlikely(tsflags)) {
2525 __sock_tx_timestamp(tsflags, tx_flags);
2526 if (tsflags & SOF_TIMESTAMPING_OPT_ID && tskey &&
2527 tsflags & SOF_TIMESTAMPING_TX_RECORD_MASK)
2528 *tskey = sk->sk_tskey++;
2529 }
2530 if (unlikely(sock_flag(sk, SOCK_WIFI_STATUS)))
2531 *tx_flags |= SKBTX_WIFI_STATUS;
2532}
2533
2534static inline void sock_tx_timestamp(struct sock *sk, __u16 tsflags,
2535 __u8 *tx_flags)
2536{
2537 _sock_tx_timestamp(sk, tsflags, tx_flags, NULL);
2538}
2539
2540static inline void skb_setup_tx_timestamp(struct sk_buff *skb, __u16 tsflags)
2541{
2542 _sock_tx_timestamp(skb->sk, tsflags, &skb_shinfo(skb)->tx_flags,
2543 &skb_shinfo(skb)->tskey);
2544}
2545
2546/**
2547 * sk_eat_skb - Release a skb if it is no longer needed
2548 * @sk: socket to eat this skb from
2549 * @skb: socket buffer to eat
2550 *
2551 * This routine must be called with interrupts disabled or with the socket
2552 * locked so that the sk_buff queue operation is ok.
2553*/
2554DECLARE_STATIC_KEY_FALSE(tcp_rx_skb_cache_key);
2555static inline void sk_eat_skb(struct sock *sk, struct sk_buff *skb)
2556{
2557 __skb_unlink(skb, &sk->sk_receive_queue);
2558 if (static_branch_unlikely(&tcp_rx_skb_cache_key) &&
2559 !sk->sk_rx_skb_cache) {
2560 sk->sk_rx_skb_cache = skb;
2561 skb_orphan(skb);
2562 return;
2563 }
2564 __kfree_skb(skb);
2565}
2566
2567static inline
2568struct net *sock_net(const struct sock *sk)
2569{
2570 return read_pnet(&sk->sk_net);
2571}
2572
2573static inline
2574void sock_net_set(struct sock *sk, struct net *net)
2575{
2576 write_pnet(&sk->sk_net, net);
2577}
2578
2579static inline struct sock *skb_steal_sock(struct sk_buff *skb)
2580{
2581 if (skb->sk) {
2582 struct sock *sk = skb->sk;
2583
2584 skb->destructor = NULL;
2585 skb->sk = NULL;
2586 return sk;
2587 }
2588 return NULL;
2589}
2590
2591/* This helper checks if a socket is a full socket,
2592 * ie _not_ a timewait or request socket.
2593 */
2594static inline bool sk_fullsock(const struct sock *sk)
2595{
2596 return (1 << sk->sk_state) & ~(TCPF_TIME_WAIT | TCPF_NEW_SYN_RECV);
2597}
2598
2599/* Checks if this SKB belongs to an HW offloaded socket
2600 * and whether any SW fallbacks are required based on dev.
2601 * Check decrypted mark in case skb_orphan() cleared socket.
2602 */
2603static inline struct sk_buff *sk_validate_xmit_skb(struct sk_buff *skb,
2604 struct net_device *dev)
2605{
2606#ifdef CONFIG_SOCK_VALIDATE_XMIT
2607 struct sock *sk = skb->sk;
2608
2609 if (sk && sk_fullsock(sk) && sk->sk_validate_xmit_skb) {
2610 skb = sk->sk_validate_xmit_skb(sk, dev, skb);
2611#ifdef CONFIG_TLS_DEVICE
2612 } else if (unlikely(skb->decrypted)) {
2613 pr_warn_ratelimited("unencrypted skb with no associated socket - dropping\n");
2614 kfree_skb(skb);
2615 skb = NULL;
2616#endif
2617 }
2618#endif
2619
2620 return skb;
2621}
2622
2623/* This helper checks if a socket is a LISTEN or NEW_SYN_RECV
2624 * SYNACK messages can be attached to either ones (depending on SYNCOOKIE)
2625 */
2626static inline bool sk_listener(const struct sock *sk)
2627{
2628 return (1 << sk->sk_state) & (TCPF_LISTEN | TCPF_NEW_SYN_RECV);
2629}
2630
2631void sock_enable_timestamp(struct sock *sk, int flag);
2632int sock_recv_errqueue(struct sock *sk, struct msghdr *msg, int len, int level,
2633 int type);
2634
2635bool sk_ns_capable(const struct sock *sk,
2636 struct user_namespace *user_ns, int cap);
2637bool sk_capable(const struct sock *sk, int cap);
2638bool sk_net_capable(const struct sock *sk, int cap);
2639
2640void sk_get_meminfo(const struct sock *sk, u32 *meminfo);
2641
2642/* Take into consideration the size of the struct sk_buff overhead in the
2643 * determination of these values, since that is non-constant across
2644 * platforms. This makes socket queueing behavior and performance
2645 * not depend upon such differences.
2646 */
2647#define _SK_MEM_PACKETS 256
2648#define _SK_MEM_OVERHEAD SKB_TRUESIZE(256)
2649#define SK_WMEM_MAX (_SK_MEM_OVERHEAD * _SK_MEM_PACKETS)
2650#define SK_RMEM_MAX (_SK_MEM_OVERHEAD * _SK_MEM_PACKETS)
2651
2652extern __u32 sysctl_wmem_max;
2653extern __u32 sysctl_rmem_max;
2654
2655extern int sysctl_tstamp_allow_data;
2656extern int sysctl_optmem_max;
2657
2658extern __u32 sysctl_wmem_default;
2659extern __u32 sysctl_rmem_default;
2660
2661
2662/* On 32bit arches, an skb frag is limited to 2^15 */
2663#define SKB_FRAG_PAGE_ORDER get_order(32768)
2664DECLARE_STATIC_KEY_FALSE(net_high_order_alloc_disable_key);
2665
2666static inline int sk_get_wmem0(const struct sock *sk, const struct proto *proto)
2667{
2668 /* Does this proto have per netns sysctl_wmem ? */
2669 if (proto->sysctl_wmem_offset)
2670 return *(int *)((void *)sock_net(sk) + proto->sysctl_wmem_offset);
2671
2672 return *proto->sysctl_wmem;
2673}
2674
2675static inline int sk_get_rmem0(const struct sock *sk, const struct proto *proto)
2676{
2677 /* Does this proto have per netns sysctl_rmem ? */
2678 if (proto->sysctl_rmem_offset)
2679 return *(int *)((void *)sock_net(sk) + proto->sysctl_rmem_offset);
2680
2681 return *proto->sysctl_rmem;
2682}
2683
2684/* Default TCP Small queue budget is ~1 ms of data (1sec >> 10)
2685 * Some wifi drivers need to tweak it to get more chunks.
2686 * They can use this helper from their ndo_start_xmit()
2687 */
2688static inline void sk_pacing_shift_update(struct sock *sk, int val)
2689{
2690 if (!sk || !sk_fullsock(sk) || READ_ONCE(sk->sk_pacing_shift) == val)
2691 return;
2692 WRITE_ONCE(sk->sk_pacing_shift, val);
2693}
2694
2695/* if a socket is bound to a device, check that the given device
2696 * index is either the same or that the socket is bound to an L3
2697 * master device and the given device index is also enslaved to
2698 * that L3 master
2699 */
2700static inline bool sk_dev_equal_l3scope(struct sock *sk, int dif)
2701{
2702 int mdif;
2703
2704 if (!sk->sk_bound_dev_if || sk->sk_bound_dev_if == dif)
2705 return true;
2706
2707 mdif = l3mdev_master_ifindex_by_index(sock_net(sk), dif);
2708 if (mdif && mdif == sk->sk_bound_dev_if)
2709 return true;
2710
2711 return false;
2712}
2713
2714#endif /* _SOCK_H */