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