1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * INET An implementation of the TCP/IP protocol suite for the LINUX
4 * operating system. INET is implemented using the BSD Socket
5 * interface as the means of communication with the user level.
6 *
7 * Generic socket support routines. Memory allocators, socket lock/release
8 * handler for protocols to use and generic option handler.
9 *
10 * Authors: Ross Biro
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
35 * code. The ACK stuff can wait and needs major
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:
84 */
85
86 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
87
88 #include <asm/unaligned.h>
89 #include <linux/capability.h>
90 #include <linux/errno.h>
91 #include <linux/errqueue.h>
92 #include <linux/types.h>
93 #include <linux/socket.h>
94 #include <linux/in.h>
95 #include <linux/kernel.h>
96 #include <linux/module.h>
97 #include <linux/proc_fs.h>
98 #include <linux/seq_file.h>
99 #include <linux/sched.h>
100 #include <linux/sched/mm.h>
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/udp.h>
111 #include <linux/init.h>
112 #include <linux/highmem.h>
113 #include <linux/user_namespace.h>
114 #include <linux/static_key.h>
115 #include <linux/memcontrol.h>
116 #include <linux/prefetch.h>
117 #include <linux/compat.h>
118
119 #include <linux/uaccess.h>
120
121 #include <linux/netdevice.h>
122 #include <net/protocol.h>
123 #include <linux/skbuff.h>
124 #include <net/net_namespace.h>
125 #include <net/request_sock.h>
126 #include <net/sock.h>
127 #include <linux/net_tstamp.h>
128 #include <net/xfrm.h>
129 #include <linux/ipsec.h>
130 #include <net/cls_cgroup.h>
131 #include <net/netprio_cgroup.h>
132 #include <linux/sock_diag.h>
133
134 #include <linux/filter.h>
135 #include <net/sock_reuseport.h>
136 #include <net/bpf_sk_storage.h>
137
138 #include <trace/events/sock.h>
139 #include <trace/hooks/sched.h>
140 #include <trace/hooks/net.h>
141
142 #include <net/tcp.h>
143 #include <net/busy_poll.h>
144
145 #include <linux/ethtool.h>
146
147 #include "dev.h"
148
149 static DEFINE_MUTEX(proto_list_mutex);
150 static LIST_HEAD(proto_list);
151
152 static void sock_def_write_space_wfree(struct sock *sk);
153 static void sock_def_write_space(struct sock *sk);
154
155 /**
156 * sk_ns_capable - General socket capability test
157 * @sk: Socket to use a capability on or through
158 * @user_ns: The user namespace of the capability to use
159 * @cap: The capability to use
160 *
161 * Test to see if the opener of the socket had when the socket was
162 * created and the current process has the capability @cap in the user
163 * namespace @user_ns.
164 */
sk_ns_capable(const struct sock * sk,struct user_namespace * user_ns,int cap)165 bool sk_ns_capable(const struct sock *sk,
166 struct user_namespace *user_ns, int cap)
167 {
168 return file_ns_capable(sk->sk_socket->file, user_ns, cap) &&
169 ns_capable(user_ns, cap);
170 }
171 EXPORT_SYMBOL(sk_ns_capable);
172
173 /**
174 * sk_capable - Socket global capability test
175 * @sk: Socket to use a capability on or through
176 * @cap: The global capability to use
177 *
178 * Test to see if the opener of the socket had when the socket was
179 * created and the current process has the capability @cap in all user
180 * namespaces.
181 */
sk_capable(const struct sock * sk,int cap)182 bool sk_capable(const struct sock *sk, int cap)
183 {
184 return sk_ns_capable(sk, &init_user_ns, cap);
185 }
186 EXPORT_SYMBOL(sk_capable);
187
188 /**
189 * sk_net_capable - Network namespace socket capability test
190 * @sk: Socket to use a capability on or through
191 * @cap: The capability to use
192 *
193 * Test to see if the opener of the socket had when the socket was created
194 * and the current process has the capability @cap over the network namespace
195 * the socket is a member of.
196 */
sk_net_capable(const struct sock * sk,int cap)197 bool sk_net_capable(const struct sock *sk, int cap)
198 {
199 return sk_ns_capable(sk, sock_net(sk)->user_ns, cap);
200 }
201 EXPORT_SYMBOL(sk_net_capable);
202
203 /*
204 * Each address family might have different locking rules, so we have
205 * one slock key per address family and separate keys for internal and
206 * userspace sockets.
207 */
208 static struct lock_class_key af_family_keys[AF_MAX];
209 static struct lock_class_key af_family_kern_keys[AF_MAX];
210 static struct lock_class_key af_family_slock_keys[AF_MAX];
211 static struct lock_class_key af_family_kern_slock_keys[AF_MAX];
212
213 /*
214 * Make lock validator output more readable. (we pre-construct these
215 * strings build-time, so that runtime initialization of socket
216 * locks is fast):
217 */
218
219 #define _sock_locks(x) \
220 x "AF_UNSPEC", x "AF_UNIX" , x "AF_INET" , \
221 x "AF_AX25" , x "AF_IPX" , x "AF_APPLETALK", \
222 x "AF_NETROM", x "AF_BRIDGE" , x "AF_ATMPVC" , \
223 x "AF_X25" , x "AF_INET6" , x "AF_ROSE" , \
224 x "AF_DECnet", x "AF_NETBEUI" , x "AF_SECURITY" , \
225 x "AF_KEY" , x "AF_NETLINK" , x "AF_PACKET" , \
226 x "AF_ASH" , x "AF_ECONET" , x "AF_ATMSVC" , \
227 x "AF_RDS" , x "AF_SNA" , x "AF_IRDA" , \
228 x "AF_PPPOX" , x "AF_WANPIPE" , x "AF_LLC" , \
229 x "27" , x "28" , x "AF_CAN" , \
230 x "AF_TIPC" , x "AF_BLUETOOTH", x "IUCV" , \
231 x "AF_RXRPC" , x "AF_ISDN" , x "AF_PHONET" , \
232 x "AF_IEEE802154", x "AF_CAIF" , x "AF_ALG" , \
233 x "AF_NFC" , x "AF_VSOCK" , x "AF_KCM" , \
234 x "AF_QIPCRTR", x "AF_SMC" , x "AF_XDP" , \
235 x "AF_MCTP" , \
236 x "AF_MAX"
237
238 static const char *const af_family_key_strings[AF_MAX+1] = {
239 _sock_locks("sk_lock-")
240 };
241 static const char *const af_family_slock_key_strings[AF_MAX+1] = {
242 _sock_locks("slock-")
243 };
244 static const char *const af_family_clock_key_strings[AF_MAX+1] = {
245 _sock_locks("clock-")
246 };
247
248 static const char *const af_family_kern_key_strings[AF_MAX+1] = {
249 _sock_locks("k-sk_lock-")
250 };
251 static const char *const af_family_kern_slock_key_strings[AF_MAX+1] = {
252 _sock_locks("k-slock-")
253 };
254 static const char *const af_family_kern_clock_key_strings[AF_MAX+1] = {
255 _sock_locks("k-clock-")
256 };
257 static const char *const af_family_rlock_key_strings[AF_MAX+1] = {
258 _sock_locks("rlock-")
259 };
260 static const char *const af_family_wlock_key_strings[AF_MAX+1] = {
261 _sock_locks("wlock-")
262 };
263 static const char *const af_family_elock_key_strings[AF_MAX+1] = {
264 _sock_locks("elock-")
265 };
266
267 /*
268 * sk_callback_lock and sk queues locking rules are per-address-family,
269 * so split the lock classes by using a per-AF key:
270 */
271 static struct lock_class_key af_callback_keys[AF_MAX];
272 static struct lock_class_key af_rlock_keys[AF_MAX];
273 static struct lock_class_key af_wlock_keys[AF_MAX];
274 static struct lock_class_key af_elock_keys[AF_MAX];
275 static struct lock_class_key af_kern_callback_keys[AF_MAX];
276
277 /* Run time adjustable parameters. */
278 __u32 sysctl_wmem_max __read_mostly = SK_WMEM_MAX;
279 EXPORT_SYMBOL(sysctl_wmem_max);
280 __u32 sysctl_rmem_max __read_mostly = SK_RMEM_MAX;
281 EXPORT_SYMBOL(sysctl_rmem_max);
282 __u32 sysctl_wmem_default __read_mostly = SK_WMEM_MAX;
283 __u32 sysctl_rmem_default __read_mostly = SK_RMEM_MAX;
284
285 /* Maximal space eaten by iovec or ancillary data plus some space */
286 int sysctl_optmem_max __read_mostly = sizeof(unsigned long)*(2*UIO_MAXIOV+512);
287 EXPORT_SYMBOL(sysctl_optmem_max);
288
289 int sysctl_tstamp_allow_data __read_mostly = 1;
290
291 DEFINE_STATIC_KEY_FALSE(memalloc_socks_key);
292 EXPORT_SYMBOL_GPL(memalloc_socks_key);
293
294 /**
295 * sk_set_memalloc - sets %SOCK_MEMALLOC
296 * @sk: socket to set it on
297 *
298 * Set %SOCK_MEMALLOC on a socket for access to emergency reserves.
299 * It's the responsibility of the admin to adjust min_free_kbytes
300 * to meet the requirements
301 */
sk_set_memalloc(struct sock * sk)302 void sk_set_memalloc(struct sock *sk)
303 {
304 sock_set_flag(sk, SOCK_MEMALLOC);
305 sk->sk_allocation |= __GFP_MEMALLOC;
306 static_branch_inc(&memalloc_socks_key);
307 }
308 EXPORT_SYMBOL_GPL(sk_set_memalloc);
309
sk_clear_memalloc(struct sock * sk)310 void sk_clear_memalloc(struct sock *sk)
311 {
312 sock_reset_flag(sk, SOCK_MEMALLOC);
313 sk->sk_allocation &= ~__GFP_MEMALLOC;
314 static_branch_dec(&memalloc_socks_key);
315
316 /*
317 * SOCK_MEMALLOC is allowed to ignore rmem limits to ensure forward
318 * progress of swapping. SOCK_MEMALLOC may be cleared while
319 * it has rmem allocations due to the last swapfile being deactivated
320 * but there is a risk that the socket is unusable due to exceeding
321 * the rmem limits. Reclaim the reserves and obey rmem limits again.
322 */
323 sk_mem_reclaim(sk);
324 }
325 EXPORT_SYMBOL_GPL(sk_clear_memalloc);
326
__sk_backlog_rcv(struct sock * sk,struct sk_buff * skb)327 int __sk_backlog_rcv(struct sock *sk, struct sk_buff *skb)
328 {
329 int ret;
330 unsigned int noreclaim_flag;
331
332 /* these should have been dropped before queueing */
333 BUG_ON(!sock_flag(sk, SOCK_MEMALLOC));
334
335 noreclaim_flag = memalloc_noreclaim_save();
336 ret = INDIRECT_CALL_INET(sk->sk_backlog_rcv,
337 tcp_v6_do_rcv,
338 tcp_v4_do_rcv,
339 sk, skb);
340 memalloc_noreclaim_restore(noreclaim_flag);
341
342 return ret;
343 }
344 EXPORT_SYMBOL(__sk_backlog_rcv);
345
sk_error_report(struct sock * sk)346 void sk_error_report(struct sock *sk)
347 {
348 sk->sk_error_report(sk);
349
350 switch (sk->sk_family) {
351 case AF_INET:
352 fallthrough;
353 case AF_INET6:
354 trace_inet_sk_error_report(sk);
355 break;
356 default:
357 break;
358 }
359 }
360 EXPORT_SYMBOL(sk_error_report);
361
sock_get_timeout(long timeo,void * optval,bool old_timeval)362 int sock_get_timeout(long timeo, void *optval, bool old_timeval)
363 {
364 struct __kernel_sock_timeval tv;
365
366 if (timeo == MAX_SCHEDULE_TIMEOUT) {
367 tv.tv_sec = 0;
368 tv.tv_usec = 0;
369 } else {
370 tv.tv_sec = timeo / HZ;
371 tv.tv_usec = ((timeo % HZ) * USEC_PER_SEC) / HZ;
372 }
373
374 if (old_timeval && in_compat_syscall() && !COMPAT_USE_64BIT_TIME) {
375 struct old_timeval32 tv32 = { tv.tv_sec, tv.tv_usec };
376 *(struct old_timeval32 *)optval = tv32;
377 return sizeof(tv32);
378 }
379
380 if (old_timeval) {
381 struct __kernel_old_timeval old_tv;
382 old_tv.tv_sec = tv.tv_sec;
383 old_tv.tv_usec = tv.tv_usec;
384 *(struct __kernel_old_timeval *)optval = old_tv;
385 return sizeof(old_tv);
386 }
387
388 *(struct __kernel_sock_timeval *)optval = tv;
389 return sizeof(tv);
390 }
391 EXPORT_SYMBOL(sock_get_timeout);
392
sock_copy_user_timeval(struct __kernel_sock_timeval * tv,sockptr_t optval,int optlen,bool old_timeval)393 int sock_copy_user_timeval(struct __kernel_sock_timeval *tv,
394 sockptr_t optval, int optlen, bool old_timeval)
395 {
396 if (old_timeval && in_compat_syscall() && !COMPAT_USE_64BIT_TIME) {
397 struct old_timeval32 tv32;
398
399 if (optlen < sizeof(tv32))
400 return -EINVAL;
401
402 if (copy_from_sockptr(&tv32, optval, sizeof(tv32)))
403 return -EFAULT;
404 tv->tv_sec = tv32.tv_sec;
405 tv->tv_usec = tv32.tv_usec;
406 } else if (old_timeval) {
407 struct __kernel_old_timeval old_tv;
408
409 if (optlen < sizeof(old_tv))
410 return -EINVAL;
411 if (copy_from_sockptr(&old_tv, optval, sizeof(old_tv)))
412 return -EFAULT;
413 tv->tv_sec = old_tv.tv_sec;
414 tv->tv_usec = old_tv.tv_usec;
415 } else {
416 if (optlen < sizeof(*tv))
417 return -EINVAL;
418 if (copy_from_sockptr(tv, optval, sizeof(*tv)))
419 return -EFAULT;
420 }
421
422 return 0;
423 }
424 EXPORT_SYMBOL(sock_copy_user_timeval);
425
sock_set_timeout(long * timeo_p,sockptr_t optval,int optlen,bool old_timeval)426 static int sock_set_timeout(long *timeo_p, sockptr_t optval, int optlen,
427 bool old_timeval)
428 {
429 struct __kernel_sock_timeval tv;
430 int err = sock_copy_user_timeval(&tv, optval, optlen, old_timeval);
431 long val;
432
433 if (err)
434 return err;
435
436 if (tv.tv_usec < 0 || tv.tv_usec >= USEC_PER_SEC)
437 return -EDOM;
438
439 if (tv.tv_sec < 0) {
440 static int warned __read_mostly;
441
442 WRITE_ONCE(*timeo_p, 0);
443 if (warned < 10 && net_ratelimit()) {
444 warned++;
445 pr_info("%s: `%s' (pid %d) tries to set negative timeout\n",
446 __func__, current->comm, task_pid_nr(current));
447 }
448 return 0;
449 }
450 val = MAX_SCHEDULE_TIMEOUT;
451 if ((tv.tv_sec || tv.tv_usec) &&
452 (tv.tv_sec < (MAX_SCHEDULE_TIMEOUT / HZ - 1)))
453 val = tv.tv_sec * HZ + DIV_ROUND_UP((unsigned long)tv.tv_usec,
454 USEC_PER_SEC / HZ);
455 WRITE_ONCE(*timeo_p, val);
456 return 0;
457 }
458
sock_needs_netstamp(const struct sock * sk)459 static bool sock_needs_netstamp(const struct sock *sk)
460 {
461 switch (sk->sk_family) {
462 case AF_UNSPEC:
463 case AF_UNIX:
464 return false;
465 default:
466 return true;
467 }
468 }
469
sock_disable_timestamp(struct sock * sk,unsigned long flags)470 static void sock_disable_timestamp(struct sock *sk, unsigned long flags)
471 {
472 if (sk->sk_flags & flags) {
473 sk->sk_flags &= ~flags;
474 if (sock_needs_netstamp(sk) &&
475 !(sk->sk_flags & SK_FLAGS_TIMESTAMP))
476 net_disable_timestamp();
477 }
478 }
479
480
__sock_queue_rcv_skb(struct sock * sk,struct sk_buff * skb)481 int __sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
482 {
483 unsigned long flags;
484 struct sk_buff_head *list = &sk->sk_receive_queue;
485
486 if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) {
487 atomic_inc(&sk->sk_drops);
488 trace_sock_rcvqueue_full(sk, skb);
489 return -ENOMEM;
490 }
491
492 if (!sk_rmem_schedule(sk, skb, skb->truesize)) {
493 atomic_inc(&sk->sk_drops);
494 return -ENOBUFS;
495 }
496
497 skb->dev = NULL;
498 skb_set_owner_r(skb, sk);
499
500 /* we escape from rcu protected region, make sure we dont leak
501 * a norefcounted dst
502 */
503 skb_dst_force(skb);
504
505 spin_lock_irqsave(&list->lock, flags);
506 sock_skb_set_dropcount(sk, skb);
507 __skb_queue_tail(list, skb);
508 spin_unlock_irqrestore(&list->lock, flags);
509
510 if (!sock_flag(sk, SOCK_DEAD))
511 sk->sk_data_ready(sk);
512 return 0;
513 }
514 EXPORT_SYMBOL(__sock_queue_rcv_skb);
515
sock_queue_rcv_skb_reason(struct sock * sk,struct sk_buff * skb,enum skb_drop_reason * reason)516 int sock_queue_rcv_skb_reason(struct sock *sk, struct sk_buff *skb,
517 enum skb_drop_reason *reason)
518 {
519 enum skb_drop_reason drop_reason;
520 int err;
521
522 err = sk_filter(sk, skb);
523 if (err) {
524 drop_reason = SKB_DROP_REASON_SOCKET_FILTER;
525 goto out;
526 }
527 err = __sock_queue_rcv_skb(sk, skb);
528 switch (err) {
529 case -ENOMEM:
530 drop_reason = SKB_DROP_REASON_SOCKET_RCVBUFF;
531 break;
532 case -ENOBUFS:
533 drop_reason = SKB_DROP_REASON_PROTO_MEM;
534 break;
535 default:
536 drop_reason = SKB_NOT_DROPPED_YET;
537 break;
538 }
539 out:
540 if (reason)
541 *reason = drop_reason;
542 return err;
543 }
544 EXPORT_SYMBOL(sock_queue_rcv_skb_reason);
545
__sk_receive_skb(struct sock * sk,struct sk_buff * skb,const int nested,unsigned int trim_cap,bool refcounted)546 int __sk_receive_skb(struct sock *sk, struct sk_buff *skb,
547 const int nested, unsigned int trim_cap, bool refcounted)
548 {
549 int rc = NET_RX_SUCCESS;
550
551 if (sk_filter_trim_cap(sk, skb, trim_cap))
552 goto discard_and_relse;
553
554 skb->dev = NULL;
555
556 if (sk_rcvqueues_full(sk, sk->sk_rcvbuf)) {
557 atomic_inc(&sk->sk_drops);
558 goto discard_and_relse;
559 }
560 if (nested)
561 bh_lock_sock_nested(sk);
562 else
563 bh_lock_sock(sk);
564 if (!sock_owned_by_user(sk)) {
565 /*
566 * trylock + unlock semantics:
567 */
568 mutex_acquire(&sk->sk_lock.dep_map, 0, 1, _RET_IP_);
569
570 rc = sk_backlog_rcv(sk, skb);
571
572 mutex_release(&sk->sk_lock.dep_map, _RET_IP_);
573 } else if (sk_add_backlog(sk, skb, READ_ONCE(sk->sk_rcvbuf))) {
574 bh_unlock_sock(sk);
575 atomic_inc(&sk->sk_drops);
576 goto discard_and_relse;
577 }
578
579 bh_unlock_sock(sk);
580 out:
581 if (refcounted)
582 sock_put(sk);
583 return rc;
584 discard_and_relse:
585 kfree_skb(skb);
586 goto out;
587 }
588 EXPORT_SYMBOL(__sk_receive_skb);
589
590 INDIRECT_CALLABLE_DECLARE(struct dst_entry *ip6_dst_check(struct dst_entry *,
591 u32));
592 INDIRECT_CALLABLE_DECLARE(struct dst_entry *ipv4_dst_check(struct dst_entry *,
593 u32));
__sk_dst_check(struct sock * sk,u32 cookie)594 struct dst_entry *__sk_dst_check(struct sock *sk, u32 cookie)
595 {
596 struct dst_entry *dst = __sk_dst_get(sk);
597
598 if (dst && dst->obsolete &&
599 INDIRECT_CALL_INET(dst->ops->check, ip6_dst_check, ipv4_dst_check,
600 dst, cookie) == NULL) {
601 sk_tx_queue_clear(sk);
602 WRITE_ONCE(sk->sk_dst_pending_confirm, 0);
603 RCU_INIT_POINTER(sk->sk_dst_cache, NULL);
604 dst_release(dst);
605 return NULL;
606 }
607
608 return dst;
609 }
610 EXPORT_SYMBOL(__sk_dst_check);
611
sk_dst_check(struct sock * sk,u32 cookie)612 struct dst_entry *sk_dst_check(struct sock *sk, u32 cookie)
613 {
614 struct dst_entry *dst = sk_dst_get(sk);
615
616 if (dst && dst->obsolete &&
617 INDIRECT_CALL_INET(dst->ops->check, ip6_dst_check, ipv4_dst_check,
618 dst, cookie) == NULL) {
619 sk_dst_reset(sk);
620 dst_release(dst);
621 return NULL;
622 }
623
624 return dst;
625 }
626 EXPORT_SYMBOL(sk_dst_check);
627
sock_bindtoindex_locked(struct sock * sk,int ifindex)628 static int sock_bindtoindex_locked(struct sock *sk, int ifindex)
629 {
630 int ret = -ENOPROTOOPT;
631 #ifdef CONFIG_NETDEVICES
632 struct net *net = sock_net(sk);
633
634 /* Sorry... */
635 ret = -EPERM;
636 if (sk->sk_bound_dev_if && !ns_capable(net->user_ns, CAP_NET_RAW))
637 goto out;
638
639 ret = -EINVAL;
640 if (ifindex < 0)
641 goto out;
642
643 /* Paired with all READ_ONCE() done locklessly. */
644 WRITE_ONCE(sk->sk_bound_dev_if, ifindex);
645
646 if (sk->sk_prot->rehash)
647 sk->sk_prot->rehash(sk);
648 sk_dst_reset(sk);
649
650 ret = 0;
651
652 out:
653 #endif
654
655 return ret;
656 }
657
sock_bindtoindex(struct sock * sk,int ifindex,bool lock_sk)658 int sock_bindtoindex(struct sock *sk, int ifindex, bool lock_sk)
659 {
660 int ret;
661
662 if (lock_sk)
663 lock_sock(sk);
664 ret = sock_bindtoindex_locked(sk, ifindex);
665 if (lock_sk)
666 release_sock(sk);
667
668 return ret;
669 }
670 EXPORT_SYMBOL(sock_bindtoindex);
671
sock_setbindtodevice(struct sock * sk,sockptr_t optval,int optlen)672 static int sock_setbindtodevice(struct sock *sk, sockptr_t optval, int optlen)
673 {
674 int ret = -ENOPROTOOPT;
675 #ifdef CONFIG_NETDEVICES
676 struct net *net = sock_net(sk);
677 char devname[IFNAMSIZ];
678 int index;
679
680 ret = -EINVAL;
681 if (optlen < 0)
682 goto out;
683
684 /* Bind this socket to a particular device like "eth0",
685 * as specified in the passed interface name. If the
686 * name is "" or the option length is zero the socket
687 * is not bound.
688 */
689 if (optlen > IFNAMSIZ - 1)
690 optlen = IFNAMSIZ - 1;
691 memset(devname, 0, sizeof(devname));
692
693 ret = -EFAULT;
694 if (copy_from_sockptr(devname, optval, optlen))
695 goto out;
696
697 index = 0;
698 if (devname[0] != '\0') {
699 struct net_device *dev;
700
701 rcu_read_lock();
702 dev = dev_get_by_name_rcu(net, devname);
703 if (dev)
704 index = dev->ifindex;
705 rcu_read_unlock();
706 ret = -ENODEV;
707 if (!dev)
708 goto out;
709 }
710
711 sockopt_lock_sock(sk);
712 ret = sock_bindtoindex_locked(sk, index);
713 sockopt_release_sock(sk);
714 out:
715 #endif
716
717 return ret;
718 }
719
sock_getbindtodevice(struct sock * sk,sockptr_t optval,sockptr_t optlen,int len)720 static int sock_getbindtodevice(struct sock *sk, sockptr_t optval,
721 sockptr_t optlen, int len)
722 {
723 int ret = -ENOPROTOOPT;
724 #ifdef CONFIG_NETDEVICES
725 int bound_dev_if = READ_ONCE(sk->sk_bound_dev_if);
726 struct net *net = sock_net(sk);
727 char devname[IFNAMSIZ];
728
729 if (bound_dev_if == 0) {
730 len = 0;
731 goto zero;
732 }
733
734 ret = -EINVAL;
735 if (len < IFNAMSIZ)
736 goto out;
737
738 ret = netdev_get_name(net, devname, bound_dev_if);
739 if (ret)
740 goto out;
741
742 len = strlen(devname) + 1;
743
744 ret = -EFAULT;
745 if (copy_to_sockptr(optval, devname, len))
746 goto out;
747
748 zero:
749 ret = -EFAULT;
750 if (copy_to_sockptr(optlen, &len, sizeof(int)))
751 goto out;
752
753 ret = 0;
754
755 out:
756 #endif
757
758 return ret;
759 }
760
sk_mc_loop(struct sock * sk)761 bool sk_mc_loop(struct sock *sk)
762 {
763 if (dev_recursion_level())
764 return false;
765 if (!sk)
766 return true;
767 /* IPV6_ADDRFORM can change sk->sk_family under us. */
768 switch (READ_ONCE(sk->sk_family)) {
769 case AF_INET:
770 return inet_sk(sk)->mc_loop;
771 #if IS_ENABLED(CONFIG_IPV6)
772 case AF_INET6:
773 return inet6_sk(sk)->mc_loop;
774 #endif
775 }
776 WARN_ON_ONCE(1);
777 return true;
778 }
779 EXPORT_SYMBOL(sk_mc_loop);
780
sock_set_reuseaddr(struct sock * sk)781 void sock_set_reuseaddr(struct sock *sk)
782 {
783 lock_sock(sk);
784 sk->sk_reuse = SK_CAN_REUSE;
785 release_sock(sk);
786 }
787 EXPORT_SYMBOL(sock_set_reuseaddr);
788
sock_set_reuseport(struct sock * sk)789 void sock_set_reuseport(struct sock *sk)
790 {
791 lock_sock(sk);
792 sk->sk_reuseport = true;
793 release_sock(sk);
794 }
795 EXPORT_SYMBOL(sock_set_reuseport);
796
sock_no_linger(struct sock * sk)797 void sock_no_linger(struct sock *sk)
798 {
799 lock_sock(sk);
800 WRITE_ONCE(sk->sk_lingertime, 0);
801 sock_set_flag(sk, SOCK_LINGER);
802 release_sock(sk);
803 }
804 EXPORT_SYMBOL(sock_no_linger);
805
sock_set_priority(struct sock * sk,u32 priority)806 void sock_set_priority(struct sock *sk, u32 priority)
807 {
808 lock_sock(sk);
809 WRITE_ONCE(sk->sk_priority, priority);
810 release_sock(sk);
811 }
812 EXPORT_SYMBOL(sock_set_priority);
813
sock_set_sndtimeo(struct sock * sk,s64 secs)814 void sock_set_sndtimeo(struct sock *sk, s64 secs)
815 {
816 lock_sock(sk);
817 if (secs && secs < MAX_SCHEDULE_TIMEOUT / HZ - 1)
818 WRITE_ONCE(sk->sk_sndtimeo, secs * HZ);
819 else
820 WRITE_ONCE(sk->sk_sndtimeo, MAX_SCHEDULE_TIMEOUT);
821 release_sock(sk);
822 }
823 EXPORT_SYMBOL(sock_set_sndtimeo);
824
__sock_set_timestamps(struct sock * sk,bool val,bool new,bool ns)825 static void __sock_set_timestamps(struct sock *sk, bool val, bool new, bool ns)
826 {
827 if (val) {
828 sock_valbool_flag(sk, SOCK_TSTAMP_NEW, new);
829 sock_valbool_flag(sk, SOCK_RCVTSTAMPNS, ns);
830 sock_set_flag(sk, SOCK_RCVTSTAMP);
831 sock_enable_timestamp(sk, SOCK_TIMESTAMP);
832 } else {
833 sock_reset_flag(sk, SOCK_RCVTSTAMP);
834 sock_reset_flag(sk, SOCK_RCVTSTAMPNS);
835 }
836 }
837
sock_enable_timestamps(struct sock * sk)838 void sock_enable_timestamps(struct sock *sk)
839 {
840 lock_sock(sk);
841 __sock_set_timestamps(sk, true, false, true);
842 release_sock(sk);
843 }
844 EXPORT_SYMBOL(sock_enable_timestamps);
845
sock_set_timestamp(struct sock * sk,int optname,bool valbool)846 void sock_set_timestamp(struct sock *sk, int optname, bool valbool)
847 {
848 switch (optname) {
849 case SO_TIMESTAMP_OLD:
850 __sock_set_timestamps(sk, valbool, false, false);
851 break;
852 case SO_TIMESTAMP_NEW:
853 __sock_set_timestamps(sk, valbool, true, false);
854 break;
855 case SO_TIMESTAMPNS_OLD:
856 __sock_set_timestamps(sk, valbool, false, true);
857 break;
858 case SO_TIMESTAMPNS_NEW:
859 __sock_set_timestamps(sk, valbool, true, true);
860 break;
861 }
862 }
863
sock_timestamping_bind_phc(struct sock * sk,int phc_index)864 static int sock_timestamping_bind_phc(struct sock *sk, int phc_index)
865 {
866 struct net *net = sock_net(sk);
867 struct net_device *dev = NULL;
868 bool match = false;
869 int *vclock_index;
870 int i, num;
871
872 if (sk->sk_bound_dev_if)
873 dev = dev_get_by_index(net, sk->sk_bound_dev_if);
874
875 if (!dev) {
876 pr_err("%s: sock not bind to device\n", __func__);
877 return -EOPNOTSUPP;
878 }
879
880 num = ethtool_get_phc_vclocks(dev, &vclock_index);
881 dev_put(dev);
882
883 for (i = 0; i < num; i++) {
884 if (*(vclock_index + i) == phc_index) {
885 match = true;
886 break;
887 }
888 }
889
890 if (num > 0)
891 kfree(vclock_index);
892
893 if (!match)
894 return -EINVAL;
895
896 WRITE_ONCE(sk->sk_bind_phc, phc_index);
897
898 return 0;
899 }
900
sock_set_timestamping(struct sock * sk,int optname,struct so_timestamping timestamping)901 int sock_set_timestamping(struct sock *sk, int optname,
902 struct so_timestamping timestamping)
903 {
904 int val = timestamping.flags;
905 int ret;
906
907 if (val & ~SOF_TIMESTAMPING_MASK)
908 return -EINVAL;
909
910 if (val & SOF_TIMESTAMPING_OPT_ID &&
911 !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)) {
912 if (sk_is_tcp(sk)) {
913 if ((1 << sk->sk_state) &
914 (TCPF_CLOSE | TCPF_LISTEN))
915 return -EINVAL;
916 atomic_set(&sk->sk_tskey, tcp_sk(sk)->snd_una);
917 } else {
918 atomic_set(&sk->sk_tskey, 0);
919 }
920 }
921
922 if (val & SOF_TIMESTAMPING_OPT_STATS &&
923 !(val & SOF_TIMESTAMPING_OPT_TSONLY))
924 return -EINVAL;
925
926 if (val & SOF_TIMESTAMPING_BIND_PHC) {
927 ret = sock_timestamping_bind_phc(sk, timestamping.bind_phc);
928 if (ret)
929 return ret;
930 }
931
932 WRITE_ONCE(sk->sk_tsflags, val);
933 sock_valbool_flag(sk, SOCK_TSTAMP_NEW, optname == SO_TIMESTAMPING_NEW);
934
935 if (val & SOF_TIMESTAMPING_RX_SOFTWARE)
936 sock_enable_timestamp(sk,
937 SOCK_TIMESTAMPING_RX_SOFTWARE);
938 else
939 sock_disable_timestamp(sk,
940 (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE));
941 return 0;
942 }
943
sock_set_keepalive(struct sock * sk)944 void sock_set_keepalive(struct sock *sk)
945 {
946 lock_sock(sk);
947 if (sk->sk_prot->keepalive)
948 sk->sk_prot->keepalive(sk, true);
949 sock_valbool_flag(sk, SOCK_KEEPOPEN, true);
950 release_sock(sk);
951 }
952 EXPORT_SYMBOL(sock_set_keepalive);
953
__sock_set_rcvbuf(struct sock * sk,int val)954 static void __sock_set_rcvbuf(struct sock *sk, int val)
955 {
956 /* Ensure val * 2 fits into an int, to prevent max_t() from treating it
957 * as a negative value.
958 */
959 val = min_t(int, val, INT_MAX / 2);
960 sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
961
962 /* We double it on the way in to account for "struct sk_buff" etc.
963 * overhead. Applications assume that the SO_RCVBUF setting they make
964 * will allow that much actual data to be received on that socket.
965 *
966 * Applications are unaware that "struct sk_buff" and other overheads
967 * allocate from the receive buffer during socket buffer allocation.
968 *
969 * And after considering the possible alternatives, returning the value
970 * we actually used in getsockopt is the most desirable behavior.
971 */
972 WRITE_ONCE(sk->sk_rcvbuf, max_t(int, val * 2, SOCK_MIN_RCVBUF));
973 }
974
sock_set_rcvbuf(struct sock * sk,int val)975 void sock_set_rcvbuf(struct sock *sk, int val)
976 {
977 lock_sock(sk);
978 __sock_set_rcvbuf(sk, val);
979 release_sock(sk);
980 }
981 EXPORT_SYMBOL(sock_set_rcvbuf);
982
__sock_set_mark(struct sock * sk,u32 val)983 static void __sock_set_mark(struct sock *sk, u32 val)
984 {
985 if (val != sk->sk_mark) {
986 WRITE_ONCE(sk->sk_mark, val);
987 sk_dst_reset(sk);
988 }
989 }
990
sock_set_mark(struct sock * sk,u32 val)991 void sock_set_mark(struct sock *sk, u32 val)
992 {
993 lock_sock(sk);
994 __sock_set_mark(sk, val);
995 release_sock(sk);
996 }
997 EXPORT_SYMBOL(sock_set_mark);
998
sock_release_reserved_memory(struct sock * sk,int bytes)999 static void sock_release_reserved_memory(struct sock *sk, int bytes)
1000 {
1001 /* Round down bytes to multiple of pages */
1002 bytes = round_down(bytes, PAGE_SIZE);
1003
1004 WARN_ON(bytes > sk->sk_reserved_mem);
1005 WRITE_ONCE(sk->sk_reserved_mem, sk->sk_reserved_mem - bytes);
1006 sk_mem_reclaim(sk);
1007 }
1008
sock_reserve_memory(struct sock * sk,int bytes)1009 static int sock_reserve_memory(struct sock *sk, int bytes)
1010 {
1011 long allocated;
1012 bool charged;
1013 int pages;
1014
1015 if (!mem_cgroup_sockets_enabled || !sk->sk_memcg || !sk_has_account(sk))
1016 return -EOPNOTSUPP;
1017
1018 if (!bytes)
1019 return 0;
1020
1021 pages = sk_mem_pages(bytes);
1022
1023 /* pre-charge to memcg */
1024 charged = mem_cgroup_charge_skmem(sk->sk_memcg, pages,
1025 GFP_KERNEL | __GFP_RETRY_MAYFAIL);
1026 if (!charged)
1027 return -ENOMEM;
1028
1029 /* pre-charge to forward_alloc */
1030 sk_memory_allocated_add(sk, pages);
1031 allocated = sk_memory_allocated(sk);
1032 /* If the system goes into memory pressure with this
1033 * precharge, give up and return error.
1034 */
1035 if (allocated > sk_prot_mem_limits(sk, 1)) {
1036 sk_memory_allocated_sub(sk, pages);
1037 mem_cgroup_uncharge_skmem(sk->sk_memcg, pages);
1038 return -ENOMEM;
1039 }
1040 sk_forward_alloc_add(sk, pages << PAGE_SHIFT);
1041
1042 WRITE_ONCE(sk->sk_reserved_mem,
1043 sk->sk_reserved_mem + (pages << PAGE_SHIFT));
1044
1045 return 0;
1046 }
1047
sockopt_lock_sock(struct sock * sk)1048 void sockopt_lock_sock(struct sock *sk)
1049 {
1050 /* When current->bpf_ctx is set, the setsockopt is called from
1051 * a bpf prog. bpf has ensured the sk lock has been
1052 * acquired before calling setsockopt().
1053 */
1054 if (has_current_bpf_ctx())
1055 return;
1056
1057 lock_sock(sk);
1058 }
1059 EXPORT_SYMBOL(sockopt_lock_sock);
1060
sockopt_release_sock(struct sock * sk)1061 void sockopt_release_sock(struct sock *sk)
1062 {
1063 if (has_current_bpf_ctx())
1064 return;
1065
1066 release_sock(sk);
1067 }
1068 EXPORT_SYMBOL(sockopt_release_sock);
1069
sockopt_ns_capable(struct user_namespace * ns,int cap)1070 bool sockopt_ns_capable(struct user_namespace *ns, int cap)
1071 {
1072 return has_current_bpf_ctx() || ns_capable(ns, cap);
1073 }
1074 EXPORT_SYMBOL(sockopt_ns_capable);
1075
sockopt_capable(int cap)1076 bool sockopt_capable(int cap)
1077 {
1078 return has_current_bpf_ctx() || capable(cap);
1079 }
1080 EXPORT_SYMBOL(sockopt_capable);
1081
1082 /*
1083 * This is meant for all protocols to use and covers goings on
1084 * at the socket level. Everything here is generic.
1085 */
1086
sk_setsockopt(struct sock * sk,int level,int optname,sockptr_t optval,unsigned int optlen)1087 int sk_setsockopt(struct sock *sk, int level, int optname,
1088 sockptr_t optval, unsigned int optlen)
1089 {
1090 struct so_timestamping timestamping;
1091 struct socket *sock = sk->sk_socket;
1092 struct sock_txtime sk_txtime;
1093 int val;
1094 int valbool;
1095 struct linger ling;
1096 int ret = 0;
1097
1098 /*
1099 * Options without arguments
1100 */
1101
1102 if (optname == SO_BINDTODEVICE)
1103 return sock_setbindtodevice(sk, optval, optlen);
1104
1105 if (optlen < sizeof(int))
1106 return -EINVAL;
1107
1108 if (copy_from_sockptr(&val, optval, sizeof(val)))
1109 return -EFAULT;
1110
1111 valbool = val ? 1 : 0;
1112
1113 sockopt_lock_sock(sk);
1114
1115 switch (optname) {
1116 case SO_DEBUG:
1117 if (val && !sockopt_capable(CAP_NET_ADMIN))
1118 ret = -EACCES;
1119 else
1120 sock_valbool_flag(sk, SOCK_DBG, valbool);
1121 break;
1122 case SO_REUSEADDR:
1123 sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE);
1124 break;
1125 case SO_REUSEPORT:
1126 sk->sk_reuseport = valbool;
1127 break;
1128 case SO_TYPE:
1129 case SO_PROTOCOL:
1130 case SO_DOMAIN:
1131 case SO_ERROR:
1132 ret = -ENOPROTOOPT;
1133 break;
1134 case SO_DONTROUTE:
1135 sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool);
1136 sk_dst_reset(sk);
1137 break;
1138 case SO_BROADCAST:
1139 sock_valbool_flag(sk, SOCK_BROADCAST, valbool);
1140 break;
1141 case SO_SNDBUF:
1142 /* Don't error on this BSD doesn't and if you think
1143 * about it this is right. Otherwise apps have to
1144 * play 'guess the biggest size' games. RCVBUF/SNDBUF
1145 * are treated in BSD as hints
1146 */
1147 val = min_t(u32, val, READ_ONCE(sysctl_wmem_max));
1148 set_sndbuf:
1149 /* Ensure val * 2 fits into an int, to prevent max_t()
1150 * from treating it as a negative value.
1151 */
1152 val = min_t(int, val, INT_MAX / 2);
1153 sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
1154 WRITE_ONCE(sk->sk_sndbuf,
1155 max_t(int, val * 2, SOCK_MIN_SNDBUF));
1156 /* Wake up sending tasks if we upped the value. */
1157 sk->sk_write_space(sk);
1158 break;
1159
1160 case SO_SNDBUFFORCE:
1161 if (!sockopt_capable(CAP_NET_ADMIN)) {
1162 ret = -EPERM;
1163 break;
1164 }
1165
1166 /* No negative values (to prevent underflow, as val will be
1167 * multiplied by 2).
1168 */
1169 if (val < 0)
1170 val = 0;
1171 goto set_sndbuf;
1172
1173 case SO_RCVBUF:
1174 /* Don't error on this BSD doesn't and if you think
1175 * about it this is right. Otherwise apps have to
1176 * play 'guess the biggest size' games. RCVBUF/SNDBUF
1177 * are treated in BSD as hints
1178 */
1179 __sock_set_rcvbuf(sk, min_t(u32, val, READ_ONCE(sysctl_rmem_max)));
1180 break;
1181
1182 case SO_RCVBUFFORCE:
1183 if (!sockopt_capable(CAP_NET_ADMIN)) {
1184 ret = -EPERM;
1185 break;
1186 }
1187
1188 /* No negative values (to prevent underflow, as val will be
1189 * multiplied by 2).
1190 */
1191 __sock_set_rcvbuf(sk, max(val, 0));
1192 break;
1193
1194 case SO_KEEPALIVE:
1195 if (sk->sk_prot->keepalive)
1196 sk->sk_prot->keepalive(sk, valbool);
1197 sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool);
1198 break;
1199
1200 case SO_OOBINLINE:
1201 sock_valbool_flag(sk, SOCK_URGINLINE, valbool);
1202 break;
1203
1204 case SO_NO_CHECK:
1205 sk->sk_no_check_tx = valbool;
1206 break;
1207
1208 case SO_PRIORITY:
1209 if ((val >= 0 && val <= 6) ||
1210 sockopt_ns_capable(sock_net(sk)->user_ns, CAP_NET_RAW) ||
1211 sockopt_ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
1212 WRITE_ONCE(sk->sk_priority, val);
1213 else
1214 ret = -EPERM;
1215 break;
1216
1217 case SO_LINGER:
1218 if (optlen < sizeof(ling)) {
1219 ret = -EINVAL; /* 1003.1g */
1220 break;
1221 }
1222 if (copy_from_sockptr(&ling, optval, sizeof(ling))) {
1223 ret = -EFAULT;
1224 break;
1225 }
1226 if (!ling.l_onoff) {
1227 sock_reset_flag(sk, SOCK_LINGER);
1228 } else {
1229 unsigned long t_sec = ling.l_linger;
1230
1231 if (t_sec >= MAX_SCHEDULE_TIMEOUT / HZ)
1232 WRITE_ONCE(sk->sk_lingertime, MAX_SCHEDULE_TIMEOUT);
1233 else
1234 WRITE_ONCE(sk->sk_lingertime, t_sec * HZ);
1235 sock_set_flag(sk, SOCK_LINGER);
1236 }
1237 break;
1238
1239 case SO_BSDCOMPAT:
1240 break;
1241
1242 case SO_PASSCRED:
1243 if (valbool)
1244 set_bit(SOCK_PASSCRED, &sock->flags);
1245 else
1246 clear_bit(SOCK_PASSCRED, &sock->flags);
1247 break;
1248
1249 case SO_TIMESTAMP_OLD:
1250 case SO_TIMESTAMP_NEW:
1251 case SO_TIMESTAMPNS_OLD:
1252 case SO_TIMESTAMPNS_NEW:
1253 sock_set_timestamp(sk, optname, valbool);
1254 break;
1255
1256 case SO_TIMESTAMPING_NEW:
1257 case SO_TIMESTAMPING_OLD:
1258 if (optlen == sizeof(timestamping)) {
1259 if (copy_from_sockptr(×tamping, optval,
1260 sizeof(timestamping))) {
1261 ret = -EFAULT;
1262 break;
1263 }
1264 } else {
1265 memset(×tamping, 0, sizeof(timestamping));
1266 timestamping.flags = val;
1267 }
1268 ret = sock_set_timestamping(sk, optname, timestamping);
1269 break;
1270
1271 case SO_RCVLOWAT:
1272 if (val < 0)
1273 val = INT_MAX;
1274 if (sock && sock->ops->set_rcvlowat)
1275 ret = sock->ops->set_rcvlowat(sk, val);
1276 else
1277 WRITE_ONCE(sk->sk_rcvlowat, val ? : 1);
1278 break;
1279
1280 case SO_RCVTIMEO_OLD:
1281 case SO_RCVTIMEO_NEW:
1282 ret = sock_set_timeout(&sk->sk_rcvtimeo, optval,
1283 optlen, optname == SO_RCVTIMEO_OLD);
1284 break;
1285
1286 case SO_SNDTIMEO_OLD:
1287 case SO_SNDTIMEO_NEW:
1288 ret = sock_set_timeout(&sk->sk_sndtimeo, optval,
1289 optlen, optname == SO_SNDTIMEO_OLD);
1290 break;
1291
1292 case SO_ATTACH_FILTER: {
1293 struct sock_fprog fprog;
1294
1295 ret = copy_bpf_fprog_from_user(&fprog, optval, optlen);
1296 if (!ret)
1297 ret = sk_attach_filter(&fprog, sk);
1298 break;
1299 }
1300 case SO_ATTACH_BPF:
1301 ret = -EINVAL;
1302 if (optlen == sizeof(u32)) {
1303 u32 ufd;
1304
1305 ret = -EFAULT;
1306 if (copy_from_sockptr(&ufd, optval, sizeof(ufd)))
1307 break;
1308
1309 ret = sk_attach_bpf(ufd, sk);
1310 }
1311 break;
1312
1313 case SO_ATTACH_REUSEPORT_CBPF: {
1314 struct sock_fprog fprog;
1315
1316 ret = copy_bpf_fprog_from_user(&fprog, optval, optlen);
1317 if (!ret)
1318 ret = sk_reuseport_attach_filter(&fprog, sk);
1319 break;
1320 }
1321 case SO_ATTACH_REUSEPORT_EBPF:
1322 ret = -EINVAL;
1323 if (optlen == sizeof(u32)) {
1324 u32 ufd;
1325
1326 ret = -EFAULT;
1327 if (copy_from_sockptr(&ufd, optval, sizeof(ufd)))
1328 break;
1329
1330 ret = sk_reuseport_attach_bpf(ufd, sk);
1331 }
1332 break;
1333
1334 case SO_DETACH_REUSEPORT_BPF:
1335 ret = reuseport_detach_prog(sk);
1336 break;
1337
1338 case SO_DETACH_FILTER:
1339 ret = sk_detach_filter(sk);
1340 break;
1341
1342 case SO_LOCK_FILTER:
1343 if (sock_flag(sk, SOCK_FILTER_LOCKED) && !valbool)
1344 ret = -EPERM;
1345 else
1346 sock_valbool_flag(sk, SOCK_FILTER_LOCKED, valbool);
1347 break;
1348
1349 case SO_PASSSEC:
1350 if (valbool)
1351 set_bit(SOCK_PASSSEC, &sock->flags);
1352 else
1353 clear_bit(SOCK_PASSSEC, &sock->flags);
1354 break;
1355 case SO_MARK:
1356 if (!sockopt_ns_capable(sock_net(sk)->user_ns, CAP_NET_RAW) &&
1357 !sockopt_ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) {
1358 ret = -EPERM;
1359 break;
1360 }
1361
1362 __sock_set_mark(sk, val);
1363 break;
1364 case SO_RCVMARK:
1365 sock_valbool_flag(sk, SOCK_RCVMARK, valbool);
1366 break;
1367
1368 case SO_RXQ_OVFL:
1369 sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool);
1370 break;
1371
1372 case SO_WIFI_STATUS:
1373 sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool);
1374 break;
1375
1376 case SO_PEEK_OFF:
1377 if (sock->ops->set_peek_off)
1378 ret = sock->ops->set_peek_off(sk, val);
1379 else
1380 ret = -EOPNOTSUPP;
1381 break;
1382
1383 case SO_NOFCS:
1384 sock_valbool_flag(sk, SOCK_NOFCS, valbool);
1385 break;
1386
1387 case SO_SELECT_ERR_QUEUE:
1388 sock_valbool_flag(sk, SOCK_SELECT_ERR_QUEUE, valbool);
1389 break;
1390
1391 #ifdef CONFIG_NET_RX_BUSY_POLL
1392 case SO_BUSY_POLL:
1393 /* allow unprivileged users to decrease the value */
1394 if ((val > sk->sk_ll_usec) && !sockopt_capable(CAP_NET_ADMIN))
1395 ret = -EPERM;
1396 else {
1397 if (val < 0)
1398 ret = -EINVAL;
1399 else
1400 WRITE_ONCE(sk->sk_ll_usec, val);
1401 }
1402 break;
1403 case SO_PREFER_BUSY_POLL:
1404 if (valbool && !sockopt_capable(CAP_NET_ADMIN))
1405 ret = -EPERM;
1406 else
1407 WRITE_ONCE(sk->sk_prefer_busy_poll, valbool);
1408 break;
1409 case SO_BUSY_POLL_BUDGET:
1410 if (val > READ_ONCE(sk->sk_busy_poll_budget) && !sockopt_capable(CAP_NET_ADMIN)) {
1411 ret = -EPERM;
1412 } else {
1413 if (val < 0 || val > U16_MAX)
1414 ret = -EINVAL;
1415 else
1416 WRITE_ONCE(sk->sk_busy_poll_budget, val);
1417 }
1418 break;
1419 #endif
1420
1421 case SO_MAX_PACING_RATE:
1422 {
1423 unsigned long ulval = (val == ~0U) ? ~0UL : (unsigned int)val;
1424
1425 if (sizeof(ulval) != sizeof(val) &&
1426 optlen >= sizeof(ulval) &&
1427 copy_from_sockptr(&ulval, optval, sizeof(ulval))) {
1428 ret = -EFAULT;
1429 break;
1430 }
1431 if (ulval != ~0UL)
1432 cmpxchg(&sk->sk_pacing_status,
1433 SK_PACING_NONE,
1434 SK_PACING_NEEDED);
1435 /* Pairs with READ_ONCE() from sk_getsockopt() */
1436 WRITE_ONCE(sk->sk_max_pacing_rate, ulval);
1437 sk->sk_pacing_rate = min(sk->sk_pacing_rate, ulval);
1438 break;
1439 }
1440 case SO_INCOMING_CPU:
1441 reuseport_update_incoming_cpu(sk, val);
1442 break;
1443
1444 case SO_CNX_ADVICE:
1445 if (val == 1)
1446 dst_negative_advice(sk);
1447 break;
1448
1449 case SO_ZEROCOPY:
1450 if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6) {
1451 if (!(sk_is_tcp(sk) ||
1452 (sk->sk_type == SOCK_DGRAM &&
1453 sk->sk_protocol == IPPROTO_UDP)))
1454 ret = -EOPNOTSUPP;
1455 } else if (sk->sk_family != PF_RDS) {
1456 ret = -EOPNOTSUPP;
1457 }
1458 if (!ret) {
1459 if (val < 0 || val > 1)
1460 ret = -EINVAL;
1461 else
1462 sock_valbool_flag(sk, SOCK_ZEROCOPY, valbool);
1463 }
1464 break;
1465
1466 case SO_TXTIME:
1467 if (optlen != sizeof(struct sock_txtime)) {
1468 ret = -EINVAL;
1469 break;
1470 } else if (copy_from_sockptr(&sk_txtime, optval,
1471 sizeof(struct sock_txtime))) {
1472 ret = -EFAULT;
1473 break;
1474 } else if (sk_txtime.flags & ~SOF_TXTIME_FLAGS_MASK) {
1475 ret = -EINVAL;
1476 break;
1477 }
1478 /* CLOCK_MONOTONIC is only used by sch_fq, and this packet
1479 * scheduler has enough safe guards.
1480 */
1481 if (sk_txtime.clockid != CLOCK_MONOTONIC &&
1482 !sockopt_ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) {
1483 ret = -EPERM;
1484 break;
1485 }
1486 sock_valbool_flag(sk, SOCK_TXTIME, true);
1487 sk->sk_clockid = sk_txtime.clockid;
1488 sk->sk_txtime_deadline_mode =
1489 !!(sk_txtime.flags & SOF_TXTIME_DEADLINE_MODE);
1490 sk->sk_txtime_report_errors =
1491 !!(sk_txtime.flags & SOF_TXTIME_REPORT_ERRORS);
1492 break;
1493
1494 case SO_BINDTOIFINDEX:
1495 ret = sock_bindtoindex_locked(sk, val);
1496 break;
1497
1498 case SO_BUF_LOCK:
1499 if (val & ~SOCK_BUF_LOCK_MASK) {
1500 ret = -EINVAL;
1501 break;
1502 }
1503 sk->sk_userlocks = val | (sk->sk_userlocks &
1504 ~SOCK_BUF_LOCK_MASK);
1505 break;
1506
1507 case SO_RESERVE_MEM:
1508 {
1509 int delta;
1510
1511 if (val < 0) {
1512 ret = -EINVAL;
1513 break;
1514 }
1515
1516 delta = val - sk->sk_reserved_mem;
1517 if (delta < 0)
1518 sock_release_reserved_memory(sk, -delta);
1519 else
1520 ret = sock_reserve_memory(sk, delta);
1521 break;
1522 }
1523
1524 case SO_TXREHASH:
1525 if (val < -1 || val > 1) {
1526 ret = -EINVAL;
1527 break;
1528 }
1529 if ((u8)val == SOCK_TXREHASH_DEFAULT)
1530 val = READ_ONCE(sock_net(sk)->core.sysctl_txrehash);
1531 /* Paired with READ_ONCE() in tcp_rtx_synack()
1532 * and sk_getsockopt().
1533 */
1534 WRITE_ONCE(sk->sk_txrehash, (u8)val);
1535 break;
1536
1537 default:
1538 ret = -ENOPROTOOPT;
1539 break;
1540 }
1541 sockopt_release_sock(sk);
1542 return ret;
1543 }
1544
sock_setsockopt(struct socket * sock,int level,int optname,sockptr_t optval,unsigned int optlen)1545 int sock_setsockopt(struct socket *sock, int level, int optname,
1546 sockptr_t optval, unsigned int optlen)
1547 {
1548 return sk_setsockopt(sock->sk, level, optname,
1549 optval, optlen);
1550 }
1551 EXPORT_SYMBOL(sock_setsockopt);
1552
sk_get_peer_cred(struct sock * sk)1553 static const struct cred *sk_get_peer_cred(struct sock *sk)
1554 {
1555 const struct cred *cred;
1556
1557 spin_lock(&sk->sk_peer_lock);
1558 cred = get_cred(sk->sk_peer_cred);
1559 spin_unlock(&sk->sk_peer_lock);
1560
1561 return cred;
1562 }
1563
cred_to_ucred(struct pid * pid,const struct cred * cred,struct ucred * ucred)1564 static void cred_to_ucred(struct pid *pid, const struct cred *cred,
1565 struct ucred *ucred)
1566 {
1567 ucred->pid = pid_vnr(pid);
1568 ucred->uid = ucred->gid = -1;
1569 if (cred) {
1570 struct user_namespace *current_ns = current_user_ns();
1571
1572 ucred->uid = from_kuid_munged(current_ns, cred->euid);
1573 ucred->gid = from_kgid_munged(current_ns, cred->egid);
1574 }
1575 }
1576
groups_to_user(sockptr_t dst,const struct group_info * src)1577 static int groups_to_user(sockptr_t dst, const struct group_info *src)
1578 {
1579 struct user_namespace *user_ns = current_user_ns();
1580 int i;
1581
1582 for (i = 0; i < src->ngroups; i++) {
1583 gid_t gid = from_kgid_munged(user_ns, src->gid[i]);
1584
1585 if (copy_to_sockptr_offset(dst, i * sizeof(gid), &gid, sizeof(gid)))
1586 return -EFAULT;
1587 }
1588
1589 return 0;
1590 }
1591
sk_getsockopt(struct sock * sk,int level,int optname,sockptr_t optval,sockptr_t optlen)1592 int sk_getsockopt(struct sock *sk, int level, int optname,
1593 sockptr_t optval, sockptr_t optlen)
1594 {
1595 struct socket *sock = sk->sk_socket;
1596
1597 union {
1598 int val;
1599 u64 val64;
1600 unsigned long ulval;
1601 struct linger ling;
1602 struct old_timeval32 tm32;
1603 struct __kernel_old_timeval tm;
1604 struct __kernel_sock_timeval stm;
1605 struct sock_txtime txtime;
1606 struct so_timestamping timestamping;
1607 } v;
1608
1609 int lv = sizeof(int);
1610 int len;
1611
1612 if (copy_from_sockptr(&len, optlen, sizeof(int)))
1613 return -EFAULT;
1614 if (len < 0)
1615 return -EINVAL;
1616
1617 memset(&v, 0, sizeof(v));
1618
1619 switch (optname) {
1620 case SO_DEBUG:
1621 v.val = sock_flag(sk, SOCK_DBG);
1622 break;
1623
1624 case SO_DONTROUTE:
1625 v.val = sock_flag(sk, SOCK_LOCALROUTE);
1626 break;
1627
1628 case SO_BROADCAST:
1629 v.val = sock_flag(sk, SOCK_BROADCAST);
1630 break;
1631
1632 case SO_SNDBUF:
1633 v.val = READ_ONCE(sk->sk_sndbuf);
1634 break;
1635
1636 case SO_RCVBUF:
1637 v.val = READ_ONCE(sk->sk_rcvbuf);
1638 break;
1639
1640 case SO_REUSEADDR:
1641 v.val = sk->sk_reuse;
1642 break;
1643
1644 case SO_REUSEPORT:
1645 v.val = sk->sk_reuseport;
1646 break;
1647
1648 case SO_KEEPALIVE:
1649 v.val = sock_flag(sk, SOCK_KEEPOPEN);
1650 break;
1651
1652 case SO_TYPE:
1653 v.val = sk->sk_type;
1654 break;
1655
1656 case SO_PROTOCOL:
1657 v.val = sk->sk_protocol;
1658 break;
1659
1660 case SO_DOMAIN:
1661 v.val = sk->sk_family;
1662 break;
1663
1664 case SO_ERROR:
1665 v.val = -sock_error(sk);
1666 if (v.val == 0)
1667 v.val = xchg(&sk->sk_err_soft, 0);
1668 break;
1669
1670 case SO_OOBINLINE:
1671 v.val = sock_flag(sk, SOCK_URGINLINE);
1672 break;
1673
1674 case SO_NO_CHECK:
1675 v.val = sk->sk_no_check_tx;
1676 break;
1677
1678 case SO_PRIORITY:
1679 v.val = READ_ONCE(sk->sk_priority);
1680 break;
1681
1682 case SO_LINGER:
1683 lv = sizeof(v.ling);
1684 v.ling.l_onoff = sock_flag(sk, SOCK_LINGER);
1685 v.ling.l_linger = READ_ONCE(sk->sk_lingertime) / HZ;
1686 break;
1687
1688 case SO_BSDCOMPAT:
1689 break;
1690
1691 case SO_TIMESTAMP_OLD:
1692 v.val = sock_flag(sk, SOCK_RCVTSTAMP) &&
1693 !sock_flag(sk, SOCK_TSTAMP_NEW) &&
1694 !sock_flag(sk, SOCK_RCVTSTAMPNS);
1695 break;
1696
1697 case SO_TIMESTAMPNS_OLD:
1698 v.val = sock_flag(sk, SOCK_RCVTSTAMPNS) && !sock_flag(sk, SOCK_TSTAMP_NEW);
1699 break;
1700
1701 case SO_TIMESTAMP_NEW:
1702 v.val = sock_flag(sk, SOCK_RCVTSTAMP) && sock_flag(sk, SOCK_TSTAMP_NEW);
1703 break;
1704
1705 case SO_TIMESTAMPNS_NEW:
1706 v.val = sock_flag(sk, SOCK_RCVTSTAMPNS) && sock_flag(sk, SOCK_TSTAMP_NEW);
1707 break;
1708
1709 case SO_TIMESTAMPING_OLD:
1710 case SO_TIMESTAMPING_NEW:
1711 lv = sizeof(v.timestamping);
1712 /* For the later-added case SO_TIMESTAMPING_NEW: Be strict about only
1713 * returning the flags when they were set through the same option.
1714 * Don't change the beviour for the old case SO_TIMESTAMPING_OLD.
1715 */
1716 if (optname == SO_TIMESTAMPING_OLD || sock_flag(sk, SOCK_TSTAMP_NEW)) {
1717 v.timestamping.flags = READ_ONCE(sk->sk_tsflags);
1718 v.timestamping.bind_phc = READ_ONCE(sk->sk_bind_phc);
1719 }
1720 break;
1721
1722 case SO_RCVTIMEO_OLD:
1723 case SO_RCVTIMEO_NEW:
1724 lv = sock_get_timeout(READ_ONCE(sk->sk_rcvtimeo), &v,
1725 SO_RCVTIMEO_OLD == optname);
1726 break;
1727
1728 case SO_SNDTIMEO_OLD:
1729 case SO_SNDTIMEO_NEW:
1730 lv = sock_get_timeout(READ_ONCE(sk->sk_sndtimeo), &v,
1731 SO_SNDTIMEO_OLD == optname);
1732 break;
1733
1734 case SO_RCVLOWAT:
1735 v.val = READ_ONCE(sk->sk_rcvlowat);
1736 break;
1737
1738 case SO_SNDLOWAT:
1739 v.val = 1;
1740 break;
1741
1742 case SO_PASSCRED:
1743 v.val = !!test_bit(SOCK_PASSCRED, &sock->flags);
1744 break;
1745
1746 case SO_PEERCRED:
1747 {
1748 struct ucred peercred;
1749 if (len > sizeof(peercred))
1750 len = sizeof(peercred);
1751
1752 spin_lock(&sk->sk_peer_lock);
1753 cred_to_ucred(sk->sk_peer_pid, sk->sk_peer_cred, &peercred);
1754 spin_unlock(&sk->sk_peer_lock);
1755
1756 if (copy_to_sockptr(optval, &peercred, len))
1757 return -EFAULT;
1758 goto lenout;
1759 }
1760
1761 case SO_PEERGROUPS:
1762 {
1763 const struct cred *cred;
1764 int ret, n;
1765
1766 cred = sk_get_peer_cred(sk);
1767 if (!cred)
1768 return -ENODATA;
1769
1770 n = cred->group_info->ngroups;
1771 if (len < n * sizeof(gid_t)) {
1772 len = n * sizeof(gid_t);
1773 put_cred(cred);
1774 return copy_to_sockptr(optlen, &len, sizeof(int)) ? -EFAULT : -ERANGE;
1775 }
1776 len = n * sizeof(gid_t);
1777
1778 ret = groups_to_user(optval, cred->group_info);
1779 put_cred(cred);
1780 if (ret)
1781 return ret;
1782 goto lenout;
1783 }
1784
1785 case SO_PEERNAME:
1786 {
1787 struct sockaddr_storage address;
1788
1789 lv = sock->ops->getname(sock, (struct sockaddr *)&address, 2);
1790 if (lv < 0)
1791 return -ENOTCONN;
1792 if (lv < len)
1793 return -EINVAL;
1794 if (copy_to_sockptr(optval, &address, len))
1795 return -EFAULT;
1796 goto lenout;
1797 }
1798
1799 /* Dubious BSD thing... Probably nobody even uses it, but
1800 * the UNIX standard wants it for whatever reason... -DaveM
1801 */
1802 case SO_ACCEPTCONN:
1803 v.val = sk->sk_state == TCP_LISTEN;
1804 break;
1805
1806 case SO_PASSSEC:
1807 v.val = !!test_bit(SOCK_PASSSEC, &sock->flags);
1808 break;
1809
1810 case SO_PEERSEC:
1811 return security_socket_getpeersec_stream(sock, optval.user, optlen.user, len);
1812
1813 case SO_MARK:
1814 v.val = READ_ONCE(sk->sk_mark);
1815 break;
1816
1817 case SO_RCVMARK:
1818 v.val = sock_flag(sk, SOCK_RCVMARK);
1819 break;
1820
1821 case SO_RXQ_OVFL:
1822 v.val = sock_flag(sk, SOCK_RXQ_OVFL);
1823 break;
1824
1825 case SO_WIFI_STATUS:
1826 v.val = sock_flag(sk, SOCK_WIFI_STATUS);
1827 break;
1828
1829 case SO_PEEK_OFF:
1830 if (!sock->ops->set_peek_off)
1831 return -EOPNOTSUPP;
1832
1833 v.val = READ_ONCE(sk->sk_peek_off);
1834 break;
1835 case SO_NOFCS:
1836 v.val = sock_flag(sk, SOCK_NOFCS);
1837 break;
1838
1839 case SO_BINDTODEVICE:
1840 return sock_getbindtodevice(sk, optval, optlen, len);
1841
1842 case SO_GET_FILTER:
1843 len = sk_get_filter(sk, optval, len);
1844 if (len < 0)
1845 return len;
1846
1847 goto lenout;
1848
1849 case SO_LOCK_FILTER:
1850 v.val = sock_flag(sk, SOCK_FILTER_LOCKED);
1851 break;
1852
1853 case SO_BPF_EXTENSIONS:
1854 v.val = bpf_tell_extensions();
1855 break;
1856
1857 case SO_SELECT_ERR_QUEUE:
1858 v.val = sock_flag(sk, SOCK_SELECT_ERR_QUEUE);
1859 break;
1860
1861 #ifdef CONFIG_NET_RX_BUSY_POLL
1862 case SO_BUSY_POLL:
1863 v.val = READ_ONCE(sk->sk_ll_usec);
1864 break;
1865 case SO_PREFER_BUSY_POLL:
1866 v.val = READ_ONCE(sk->sk_prefer_busy_poll);
1867 break;
1868 #endif
1869
1870 case SO_MAX_PACING_RATE:
1871 /* The READ_ONCE() pair with the WRITE_ONCE() in sk_setsockopt() */
1872 if (sizeof(v.ulval) != sizeof(v.val) && len >= sizeof(v.ulval)) {
1873 lv = sizeof(v.ulval);
1874 v.ulval = READ_ONCE(sk->sk_max_pacing_rate);
1875 } else {
1876 /* 32bit version */
1877 v.val = min_t(unsigned long, ~0U,
1878 READ_ONCE(sk->sk_max_pacing_rate));
1879 }
1880 break;
1881
1882 case SO_INCOMING_CPU:
1883 v.val = READ_ONCE(sk->sk_incoming_cpu);
1884 break;
1885
1886 case SO_MEMINFO:
1887 {
1888 u32 meminfo[SK_MEMINFO_VARS];
1889
1890 sk_get_meminfo(sk, meminfo);
1891
1892 len = min_t(unsigned int, len, sizeof(meminfo));
1893 if (copy_to_sockptr(optval, &meminfo, len))
1894 return -EFAULT;
1895
1896 goto lenout;
1897 }
1898
1899 #ifdef CONFIG_NET_RX_BUSY_POLL
1900 case SO_INCOMING_NAPI_ID:
1901 v.val = READ_ONCE(sk->sk_napi_id);
1902
1903 /* aggregate non-NAPI IDs down to 0 */
1904 if (v.val < MIN_NAPI_ID)
1905 v.val = 0;
1906
1907 break;
1908 #endif
1909
1910 case SO_COOKIE:
1911 lv = sizeof(u64);
1912 if (len < lv)
1913 return -EINVAL;
1914 v.val64 = sock_gen_cookie(sk);
1915 break;
1916
1917 case SO_ZEROCOPY:
1918 v.val = sock_flag(sk, SOCK_ZEROCOPY);
1919 break;
1920
1921 case SO_TXTIME:
1922 lv = sizeof(v.txtime);
1923 v.txtime.clockid = sk->sk_clockid;
1924 v.txtime.flags |= sk->sk_txtime_deadline_mode ?
1925 SOF_TXTIME_DEADLINE_MODE : 0;
1926 v.txtime.flags |= sk->sk_txtime_report_errors ?
1927 SOF_TXTIME_REPORT_ERRORS : 0;
1928 break;
1929
1930 case SO_BINDTOIFINDEX:
1931 v.val = READ_ONCE(sk->sk_bound_dev_if);
1932 break;
1933
1934 case SO_NETNS_COOKIE:
1935 lv = sizeof(u64);
1936 if (len != lv)
1937 return -EINVAL;
1938 v.val64 = sock_net(sk)->net_cookie;
1939 break;
1940
1941 case SO_BUF_LOCK:
1942 v.val = sk->sk_userlocks & SOCK_BUF_LOCK_MASK;
1943 break;
1944
1945 case SO_RESERVE_MEM:
1946 v.val = READ_ONCE(sk->sk_reserved_mem);
1947 break;
1948
1949 case SO_TXREHASH:
1950 /* Paired with WRITE_ONCE() in sk_setsockopt() */
1951 v.val = READ_ONCE(sk->sk_txrehash);
1952 break;
1953
1954 default:
1955 /* We implement the SO_SNDLOWAT etc to not be settable
1956 * (1003.1g 7).
1957 */
1958 return -ENOPROTOOPT;
1959 }
1960
1961 if (len > lv)
1962 len = lv;
1963 if (copy_to_sockptr(optval, &v, len))
1964 return -EFAULT;
1965 lenout:
1966 if (copy_to_sockptr(optlen, &len, sizeof(int)))
1967 return -EFAULT;
1968 return 0;
1969 }
1970
sock_getsockopt(struct socket * sock,int level,int optname,char __user * optval,int __user * optlen)1971 int sock_getsockopt(struct socket *sock, int level, int optname,
1972 char __user *optval, int __user *optlen)
1973 {
1974 return sk_getsockopt(sock->sk, level, optname,
1975 USER_SOCKPTR(optval),
1976 USER_SOCKPTR(optlen));
1977 }
1978
1979 /*
1980 * Initialize an sk_lock.
1981 *
1982 * (We also register the sk_lock with the lock validator.)
1983 */
sock_lock_init(struct sock * sk)1984 static inline void sock_lock_init(struct sock *sk)
1985 {
1986 if (sk->sk_kern_sock)
1987 sock_lock_init_class_and_name(
1988 sk,
1989 af_family_kern_slock_key_strings[sk->sk_family],
1990 af_family_kern_slock_keys + sk->sk_family,
1991 af_family_kern_key_strings[sk->sk_family],
1992 af_family_kern_keys + sk->sk_family);
1993 else
1994 sock_lock_init_class_and_name(
1995 sk,
1996 af_family_slock_key_strings[sk->sk_family],
1997 af_family_slock_keys + sk->sk_family,
1998 af_family_key_strings[sk->sk_family],
1999 af_family_keys + sk->sk_family);
2000 }
2001
2002 /*
2003 * Copy all fields from osk to nsk but nsk->sk_refcnt must not change yet,
2004 * even temporarly, because of RCU lookups. sk_node should also be left as is.
2005 * We must not copy fields between sk_dontcopy_begin and sk_dontcopy_end
2006 */
sock_copy(struct sock * nsk,const struct sock * osk)2007 static void sock_copy(struct sock *nsk, const struct sock *osk)
2008 {
2009 const struct proto *prot = READ_ONCE(osk->sk_prot);
2010 #ifdef CONFIG_SECURITY_NETWORK
2011 void *sptr = nsk->sk_security;
2012 #endif
2013
2014 /* If we move sk_tx_queue_mapping out of the private section,
2015 * we must check if sk_tx_queue_clear() is called after
2016 * sock_copy() in sk_clone_lock().
2017 */
2018 BUILD_BUG_ON(offsetof(struct sock, sk_tx_queue_mapping) <
2019 offsetof(struct sock, sk_dontcopy_begin) ||
2020 offsetof(struct sock, sk_tx_queue_mapping) >=
2021 offsetof(struct sock, sk_dontcopy_end));
2022
2023 memcpy(nsk, osk, offsetof(struct sock, sk_dontcopy_begin));
2024
2025 memcpy(&nsk->sk_dontcopy_end, &osk->sk_dontcopy_end,
2026 prot->obj_size - offsetof(struct sock, sk_dontcopy_end));
2027
2028 #ifdef CONFIG_SECURITY_NETWORK
2029 nsk->sk_security = sptr;
2030 security_sk_clone(osk, nsk);
2031 #endif
2032 }
2033
sk_prot_alloc(struct proto * prot,gfp_t priority,int family)2034 static struct sock *sk_prot_alloc(struct proto *prot, gfp_t priority,
2035 int family)
2036 {
2037 struct sock *sk;
2038 struct kmem_cache *slab;
2039
2040 slab = prot->slab;
2041 if (slab != NULL) {
2042 sk = kmem_cache_alloc(slab, priority & ~__GFP_ZERO);
2043 if (!sk)
2044 return sk;
2045 if (want_init_on_alloc(priority))
2046 sk_prot_clear_nulls(sk, prot->obj_size);
2047 } else
2048 sk = kmalloc(prot->obj_size, priority);
2049
2050 if (sk != NULL) {
2051 if (security_sk_alloc(sk, family, priority))
2052 goto out_free;
2053
2054 trace_android_rvh_sk_alloc(sk);
2055
2056 if (!try_module_get(prot->owner))
2057 goto out_free_sec;
2058 }
2059
2060 return sk;
2061
2062 out_free_sec:
2063 security_sk_free(sk);
2064 trace_android_rvh_sk_free(sk);
2065 out_free:
2066 if (slab != NULL)
2067 kmem_cache_free(slab, sk);
2068 else
2069 kfree(sk);
2070 return NULL;
2071 }
2072
sk_prot_free(struct proto * prot,struct sock * sk)2073 static void sk_prot_free(struct proto *prot, struct sock *sk)
2074 {
2075 struct kmem_cache *slab;
2076 struct module *owner;
2077
2078 owner = prot->owner;
2079 slab = prot->slab;
2080
2081 cgroup_sk_free(&sk->sk_cgrp_data);
2082 mem_cgroup_sk_free(sk);
2083 security_sk_free(sk);
2084 trace_android_rvh_sk_free(sk);
2085 if (slab != NULL)
2086 kmem_cache_free(slab, sk);
2087 else
2088 kfree(sk);
2089 module_put(owner);
2090 }
2091
2092 /**
2093 * sk_alloc - All socket objects are allocated here
2094 * @net: the applicable net namespace
2095 * @family: protocol family
2096 * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
2097 * @prot: struct proto associated with this new sock instance
2098 * @kern: is this to be a kernel socket?
2099 */
sk_alloc(struct net * net,int family,gfp_t priority,struct proto * prot,int kern)2100 struct sock *sk_alloc(struct net *net, int family, gfp_t priority,
2101 struct proto *prot, int kern)
2102 {
2103 struct sock *sk;
2104
2105 sk = sk_prot_alloc(prot, priority | __GFP_ZERO, family);
2106 if (sk) {
2107 sk->sk_family = family;
2108 /*
2109 * See comment in struct sock definition to understand
2110 * why we need sk_prot_creator -acme
2111 */
2112 sk->sk_prot = sk->sk_prot_creator = prot;
2113 sk->sk_kern_sock = kern;
2114 sock_lock_init(sk);
2115 sk->sk_net_refcnt = kern ? 0 : 1;
2116 if (likely(sk->sk_net_refcnt)) {
2117 get_net_track(net, &sk->ns_tracker, priority);
2118 sock_inuse_add(net, 1);
2119 }
2120
2121 sock_net_set(sk, net);
2122 refcount_set(&sk->sk_wmem_alloc, 1);
2123
2124 mem_cgroup_sk_alloc(sk);
2125 cgroup_sk_alloc(&sk->sk_cgrp_data);
2126 sock_update_classid(&sk->sk_cgrp_data);
2127 sock_update_netprioidx(&sk->sk_cgrp_data);
2128 sk_tx_queue_clear(sk);
2129 }
2130
2131 return sk;
2132 }
2133 EXPORT_SYMBOL(sk_alloc);
2134
2135 /* Sockets having SOCK_RCU_FREE will call this function after one RCU
2136 * grace period. This is the case for UDP sockets and TCP listeners.
2137 */
__sk_destruct(struct rcu_head * head)2138 static void __sk_destruct(struct rcu_head *head)
2139 {
2140 struct sock *sk = container_of(head, struct sock, sk_rcu);
2141 struct sk_filter *filter;
2142
2143 if (sk->sk_destruct)
2144 sk->sk_destruct(sk);
2145
2146 filter = rcu_dereference_check(sk->sk_filter,
2147 refcount_read(&sk->sk_wmem_alloc) == 0);
2148 if (filter) {
2149 sk_filter_uncharge(sk, filter);
2150 RCU_INIT_POINTER(sk->sk_filter, NULL);
2151 }
2152
2153 sock_disable_timestamp(sk, SK_FLAGS_TIMESTAMP);
2154
2155 #ifdef CONFIG_BPF_SYSCALL
2156 bpf_sk_storage_free(sk);
2157 #endif
2158
2159 if (atomic_read(&sk->sk_omem_alloc))
2160 pr_debug("%s: optmem leakage (%d bytes) detected\n",
2161 __func__, atomic_read(&sk->sk_omem_alloc));
2162
2163 if (sk->sk_frag.page) {
2164 put_page(sk->sk_frag.page);
2165 sk->sk_frag.page = NULL;
2166 }
2167
2168 /* We do not need to acquire sk->sk_peer_lock, we are the last user. */
2169 put_cred(sk->sk_peer_cred);
2170 put_pid(sk->sk_peer_pid);
2171
2172 if (likely(sk->sk_net_refcnt))
2173 put_net_track(sock_net(sk), &sk->ns_tracker);
2174 sk_prot_free(sk->sk_prot_creator, sk);
2175 }
2176
sk_destruct(struct sock * sk)2177 void sk_destruct(struct sock *sk)
2178 {
2179 bool use_call_rcu = sock_flag(sk, SOCK_RCU_FREE);
2180
2181 if (rcu_access_pointer(sk->sk_reuseport_cb)) {
2182 reuseport_detach_sock(sk);
2183 use_call_rcu = true;
2184 }
2185
2186 if (use_call_rcu)
2187 call_rcu(&sk->sk_rcu, __sk_destruct);
2188 else
2189 __sk_destruct(&sk->sk_rcu);
2190 }
2191
__sk_free(struct sock * sk)2192 static void __sk_free(struct sock *sk)
2193 {
2194 if (likely(sk->sk_net_refcnt))
2195 sock_inuse_add(sock_net(sk), -1);
2196
2197 if (unlikely(sk->sk_net_refcnt && sock_diag_has_destroy_listeners(sk)))
2198 sock_diag_broadcast_destroy(sk);
2199 else
2200 sk_destruct(sk);
2201 }
2202
sk_free(struct sock * sk)2203 void sk_free(struct sock *sk)
2204 {
2205 /*
2206 * We subtract one from sk_wmem_alloc and can know if
2207 * some packets are still in some tx queue.
2208 * If not null, sock_wfree() will call __sk_free(sk) later
2209 */
2210 if (refcount_dec_and_test(&sk->sk_wmem_alloc))
2211 __sk_free(sk);
2212 }
2213 EXPORT_SYMBOL(sk_free);
2214
sk_init_common(struct sock * sk)2215 static void sk_init_common(struct sock *sk)
2216 {
2217 skb_queue_head_init(&sk->sk_receive_queue);
2218 skb_queue_head_init(&sk->sk_write_queue);
2219 skb_queue_head_init(&sk->sk_error_queue);
2220
2221 rwlock_init(&sk->sk_callback_lock);
2222 lockdep_set_class_and_name(&sk->sk_receive_queue.lock,
2223 af_rlock_keys + sk->sk_family,
2224 af_family_rlock_key_strings[sk->sk_family]);
2225 lockdep_set_class_and_name(&sk->sk_write_queue.lock,
2226 af_wlock_keys + sk->sk_family,
2227 af_family_wlock_key_strings[sk->sk_family]);
2228 lockdep_set_class_and_name(&sk->sk_error_queue.lock,
2229 af_elock_keys + sk->sk_family,
2230 af_family_elock_key_strings[sk->sk_family]);
2231 lockdep_set_class_and_name(&sk->sk_callback_lock,
2232 af_callback_keys + sk->sk_family,
2233 af_family_clock_key_strings[sk->sk_family]);
2234 }
2235
2236 /**
2237 * sk_clone_lock - clone a socket, and lock its clone
2238 * @sk: the socket to clone
2239 * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
2240 *
2241 * Caller must unlock socket even in error path (bh_unlock_sock(newsk))
2242 */
sk_clone_lock(const struct sock * sk,const gfp_t priority)2243 struct sock *sk_clone_lock(const struct sock *sk, const gfp_t priority)
2244 {
2245 struct proto *prot = READ_ONCE(sk->sk_prot);
2246 struct sk_filter *filter;
2247 bool is_charged = true;
2248 struct sock *newsk;
2249
2250 newsk = sk_prot_alloc(prot, priority, sk->sk_family);
2251 if (!newsk)
2252 goto out;
2253
2254 sock_copy(newsk, sk);
2255
2256 newsk->sk_prot_creator = prot;
2257
2258 /* SANITY */
2259 if (likely(newsk->sk_net_refcnt)) {
2260 get_net_track(sock_net(newsk), &newsk->ns_tracker, priority);
2261 sock_inuse_add(sock_net(newsk), 1);
2262 }
2263 sk_node_init(&newsk->sk_node);
2264 sock_lock_init(newsk);
2265 bh_lock_sock(newsk);
2266 newsk->sk_backlog.head = newsk->sk_backlog.tail = NULL;
2267 newsk->sk_backlog.len = 0;
2268
2269 atomic_set(&newsk->sk_rmem_alloc, 0);
2270
2271 /* sk_wmem_alloc set to one (see sk_free() and sock_wfree()) */
2272 refcount_set(&newsk->sk_wmem_alloc, 1);
2273
2274 atomic_set(&newsk->sk_omem_alloc, 0);
2275 sk_init_common(newsk);
2276
2277 newsk->sk_dst_cache = NULL;
2278 newsk->sk_dst_pending_confirm = 0;
2279 newsk->sk_wmem_queued = 0;
2280 newsk->sk_forward_alloc = 0;
2281 newsk->sk_reserved_mem = 0;
2282 atomic_set(&newsk->sk_drops, 0);
2283 newsk->sk_send_head = NULL;
2284 newsk->sk_userlocks = sk->sk_userlocks & ~SOCK_BINDPORT_LOCK;
2285 atomic_set(&newsk->sk_zckey, 0);
2286
2287 sock_reset_flag(newsk, SOCK_DONE);
2288
2289 /* sk->sk_memcg will be populated at accept() time */
2290 newsk->sk_memcg = NULL;
2291
2292 cgroup_sk_clone(&newsk->sk_cgrp_data);
2293
2294 rcu_read_lock();
2295 filter = rcu_dereference(sk->sk_filter);
2296 if (filter != NULL)
2297 /* though it's an empty new sock, the charging may fail
2298 * if sysctl_optmem_max was changed between creation of
2299 * original socket and cloning
2300 */
2301 is_charged = sk_filter_charge(newsk, filter);
2302 RCU_INIT_POINTER(newsk->sk_filter, filter);
2303 rcu_read_unlock();
2304
2305 if (unlikely(!is_charged || xfrm_sk_clone_policy(newsk, sk))) {
2306 /* We need to make sure that we don't uncharge the new
2307 * socket if we couldn't charge it in the first place
2308 * as otherwise we uncharge the parent's filter.
2309 */
2310 if (!is_charged)
2311 RCU_INIT_POINTER(newsk->sk_filter, NULL);
2312 sk_free_unlock_clone(newsk);
2313 newsk = NULL;
2314 goto out;
2315 }
2316 RCU_INIT_POINTER(newsk->sk_reuseport_cb, NULL);
2317
2318 if (bpf_sk_storage_clone(sk, newsk)) {
2319 sk_free_unlock_clone(newsk);
2320 newsk = NULL;
2321 goto out;
2322 }
2323
2324 /* Clear sk_user_data if parent had the pointer tagged
2325 * as not suitable for copying when cloning.
2326 */
2327 if (sk_user_data_is_nocopy(newsk))
2328 newsk->sk_user_data = NULL;
2329
2330 newsk->sk_err = 0;
2331 newsk->sk_err_soft = 0;
2332 newsk->sk_priority = 0;
2333 newsk->sk_incoming_cpu = raw_smp_processor_id();
2334
2335 /* Before updating sk_refcnt, we must commit prior changes to memory
2336 * (Documentation/RCU/rculist_nulls.rst for details)
2337 */
2338 smp_wmb();
2339 refcount_set(&newsk->sk_refcnt, 2);
2340
2341 /* Increment the counter in the same struct proto as the master
2342 * sock (sk_refcnt_debug_inc uses newsk->sk_prot->socks, that
2343 * is the same as sk->sk_prot->socks, as this field was copied
2344 * with memcpy).
2345 *
2346 * This _changes_ the previous behaviour, where
2347 * tcp_create_openreq_child always was incrementing the
2348 * equivalent to tcp_prot->socks (inet_sock_nr), so this have
2349 * to be taken into account in all callers. -acme
2350 */
2351 sk_refcnt_debug_inc(newsk);
2352 sk_set_socket(newsk, NULL);
2353 sk_tx_queue_clear(newsk);
2354 RCU_INIT_POINTER(newsk->sk_wq, NULL);
2355
2356 if (newsk->sk_prot->sockets_allocated)
2357 sk_sockets_allocated_inc(newsk);
2358
2359 if (sock_needs_netstamp(sk) && newsk->sk_flags & SK_FLAGS_TIMESTAMP)
2360 net_enable_timestamp();
2361 out:
2362 return newsk;
2363 }
2364 EXPORT_SYMBOL_GPL(sk_clone_lock);
2365
sk_free_unlock_clone(struct sock * sk)2366 void sk_free_unlock_clone(struct sock *sk)
2367 {
2368 /* It is still raw copy of parent, so invalidate
2369 * destructor and make plain sk_free() */
2370 sk->sk_destruct = NULL;
2371 bh_unlock_sock(sk);
2372 sk_free(sk);
2373 }
2374 EXPORT_SYMBOL_GPL(sk_free_unlock_clone);
2375
sk_trim_gso_size(struct sock * sk)2376 static void sk_trim_gso_size(struct sock *sk)
2377 {
2378 if (sk->sk_gso_max_size <= GSO_LEGACY_MAX_SIZE)
2379 return;
2380 #if IS_ENABLED(CONFIG_IPV6)
2381 if (sk->sk_family == AF_INET6 &&
2382 sk_is_tcp(sk) &&
2383 !ipv6_addr_v4mapped(&sk->sk_v6_rcv_saddr))
2384 return;
2385 #endif
2386 sk->sk_gso_max_size = GSO_LEGACY_MAX_SIZE;
2387 }
2388
sk_setup_caps(struct sock * sk,struct dst_entry * dst)2389 void sk_setup_caps(struct sock *sk, struct dst_entry *dst)
2390 {
2391 u32 max_segs = 1;
2392
2393 sk->sk_route_caps = dst->dev->features;
2394 if (sk_is_tcp(sk))
2395 sk->sk_route_caps |= NETIF_F_GSO;
2396 if (sk->sk_route_caps & NETIF_F_GSO)
2397 sk->sk_route_caps |= NETIF_F_GSO_SOFTWARE;
2398 if (unlikely(sk->sk_gso_disabled))
2399 sk->sk_route_caps &= ~NETIF_F_GSO_MASK;
2400 if (sk_can_gso(sk)) {
2401 if (dst->header_len && !xfrm_dst_offload_ok(dst)) {
2402 sk->sk_route_caps &= ~NETIF_F_GSO_MASK;
2403 } else {
2404 sk->sk_route_caps |= NETIF_F_SG | NETIF_F_HW_CSUM;
2405 /* pairs with the WRITE_ONCE() in netif_set_gso_max_size() */
2406 sk->sk_gso_max_size = READ_ONCE(dst->dev->gso_max_size);
2407 sk_trim_gso_size(sk);
2408 sk->sk_gso_max_size -= (MAX_TCP_HEADER + 1);
2409 /* pairs with the WRITE_ONCE() in netif_set_gso_max_segs() */
2410 max_segs = max_t(u32, READ_ONCE(dst->dev->gso_max_segs), 1);
2411 }
2412 }
2413 sk->sk_gso_max_segs = max_segs;
2414 sk_dst_set(sk, dst);
2415 }
2416 EXPORT_SYMBOL_GPL(sk_setup_caps);
2417
2418 /*
2419 * Simple resource managers for sockets.
2420 */
2421
2422
2423 /*
2424 * Write buffer destructor automatically called from kfree_skb.
2425 */
sock_wfree(struct sk_buff * skb)2426 void sock_wfree(struct sk_buff *skb)
2427 {
2428 struct sock *sk = skb->sk;
2429 unsigned int len = skb->truesize;
2430 bool free;
2431
2432 if (!sock_flag(sk, SOCK_USE_WRITE_QUEUE)) {
2433 if (sock_flag(sk, SOCK_RCU_FREE) &&
2434 sk->sk_write_space == sock_def_write_space) {
2435 rcu_read_lock();
2436 free = refcount_sub_and_test(len, &sk->sk_wmem_alloc);
2437 sock_def_write_space_wfree(sk);
2438 rcu_read_unlock();
2439 if (unlikely(free))
2440 __sk_free(sk);
2441 return;
2442 }
2443
2444 /*
2445 * Keep a reference on sk_wmem_alloc, this will be released
2446 * after sk_write_space() call
2447 */
2448 WARN_ON(refcount_sub_and_test(len - 1, &sk->sk_wmem_alloc));
2449 sk->sk_write_space(sk);
2450 len = 1;
2451 }
2452 /*
2453 * if sk_wmem_alloc reaches 0, we must finish what sk_free()
2454 * could not do because of in-flight packets
2455 */
2456 if (refcount_sub_and_test(len, &sk->sk_wmem_alloc))
2457 __sk_free(sk);
2458 }
2459 EXPORT_SYMBOL(sock_wfree);
2460
2461 /* This variant of sock_wfree() is used by TCP,
2462 * since it sets SOCK_USE_WRITE_QUEUE.
2463 */
__sock_wfree(struct sk_buff * skb)2464 void __sock_wfree(struct sk_buff *skb)
2465 {
2466 struct sock *sk = skb->sk;
2467
2468 if (refcount_sub_and_test(skb->truesize, &sk->sk_wmem_alloc))
2469 __sk_free(sk);
2470 }
2471
skb_set_owner_w(struct sk_buff * skb,struct sock * sk)2472 void skb_set_owner_w(struct sk_buff *skb, struct sock *sk)
2473 {
2474 skb_orphan(skb);
2475 skb->sk = sk;
2476 #ifdef CONFIG_INET
2477 if (unlikely(!sk_fullsock(sk))) {
2478 skb->destructor = sock_edemux;
2479 sock_hold(sk);
2480 return;
2481 }
2482 #endif
2483 skb->destructor = sock_wfree;
2484 skb_set_hash_from_sk(skb, sk);
2485 /*
2486 * We used to take a refcount on sk, but following operation
2487 * is enough to guarantee sk_free() wont free this sock until
2488 * all in-flight packets are completed
2489 */
2490 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
2491 }
2492 EXPORT_SYMBOL(skb_set_owner_w);
2493
can_skb_orphan_partial(const struct sk_buff * skb)2494 static bool can_skb_orphan_partial(const struct sk_buff *skb)
2495 {
2496 #ifdef CONFIG_TLS_DEVICE
2497 /* Drivers depend on in-order delivery for crypto offload,
2498 * partial orphan breaks out-of-order-OK logic.
2499 */
2500 if (skb->decrypted)
2501 return false;
2502 #endif
2503 return (skb->destructor == sock_wfree ||
2504 (IS_ENABLED(CONFIG_INET) && skb->destructor == tcp_wfree));
2505 }
2506
2507 /* This helper is used by netem, as it can hold packets in its
2508 * delay queue. We want to allow the owner socket to send more
2509 * packets, as if they were already TX completed by a typical driver.
2510 * But we also want to keep skb->sk set because some packet schedulers
2511 * rely on it (sch_fq for example).
2512 */
skb_orphan_partial(struct sk_buff * skb)2513 void skb_orphan_partial(struct sk_buff *skb)
2514 {
2515 if (skb_is_tcp_pure_ack(skb))
2516 return;
2517
2518 if (can_skb_orphan_partial(skb) && skb_set_owner_sk_safe(skb, skb->sk))
2519 return;
2520
2521 skb_orphan(skb);
2522 }
2523 EXPORT_SYMBOL(skb_orphan_partial);
2524
2525 /*
2526 * Read buffer destructor automatically called from kfree_skb.
2527 */
sock_rfree(struct sk_buff * skb)2528 void sock_rfree(struct sk_buff *skb)
2529 {
2530 struct sock *sk = skb->sk;
2531 unsigned int len = skb->truesize;
2532
2533 atomic_sub(len, &sk->sk_rmem_alloc);
2534 sk_mem_uncharge(sk, len);
2535 }
2536 EXPORT_SYMBOL(sock_rfree);
2537
2538 /*
2539 * Buffer destructor for skbs that are not used directly in read or write
2540 * path, e.g. for error handler skbs. Automatically called from kfree_skb.
2541 */
sock_efree(struct sk_buff * skb)2542 void sock_efree(struct sk_buff *skb)
2543 {
2544 sock_put(skb->sk);
2545 }
2546 EXPORT_SYMBOL(sock_efree);
2547
2548 /* Buffer destructor for prefetch/receive path where reference count may
2549 * not be held, e.g. for listen sockets.
2550 */
2551 #ifdef CONFIG_INET
sock_pfree(struct sk_buff * skb)2552 void sock_pfree(struct sk_buff *skb)
2553 {
2554 if (sk_is_refcounted(skb->sk))
2555 sock_gen_put(skb->sk);
2556 }
2557 EXPORT_SYMBOL(sock_pfree);
2558 #endif /* CONFIG_INET */
2559
sock_i_uid(struct sock * sk)2560 kuid_t sock_i_uid(struct sock *sk)
2561 {
2562 kuid_t uid;
2563
2564 read_lock_bh(&sk->sk_callback_lock);
2565 uid = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_uid : GLOBAL_ROOT_UID;
2566 read_unlock_bh(&sk->sk_callback_lock);
2567 return uid;
2568 }
2569 EXPORT_SYMBOL(sock_i_uid);
2570
__sock_i_ino(struct sock * sk)2571 unsigned long __sock_i_ino(struct sock *sk)
2572 {
2573 unsigned long ino;
2574
2575 read_lock(&sk->sk_callback_lock);
2576 ino = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_ino : 0;
2577 read_unlock(&sk->sk_callback_lock);
2578 return ino;
2579 }
2580 EXPORT_SYMBOL(__sock_i_ino);
2581
sock_i_ino(struct sock * sk)2582 unsigned long sock_i_ino(struct sock *sk)
2583 {
2584 unsigned long ino;
2585
2586 local_bh_disable();
2587 ino = __sock_i_ino(sk);
2588 local_bh_enable();
2589 return ino;
2590 }
2591 EXPORT_SYMBOL(sock_i_ino);
2592
2593 /*
2594 * Allocate a skb from the socket's send buffer.
2595 */
sock_wmalloc(struct sock * sk,unsigned long size,int force,gfp_t priority)2596 struct sk_buff *sock_wmalloc(struct sock *sk, unsigned long size, int force,
2597 gfp_t priority)
2598 {
2599 if (force ||
2600 refcount_read(&sk->sk_wmem_alloc) < READ_ONCE(sk->sk_sndbuf)) {
2601 struct sk_buff *skb = alloc_skb(size, priority);
2602
2603 if (skb) {
2604 skb_set_owner_w(skb, sk);
2605 return skb;
2606 }
2607 }
2608 return NULL;
2609 }
2610 EXPORT_SYMBOL(sock_wmalloc);
2611
sock_ofree(struct sk_buff * skb)2612 static void sock_ofree(struct sk_buff *skb)
2613 {
2614 struct sock *sk = skb->sk;
2615
2616 atomic_sub(skb->truesize, &sk->sk_omem_alloc);
2617 }
2618
sock_omalloc(struct sock * sk,unsigned long size,gfp_t priority)2619 struct sk_buff *sock_omalloc(struct sock *sk, unsigned long size,
2620 gfp_t priority)
2621 {
2622 struct sk_buff *skb;
2623
2624 /* small safe race: SKB_TRUESIZE may differ from final skb->truesize */
2625 if (atomic_read(&sk->sk_omem_alloc) + SKB_TRUESIZE(size) >
2626 READ_ONCE(sysctl_optmem_max))
2627 return NULL;
2628
2629 skb = alloc_skb(size, priority);
2630 if (!skb)
2631 return NULL;
2632
2633 atomic_add(skb->truesize, &sk->sk_omem_alloc);
2634 skb->sk = sk;
2635 skb->destructor = sock_ofree;
2636 return skb;
2637 }
2638
2639 /*
2640 * Allocate a memory block from the socket's option memory buffer.
2641 */
sock_kmalloc(struct sock * sk,int size,gfp_t priority)2642 void *sock_kmalloc(struct sock *sk, int size, gfp_t priority)
2643 {
2644 int optmem_max = READ_ONCE(sysctl_optmem_max);
2645
2646 if ((unsigned int)size <= optmem_max &&
2647 atomic_read(&sk->sk_omem_alloc) + size < optmem_max) {
2648 void *mem;
2649 /* First do the add, to avoid the race if kmalloc
2650 * might sleep.
2651 */
2652 atomic_add(size, &sk->sk_omem_alloc);
2653 mem = kmalloc(size, priority);
2654 if (mem)
2655 return mem;
2656 atomic_sub(size, &sk->sk_omem_alloc);
2657 }
2658 return NULL;
2659 }
2660 EXPORT_SYMBOL(sock_kmalloc);
2661
2662 /* Free an option memory block. Note, we actually want the inline
2663 * here as this allows gcc to detect the nullify and fold away the
2664 * condition entirely.
2665 */
__sock_kfree_s(struct sock * sk,void * mem,int size,const bool nullify)2666 static inline void __sock_kfree_s(struct sock *sk, void *mem, int size,
2667 const bool nullify)
2668 {
2669 if (WARN_ON_ONCE(!mem))
2670 return;
2671 if (nullify)
2672 kfree_sensitive(mem);
2673 else
2674 kfree(mem);
2675 atomic_sub(size, &sk->sk_omem_alloc);
2676 }
2677
sock_kfree_s(struct sock * sk,void * mem,int size)2678 void sock_kfree_s(struct sock *sk, void *mem, int size)
2679 {
2680 __sock_kfree_s(sk, mem, size, false);
2681 }
2682 EXPORT_SYMBOL(sock_kfree_s);
2683
sock_kzfree_s(struct sock * sk,void * mem,int size)2684 void sock_kzfree_s(struct sock *sk, void *mem, int size)
2685 {
2686 __sock_kfree_s(sk, mem, size, true);
2687 }
2688 EXPORT_SYMBOL(sock_kzfree_s);
2689
2690 /* It is almost wait_for_tcp_memory minus release_sock/lock_sock.
2691 I think, these locks should be removed for datagram sockets.
2692 */
sock_wait_for_wmem(struct sock * sk,long timeo)2693 static long sock_wait_for_wmem(struct sock *sk, long timeo)
2694 {
2695 DEFINE_WAIT(wait);
2696
2697 sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
2698 for (;;) {
2699 if (!timeo)
2700 break;
2701 if (signal_pending(current))
2702 break;
2703 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
2704 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
2705 if (refcount_read(&sk->sk_wmem_alloc) < READ_ONCE(sk->sk_sndbuf))
2706 break;
2707 if (READ_ONCE(sk->sk_shutdown) & SEND_SHUTDOWN)
2708 break;
2709 if (READ_ONCE(sk->sk_err))
2710 break;
2711 timeo = schedule_timeout(timeo);
2712 }
2713 finish_wait(sk_sleep(sk), &wait);
2714 return timeo;
2715 }
2716
2717
2718 /*
2719 * Generic send/receive buffer handlers
2720 */
2721
sock_alloc_send_pskb(struct sock * sk,unsigned long header_len,unsigned long data_len,int noblock,int * errcode,int max_page_order)2722 struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
2723 unsigned long data_len, int noblock,
2724 int *errcode, int max_page_order)
2725 {
2726 struct sk_buff *skb;
2727 long timeo;
2728 int err;
2729
2730 timeo = sock_sndtimeo(sk, noblock);
2731 for (;;) {
2732 err = sock_error(sk);
2733 if (err != 0)
2734 goto failure;
2735
2736 err = -EPIPE;
2737 if (READ_ONCE(sk->sk_shutdown) & SEND_SHUTDOWN)
2738 goto failure;
2739
2740 if (sk_wmem_alloc_get(sk) < READ_ONCE(sk->sk_sndbuf))
2741 break;
2742
2743 sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
2744 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
2745 err = -EAGAIN;
2746 if (!timeo)
2747 goto failure;
2748 if (signal_pending(current))
2749 goto interrupted;
2750 timeo = sock_wait_for_wmem(sk, timeo);
2751 }
2752 skb = alloc_skb_with_frags(header_len, data_len, max_page_order,
2753 errcode, sk->sk_allocation);
2754 if (skb)
2755 skb_set_owner_w(skb, sk);
2756 return skb;
2757
2758 interrupted:
2759 err = sock_intr_errno(timeo);
2760 failure:
2761 *errcode = err;
2762 return NULL;
2763 }
2764 EXPORT_SYMBOL(sock_alloc_send_pskb);
2765
__sock_cmsg_send(struct sock * sk,struct msghdr * msg,struct cmsghdr * cmsg,struct sockcm_cookie * sockc)2766 int __sock_cmsg_send(struct sock *sk, struct msghdr *msg, struct cmsghdr *cmsg,
2767 struct sockcm_cookie *sockc)
2768 {
2769 u32 tsflags;
2770
2771 switch (cmsg->cmsg_type) {
2772 case SO_MARK:
2773 if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_RAW) &&
2774 !ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
2775 return -EPERM;
2776 if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32)))
2777 return -EINVAL;
2778 sockc->mark = *(u32 *)CMSG_DATA(cmsg);
2779 break;
2780 case SO_TIMESTAMPING_OLD:
2781 case SO_TIMESTAMPING_NEW:
2782 if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32)))
2783 return -EINVAL;
2784
2785 tsflags = *(u32 *)CMSG_DATA(cmsg);
2786 if (tsflags & ~SOF_TIMESTAMPING_TX_RECORD_MASK)
2787 return -EINVAL;
2788
2789 sockc->tsflags &= ~SOF_TIMESTAMPING_TX_RECORD_MASK;
2790 sockc->tsflags |= tsflags;
2791 break;
2792 case SCM_TXTIME:
2793 if (!sock_flag(sk, SOCK_TXTIME))
2794 return -EINVAL;
2795 if (cmsg->cmsg_len != CMSG_LEN(sizeof(u64)))
2796 return -EINVAL;
2797 sockc->transmit_time = get_unaligned((u64 *)CMSG_DATA(cmsg));
2798 break;
2799 /* SCM_RIGHTS and SCM_CREDENTIALS are semantically in SOL_UNIX. */
2800 case SCM_RIGHTS:
2801 case SCM_CREDENTIALS:
2802 break;
2803 default:
2804 return -EINVAL;
2805 }
2806 return 0;
2807 }
2808 EXPORT_SYMBOL(__sock_cmsg_send);
2809
sock_cmsg_send(struct sock * sk,struct msghdr * msg,struct sockcm_cookie * sockc)2810 int sock_cmsg_send(struct sock *sk, struct msghdr *msg,
2811 struct sockcm_cookie *sockc)
2812 {
2813 struct cmsghdr *cmsg;
2814 int ret;
2815
2816 for_each_cmsghdr(cmsg, msg) {
2817 if (!CMSG_OK(msg, cmsg))
2818 return -EINVAL;
2819 if (cmsg->cmsg_level != SOL_SOCKET)
2820 continue;
2821 ret = __sock_cmsg_send(sk, msg, cmsg, sockc);
2822 if (ret)
2823 return ret;
2824 }
2825 return 0;
2826 }
2827 EXPORT_SYMBOL(sock_cmsg_send);
2828
sk_enter_memory_pressure(struct sock * sk)2829 static void sk_enter_memory_pressure(struct sock *sk)
2830 {
2831 if (!sk->sk_prot->enter_memory_pressure)
2832 return;
2833
2834 sk->sk_prot->enter_memory_pressure(sk);
2835 }
2836
sk_leave_memory_pressure(struct sock * sk)2837 static void sk_leave_memory_pressure(struct sock *sk)
2838 {
2839 if (sk->sk_prot->leave_memory_pressure) {
2840 INDIRECT_CALL_INET_1(sk->sk_prot->leave_memory_pressure,
2841 tcp_leave_memory_pressure, sk);
2842 } else {
2843 unsigned long *memory_pressure = sk->sk_prot->memory_pressure;
2844
2845 if (memory_pressure && READ_ONCE(*memory_pressure))
2846 WRITE_ONCE(*memory_pressure, 0);
2847 }
2848 }
2849
2850 DEFINE_STATIC_KEY_FALSE(net_high_order_alloc_disable_key);
2851
2852 /**
2853 * skb_page_frag_refill - check that a page_frag contains enough room
2854 * @sz: minimum size of the fragment we want to get
2855 * @pfrag: pointer to page_frag
2856 * @gfp: priority for memory allocation
2857 *
2858 * Note: While this allocator tries to use high order pages, there is
2859 * no guarantee that allocations succeed. Therefore, @sz MUST be
2860 * less or equal than PAGE_SIZE.
2861 */
skb_page_frag_refill(unsigned int sz,struct page_frag * pfrag,gfp_t gfp)2862 bool skb_page_frag_refill(unsigned int sz, struct page_frag *pfrag, gfp_t gfp)
2863 {
2864 if (pfrag->page) {
2865 if (page_ref_count(pfrag->page) == 1) {
2866 pfrag->offset = 0;
2867 return true;
2868 }
2869 if (pfrag->offset + sz <= pfrag->size)
2870 return true;
2871 put_page(pfrag->page);
2872 }
2873
2874 pfrag->offset = 0;
2875 if (SKB_FRAG_PAGE_ORDER &&
2876 !static_branch_unlikely(&net_high_order_alloc_disable_key)) {
2877 /* Avoid direct reclaim but allow kswapd to wake */
2878 pfrag->page = alloc_pages((gfp & ~__GFP_DIRECT_RECLAIM) |
2879 __GFP_COMP | __GFP_NOWARN |
2880 __GFP_NORETRY,
2881 SKB_FRAG_PAGE_ORDER);
2882 if (likely(pfrag->page)) {
2883 pfrag->size = PAGE_SIZE << SKB_FRAG_PAGE_ORDER;
2884 return true;
2885 }
2886 }
2887 pfrag->page = alloc_page(gfp);
2888 if (likely(pfrag->page)) {
2889 pfrag->size = PAGE_SIZE;
2890 return true;
2891 }
2892 return false;
2893 }
2894 EXPORT_SYMBOL(skb_page_frag_refill);
2895
sk_page_frag_refill(struct sock * sk,struct page_frag * pfrag)2896 bool sk_page_frag_refill(struct sock *sk, struct page_frag *pfrag)
2897 {
2898 if (likely(skb_page_frag_refill(32U, pfrag, sk->sk_allocation)))
2899 return true;
2900
2901 sk_enter_memory_pressure(sk);
2902 sk_stream_moderate_sndbuf(sk);
2903 return false;
2904 }
2905 EXPORT_SYMBOL(sk_page_frag_refill);
2906
__lock_sock(struct sock * sk)2907 void __lock_sock(struct sock *sk)
2908 __releases(&sk->sk_lock.slock)
2909 __acquires(&sk->sk_lock.slock)
2910 {
2911 DEFINE_WAIT(wait);
2912
2913 for (;;) {
2914 prepare_to_wait_exclusive(&sk->sk_lock.wq, &wait,
2915 TASK_UNINTERRUPTIBLE);
2916 spin_unlock_bh(&sk->sk_lock.slock);
2917 schedule();
2918 spin_lock_bh(&sk->sk_lock.slock);
2919 if (!sock_owned_by_user(sk))
2920 break;
2921 }
2922 finish_wait(&sk->sk_lock.wq, &wait);
2923 }
2924
__release_sock(struct sock * sk)2925 void __release_sock(struct sock *sk)
2926 __releases(&sk->sk_lock.slock)
2927 __acquires(&sk->sk_lock.slock)
2928 {
2929 struct sk_buff *skb, *next;
2930
2931 while ((skb = sk->sk_backlog.head) != NULL) {
2932 sk->sk_backlog.head = sk->sk_backlog.tail = NULL;
2933
2934 spin_unlock_bh(&sk->sk_lock.slock);
2935
2936 do {
2937 next = skb->next;
2938 prefetch(next);
2939 DEBUG_NET_WARN_ON_ONCE(skb_dst_is_noref(skb));
2940 skb_mark_not_on_list(skb);
2941 sk_backlog_rcv(sk, skb);
2942
2943 cond_resched();
2944
2945 skb = next;
2946 } while (skb != NULL);
2947
2948 spin_lock_bh(&sk->sk_lock.slock);
2949 }
2950
2951 /*
2952 * Doing the zeroing here guarantee we can not loop forever
2953 * while a wild producer attempts to flood us.
2954 */
2955 sk->sk_backlog.len = 0;
2956 }
2957
__sk_flush_backlog(struct sock * sk)2958 void __sk_flush_backlog(struct sock *sk)
2959 {
2960 spin_lock_bh(&sk->sk_lock.slock);
2961 __release_sock(sk);
2962 spin_unlock_bh(&sk->sk_lock.slock);
2963 }
2964 EXPORT_SYMBOL_GPL(__sk_flush_backlog);
2965
2966 /**
2967 * sk_wait_data - wait for data to arrive at sk_receive_queue
2968 * @sk: sock to wait on
2969 * @timeo: for how long
2970 * @skb: last skb seen on sk_receive_queue
2971 *
2972 * Now socket state including sk->sk_err is changed only under lock,
2973 * hence we may omit checks after joining wait queue.
2974 * We check receive queue before schedule() only as optimization;
2975 * it is very likely that release_sock() added new data.
2976 */
sk_wait_data(struct sock * sk,long * timeo,const struct sk_buff * skb)2977 int sk_wait_data(struct sock *sk, long *timeo, const struct sk_buff *skb)
2978 {
2979 DEFINE_WAIT_FUNC(wait, woken_wake_function);
2980 int rc;
2981
2982 add_wait_queue(sk_sleep(sk), &wait);
2983 sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
2984 rc = sk_wait_event(sk, timeo, skb_peek_tail(&sk->sk_receive_queue) != skb, &wait);
2985 sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
2986 remove_wait_queue(sk_sleep(sk), &wait);
2987 return rc;
2988 }
2989 EXPORT_SYMBOL(sk_wait_data);
2990
2991 /**
2992 * __sk_mem_raise_allocated - increase memory_allocated
2993 * @sk: socket
2994 * @size: memory size to allocate
2995 * @amt: pages to allocate
2996 * @kind: allocation type
2997 *
2998 * Similar to __sk_mem_schedule(), but does not update sk_forward_alloc
2999 */
__sk_mem_raise_allocated(struct sock * sk,int size,int amt,int kind)3000 int __sk_mem_raise_allocated(struct sock *sk, int size, int amt, int kind)
3001 {
3002 bool memcg_charge = mem_cgroup_sockets_enabled && sk->sk_memcg;
3003 struct proto *prot = sk->sk_prot;
3004 bool charged = true;
3005 long allocated;
3006
3007 sk_memory_allocated_add(sk, amt);
3008 allocated = sk_memory_allocated(sk);
3009 if (memcg_charge &&
3010 !(charged = mem_cgroup_charge_skmem(sk->sk_memcg, amt,
3011 gfp_memcg_charge())))
3012 goto suppress_allocation;
3013
3014 /* Under limit. */
3015 if (allocated <= sk_prot_mem_limits(sk, 0)) {
3016 sk_leave_memory_pressure(sk);
3017 return 1;
3018 }
3019
3020 /* Under pressure. */
3021 if (allocated > sk_prot_mem_limits(sk, 1))
3022 sk_enter_memory_pressure(sk);
3023
3024 /* Over hard limit. */
3025 if (allocated > sk_prot_mem_limits(sk, 2))
3026 goto suppress_allocation;
3027
3028 /* guarantee minimum buffer size under pressure */
3029 if (kind == SK_MEM_RECV) {
3030 if (atomic_read(&sk->sk_rmem_alloc) < sk_get_rmem0(sk, prot))
3031 return 1;
3032
3033 } else { /* SK_MEM_SEND */
3034 int wmem0 = sk_get_wmem0(sk, prot);
3035
3036 if (sk->sk_type == SOCK_STREAM) {
3037 if (sk->sk_wmem_queued < wmem0)
3038 return 1;
3039 } else if (refcount_read(&sk->sk_wmem_alloc) < wmem0) {
3040 return 1;
3041 }
3042 }
3043
3044 if (sk_has_memory_pressure(sk)) {
3045 u64 alloc;
3046
3047 if (!sk_under_memory_pressure(sk))
3048 return 1;
3049 alloc = sk_sockets_allocated_read_positive(sk);
3050 if (sk_prot_mem_limits(sk, 2) > alloc *
3051 sk_mem_pages(sk->sk_wmem_queued +
3052 atomic_read(&sk->sk_rmem_alloc) +
3053 sk->sk_forward_alloc))
3054 return 1;
3055 }
3056
3057 suppress_allocation:
3058
3059 if (kind == SK_MEM_SEND && sk->sk_type == SOCK_STREAM) {
3060 sk_stream_moderate_sndbuf(sk);
3061
3062 /* Fail only if socket is _under_ its sndbuf.
3063 * In this case we cannot block, so that we have to fail.
3064 */
3065 if (sk->sk_wmem_queued + size >= sk->sk_sndbuf) {
3066 /* Force charge with __GFP_NOFAIL */
3067 if (memcg_charge && !charged) {
3068 mem_cgroup_charge_skmem(sk->sk_memcg, amt,
3069 gfp_memcg_charge() | __GFP_NOFAIL);
3070 }
3071 return 1;
3072 }
3073 }
3074
3075 if (kind == SK_MEM_SEND || (kind == SK_MEM_RECV && charged))
3076 trace_sock_exceed_buf_limit(sk, prot, allocated, kind);
3077
3078 sk_memory_allocated_sub(sk, amt);
3079
3080 if (memcg_charge && charged)
3081 mem_cgroup_uncharge_skmem(sk->sk_memcg, amt);
3082
3083 return 0;
3084 }
3085
3086 /**
3087 * __sk_mem_schedule - increase sk_forward_alloc and memory_allocated
3088 * @sk: socket
3089 * @size: memory size to allocate
3090 * @kind: allocation type
3091 *
3092 * If kind is SK_MEM_SEND, it means wmem allocation. Otherwise it means
3093 * rmem allocation. This function assumes that protocols which have
3094 * memory_pressure use sk_wmem_queued as write buffer accounting.
3095 */
__sk_mem_schedule(struct sock * sk,int size,int kind)3096 int __sk_mem_schedule(struct sock *sk, int size, int kind)
3097 {
3098 int ret, amt = sk_mem_pages(size);
3099
3100 sk_forward_alloc_add(sk, amt << PAGE_SHIFT);
3101 ret = __sk_mem_raise_allocated(sk, size, amt, kind);
3102 if (!ret)
3103 sk_forward_alloc_add(sk, -(amt << PAGE_SHIFT));
3104 return ret;
3105 }
3106 EXPORT_SYMBOL(__sk_mem_schedule);
3107
3108 /**
3109 * __sk_mem_reduce_allocated - reclaim memory_allocated
3110 * @sk: socket
3111 * @amount: number of quanta
3112 *
3113 * Similar to __sk_mem_reclaim(), but does not update sk_forward_alloc
3114 */
__sk_mem_reduce_allocated(struct sock * sk,int amount)3115 void __sk_mem_reduce_allocated(struct sock *sk, int amount)
3116 {
3117 sk_memory_allocated_sub(sk, amount);
3118
3119 if (mem_cgroup_sockets_enabled && sk->sk_memcg)
3120 mem_cgroup_uncharge_skmem(sk->sk_memcg, amount);
3121
3122 if (sk_under_global_memory_pressure(sk) &&
3123 (sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0)))
3124 sk_leave_memory_pressure(sk);
3125 }
3126
3127 /**
3128 * __sk_mem_reclaim - reclaim sk_forward_alloc and memory_allocated
3129 * @sk: socket
3130 * @amount: number of bytes (rounded down to a PAGE_SIZE multiple)
3131 */
__sk_mem_reclaim(struct sock * sk,int amount)3132 void __sk_mem_reclaim(struct sock *sk, int amount)
3133 {
3134 amount >>= PAGE_SHIFT;
3135 sk_forward_alloc_add(sk, -(amount << PAGE_SHIFT));
3136 __sk_mem_reduce_allocated(sk, amount);
3137 }
3138 EXPORT_SYMBOL(__sk_mem_reclaim);
3139
sk_set_peek_off(struct sock * sk,int val)3140 int sk_set_peek_off(struct sock *sk, int val)
3141 {
3142 WRITE_ONCE(sk->sk_peek_off, val);
3143 return 0;
3144 }
3145 EXPORT_SYMBOL_GPL(sk_set_peek_off);
3146
3147 /*
3148 * Set of default routines for initialising struct proto_ops when
3149 * the protocol does not support a particular function. In certain
3150 * cases where it makes no sense for a protocol to have a "do nothing"
3151 * function, some default processing is provided.
3152 */
3153
sock_no_bind(struct socket * sock,struct sockaddr * saddr,int len)3154 int sock_no_bind(struct socket *sock, struct sockaddr *saddr, int len)
3155 {
3156 return -EOPNOTSUPP;
3157 }
3158 EXPORT_SYMBOL(sock_no_bind);
3159
sock_no_connect(struct socket * sock,struct sockaddr * saddr,int len,int flags)3160 int sock_no_connect(struct socket *sock, struct sockaddr *saddr,
3161 int len, int flags)
3162 {
3163 return -EOPNOTSUPP;
3164 }
3165 EXPORT_SYMBOL(sock_no_connect);
3166
sock_no_socketpair(struct socket * sock1,struct socket * sock2)3167 int sock_no_socketpair(struct socket *sock1, struct socket *sock2)
3168 {
3169 return -EOPNOTSUPP;
3170 }
3171 EXPORT_SYMBOL(sock_no_socketpair);
3172
sock_no_accept(struct socket * sock,struct socket * newsock,int flags,bool kern)3173 int sock_no_accept(struct socket *sock, struct socket *newsock, int flags,
3174 bool kern)
3175 {
3176 return -EOPNOTSUPP;
3177 }
3178 EXPORT_SYMBOL(sock_no_accept);
3179
sock_no_getname(struct socket * sock,struct sockaddr * saddr,int peer)3180 int sock_no_getname(struct socket *sock, struct sockaddr *saddr,
3181 int peer)
3182 {
3183 return -EOPNOTSUPP;
3184 }
3185 EXPORT_SYMBOL(sock_no_getname);
3186
sock_no_ioctl(struct socket * sock,unsigned int cmd,unsigned long arg)3187 int sock_no_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
3188 {
3189 return -EOPNOTSUPP;
3190 }
3191 EXPORT_SYMBOL(sock_no_ioctl);
3192
sock_no_listen(struct socket * sock,int backlog)3193 int sock_no_listen(struct socket *sock, int backlog)
3194 {
3195 return -EOPNOTSUPP;
3196 }
3197 EXPORT_SYMBOL(sock_no_listen);
3198
sock_no_shutdown(struct socket * sock,int how)3199 int sock_no_shutdown(struct socket *sock, int how)
3200 {
3201 return -EOPNOTSUPP;
3202 }
3203 EXPORT_SYMBOL(sock_no_shutdown);
3204
sock_no_sendmsg(struct socket * sock,struct msghdr * m,size_t len)3205 int sock_no_sendmsg(struct socket *sock, struct msghdr *m, size_t len)
3206 {
3207 return -EOPNOTSUPP;
3208 }
3209 EXPORT_SYMBOL(sock_no_sendmsg);
3210
sock_no_sendmsg_locked(struct sock * sk,struct msghdr * m,size_t len)3211 int sock_no_sendmsg_locked(struct sock *sk, struct msghdr *m, size_t len)
3212 {
3213 return -EOPNOTSUPP;
3214 }
3215 EXPORT_SYMBOL(sock_no_sendmsg_locked);
3216
sock_no_recvmsg(struct socket * sock,struct msghdr * m,size_t len,int flags)3217 int sock_no_recvmsg(struct socket *sock, struct msghdr *m, size_t len,
3218 int flags)
3219 {
3220 return -EOPNOTSUPP;
3221 }
3222 EXPORT_SYMBOL(sock_no_recvmsg);
3223
sock_no_mmap(struct file * file,struct socket * sock,struct vm_area_struct * vma)3224 int sock_no_mmap(struct file *file, struct socket *sock, struct vm_area_struct *vma)
3225 {
3226 /* Mirror missing mmap method error code */
3227 return -ENODEV;
3228 }
3229 EXPORT_SYMBOL(sock_no_mmap);
3230
3231 /*
3232 * When a file is received (via SCM_RIGHTS, etc), we must bump the
3233 * various sock-based usage counts.
3234 */
__receive_sock(struct file * file)3235 void __receive_sock(struct file *file)
3236 {
3237 struct socket *sock;
3238
3239 sock = sock_from_file(file);
3240 if (sock) {
3241 sock_update_netprioidx(&sock->sk->sk_cgrp_data);
3242 sock_update_classid(&sock->sk->sk_cgrp_data);
3243 }
3244 }
3245
sock_no_sendpage(struct socket * sock,struct page * page,int offset,size_t size,int flags)3246 ssize_t sock_no_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags)
3247 {
3248 ssize_t res;
3249 struct msghdr msg = {.msg_flags = flags};
3250 struct kvec iov;
3251 char *kaddr = kmap(page);
3252 iov.iov_base = kaddr + offset;
3253 iov.iov_len = size;
3254 res = kernel_sendmsg(sock, &msg, &iov, 1, size);
3255 kunmap(page);
3256 return res;
3257 }
3258 EXPORT_SYMBOL(sock_no_sendpage);
3259
sock_no_sendpage_locked(struct sock * sk,struct page * page,int offset,size_t size,int flags)3260 ssize_t sock_no_sendpage_locked(struct sock *sk, struct page *page,
3261 int offset, size_t size, int flags)
3262 {
3263 ssize_t res;
3264 struct msghdr msg = {.msg_flags = flags};
3265 struct kvec iov;
3266 char *kaddr = kmap(page);
3267
3268 iov.iov_base = kaddr + offset;
3269 iov.iov_len = size;
3270 res = kernel_sendmsg_locked(sk, &msg, &iov, 1, size);
3271 kunmap(page);
3272 return res;
3273 }
3274 EXPORT_SYMBOL(sock_no_sendpage_locked);
3275
3276 /*
3277 * Default Socket Callbacks
3278 */
3279
sock_def_wakeup(struct sock * sk)3280 static void sock_def_wakeup(struct sock *sk)
3281 {
3282 struct socket_wq *wq;
3283
3284 rcu_read_lock();
3285 wq = rcu_dereference(sk->sk_wq);
3286 if (skwq_has_sleeper(wq))
3287 wake_up_interruptible_all(&wq->wait);
3288 rcu_read_unlock();
3289 }
3290
sock_def_error_report(struct sock * sk)3291 static void sock_def_error_report(struct sock *sk)
3292 {
3293 struct socket_wq *wq;
3294
3295 rcu_read_lock();
3296 wq = rcu_dereference(sk->sk_wq);
3297 if (skwq_has_sleeper(wq))
3298 wake_up_interruptible_poll(&wq->wait, EPOLLERR);
3299 sk_wake_async(sk, SOCK_WAKE_IO, POLL_ERR);
3300 rcu_read_unlock();
3301 }
3302
sock_def_readable(struct sock * sk)3303 void sock_def_readable(struct sock *sk)
3304 {
3305 struct socket_wq *wq;
3306
3307 rcu_read_lock();
3308 wq = rcu_dereference(sk->sk_wq);
3309
3310 if (skwq_has_sleeper(wq)) {
3311 int done = 0;
3312
3313 trace_android_vh_do_wake_up_sync(&wq->wait, &done, sk);
3314 if (done)
3315 goto out;
3316
3317 wake_up_interruptible_sync_poll(&wq->wait, EPOLLIN | EPOLLPRI |
3318 EPOLLRDNORM | EPOLLRDBAND);
3319 }
3320
3321 out:
3322 sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
3323 rcu_read_unlock();
3324 }
3325
sock_def_write_space(struct sock * sk)3326 static void sock_def_write_space(struct sock *sk)
3327 {
3328 struct socket_wq *wq;
3329
3330 rcu_read_lock();
3331
3332 /* Do not wake up a writer until he can make "significant"
3333 * progress. --DaveM
3334 */
3335 if (sock_writeable(sk)) {
3336 wq = rcu_dereference(sk->sk_wq);
3337 if (skwq_has_sleeper(wq))
3338 wake_up_interruptible_sync_poll(&wq->wait, EPOLLOUT |
3339 EPOLLWRNORM | EPOLLWRBAND);
3340
3341 /* Should agree with poll, otherwise some programs break */
3342 sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
3343 }
3344
3345 rcu_read_unlock();
3346 }
3347
3348 /* An optimised version of sock_def_write_space(), should only be called
3349 * for SOCK_RCU_FREE sockets under RCU read section and after putting
3350 * ->sk_wmem_alloc.
3351 */
sock_def_write_space_wfree(struct sock * sk)3352 static void sock_def_write_space_wfree(struct sock *sk)
3353 {
3354 /* Do not wake up a writer until he can make "significant"
3355 * progress. --DaveM
3356 */
3357 if (sock_writeable(sk)) {
3358 struct socket_wq *wq = rcu_dereference(sk->sk_wq);
3359
3360 /* rely on refcount_sub from sock_wfree() */
3361 smp_mb__after_atomic();
3362 if (wq && waitqueue_active(&wq->wait))
3363 wake_up_interruptible_sync_poll(&wq->wait, EPOLLOUT |
3364 EPOLLWRNORM | EPOLLWRBAND);
3365
3366 /* Should agree with poll, otherwise some programs break */
3367 sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
3368 }
3369 }
3370
sock_def_destruct(struct sock * sk)3371 static void sock_def_destruct(struct sock *sk)
3372 {
3373 }
3374
sk_send_sigurg(struct sock * sk)3375 void sk_send_sigurg(struct sock *sk)
3376 {
3377 if (sk->sk_socket && sk->sk_socket->file)
3378 if (send_sigurg(&sk->sk_socket->file->f_owner))
3379 sk_wake_async(sk, SOCK_WAKE_URG, POLL_PRI);
3380 }
3381 EXPORT_SYMBOL(sk_send_sigurg);
3382
sk_reset_timer(struct sock * sk,struct timer_list * timer,unsigned long expires)3383 void sk_reset_timer(struct sock *sk, struct timer_list* timer,
3384 unsigned long expires)
3385 {
3386 if (!mod_timer(timer, expires))
3387 sock_hold(sk);
3388 }
3389 EXPORT_SYMBOL(sk_reset_timer);
3390
sk_stop_timer(struct sock * sk,struct timer_list * timer)3391 void sk_stop_timer(struct sock *sk, struct timer_list* timer)
3392 {
3393 if (del_timer(timer))
3394 __sock_put(sk);
3395 }
3396 EXPORT_SYMBOL(sk_stop_timer);
3397
sk_stop_timer_sync(struct sock * sk,struct timer_list * timer)3398 void sk_stop_timer_sync(struct sock *sk, struct timer_list *timer)
3399 {
3400 if (del_timer_sync(timer))
3401 __sock_put(sk);
3402 }
3403 EXPORT_SYMBOL(sk_stop_timer_sync);
3404
sock_init_data_uid(struct socket * sock,struct sock * sk,kuid_t uid)3405 void sock_init_data_uid(struct socket *sock, struct sock *sk, kuid_t uid)
3406 {
3407 sk_init_common(sk);
3408 sk->sk_send_head = NULL;
3409
3410 timer_setup(&sk->sk_timer, NULL, 0);
3411
3412 sk->sk_allocation = GFP_KERNEL;
3413 sk->sk_rcvbuf = READ_ONCE(sysctl_rmem_default);
3414 sk->sk_sndbuf = READ_ONCE(sysctl_wmem_default);
3415 sk->sk_state = TCP_CLOSE;
3416 sk_set_socket(sk, sock);
3417
3418 sock_set_flag(sk, SOCK_ZAPPED);
3419
3420 if (sock) {
3421 sk->sk_type = sock->type;
3422 RCU_INIT_POINTER(sk->sk_wq, &sock->wq);
3423 sock->sk = sk;
3424 } else {
3425 RCU_INIT_POINTER(sk->sk_wq, NULL);
3426 }
3427 sk->sk_uid = uid;
3428
3429 rwlock_init(&sk->sk_callback_lock);
3430 if (sk->sk_kern_sock)
3431 lockdep_set_class_and_name(
3432 &sk->sk_callback_lock,
3433 af_kern_callback_keys + sk->sk_family,
3434 af_family_kern_clock_key_strings[sk->sk_family]);
3435 else
3436 lockdep_set_class_and_name(
3437 &sk->sk_callback_lock,
3438 af_callback_keys + sk->sk_family,
3439 af_family_clock_key_strings[sk->sk_family]);
3440
3441 sk->sk_state_change = sock_def_wakeup;
3442 sk->sk_data_ready = sock_def_readable;
3443 sk->sk_write_space = sock_def_write_space;
3444 sk->sk_error_report = sock_def_error_report;
3445 sk->sk_destruct = sock_def_destruct;
3446
3447 sk->sk_frag.page = NULL;
3448 sk->sk_frag.offset = 0;
3449 sk->sk_peek_off = -1;
3450
3451 sk->sk_peer_pid = NULL;
3452 sk->sk_peer_cred = NULL;
3453 spin_lock_init(&sk->sk_peer_lock);
3454
3455 sk->sk_write_pending = 0;
3456 sk->sk_rcvlowat = 1;
3457 sk->sk_rcvtimeo = MAX_SCHEDULE_TIMEOUT;
3458 sk->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT;
3459
3460 sk->sk_stamp = SK_DEFAULT_STAMP;
3461 #if BITS_PER_LONG==32
3462 seqlock_init(&sk->sk_stamp_seq);
3463 #endif
3464 atomic_set(&sk->sk_zckey, 0);
3465
3466 #ifdef CONFIG_NET_RX_BUSY_POLL
3467 sk->sk_napi_id = 0;
3468 sk->sk_ll_usec = READ_ONCE(sysctl_net_busy_read);
3469 #endif
3470
3471 sk->sk_max_pacing_rate = ~0UL;
3472 sk->sk_pacing_rate = ~0UL;
3473 WRITE_ONCE(sk->sk_pacing_shift, 10);
3474 sk->sk_incoming_cpu = -1;
3475
3476 sk_rx_queue_clear(sk);
3477 /*
3478 * Before updating sk_refcnt, we must commit prior changes to memory
3479 * (Documentation/RCU/rculist_nulls.rst for details)
3480 */
3481 smp_wmb();
3482 refcount_set(&sk->sk_refcnt, 1);
3483 atomic_set(&sk->sk_drops, 0);
3484 }
3485 EXPORT_SYMBOL(sock_init_data_uid);
3486
sock_init_data(struct socket * sock,struct sock * sk)3487 void sock_init_data(struct socket *sock, struct sock *sk)
3488 {
3489 kuid_t uid = sock ?
3490 SOCK_INODE(sock)->i_uid :
3491 make_kuid(sock_net(sk)->user_ns, 0);
3492
3493 sock_init_data_uid(sock, sk, uid);
3494 }
3495 EXPORT_SYMBOL(sock_init_data);
3496
lock_sock_nested(struct sock * sk,int subclass)3497 void lock_sock_nested(struct sock *sk, int subclass)
3498 {
3499 /* The sk_lock has mutex_lock() semantics here. */
3500 mutex_acquire(&sk->sk_lock.dep_map, subclass, 0, _RET_IP_);
3501
3502 might_sleep();
3503 spin_lock_bh(&sk->sk_lock.slock);
3504 if (sock_owned_by_user_nocheck(sk))
3505 __lock_sock(sk);
3506 sk->sk_lock.owned = 1;
3507 spin_unlock_bh(&sk->sk_lock.slock);
3508 }
3509 EXPORT_SYMBOL(lock_sock_nested);
3510
release_sock(struct sock * sk)3511 void release_sock(struct sock *sk)
3512 {
3513 spin_lock_bh(&sk->sk_lock.slock);
3514 if (sk->sk_backlog.tail)
3515 __release_sock(sk);
3516
3517 /* Warning : release_cb() might need to release sk ownership,
3518 * ie call sock_release_ownership(sk) before us.
3519 */
3520 if (sk->sk_prot->release_cb)
3521 sk->sk_prot->release_cb(sk);
3522
3523 sock_release_ownership(sk);
3524 if (waitqueue_active(&sk->sk_lock.wq))
3525 wake_up(&sk->sk_lock.wq);
3526 spin_unlock_bh(&sk->sk_lock.slock);
3527 }
3528 EXPORT_SYMBOL(release_sock);
3529
__lock_sock_fast(struct sock * sk)3530 bool __lock_sock_fast(struct sock *sk) __acquires(&sk->sk_lock.slock)
3531 {
3532 might_sleep();
3533 spin_lock_bh(&sk->sk_lock.slock);
3534
3535 if (!sock_owned_by_user_nocheck(sk)) {
3536 /*
3537 * Fast path return with bottom halves disabled and
3538 * sock::sk_lock.slock held.
3539 *
3540 * The 'mutex' is not contended and holding
3541 * sock::sk_lock.slock prevents all other lockers to
3542 * proceed so the corresponding unlock_sock_fast() can
3543 * avoid the slow path of release_sock() completely and
3544 * just release slock.
3545 *
3546 * From a semantical POV this is equivalent to 'acquiring'
3547 * the 'mutex', hence the corresponding lockdep
3548 * mutex_release() has to happen in the fast path of
3549 * unlock_sock_fast().
3550 */
3551 return false;
3552 }
3553
3554 __lock_sock(sk);
3555 sk->sk_lock.owned = 1;
3556 __acquire(&sk->sk_lock.slock);
3557 spin_unlock_bh(&sk->sk_lock.slock);
3558 return true;
3559 }
3560 EXPORT_SYMBOL(__lock_sock_fast);
3561
sock_gettstamp(struct socket * sock,void __user * userstamp,bool timeval,bool time32)3562 int sock_gettstamp(struct socket *sock, void __user *userstamp,
3563 bool timeval, bool time32)
3564 {
3565 struct sock *sk = sock->sk;
3566 struct timespec64 ts;
3567
3568 sock_enable_timestamp(sk, SOCK_TIMESTAMP);
3569 ts = ktime_to_timespec64(sock_read_timestamp(sk));
3570 if (ts.tv_sec == -1)
3571 return -ENOENT;
3572 if (ts.tv_sec == 0) {
3573 ktime_t kt = ktime_get_real();
3574 sock_write_timestamp(sk, kt);
3575 ts = ktime_to_timespec64(kt);
3576 }
3577
3578 if (timeval)
3579 ts.tv_nsec /= 1000;
3580
3581 #ifdef CONFIG_COMPAT_32BIT_TIME
3582 if (time32)
3583 return put_old_timespec32(&ts, userstamp);
3584 #endif
3585 #ifdef CONFIG_SPARC64
3586 /* beware of padding in sparc64 timeval */
3587 if (timeval && !in_compat_syscall()) {
3588 struct __kernel_old_timeval __user tv = {
3589 .tv_sec = ts.tv_sec,
3590 .tv_usec = ts.tv_nsec,
3591 };
3592 if (copy_to_user(userstamp, &tv, sizeof(tv)))
3593 return -EFAULT;
3594 return 0;
3595 }
3596 #endif
3597 return put_timespec64(&ts, userstamp);
3598 }
3599 EXPORT_SYMBOL(sock_gettstamp);
3600
sock_enable_timestamp(struct sock * sk,enum sock_flags flag)3601 void sock_enable_timestamp(struct sock *sk, enum sock_flags flag)
3602 {
3603 if (!sock_flag(sk, flag)) {
3604 unsigned long previous_flags = sk->sk_flags;
3605
3606 sock_set_flag(sk, flag);
3607 /*
3608 * we just set one of the two flags which require net
3609 * time stamping, but time stamping might have been on
3610 * already because of the other one
3611 */
3612 if (sock_needs_netstamp(sk) &&
3613 !(previous_flags & SK_FLAGS_TIMESTAMP))
3614 net_enable_timestamp();
3615 }
3616 }
3617
sock_recv_errqueue(struct sock * sk,struct msghdr * msg,int len,int level,int type)3618 int sock_recv_errqueue(struct sock *sk, struct msghdr *msg, int len,
3619 int level, int type)
3620 {
3621 struct sock_exterr_skb *serr;
3622 struct sk_buff *skb;
3623 int copied, err;
3624
3625 err = -EAGAIN;
3626 skb = sock_dequeue_err_skb(sk);
3627 if (skb == NULL)
3628 goto out;
3629
3630 copied = skb->len;
3631 if (copied > len) {
3632 msg->msg_flags |= MSG_TRUNC;
3633 copied = len;
3634 }
3635 err = skb_copy_datagram_msg(skb, 0, msg, copied);
3636 if (err)
3637 goto out_free_skb;
3638
3639 sock_recv_timestamp(msg, sk, skb);
3640
3641 serr = SKB_EXT_ERR(skb);
3642 put_cmsg(msg, level, type, sizeof(serr->ee), &serr->ee);
3643
3644 msg->msg_flags |= MSG_ERRQUEUE;
3645 err = copied;
3646
3647 out_free_skb:
3648 kfree_skb(skb);
3649 out:
3650 return err;
3651 }
3652 EXPORT_SYMBOL(sock_recv_errqueue);
3653
3654 /*
3655 * Get a socket option on an socket.
3656 *
3657 * FIX: POSIX 1003.1g is very ambiguous here. It states that
3658 * asynchronous errors should be reported by getsockopt. We assume
3659 * this means if you specify SO_ERROR (otherwise whats the point of it).
3660 */
sock_common_getsockopt(struct socket * sock,int level,int optname,char __user * optval,int __user * optlen)3661 int sock_common_getsockopt(struct socket *sock, int level, int optname,
3662 char __user *optval, int __user *optlen)
3663 {
3664 struct sock *sk = sock->sk;
3665
3666 /* IPV6_ADDRFORM can change sk->sk_prot under us. */
3667 return READ_ONCE(sk->sk_prot)->getsockopt(sk, level, optname, optval, optlen);
3668 }
3669 EXPORT_SYMBOL(sock_common_getsockopt);
3670
sock_common_recvmsg(struct socket * sock,struct msghdr * msg,size_t size,int flags)3671 int sock_common_recvmsg(struct socket *sock, struct msghdr *msg, size_t size,
3672 int flags)
3673 {
3674 struct sock *sk = sock->sk;
3675 int addr_len = 0;
3676 int err;
3677
3678 err = sk->sk_prot->recvmsg(sk, msg, size, flags, &addr_len);
3679 if (err >= 0)
3680 msg->msg_namelen = addr_len;
3681 return err;
3682 }
3683 EXPORT_SYMBOL(sock_common_recvmsg);
3684
3685 /*
3686 * Set socket options on an inet socket.
3687 */
sock_common_setsockopt(struct socket * sock,int level,int optname,sockptr_t optval,unsigned int optlen)3688 int sock_common_setsockopt(struct socket *sock, int level, int optname,
3689 sockptr_t optval, unsigned int optlen)
3690 {
3691 struct sock *sk = sock->sk;
3692
3693 /* IPV6_ADDRFORM can change sk->sk_prot under us. */
3694 return READ_ONCE(sk->sk_prot)->setsockopt(sk, level, optname, optval, optlen);
3695 }
3696 EXPORT_SYMBOL(sock_common_setsockopt);
3697
sk_common_release(struct sock * sk)3698 void sk_common_release(struct sock *sk)
3699 {
3700 if (sk->sk_prot->destroy)
3701 sk->sk_prot->destroy(sk);
3702
3703 /*
3704 * Observation: when sk_common_release is called, processes have
3705 * no access to socket. But net still has.
3706 * Step one, detach it from networking:
3707 *
3708 * A. Remove from hash tables.
3709 */
3710
3711 sk->sk_prot->unhash(sk);
3712
3713 /*
3714 * In this point socket cannot receive new packets, but it is possible
3715 * that some packets are in flight because some CPU runs receiver and
3716 * did hash table lookup before we unhashed socket. They will achieve
3717 * receive queue and will be purged by socket destructor.
3718 *
3719 * Also we still have packets pending on receive queue and probably,
3720 * our own packets waiting in device queues. sock_destroy will drain
3721 * receive queue, but transmitted packets will delay socket destruction
3722 * until the last reference will be released.
3723 */
3724
3725 sock_orphan(sk);
3726
3727 xfrm_sk_free_policy(sk);
3728
3729 sk_refcnt_debug_release(sk);
3730
3731 sock_put(sk);
3732 }
3733 EXPORT_SYMBOL(sk_common_release);
3734
sk_get_meminfo(const struct sock * sk,u32 * mem)3735 void sk_get_meminfo(const struct sock *sk, u32 *mem)
3736 {
3737 memset(mem, 0, sizeof(*mem) * SK_MEMINFO_VARS);
3738
3739 mem[SK_MEMINFO_RMEM_ALLOC] = sk_rmem_alloc_get(sk);
3740 mem[SK_MEMINFO_RCVBUF] = READ_ONCE(sk->sk_rcvbuf);
3741 mem[SK_MEMINFO_WMEM_ALLOC] = sk_wmem_alloc_get(sk);
3742 mem[SK_MEMINFO_SNDBUF] = READ_ONCE(sk->sk_sndbuf);
3743 mem[SK_MEMINFO_FWD_ALLOC] = sk_forward_alloc_get(sk);
3744 mem[SK_MEMINFO_WMEM_QUEUED] = READ_ONCE(sk->sk_wmem_queued);
3745 mem[SK_MEMINFO_OPTMEM] = atomic_read(&sk->sk_omem_alloc);
3746 mem[SK_MEMINFO_BACKLOG] = READ_ONCE(sk->sk_backlog.len);
3747 mem[SK_MEMINFO_DROPS] = atomic_read(&sk->sk_drops);
3748 }
3749
3750 #ifdef CONFIG_PROC_FS
3751 static DECLARE_BITMAP(proto_inuse_idx, PROTO_INUSE_NR);
3752
sock_prot_inuse_get(struct net * net,struct proto * prot)3753 int sock_prot_inuse_get(struct net *net, struct proto *prot)
3754 {
3755 int cpu, idx = prot->inuse_idx;
3756 int res = 0;
3757
3758 for_each_possible_cpu(cpu)
3759 res += per_cpu_ptr(net->core.prot_inuse, cpu)->val[idx];
3760
3761 return res >= 0 ? res : 0;
3762 }
3763 EXPORT_SYMBOL_GPL(sock_prot_inuse_get);
3764
sock_inuse_get(struct net * net)3765 int sock_inuse_get(struct net *net)
3766 {
3767 int cpu, res = 0;
3768
3769 for_each_possible_cpu(cpu)
3770 res += per_cpu_ptr(net->core.prot_inuse, cpu)->all;
3771
3772 return res;
3773 }
3774
3775 EXPORT_SYMBOL_GPL(sock_inuse_get);
3776
sock_inuse_init_net(struct net * net)3777 static int __net_init sock_inuse_init_net(struct net *net)
3778 {
3779 net->core.prot_inuse = alloc_percpu(struct prot_inuse);
3780 if (net->core.prot_inuse == NULL)
3781 return -ENOMEM;
3782 return 0;
3783 }
3784
sock_inuse_exit_net(struct net * net)3785 static void __net_exit sock_inuse_exit_net(struct net *net)
3786 {
3787 free_percpu(net->core.prot_inuse);
3788 }
3789
3790 static struct pernet_operations net_inuse_ops = {
3791 .init = sock_inuse_init_net,
3792 .exit = sock_inuse_exit_net,
3793 };
3794
net_inuse_init(void)3795 static __init int net_inuse_init(void)
3796 {
3797 if (register_pernet_subsys(&net_inuse_ops))
3798 panic("Cannot initialize net inuse counters");
3799
3800 return 0;
3801 }
3802
3803 core_initcall(net_inuse_init);
3804
assign_proto_idx(struct proto * prot)3805 static int assign_proto_idx(struct proto *prot)
3806 {
3807 prot->inuse_idx = find_first_zero_bit(proto_inuse_idx, PROTO_INUSE_NR);
3808
3809 if (unlikely(prot->inuse_idx == PROTO_INUSE_NR - 1)) {
3810 pr_err("PROTO_INUSE_NR exhausted\n");
3811 return -ENOSPC;
3812 }
3813
3814 set_bit(prot->inuse_idx, proto_inuse_idx);
3815 return 0;
3816 }
3817
release_proto_idx(struct proto * prot)3818 static void release_proto_idx(struct proto *prot)
3819 {
3820 if (prot->inuse_idx != PROTO_INUSE_NR - 1)
3821 clear_bit(prot->inuse_idx, proto_inuse_idx);
3822 }
3823 #else
assign_proto_idx(struct proto * prot)3824 static inline int assign_proto_idx(struct proto *prot)
3825 {
3826 return 0;
3827 }
3828
release_proto_idx(struct proto * prot)3829 static inline void release_proto_idx(struct proto *prot)
3830 {
3831 }
3832
3833 #endif
3834
tw_prot_cleanup(struct timewait_sock_ops * twsk_prot)3835 static void tw_prot_cleanup(struct timewait_sock_ops *twsk_prot)
3836 {
3837 if (!twsk_prot)
3838 return;
3839 kfree(twsk_prot->twsk_slab_name);
3840 twsk_prot->twsk_slab_name = NULL;
3841 kmem_cache_destroy(twsk_prot->twsk_slab);
3842 twsk_prot->twsk_slab = NULL;
3843 }
3844
tw_prot_init(const struct proto * prot)3845 static int tw_prot_init(const struct proto *prot)
3846 {
3847 struct timewait_sock_ops *twsk_prot = prot->twsk_prot;
3848
3849 if (!twsk_prot)
3850 return 0;
3851
3852 twsk_prot->twsk_slab_name = kasprintf(GFP_KERNEL, "tw_sock_%s",
3853 prot->name);
3854 if (!twsk_prot->twsk_slab_name)
3855 return -ENOMEM;
3856
3857 twsk_prot->twsk_slab =
3858 kmem_cache_create(twsk_prot->twsk_slab_name,
3859 twsk_prot->twsk_obj_size, 0,
3860 SLAB_ACCOUNT | prot->slab_flags,
3861 NULL);
3862 if (!twsk_prot->twsk_slab) {
3863 pr_crit("%s: Can't create timewait sock SLAB cache!\n",
3864 prot->name);
3865 return -ENOMEM;
3866 }
3867
3868 return 0;
3869 }
3870
req_prot_cleanup(struct request_sock_ops * rsk_prot)3871 static void req_prot_cleanup(struct request_sock_ops *rsk_prot)
3872 {
3873 if (!rsk_prot)
3874 return;
3875 kfree(rsk_prot->slab_name);
3876 rsk_prot->slab_name = NULL;
3877 kmem_cache_destroy(rsk_prot->slab);
3878 rsk_prot->slab = NULL;
3879 }
3880
req_prot_init(const struct proto * prot)3881 static int req_prot_init(const struct proto *prot)
3882 {
3883 struct request_sock_ops *rsk_prot = prot->rsk_prot;
3884
3885 if (!rsk_prot)
3886 return 0;
3887
3888 rsk_prot->slab_name = kasprintf(GFP_KERNEL, "request_sock_%s",
3889 prot->name);
3890 if (!rsk_prot->slab_name)
3891 return -ENOMEM;
3892
3893 rsk_prot->slab = kmem_cache_create(rsk_prot->slab_name,
3894 rsk_prot->obj_size, 0,
3895 SLAB_ACCOUNT | prot->slab_flags,
3896 NULL);
3897
3898 if (!rsk_prot->slab) {
3899 pr_crit("%s: Can't create request sock SLAB cache!\n",
3900 prot->name);
3901 return -ENOMEM;
3902 }
3903 return 0;
3904 }
3905
proto_register(struct proto * prot,int alloc_slab)3906 int proto_register(struct proto *prot, int alloc_slab)
3907 {
3908 int ret = -ENOBUFS;
3909
3910 if (prot->memory_allocated && !prot->sysctl_mem) {
3911 pr_err("%s: missing sysctl_mem\n", prot->name);
3912 return -EINVAL;
3913 }
3914 if (prot->memory_allocated && !prot->per_cpu_fw_alloc) {
3915 pr_err("%s: missing per_cpu_fw_alloc\n", prot->name);
3916 return -EINVAL;
3917 }
3918 if (alloc_slab) {
3919 prot->slab = kmem_cache_create_usercopy(prot->name,
3920 prot->obj_size, 0,
3921 SLAB_HWCACHE_ALIGN | SLAB_ACCOUNT |
3922 prot->slab_flags,
3923 prot->useroffset, prot->usersize,
3924 NULL);
3925
3926 if (prot->slab == NULL) {
3927 pr_crit("%s: Can't create sock SLAB cache!\n",
3928 prot->name);
3929 goto out;
3930 }
3931
3932 if (req_prot_init(prot))
3933 goto out_free_request_sock_slab;
3934
3935 if (tw_prot_init(prot))
3936 goto out_free_timewait_sock_slab;
3937 }
3938
3939 mutex_lock(&proto_list_mutex);
3940 ret = assign_proto_idx(prot);
3941 if (ret) {
3942 mutex_unlock(&proto_list_mutex);
3943 goto out_free_timewait_sock_slab;
3944 }
3945 list_add(&prot->node, &proto_list);
3946 mutex_unlock(&proto_list_mutex);
3947 return ret;
3948
3949 out_free_timewait_sock_slab:
3950 if (alloc_slab)
3951 tw_prot_cleanup(prot->twsk_prot);
3952 out_free_request_sock_slab:
3953 if (alloc_slab) {
3954 req_prot_cleanup(prot->rsk_prot);
3955
3956 kmem_cache_destroy(prot->slab);
3957 prot->slab = NULL;
3958 }
3959 out:
3960 return ret;
3961 }
3962 EXPORT_SYMBOL(proto_register);
3963
proto_unregister(struct proto * prot)3964 void proto_unregister(struct proto *prot)
3965 {
3966 mutex_lock(&proto_list_mutex);
3967 release_proto_idx(prot);
3968 list_del(&prot->node);
3969 mutex_unlock(&proto_list_mutex);
3970
3971 kmem_cache_destroy(prot->slab);
3972 prot->slab = NULL;
3973
3974 req_prot_cleanup(prot->rsk_prot);
3975 tw_prot_cleanup(prot->twsk_prot);
3976 }
3977 EXPORT_SYMBOL(proto_unregister);
3978
sock_load_diag_module(int family,int protocol)3979 int sock_load_diag_module(int family, int protocol)
3980 {
3981 if (!protocol) {
3982 if (!sock_is_registered(family))
3983 return -ENOENT;
3984
3985 return request_module("net-pf-%d-proto-%d-type-%d", PF_NETLINK,
3986 NETLINK_SOCK_DIAG, family);
3987 }
3988
3989 #ifdef CONFIG_INET
3990 if (family == AF_INET &&
3991 protocol != IPPROTO_RAW &&
3992 protocol < MAX_INET_PROTOS &&
3993 !rcu_access_pointer(inet_protos[protocol]))
3994 return -ENOENT;
3995 #endif
3996
3997 return request_module("net-pf-%d-proto-%d-type-%d-%d", PF_NETLINK,
3998 NETLINK_SOCK_DIAG, family, protocol);
3999 }
4000 EXPORT_SYMBOL(sock_load_diag_module);
4001
4002 #ifdef CONFIG_PROC_FS
proto_seq_start(struct seq_file * seq,loff_t * pos)4003 static void *proto_seq_start(struct seq_file *seq, loff_t *pos)
4004 __acquires(proto_list_mutex)
4005 {
4006 mutex_lock(&proto_list_mutex);
4007 return seq_list_start_head(&proto_list, *pos);
4008 }
4009
proto_seq_next(struct seq_file * seq,void * v,loff_t * pos)4010 static void *proto_seq_next(struct seq_file *seq, void *v, loff_t *pos)
4011 {
4012 return seq_list_next(v, &proto_list, pos);
4013 }
4014
proto_seq_stop(struct seq_file * seq,void * v)4015 static void proto_seq_stop(struct seq_file *seq, void *v)
4016 __releases(proto_list_mutex)
4017 {
4018 mutex_unlock(&proto_list_mutex);
4019 }
4020
proto_method_implemented(const void * method)4021 static char proto_method_implemented(const void *method)
4022 {
4023 return method == NULL ? 'n' : 'y';
4024 }
sock_prot_memory_allocated(struct proto * proto)4025 static long sock_prot_memory_allocated(struct proto *proto)
4026 {
4027 return proto->memory_allocated != NULL ? proto_memory_allocated(proto) : -1L;
4028 }
4029
sock_prot_memory_pressure(struct proto * proto)4030 static const char *sock_prot_memory_pressure(struct proto *proto)
4031 {
4032 return proto->memory_pressure != NULL ?
4033 proto_memory_pressure(proto) ? "yes" : "no" : "NI";
4034 }
4035
proto_seq_printf(struct seq_file * seq,struct proto * proto)4036 static void proto_seq_printf(struct seq_file *seq, struct proto *proto)
4037 {
4038
4039 seq_printf(seq, "%-9s %4u %6d %6ld %-3s %6u %-3s %-10s "
4040 "%2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c\n",
4041 proto->name,
4042 proto->obj_size,
4043 sock_prot_inuse_get(seq_file_net(seq), proto),
4044 sock_prot_memory_allocated(proto),
4045 sock_prot_memory_pressure(proto),
4046 proto->max_header,
4047 proto->slab == NULL ? "no" : "yes",
4048 module_name(proto->owner),
4049 proto_method_implemented(proto->close),
4050 proto_method_implemented(proto->connect),
4051 proto_method_implemented(proto->disconnect),
4052 proto_method_implemented(proto->accept),
4053 proto_method_implemented(proto->ioctl),
4054 proto_method_implemented(proto->init),
4055 proto_method_implemented(proto->destroy),
4056 proto_method_implemented(proto->shutdown),
4057 proto_method_implemented(proto->setsockopt),
4058 proto_method_implemented(proto->getsockopt),
4059 proto_method_implemented(proto->sendmsg),
4060 proto_method_implemented(proto->recvmsg),
4061 proto_method_implemented(proto->sendpage),
4062 proto_method_implemented(proto->bind),
4063 proto_method_implemented(proto->backlog_rcv),
4064 proto_method_implemented(proto->hash),
4065 proto_method_implemented(proto->unhash),
4066 proto_method_implemented(proto->get_port),
4067 proto_method_implemented(proto->enter_memory_pressure));
4068 }
4069
proto_seq_show(struct seq_file * seq,void * v)4070 static int proto_seq_show(struct seq_file *seq, void *v)
4071 {
4072 if (v == &proto_list)
4073 seq_printf(seq, "%-9s %-4s %-8s %-6s %-5s %-7s %-4s %-10s %s",
4074 "protocol",
4075 "size",
4076 "sockets",
4077 "memory",
4078 "press",
4079 "maxhdr",
4080 "slab",
4081 "module",
4082 "cl co di ac io in de sh ss gs se re sp bi br ha uh gp em\n");
4083 else
4084 proto_seq_printf(seq, list_entry(v, struct proto, node));
4085 return 0;
4086 }
4087
4088 static const struct seq_operations proto_seq_ops = {
4089 .start = proto_seq_start,
4090 .next = proto_seq_next,
4091 .stop = proto_seq_stop,
4092 .show = proto_seq_show,
4093 };
4094
proto_init_net(struct net * net)4095 static __net_init int proto_init_net(struct net *net)
4096 {
4097 if (!proc_create_net("protocols", 0444, net->proc_net, &proto_seq_ops,
4098 sizeof(struct seq_net_private)))
4099 return -ENOMEM;
4100
4101 return 0;
4102 }
4103
proto_exit_net(struct net * net)4104 static __net_exit void proto_exit_net(struct net *net)
4105 {
4106 remove_proc_entry("protocols", net->proc_net);
4107 }
4108
4109
4110 static __net_initdata struct pernet_operations proto_net_ops = {
4111 .init = proto_init_net,
4112 .exit = proto_exit_net,
4113 };
4114
proto_init(void)4115 static int __init proto_init(void)
4116 {
4117 return register_pernet_subsys(&proto_net_ops);
4118 }
4119
4120 subsys_initcall(proto_init);
4121
4122 #endif /* PROC_FS */
4123
4124 #ifdef CONFIG_NET_RX_BUSY_POLL
sk_busy_loop_end(void * p,unsigned long start_time)4125 bool sk_busy_loop_end(void *p, unsigned long start_time)
4126 {
4127 struct sock *sk = p;
4128
4129 if (!skb_queue_empty_lockless(&sk->sk_receive_queue))
4130 return true;
4131
4132 if (sk_is_udp(sk) &&
4133 !skb_queue_empty_lockless(&udp_sk(sk)->reader_queue))
4134 return true;
4135
4136 return sk_busy_loop_timeout(sk, start_time);
4137 }
4138 EXPORT_SYMBOL(sk_busy_loop_end);
4139 #endif /* CONFIG_NET_RX_BUSY_POLL */
4140
sock_bind_add(struct sock * sk,struct sockaddr * addr,int addr_len)4141 int sock_bind_add(struct sock *sk, struct sockaddr *addr, int addr_len)
4142 {
4143 if (!sk->sk_prot->bind_add)
4144 return -EOPNOTSUPP;
4145 return sk->sk_prot->bind_add(sk, addr, addr_len);
4146 }
4147 EXPORT_SYMBOL(sock_bind_add);
4148