]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blame - net/core/sock.c
net: add a new bind_add method
[mirror_ubuntu-jammy-kernel.git] / net / core / sock.c
CommitLineData
2874c5fd 1// SPDX-License-Identifier: GPL-2.0-or-later
1da177e4
LT
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 * Generic socket support routines. Memory allocators, socket lock/release
8 * handler for protocols to use and generic option handler.
9 *
02c30a84 10 * Authors: Ross Biro
1da177e4
LT
11 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
12 * Florian La Roche, <flla@stud.uni-sb.de>
13 * Alan Cox, <A.Cox@swansea.ac.uk>
14 *
15 * Fixes:
16 * Alan Cox : Numerous verify_area() problems
17 * Alan Cox : Connecting on a connecting socket
18 * now returns an error for tcp.
19 * Alan Cox : sock->protocol is set correctly.
20 * and is not sometimes left as 0.
21 * Alan Cox : connect handles icmp errors on a
22 * connect properly. Unfortunately there
23 * is a restart syscall nasty there. I
24 * can't match BSD without hacking the C
25 * library. Ideas urgently sought!
26 * Alan Cox : Disallow bind() to addresses that are
27 * not ours - especially broadcast ones!!
28 * Alan Cox : Socket 1024 _IS_ ok for users. (fencepost)
29 * Alan Cox : sock_wfree/sock_rfree don't destroy sockets,
30 * instead they leave that for the DESTROY timer.
31 * Alan Cox : Clean up error flag in accept
32 * Alan Cox : TCP ack handling is buggy, the DESTROY timer
33 * was buggy. Put a remove_sock() in the handler
34 * for memory when we hit 0. Also altered the timer
4ec93edb 35 * code. The ACK stuff can wait and needs major
1da177e4
LT
36 * TCP layer surgery.
37 * Alan Cox : Fixed TCP ack bug, removed remove sock
38 * and fixed timer/inet_bh race.
39 * Alan Cox : Added zapped flag for TCP
40 * Alan Cox : Move kfree_skb into skbuff.c and tidied up surplus code
41 * Alan Cox : for new sk_buff allocations wmalloc/rmalloc now call alloc_skb
42 * Alan Cox : kfree_s calls now are kfree_skbmem so we can track skb resources
43 * Alan Cox : Supports socket option broadcast now as does udp. Packet and raw need fixing.
44 * Alan Cox : Added RCVBUF,SNDBUF size setting. It suddenly occurred to me how easy it was so...
45 * Rick Sladkey : Relaxed UDP rules for matching packets.
46 * C.E.Hawkins : IFF_PROMISC/SIOCGHWADDR support
47 * Pauline Middelink : identd support
48 * Alan Cox : Fixed connect() taking signals I think.
49 * Alan Cox : SO_LINGER supported
50 * Alan Cox : Error reporting fixes
51 * Anonymous : inet_create tidied up (sk->reuse setting)
52 * Alan Cox : inet sockets don't set sk->type!
53 * Alan Cox : Split socket option code
54 * Alan Cox : Callbacks
55 * Alan Cox : Nagle flag for Charles & Johannes stuff
56 * Alex : Removed restriction on inet fioctl
57 * Alan Cox : Splitting INET from NET core
58 * Alan Cox : Fixed bogus SO_TYPE handling in getsockopt()
59 * Adam Caldwell : Missing return in SO_DONTROUTE/SO_DEBUG code
60 * Alan Cox : Split IP from generic code
61 * Alan Cox : New kfree_skbmem()
62 * Alan Cox : Make SO_DEBUG superuser only.
63 * Alan Cox : Allow anyone to clear SO_DEBUG
64 * (compatibility fix)
65 * Alan Cox : Added optimistic memory grabbing for AF_UNIX throughput.
66 * Alan Cox : Allocator for a socket is settable.
67 * Alan Cox : SO_ERROR includes soft errors.
68 * Alan Cox : Allow NULL arguments on some SO_ opts
69 * Alan Cox : Generic socket allocation to make hooks
70 * easier (suggested by Craig Metz).
71 * Michael Pall : SO_ERROR returns positive errno again
72 * Steve Whitehouse: Added default destructor to free
73 * protocol private data.
74 * Steve Whitehouse: Added various other default routines
75 * common to several socket families.
76 * Chris Evans : Call suser() check last on F_SETOWN
77 * Jay Schulist : Added SO_ATTACH_FILTER and SO_DETACH_FILTER.
78 * Andi Kleen : Add sock_kmalloc()/sock_kfree_s()
79 * Andi Kleen : Fix write_space callback
80 * Chris Evans : Security fixes - signedness again
81 * Arnaldo C. Melo : cleanups, use skb_queue_purge
82 *
83 * To Fix:
1da177e4
LT
84 */
85
e005d193
JP
86#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
87
80b14dee 88#include <asm/unaligned.h>
4fc268d2 89#include <linux/capability.h>
1da177e4 90#include <linux/errno.h>
cb820f8e 91#include <linux/errqueue.h>
1da177e4
LT
92#include <linux/types.h>
93#include <linux/socket.h>
94#include <linux/in.h>
95#include <linux/kernel.h>
1da177e4
LT
96#include <linux/module.h>
97#include <linux/proc_fs.h>
98#include <linux/seq_file.h>
99#include <linux/sched.h>
f1083048 100#include <linux/sched/mm.h>
1da177e4
LT
101#include <linux/timer.h>
102#include <linux/string.h>
103#include <linux/sockios.h>
104#include <linux/net.h>
105#include <linux/mm.h>
106#include <linux/slab.h>
107#include <linux/interrupt.h>
108#include <linux/poll.h>
109#include <linux/tcp.h>
110#include <linux/init.h>
a1f8e7f7 111#include <linux/highmem.h>
3f551f94 112#include <linux/user_namespace.h>
c5905afb 113#include <linux/static_key.h>
3969eb38 114#include <linux/memcontrol.h>
8c1ae10d 115#include <linux/prefetch.h>
1da177e4 116
7c0f6ba6 117#include <linux/uaccess.h>
1da177e4
LT
118
119#include <linux/netdevice.h>
120#include <net/protocol.h>
121#include <linux/skbuff.h>
457c4cbc 122#include <net/net_namespace.h>
2e6599cb 123#include <net/request_sock.h>
1da177e4 124#include <net/sock.h>
20d49473 125#include <linux/net_tstamp.h>
1da177e4
LT
126#include <net/xfrm.h>
127#include <linux/ipsec.h>
f8451725 128#include <net/cls_cgroup.h>
5bc1421e 129#include <net/netprio_cgroup.h>
eb4cb008 130#include <linux/sock_diag.h>
1da177e4
LT
131
132#include <linux/filter.h>
538950a1 133#include <net/sock_reuseport.h>
6ac99e8f 134#include <net/bpf_sk_storage.h>
1da177e4 135
3847ce32
SM
136#include <trace/events/sock.h>
137
1da177e4 138#include <net/tcp.h>
076bb0c8 139#include <net/busy_poll.h>
06021292 140
36b77a52 141static DEFINE_MUTEX(proto_list_mutex);
d1a4c0b3
GC
142static LIST_HEAD(proto_list);
143
648845ab
TZ
144static void sock_inuse_add(struct net *net, int val);
145
a3b299da
EB
146/**
147 * sk_ns_capable - General socket capability test
148 * @sk: Socket to use a capability on or through
149 * @user_ns: The user namespace of the capability to use
150 * @cap: The capability to use
151 *
152 * Test to see if the opener of the socket had when the socket was
153 * created and the current process has the capability @cap in the user
154 * namespace @user_ns.
155 */
156bool sk_ns_capable(const struct sock *sk,
157 struct user_namespace *user_ns, int cap)
158{
159 return file_ns_capable(sk->sk_socket->file, user_ns, cap) &&
160 ns_capable(user_ns, cap);
161}
162EXPORT_SYMBOL(sk_ns_capable);
163
164/**
165 * sk_capable - Socket global capability test
166 * @sk: Socket to use a capability on or through
e793c0f7 167 * @cap: The global capability to use
a3b299da
EB
168 *
169 * Test to see if the opener of the socket had when the socket was
170 * created and the current process has the capability @cap in all user
171 * namespaces.
172 */
173bool sk_capable(const struct sock *sk, int cap)
174{
175 return sk_ns_capable(sk, &init_user_ns, cap);
176}
177EXPORT_SYMBOL(sk_capable);
178
179/**
180 * sk_net_capable - Network namespace socket capability test
181 * @sk: Socket to use a capability on or through
182 * @cap: The capability to use
183 *
e793c0f7 184 * Test to see if the opener of the socket had when the socket was created
a3b299da
EB
185 * and the current process has the capability @cap over the network namespace
186 * the socket is a member of.
187 */
188bool sk_net_capable(const struct sock *sk, int cap)
189{
190 return sk_ns_capable(sk, sock_net(sk)->user_ns, cap);
191}
192EXPORT_SYMBOL(sk_net_capable);
193
da21f24d
IM
194/*
195 * Each address family might have different locking rules, so we have
cdfbabfb
DH
196 * one slock key per address family and separate keys for internal and
197 * userspace sockets.
da21f24d 198 */
a5b5bb9a 199static struct lock_class_key af_family_keys[AF_MAX];
cdfbabfb 200static struct lock_class_key af_family_kern_keys[AF_MAX];
a5b5bb9a 201static struct lock_class_key af_family_slock_keys[AF_MAX];
cdfbabfb 202static struct lock_class_key af_family_kern_slock_keys[AF_MAX];
a5b5bb9a 203
a5b5bb9a
IM
204/*
205 * Make lock validator output more readable. (we pre-construct these
206 * strings build-time, so that runtime initialization of socket
207 * locks is fast):
208 */
cdfbabfb
DH
209
210#define _sock_locks(x) \
211 x "AF_UNSPEC", x "AF_UNIX" , x "AF_INET" , \
212 x "AF_AX25" , x "AF_IPX" , x "AF_APPLETALK", \
213 x "AF_NETROM", x "AF_BRIDGE" , x "AF_ATMPVC" , \
214 x "AF_X25" , x "AF_INET6" , x "AF_ROSE" , \
215 x "AF_DECnet", x "AF_NETBEUI" , x "AF_SECURITY" , \
216 x "AF_KEY" , x "AF_NETLINK" , x "AF_PACKET" , \
217 x "AF_ASH" , x "AF_ECONET" , x "AF_ATMSVC" , \
218 x "AF_RDS" , x "AF_SNA" , x "AF_IRDA" , \
219 x "AF_PPPOX" , x "AF_WANPIPE" , x "AF_LLC" , \
220 x "27" , x "28" , x "AF_CAN" , \
221 x "AF_TIPC" , x "AF_BLUETOOTH", x "IUCV" , \
222 x "AF_RXRPC" , x "AF_ISDN" , x "AF_PHONET" , \
223 x "AF_IEEE802154", x "AF_CAIF" , x "AF_ALG" , \
224 x "AF_NFC" , x "AF_VSOCK" , x "AF_KCM" , \
68e8b849
BT
225 x "AF_QIPCRTR", x "AF_SMC" , x "AF_XDP" , \
226 x "AF_MAX"
cdfbabfb 227
36cbd3dc 228static const char *const af_family_key_strings[AF_MAX+1] = {
cdfbabfb 229 _sock_locks("sk_lock-")
a5b5bb9a 230};
36cbd3dc 231static const char *const af_family_slock_key_strings[AF_MAX+1] = {
cdfbabfb 232 _sock_locks("slock-")
a5b5bb9a 233};
36cbd3dc 234static const char *const af_family_clock_key_strings[AF_MAX+1] = {
cdfbabfb
DH
235 _sock_locks("clock-")
236};
237
238static const char *const af_family_kern_key_strings[AF_MAX+1] = {
239 _sock_locks("k-sk_lock-")
240};
241static const char *const af_family_kern_slock_key_strings[AF_MAX+1] = {
242 _sock_locks("k-slock-")
243};
244static const char *const af_family_kern_clock_key_strings[AF_MAX+1] = {
245 _sock_locks("k-clock-")
443aef0e 246};
581319c5 247static const char *const af_family_rlock_key_strings[AF_MAX+1] = {
6b431d50 248 _sock_locks("rlock-")
581319c5
PA
249};
250static const char *const af_family_wlock_key_strings[AF_MAX+1] = {
6b431d50 251 _sock_locks("wlock-")
581319c5
PA
252};
253static const char *const af_family_elock_key_strings[AF_MAX+1] = {
6b431d50 254 _sock_locks("elock-")
581319c5 255};
da21f24d
IM
256
257/*
581319c5 258 * sk_callback_lock and sk queues locking rules are per-address-family,
da21f24d
IM
259 * so split the lock classes by using a per-AF key:
260 */
261static struct lock_class_key af_callback_keys[AF_MAX];
581319c5
PA
262static struct lock_class_key af_rlock_keys[AF_MAX];
263static struct lock_class_key af_wlock_keys[AF_MAX];
264static struct lock_class_key af_elock_keys[AF_MAX];
cdfbabfb 265static struct lock_class_key af_kern_callback_keys[AF_MAX];
da21f24d 266
1da177e4 267/* Run time adjustable parameters. */
ab32ea5d 268__u32 sysctl_wmem_max __read_mostly = SK_WMEM_MAX;
6d8ebc8a 269EXPORT_SYMBOL(sysctl_wmem_max);
ab32ea5d 270__u32 sysctl_rmem_max __read_mostly = SK_RMEM_MAX;
6d8ebc8a 271EXPORT_SYMBOL(sysctl_rmem_max);
ab32ea5d
BH
272__u32 sysctl_wmem_default __read_mostly = SK_WMEM_MAX;
273__u32 sysctl_rmem_default __read_mostly = SK_RMEM_MAX;
1da177e4 274
25985edc 275/* Maximal space eaten by iovec or ancillary data plus some space */
ab32ea5d 276int sysctl_optmem_max __read_mostly = sizeof(unsigned long)*(2*UIO_MAXIOV+512);
2a91525c 277EXPORT_SYMBOL(sysctl_optmem_max);
1da177e4 278
b245be1f
WB
279int sysctl_tstamp_allow_data __read_mostly = 1;
280
a7950ae8
DB
281DEFINE_STATIC_KEY_FALSE(memalloc_socks_key);
282EXPORT_SYMBOL_GPL(memalloc_socks_key);
c93bdd0e 283
7cb02404
MG
284/**
285 * sk_set_memalloc - sets %SOCK_MEMALLOC
286 * @sk: socket to set it on
287 *
288 * Set %SOCK_MEMALLOC on a socket for access to emergency reserves.
289 * It's the responsibility of the admin to adjust min_free_kbytes
290 * to meet the requirements
291 */
292void sk_set_memalloc(struct sock *sk)
293{
294 sock_set_flag(sk, SOCK_MEMALLOC);
295 sk->sk_allocation |= __GFP_MEMALLOC;
a7950ae8 296 static_branch_inc(&memalloc_socks_key);
7cb02404
MG
297}
298EXPORT_SYMBOL_GPL(sk_set_memalloc);
299
300void sk_clear_memalloc(struct sock *sk)
301{
302 sock_reset_flag(sk, SOCK_MEMALLOC);
303 sk->sk_allocation &= ~__GFP_MEMALLOC;
a7950ae8 304 static_branch_dec(&memalloc_socks_key);
c76562b6
MG
305
306 /*
307 * SOCK_MEMALLOC is allowed to ignore rmem limits to ensure forward
5d753610
MG
308 * progress of swapping. SOCK_MEMALLOC may be cleared while
309 * it has rmem allocations due to the last swapfile being deactivated
310 * but there is a risk that the socket is unusable due to exceeding
311 * the rmem limits. Reclaim the reserves and obey rmem limits again.
c76562b6 312 */
5d753610 313 sk_mem_reclaim(sk);
7cb02404
MG
314}
315EXPORT_SYMBOL_GPL(sk_clear_memalloc);
316
b4b9e355
MG
317int __sk_backlog_rcv(struct sock *sk, struct sk_buff *skb)
318{
319 int ret;
f1083048 320 unsigned int noreclaim_flag;
b4b9e355
MG
321
322 /* these should have been dropped before queueing */
323 BUG_ON(!sock_flag(sk, SOCK_MEMALLOC));
324
f1083048 325 noreclaim_flag = memalloc_noreclaim_save();
b4b9e355 326 ret = sk->sk_backlog_rcv(sk, skb);
f1083048 327 memalloc_noreclaim_restore(noreclaim_flag);
b4b9e355
MG
328
329 return ret;
330}
331EXPORT_SYMBOL(__sk_backlog_rcv);
332
a9beb86a 333static int sock_get_timeout(long timeo, void *optval, bool old_timeval)
fe0c72f3 334{
a9beb86a 335 struct __kernel_sock_timeval tv;
fe0c72f3
AB
336
337 if (timeo == MAX_SCHEDULE_TIMEOUT) {
338 tv.tv_sec = 0;
339 tv.tv_usec = 0;
340 } else {
341 tv.tv_sec = timeo / HZ;
342 tv.tv_usec = ((timeo % HZ) * USEC_PER_SEC) / HZ;
343 }
344
e6986423 345 if (old_timeval && in_compat_syscall() && !COMPAT_USE_64BIT_TIME) {
fe0c72f3
AB
346 struct old_timeval32 tv32 = { tv.tv_sec, tv.tv_usec };
347 *(struct old_timeval32 *)optval = tv32;
348 return sizeof(tv32);
349 }
350
a9beb86a
DD
351 if (old_timeval) {
352 struct __kernel_old_timeval old_tv;
353 old_tv.tv_sec = tv.tv_sec;
354 old_tv.tv_usec = tv.tv_usec;
355 *(struct __kernel_old_timeval *)optval = old_tv;
28e72b26 356 return sizeof(old_tv);
a9beb86a
DD
357 }
358
28e72b26
VC
359 *(struct __kernel_sock_timeval *)optval = tv;
360 return sizeof(tv);
fe0c72f3
AB
361}
362
a9beb86a 363static int sock_set_timeout(long *timeo_p, char __user *optval, int optlen, bool old_timeval)
1da177e4 364{
a9beb86a 365 struct __kernel_sock_timeval tv;
1da177e4 366
e6986423 367 if (old_timeval && in_compat_syscall() && !COMPAT_USE_64BIT_TIME) {
fe0c72f3
AB
368 struct old_timeval32 tv32;
369
370 if (optlen < sizeof(tv32))
371 return -EINVAL;
372
373 if (copy_from_user(&tv32, optval, sizeof(tv32)))
374 return -EFAULT;
375 tv.tv_sec = tv32.tv_sec;
376 tv.tv_usec = tv32.tv_usec;
a9beb86a
DD
377 } else if (old_timeval) {
378 struct __kernel_old_timeval old_tv;
379
380 if (optlen < sizeof(old_tv))
381 return -EINVAL;
382 if (copy_from_user(&old_tv, optval, sizeof(old_tv)))
383 return -EFAULT;
384 tv.tv_sec = old_tv.tv_sec;
385 tv.tv_usec = old_tv.tv_usec;
fe0c72f3
AB
386 } else {
387 if (optlen < sizeof(tv))
388 return -EINVAL;
389 if (copy_from_user(&tv, optval, sizeof(tv)))
390 return -EFAULT;
391 }
ba78073e
VA
392 if (tv.tv_usec < 0 || tv.tv_usec >= USEC_PER_SEC)
393 return -EDOM;
1da177e4 394
ba78073e 395 if (tv.tv_sec < 0) {
6f11df83
AM
396 static int warned __read_mostly;
397
ba78073e 398 *timeo_p = 0;
50aab54f 399 if (warned < 10 && net_ratelimit()) {
ba78073e 400 warned++;
e005d193
JP
401 pr_info("%s: `%s' (pid %d) tries to set negative timeout\n",
402 __func__, current->comm, task_pid_nr(current));
50aab54f 403 }
ba78073e
VA
404 return 0;
405 }
1da177e4
LT
406 *timeo_p = MAX_SCHEDULE_TIMEOUT;
407 if (tv.tv_sec == 0 && tv.tv_usec == 0)
408 return 0;
a9beb86a
DD
409 if (tv.tv_sec < (MAX_SCHEDULE_TIMEOUT / HZ - 1))
410 *timeo_p = tv.tv_sec * HZ + DIV_ROUND_UP((unsigned long)tv.tv_usec, USEC_PER_SEC / HZ);
1da177e4
LT
411 return 0;
412}
413
414static void sock_warn_obsolete_bsdism(const char *name)
415{
416 static int warned;
417 static char warncomm[TASK_COMM_LEN];
4ec93edb
YH
418 if (strcmp(warncomm, current->comm) && warned < 5) {
419 strcpy(warncomm, current->comm);
e005d193
JP
420 pr_warn("process `%s' is using obsolete %s SO_BSDCOMPAT\n",
421 warncomm, name);
1da177e4
LT
422 warned++;
423 }
424}
425
080a270f
HFS
426static bool sock_needs_netstamp(const struct sock *sk)
427{
428 switch (sk->sk_family) {
429 case AF_UNSPEC:
430 case AF_UNIX:
431 return false;
432 default:
433 return true;
434 }
435}
436
08e29af3 437static void sock_disable_timestamp(struct sock *sk, unsigned long flags)
4ec93edb 438{
08e29af3
ED
439 if (sk->sk_flags & flags) {
440 sk->sk_flags &= ~flags;
080a270f
HFS
441 if (sock_needs_netstamp(sk) &&
442 !(sk->sk_flags & SK_FLAGS_TIMESTAMP))
20d49473 443 net_disable_timestamp();
1da177e4
LT
444 }
445}
446
447
e6afc8ac 448int __sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
f0088a50 449{
3b885787
NH
450 unsigned long flags;
451 struct sk_buff_head *list = &sk->sk_receive_queue;
f0088a50 452
0fd7bac6 453 if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) {
766e9037 454 atomic_inc(&sk->sk_drops);
3847ce32 455 trace_sock_rcvqueue_full(sk, skb);
766e9037 456 return -ENOMEM;
f0088a50
DV
457 }
458
c76562b6 459 if (!sk_rmem_schedule(sk, skb, skb->truesize)) {
766e9037
ED
460 atomic_inc(&sk->sk_drops);
461 return -ENOBUFS;
3ab224be
HA
462 }
463
f0088a50
DV
464 skb->dev = NULL;
465 skb_set_owner_r(skb, sk);
49ad9599 466
7fee226a
ED
467 /* we escape from rcu protected region, make sure we dont leak
468 * a norefcounted dst
469 */
470 skb_dst_force(skb);
471
3b885787 472 spin_lock_irqsave(&list->lock, flags);
3bc3b96f 473 sock_skb_set_dropcount(sk, skb);
3b885787
NH
474 __skb_queue_tail(list, skb);
475 spin_unlock_irqrestore(&list->lock, flags);
f0088a50
DV
476
477 if (!sock_flag(sk, SOCK_DEAD))
676d2369 478 sk->sk_data_ready(sk);
766e9037 479 return 0;
f0088a50 480}
e6afc8ac 481EXPORT_SYMBOL(__sock_queue_rcv_skb);
482
483int sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
484{
485 int err;
486
487 err = sk_filter(sk, skb);
488 if (err)
489 return err;
490
491 return __sock_queue_rcv_skb(sk, skb);
492}
f0088a50
DV
493EXPORT_SYMBOL(sock_queue_rcv_skb);
494
4f0c40d9 495int __sk_receive_skb(struct sock *sk, struct sk_buff *skb,
c3f24cfb 496 const int nested, unsigned int trim_cap, bool refcounted)
f0088a50
DV
497{
498 int rc = NET_RX_SUCCESS;
499
4f0c40d9 500 if (sk_filter_trim_cap(sk, skb, trim_cap))
f0088a50
DV
501 goto discard_and_relse;
502
503 skb->dev = NULL;
504
274f482d 505 if (sk_rcvqueues_full(sk, sk->sk_rcvbuf)) {
c377411f
ED
506 atomic_inc(&sk->sk_drops);
507 goto discard_and_relse;
508 }
58a5a7b9
ACM
509 if (nested)
510 bh_lock_sock_nested(sk);
511 else
512 bh_lock_sock(sk);
a5b5bb9a
IM
513 if (!sock_owned_by_user(sk)) {
514 /*
515 * trylock + unlock semantics:
516 */
517 mutex_acquire(&sk->sk_lock.dep_map, 0, 1, _RET_IP_);
518
c57943a1 519 rc = sk_backlog_rcv(sk, skb);
a5b5bb9a 520
5facae4f 521 mutex_release(&sk->sk_lock.dep_map, _RET_IP_);
8265792b 522 } else if (sk_add_backlog(sk, skb, READ_ONCE(sk->sk_rcvbuf))) {
8eae939f
ZY
523 bh_unlock_sock(sk);
524 atomic_inc(&sk->sk_drops);
525 goto discard_and_relse;
526 }
527
f0088a50
DV
528 bh_unlock_sock(sk);
529out:
c3f24cfb
ED
530 if (refcounted)
531 sock_put(sk);
f0088a50
DV
532 return rc;
533discard_and_relse:
534 kfree_skb(skb);
535 goto out;
536}
4f0c40d9 537EXPORT_SYMBOL(__sk_receive_skb);
f0088a50
DV
538
539struct dst_entry *__sk_dst_check(struct sock *sk, u32 cookie)
540{
b6c6712a 541 struct dst_entry *dst = __sk_dst_get(sk);
f0088a50
DV
542
543 if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) {
e022f0b4 544 sk_tx_queue_clear(sk);
9b8805a3 545 sk->sk_dst_pending_confirm = 0;
a9b3cd7f 546 RCU_INIT_POINTER(sk->sk_dst_cache, NULL);
f0088a50
DV
547 dst_release(dst);
548 return NULL;
549 }
550
551 return dst;
552}
553EXPORT_SYMBOL(__sk_dst_check);
554
555struct dst_entry *sk_dst_check(struct sock *sk, u32 cookie)
556{
557 struct dst_entry *dst = sk_dst_get(sk);
558
559 if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) {
560 sk_dst_reset(sk);
561 dst_release(dst);
562 return NULL;
563 }
564
565 return dst;
566}
567EXPORT_SYMBOL(sk_dst_check);
568
7594888c 569static int sock_bindtoindex_locked(struct sock *sk, int ifindex)
4878809f
DM
570{
571 int ret = -ENOPROTOOPT;
572#ifdef CONFIG_NETDEVICES
3b1e0a65 573 struct net *net = sock_net(sk);
4878809f
DM
574
575 /* Sorry... */
576 ret = -EPERM;
c427bfec 577 if (sk->sk_bound_dev_if && !ns_capable(net->user_ns, CAP_NET_RAW))
4878809f
DM
578 goto out;
579
f5dd3d0c
DH
580 ret = -EINVAL;
581 if (ifindex < 0)
582 goto out;
583
584 sk->sk_bound_dev_if = ifindex;
585 if (sk->sk_prot->rehash)
586 sk->sk_prot->rehash(sk);
587 sk_dst_reset(sk);
588
589 ret = 0;
590
591out:
592#endif
593
594 return ret;
595}
596
7594888c
CH
597int sock_bindtoindex(struct sock *sk, int ifindex)
598{
599 int ret;
600
601 lock_sock(sk);
602 ret = sock_bindtoindex_locked(sk, ifindex);
603 release_sock(sk);
604
605 return ret;
606}
607EXPORT_SYMBOL(sock_bindtoindex);
608
f5dd3d0c
DH
609static int sock_setbindtodevice(struct sock *sk, char __user *optval,
610 int optlen)
611{
612 int ret = -ENOPROTOOPT;
613#ifdef CONFIG_NETDEVICES
614 struct net *net = sock_net(sk);
615 char devname[IFNAMSIZ];
616 int index;
617
4878809f
DM
618 ret = -EINVAL;
619 if (optlen < 0)
620 goto out;
621
622 /* Bind this socket to a particular device like "eth0",
623 * as specified in the passed interface name. If the
624 * name is "" or the option length is zero the socket
625 * is not bound.
626 */
627 if (optlen > IFNAMSIZ - 1)
628 optlen = IFNAMSIZ - 1;
629 memset(devname, 0, sizeof(devname));
630
631 ret = -EFAULT;
632 if (copy_from_user(devname, optval, optlen))
633 goto out;
634
000ba2e4
DM
635 index = 0;
636 if (devname[0] != '\0') {
bf8e56bf 637 struct net_device *dev;
4878809f 638
bf8e56bf
ED
639 rcu_read_lock();
640 dev = dev_get_by_name_rcu(net, devname);
641 if (dev)
642 index = dev->ifindex;
643 rcu_read_unlock();
4878809f
DM
644 ret = -ENODEV;
645 if (!dev)
646 goto out;
4878809f
DM
647 }
648
7594888c 649 return sock_bindtoindex(sk, index);
4878809f
DM
650out:
651#endif
652
653 return ret;
654}
655
c91f6df2
BH
656static int sock_getbindtodevice(struct sock *sk, char __user *optval,
657 int __user *optlen, int len)
658{
659 int ret = -ENOPROTOOPT;
660#ifdef CONFIG_NETDEVICES
661 struct net *net = sock_net(sk);
c91f6df2 662 char devname[IFNAMSIZ];
c91f6df2
BH
663
664 if (sk->sk_bound_dev_if == 0) {
665 len = 0;
666 goto zero;
667 }
668
669 ret = -EINVAL;
670 if (len < IFNAMSIZ)
671 goto out;
672
5dbe7c17
NS
673 ret = netdev_get_name(net, devname, sk->sk_bound_dev_if);
674 if (ret)
c91f6df2 675 goto out;
c91f6df2
BH
676
677 len = strlen(devname) + 1;
678
679 ret = -EFAULT;
680 if (copy_to_user(optval, devname, len))
681 goto out;
682
683zero:
684 ret = -EFAULT;
685 if (put_user(len, optlen))
686 goto out;
687
688 ret = 0;
689
690out:
691#endif
692
693 return ret;
694}
695
193d357d
AD
696static inline void sock_valbool_flag(struct sock *sk, enum sock_flags bit,
697 int valbool)
c0ef877b
PE
698{
699 if (valbool)
700 sock_set_flag(sk, bit);
701 else
702 sock_reset_flag(sk, bit);
703}
704
f60e5990 705bool sk_mc_loop(struct sock *sk)
706{
707 if (dev_recursion_level())
708 return false;
709 if (!sk)
710 return true;
711 switch (sk->sk_family) {
712 case AF_INET:
713 return inet_sk(sk)->mc_loop;
714#if IS_ENABLED(CONFIG_IPV6)
715 case AF_INET6:
716 return inet6_sk(sk)->mc_loop;
717#endif
718 }
719 WARN_ON(1);
720 return true;
721}
722EXPORT_SYMBOL(sk_mc_loop);
723
b58f0e8f
CH
724void sock_set_reuseaddr(struct sock *sk)
725{
726 lock_sock(sk);
727 sk->sk_reuse = SK_CAN_REUSE;
728 release_sock(sk);
729}
730EXPORT_SYMBOL(sock_set_reuseaddr);
731
fe31a326
CH
732void sock_set_reuseport(struct sock *sk)
733{
734 lock_sock(sk);
735 sk->sk_reuseport = true;
736 release_sock(sk);
737}
738EXPORT_SYMBOL(sock_set_reuseport);
739
c433594c
CH
740void sock_no_linger(struct sock *sk)
741{
742 lock_sock(sk);
743 sk->sk_lingertime = 0;
744 sock_set_flag(sk, SOCK_LINGER);
745 release_sock(sk);
746}
747EXPORT_SYMBOL(sock_no_linger);
748
6e434967
CH
749void sock_set_priority(struct sock *sk, u32 priority)
750{
751 lock_sock(sk);
752 sk->sk_priority = priority;
753 release_sock(sk);
754}
755EXPORT_SYMBOL(sock_set_priority);
756
76ee0785
CH
757void sock_set_sndtimeo(struct sock *sk, s64 secs)
758{
759 lock_sock(sk);
760 if (secs && secs < MAX_SCHEDULE_TIMEOUT / HZ - 1)
761 sk->sk_sndtimeo = secs * HZ;
762 else
763 sk->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT;
764 release_sock(sk);
765}
766EXPORT_SYMBOL(sock_set_sndtimeo);
767
783da70e
CH
768static void __sock_set_timestamps(struct sock *sk, bool val, bool new, bool ns)
769{
770 if (val) {
771 sock_valbool_flag(sk, SOCK_TSTAMP_NEW, new);
772 sock_valbool_flag(sk, SOCK_RCVTSTAMPNS, ns);
773 sock_set_flag(sk, SOCK_RCVTSTAMP);
774 sock_enable_timestamp(sk, SOCK_TIMESTAMP);
775 } else {
776 sock_reset_flag(sk, SOCK_RCVTSTAMP);
777 sock_reset_flag(sk, SOCK_RCVTSTAMPNS);
778 sock_reset_flag(sk, SOCK_TSTAMP_NEW);
779 }
780}
781
782void sock_enable_timestamps(struct sock *sk)
783{
784 lock_sock(sk);
785 __sock_set_timestamps(sk, true, false, true);
786 release_sock(sk);
787}
788EXPORT_SYMBOL(sock_enable_timestamps);
789
ce3d9544
CH
790void sock_set_keepalive(struct sock *sk)
791{
792 lock_sock(sk);
793 if (sk->sk_prot->keepalive)
794 sk->sk_prot->keepalive(sk, true);
795 sock_valbool_flag(sk, SOCK_KEEPOPEN, true);
796 release_sock(sk);
797}
798EXPORT_SYMBOL(sock_set_keepalive);
799
26cfabf9
CH
800static void __sock_set_rcvbuf(struct sock *sk, int val)
801{
802 /* Ensure val * 2 fits into an int, to prevent max_t() from treating it
803 * as a negative value.
804 */
805 val = min_t(int, val, INT_MAX / 2);
806 sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
807
808 /* We double it on the way in to account for "struct sk_buff" etc.
809 * overhead. Applications assume that the SO_RCVBUF setting they make
810 * will allow that much actual data to be received on that socket.
811 *
812 * Applications are unaware that "struct sk_buff" and other overheads
813 * allocate from the receive buffer during socket buffer allocation.
814 *
815 * And after considering the possible alternatives, returning the value
816 * we actually used in getsockopt is the most desirable behavior.
817 */
818 WRITE_ONCE(sk->sk_rcvbuf, max_t(int, val * 2, SOCK_MIN_RCVBUF));
819}
820
821void sock_set_rcvbuf(struct sock *sk, int val)
822{
823 lock_sock(sk);
824 __sock_set_rcvbuf(sk, val);
825 release_sock(sk);
826}
827EXPORT_SYMBOL(sock_set_rcvbuf);
828
1da177e4
LT
829/*
830 * This is meant for all protocols to use and covers goings on
831 * at the socket level. Everything here is generic.
832 */
833
834int sock_setsockopt(struct socket *sock, int level, int optname,
b7058842 835 char __user *optval, unsigned int optlen)
1da177e4 836{
80b14dee 837 struct sock_txtime sk_txtime;
2a91525c 838 struct sock *sk = sock->sk;
1da177e4
LT
839 int val;
840 int valbool;
841 struct linger ling;
842 int ret = 0;
4ec93edb 843
1da177e4
LT
844 /*
845 * Options without arguments
846 */
847
4878809f 848 if (optname == SO_BINDTODEVICE)
c91f6df2 849 return sock_setbindtodevice(sk, optval, optlen);
4878809f 850
e71a4783
SH
851 if (optlen < sizeof(int))
852 return -EINVAL;
4ec93edb 853
1da177e4
LT
854 if (get_user(val, (int __user *)optval))
855 return -EFAULT;
4ec93edb 856
2a91525c 857 valbool = val ? 1 : 0;
1da177e4
LT
858
859 lock_sock(sk);
860
2a91525c 861 switch (optname) {
e71a4783 862 case SO_DEBUG:
2a91525c 863 if (val && !capable(CAP_NET_ADMIN))
e71a4783 864 ret = -EACCES;
2a91525c 865 else
c0ef877b 866 sock_valbool_flag(sk, SOCK_DBG, valbool);
e71a4783
SH
867 break;
868 case SO_REUSEADDR:
cdb8744d 869 sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE);
e71a4783 870 break;
055dc21a
TH
871 case SO_REUSEPORT:
872 sk->sk_reuseport = valbool;
873 break;
e71a4783 874 case SO_TYPE:
49c794e9 875 case SO_PROTOCOL:
0d6038ee 876 case SO_DOMAIN:
e71a4783
SH
877 case SO_ERROR:
878 ret = -ENOPROTOOPT;
879 break;
880 case SO_DONTROUTE:
c0ef877b 881 sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool);
0fbe82e6 882 sk_dst_reset(sk);
e71a4783
SH
883 break;
884 case SO_BROADCAST:
885 sock_valbool_flag(sk, SOCK_BROADCAST, valbool);
886 break;
887 case SO_SNDBUF:
888 /* Don't error on this BSD doesn't and if you think
82981930
ED
889 * about it this is right. Otherwise apps have to
890 * play 'guess the biggest size' games. RCVBUF/SNDBUF
891 * are treated in BSD as hints
892 */
893 val = min_t(u32, val, sysctl_wmem_max);
b0573dea 894set_sndbuf:
4057765f
GN
895 /* Ensure val * 2 fits into an int, to prevent max_t()
896 * from treating it as a negative value.
897 */
898 val = min_t(int, val, INT_MAX / 2);
e71a4783 899 sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
e292f05e
ED
900 WRITE_ONCE(sk->sk_sndbuf,
901 max_t(int, val * 2, SOCK_MIN_SNDBUF));
82981930 902 /* Wake up sending tasks if we upped the value. */
e71a4783
SH
903 sk->sk_write_space(sk);
904 break;
1da177e4 905
e71a4783
SH
906 case SO_SNDBUFFORCE:
907 if (!capable(CAP_NET_ADMIN)) {
908 ret = -EPERM;
909 break;
910 }
4057765f
GN
911
912 /* No negative values (to prevent underflow, as val will be
913 * multiplied by 2).
914 */
915 if (val < 0)
916 val = 0;
e71a4783 917 goto set_sndbuf;
b0573dea 918
e71a4783
SH
919 case SO_RCVBUF:
920 /* Don't error on this BSD doesn't and if you think
82981930
ED
921 * about it this is right. Otherwise apps have to
922 * play 'guess the biggest size' games. RCVBUF/SNDBUF
923 * are treated in BSD as hints
924 */
26cfabf9 925 __sock_set_rcvbuf(sk, min_t(u32, val, sysctl_rmem_max));
e71a4783
SH
926 break;
927
928 case SO_RCVBUFFORCE:
929 if (!capable(CAP_NET_ADMIN)) {
930 ret = -EPERM;
1da177e4 931 break;
e71a4783 932 }
4057765f
GN
933
934 /* No negative values (to prevent underflow, as val will be
935 * multiplied by 2).
936 */
26cfabf9
CH
937 __sock_set_rcvbuf(sk, max(val, 0));
938 break;
1da177e4 939
e71a4783 940 case SO_KEEPALIVE:
4b9d07a4
UB
941 if (sk->sk_prot->keepalive)
942 sk->sk_prot->keepalive(sk, valbool);
e71a4783
SH
943 sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool);
944 break;
945
946 case SO_OOBINLINE:
947 sock_valbool_flag(sk, SOCK_URGINLINE, valbool);
948 break;
949
950 case SO_NO_CHECK:
28448b80 951 sk->sk_no_check_tx = valbool;
e71a4783
SH
952 break;
953
954 case SO_PRIORITY:
5e1fccc0
EB
955 if ((val >= 0 && val <= 6) ||
956 ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
e71a4783
SH
957 sk->sk_priority = val;
958 else
959 ret = -EPERM;
960 break;
961
962 case SO_LINGER:
963 if (optlen < sizeof(ling)) {
964 ret = -EINVAL; /* 1003.1g */
1da177e4 965 break;
e71a4783 966 }
2a91525c 967 if (copy_from_user(&ling, optval, sizeof(ling))) {
e71a4783 968 ret = -EFAULT;
1da177e4 969 break;
e71a4783
SH
970 }
971 if (!ling.l_onoff)
972 sock_reset_flag(sk, SOCK_LINGER);
973 else {
1da177e4 974#if (BITS_PER_LONG == 32)
e71a4783
SH
975 if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ)
976 sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT;
1da177e4 977 else
e71a4783
SH
978#endif
979 sk->sk_lingertime = (unsigned int)ling.l_linger * HZ;
980 sock_set_flag(sk, SOCK_LINGER);
981 }
982 break;
983
984 case SO_BSDCOMPAT:
985 sock_warn_obsolete_bsdism("setsockopt");
986 break;
987
988 case SO_PASSCRED:
989 if (valbool)
990 set_bit(SOCK_PASSCRED, &sock->flags);
991 else
992 clear_bit(SOCK_PASSCRED, &sock->flags);
993 break;
994
7f1bc6e9 995 case SO_TIMESTAMP_OLD:
783da70e
CH
996 __sock_set_timestamps(sk, valbool, false, false);
997 break;
887feae3 998 case SO_TIMESTAMP_NEW:
783da70e
CH
999 __sock_set_timestamps(sk, valbool, true, false);
1000 break;
7f1bc6e9 1001 case SO_TIMESTAMPNS_OLD:
783da70e
CH
1002 __sock_set_timestamps(sk, valbool, false, true);
1003 break;
887feae3 1004 case SO_TIMESTAMPNS_NEW:
783da70e 1005 __sock_set_timestamps(sk, valbool, true, true);
e71a4783 1006 break;
9718475e
DD
1007 case SO_TIMESTAMPING_NEW:
1008 sock_set_flag(sk, SOCK_TSTAMP_NEW);
ff7653f9 1009 /* fall through */
7f1bc6e9 1010 case SO_TIMESTAMPING_OLD:
20d49473 1011 if (val & ~SOF_TIMESTAMPING_MASK) {
f249fb78 1012 ret = -EINVAL;
20d49473
PO
1013 break;
1014 }
b245be1f 1015
09c2d251 1016 if (val & SOF_TIMESTAMPING_OPT_ID &&
4ed2d765 1017 !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)) {
ac5cc977
WC
1018 if (sk->sk_protocol == IPPROTO_TCP &&
1019 sk->sk_type == SOCK_STREAM) {
6db8b963
SHY
1020 if ((1 << sk->sk_state) &
1021 (TCPF_CLOSE | TCPF_LISTEN)) {
4ed2d765
WB
1022 ret = -EINVAL;
1023 break;
1024 }
1025 sk->sk_tskey = tcp_sk(sk)->snd_una;
1026 } else {
1027 sk->sk_tskey = 0;
1028 }
1029 }
1c885808
FY
1030
1031 if (val & SOF_TIMESTAMPING_OPT_STATS &&
1032 !(val & SOF_TIMESTAMPING_OPT_TSONLY)) {
1033 ret = -EINVAL;
1034 break;
1035 }
1036
b9f40e21 1037 sk->sk_tsflags = val;
20d49473
PO
1038 if (val & SOF_TIMESTAMPING_RX_SOFTWARE)
1039 sock_enable_timestamp(sk,
1040 SOCK_TIMESTAMPING_RX_SOFTWARE);
9718475e
DD
1041 else {
1042 if (optname == SO_TIMESTAMPING_NEW)
1043 sock_reset_flag(sk, SOCK_TSTAMP_NEW);
1044
20d49473 1045 sock_disable_timestamp(sk,
08e29af3 1046 (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE));
9718475e 1047 }
20d49473
PO
1048 break;
1049
e71a4783
SH
1050 case SO_RCVLOWAT:
1051 if (val < 0)
1052 val = INT_MAX;
d1361840
ED
1053 if (sock->ops->set_rcvlowat)
1054 ret = sock->ops->set_rcvlowat(sk, val);
1055 else
eac66402 1056 WRITE_ONCE(sk->sk_rcvlowat, val ? : 1);
e71a4783
SH
1057 break;
1058
45bdc661 1059 case SO_RCVTIMEO_OLD:
a9beb86a
DD
1060 case SO_RCVTIMEO_NEW:
1061 ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen, optname == SO_RCVTIMEO_OLD);
e71a4783
SH
1062 break;
1063
45bdc661 1064 case SO_SNDTIMEO_OLD:
a9beb86a
DD
1065 case SO_SNDTIMEO_NEW:
1066 ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen, optname == SO_SNDTIMEO_OLD);
e71a4783 1067 break;
1da177e4 1068
e71a4783
SH
1069 case SO_ATTACH_FILTER:
1070 ret = -EINVAL;
1071 if (optlen == sizeof(struct sock_fprog)) {
1072 struct sock_fprog fprog;
1da177e4 1073
e71a4783
SH
1074 ret = -EFAULT;
1075 if (copy_from_user(&fprog, optval, sizeof(fprog)))
1da177e4 1076 break;
e71a4783
SH
1077
1078 ret = sk_attach_filter(&fprog, sk);
1079 }
1080 break;
1081
89aa0758
AS
1082 case SO_ATTACH_BPF:
1083 ret = -EINVAL;
1084 if (optlen == sizeof(u32)) {
1085 u32 ufd;
1086
1087 ret = -EFAULT;
1088 if (copy_from_user(&ufd, optval, sizeof(ufd)))
1089 break;
1090
1091 ret = sk_attach_bpf(ufd, sk);
1092 }
1093 break;
1094
538950a1
CG
1095 case SO_ATTACH_REUSEPORT_CBPF:
1096 ret = -EINVAL;
1097 if (optlen == sizeof(struct sock_fprog)) {
1098 struct sock_fprog fprog;
1099
1100 ret = -EFAULT;
1101 if (copy_from_user(&fprog, optval, sizeof(fprog)))
1102 break;
1103
1104 ret = sk_reuseport_attach_filter(&fprog, sk);
1105 }
1106 break;
1107
1108 case SO_ATTACH_REUSEPORT_EBPF:
1109 ret = -EINVAL;
1110 if (optlen == sizeof(u32)) {
1111 u32 ufd;
1112
1113 ret = -EFAULT;
1114 if (copy_from_user(&ufd, optval, sizeof(ufd)))
1115 break;
1116
1117 ret = sk_reuseport_attach_bpf(ufd, sk);
1118 }
1119 break;
1120
99f3a064
MKL
1121 case SO_DETACH_REUSEPORT_BPF:
1122 ret = reuseport_detach_prog(sk);
1123 break;
1124
e71a4783 1125 case SO_DETACH_FILTER:
55b33325 1126 ret = sk_detach_filter(sk);
e71a4783 1127 break;
1da177e4 1128
d59577b6
VB
1129 case SO_LOCK_FILTER:
1130 if (sock_flag(sk, SOCK_FILTER_LOCKED) && !valbool)
1131 ret = -EPERM;
1132 else
1133 sock_valbool_flag(sk, SOCK_FILTER_LOCKED, valbool);
1134 break;
1135
e71a4783
SH
1136 case SO_PASSSEC:
1137 if (valbool)
1138 set_bit(SOCK_PASSSEC, &sock->flags);
1139 else
1140 clear_bit(SOCK_PASSSEC, &sock->flags);
1141 break;
4a19ec58 1142 case SO_MARK:
50254256 1143 if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) {
4a19ec58 1144 ret = -EPERM;
50254256 1145 } else if (val != sk->sk_mark) {
4a19ec58 1146 sk->sk_mark = val;
50254256
DB
1147 sk_dst_reset(sk);
1148 }
4a19ec58 1149 break;
877ce7c1 1150
3b885787 1151 case SO_RXQ_OVFL:
8083f0fc 1152 sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool);
3b885787 1153 break;
6e3e939f
JB
1154
1155 case SO_WIFI_STATUS:
1156 sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool);
1157 break;
1158
ef64a54f
PE
1159 case SO_PEEK_OFF:
1160 if (sock->ops->set_peek_off)
12663bfc 1161 ret = sock->ops->set_peek_off(sk, val);
ef64a54f
PE
1162 else
1163 ret = -EOPNOTSUPP;
1164 break;
3bdc0eba
BG
1165
1166 case SO_NOFCS:
1167 sock_valbool_flag(sk, SOCK_NOFCS, valbool);
1168 break;
1169
7d4c04fc
KJ
1170 case SO_SELECT_ERR_QUEUE:
1171 sock_valbool_flag(sk, SOCK_SELECT_ERR_QUEUE, valbool);
1172 break;
1173
e0d1095a 1174#ifdef CONFIG_NET_RX_BUSY_POLL
64b0dc51 1175 case SO_BUSY_POLL:
dafcc438
ET
1176 /* allow unprivileged users to decrease the value */
1177 if ((val > sk->sk_ll_usec) && !capable(CAP_NET_ADMIN))
1178 ret = -EPERM;
1179 else {
1180 if (val < 0)
1181 ret = -EINVAL;
1182 else
1183 sk->sk_ll_usec = val;
1184 }
1185 break;
1186#endif
62748f32
ED
1187
1188 case SO_MAX_PACING_RATE:
6bdef102
ED
1189 {
1190 unsigned long ulval = (val == ~0U) ? ~0UL : val;
1191
1192 if (sizeof(ulval) != sizeof(val) &&
1193 optlen >= sizeof(ulval) &&
1194 get_user(ulval, (unsigned long __user *)optval)) {
1195 ret = -EFAULT;
1196 break;
1197 }
1198 if (ulval != ~0UL)
218af599
ED
1199 cmpxchg(&sk->sk_pacing_status,
1200 SK_PACING_NONE,
1201 SK_PACING_NEEDED);
6bdef102
ED
1202 sk->sk_max_pacing_rate = ulval;
1203 sk->sk_pacing_rate = min(sk->sk_pacing_rate, ulval);
62748f32 1204 break;
6bdef102 1205 }
70da268b 1206 case SO_INCOMING_CPU:
7170a977 1207 WRITE_ONCE(sk->sk_incoming_cpu, val);
70da268b
ED
1208 break;
1209
a87cb3e4
TH
1210 case SO_CNX_ADVICE:
1211 if (val == 1)
1212 dst_negative_advice(sk);
1213 break;
76851d12
WB
1214
1215 case SO_ZEROCOPY:
28190752 1216 if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6) {
b5947e5d
WB
1217 if (!((sk->sk_type == SOCK_STREAM &&
1218 sk->sk_protocol == IPPROTO_TCP) ||
1219 (sk->sk_type == SOCK_DGRAM &&
1220 sk->sk_protocol == IPPROTO_UDP)))
28190752 1221 ret = -ENOTSUPP;
28190752 1222 } else if (sk->sk_family != PF_RDS) {
76851d12 1223 ret = -ENOTSUPP;
28190752
SV
1224 }
1225 if (!ret) {
1226 if (val < 0 || val > 1)
1227 ret = -EINVAL;
1228 else
1229 sock_valbool_flag(sk, SOCK_ZEROCOPY, valbool);
28190752 1230 }
334e6413
JSP
1231 break;
1232
80b14dee 1233 case SO_TXTIME:
790709f2 1234 if (optlen != sizeof(struct sock_txtime)) {
80b14dee 1235 ret = -EINVAL;
790709f2 1236 break;
80b14dee
RC
1237 } else if (copy_from_user(&sk_txtime, optval,
1238 sizeof(struct sock_txtime))) {
1239 ret = -EFAULT;
790709f2 1240 break;
80b14dee
RC
1241 } else if (sk_txtime.flags & ~SOF_TXTIME_FLAGS_MASK) {
1242 ret = -EINVAL;
790709f2
ED
1243 break;
1244 }
1245 /* CLOCK_MONOTONIC is only used by sch_fq, and this packet
1246 * scheduler has enough safe guards.
1247 */
1248 if (sk_txtime.clockid != CLOCK_MONOTONIC &&
1249 !ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) {
1250 ret = -EPERM;
1251 break;
80b14dee 1252 }
790709f2
ED
1253 sock_valbool_flag(sk, SOCK_TXTIME, true);
1254 sk->sk_clockid = sk_txtime.clockid;
1255 sk->sk_txtime_deadline_mode =
1256 !!(sk_txtime.flags & SOF_TXTIME_DEADLINE_MODE);
1257 sk->sk_txtime_report_errors =
1258 !!(sk_txtime.flags & SOF_TXTIME_REPORT_ERRORS);
80b14dee
RC
1259 break;
1260
f5dd3d0c 1261 case SO_BINDTOIFINDEX:
7594888c 1262 ret = sock_bindtoindex_locked(sk, val);
f5dd3d0c
DH
1263 break;
1264
e71a4783
SH
1265 default:
1266 ret = -ENOPROTOOPT;
1267 break;
4ec93edb 1268 }
1da177e4
LT
1269 release_sock(sk);
1270 return ret;
1271}
2a91525c 1272EXPORT_SYMBOL(sock_setsockopt);
1da177e4
LT
1273
1274
8f09898b 1275static void cred_to_ucred(struct pid *pid, const struct cred *cred,
1276 struct ucred *ucred)
3f551f94
EB
1277{
1278 ucred->pid = pid_vnr(pid);
1279 ucred->uid = ucred->gid = -1;
1280 if (cred) {
1281 struct user_namespace *current_ns = current_user_ns();
1282
b2e4f544
EB
1283 ucred->uid = from_kuid_munged(current_ns, cred->euid);
1284 ucred->gid = from_kgid_munged(current_ns, cred->egid);
3f551f94
EB
1285 }
1286}
1287
28b5ba2a
DH
1288static int groups_to_user(gid_t __user *dst, const struct group_info *src)
1289{
1290 struct user_namespace *user_ns = current_user_ns();
1291 int i;
1292
1293 for (i = 0; i < src->ngroups; i++)
1294 if (put_user(from_kgid_munged(user_ns, src->gid[i]), dst + i))
1295 return -EFAULT;
1296
1297 return 0;
1298}
1299
1da177e4
LT
1300int sock_getsockopt(struct socket *sock, int level, int optname,
1301 char __user *optval, int __user *optlen)
1302{
1303 struct sock *sk = sock->sk;
4ec93edb 1304
e71a4783 1305 union {
4ec93edb 1306 int val;
5daab9db 1307 u64 val64;
677f136c 1308 unsigned long ulval;
4ec93edb 1309 struct linger ling;
fe0c72f3
AB
1310 struct old_timeval32 tm32;
1311 struct __kernel_old_timeval tm;
a9beb86a 1312 struct __kernel_sock_timeval stm;
80b14dee 1313 struct sock_txtime txtime;
1da177e4 1314 } v;
4ec93edb 1315
4d0392be 1316 int lv = sizeof(int);
1da177e4 1317 int len;
4ec93edb 1318
e71a4783 1319 if (get_user(len, optlen))
4ec93edb 1320 return -EFAULT;
e71a4783 1321 if (len < 0)
1da177e4 1322 return -EINVAL;
4ec93edb 1323
50fee1de 1324 memset(&v, 0, sizeof(v));
df0bca04 1325
2a91525c 1326 switch (optname) {
e71a4783
SH
1327 case SO_DEBUG:
1328 v.val = sock_flag(sk, SOCK_DBG);
1329 break;
1330
1331 case SO_DONTROUTE:
1332 v.val = sock_flag(sk, SOCK_LOCALROUTE);
1333 break;
1334
1335 case SO_BROADCAST:
1b23a5df 1336 v.val = sock_flag(sk, SOCK_BROADCAST);
e71a4783
SH
1337 break;
1338
1339 case SO_SNDBUF:
1340 v.val = sk->sk_sndbuf;
1341 break;
1342
1343 case SO_RCVBUF:
1344 v.val = sk->sk_rcvbuf;
1345 break;
1346
1347 case SO_REUSEADDR:
1348 v.val = sk->sk_reuse;
1349 break;
1350
055dc21a
TH
1351 case SO_REUSEPORT:
1352 v.val = sk->sk_reuseport;
1353 break;
1354
e71a4783 1355 case SO_KEEPALIVE:
1b23a5df 1356 v.val = sock_flag(sk, SOCK_KEEPOPEN);
e71a4783
SH
1357 break;
1358
1359 case SO_TYPE:
1360 v.val = sk->sk_type;
1361 break;
1362
49c794e9
JE
1363 case SO_PROTOCOL:
1364 v.val = sk->sk_protocol;
1365 break;
1366
0d6038ee
JE
1367 case SO_DOMAIN:
1368 v.val = sk->sk_family;
1369 break;
1370
e71a4783
SH
1371 case SO_ERROR:
1372 v.val = -sock_error(sk);
2a91525c 1373 if (v.val == 0)
e71a4783
SH
1374 v.val = xchg(&sk->sk_err_soft, 0);
1375 break;
1376
1377 case SO_OOBINLINE:
1b23a5df 1378 v.val = sock_flag(sk, SOCK_URGINLINE);
e71a4783
SH
1379 break;
1380
1381 case SO_NO_CHECK:
28448b80 1382 v.val = sk->sk_no_check_tx;
e71a4783
SH
1383 break;
1384
1385 case SO_PRIORITY:
1386 v.val = sk->sk_priority;
1387 break;
1388
1389 case SO_LINGER:
1390 lv = sizeof(v.ling);
1b23a5df 1391 v.ling.l_onoff = sock_flag(sk, SOCK_LINGER);
e71a4783
SH
1392 v.ling.l_linger = sk->sk_lingertime / HZ;
1393 break;
1394
1395 case SO_BSDCOMPAT:
1396 sock_warn_obsolete_bsdism("getsockopt");
1397 break;
1398
7f1bc6e9 1399 case SO_TIMESTAMP_OLD:
92f37fd2 1400 v.val = sock_flag(sk, SOCK_RCVTSTAMP) &&
887feae3 1401 !sock_flag(sk, SOCK_TSTAMP_NEW) &&
92f37fd2
ED
1402 !sock_flag(sk, SOCK_RCVTSTAMPNS);
1403 break;
1404
7f1bc6e9 1405 case SO_TIMESTAMPNS_OLD:
887feae3
DD
1406 v.val = sock_flag(sk, SOCK_RCVTSTAMPNS) && !sock_flag(sk, SOCK_TSTAMP_NEW);
1407 break;
1408
1409 case SO_TIMESTAMP_NEW:
1410 v.val = sock_flag(sk, SOCK_RCVTSTAMP) && sock_flag(sk, SOCK_TSTAMP_NEW);
1411 break;
1412
1413 case SO_TIMESTAMPNS_NEW:
1414 v.val = sock_flag(sk, SOCK_RCVTSTAMPNS) && sock_flag(sk, SOCK_TSTAMP_NEW);
e71a4783
SH
1415 break;
1416
7f1bc6e9 1417 case SO_TIMESTAMPING_OLD:
b9f40e21 1418 v.val = sk->sk_tsflags;
20d49473
PO
1419 break;
1420
a9beb86a
DD
1421 case SO_RCVTIMEO_OLD:
1422 case SO_RCVTIMEO_NEW:
1423 lv = sock_get_timeout(sk->sk_rcvtimeo, &v, SO_RCVTIMEO_OLD == optname);
e71a4783
SH
1424 break;
1425
a9beb86a
DD
1426 case SO_SNDTIMEO_OLD:
1427 case SO_SNDTIMEO_NEW:
1428 lv = sock_get_timeout(sk->sk_sndtimeo, &v, SO_SNDTIMEO_OLD == optname);
e71a4783 1429 break;
1da177e4 1430
e71a4783
SH
1431 case SO_RCVLOWAT:
1432 v.val = sk->sk_rcvlowat;
1433 break;
1da177e4 1434
e71a4783 1435 case SO_SNDLOWAT:
2a91525c 1436 v.val = 1;
e71a4783 1437 break;
1da177e4 1438
e71a4783 1439 case SO_PASSCRED:
82981930 1440 v.val = !!test_bit(SOCK_PASSCRED, &sock->flags);
e71a4783 1441 break;
1da177e4 1442
e71a4783 1443 case SO_PEERCRED:
109f6e39
EB
1444 {
1445 struct ucred peercred;
1446 if (len > sizeof(peercred))
1447 len = sizeof(peercred);
1448 cred_to_ucred(sk->sk_peer_pid, sk->sk_peer_cred, &peercred);
1449 if (copy_to_user(optval, &peercred, len))
e71a4783
SH
1450 return -EFAULT;
1451 goto lenout;
109f6e39 1452 }
1da177e4 1453
28b5ba2a
DH
1454 case SO_PEERGROUPS:
1455 {
1456 int ret, n;
1457
1458 if (!sk->sk_peer_cred)
1459 return -ENODATA;
1460
1461 n = sk->sk_peer_cred->group_info->ngroups;
1462 if (len < n * sizeof(gid_t)) {
1463 len = n * sizeof(gid_t);
1464 return put_user(len, optlen) ? -EFAULT : -ERANGE;
1465 }
1466 len = n * sizeof(gid_t);
1467
1468 ret = groups_to_user((gid_t __user *)optval,
1469 sk->sk_peer_cred->group_info);
1470 if (ret)
1471 return ret;
1472 goto lenout;
1473 }
1474
e71a4783
SH
1475 case SO_PEERNAME:
1476 {
1477 char address[128];
1478
9b2c45d4
DV
1479 lv = sock->ops->getname(sock, (struct sockaddr *)address, 2);
1480 if (lv < 0)
e71a4783
SH
1481 return -ENOTCONN;
1482 if (lv < len)
1483 return -EINVAL;
1484 if (copy_to_user(optval, address, len))
1485 return -EFAULT;
1486 goto lenout;
1487 }
1da177e4 1488
e71a4783
SH
1489 /* Dubious BSD thing... Probably nobody even uses it, but
1490 * the UNIX standard wants it for whatever reason... -DaveM
1491 */
1492 case SO_ACCEPTCONN:
1493 v.val = sk->sk_state == TCP_LISTEN;
1494 break;
1da177e4 1495
e71a4783 1496 case SO_PASSSEC:
82981930 1497 v.val = !!test_bit(SOCK_PASSSEC, &sock->flags);
e71a4783 1498 break;
877ce7c1 1499
e71a4783
SH
1500 case SO_PEERSEC:
1501 return security_socket_getpeersec_stream(sock, optval, optlen, len);
1da177e4 1502
4a19ec58
LAT
1503 case SO_MARK:
1504 v.val = sk->sk_mark;
1505 break;
1506
3b885787 1507 case SO_RXQ_OVFL:
1b23a5df 1508 v.val = sock_flag(sk, SOCK_RXQ_OVFL);
3b885787
NH
1509 break;
1510
6e3e939f 1511 case SO_WIFI_STATUS:
1b23a5df 1512 v.val = sock_flag(sk, SOCK_WIFI_STATUS);
6e3e939f
JB
1513 break;
1514
ef64a54f
PE
1515 case SO_PEEK_OFF:
1516 if (!sock->ops->set_peek_off)
1517 return -EOPNOTSUPP;
1518
1519 v.val = sk->sk_peek_off;
1520 break;
bc2f7996 1521 case SO_NOFCS:
1b23a5df 1522 v.val = sock_flag(sk, SOCK_NOFCS);
bc2f7996 1523 break;
c91f6df2 1524
f7b86bfe 1525 case SO_BINDTODEVICE:
c91f6df2
BH
1526 return sock_getbindtodevice(sk, optval, optlen, len);
1527
a8fc9277
PE
1528 case SO_GET_FILTER:
1529 len = sk_get_filter(sk, (struct sock_filter __user *)optval, len);
1530 if (len < 0)
1531 return len;
1532
1533 goto lenout;
c91f6df2 1534
d59577b6
VB
1535 case SO_LOCK_FILTER:
1536 v.val = sock_flag(sk, SOCK_FILTER_LOCKED);
1537 break;
1538
ea02f941
MS
1539 case SO_BPF_EXTENSIONS:
1540 v.val = bpf_tell_extensions();
1541 break;
1542
7d4c04fc
KJ
1543 case SO_SELECT_ERR_QUEUE:
1544 v.val = sock_flag(sk, SOCK_SELECT_ERR_QUEUE);
1545 break;
1546
e0d1095a 1547#ifdef CONFIG_NET_RX_BUSY_POLL
64b0dc51 1548 case SO_BUSY_POLL:
dafcc438
ET
1549 v.val = sk->sk_ll_usec;
1550 break;
1551#endif
1552
62748f32 1553 case SO_MAX_PACING_RATE:
677f136c
ED
1554 if (sizeof(v.ulval) != sizeof(v.val) && len >= sizeof(v.ulval)) {
1555 lv = sizeof(v.ulval);
1556 v.ulval = sk->sk_max_pacing_rate;
1557 } else {
1558 /* 32bit version */
1559 v.val = min_t(unsigned long, sk->sk_max_pacing_rate, ~0U);
1560 }
62748f32
ED
1561 break;
1562
2c8c56e1 1563 case SO_INCOMING_CPU:
7170a977 1564 v.val = READ_ONCE(sk->sk_incoming_cpu);
2c8c56e1
ED
1565 break;
1566
a2d133b1
JH
1567 case SO_MEMINFO:
1568 {
1569 u32 meminfo[SK_MEMINFO_VARS];
1570
a2d133b1
JH
1571 sk_get_meminfo(sk, meminfo);
1572
1573 len = min_t(unsigned int, len, sizeof(meminfo));
1574 if (copy_to_user(optval, &meminfo, len))
1575 return -EFAULT;
1576
1577 goto lenout;
1578 }
6d433902
SS
1579
1580#ifdef CONFIG_NET_RX_BUSY_POLL
1581 case SO_INCOMING_NAPI_ID:
1582 v.val = READ_ONCE(sk->sk_napi_id);
1583
1584 /* aggregate non-NAPI IDs down to 0 */
1585 if (v.val < MIN_NAPI_ID)
1586 v.val = 0;
1587
1588 break;
1589#endif
1590
5daab9db
CF
1591 case SO_COOKIE:
1592 lv = sizeof(u64);
1593 if (len < lv)
1594 return -EINVAL;
1595 v.val64 = sock_gen_cookie(sk);
1596 break;
1597
76851d12
WB
1598 case SO_ZEROCOPY:
1599 v.val = sock_flag(sk, SOCK_ZEROCOPY);
1600 break;
1601
80b14dee
RC
1602 case SO_TXTIME:
1603 lv = sizeof(v.txtime);
1604 v.txtime.clockid = sk->sk_clockid;
1605 v.txtime.flags |= sk->sk_txtime_deadline_mode ?
1606 SOF_TXTIME_DEADLINE_MODE : 0;
4b15c707
JSP
1607 v.txtime.flags |= sk->sk_txtime_report_errors ?
1608 SOF_TXTIME_REPORT_ERRORS : 0;
80b14dee
RC
1609 break;
1610
f5dd3d0c
DH
1611 case SO_BINDTOIFINDEX:
1612 v.val = sk->sk_bound_dev_if;
1613 break;
1614
e71a4783 1615 default:
443b5991
YH
1616 /* We implement the SO_SNDLOWAT etc to not be settable
1617 * (1003.1g 7).
1618 */
e71a4783 1619 return -ENOPROTOOPT;
1da177e4 1620 }
e71a4783 1621
1da177e4
LT
1622 if (len > lv)
1623 len = lv;
1624 if (copy_to_user(optval, &v, len))
1625 return -EFAULT;
1626lenout:
4ec93edb
YH
1627 if (put_user(len, optlen))
1628 return -EFAULT;
1629 return 0;
1da177e4
LT
1630}
1631
a5b5bb9a
IM
1632/*
1633 * Initialize an sk_lock.
1634 *
1635 * (We also register the sk_lock with the lock validator.)
1636 */
b6f99a21 1637static inline void sock_lock_init(struct sock *sk)
a5b5bb9a 1638{
cdfbabfb
DH
1639 if (sk->sk_kern_sock)
1640 sock_lock_init_class_and_name(
1641 sk,
1642 af_family_kern_slock_key_strings[sk->sk_family],
1643 af_family_kern_slock_keys + sk->sk_family,
1644 af_family_kern_key_strings[sk->sk_family],
1645 af_family_kern_keys + sk->sk_family);
1646 else
1647 sock_lock_init_class_and_name(
1648 sk,
ed07536e
PZ
1649 af_family_slock_key_strings[sk->sk_family],
1650 af_family_slock_keys + sk->sk_family,
1651 af_family_key_strings[sk->sk_family],
1652 af_family_keys + sk->sk_family);
a5b5bb9a
IM
1653}
1654
4dc6dc71
ED
1655/*
1656 * Copy all fields from osk to nsk but nsk->sk_refcnt must not change yet,
1657 * even temporarly, because of RCU lookups. sk_node should also be left as is.
68835aba 1658 * We must not copy fields between sk_dontcopy_begin and sk_dontcopy_end
4dc6dc71 1659 */
f1a6c4da
PE
1660static void sock_copy(struct sock *nsk, const struct sock *osk)
1661{
b8e202d1 1662 const struct proto *prot = READ_ONCE(osk->sk_prot);
f1a6c4da
PE
1663#ifdef CONFIG_SECURITY_NETWORK
1664 void *sptr = nsk->sk_security;
1665#endif
68835aba
ED
1666 memcpy(nsk, osk, offsetof(struct sock, sk_dontcopy_begin));
1667
1668 memcpy(&nsk->sk_dontcopy_end, &osk->sk_dontcopy_end,
b8e202d1 1669 prot->obj_size - offsetof(struct sock, sk_dontcopy_end));
68835aba 1670
f1a6c4da
PE
1671#ifdef CONFIG_SECURITY_NETWORK
1672 nsk->sk_security = sptr;
1673 security_sk_clone(osk, nsk);
1674#endif
1675}
1676
2e4afe7b
PE
1677static struct sock *sk_prot_alloc(struct proto *prot, gfp_t priority,
1678 int family)
c308c1b2
PE
1679{
1680 struct sock *sk;
1681 struct kmem_cache *slab;
1682
1683 slab = prot->slab;
e912b114
ED
1684 if (slab != NULL) {
1685 sk = kmem_cache_alloc(slab, priority & ~__GFP_ZERO);
1686 if (!sk)
1687 return sk;
6471384a 1688 if (want_init_on_alloc(priority))
ba2489b0 1689 sk_prot_clear_nulls(sk, prot->obj_size);
fcbdf09d 1690 } else
c308c1b2
PE
1691 sk = kmalloc(prot->obj_size, priority);
1692
2e4afe7b
PE
1693 if (sk != NULL) {
1694 if (security_sk_alloc(sk, family, priority))
1695 goto out_free;
1696
1697 if (!try_module_get(prot->owner))
1698 goto out_free_sec;
e022f0b4 1699 sk_tx_queue_clear(sk);
2e4afe7b
PE
1700 }
1701
c308c1b2 1702 return sk;
2e4afe7b
PE
1703
1704out_free_sec:
1705 security_sk_free(sk);
1706out_free:
1707 if (slab != NULL)
1708 kmem_cache_free(slab, sk);
1709 else
1710 kfree(sk);
1711 return NULL;
c308c1b2
PE
1712}
1713
1714static void sk_prot_free(struct proto *prot, struct sock *sk)
1715{
1716 struct kmem_cache *slab;
2e4afe7b 1717 struct module *owner;
c308c1b2 1718
2e4afe7b 1719 owner = prot->owner;
c308c1b2 1720 slab = prot->slab;
2e4afe7b 1721
bd1060a1 1722 cgroup_sk_free(&sk->sk_cgrp_data);
2d758073 1723 mem_cgroup_sk_free(sk);
2e4afe7b 1724 security_sk_free(sk);
c308c1b2
PE
1725 if (slab != NULL)
1726 kmem_cache_free(slab, sk);
1727 else
1728 kfree(sk);
2e4afe7b 1729 module_put(owner);
c308c1b2
PE
1730}
1731
1da177e4
LT
1732/**
1733 * sk_alloc - All socket objects are allocated here
c4ea43c5 1734 * @net: the applicable net namespace
4dc3b16b
PP
1735 * @family: protocol family
1736 * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
1737 * @prot: struct proto associated with this new sock instance
11aa9c28 1738 * @kern: is this to be a kernel socket?
1da177e4 1739 */
1b8d7ae4 1740struct sock *sk_alloc(struct net *net, int family, gfp_t priority,
11aa9c28 1741 struct proto *prot, int kern)
1da177e4 1742{
c308c1b2 1743 struct sock *sk;
1da177e4 1744
154adbc8 1745 sk = sk_prot_alloc(prot, priority | __GFP_ZERO, family);
1da177e4 1746 if (sk) {
154adbc8
PE
1747 sk->sk_family = family;
1748 /*
1749 * See comment in struct sock definition to understand
1750 * why we need sk_prot_creator -acme
1751 */
1752 sk->sk_prot = sk->sk_prot_creator = prot;
cdfbabfb 1753 sk->sk_kern_sock = kern;
154adbc8 1754 sock_lock_init(sk);
26abe143 1755 sk->sk_net_refcnt = kern ? 0 : 1;
648845ab 1756 if (likely(sk->sk_net_refcnt)) {
26abe143 1757 get_net(net);
648845ab
TZ
1758 sock_inuse_add(net, 1);
1759 }
1760
26abe143 1761 sock_net_set(sk, net);
14afee4b 1762 refcount_set(&sk->sk_wmem_alloc, 1);
f8451725 1763
2d758073 1764 mem_cgroup_sk_alloc(sk);
d979a39d 1765 cgroup_sk_alloc(&sk->sk_cgrp_data);
2a56a1fe
TH
1766 sock_update_classid(&sk->sk_cgrp_data);
1767 sock_update_netprioidx(&sk->sk_cgrp_data);
1da177e4 1768 }
a79af59e 1769
2e4afe7b 1770 return sk;
1da177e4 1771}
2a91525c 1772EXPORT_SYMBOL(sk_alloc);
1da177e4 1773
a4298e45
ED
1774/* Sockets having SOCK_RCU_FREE will call this function after one RCU
1775 * grace period. This is the case for UDP sockets and TCP listeners.
1776 */
1777static void __sk_destruct(struct rcu_head *head)
1da177e4 1778{
a4298e45 1779 struct sock *sk = container_of(head, struct sock, sk_rcu);
1da177e4 1780 struct sk_filter *filter;
1da177e4
LT
1781
1782 if (sk->sk_destruct)
1783 sk->sk_destruct(sk);
1784
a898def2 1785 filter = rcu_dereference_check(sk->sk_filter,
14afee4b 1786 refcount_read(&sk->sk_wmem_alloc) == 0);
1da177e4 1787 if (filter) {
309dd5fc 1788 sk_filter_uncharge(sk, filter);
a9b3cd7f 1789 RCU_INIT_POINTER(sk->sk_filter, NULL);
1da177e4
LT
1790 }
1791
08e29af3 1792 sock_disable_timestamp(sk, SK_FLAGS_TIMESTAMP);
1da177e4 1793
6ac99e8f
MKL
1794#ifdef CONFIG_BPF_SYSCALL
1795 bpf_sk_storage_free(sk);
1796#endif
1797
1da177e4 1798 if (atomic_read(&sk->sk_omem_alloc))
e005d193
JP
1799 pr_debug("%s: optmem leakage (%d bytes) detected\n",
1800 __func__, atomic_read(&sk->sk_omem_alloc));
1da177e4 1801
22a0e18e
ED
1802 if (sk->sk_frag.page) {
1803 put_page(sk->sk_frag.page);
1804 sk->sk_frag.page = NULL;
1805 }
1806
109f6e39
EB
1807 if (sk->sk_peer_cred)
1808 put_cred(sk->sk_peer_cred);
1809 put_pid(sk->sk_peer_pid);
26abe143
EB
1810 if (likely(sk->sk_net_refcnt))
1811 put_net(sock_net(sk));
c308c1b2 1812 sk_prot_free(sk->sk_prot_creator, sk);
1da177e4 1813}
2b85a34e 1814
a4298e45
ED
1815void sk_destruct(struct sock *sk)
1816{
8c7138b3
MKL
1817 bool use_call_rcu = sock_flag(sk, SOCK_RCU_FREE);
1818
1819 if (rcu_access_pointer(sk->sk_reuseport_cb)) {
1820 reuseport_detach_sock(sk);
1821 use_call_rcu = true;
1822 }
1823
1824 if (use_call_rcu)
a4298e45
ED
1825 call_rcu(&sk->sk_rcu, __sk_destruct);
1826 else
1827 __sk_destruct(&sk->sk_rcu);
1828}
1829
eb4cb008
CG
1830static void __sk_free(struct sock *sk)
1831{
648845ab
TZ
1832 if (likely(sk->sk_net_refcnt))
1833 sock_inuse_add(sock_net(sk), -1);
1834
9709020c 1835 if (unlikely(sk->sk_net_refcnt && sock_diag_has_destroy_listeners(sk)))
eb4cb008
CG
1836 sock_diag_broadcast_destroy(sk);
1837 else
1838 sk_destruct(sk);
1839}
1840
2b85a34e
ED
1841void sk_free(struct sock *sk)
1842{
1843 /*
25985edc 1844 * We subtract one from sk_wmem_alloc and can know if
2b85a34e
ED
1845 * some packets are still in some tx queue.
1846 * If not null, sock_wfree() will call __sk_free(sk) later
1847 */
14afee4b 1848 if (refcount_dec_and_test(&sk->sk_wmem_alloc))
2b85a34e
ED
1849 __sk_free(sk);
1850}
2a91525c 1851EXPORT_SYMBOL(sk_free);
1da177e4 1852
581319c5
PA
1853static void sk_init_common(struct sock *sk)
1854{
1855 skb_queue_head_init(&sk->sk_receive_queue);
1856 skb_queue_head_init(&sk->sk_write_queue);
1857 skb_queue_head_init(&sk->sk_error_queue);
1858
1859 rwlock_init(&sk->sk_callback_lock);
1860 lockdep_set_class_and_name(&sk->sk_receive_queue.lock,
1861 af_rlock_keys + sk->sk_family,
1862 af_family_rlock_key_strings[sk->sk_family]);
1863 lockdep_set_class_and_name(&sk->sk_write_queue.lock,
1864 af_wlock_keys + sk->sk_family,
1865 af_family_wlock_key_strings[sk->sk_family]);
1866 lockdep_set_class_and_name(&sk->sk_error_queue.lock,
1867 af_elock_keys + sk->sk_family,
1868 af_family_elock_key_strings[sk->sk_family]);
1869 lockdep_set_class_and_name(&sk->sk_callback_lock,
1870 af_callback_keys + sk->sk_family,
1871 af_family_clock_key_strings[sk->sk_family]);
1872}
1873
e56c57d0
ED
1874/**
1875 * sk_clone_lock - clone a socket, and lock its clone
1876 * @sk: the socket to clone
1877 * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
1878 *
1879 * Caller must unlock socket even in error path (bh_unlock_sock(newsk))
1880 */
1881struct sock *sk_clone_lock(const struct sock *sk, const gfp_t priority)
87d11ceb 1882{
b8e202d1 1883 struct proto *prot = READ_ONCE(sk->sk_prot);
8fd1d178 1884 struct sock *newsk;
278571ba 1885 bool is_charged = true;
87d11ceb 1886
b8e202d1 1887 newsk = sk_prot_alloc(prot, priority, sk->sk_family);
87d11ceb
ACM
1888 if (newsk != NULL) {
1889 struct sk_filter *filter;
1890
892c141e 1891 sock_copy(newsk, sk);
87d11ceb 1892
b8e202d1 1893 newsk->sk_prot_creator = prot;
9d538fa6 1894
87d11ceb 1895 /* SANITY */
8a681736
SV
1896 if (likely(newsk->sk_net_refcnt))
1897 get_net(sock_net(newsk));
87d11ceb
ACM
1898 sk_node_init(&newsk->sk_node);
1899 sock_lock_init(newsk);
1900 bh_lock_sock(newsk);
fa438ccf 1901 newsk->sk_backlog.head = newsk->sk_backlog.tail = NULL;
8eae939f 1902 newsk->sk_backlog.len = 0;
87d11ceb
ACM
1903
1904 atomic_set(&newsk->sk_rmem_alloc, 0);
2b85a34e
ED
1905 /*
1906 * sk_wmem_alloc set to one (see sk_free() and sock_wfree())
1907 */
14afee4b 1908 refcount_set(&newsk->sk_wmem_alloc, 1);
87d11ceb 1909 atomic_set(&newsk->sk_omem_alloc, 0);
581319c5 1910 sk_init_common(newsk);
87d11ceb
ACM
1911
1912 newsk->sk_dst_cache = NULL;
9b8805a3 1913 newsk->sk_dst_pending_confirm = 0;
87d11ceb
ACM
1914 newsk->sk_wmem_queued = 0;
1915 newsk->sk_forward_alloc = 0;
9caad864 1916 atomic_set(&newsk->sk_drops, 0);
87d11ceb 1917 newsk->sk_send_head = NULL;
87d11ceb 1918 newsk->sk_userlocks = sk->sk_userlocks & ~SOCK_BINDPORT_LOCK;
52267790 1919 atomic_set(&newsk->sk_zckey, 0);
87d11ceb
ACM
1920
1921 sock_reset_flag(newsk, SOCK_DONE);
d752a498
SB
1922
1923 /* sk->sk_memcg will be populated at accept() time */
1924 newsk->sk_memcg = NULL;
1925
c0576e39 1926 cgroup_sk_alloc(&newsk->sk_cgrp_data);
87d11ceb 1927
eefca20e
ED
1928 rcu_read_lock();
1929 filter = rcu_dereference(sk->sk_filter);
87d11ceb 1930 if (filter != NULL)
278571ba
AS
1931 /* though it's an empty new sock, the charging may fail
1932 * if sysctl_optmem_max was changed between creation of
1933 * original socket and cloning
1934 */
1935 is_charged = sk_filter_charge(newsk, filter);
eefca20e
ED
1936 RCU_INIT_POINTER(newsk->sk_filter, filter);
1937 rcu_read_unlock();
87d11ceb 1938
d188ba86 1939 if (unlikely(!is_charged || xfrm_sk_clone_policy(newsk, sk))) {
a97e50cc
DB
1940 /* We need to make sure that we don't uncharge the new
1941 * socket if we couldn't charge it in the first place
1942 * as otherwise we uncharge the parent's filter.
1943 */
1944 if (!is_charged)
1945 RCU_INIT_POINTER(newsk->sk_filter, NULL);
94352d45 1946 sk_free_unlock_clone(newsk);
87d11ceb
ACM
1947 newsk = NULL;
1948 goto out;
1949 }
fa463497 1950 RCU_INIT_POINTER(newsk->sk_reuseport_cb, NULL);
8f51dfc7
SF
1951
1952 if (bpf_sk_storage_clone(sk, newsk)) {
1953 sk_free_unlock_clone(newsk);
1954 newsk = NULL;
1955 goto out;
1956 }
87d11ceb 1957
f1ff5ce2
JS
1958 /* Clear sk_user_data if parent had the pointer tagged
1959 * as not suitable for copying when cloning.
1960 */
1961 if (sk_user_data_is_nocopy(newsk))
7a1ca972 1962 newsk->sk_user_data = NULL;
f1ff5ce2 1963
87d11ceb 1964 newsk->sk_err = 0;
e551c32d 1965 newsk->sk_err_soft = 0;
87d11ceb 1966 newsk->sk_priority = 0;
2c8c56e1 1967 newsk->sk_incoming_cpu = raw_smp_processor_id();
648845ab
TZ
1968 if (likely(newsk->sk_net_refcnt))
1969 sock_inuse_add(sock_net(newsk), 1);
d979a39d 1970
4dc6dc71
ED
1971 /*
1972 * Before updating sk_refcnt, we must commit prior changes to memory
1973 * (Documentation/RCU/rculist_nulls.txt for details)
1974 */
1975 smp_wmb();
41c6d650 1976 refcount_set(&newsk->sk_refcnt, 2);
87d11ceb
ACM
1977
1978 /*
1979 * Increment the counter in the same struct proto as the master
1980 * sock (sk_refcnt_debug_inc uses newsk->sk_prot->socks, that
1981 * is the same as sk->sk_prot->socks, as this field was copied
1982 * with memcpy).
1983 *
1984 * This _changes_ the previous behaviour, where
1985 * tcp_create_openreq_child always was incrementing the
1986 * equivalent to tcp_prot->socks (inet_sock_nr), so this have
1987 * to be taken into account in all callers. -acme
1988 */
1989 sk_refcnt_debug_inc(newsk);
972692e0 1990 sk_set_socket(newsk, NULL);
c2f26e8f 1991 RCU_INIT_POINTER(newsk->sk_wq, NULL);
87d11ceb
ACM
1992
1993 if (newsk->sk_prot->sockets_allocated)
180d8cd9 1994 sk_sockets_allocated_inc(newsk);
704da560 1995
080a270f
HFS
1996 if (sock_needs_netstamp(sk) &&
1997 newsk->sk_flags & SK_FLAGS_TIMESTAMP)
704da560 1998 net_enable_timestamp();
87d11ceb
ACM
1999 }
2000out:
2001 return newsk;
2002}
e56c57d0 2003EXPORT_SYMBOL_GPL(sk_clone_lock);
87d11ceb 2004
94352d45
ACM
2005void sk_free_unlock_clone(struct sock *sk)
2006{
2007 /* It is still raw copy of parent, so invalidate
2008 * destructor and make plain sk_free() */
2009 sk->sk_destruct = NULL;
2010 bh_unlock_sock(sk);
2011 sk_free(sk);
2012}
2013EXPORT_SYMBOL_GPL(sk_free_unlock_clone);
2014
9958089a
AK
2015void sk_setup_caps(struct sock *sk, struct dst_entry *dst)
2016{
d6a4e26a
ED
2017 u32 max_segs = 1;
2018
6bd4f355 2019 sk_dst_set(sk, dst);
0a6b2a1d 2020 sk->sk_route_caps = dst->dev->features | sk->sk_route_forced_caps;
9958089a 2021 if (sk->sk_route_caps & NETIF_F_GSO)
4fcd6b99 2022 sk->sk_route_caps |= NETIF_F_GSO_SOFTWARE;
a465419b 2023 sk->sk_route_caps &= ~sk->sk_route_nocaps;
9958089a 2024 if (sk_can_gso(sk)) {
f70f250a 2025 if (dst->header_len && !xfrm_dst_offload_ok(dst)) {
9958089a 2026 sk->sk_route_caps &= ~NETIF_F_GSO_MASK;
82cc1a7a 2027 } else {
9958089a 2028 sk->sk_route_caps |= NETIF_F_SG | NETIF_F_HW_CSUM;
82cc1a7a 2029 sk->sk_gso_max_size = dst->dev->gso_max_size;
d6a4e26a 2030 max_segs = max_t(u32, dst->dev->gso_max_segs, 1);
82cc1a7a 2031 }
9958089a 2032 }
d6a4e26a 2033 sk->sk_gso_max_segs = max_segs;
9958089a
AK
2034}
2035EXPORT_SYMBOL_GPL(sk_setup_caps);
2036
1da177e4
LT
2037/*
2038 * Simple resource managers for sockets.
2039 */
2040
2041
4ec93edb
YH
2042/*
2043 * Write buffer destructor automatically called from kfree_skb.
1da177e4
LT
2044 */
2045void sock_wfree(struct sk_buff *skb)
2046{
2047 struct sock *sk = skb->sk;
d99927f4 2048 unsigned int len = skb->truesize;
1da177e4 2049
d99927f4
ED
2050 if (!sock_flag(sk, SOCK_USE_WRITE_QUEUE)) {
2051 /*
2052 * Keep a reference on sk_wmem_alloc, this will be released
2053 * after sk_write_space() call
2054 */
14afee4b 2055 WARN_ON(refcount_sub_and_test(len - 1, &sk->sk_wmem_alloc));
1da177e4 2056 sk->sk_write_space(sk);
d99927f4
ED
2057 len = 1;
2058 }
2b85a34e 2059 /*
d99927f4
ED
2060 * if sk_wmem_alloc reaches 0, we must finish what sk_free()
2061 * could not do because of in-flight packets
2b85a34e 2062 */
14afee4b 2063 if (refcount_sub_and_test(len, &sk->sk_wmem_alloc))
2b85a34e 2064 __sk_free(sk);
1da177e4 2065}
2a91525c 2066EXPORT_SYMBOL(sock_wfree);
1da177e4 2067
1d2077ac
ED
2068/* This variant of sock_wfree() is used by TCP,
2069 * since it sets SOCK_USE_WRITE_QUEUE.
2070 */
2071void __sock_wfree(struct sk_buff *skb)
2072{
2073 struct sock *sk = skb->sk;
2074
14afee4b 2075 if (refcount_sub_and_test(skb->truesize, &sk->sk_wmem_alloc))
1d2077ac
ED
2076 __sk_free(sk);
2077}
2078
9e17f8a4
ED
2079void skb_set_owner_w(struct sk_buff *skb, struct sock *sk)
2080{
2081 skb_orphan(skb);
2082 skb->sk = sk;
2083#ifdef CONFIG_INET
2084 if (unlikely(!sk_fullsock(sk))) {
2085 skb->destructor = sock_edemux;
2086 sock_hold(sk);
2087 return;
2088 }
2089#endif
2090 skb->destructor = sock_wfree;
2091 skb_set_hash_from_sk(skb, sk);
2092 /*
2093 * We used to take a refcount on sk, but following operation
2094 * is enough to guarantee sk_free() wont free this sock until
2095 * all in-flight packets are completed
2096 */
14afee4b 2097 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
9e17f8a4
ED
2098}
2099EXPORT_SYMBOL(skb_set_owner_w);
2100
41477662
JK
2101static bool can_skb_orphan_partial(const struct sk_buff *skb)
2102{
2103#ifdef CONFIG_TLS_DEVICE
2104 /* Drivers depend on in-order delivery for crypto offload,
2105 * partial orphan breaks out-of-order-OK logic.
2106 */
2107 if (skb->decrypted)
2108 return false;
2109#endif
2110 return (skb->destructor == sock_wfree ||
2111 (IS_ENABLED(CONFIG_INET) && skb->destructor == tcp_wfree));
2112}
2113
1d2077ac
ED
2114/* This helper is used by netem, as it can hold packets in its
2115 * delay queue. We want to allow the owner socket to send more
2116 * packets, as if they were already TX completed by a typical driver.
2117 * But we also want to keep skb->sk set because some packet schedulers
f6ba8d33 2118 * rely on it (sch_fq for example).
1d2077ac 2119 */
f2f872f9
ED
2120void skb_orphan_partial(struct sk_buff *skb)
2121{
f6ba8d33 2122 if (skb_is_tcp_pure_ack(skb))
1d2077ac
ED
2123 return;
2124
41477662 2125 if (can_skb_orphan_partial(skb)) {
f6ba8d33
ED
2126 struct sock *sk = skb->sk;
2127
41c6d650 2128 if (refcount_inc_not_zero(&sk->sk_refcnt)) {
14afee4b 2129 WARN_ON(refcount_sub_and_test(skb->truesize, &sk->sk_wmem_alloc));
f6ba8d33
ED
2130 skb->destructor = sock_efree;
2131 }
f2f872f9
ED
2132 } else {
2133 skb_orphan(skb);
2134 }
2135}
2136EXPORT_SYMBOL(skb_orphan_partial);
2137
4ec93edb
YH
2138/*
2139 * Read buffer destructor automatically called from kfree_skb.
1da177e4
LT
2140 */
2141void sock_rfree(struct sk_buff *skb)
2142{
2143 struct sock *sk = skb->sk;
d361fd59 2144 unsigned int len = skb->truesize;
1da177e4 2145
d361fd59
ED
2146 atomic_sub(len, &sk->sk_rmem_alloc);
2147 sk_mem_uncharge(sk, len);
1da177e4 2148}
2a91525c 2149EXPORT_SYMBOL(sock_rfree);
1da177e4 2150
7768eed8
OH
2151/*
2152 * Buffer destructor for skbs that are not used directly in read or write
2153 * path, e.g. for error handler skbs. Automatically called from kfree_skb.
2154 */
62bccb8c
AD
2155void sock_efree(struct sk_buff *skb)
2156{
2157 sock_put(skb->sk);
2158}
2159EXPORT_SYMBOL(sock_efree);
2160
cf7fbe66
JS
2161/* Buffer destructor for prefetch/receive path where reference count may
2162 * not be held, e.g. for listen sockets.
2163 */
2164#ifdef CONFIG_INET
2165void sock_pfree(struct sk_buff *skb)
2166{
7ae215d2
JS
2167 if (sk_is_refcounted(skb->sk))
2168 sock_gen_put(skb->sk);
cf7fbe66
JS
2169}
2170EXPORT_SYMBOL(sock_pfree);
2171#endif /* CONFIG_INET */
2172
976d0201 2173kuid_t sock_i_uid(struct sock *sk)
1da177e4 2174{
976d0201 2175 kuid_t uid;
1da177e4 2176
f064af1e 2177 read_lock_bh(&sk->sk_callback_lock);
976d0201 2178 uid = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_uid : GLOBAL_ROOT_UID;
f064af1e 2179 read_unlock_bh(&sk->sk_callback_lock);
1da177e4
LT
2180 return uid;
2181}
2a91525c 2182EXPORT_SYMBOL(sock_i_uid);
1da177e4
LT
2183
2184unsigned long sock_i_ino(struct sock *sk)
2185{
2186 unsigned long ino;
2187
f064af1e 2188 read_lock_bh(&sk->sk_callback_lock);
1da177e4 2189 ino = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_ino : 0;
f064af1e 2190 read_unlock_bh(&sk->sk_callback_lock);
1da177e4
LT
2191 return ino;
2192}
2a91525c 2193EXPORT_SYMBOL(sock_i_ino);
1da177e4
LT
2194
2195/*
2196 * Allocate a skb from the socket's send buffer.
2197 */
86a76caf 2198struct sk_buff *sock_wmalloc(struct sock *sk, unsigned long size, int force,
dd0fc66f 2199 gfp_t priority)
1da177e4 2200{
e292f05e
ED
2201 if (force ||
2202 refcount_read(&sk->sk_wmem_alloc) < READ_ONCE(sk->sk_sndbuf)) {
2a91525c 2203 struct sk_buff *skb = alloc_skb(size, priority);
e292f05e 2204
1da177e4
LT
2205 if (skb) {
2206 skb_set_owner_w(skb, sk);
2207 return skb;
2208 }
2209 }
2210 return NULL;
2211}
2a91525c 2212EXPORT_SYMBOL(sock_wmalloc);
1da177e4 2213
98ba0bd5
WB
2214static void sock_ofree(struct sk_buff *skb)
2215{
2216 struct sock *sk = skb->sk;
2217
2218 atomic_sub(skb->truesize, &sk->sk_omem_alloc);
2219}
2220
2221struct sk_buff *sock_omalloc(struct sock *sk, unsigned long size,
2222 gfp_t priority)
2223{
2224 struct sk_buff *skb;
2225
2226 /* small safe race: SKB_TRUESIZE may differ from final skb->truesize */
2227 if (atomic_read(&sk->sk_omem_alloc) + SKB_TRUESIZE(size) >
2228 sysctl_optmem_max)
2229 return NULL;
2230
2231 skb = alloc_skb(size, priority);
2232 if (!skb)
2233 return NULL;
2234
2235 atomic_add(skb->truesize, &sk->sk_omem_alloc);
2236 skb->sk = sk;
2237 skb->destructor = sock_ofree;
2238 return skb;
2239}
2240
4ec93edb 2241/*
1da177e4 2242 * Allocate a memory block from the socket's option memory buffer.
4ec93edb 2243 */
dd0fc66f 2244void *sock_kmalloc(struct sock *sk, int size, gfp_t priority)
1da177e4 2245{
95c96174 2246 if ((unsigned int)size <= sysctl_optmem_max &&
1da177e4
LT
2247 atomic_read(&sk->sk_omem_alloc) + size < sysctl_optmem_max) {
2248 void *mem;
2249 /* First do the add, to avoid the race if kmalloc
4ec93edb 2250 * might sleep.
1da177e4
LT
2251 */
2252 atomic_add(size, &sk->sk_omem_alloc);
2253 mem = kmalloc(size, priority);
2254 if (mem)
2255 return mem;
2256 atomic_sub(size, &sk->sk_omem_alloc);
2257 }
2258 return NULL;
2259}
2a91525c 2260EXPORT_SYMBOL(sock_kmalloc);
1da177e4 2261
79e88659
DB
2262/* Free an option memory block. Note, we actually want the inline
2263 * here as this allows gcc to detect the nullify and fold away the
2264 * condition entirely.
1da177e4 2265 */
79e88659
DB
2266static inline void __sock_kfree_s(struct sock *sk, void *mem, int size,
2267 const bool nullify)
1da177e4 2268{
e53da5fb
DM
2269 if (WARN_ON_ONCE(!mem))
2270 return;
79e88659
DB
2271 if (nullify)
2272 kzfree(mem);
2273 else
2274 kfree(mem);
1da177e4
LT
2275 atomic_sub(size, &sk->sk_omem_alloc);
2276}
79e88659
DB
2277
2278void sock_kfree_s(struct sock *sk, void *mem, int size)
2279{
2280 __sock_kfree_s(sk, mem, size, false);
2281}
2a91525c 2282EXPORT_SYMBOL(sock_kfree_s);
1da177e4 2283
79e88659
DB
2284void sock_kzfree_s(struct sock *sk, void *mem, int size)
2285{
2286 __sock_kfree_s(sk, mem, size, true);
2287}
2288EXPORT_SYMBOL(sock_kzfree_s);
2289
1da177e4
LT
2290/* It is almost wait_for_tcp_memory minus release_sock/lock_sock.
2291 I think, these locks should be removed for datagram sockets.
2292 */
2a91525c 2293static long sock_wait_for_wmem(struct sock *sk, long timeo)
1da177e4
LT
2294{
2295 DEFINE_WAIT(wait);
2296
9cd3e072 2297 sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
1da177e4
LT
2298 for (;;) {
2299 if (!timeo)
2300 break;
2301 if (signal_pending(current))
2302 break;
2303 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
aa395145 2304 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
e292f05e 2305 if (refcount_read(&sk->sk_wmem_alloc) < READ_ONCE(sk->sk_sndbuf))
1da177e4
LT
2306 break;
2307 if (sk->sk_shutdown & SEND_SHUTDOWN)
2308 break;
2309 if (sk->sk_err)
2310 break;
2311 timeo = schedule_timeout(timeo);
2312 }
aa395145 2313 finish_wait(sk_sleep(sk), &wait);
1da177e4
LT
2314 return timeo;
2315}
2316
2317
2318/*
2319 * Generic send/receive buffer handlers
2320 */
2321
4cc7f68d
HX
2322struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
2323 unsigned long data_len, int noblock,
28d64271 2324 int *errcode, int max_page_order)
1da177e4 2325{
2e4e4410 2326 struct sk_buff *skb;
1da177e4
LT
2327 long timeo;
2328 int err;
2329
1da177e4 2330 timeo = sock_sndtimeo(sk, noblock);
2e4e4410 2331 for (;;) {
1da177e4
LT
2332 err = sock_error(sk);
2333 if (err != 0)
2334 goto failure;
2335
2336 err = -EPIPE;
2337 if (sk->sk_shutdown & SEND_SHUTDOWN)
2338 goto failure;
2339
e292f05e 2340 if (sk_wmem_alloc_get(sk) < READ_ONCE(sk->sk_sndbuf))
2e4e4410 2341 break;
28d64271 2342
9cd3e072 2343 sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
2e4e4410
ED
2344 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
2345 err = -EAGAIN;
2346 if (!timeo)
1da177e4 2347 goto failure;
2e4e4410
ED
2348 if (signal_pending(current))
2349 goto interrupted;
2350 timeo = sock_wait_for_wmem(sk, timeo);
1da177e4 2351 }
2e4e4410
ED
2352 skb = alloc_skb_with_frags(header_len, data_len, max_page_order,
2353 errcode, sk->sk_allocation);
2354 if (skb)
2355 skb_set_owner_w(skb, sk);
1da177e4
LT
2356 return skb;
2357
2358interrupted:
2359 err = sock_intr_errno(timeo);
2360failure:
2361 *errcode = err;
2362 return NULL;
2363}
4cc7f68d 2364EXPORT_SYMBOL(sock_alloc_send_pskb);
1da177e4 2365
4ec93edb 2366struct sk_buff *sock_alloc_send_skb(struct sock *sk, unsigned long size,
1da177e4
LT
2367 int noblock, int *errcode)
2368{
28d64271 2369 return sock_alloc_send_pskb(sk, size, 0, noblock, errcode, 0);
1da177e4 2370}
2a91525c 2371EXPORT_SYMBOL(sock_alloc_send_skb);
1da177e4 2372
39771b12
WB
2373int __sock_cmsg_send(struct sock *sk, struct msghdr *msg, struct cmsghdr *cmsg,
2374 struct sockcm_cookie *sockc)
2375{
3dd17e63
SHY
2376 u32 tsflags;
2377
39771b12
WB
2378 switch (cmsg->cmsg_type) {
2379 case SO_MARK:
2380 if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
2381 return -EPERM;
2382 if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32)))
2383 return -EINVAL;
2384 sockc->mark = *(u32 *)CMSG_DATA(cmsg);
2385 break;
7f1bc6e9 2386 case SO_TIMESTAMPING_OLD:
3dd17e63
SHY
2387 if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32)))
2388 return -EINVAL;
2389
2390 tsflags = *(u32 *)CMSG_DATA(cmsg);
2391 if (tsflags & ~SOF_TIMESTAMPING_TX_RECORD_MASK)
2392 return -EINVAL;
2393
2394 sockc->tsflags &= ~SOF_TIMESTAMPING_TX_RECORD_MASK;
2395 sockc->tsflags |= tsflags;
2396 break;
80b14dee
RC
2397 case SCM_TXTIME:
2398 if (!sock_flag(sk, SOCK_TXTIME))
2399 return -EINVAL;
2400 if (cmsg->cmsg_len != CMSG_LEN(sizeof(u64)))
2401 return -EINVAL;
2402 sockc->transmit_time = get_unaligned((u64 *)CMSG_DATA(cmsg));
2403 break;
779f1ede
SHY
2404 /* SCM_RIGHTS and SCM_CREDENTIALS are semantically in SOL_UNIX. */
2405 case SCM_RIGHTS:
2406 case SCM_CREDENTIALS:
2407 break;
39771b12
WB
2408 default:
2409 return -EINVAL;
2410 }
2411 return 0;
2412}
2413EXPORT_SYMBOL(__sock_cmsg_send);
2414
f28ea365
EJ
2415int sock_cmsg_send(struct sock *sk, struct msghdr *msg,
2416 struct sockcm_cookie *sockc)
2417{
2418 struct cmsghdr *cmsg;
39771b12 2419 int ret;
f28ea365
EJ
2420
2421 for_each_cmsghdr(cmsg, msg) {
2422 if (!CMSG_OK(msg, cmsg))
2423 return -EINVAL;
2424 if (cmsg->cmsg_level != SOL_SOCKET)
2425 continue;
39771b12
WB
2426 ret = __sock_cmsg_send(sk, msg, cmsg, sockc);
2427 if (ret)
2428 return ret;
f28ea365
EJ
2429 }
2430 return 0;
2431}
2432EXPORT_SYMBOL(sock_cmsg_send);
2433
06044751
ED
2434static void sk_enter_memory_pressure(struct sock *sk)
2435{
2436 if (!sk->sk_prot->enter_memory_pressure)
2437 return;
2438
2439 sk->sk_prot->enter_memory_pressure(sk);
2440}
2441
2442static void sk_leave_memory_pressure(struct sock *sk)
2443{
2444 if (sk->sk_prot->leave_memory_pressure) {
2445 sk->sk_prot->leave_memory_pressure(sk);
2446 } else {
2447 unsigned long *memory_pressure = sk->sk_prot->memory_pressure;
2448
503978ac
ED
2449 if (memory_pressure && READ_ONCE(*memory_pressure))
2450 WRITE_ONCE(*memory_pressure, 0);
06044751
ED
2451 }
2452}
2453
5640f768 2454#define SKB_FRAG_PAGE_ORDER get_order(32768)
ce27ec60 2455DEFINE_STATIC_KEY_FALSE(net_high_order_alloc_disable_key);
5640f768 2456
400dfd3a
ED
2457/**
2458 * skb_page_frag_refill - check that a page_frag contains enough room
2459 * @sz: minimum size of the fragment we want to get
2460 * @pfrag: pointer to page_frag
82d5e2b8 2461 * @gfp: priority for memory allocation
400dfd3a
ED
2462 *
2463 * Note: While this allocator tries to use high order pages, there is
2464 * no guarantee that allocations succeed. Therefore, @sz MUST be
2465 * less or equal than PAGE_SIZE.
2466 */
d9b2938a 2467bool skb_page_frag_refill(unsigned int sz, struct page_frag *pfrag, gfp_t gfp)
5640f768 2468{
5640f768 2469 if (pfrag->page) {
fe896d18 2470 if (page_ref_count(pfrag->page) == 1) {
5640f768
ED
2471 pfrag->offset = 0;
2472 return true;
2473 }
400dfd3a 2474 if (pfrag->offset + sz <= pfrag->size)
5640f768
ED
2475 return true;
2476 put_page(pfrag->page);
2477 }
2478
d9b2938a 2479 pfrag->offset = 0;
ce27ec60
ED
2480 if (SKB_FRAG_PAGE_ORDER &&
2481 !static_branch_unlikely(&net_high_order_alloc_disable_key)) {
d0164adc
MG
2482 /* Avoid direct reclaim but allow kswapd to wake */
2483 pfrag->page = alloc_pages((gfp & ~__GFP_DIRECT_RECLAIM) |
2484 __GFP_COMP | __GFP_NOWARN |
2485 __GFP_NORETRY,
d9b2938a 2486 SKB_FRAG_PAGE_ORDER);
5640f768 2487 if (likely(pfrag->page)) {
d9b2938a 2488 pfrag->size = PAGE_SIZE << SKB_FRAG_PAGE_ORDER;
5640f768
ED
2489 return true;
2490 }
d9b2938a
ED
2491 }
2492 pfrag->page = alloc_page(gfp);
2493 if (likely(pfrag->page)) {
2494 pfrag->size = PAGE_SIZE;
2495 return true;
2496 }
400dfd3a
ED
2497 return false;
2498}
2499EXPORT_SYMBOL(skb_page_frag_refill);
2500
2501bool sk_page_frag_refill(struct sock *sk, struct page_frag *pfrag)
2502{
2503 if (likely(skb_page_frag_refill(32U, pfrag, sk->sk_allocation)))
2504 return true;
2505
5640f768
ED
2506 sk_enter_memory_pressure(sk);
2507 sk_stream_moderate_sndbuf(sk);
2508 return false;
2509}
2510EXPORT_SYMBOL(sk_page_frag_refill);
2511
1da177e4 2512static void __lock_sock(struct sock *sk)
f39234d6
NK
2513 __releases(&sk->sk_lock.slock)
2514 __acquires(&sk->sk_lock.slock)
1da177e4
LT
2515{
2516 DEFINE_WAIT(wait);
2517
e71a4783 2518 for (;;) {
1da177e4
LT
2519 prepare_to_wait_exclusive(&sk->sk_lock.wq, &wait,
2520 TASK_UNINTERRUPTIBLE);
2521 spin_unlock_bh(&sk->sk_lock.slock);
2522 schedule();
2523 spin_lock_bh(&sk->sk_lock.slock);
e71a4783 2524 if (!sock_owned_by_user(sk))
1da177e4
LT
2525 break;
2526 }
2527 finish_wait(&sk->sk_lock.wq, &wait);
2528}
2529
8873c064 2530void __release_sock(struct sock *sk)
f39234d6
NK
2531 __releases(&sk->sk_lock.slock)
2532 __acquires(&sk->sk_lock.slock)
1da177e4 2533{
5413d1ba 2534 struct sk_buff *skb, *next;
1da177e4 2535
5413d1ba 2536 while ((skb = sk->sk_backlog.head) != NULL) {
1da177e4 2537 sk->sk_backlog.head = sk->sk_backlog.tail = NULL;
1da177e4 2538
5413d1ba 2539 spin_unlock_bh(&sk->sk_lock.slock);
1da177e4 2540
5413d1ba
ED
2541 do {
2542 next = skb->next;
e4cbb02a 2543 prefetch(next);
7fee226a 2544 WARN_ON_ONCE(skb_dst_is_noref(skb));
a8305bff 2545 skb_mark_not_on_list(skb);
c57943a1 2546 sk_backlog_rcv(sk, skb);
1da177e4 2547
5413d1ba 2548 cond_resched();
1da177e4
LT
2549
2550 skb = next;
2551 } while (skb != NULL);
2552
5413d1ba
ED
2553 spin_lock_bh(&sk->sk_lock.slock);
2554 }
8eae939f
ZY
2555
2556 /*
2557 * Doing the zeroing here guarantee we can not loop forever
2558 * while a wild producer attempts to flood us.
2559 */
2560 sk->sk_backlog.len = 0;
1da177e4
LT
2561}
2562
d41a69f1
ED
2563void __sk_flush_backlog(struct sock *sk)
2564{
2565 spin_lock_bh(&sk->sk_lock.slock);
2566 __release_sock(sk);
2567 spin_unlock_bh(&sk->sk_lock.slock);
2568}
2569
1da177e4
LT
2570/**
2571 * sk_wait_data - wait for data to arrive at sk_receive_queue
4dc3b16b
PP
2572 * @sk: sock to wait on
2573 * @timeo: for how long
dfbafc99 2574 * @skb: last skb seen on sk_receive_queue
1da177e4
LT
2575 *
2576 * Now socket state including sk->sk_err is changed only under lock,
2577 * hence we may omit checks after joining wait queue.
2578 * We check receive queue before schedule() only as optimization;
2579 * it is very likely that release_sock() added new data.
2580 */
dfbafc99 2581int sk_wait_data(struct sock *sk, long *timeo, const struct sk_buff *skb)
1da177e4 2582{
d9dc8b0f 2583 DEFINE_WAIT_FUNC(wait, woken_wake_function);
1da177e4 2584 int rc;
1da177e4 2585
d9dc8b0f 2586 add_wait_queue(sk_sleep(sk), &wait);
9cd3e072 2587 sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
d9dc8b0f 2588 rc = sk_wait_event(sk, timeo, skb_peek_tail(&sk->sk_receive_queue) != skb, &wait);
9cd3e072 2589 sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
d9dc8b0f 2590 remove_wait_queue(sk_sleep(sk), &wait);
1da177e4
LT
2591 return rc;
2592}
1da177e4
LT
2593EXPORT_SYMBOL(sk_wait_data);
2594
3ab224be 2595/**
f8c3bf00 2596 * __sk_mem_raise_allocated - increase memory_allocated
3ab224be
HA
2597 * @sk: socket
2598 * @size: memory size to allocate
f8c3bf00 2599 * @amt: pages to allocate
3ab224be
HA
2600 * @kind: allocation type
2601 *
f8c3bf00 2602 * Similar to __sk_mem_schedule(), but does not update sk_forward_alloc
3ab224be 2603 */
f8c3bf00 2604int __sk_mem_raise_allocated(struct sock *sk, int size, int amt, int kind)
3ab224be
HA
2605{
2606 struct proto *prot = sk->sk_prot;
f8c3bf00 2607 long allocated = sk_memory_allocated_add(sk, amt);
d6f19938 2608 bool charged = true;
e805605c 2609
baac50bb 2610 if (mem_cgroup_sockets_enabled && sk->sk_memcg &&
d6f19938 2611 !(charged = mem_cgroup_charge_skmem(sk->sk_memcg, amt)))
e805605c 2612 goto suppress_allocation;
3ab224be
HA
2613
2614 /* Under limit. */
e805605c 2615 if (allocated <= sk_prot_mem_limits(sk, 0)) {
180d8cd9 2616 sk_leave_memory_pressure(sk);
3ab224be
HA
2617 return 1;
2618 }
2619
e805605c
JW
2620 /* Under pressure. */
2621 if (allocated > sk_prot_mem_limits(sk, 1))
180d8cd9 2622 sk_enter_memory_pressure(sk);
3ab224be 2623
e805605c
JW
2624 /* Over hard limit. */
2625 if (allocated > sk_prot_mem_limits(sk, 2))
3ab224be
HA
2626 goto suppress_allocation;
2627
2628 /* guarantee minimum buffer size under pressure */
2629 if (kind == SK_MEM_RECV) {
a3dcaf17 2630 if (atomic_read(&sk->sk_rmem_alloc) < sk_get_rmem0(sk, prot))
3ab224be 2631 return 1;
180d8cd9 2632
3ab224be 2633 } else { /* SK_MEM_SEND */
a3dcaf17
ED
2634 int wmem0 = sk_get_wmem0(sk, prot);
2635
3ab224be 2636 if (sk->sk_type == SOCK_STREAM) {
a3dcaf17 2637 if (sk->sk_wmem_queued < wmem0)
3ab224be 2638 return 1;
a3dcaf17 2639 } else if (refcount_read(&sk->sk_wmem_alloc) < wmem0) {
3ab224be 2640 return 1;
a3dcaf17 2641 }
3ab224be
HA
2642 }
2643
180d8cd9 2644 if (sk_has_memory_pressure(sk)) {
5bf325a5 2645 u64 alloc;
1748376b 2646
180d8cd9 2647 if (!sk_under_memory_pressure(sk))
1748376b 2648 return 1;
180d8cd9
GC
2649 alloc = sk_sockets_allocated_read_positive(sk);
2650 if (sk_prot_mem_limits(sk, 2) > alloc *
3ab224be
HA
2651 sk_mem_pages(sk->sk_wmem_queued +
2652 atomic_read(&sk->sk_rmem_alloc) +
2653 sk->sk_forward_alloc))
2654 return 1;
2655 }
2656
2657suppress_allocation:
2658
2659 if (kind == SK_MEM_SEND && sk->sk_type == SOCK_STREAM) {
2660 sk_stream_moderate_sndbuf(sk);
2661
2662 /* Fail only if socket is _under_ its sndbuf.
2663 * In this case we cannot block, so that we have to fail.
2664 */
2665 if (sk->sk_wmem_queued + size >= sk->sk_sndbuf)
2666 return 1;
2667 }
2668
d6f19938
YS
2669 if (kind == SK_MEM_SEND || (kind == SK_MEM_RECV && charged))
2670 trace_sock_exceed_buf_limit(sk, prot, allocated, kind);
3847ce32 2671
0e90b31f 2672 sk_memory_allocated_sub(sk, amt);
180d8cd9 2673
baac50bb
JW
2674 if (mem_cgroup_sockets_enabled && sk->sk_memcg)
2675 mem_cgroup_uncharge_skmem(sk->sk_memcg, amt);
e805605c 2676
3ab224be
HA
2677 return 0;
2678}
f8c3bf00
PA
2679EXPORT_SYMBOL(__sk_mem_raise_allocated);
2680
2681/**
2682 * __sk_mem_schedule - increase sk_forward_alloc and memory_allocated
2683 * @sk: socket
2684 * @size: memory size to allocate
2685 * @kind: allocation type
2686 *
2687 * If kind is SK_MEM_SEND, it means wmem allocation. Otherwise it means
2688 * rmem allocation. This function assumes that protocols which have
2689 * memory_pressure use sk_wmem_queued as write buffer accounting.
2690 */
2691int __sk_mem_schedule(struct sock *sk, int size, int kind)
2692{
2693 int ret, amt = sk_mem_pages(size);
2694
2695 sk->sk_forward_alloc += amt << SK_MEM_QUANTUM_SHIFT;
2696 ret = __sk_mem_raise_allocated(sk, size, amt, kind);
2697 if (!ret)
2698 sk->sk_forward_alloc -= amt << SK_MEM_QUANTUM_SHIFT;
2699 return ret;
2700}
3ab224be
HA
2701EXPORT_SYMBOL(__sk_mem_schedule);
2702
2703/**
f8c3bf00 2704 * __sk_mem_reduce_allocated - reclaim memory_allocated
3ab224be 2705 * @sk: socket
f8c3bf00
PA
2706 * @amount: number of quanta
2707 *
2708 * Similar to __sk_mem_reclaim(), but does not update sk_forward_alloc
3ab224be 2709 */
f8c3bf00 2710void __sk_mem_reduce_allocated(struct sock *sk, int amount)
3ab224be 2711{
1a24e04e 2712 sk_memory_allocated_sub(sk, amount);
3ab224be 2713
baac50bb
JW
2714 if (mem_cgroup_sockets_enabled && sk->sk_memcg)
2715 mem_cgroup_uncharge_skmem(sk->sk_memcg, amount);
e805605c 2716
180d8cd9
GC
2717 if (sk_under_memory_pressure(sk) &&
2718 (sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0)))
2719 sk_leave_memory_pressure(sk);
3ab224be 2720}
f8c3bf00
PA
2721EXPORT_SYMBOL(__sk_mem_reduce_allocated);
2722
2723/**
2724 * __sk_mem_reclaim - reclaim sk_forward_alloc and memory_allocated
2725 * @sk: socket
2726 * @amount: number of bytes (rounded down to a SK_MEM_QUANTUM multiple)
2727 */
2728void __sk_mem_reclaim(struct sock *sk, int amount)
2729{
2730 amount >>= SK_MEM_QUANTUM_SHIFT;
2731 sk->sk_forward_alloc -= amount << SK_MEM_QUANTUM_SHIFT;
2732 __sk_mem_reduce_allocated(sk, amount);
2733}
3ab224be
HA
2734EXPORT_SYMBOL(__sk_mem_reclaim);
2735
627d2d6b 2736int sk_set_peek_off(struct sock *sk, int val)
2737{
627d2d6b 2738 sk->sk_peek_off = val;
2739 return 0;
2740}
2741EXPORT_SYMBOL_GPL(sk_set_peek_off);
3ab224be 2742
1da177e4
LT
2743/*
2744 * Set of default routines for initialising struct proto_ops when
2745 * the protocol does not support a particular function. In certain
2746 * cases where it makes no sense for a protocol to have a "do nothing"
2747 * function, some default processing is provided.
2748 */
2749
2750int sock_no_bind(struct socket *sock, struct sockaddr *saddr, int len)
2751{
2752 return -EOPNOTSUPP;
2753}
2a91525c 2754EXPORT_SYMBOL(sock_no_bind);
1da177e4 2755
4ec93edb 2756int sock_no_connect(struct socket *sock, struct sockaddr *saddr,
1da177e4
LT
2757 int len, int flags)
2758{
2759 return -EOPNOTSUPP;
2760}
2a91525c 2761EXPORT_SYMBOL(sock_no_connect);
1da177e4
LT
2762
2763int sock_no_socketpair(struct socket *sock1, struct socket *sock2)
2764{
2765 return -EOPNOTSUPP;
2766}
2a91525c 2767EXPORT_SYMBOL(sock_no_socketpair);
1da177e4 2768
cdfbabfb
DH
2769int sock_no_accept(struct socket *sock, struct socket *newsock, int flags,
2770 bool kern)
1da177e4
LT
2771{
2772 return -EOPNOTSUPP;
2773}
2a91525c 2774EXPORT_SYMBOL(sock_no_accept);
1da177e4 2775
4ec93edb 2776int sock_no_getname(struct socket *sock, struct sockaddr *saddr,
9b2c45d4 2777 int peer)
1da177e4
LT
2778{
2779 return -EOPNOTSUPP;
2780}
2a91525c 2781EXPORT_SYMBOL(sock_no_getname);
1da177e4 2782
1da177e4
LT
2783int sock_no_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
2784{
2785 return -EOPNOTSUPP;
2786}
2a91525c 2787EXPORT_SYMBOL(sock_no_ioctl);
1da177e4
LT
2788
2789int sock_no_listen(struct socket *sock, int backlog)
2790{
2791 return -EOPNOTSUPP;
2792}
2a91525c 2793EXPORT_SYMBOL(sock_no_listen);
1da177e4
LT
2794
2795int sock_no_shutdown(struct socket *sock, int how)
2796{
2797 return -EOPNOTSUPP;
2798}
2a91525c 2799EXPORT_SYMBOL(sock_no_shutdown);
1da177e4
LT
2800
2801int sock_no_setsockopt(struct socket *sock, int level, int optname,
b7058842 2802 char __user *optval, unsigned int optlen)
1da177e4
LT
2803{
2804 return -EOPNOTSUPP;
2805}
2a91525c 2806EXPORT_SYMBOL(sock_no_setsockopt);
1da177e4
LT
2807
2808int sock_no_getsockopt(struct socket *sock, int level, int optname,
2809 char __user *optval, int __user *optlen)
2810{
2811 return -EOPNOTSUPP;
2812}
2a91525c 2813EXPORT_SYMBOL(sock_no_getsockopt);
1da177e4 2814
1b784140 2815int sock_no_sendmsg(struct socket *sock, struct msghdr *m, size_t len)
1da177e4
LT
2816{
2817 return -EOPNOTSUPP;
2818}
2a91525c 2819EXPORT_SYMBOL(sock_no_sendmsg);
1da177e4 2820
306b13eb
TH
2821int sock_no_sendmsg_locked(struct sock *sk, struct msghdr *m, size_t len)
2822{
2823 return -EOPNOTSUPP;
2824}
2825EXPORT_SYMBOL(sock_no_sendmsg_locked);
2826
1b784140
YX
2827int sock_no_recvmsg(struct socket *sock, struct msghdr *m, size_t len,
2828 int flags)
1da177e4
LT
2829{
2830 return -EOPNOTSUPP;
2831}
2a91525c 2832EXPORT_SYMBOL(sock_no_recvmsg);
1da177e4
LT
2833
2834int sock_no_mmap(struct file *file, struct socket *sock, struct vm_area_struct *vma)
2835{
2836 /* Mirror missing mmap method error code */
2837 return -ENODEV;
2838}
2a91525c 2839EXPORT_SYMBOL(sock_no_mmap);
1da177e4
LT
2840
2841ssize_t sock_no_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags)
2842{
2843 ssize_t res;
2844 struct msghdr msg = {.msg_flags = flags};
2845 struct kvec iov;
2846 char *kaddr = kmap(page);
2847 iov.iov_base = kaddr + offset;
2848 iov.iov_len = size;
2849 res = kernel_sendmsg(sock, &msg, &iov, 1, size);
2850 kunmap(page);
2851 return res;
2852}
2a91525c 2853EXPORT_SYMBOL(sock_no_sendpage);
1da177e4 2854
306b13eb
TH
2855ssize_t sock_no_sendpage_locked(struct sock *sk, struct page *page,
2856 int offset, size_t size, int flags)
2857{
2858 ssize_t res;
2859 struct msghdr msg = {.msg_flags = flags};
2860 struct kvec iov;
2861 char *kaddr = kmap(page);
2862
2863 iov.iov_base = kaddr + offset;
2864 iov.iov_len = size;
2865 res = kernel_sendmsg_locked(sk, &msg, &iov, 1, size);
2866 kunmap(page);
2867 return res;
2868}
2869EXPORT_SYMBOL(sock_no_sendpage_locked);
2870
1da177e4
LT
2871/*
2872 * Default Socket Callbacks
2873 */
2874
2875static void sock_def_wakeup(struct sock *sk)
2876{
43815482
ED
2877 struct socket_wq *wq;
2878
2879 rcu_read_lock();
2880 wq = rcu_dereference(sk->sk_wq);
1ce0bf50 2881 if (skwq_has_sleeper(wq))
43815482
ED
2882 wake_up_interruptible_all(&wq->wait);
2883 rcu_read_unlock();
1da177e4
LT
2884}
2885
2886static void sock_def_error_report(struct sock *sk)
2887{
43815482
ED
2888 struct socket_wq *wq;
2889
2890 rcu_read_lock();
2891 wq = rcu_dereference(sk->sk_wq);
1ce0bf50 2892 if (skwq_has_sleeper(wq))
a9a08845 2893 wake_up_interruptible_poll(&wq->wait, EPOLLERR);
8d8ad9d7 2894 sk_wake_async(sk, SOCK_WAKE_IO, POLL_ERR);
43815482 2895 rcu_read_unlock();
1da177e4
LT
2896}
2897
43a825af 2898void sock_def_readable(struct sock *sk)
1da177e4 2899{
43815482
ED
2900 struct socket_wq *wq;
2901
2902 rcu_read_lock();
2903 wq = rcu_dereference(sk->sk_wq);
1ce0bf50 2904 if (skwq_has_sleeper(wq))
a9a08845
LT
2905 wake_up_interruptible_sync_poll(&wq->wait, EPOLLIN | EPOLLPRI |
2906 EPOLLRDNORM | EPOLLRDBAND);
8d8ad9d7 2907 sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
43815482 2908 rcu_read_unlock();
1da177e4
LT
2909}
2910
2911static void sock_def_write_space(struct sock *sk)
2912{
43815482
ED
2913 struct socket_wq *wq;
2914
2915 rcu_read_lock();
1da177e4
LT
2916
2917 /* Do not wake up a writer until he can make "significant"
2918 * progress. --DaveM
2919 */
e292f05e 2920 if ((refcount_read(&sk->sk_wmem_alloc) << 1) <= READ_ONCE(sk->sk_sndbuf)) {
43815482 2921 wq = rcu_dereference(sk->sk_wq);
1ce0bf50 2922 if (skwq_has_sleeper(wq))
a9a08845
LT
2923 wake_up_interruptible_sync_poll(&wq->wait, EPOLLOUT |
2924 EPOLLWRNORM | EPOLLWRBAND);
1da177e4
LT
2925
2926 /* Should agree with poll, otherwise some programs break */
2927 if (sock_writeable(sk))
8d8ad9d7 2928 sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
1da177e4
LT
2929 }
2930
43815482 2931 rcu_read_unlock();
1da177e4
LT
2932}
2933
2934static void sock_def_destruct(struct sock *sk)
2935{
1da177e4
LT
2936}
2937
2938void sk_send_sigurg(struct sock *sk)
2939{
2940 if (sk->sk_socket && sk->sk_socket->file)
2941 if (send_sigurg(&sk->sk_socket->file->f_owner))
8d8ad9d7 2942 sk_wake_async(sk, SOCK_WAKE_URG, POLL_PRI);
1da177e4 2943}
2a91525c 2944EXPORT_SYMBOL(sk_send_sigurg);
1da177e4
LT
2945
2946void sk_reset_timer(struct sock *sk, struct timer_list* timer,
2947 unsigned long expires)
2948{
2949 if (!mod_timer(timer, expires))
2950 sock_hold(sk);
2951}
1da177e4
LT
2952EXPORT_SYMBOL(sk_reset_timer);
2953
2954void sk_stop_timer(struct sock *sk, struct timer_list* timer)
2955{
25cc4ae9 2956 if (del_timer(timer))
1da177e4
LT
2957 __sock_put(sk);
2958}
1da177e4
LT
2959EXPORT_SYMBOL(sk_stop_timer);
2960
2961void sock_init_data(struct socket *sock, struct sock *sk)
2962{
581319c5 2963 sk_init_common(sk);
1da177e4
LT
2964 sk->sk_send_head = NULL;
2965
99767f27 2966 timer_setup(&sk->sk_timer, NULL, 0);
4ec93edb 2967
1da177e4
LT
2968 sk->sk_allocation = GFP_KERNEL;
2969 sk->sk_rcvbuf = sysctl_rmem_default;
2970 sk->sk_sndbuf = sysctl_wmem_default;
2971 sk->sk_state = TCP_CLOSE;
972692e0 2972 sk_set_socket(sk, sock);
1da177e4
LT
2973
2974 sock_set_flag(sk, SOCK_ZAPPED);
2975
e71a4783 2976 if (sock) {
1da177e4 2977 sk->sk_type = sock->type;
333f7909 2978 RCU_INIT_POINTER(sk->sk_wq, &sock->wq);
1da177e4 2979 sock->sk = sk;
86741ec2
LC
2980 sk->sk_uid = SOCK_INODE(sock)->i_uid;
2981 } else {
c2f26e8f 2982 RCU_INIT_POINTER(sk->sk_wq, NULL);
86741ec2
LC
2983 sk->sk_uid = make_kuid(sock_net(sk)->user_ns, 0);
2984 }
1da177e4 2985
1da177e4 2986 rwlock_init(&sk->sk_callback_lock);
cdfbabfb
DH
2987 if (sk->sk_kern_sock)
2988 lockdep_set_class_and_name(
2989 &sk->sk_callback_lock,
2990 af_kern_callback_keys + sk->sk_family,
2991 af_family_kern_clock_key_strings[sk->sk_family]);
2992 else
2993 lockdep_set_class_and_name(
2994 &sk->sk_callback_lock,
443aef0e
PZ
2995 af_callback_keys + sk->sk_family,
2996 af_family_clock_key_strings[sk->sk_family]);
1da177e4
LT
2997
2998 sk->sk_state_change = sock_def_wakeup;
2999 sk->sk_data_ready = sock_def_readable;
3000 sk->sk_write_space = sock_def_write_space;
3001 sk->sk_error_report = sock_def_error_report;
3002 sk->sk_destruct = sock_def_destruct;
3003
5640f768
ED
3004 sk->sk_frag.page = NULL;
3005 sk->sk_frag.offset = 0;
ef64a54f 3006 sk->sk_peek_off = -1;
1da177e4 3007
109f6e39
EB
3008 sk->sk_peer_pid = NULL;
3009 sk->sk_peer_cred = NULL;
1da177e4
LT
3010 sk->sk_write_pending = 0;
3011 sk->sk_rcvlowat = 1;
3012 sk->sk_rcvtimeo = MAX_SCHEDULE_TIMEOUT;
3013 sk->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT;
3014
6c7c98ba 3015 sk->sk_stamp = SK_DEFAULT_STAMP;
3a0ed3e9
DD
3016#if BITS_PER_LONG==32
3017 seqlock_init(&sk->sk_stamp_seq);
3018#endif
52267790 3019 atomic_set(&sk->sk_zckey, 0);
1da177e4 3020
e0d1095a 3021#ifdef CONFIG_NET_RX_BUSY_POLL
06021292 3022 sk->sk_napi_id = 0;
64b0dc51 3023 sk->sk_ll_usec = sysctl_net_busy_read;
06021292
ET
3024#endif
3025
76a9ebe8
ED
3026 sk->sk_max_pacing_rate = ~0UL;
3027 sk->sk_pacing_rate = ~0UL;
7c68fa2b 3028 WRITE_ONCE(sk->sk_pacing_shift, 10);
70da268b 3029 sk->sk_incoming_cpu = -1;
c6345ce7
AN
3030
3031 sk_rx_queue_clear(sk);
4dc6dc71
ED
3032 /*
3033 * Before updating sk_refcnt, we must commit prior changes to memory
3034 * (Documentation/RCU/rculist_nulls.txt for details)
3035 */
3036 smp_wmb();
41c6d650 3037 refcount_set(&sk->sk_refcnt, 1);
33c732c3 3038 atomic_set(&sk->sk_drops, 0);
1da177e4 3039}
2a91525c 3040EXPORT_SYMBOL(sock_init_data);
1da177e4 3041
b5606c2d 3042void lock_sock_nested(struct sock *sk, int subclass)
1da177e4
LT
3043{
3044 might_sleep();
a5b5bb9a 3045 spin_lock_bh(&sk->sk_lock.slock);
d2e9117c 3046 if (sk->sk_lock.owned)
1da177e4 3047 __lock_sock(sk);
d2e9117c 3048 sk->sk_lock.owned = 1;
a5b5bb9a
IM
3049 spin_unlock(&sk->sk_lock.slock);
3050 /*
3051 * The sk_lock has mutex_lock() semantics here:
3052 */
fcc70d5f 3053 mutex_acquire(&sk->sk_lock.dep_map, subclass, 0, _RET_IP_);
a5b5bb9a 3054 local_bh_enable();
1da177e4 3055}
fcc70d5f 3056EXPORT_SYMBOL(lock_sock_nested);
1da177e4 3057
b5606c2d 3058void release_sock(struct sock *sk)
1da177e4 3059{
a5b5bb9a 3060 spin_lock_bh(&sk->sk_lock.slock);
1da177e4
LT
3061 if (sk->sk_backlog.tail)
3062 __release_sock(sk);
46d3ceab 3063
c3f9b018
ED
3064 /* Warning : release_cb() might need to release sk ownership,
3065 * ie call sock_release_ownership(sk) before us.
3066 */
46d3ceab
ED
3067 if (sk->sk_prot->release_cb)
3068 sk->sk_prot->release_cb(sk);
3069
c3f9b018 3070 sock_release_ownership(sk);
a5b5bb9a
IM
3071 if (waitqueue_active(&sk->sk_lock.wq))
3072 wake_up(&sk->sk_lock.wq);
3073 spin_unlock_bh(&sk->sk_lock.slock);
1da177e4
LT
3074}
3075EXPORT_SYMBOL(release_sock);
3076
8a74ad60
ED
3077/**
3078 * lock_sock_fast - fast version of lock_sock
3079 * @sk: socket
3080 *
3081 * This version should be used for very small section, where process wont block
d651983d
MCC
3082 * return false if fast path is taken:
3083 *
8a74ad60 3084 * sk_lock.slock locked, owned = 0, BH disabled
d651983d
MCC
3085 *
3086 * return true if slow path is taken:
3087 *
8a74ad60
ED
3088 * sk_lock.slock unlocked, owned = 1, BH enabled
3089 */
3090bool lock_sock_fast(struct sock *sk)
3091{
3092 might_sleep();
3093 spin_lock_bh(&sk->sk_lock.slock);
3094
3095 if (!sk->sk_lock.owned)
3096 /*
3097 * Note : We must disable BH
3098 */
3099 return false;
3100
3101 __lock_sock(sk);
3102 sk->sk_lock.owned = 1;
3103 spin_unlock(&sk->sk_lock.slock);
3104 /*
3105 * The sk_lock has mutex_lock() semantics here:
3106 */
3107 mutex_acquire(&sk->sk_lock.dep_map, 0, 0, _RET_IP_);
3108 local_bh_enable();
3109 return true;
3110}
3111EXPORT_SYMBOL(lock_sock_fast);
3112
c7cbdbf2
AB
3113int sock_gettstamp(struct socket *sock, void __user *userstamp,
3114 bool timeval, bool time32)
4ec93edb 3115{
c7cbdbf2
AB
3116 struct sock *sk = sock->sk;
3117 struct timespec64 ts;
9dae3497
YS
3118
3119 sock_enable_timestamp(sk, SOCK_TIMESTAMP);
c7cbdbf2
AB
3120 ts = ktime_to_timespec64(sock_read_timestamp(sk));
3121 if (ts.tv_sec == -1)
1da177e4 3122 return -ENOENT;
c7cbdbf2 3123 if (ts.tv_sec == 0) {
3a0ed3e9 3124 ktime_t kt = ktime_get_real();
f95f96a4 3125 sock_write_timestamp(sk, kt);
c7cbdbf2 3126 ts = ktime_to_timespec64(kt);
b7aa0bf7 3127 }
1da177e4 3128
c7cbdbf2
AB
3129 if (timeval)
3130 ts.tv_nsec /= 1000;
9dae3497 3131
c7cbdbf2
AB
3132#ifdef CONFIG_COMPAT_32BIT_TIME
3133 if (time32)
3134 return put_old_timespec32(&ts, userstamp);
3135#endif
3136#ifdef CONFIG_SPARC64
3137 /* beware of padding in sparc64 timeval */
3138 if (timeval && !in_compat_syscall()) {
3139 struct __kernel_old_timeval __user tv = {
c98f4822
SR
3140 .tv_sec = ts.tv_sec,
3141 .tv_usec = ts.tv_nsec,
c7cbdbf2 3142 };
c98f4822 3143 if (copy_to_user(userstamp, &tv, sizeof(tv)))
c7cbdbf2
AB
3144 return -EFAULT;
3145 return 0;
ae40eb1e 3146 }
c7cbdbf2
AB
3147#endif
3148 return put_timespec64(&ts, userstamp);
ae40eb1e 3149}
c7cbdbf2 3150EXPORT_SYMBOL(sock_gettstamp);
ae40eb1e 3151
193d357d 3152void sock_enable_timestamp(struct sock *sk, enum sock_flags flag)
4ec93edb 3153{
20d49473 3154 if (!sock_flag(sk, flag)) {
08e29af3
ED
3155 unsigned long previous_flags = sk->sk_flags;
3156
20d49473
PO
3157 sock_set_flag(sk, flag);
3158 /*
3159 * we just set one of the two flags which require net
3160 * time stamping, but time stamping might have been on
3161 * already because of the other one
3162 */
080a270f
HFS
3163 if (sock_needs_netstamp(sk) &&
3164 !(previous_flags & SK_FLAGS_TIMESTAMP))
20d49473 3165 net_enable_timestamp();
1da177e4
LT
3166 }
3167}
1da177e4 3168
cb820f8e
RC
3169int sock_recv_errqueue(struct sock *sk, struct msghdr *msg, int len,
3170 int level, int type)
3171{
3172 struct sock_exterr_skb *serr;
364a9e93 3173 struct sk_buff *skb;
cb820f8e
RC
3174 int copied, err;
3175
3176 err = -EAGAIN;
364a9e93 3177 skb = sock_dequeue_err_skb(sk);
cb820f8e
RC
3178 if (skb == NULL)
3179 goto out;
3180
3181 copied = skb->len;
3182 if (copied > len) {
3183 msg->msg_flags |= MSG_TRUNC;
3184 copied = len;
3185 }
51f3d02b 3186 err = skb_copy_datagram_msg(skb, 0, msg, copied);
cb820f8e
RC
3187 if (err)
3188 goto out_free_skb;
3189
3190 sock_recv_timestamp(msg, sk, skb);
3191
3192 serr = SKB_EXT_ERR(skb);
3193 put_cmsg(msg, level, type, sizeof(serr->ee), &serr->ee);
3194
3195 msg->msg_flags |= MSG_ERRQUEUE;
3196 err = copied;
3197
cb820f8e
RC
3198out_free_skb:
3199 kfree_skb(skb);
3200out:
3201 return err;
3202}
3203EXPORT_SYMBOL(sock_recv_errqueue);
3204
1da177e4
LT
3205/*
3206 * Get a socket option on an socket.
3207 *
3208 * FIX: POSIX 1003.1g is very ambiguous here. It states that
3209 * asynchronous errors should be reported by getsockopt. We assume
3210 * this means if you specify SO_ERROR (otherwise whats the point of it).
3211 */
3212int sock_common_getsockopt(struct socket *sock, int level, int optname,
3213 char __user *optval, int __user *optlen)
3214{
3215 struct sock *sk = sock->sk;
3216
3217 return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen);
3218}
1da177e4
LT
3219EXPORT_SYMBOL(sock_common_getsockopt);
3220
3fdadf7d 3221#ifdef CONFIG_COMPAT
543d9cfe
ACM
3222int compat_sock_common_getsockopt(struct socket *sock, int level, int optname,
3223 char __user *optval, int __user *optlen)
3fdadf7d
DM
3224{
3225 struct sock *sk = sock->sk;
3226
1e51f951 3227 if (sk->sk_prot->compat_getsockopt != NULL)
543d9cfe
ACM
3228 return sk->sk_prot->compat_getsockopt(sk, level, optname,
3229 optval, optlen);
3fdadf7d
DM
3230 return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen);
3231}
3232EXPORT_SYMBOL(compat_sock_common_getsockopt);
3233#endif
3234
1b784140
YX
3235int sock_common_recvmsg(struct socket *sock, struct msghdr *msg, size_t size,
3236 int flags)
1da177e4
LT
3237{
3238 struct sock *sk = sock->sk;
3239 int addr_len = 0;
3240 int err;
3241
1b784140 3242 err = sk->sk_prot->recvmsg(sk, msg, size, flags & MSG_DONTWAIT,
1da177e4
LT
3243 flags & ~MSG_DONTWAIT, &addr_len);
3244 if (err >= 0)
3245 msg->msg_namelen = addr_len;
3246 return err;
3247}
1da177e4
LT
3248EXPORT_SYMBOL(sock_common_recvmsg);
3249
3250/*
3251 * Set socket options on an inet socket.
3252 */
3253int sock_common_setsockopt(struct socket *sock, int level, int optname,
b7058842 3254 char __user *optval, unsigned int optlen)
1da177e4
LT
3255{
3256 struct sock *sk = sock->sk;
3257
3258 return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen);
3259}
1da177e4
LT
3260EXPORT_SYMBOL(sock_common_setsockopt);
3261
3fdadf7d 3262#ifdef CONFIG_COMPAT
543d9cfe 3263int compat_sock_common_setsockopt(struct socket *sock, int level, int optname,
b7058842 3264 char __user *optval, unsigned int optlen)
3fdadf7d
DM
3265{
3266 struct sock *sk = sock->sk;
3267
543d9cfe
ACM
3268 if (sk->sk_prot->compat_setsockopt != NULL)
3269 return sk->sk_prot->compat_setsockopt(sk, level, optname,
3270 optval, optlen);
3fdadf7d
DM
3271 return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen);
3272}
3273EXPORT_SYMBOL(compat_sock_common_setsockopt);
3274#endif
3275
1da177e4
LT
3276void sk_common_release(struct sock *sk)
3277{
3278 if (sk->sk_prot->destroy)
3279 sk->sk_prot->destroy(sk);
3280
3281 /*
3282 * Observation: when sock_common_release is called, processes have
3283 * no access to socket. But net still has.
3284 * Step one, detach it from networking:
3285 *
3286 * A. Remove from hash tables.
3287 */
3288
3289 sk->sk_prot->unhash(sk);
3290
3291 /*
3292 * In this point socket cannot receive new packets, but it is possible
3293 * that some packets are in flight because some CPU runs receiver and
3294 * did hash table lookup before we unhashed socket. They will achieve
3295 * receive queue and will be purged by socket destructor.
3296 *
3297 * Also we still have packets pending on receive queue and probably,
3298 * our own packets waiting in device queues. sock_destroy will drain
3299 * receive queue, but transmitted packets will delay socket destruction
3300 * until the last reference will be released.
3301 */
3302
3303 sock_orphan(sk);
3304
3305 xfrm_sk_free_policy(sk);
3306
e6848976 3307 sk_refcnt_debug_release(sk);
5640f768 3308
1da177e4
LT
3309 sock_put(sk);
3310}
1da177e4
LT
3311EXPORT_SYMBOL(sk_common_release);
3312
a2d133b1
JH
3313void sk_get_meminfo(const struct sock *sk, u32 *mem)
3314{
3315 memset(mem, 0, sizeof(*mem) * SK_MEMINFO_VARS);
3316
3317 mem[SK_MEMINFO_RMEM_ALLOC] = sk_rmem_alloc_get(sk);
ebb3b78d 3318 mem[SK_MEMINFO_RCVBUF] = READ_ONCE(sk->sk_rcvbuf);
a2d133b1 3319 mem[SK_MEMINFO_WMEM_ALLOC] = sk_wmem_alloc_get(sk);
e292f05e 3320 mem[SK_MEMINFO_SNDBUF] = READ_ONCE(sk->sk_sndbuf);
a2d133b1 3321 mem[SK_MEMINFO_FWD_ALLOC] = sk->sk_forward_alloc;
ab4e846a 3322 mem[SK_MEMINFO_WMEM_QUEUED] = READ_ONCE(sk->sk_wmem_queued);
a2d133b1 3323 mem[SK_MEMINFO_OPTMEM] = atomic_read(&sk->sk_omem_alloc);
70c26558 3324 mem[SK_MEMINFO_BACKLOG] = READ_ONCE(sk->sk_backlog.len);
a2d133b1
JH
3325 mem[SK_MEMINFO_DROPS] = atomic_read(&sk->sk_drops);
3326}
3327
13ff3d6f
PE
3328#ifdef CONFIG_PROC_FS
3329#define PROTO_INUSE_NR 64 /* should be enough for the first time */
1338d466
PE
3330struct prot_inuse {
3331 int val[PROTO_INUSE_NR];
3332};
13ff3d6f
PE
3333
3334static DECLARE_BITMAP(proto_inuse_idx, PROTO_INUSE_NR);
70ee1159 3335
70ee1159
PE
3336void sock_prot_inuse_add(struct net *net, struct proto *prot, int val)
3337{
08fc7f81 3338 __this_cpu_add(net->core.prot_inuse->val[prot->inuse_idx], val);
70ee1159
PE
3339}
3340EXPORT_SYMBOL_GPL(sock_prot_inuse_add);
3341
3342int sock_prot_inuse_get(struct net *net, struct proto *prot)
3343{
3344 int cpu, idx = prot->inuse_idx;
3345 int res = 0;
3346
3347 for_each_possible_cpu(cpu)
08fc7f81 3348 res += per_cpu_ptr(net->core.prot_inuse, cpu)->val[idx];
70ee1159
PE
3349
3350 return res >= 0 ? res : 0;
3351}
3352EXPORT_SYMBOL_GPL(sock_prot_inuse_get);
3353
648845ab
TZ
3354static void sock_inuse_add(struct net *net, int val)
3355{
3356 this_cpu_add(*net->core.sock_inuse, val);
3357}
3358
3359int sock_inuse_get(struct net *net)
3360{
3361 int cpu, res = 0;
3362
3363 for_each_possible_cpu(cpu)
3364 res += *per_cpu_ptr(net->core.sock_inuse, cpu);
3365
3366 return res;
3367}
3368
3369EXPORT_SYMBOL_GPL(sock_inuse_get);
3370
2c8c1e72 3371static int __net_init sock_inuse_init_net(struct net *net)
70ee1159 3372{
08fc7f81 3373 net->core.prot_inuse = alloc_percpu(struct prot_inuse);
648845ab
TZ
3374 if (net->core.prot_inuse == NULL)
3375 return -ENOMEM;
3376
3377 net->core.sock_inuse = alloc_percpu(int);
3378 if (net->core.sock_inuse == NULL)
3379 goto out;
3380
3381 return 0;
3382
3383out:
3384 free_percpu(net->core.prot_inuse);
3385 return -ENOMEM;
70ee1159
PE
3386}
3387
2c8c1e72 3388static void __net_exit sock_inuse_exit_net(struct net *net)
70ee1159 3389{
08fc7f81 3390 free_percpu(net->core.prot_inuse);
648845ab 3391 free_percpu(net->core.sock_inuse);
70ee1159
PE
3392}
3393
3394static struct pernet_operations net_inuse_ops = {
3395 .init = sock_inuse_init_net,
3396 .exit = sock_inuse_exit_net,
3397};
3398
3399static __init int net_inuse_init(void)
3400{
3401 if (register_pernet_subsys(&net_inuse_ops))
3402 panic("Cannot initialize net inuse counters");
3403
3404 return 0;
3405}
3406
3407core_initcall(net_inuse_init);
13ff3d6f 3408
b45ce321 3409static int assign_proto_idx(struct proto *prot)
13ff3d6f
PE
3410{
3411 prot->inuse_idx = find_first_zero_bit(proto_inuse_idx, PROTO_INUSE_NR);
3412
3413 if (unlikely(prot->inuse_idx == PROTO_INUSE_NR - 1)) {
e005d193 3414 pr_err("PROTO_INUSE_NR exhausted\n");
b45ce321 3415 return -ENOSPC;
13ff3d6f
PE
3416 }
3417
3418 set_bit(prot->inuse_idx, proto_inuse_idx);
b45ce321 3419 return 0;
13ff3d6f
PE
3420}
3421
3422static void release_proto_idx(struct proto *prot)
3423{
3424 if (prot->inuse_idx != PROTO_INUSE_NR - 1)
3425 clear_bit(prot->inuse_idx, proto_inuse_idx);
3426}
3427#else
b45ce321 3428static inline int assign_proto_idx(struct proto *prot)
13ff3d6f 3429{
b45ce321 3430 return 0;
13ff3d6f
PE
3431}
3432
3433static inline void release_proto_idx(struct proto *prot)
3434{
3435}
648845ab
TZ
3436
3437static void sock_inuse_add(struct net *net, int val)
3438{
3439}
13ff3d6f
PE
3440#endif
3441
0159dfd3
ED
3442static void req_prot_cleanup(struct request_sock_ops *rsk_prot)
3443{
3444 if (!rsk_prot)
3445 return;
3446 kfree(rsk_prot->slab_name);
3447 rsk_prot->slab_name = NULL;
adf78eda
JL
3448 kmem_cache_destroy(rsk_prot->slab);
3449 rsk_prot->slab = NULL;
0159dfd3
ED
3450}
3451
3452static int req_prot_init(const struct proto *prot)
3453{
3454 struct request_sock_ops *rsk_prot = prot->rsk_prot;
3455
3456 if (!rsk_prot)
3457 return 0;
3458
3459 rsk_prot->slab_name = kasprintf(GFP_KERNEL, "request_sock_%s",
3460 prot->name);
3461 if (!rsk_prot->slab_name)
3462 return -ENOMEM;
3463
3464 rsk_prot->slab = kmem_cache_create(rsk_prot->slab_name,
3465 rsk_prot->obj_size, 0,
e699e2c6
SB
3466 SLAB_ACCOUNT | prot->slab_flags,
3467 NULL);
0159dfd3
ED
3468
3469 if (!rsk_prot->slab) {
3470 pr_crit("%s: Can't create request sock SLAB cache!\n",
3471 prot->name);
3472 return -ENOMEM;
3473 }
3474 return 0;
3475}
3476
b733c007
PE
3477int proto_register(struct proto *prot, int alloc_slab)
3478{
b45ce321 3479 int ret = -ENOBUFS;
3480
1da177e4 3481 if (alloc_slab) {
30c2c9f1
DW
3482 prot->slab = kmem_cache_create_usercopy(prot->name,
3483 prot->obj_size, 0,
e699e2c6
SB
3484 SLAB_HWCACHE_ALIGN | SLAB_ACCOUNT |
3485 prot->slab_flags,
289a4860 3486 prot->useroffset, prot->usersize,
271b72c7 3487 NULL);
1da177e4
LT
3488
3489 if (prot->slab == NULL) {
e005d193
JP
3490 pr_crit("%s: Can't create sock SLAB cache!\n",
3491 prot->name);
60e7663d 3492 goto out;
1da177e4 3493 }
2e6599cb 3494
0159dfd3
ED
3495 if (req_prot_init(prot))
3496 goto out_free_request_sock_slab;
8feaf0c0 3497
6d6ee43e 3498 if (prot->twsk_prot != NULL) {
faf23422 3499 prot->twsk_prot->twsk_slab_name = kasprintf(GFP_KERNEL, "tw_sock_%s", prot->name);
8feaf0c0 3500
7e56b5d6 3501 if (prot->twsk_prot->twsk_slab_name == NULL)
8feaf0c0
ACM
3502 goto out_free_request_sock_slab;
3503
6d6ee43e 3504 prot->twsk_prot->twsk_slab =
7e56b5d6 3505 kmem_cache_create(prot->twsk_prot->twsk_slab_name,
6d6ee43e 3506 prot->twsk_prot->twsk_obj_size,
3ab5aee7 3507 0,
e699e2c6 3508 SLAB_ACCOUNT |
52db70dc 3509 prot->slab_flags,
20c2df83 3510 NULL);
6d6ee43e 3511 if (prot->twsk_prot->twsk_slab == NULL)
8feaf0c0
ACM
3512 goto out_free_timewait_sock_slab_name;
3513 }
1da177e4
LT
3514 }
3515
36b77a52 3516 mutex_lock(&proto_list_mutex);
b45ce321 3517 ret = assign_proto_idx(prot);
3518 if (ret) {
3519 mutex_unlock(&proto_list_mutex);
3520 goto out_free_timewait_sock_slab_name;
3521 }
1da177e4 3522 list_add(&prot->node, &proto_list);
36b77a52 3523 mutex_unlock(&proto_list_mutex);
b45ce321 3524 return ret;
b733c007 3525
8feaf0c0 3526out_free_timewait_sock_slab_name:
b45ce321 3527 if (alloc_slab && prot->twsk_prot)
3528 kfree(prot->twsk_prot->twsk_slab_name);
8feaf0c0 3529out_free_request_sock_slab:
b45ce321 3530 if (alloc_slab) {
3531 req_prot_cleanup(prot->rsk_prot);
0159dfd3 3532
b45ce321 3533 kmem_cache_destroy(prot->slab);
3534 prot->slab = NULL;
3535 }
b733c007 3536out:
b45ce321 3537 return ret;
1da177e4 3538}
1da177e4
LT
3539EXPORT_SYMBOL(proto_register);
3540
3541void proto_unregister(struct proto *prot)
3542{
36b77a52 3543 mutex_lock(&proto_list_mutex);
13ff3d6f 3544 release_proto_idx(prot);
0a3f4358 3545 list_del(&prot->node);
36b77a52 3546 mutex_unlock(&proto_list_mutex);
1da177e4 3547
adf78eda
JL
3548 kmem_cache_destroy(prot->slab);
3549 prot->slab = NULL;
1da177e4 3550
0159dfd3 3551 req_prot_cleanup(prot->rsk_prot);
2e6599cb 3552
6d6ee43e 3553 if (prot->twsk_prot != NULL && prot->twsk_prot->twsk_slab != NULL) {
6d6ee43e 3554 kmem_cache_destroy(prot->twsk_prot->twsk_slab);
7e56b5d6 3555 kfree(prot->twsk_prot->twsk_slab_name);
6d6ee43e 3556 prot->twsk_prot->twsk_slab = NULL;
8feaf0c0 3557 }
1da177e4 3558}
1da177e4
LT
3559EXPORT_SYMBOL(proto_unregister);
3560
bf2ae2e4
XL
3561int sock_load_diag_module(int family, int protocol)
3562{
3563 if (!protocol) {
3564 if (!sock_is_registered(family))
3565 return -ENOENT;
3566
3567 return request_module("net-pf-%d-proto-%d-type-%d", PF_NETLINK,
3568 NETLINK_SOCK_DIAG, family);
3569 }
3570
3571#ifdef CONFIG_INET
3572 if (family == AF_INET &&
c34c1287 3573 protocol != IPPROTO_RAW &&
bf2ae2e4
XL
3574 !rcu_access_pointer(inet_protos[protocol]))
3575 return -ENOENT;
3576#endif
3577
3578 return request_module("net-pf-%d-proto-%d-type-%d-%d", PF_NETLINK,
3579 NETLINK_SOCK_DIAG, family, protocol);
3580}
3581EXPORT_SYMBOL(sock_load_diag_module);
3582
1da177e4 3583#ifdef CONFIG_PROC_FS
1da177e4 3584static void *proto_seq_start(struct seq_file *seq, loff_t *pos)
36b77a52 3585 __acquires(proto_list_mutex)
1da177e4 3586{
36b77a52 3587 mutex_lock(&proto_list_mutex);
60f0438a 3588 return seq_list_start_head(&proto_list, *pos);
1da177e4
LT
3589}
3590
3591static void *proto_seq_next(struct seq_file *seq, void *v, loff_t *pos)
3592{
60f0438a 3593 return seq_list_next(v, &proto_list, pos);
1da177e4
LT
3594}
3595
3596static void proto_seq_stop(struct seq_file *seq, void *v)
36b77a52 3597 __releases(proto_list_mutex)
1da177e4 3598{
36b77a52 3599 mutex_unlock(&proto_list_mutex);
1da177e4
LT
3600}
3601
3602static char proto_method_implemented(const void *method)
3603{
3604 return method == NULL ? 'n' : 'y';
3605}
180d8cd9
GC
3606static long sock_prot_memory_allocated(struct proto *proto)
3607{
cb75a36c 3608 return proto->memory_allocated != NULL ? proto_memory_allocated(proto) : -1L;
180d8cd9
GC
3609}
3610
7a512eb8 3611static const char *sock_prot_memory_pressure(struct proto *proto)
180d8cd9
GC
3612{
3613 return proto->memory_pressure != NULL ?
3614 proto_memory_pressure(proto) ? "yes" : "no" : "NI";
3615}
1da177e4
LT
3616
3617static void proto_seq_printf(struct seq_file *seq, struct proto *proto)
3618{
180d8cd9 3619
8d987e5c 3620 seq_printf(seq, "%-9s %4u %6d %6ld %-3s %6u %-3s %-10s "
1da177e4
LT
3621 "%2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c\n",
3622 proto->name,
3623 proto->obj_size,
14e943db 3624 sock_prot_inuse_get(seq_file_net(seq), proto),
180d8cd9
GC
3625 sock_prot_memory_allocated(proto),
3626 sock_prot_memory_pressure(proto),
1da177e4
LT
3627 proto->max_header,
3628 proto->slab == NULL ? "no" : "yes",
3629 module_name(proto->owner),
3630 proto_method_implemented(proto->close),
3631 proto_method_implemented(proto->connect),
3632 proto_method_implemented(proto->disconnect),
3633 proto_method_implemented(proto->accept),
3634 proto_method_implemented(proto->ioctl),
3635 proto_method_implemented(proto->init),
3636 proto_method_implemented(proto->destroy),
3637 proto_method_implemented(proto->shutdown),
3638 proto_method_implemented(proto->setsockopt),
3639 proto_method_implemented(proto->getsockopt),
3640 proto_method_implemented(proto->sendmsg),
3641 proto_method_implemented(proto->recvmsg),
3642 proto_method_implemented(proto->sendpage),
3643 proto_method_implemented(proto->bind),
3644 proto_method_implemented(proto->backlog_rcv),
3645 proto_method_implemented(proto->hash),
3646 proto_method_implemented(proto->unhash),
3647 proto_method_implemented(proto->get_port),
3648 proto_method_implemented(proto->enter_memory_pressure));
3649}
3650
3651static int proto_seq_show(struct seq_file *seq, void *v)
3652{
60f0438a 3653 if (v == &proto_list)
1da177e4
LT
3654 seq_printf(seq, "%-9s %-4s %-8s %-6s %-5s %-7s %-4s %-10s %s",
3655 "protocol",
3656 "size",
3657 "sockets",
3658 "memory",
3659 "press",
3660 "maxhdr",
3661 "slab",
3662 "module",
3663 "cl co di ac io in de sh ss gs se re sp bi br ha uh gp em\n");
3664 else
60f0438a 3665 proto_seq_printf(seq, list_entry(v, struct proto, node));
1da177e4
LT
3666 return 0;
3667}
3668
f690808e 3669static const struct seq_operations proto_seq_ops = {
1da177e4
LT
3670 .start = proto_seq_start,
3671 .next = proto_seq_next,
3672 .stop = proto_seq_stop,
3673 .show = proto_seq_show,
3674};
3675
14e943db
ED
3676static __net_init int proto_init_net(struct net *net)
3677{
c3506372
CH
3678 if (!proc_create_net("protocols", 0444, net->proc_net, &proto_seq_ops,
3679 sizeof(struct seq_net_private)))
14e943db
ED
3680 return -ENOMEM;
3681
3682 return 0;
3683}
3684
3685static __net_exit void proto_exit_net(struct net *net)
3686{
ece31ffd 3687 remove_proc_entry("protocols", net->proc_net);
14e943db
ED
3688}
3689
3690
3691static __net_initdata struct pernet_operations proto_net_ops = {
3692 .init = proto_init_net,
3693 .exit = proto_exit_net,
1da177e4
LT
3694};
3695
3696static int __init proto_init(void)
3697{
14e943db 3698 return register_pernet_subsys(&proto_net_ops);
1da177e4
LT
3699}
3700
3701subsys_initcall(proto_init);
3702
3703#endif /* PROC_FS */
7db6b048
SS
3704
3705#ifdef CONFIG_NET_RX_BUSY_POLL
3706bool sk_busy_loop_end(void *p, unsigned long start_time)
3707{
3708 struct sock *sk = p;
3709
3f926af3 3710 return !skb_queue_empty_lockless(&sk->sk_receive_queue) ||
7db6b048
SS
3711 sk_busy_loop_timeout(sk, start_time);
3712}
3713EXPORT_SYMBOL(sk_busy_loop_end);
3714#endif /* CONFIG_NET_RX_BUSY_POLL */
c0425a42
CH
3715
3716int sock_bind_add(struct sock *sk, struct sockaddr *addr, int addr_len)
3717{
3718 if (!sk->sk_prot->bind_add)
3719 return -EOPNOTSUPP;
3720 return sk->sk_prot->bind_add(sk, addr, addr_len);
3721}
3722EXPORT_SYMBOL(sock_bind_add);