PageRenderTime 71ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/net/core/sock.c

http://github.com/mirrors/linux
C | 3627 lines | 2606 code | 537 blank | 484 comment | 441 complexity | 6f71689e654581312f9fd9a8aa4beffa MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0, LGPL-2.0
  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. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  86. #include <asm/unaligned.h>
  87. #include <linux/capability.h>
  88. #include <linux/errno.h>
  89. #include <linux/errqueue.h>
  90. #include <linux/types.h>
  91. #include <linux/socket.h>
  92. #include <linux/in.h>
  93. #include <linux/kernel.h>
  94. #include <linux/module.h>
  95. #include <linux/proc_fs.h>
  96. #include <linux/seq_file.h>
  97. #include <linux/sched.h>
  98. #include <linux/sched/mm.h>
  99. #include <linux/timer.h>
  100. #include <linux/string.h>
  101. #include <linux/sockios.h>
  102. #include <linux/net.h>
  103. #include <linux/mm.h>
  104. #include <linux/slab.h>
  105. #include <linux/interrupt.h>
  106. #include <linux/poll.h>
  107. #include <linux/tcp.h>
  108. #include <linux/init.h>
  109. #include <linux/highmem.h>
  110. #include <linux/user_namespace.h>
  111. #include <linux/static_key.h>
  112. #include <linux/memcontrol.h>
  113. #include <linux/prefetch.h>
  114. #include <linux/uaccess.h>
  115. #include <linux/netdevice.h>
  116. #include <net/protocol.h>
  117. #include <linux/skbuff.h>
  118. #include <net/net_namespace.h>
  119. #include <net/request_sock.h>
  120. #include <net/sock.h>
  121. #include <linux/net_tstamp.h>
  122. #include <net/xfrm.h>
  123. #include <linux/ipsec.h>
  124. #include <net/cls_cgroup.h>
  125. #include <net/netprio_cgroup.h>
  126. #include <linux/sock_diag.h>
  127. #include <linux/filter.h>
  128. #include <net/sock_reuseport.h>
  129. #include <net/bpf_sk_storage.h>
  130. #include <trace/events/sock.h>
  131. #include <net/tcp.h>
  132. #include <net/busy_poll.h>
  133. static DEFINE_MUTEX(proto_list_mutex);
  134. static LIST_HEAD(proto_list);
  135. static void sock_inuse_add(struct net *net, int val);
  136. /**
  137. * sk_ns_capable - General socket capability test
  138. * @sk: Socket to use a capability on or through
  139. * @user_ns: The user namespace of the capability to use
  140. * @cap: The capability to use
  141. *
  142. * Test to see if the opener of the socket had when the socket was
  143. * created and the current process has the capability @cap in the user
  144. * namespace @user_ns.
  145. */
  146. bool sk_ns_capable(const struct sock *sk,
  147. struct user_namespace *user_ns, int cap)
  148. {
  149. return file_ns_capable(sk->sk_socket->file, user_ns, cap) &&
  150. ns_capable(user_ns, cap);
  151. }
  152. EXPORT_SYMBOL(sk_ns_capable);
  153. /**
  154. * sk_capable - Socket global capability test
  155. * @sk: Socket to use a capability on or through
  156. * @cap: The global capability to use
  157. *
  158. * Test to see if the opener of the socket had when the socket was
  159. * created and the current process has the capability @cap in all user
  160. * namespaces.
  161. */
  162. bool sk_capable(const struct sock *sk, int cap)
  163. {
  164. return sk_ns_capable(sk, &init_user_ns, cap);
  165. }
  166. EXPORT_SYMBOL(sk_capable);
  167. /**
  168. * sk_net_capable - Network namespace socket capability test
  169. * @sk: Socket to use a capability on or through
  170. * @cap: The capability to use
  171. *
  172. * Test to see if the opener of the socket had when the socket was created
  173. * and the current process has the capability @cap over the network namespace
  174. * the socket is a member of.
  175. */
  176. bool sk_net_capable(const struct sock *sk, int cap)
  177. {
  178. return sk_ns_capable(sk, sock_net(sk)->user_ns, cap);
  179. }
  180. EXPORT_SYMBOL(sk_net_capable);
  181. /*
  182. * Each address family might have different locking rules, so we have
  183. * one slock key per address family and separate keys for internal and
  184. * userspace sockets.
  185. */
  186. static struct lock_class_key af_family_keys[AF_MAX];
  187. static struct lock_class_key af_family_kern_keys[AF_MAX];
  188. static struct lock_class_key af_family_slock_keys[AF_MAX];
  189. static struct lock_class_key af_family_kern_slock_keys[AF_MAX];
  190. /*
  191. * Make lock validator output more readable. (we pre-construct these
  192. * strings build-time, so that runtime initialization of socket
  193. * locks is fast):
  194. */
  195. #define _sock_locks(x) \
  196. x "AF_UNSPEC", x "AF_UNIX" , x "AF_INET" , \
  197. x "AF_AX25" , x "AF_IPX" , x "AF_APPLETALK", \
  198. x "AF_NETROM", x "AF_BRIDGE" , x "AF_ATMPVC" , \
  199. x "AF_X25" , x "AF_INET6" , x "AF_ROSE" , \
  200. x "AF_DECnet", x "AF_NETBEUI" , x "AF_SECURITY" , \
  201. x "AF_KEY" , x "AF_NETLINK" , x "AF_PACKET" , \
  202. x "AF_ASH" , x "AF_ECONET" , x "AF_ATMSVC" , \
  203. x "AF_RDS" , x "AF_SNA" , x "AF_IRDA" , \
  204. x "AF_PPPOX" , x "AF_WANPIPE" , x "AF_LLC" , \
  205. x "27" , x "28" , x "AF_CAN" , \
  206. x "AF_TIPC" , x "AF_BLUETOOTH", x "IUCV" , \
  207. x "AF_RXRPC" , x "AF_ISDN" , x "AF_PHONET" , \
  208. x "AF_IEEE802154", x "AF_CAIF" , x "AF_ALG" , \
  209. x "AF_NFC" , x "AF_VSOCK" , x "AF_KCM" , \
  210. x "AF_QIPCRTR", x "AF_SMC" , x "AF_XDP" , \
  211. x "AF_MAX"
  212. static const char *const af_family_key_strings[AF_MAX+1] = {
  213. _sock_locks("sk_lock-")
  214. };
  215. static const char *const af_family_slock_key_strings[AF_MAX+1] = {
  216. _sock_locks("slock-")
  217. };
  218. static const char *const af_family_clock_key_strings[AF_MAX+1] = {
  219. _sock_locks("clock-")
  220. };
  221. static const char *const af_family_kern_key_strings[AF_MAX+1] = {
  222. _sock_locks("k-sk_lock-")
  223. };
  224. static const char *const af_family_kern_slock_key_strings[AF_MAX+1] = {
  225. _sock_locks("k-slock-")
  226. };
  227. static const char *const af_family_kern_clock_key_strings[AF_MAX+1] = {
  228. _sock_locks("k-clock-")
  229. };
  230. static const char *const af_family_rlock_key_strings[AF_MAX+1] = {
  231. _sock_locks("rlock-")
  232. };
  233. static const char *const af_family_wlock_key_strings[AF_MAX+1] = {
  234. _sock_locks("wlock-")
  235. };
  236. static const char *const af_family_elock_key_strings[AF_MAX+1] = {
  237. _sock_locks("elock-")
  238. };
  239. /*
  240. * sk_callback_lock and sk queues locking rules are per-address-family,
  241. * so split the lock classes by using a per-AF key:
  242. */
  243. static struct lock_class_key af_callback_keys[AF_MAX];
  244. static struct lock_class_key af_rlock_keys[AF_MAX];
  245. static struct lock_class_key af_wlock_keys[AF_MAX];
  246. static struct lock_class_key af_elock_keys[AF_MAX];
  247. static struct lock_class_key af_kern_callback_keys[AF_MAX];
  248. /* Run time adjustable parameters. */
  249. __u32 sysctl_wmem_max __read_mostly = SK_WMEM_MAX;
  250. EXPORT_SYMBOL(sysctl_wmem_max);
  251. __u32 sysctl_rmem_max __read_mostly = SK_RMEM_MAX;
  252. EXPORT_SYMBOL(sysctl_rmem_max);
  253. __u32 sysctl_wmem_default __read_mostly = SK_WMEM_MAX;
  254. __u32 sysctl_rmem_default __read_mostly = SK_RMEM_MAX;
  255. /* Maximal space eaten by iovec or ancillary data plus some space */
  256. int sysctl_optmem_max __read_mostly = sizeof(unsigned long)*(2*UIO_MAXIOV+512);
  257. EXPORT_SYMBOL(sysctl_optmem_max);
  258. int sysctl_tstamp_allow_data __read_mostly = 1;
  259. DEFINE_STATIC_KEY_FALSE(memalloc_socks_key);
  260. EXPORT_SYMBOL_GPL(memalloc_socks_key);
  261. /**
  262. * sk_set_memalloc - sets %SOCK_MEMALLOC
  263. * @sk: socket to set it on
  264. *
  265. * Set %SOCK_MEMALLOC on a socket for access to emergency reserves.
  266. * It's the responsibility of the admin to adjust min_free_kbytes
  267. * to meet the requirements
  268. */
  269. void sk_set_memalloc(struct sock *sk)
  270. {
  271. sock_set_flag(sk, SOCK_MEMALLOC);
  272. sk->sk_allocation |= __GFP_MEMALLOC;
  273. static_branch_inc(&memalloc_socks_key);
  274. }
  275. EXPORT_SYMBOL_GPL(sk_set_memalloc);
  276. void sk_clear_memalloc(struct sock *sk)
  277. {
  278. sock_reset_flag(sk, SOCK_MEMALLOC);
  279. sk->sk_allocation &= ~__GFP_MEMALLOC;
  280. static_branch_dec(&memalloc_socks_key);
  281. /*
  282. * SOCK_MEMALLOC is allowed to ignore rmem limits to ensure forward
  283. * progress of swapping. SOCK_MEMALLOC may be cleared while
  284. * it has rmem allocations due to the last swapfile being deactivated
  285. * but there is a risk that the socket is unusable due to exceeding
  286. * the rmem limits. Reclaim the reserves and obey rmem limits again.
  287. */
  288. sk_mem_reclaim(sk);
  289. }
  290. EXPORT_SYMBOL_GPL(sk_clear_memalloc);
  291. int __sk_backlog_rcv(struct sock *sk, struct sk_buff *skb)
  292. {
  293. int ret;
  294. unsigned int noreclaim_flag;
  295. /* these should have been dropped before queueing */
  296. BUG_ON(!sock_flag(sk, SOCK_MEMALLOC));
  297. noreclaim_flag = memalloc_noreclaim_save();
  298. ret = sk->sk_backlog_rcv(sk, skb);
  299. memalloc_noreclaim_restore(noreclaim_flag);
  300. return ret;
  301. }
  302. EXPORT_SYMBOL(__sk_backlog_rcv);
  303. static int sock_get_timeout(long timeo, void *optval, bool old_timeval)
  304. {
  305. struct __kernel_sock_timeval tv;
  306. if (timeo == MAX_SCHEDULE_TIMEOUT) {
  307. tv.tv_sec = 0;
  308. tv.tv_usec = 0;
  309. } else {
  310. tv.tv_sec = timeo / HZ;
  311. tv.tv_usec = ((timeo % HZ) * USEC_PER_SEC) / HZ;
  312. }
  313. if (old_timeval && in_compat_syscall() && !COMPAT_USE_64BIT_TIME) {
  314. struct old_timeval32 tv32 = { tv.tv_sec, tv.tv_usec };
  315. *(struct old_timeval32 *)optval = tv32;
  316. return sizeof(tv32);
  317. }
  318. if (old_timeval) {
  319. struct __kernel_old_timeval old_tv;
  320. old_tv.tv_sec = tv.tv_sec;
  321. old_tv.tv_usec = tv.tv_usec;
  322. *(struct __kernel_old_timeval *)optval = old_tv;
  323. return sizeof(old_tv);
  324. }
  325. *(struct __kernel_sock_timeval *)optval = tv;
  326. return sizeof(tv);
  327. }
  328. static int sock_set_timeout(long *timeo_p, char __user *optval, int optlen, bool old_timeval)
  329. {
  330. struct __kernel_sock_timeval tv;
  331. if (old_timeval && in_compat_syscall() && !COMPAT_USE_64BIT_TIME) {
  332. struct old_timeval32 tv32;
  333. if (optlen < sizeof(tv32))
  334. return -EINVAL;
  335. if (copy_from_user(&tv32, optval, sizeof(tv32)))
  336. return -EFAULT;
  337. tv.tv_sec = tv32.tv_sec;
  338. tv.tv_usec = tv32.tv_usec;
  339. } else if (old_timeval) {
  340. struct __kernel_old_timeval old_tv;
  341. if (optlen < sizeof(old_tv))
  342. return -EINVAL;
  343. if (copy_from_user(&old_tv, optval, sizeof(old_tv)))
  344. return -EFAULT;
  345. tv.tv_sec = old_tv.tv_sec;
  346. tv.tv_usec = old_tv.tv_usec;
  347. } else {
  348. if (optlen < sizeof(tv))
  349. return -EINVAL;
  350. if (copy_from_user(&tv, optval, sizeof(tv)))
  351. return -EFAULT;
  352. }
  353. if (tv.tv_usec < 0 || tv.tv_usec >= USEC_PER_SEC)
  354. return -EDOM;
  355. if (tv.tv_sec < 0) {
  356. static int warned __read_mostly;
  357. *timeo_p = 0;
  358. if (warned < 10 && net_ratelimit()) {
  359. warned++;
  360. pr_info("%s: `%s' (pid %d) tries to set negative timeout\n",
  361. __func__, current->comm, task_pid_nr(current));
  362. }
  363. return 0;
  364. }
  365. *timeo_p = MAX_SCHEDULE_TIMEOUT;
  366. if (tv.tv_sec == 0 && tv.tv_usec == 0)
  367. return 0;
  368. if (tv.tv_sec < (MAX_SCHEDULE_TIMEOUT / HZ - 1))
  369. *timeo_p = tv.tv_sec * HZ + DIV_ROUND_UP((unsigned long)tv.tv_usec, USEC_PER_SEC / HZ);
  370. return 0;
  371. }
  372. static void sock_warn_obsolete_bsdism(const char *name)
  373. {
  374. static int warned;
  375. static char warncomm[TASK_COMM_LEN];
  376. if (strcmp(warncomm, current->comm) && warned < 5) {
  377. strcpy(warncomm, current->comm);
  378. pr_warn("process `%s' is using obsolete %s SO_BSDCOMPAT\n",
  379. warncomm, name);
  380. warned++;
  381. }
  382. }
  383. static bool sock_needs_netstamp(const struct sock *sk)
  384. {
  385. switch (sk->sk_family) {
  386. case AF_UNSPEC:
  387. case AF_UNIX:
  388. return false;
  389. default:
  390. return true;
  391. }
  392. }
  393. static void sock_disable_timestamp(struct sock *sk, unsigned long flags)
  394. {
  395. if (sk->sk_flags & flags) {
  396. sk->sk_flags &= ~flags;
  397. if (sock_needs_netstamp(sk) &&
  398. !(sk->sk_flags & SK_FLAGS_TIMESTAMP))
  399. net_disable_timestamp();
  400. }
  401. }
  402. int __sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
  403. {
  404. unsigned long flags;
  405. struct sk_buff_head *list = &sk->sk_receive_queue;
  406. if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) {
  407. atomic_inc(&sk->sk_drops);
  408. trace_sock_rcvqueue_full(sk, skb);
  409. return -ENOMEM;
  410. }
  411. if (!sk_rmem_schedule(sk, skb, skb->truesize)) {
  412. atomic_inc(&sk->sk_drops);
  413. return -ENOBUFS;
  414. }
  415. skb->dev = NULL;
  416. skb_set_owner_r(skb, sk);
  417. /* we escape from rcu protected region, make sure we dont leak
  418. * a norefcounted dst
  419. */
  420. skb_dst_force(skb);
  421. spin_lock_irqsave(&list->lock, flags);
  422. sock_skb_set_dropcount(sk, skb);
  423. __skb_queue_tail(list, skb);
  424. spin_unlock_irqrestore(&list->lock, flags);
  425. if (!sock_flag(sk, SOCK_DEAD))
  426. sk->sk_data_ready(sk);
  427. return 0;
  428. }
  429. EXPORT_SYMBOL(__sock_queue_rcv_skb);
  430. int sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
  431. {
  432. int err;
  433. err = sk_filter(sk, skb);
  434. if (err)
  435. return err;
  436. return __sock_queue_rcv_skb(sk, skb);
  437. }
  438. EXPORT_SYMBOL(sock_queue_rcv_skb);
  439. int __sk_receive_skb(struct sock *sk, struct sk_buff *skb,
  440. const int nested, unsigned int trim_cap, bool refcounted)
  441. {
  442. int rc = NET_RX_SUCCESS;
  443. if (sk_filter_trim_cap(sk, skb, trim_cap))
  444. goto discard_and_relse;
  445. skb->dev = NULL;
  446. if (sk_rcvqueues_full(sk, sk->sk_rcvbuf)) {
  447. atomic_inc(&sk->sk_drops);
  448. goto discard_and_relse;
  449. }
  450. if (nested)
  451. bh_lock_sock_nested(sk);
  452. else
  453. bh_lock_sock(sk);
  454. if (!sock_owned_by_user(sk)) {
  455. /*
  456. * trylock + unlock semantics:
  457. */
  458. mutex_acquire(&sk->sk_lock.dep_map, 0, 1, _RET_IP_);
  459. rc = sk_backlog_rcv(sk, skb);
  460. mutex_release(&sk->sk_lock.dep_map, _RET_IP_);
  461. } else if (sk_add_backlog(sk, skb, READ_ONCE(sk->sk_rcvbuf))) {
  462. bh_unlock_sock(sk);
  463. atomic_inc(&sk->sk_drops);
  464. goto discard_and_relse;
  465. }
  466. bh_unlock_sock(sk);
  467. out:
  468. if (refcounted)
  469. sock_put(sk);
  470. return rc;
  471. discard_and_relse:
  472. kfree_skb(skb);
  473. goto out;
  474. }
  475. EXPORT_SYMBOL(__sk_receive_skb);
  476. struct dst_entry *__sk_dst_check(struct sock *sk, u32 cookie)
  477. {
  478. struct dst_entry *dst = __sk_dst_get(sk);
  479. if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) {
  480. sk_tx_queue_clear(sk);
  481. sk->sk_dst_pending_confirm = 0;
  482. RCU_INIT_POINTER(sk->sk_dst_cache, NULL);
  483. dst_release(dst);
  484. return NULL;
  485. }
  486. return dst;
  487. }
  488. EXPORT_SYMBOL(__sk_dst_check);
  489. struct dst_entry *sk_dst_check(struct sock *sk, u32 cookie)
  490. {
  491. struct dst_entry *dst = sk_dst_get(sk);
  492. if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) {
  493. sk_dst_reset(sk);
  494. dst_release(dst);
  495. return NULL;
  496. }
  497. return dst;
  498. }
  499. EXPORT_SYMBOL(sk_dst_check);
  500. static int sock_setbindtodevice_locked(struct sock *sk, int ifindex)
  501. {
  502. int ret = -ENOPROTOOPT;
  503. #ifdef CONFIG_NETDEVICES
  504. struct net *net = sock_net(sk);
  505. /* Sorry... */
  506. ret = -EPERM;
  507. if (sk->sk_bound_dev_if && !ns_capable(net->user_ns, CAP_NET_RAW))
  508. goto out;
  509. ret = -EINVAL;
  510. if (ifindex < 0)
  511. goto out;
  512. sk->sk_bound_dev_if = ifindex;
  513. if (sk->sk_prot->rehash)
  514. sk->sk_prot->rehash(sk);
  515. sk_dst_reset(sk);
  516. ret = 0;
  517. out:
  518. #endif
  519. return ret;
  520. }
  521. static int sock_setbindtodevice(struct sock *sk, char __user *optval,
  522. int optlen)
  523. {
  524. int ret = -ENOPROTOOPT;
  525. #ifdef CONFIG_NETDEVICES
  526. struct net *net = sock_net(sk);
  527. char devname[IFNAMSIZ];
  528. int index;
  529. ret = -EINVAL;
  530. if (optlen < 0)
  531. goto out;
  532. /* Bind this socket to a particular device like "eth0",
  533. * as specified in the passed interface name. If the
  534. * name is "" or the option length is zero the socket
  535. * is not bound.
  536. */
  537. if (optlen > IFNAMSIZ - 1)
  538. optlen = IFNAMSIZ - 1;
  539. memset(devname, 0, sizeof(devname));
  540. ret = -EFAULT;
  541. if (copy_from_user(devname, optval, optlen))
  542. goto out;
  543. index = 0;
  544. if (devname[0] != '\0') {
  545. struct net_device *dev;
  546. rcu_read_lock();
  547. dev = dev_get_by_name_rcu(net, devname);
  548. if (dev)
  549. index = dev->ifindex;
  550. rcu_read_unlock();
  551. ret = -ENODEV;
  552. if (!dev)
  553. goto out;
  554. }
  555. lock_sock(sk);
  556. ret = sock_setbindtodevice_locked(sk, index);
  557. release_sock(sk);
  558. out:
  559. #endif
  560. return ret;
  561. }
  562. static int sock_getbindtodevice(struct sock *sk, char __user *optval,
  563. int __user *optlen, int len)
  564. {
  565. int ret = -ENOPROTOOPT;
  566. #ifdef CONFIG_NETDEVICES
  567. struct net *net = sock_net(sk);
  568. char devname[IFNAMSIZ];
  569. if (sk->sk_bound_dev_if == 0) {
  570. len = 0;
  571. goto zero;
  572. }
  573. ret = -EINVAL;
  574. if (len < IFNAMSIZ)
  575. goto out;
  576. ret = netdev_get_name(net, devname, sk->sk_bound_dev_if);
  577. if (ret)
  578. goto out;
  579. len = strlen(devname) + 1;
  580. ret = -EFAULT;
  581. if (copy_to_user(optval, devname, len))
  582. goto out;
  583. zero:
  584. ret = -EFAULT;
  585. if (put_user(len, optlen))
  586. goto out;
  587. ret = 0;
  588. out:
  589. #endif
  590. return ret;
  591. }
  592. static inline void sock_valbool_flag(struct sock *sk, enum sock_flags bit,
  593. int valbool)
  594. {
  595. if (valbool)
  596. sock_set_flag(sk, bit);
  597. else
  598. sock_reset_flag(sk, bit);
  599. }
  600. bool sk_mc_loop(struct sock *sk)
  601. {
  602. if (dev_recursion_level())
  603. return false;
  604. if (!sk)
  605. return true;
  606. switch (sk->sk_family) {
  607. case AF_INET:
  608. return inet_sk(sk)->mc_loop;
  609. #if IS_ENABLED(CONFIG_IPV6)
  610. case AF_INET6:
  611. return inet6_sk(sk)->mc_loop;
  612. #endif
  613. }
  614. WARN_ON(1);
  615. return true;
  616. }
  617. EXPORT_SYMBOL(sk_mc_loop);
  618. /*
  619. * This is meant for all protocols to use and covers goings on
  620. * at the socket level. Everything here is generic.
  621. */
  622. int sock_setsockopt(struct socket *sock, int level, int optname,
  623. char __user *optval, unsigned int optlen)
  624. {
  625. struct sock_txtime sk_txtime;
  626. struct sock *sk = sock->sk;
  627. int val;
  628. int valbool;
  629. struct linger ling;
  630. int ret = 0;
  631. /*
  632. * Options without arguments
  633. */
  634. if (optname == SO_BINDTODEVICE)
  635. return sock_setbindtodevice(sk, optval, optlen);
  636. if (optlen < sizeof(int))
  637. return -EINVAL;
  638. if (get_user(val, (int __user *)optval))
  639. return -EFAULT;
  640. valbool = val ? 1 : 0;
  641. lock_sock(sk);
  642. switch (optname) {
  643. case SO_DEBUG:
  644. if (val && !capable(CAP_NET_ADMIN))
  645. ret = -EACCES;
  646. else
  647. sock_valbool_flag(sk, SOCK_DBG, valbool);
  648. break;
  649. case SO_REUSEADDR:
  650. sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE);
  651. break;
  652. case SO_REUSEPORT:
  653. sk->sk_reuseport = valbool;
  654. break;
  655. case SO_TYPE:
  656. case SO_PROTOCOL:
  657. case SO_DOMAIN:
  658. case SO_ERROR:
  659. ret = -ENOPROTOOPT;
  660. break;
  661. case SO_DONTROUTE:
  662. sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool);
  663. sk_dst_reset(sk);
  664. break;
  665. case SO_BROADCAST:
  666. sock_valbool_flag(sk, SOCK_BROADCAST, valbool);
  667. break;
  668. case SO_SNDBUF:
  669. /* Don't error on this BSD doesn't and if you think
  670. * about it this is right. Otherwise apps have to
  671. * play 'guess the biggest size' games. RCVBUF/SNDBUF
  672. * are treated in BSD as hints
  673. */
  674. val = min_t(u32, val, sysctl_wmem_max);
  675. set_sndbuf:
  676. /* Ensure val * 2 fits into an int, to prevent max_t()
  677. * from treating it as a negative value.
  678. */
  679. val = min_t(int, val, INT_MAX / 2);
  680. sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
  681. WRITE_ONCE(sk->sk_sndbuf,
  682. max_t(int, val * 2, SOCK_MIN_SNDBUF));
  683. /* Wake up sending tasks if we upped the value. */
  684. sk->sk_write_space(sk);
  685. break;
  686. case SO_SNDBUFFORCE:
  687. if (!capable(CAP_NET_ADMIN)) {
  688. ret = -EPERM;
  689. break;
  690. }
  691. /* No negative values (to prevent underflow, as val will be
  692. * multiplied by 2).
  693. */
  694. if (val < 0)
  695. val = 0;
  696. goto set_sndbuf;
  697. case SO_RCVBUF:
  698. /* Don't error on this BSD doesn't and if you think
  699. * about it this is right. Otherwise apps have to
  700. * play 'guess the biggest size' games. RCVBUF/SNDBUF
  701. * are treated in BSD as hints
  702. */
  703. val = min_t(u32, val, sysctl_rmem_max);
  704. set_rcvbuf:
  705. /* Ensure val * 2 fits into an int, to prevent max_t()
  706. * from treating it as a negative value.
  707. */
  708. val = min_t(int, val, INT_MAX / 2);
  709. sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
  710. /*
  711. * We double it on the way in to account for
  712. * "struct sk_buff" etc. overhead. Applications
  713. * assume that the SO_RCVBUF setting they make will
  714. * allow that much actual data to be received on that
  715. * socket.
  716. *
  717. * Applications are unaware that "struct sk_buff" and
  718. * other overheads allocate from the receive buffer
  719. * during socket buffer allocation.
  720. *
  721. * And after considering the possible alternatives,
  722. * returning the value we actually used in getsockopt
  723. * is the most desirable behavior.
  724. */
  725. WRITE_ONCE(sk->sk_rcvbuf,
  726. max_t(int, val * 2, SOCK_MIN_RCVBUF));
  727. break;
  728. case SO_RCVBUFFORCE:
  729. if (!capable(CAP_NET_ADMIN)) {
  730. ret = -EPERM;
  731. break;
  732. }
  733. /* No negative values (to prevent underflow, as val will be
  734. * multiplied by 2).
  735. */
  736. if (val < 0)
  737. val = 0;
  738. goto set_rcvbuf;
  739. case SO_KEEPALIVE:
  740. if (sk->sk_prot->keepalive)
  741. sk->sk_prot->keepalive(sk, valbool);
  742. sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool);
  743. break;
  744. case SO_OOBINLINE:
  745. sock_valbool_flag(sk, SOCK_URGINLINE, valbool);
  746. break;
  747. case SO_NO_CHECK:
  748. sk->sk_no_check_tx = valbool;
  749. break;
  750. case SO_PRIORITY:
  751. if ((val >= 0 && val <= 6) ||
  752. ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
  753. sk->sk_priority = val;
  754. else
  755. ret = -EPERM;
  756. break;
  757. case SO_LINGER:
  758. if (optlen < sizeof(ling)) {
  759. ret = -EINVAL; /* 1003.1g */
  760. break;
  761. }
  762. if (copy_from_user(&ling, optval, sizeof(ling))) {
  763. ret = -EFAULT;
  764. break;
  765. }
  766. if (!ling.l_onoff)
  767. sock_reset_flag(sk, SOCK_LINGER);
  768. else {
  769. #if (BITS_PER_LONG == 32)
  770. if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ)
  771. sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT;
  772. else
  773. #endif
  774. sk->sk_lingertime = (unsigned int)ling.l_linger * HZ;
  775. sock_set_flag(sk, SOCK_LINGER);
  776. }
  777. break;
  778. case SO_BSDCOMPAT:
  779. sock_warn_obsolete_bsdism("setsockopt");
  780. break;
  781. case SO_PASSCRED:
  782. if (valbool)
  783. set_bit(SOCK_PASSCRED, &sock->flags);
  784. else
  785. clear_bit(SOCK_PASSCRED, &sock->flags);
  786. break;
  787. case SO_TIMESTAMP_OLD:
  788. case SO_TIMESTAMP_NEW:
  789. case SO_TIMESTAMPNS_OLD:
  790. case SO_TIMESTAMPNS_NEW:
  791. if (valbool) {
  792. if (optname == SO_TIMESTAMP_NEW || optname == SO_TIMESTAMPNS_NEW)
  793. sock_set_flag(sk, SOCK_TSTAMP_NEW);
  794. else
  795. sock_reset_flag(sk, SOCK_TSTAMP_NEW);
  796. if (optname == SO_TIMESTAMP_OLD || optname == SO_TIMESTAMP_NEW)
  797. sock_reset_flag(sk, SOCK_RCVTSTAMPNS);
  798. else
  799. sock_set_flag(sk, SOCK_RCVTSTAMPNS);
  800. sock_set_flag(sk, SOCK_RCVTSTAMP);
  801. sock_enable_timestamp(sk, SOCK_TIMESTAMP);
  802. } else {
  803. sock_reset_flag(sk, SOCK_RCVTSTAMP);
  804. sock_reset_flag(sk, SOCK_RCVTSTAMPNS);
  805. sock_reset_flag(sk, SOCK_TSTAMP_NEW);
  806. }
  807. break;
  808. case SO_TIMESTAMPING_NEW:
  809. sock_set_flag(sk, SOCK_TSTAMP_NEW);
  810. /* fall through */
  811. case SO_TIMESTAMPING_OLD:
  812. if (val & ~SOF_TIMESTAMPING_MASK) {
  813. ret = -EINVAL;
  814. break;
  815. }
  816. if (val & SOF_TIMESTAMPING_OPT_ID &&
  817. !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)) {
  818. if (sk->sk_protocol == IPPROTO_TCP &&
  819. sk->sk_type == SOCK_STREAM) {
  820. if ((1 << sk->sk_state) &
  821. (TCPF_CLOSE | TCPF_LISTEN)) {
  822. ret = -EINVAL;
  823. break;
  824. }
  825. sk->sk_tskey = tcp_sk(sk)->snd_una;
  826. } else {
  827. sk->sk_tskey = 0;
  828. }
  829. }
  830. if (val & SOF_TIMESTAMPING_OPT_STATS &&
  831. !(val & SOF_TIMESTAMPING_OPT_TSONLY)) {
  832. ret = -EINVAL;
  833. break;
  834. }
  835. sk->sk_tsflags = val;
  836. if (val & SOF_TIMESTAMPING_RX_SOFTWARE)
  837. sock_enable_timestamp(sk,
  838. SOCK_TIMESTAMPING_RX_SOFTWARE);
  839. else {
  840. if (optname == SO_TIMESTAMPING_NEW)
  841. sock_reset_flag(sk, SOCK_TSTAMP_NEW);
  842. sock_disable_timestamp(sk,
  843. (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE));
  844. }
  845. break;
  846. case SO_RCVLOWAT:
  847. if (val < 0)
  848. val = INT_MAX;
  849. if (sock->ops->set_rcvlowat)
  850. ret = sock->ops->set_rcvlowat(sk, val);
  851. else
  852. WRITE_ONCE(sk->sk_rcvlowat, val ? : 1);
  853. break;
  854. case SO_RCVTIMEO_OLD:
  855. case SO_RCVTIMEO_NEW:
  856. ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen, optname == SO_RCVTIMEO_OLD);
  857. break;
  858. case SO_SNDTIMEO_OLD:
  859. case SO_SNDTIMEO_NEW:
  860. ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen, optname == SO_SNDTIMEO_OLD);
  861. break;
  862. case SO_ATTACH_FILTER:
  863. ret = -EINVAL;
  864. if (optlen == sizeof(struct sock_fprog)) {
  865. struct sock_fprog fprog;
  866. ret = -EFAULT;
  867. if (copy_from_user(&fprog, optval, sizeof(fprog)))
  868. break;
  869. ret = sk_attach_filter(&fprog, sk);
  870. }
  871. break;
  872. case SO_ATTACH_BPF:
  873. ret = -EINVAL;
  874. if (optlen == sizeof(u32)) {
  875. u32 ufd;
  876. ret = -EFAULT;
  877. if (copy_from_user(&ufd, optval, sizeof(ufd)))
  878. break;
  879. ret = sk_attach_bpf(ufd, sk);
  880. }
  881. break;
  882. case SO_ATTACH_REUSEPORT_CBPF:
  883. ret = -EINVAL;
  884. if (optlen == sizeof(struct sock_fprog)) {
  885. struct sock_fprog fprog;
  886. ret = -EFAULT;
  887. if (copy_from_user(&fprog, optval, sizeof(fprog)))
  888. break;
  889. ret = sk_reuseport_attach_filter(&fprog, sk);
  890. }
  891. break;
  892. case SO_ATTACH_REUSEPORT_EBPF:
  893. ret = -EINVAL;
  894. if (optlen == sizeof(u32)) {
  895. u32 ufd;
  896. ret = -EFAULT;
  897. if (copy_from_user(&ufd, optval, sizeof(ufd)))
  898. break;
  899. ret = sk_reuseport_attach_bpf(ufd, sk);
  900. }
  901. break;
  902. case SO_DETACH_REUSEPORT_BPF:
  903. ret = reuseport_detach_prog(sk);
  904. break;
  905. case SO_DETACH_FILTER:
  906. ret = sk_detach_filter(sk);
  907. break;
  908. case SO_LOCK_FILTER:
  909. if (sock_flag(sk, SOCK_FILTER_LOCKED) && !valbool)
  910. ret = -EPERM;
  911. else
  912. sock_valbool_flag(sk, SOCK_FILTER_LOCKED, valbool);
  913. break;
  914. case SO_PASSSEC:
  915. if (valbool)
  916. set_bit(SOCK_PASSSEC, &sock->flags);
  917. else
  918. clear_bit(SOCK_PASSSEC, &sock->flags);
  919. break;
  920. case SO_MARK:
  921. if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) {
  922. ret = -EPERM;
  923. } else if (val != sk->sk_mark) {
  924. sk->sk_mark = val;
  925. sk_dst_reset(sk);
  926. }
  927. break;
  928. case SO_RXQ_OVFL:
  929. sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool);
  930. break;
  931. case SO_WIFI_STATUS:
  932. sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool);
  933. break;
  934. case SO_PEEK_OFF:
  935. if (sock->ops->set_peek_off)
  936. ret = sock->ops->set_peek_off(sk, val);
  937. else
  938. ret = -EOPNOTSUPP;
  939. break;
  940. case SO_NOFCS:
  941. sock_valbool_flag(sk, SOCK_NOFCS, valbool);
  942. break;
  943. case SO_SELECT_ERR_QUEUE:
  944. sock_valbool_flag(sk, SOCK_SELECT_ERR_QUEUE, valbool);
  945. break;
  946. #ifdef CONFIG_NET_RX_BUSY_POLL
  947. case SO_BUSY_POLL:
  948. /* allow unprivileged users to decrease the value */
  949. if ((val > sk->sk_ll_usec) && !capable(CAP_NET_ADMIN))
  950. ret = -EPERM;
  951. else {
  952. if (val < 0)
  953. ret = -EINVAL;
  954. else
  955. sk->sk_ll_usec = val;
  956. }
  957. break;
  958. #endif
  959. case SO_MAX_PACING_RATE:
  960. {
  961. unsigned long ulval = (val == ~0U) ? ~0UL : val;
  962. if (sizeof(ulval) != sizeof(val) &&
  963. optlen >= sizeof(ulval) &&
  964. get_user(ulval, (unsigned long __user *)optval)) {
  965. ret = -EFAULT;
  966. break;
  967. }
  968. if (ulval != ~0UL)
  969. cmpxchg(&sk->sk_pacing_status,
  970. SK_PACING_NONE,
  971. SK_PACING_NEEDED);
  972. sk->sk_max_pacing_rate = ulval;
  973. sk->sk_pacing_rate = min(sk->sk_pacing_rate, ulval);
  974. break;
  975. }
  976. case SO_INCOMING_CPU:
  977. WRITE_ONCE(sk->sk_incoming_cpu, val);
  978. break;
  979. case SO_CNX_ADVICE:
  980. if (val == 1)
  981. dst_negative_advice(sk);
  982. break;
  983. case SO_ZEROCOPY:
  984. if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6) {
  985. if (!((sk->sk_type == SOCK_STREAM &&
  986. sk->sk_protocol == IPPROTO_TCP) ||
  987. (sk->sk_type == SOCK_DGRAM &&
  988. sk->sk_protocol == IPPROTO_UDP)))
  989. ret = -ENOTSUPP;
  990. } else if (sk->sk_family != PF_RDS) {
  991. ret = -ENOTSUPP;
  992. }
  993. if (!ret) {
  994. if (val < 0 || val > 1)
  995. ret = -EINVAL;
  996. else
  997. sock_valbool_flag(sk, SOCK_ZEROCOPY, valbool);
  998. }
  999. break;
  1000. case SO_TXTIME:
  1001. if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) {
  1002. ret = -EPERM;
  1003. } else if (optlen != sizeof(struct sock_txtime)) {
  1004. ret = -EINVAL;
  1005. } else if (copy_from_user(&sk_txtime, optval,
  1006. sizeof(struct sock_txtime))) {
  1007. ret = -EFAULT;
  1008. } else if (sk_txtime.flags & ~SOF_TXTIME_FLAGS_MASK) {
  1009. ret = -EINVAL;
  1010. } else {
  1011. sock_valbool_flag(sk, SOCK_TXTIME, true);
  1012. sk->sk_clockid = sk_txtime.clockid;
  1013. sk->sk_txtime_deadline_mode =
  1014. !!(sk_txtime.flags & SOF_TXTIME_DEADLINE_MODE);
  1015. sk->sk_txtime_report_errors =
  1016. !!(sk_txtime.flags & SOF_TXTIME_REPORT_ERRORS);
  1017. }
  1018. break;
  1019. case SO_BINDTOIFINDEX:
  1020. ret = sock_setbindtodevice_locked(sk, val);
  1021. break;
  1022. default:
  1023. ret = -ENOPROTOOPT;
  1024. break;
  1025. }
  1026. release_sock(sk);
  1027. return ret;
  1028. }
  1029. EXPORT_SYMBOL(sock_setsockopt);
  1030. static void cred_to_ucred(struct pid *pid, const struct cred *cred,
  1031. struct ucred *ucred)
  1032. {
  1033. ucred->pid = pid_vnr(pid);
  1034. ucred->uid = ucred->gid = -1;
  1035. if (cred) {
  1036. struct user_namespace *current_ns = current_user_ns();
  1037. ucred->uid = from_kuid_munged(current_ns, cred->euid);
  1038. ucred->gid = from_kgid_munged(current_ns, cred->egid);
  1039. }
  1040. }
  1041. static int groups_to_user(gid_t __user *dst, const struct group_info *src)
  1042. {
  1043. struct user_namespace *user_ns = current_user_ns();
  1044. int i;
  1045. for (i = 0; i < src->ngroups; i++)
  1046. if (put_user(from_kgid_munged(user_ns, src->gid[i]), dst + i))
  1047. return -EFAULT;
  1048. return 0;
  1049. }
  1050. int sock_getsockopt(struct socket *sock, int level, int optname,
  1051. char __user *optval, int __user *optlen)
  1052. {
  1053. struct sock *sk = sock->sk;
  1054. union {
  1055. int val;
  1056. u64 val64;
  1057. unsigned long ulval;
  1058. struct linger ling;
  1059. struct old_timeval32 tm32;
  1060. struct __kernel_old_timeval tm;
  1061. struct __kernel_sock_timeval stm;
  1062. struct sock_txtime txtime;
  1063. } v;
  1064. int lv = sizeof(int);
  1065. int len;
  1066. if (get_user(len, optlen))
  1067. return -EFAULT;
  1068. if (len < 0)
  1069. return -EINVAL;
  1070. memset(&v, 0, sizeof(v));
  1071. switch (optname) {
  1072. case SO_DEBUG:
  1073. v.val = sock_flag(sk, SOCK_DBG);
  1074. break;
  1075. case SO_DONTROUTE:
  1076. v.val = sock_flag(sk, SOCK_LOCALROUTE);
  1077. break;
  1078. case SO_BROADCAST:
  1079. v.val = sock_flag(sk, SOCK_BROADCAST);
  1080. break;
  1081. case SO_SNDBUF:
  1082. v.val = sk->sk_sndbuf;
  1083. break;
  1084. case SO_RCVBUF:
  1085. v.val = sk->sk_rcvbuf;
  1086. break;
  1087. case SO_REUSEADDR:
  1088. v.val = sk->sk_reuse;
  1089. break;
  1090. case SO_REUSEPORT:
  1091. v.val = sk->sk_reuseport;
  1092. break;
  1093. case SO_KEEPALIVE:
  1094. v.val = sock_flag(sk, SOCK_KEEPOPEN);
  1095. break;
  1096. case SO_TYPE:
  1097. v.val = sk->sk_type;
  1098. break;
  1099. case SO_PROTOCOL:
  1100. v.val = sk->sk_protocol;
  1101. break;
  1102. case SO_DOMAIN:
  1103. v.val = sk->sk_family;
  1104. break;
  1105. case SO_ERROR:
  1106. v.val = -sock_error(sk);
  1107. if (v.val == 0)
  1108. v.val = xchg(&sk->sk_err_soft, 0);
  1109. break;
  1110. case SO_OOBINLINE:
  1111. v.val = sock_flag(sk, SOCK_URGINLINE);
  1112. break;
  1113. case SO_NO_CHECK:
  1114. v.val = sk->sk_no_check_tx;
  1115. break;
  1116. case SO_PRIORITY:
  1117. v.val = sk->sk_priority;
  1118. break;
  1119. case SO_LINGER:
  1120. lv = sizeof(v.ling);
  1121. v.ling.l_onoff = sock_flag(sk, SOCK_LINGER);
  1122. v.ling.l_linger = sk->sk_lingertime / HZ;
  1123. break;
  1124. case SO_BSDCOMPAT:
  1125. sock_warn_obsolete_bsdism("getsockopt");
  1126. break;
  1127. case SO_TIMESTAMP_OLD:
  1128. v.val = sock_flag(sk, SOCK_RCVTSTAMP) &&
  1129. !sock_flag(sk, SOCK_TSTAMP_NEW) &&
  1130. !sock_flag(sk, SOCK_RCVTSTAMPNS);
  1131. break;
  1132. case SO_TIMESTAMPNS_OLD:
  1133. v.val = sock_flag(sk, SOCK_RCVTSTAMPNS) && !sock_flag(sk, SOCK_TSTAMP_NEW);
  1134. break;
  1135. case SO_TIMESTAMP_NEW:
  1136. v.val = sock_flag(sk, SOCK_RCVTSTAMP) && sock_flag(sk, SOCK_TSTAMP_NEW);
  1137. break;
  1138. case SO_TIMESTAMPNS_NEW:
  1139. v.val = sock_flag(sk, SOCK_RCVTSTAMPNS) && sock_flag(sk, SOCK_TSTAMP_NEW);
  1140. break;
  1141. case SO_TIMESTAMPING_OLD:
  1142. v.val = sk->sk_tsflags;
  1143. break;
  1144. case SO_RCVTIMEO_OLD:
  1145. case SO_RCVTIMEO_NEW:
  1146. lv = sock_get_timeout(sk->sk_rcvtimeo, &v, SO_RCVTIMEO_OLD == optname);
  1147. break;
  1148. case SO_SNDTIMEO_OLD:
  1149. case SO_SNDTIMEO_NEW:
  1150. lv = sock_get_timeout(sk->sk_sndtimeo, &v, SO_SNDTIMEO_OLD == optname);
  1151. break;
  1152. case SO_RCVLOWAT:
  1153. v.val = sk->sk_rcvlowat;
  1154. break;
  1155. case SO_SNDLOWAT:
  1156. v.val = 1;
  1157. break;
  1158. case SO_PASSCRED:
  1159. v.val = !!test_bit(SOCK_PASSCRED, &sock->flags);
  1160. break;
  1161. case SO_PEERCRED:
  1162. {
  1163. struct ucred peercred;
  1164. if (len > sizeof(peercred))
  1165. len = sizeof(peercred);
  1166. cred_to_ucred(sk->sk_peer_pid, sk->sk_peer_cred, &peercred);
  1167. if (copy_to_user(optval, &peercred, len))
  1168. return -EFAULT;
  1169. goto lenout;
  1170. }
  1171. case SO_PEERGROUPS:
  1172. {
  1173. int ret, n;
  1174. if (!sk->sk_peer_cred)
  1175. return -ENODATA;
  1176. n = sk->sk_peer_cred->group_info->ngroups;
  1177. if (len < n * sizeof(gid_t)) {
  1178. len = n * sizeof(gid_t);
  1179. return put_user(len, optlen) ? -EFAULT : -ERANGE;
  1180. }
  1181. len = n * sizeof(gid_t);
  1182. ret = groups_to_user((gid_t __user *)optval,
  1183. sk->sk_peer_cred->group_info);
  1184. if (ret)
  1185. return ret;
  1186. goto lenout;
  1187. }
  1188. case SO_PEERNAME:
  1189. {
  1190. char address[128];
  1191. lv = sock->ops->getname(sock, (struct sockaddr *)address, 2);
  1192. if (lv < 0)
  1193. return -ENOTCONN;
  1194. if (lv < len)
  1195. return -EINVAL;
  1196. if (copy_to_user(optval, address, len))
  1197. return -EFAULT;
  1198. goto lenout;
  1199. }
  1200. /* Dubious BSD thing... Probably nobody even uses it, but
  1201. * the UNIX standard wants it for whatever reason... -DaveM
  1202. */
  1203. case SO_ACCEPTCONN:
  1204. v.val = sk->sk_state == TCP_LISTEN;
  1205. break;
  1206. case SO_PASSSEC:
  1207. v.val = !!test_bit(SOCK_PASSSEC, &sock->flags);
  1208. break;
  1209. case SO_PEERSEC:
  1210. return security_socket_getpeersec_stream(sock, optval, optlen, len);
  1211. case SO_MARK:
  1212. v.val = sk->sk_mark;
  1213. break;
  1214. case SO_RXQ_OVFL:
  1215. v.val = sock_flag(sk, SOCK_RXQ_OVFL);
  1216. break;
  1217. case SO_WIFI_STATUS:
  1218. v.val = sock_flag(sk, SOCK_WIFI_STATUS);
  1219. break;
  1220. case SO_PEEK_OFF:
  1221. if (!sock->ops->set_peek_off)
  1222. return -EOPNOTSUPP;
  1223. v.val = sk->sk_peek_off;
  1224. break;
  1225. case SO_NOFCS:
  1226. v.val = sock_flag(sk, SOCK_NOFCS);
  1227. break;
  1228. case SO_BINDTODEVICE:
  1229. return sock_getbindtodevice(sk, optval, optlen, len);
  1230. case SO_GET_FILTER:
  1231. len = sk_get_filter(sk, (struct sock_filter __user *)optval, len);
  1232. if (len < 0)
  1233. return len;
  1234. goto lenout;
  1235. case SO_LOCK_FILTER:
  1236. v.val = sock_flag(sk, SOCK_FILTER_LOCKED);
  1237. break;
  1238. case SO_BPF_EXTENSIONS:
  1239. v.val = bpf_tell_extensions();
  1240. break;
  1241. case SO_SELECT_ERR_QUEUE:
  1242. v.val = sock_flag(sk, SOCK_SELECT_ERR_QUEUE);
  1243. break;
  1244. #ifdef CONFIG_NET_RX_BUSY_POLL
  1245. case SO_BUSY_POLL:
  1246. v.val = sk->sk_ll_usec;
  1247. break;
  1248. #endif
  1249. case SO_MAX_PACING_RATE:
  1250. if (sizeof(v.ulval) != sizeof(v.val) && len >= sizeof(v.ulval)) {
  1251. lv = sizeof(v.ulval);
  1252. v.ulval = sk->sk_max_pacing_rate;
  1253. } else {
  1254. /* 32bit version */
  1255. v.val = min_t(unsigned long, sk->sk_max_pacing_rate, ~0U);
  1256. }
  1257. break;
  1258. case SO_INCOMING_CPU:
  1259. v.val = READ_ONCE(sk->sk_incoming_cpu);
  1260. break;
  1261. case SO_MEMINFO:
  1262. {
  1263. u32 meminfo[SK_MEMINFO_VARS];
  1264. sk_get_meminfo(sk, meminfo);
  1265. len = min_t(unsigned int, len, sizeof(meminfo));
  1266. if (copy_to_user(optval, &meminfo, len))
  1267. return -EFAULT;
  1268. goto lenout;
  1269. }
  1270. #ifdef CONFIG_NET_RX_BUSY_POLL
  1271. case SO_INCOMING_NAPI_ID:
  1272. v.val = READ_ONCE(sk->sk_napi_id);
  1273. /* aggregate non-NAPI IDs down to 0 */
  1274. if (v.val < MIN_NAPI_ID)
  1275. v.val = 0;
  1276. break;
  1277. #endif
  1278. case SO_COOKIE:
  1279. lv = sizeof(u64);
  1280. if (len < lv)
  1281. return -EINVAL;
  1282. v.val64 = sock_gen_cookie(sk);
  1283. break;
  1284. case SO_ZEROCOPY:
  1285. v.val = sock_flag(sk, SOCK_ZEROCOPY);
  1286. break;
  1287. case SO_TXTIME:
  1288. lv = sizeof(v.txtime);
  1289. v.txtime.clockid = sk->sk_clockid;
  1290. v.txtime.flags |= sk->sk_txtime_deadline_mode ?
  1291. SOF_TXTIME_DEADLINE_MODE : 0;
  1292. v.txtime.flags |= sk->sk_txtime_report_errors ?
  1293. SOF_TXTIME_REPORT_ERRORS : 0;
  1294. break;
  1295. case SO_BINDTOIFINDEX:
  1296. v.val = sk->sk_bound_dev_if;
  1297. break;
  1298. default:
  1299. /* We implement the SO_SNDLOWAT etc to not be settable
  1300. * (1003.1g 7).
  1301. */
  1302. return -ENOPROTOOPT;
  1303. }
  1304. if (len > lv)
  1305. len = lv;
  1306. if (copy_to_user(optval, &v, len))
  1307. return -EFAULT;
  1308. lenout:
  1309. if (put_user(len, optlen))
  1310. return -EFAULT;
  1311. return 0;
  1312. }
  1313. /*
  1314. * Initialize an sk_lock.
  1315. *
  1316. * (We also register the sk_lock with the lock validator.)
  1317. */
  1318. static inline void sock_lock_init(struct sock *sk)
  1319. {
  1320. if (sk->sk_kern_sock)
  1321. sock_lock_init_class_and_name(
  1322. sk,
  1323. af_family_kern_slock_key_strings[sk->sk_family],
  1324. af_family_kern_slock_keys + sk->sk_family,
  1325. af_family_kern_key_strings[sk->sk_family],
  1326. af_family_kern_keys + sk->sk_family);
  1327. else
  1328. sock_lock_init_class_and_name(
  1329. sk,
  1330. af_family_slock_key_strings[sk->sk_family],
  1331. af_family_slock_keys + sk->sk_family,
  1332. af_family_key_strings[sk->sk_family],
  1333. af_family_keys + sk->sk_family);
  1334. }
  1335. /*
  1336. * Copy all fields from osk to nsk but nsk->sk_refcnt must not change yet,
  1337. * even temporarly, because of RCU lookups. sk_node should also be left as is.
  1338. * We must not copy fields between sk_dontcopy_begin and sk_dontcopy_end
  1339. */
  1340. static void sock_copy(struct sock *nsk, const struct sock *osk)
  1341. {
  1342. const struct proto *prot = READ_ONCE(osk->sk_prot);
  1343. #ifdef CONFIG_SECURITY_NETWORK
  1344. void *sptr = nsk->sk_security;
  1345. #endif
  1346. memcpy(nsk, osk, offsetof(struct sock, sk_dontcopy_begin));
  1347. memcpy(&nsk->sk_dontcopy_end, &osk->sk_dontcopy_end,
  1348. prot->obj_size - offsetof(struct sock, sk_dontcopy_end));
  1349. #ifdef CONFIG_SECURITY_NETWORK
  1350. nsk->sk_security = sptr;
  1351. security_sk_clone(osk, nsk);
  1352. #endif
  1353. }
  1354. static struct sock *sk_prot_alloc(struct proto *prot, gfp_t priority,
  1355. int family)
  1356. {
  1357. struct sock *sk;
  1358. struct kmem_cache *slab;
  1359. slab = prot->slab;
  1360. if (slab != NULL) {
  1361. sk = kmem_cache_alloc(slab, priority & ~__GFP_ZERO);
  1362. if (!sk)
  1363. return sk;
  1364. if (want_init_on_alloc(priority))
  1365. sk_prot_clear_nulls(sk, prot->obj_size);
  1366. } else
  1367. sk = kmalloc(prot->obj_size, priority);
  1368. if (sk != NULL) {
  1369. if (security_sk_alloc(sk, family, priority))
  1370. goto out_free;
  1371. if (!try_module_get(prot->owner))
  1372. goto out_free_sec;
  1373. sk_tx_queue_clear(sk);
  1374. }
  1375. return sk;
  1376. out_free_sec:
  1377. security_sk_free(sk);
  1378. out_free:
  1379. if (slab != NULL)
  1380. kmem_cache_free(slab, sk);
  1381. else
  1382. kfree(sk);
  1383. return NULL;
  1384. }
  1385. static void sk_prot_free(struct proto *prot, struct sock *sk)
  1386. {
  1387. struct kmem_cache *slab;
  1388. struct module *owner;
  1389. owner = prot->owner;
  1390. slab = prot->slab;
  1391. cgroup_sk_free(&sk->sk_cgrp_data);
  1392. mem_cgroup_sk_free(sk);
  1393. security_sk_free(sk);
  1394. if (slab != NULL)
  1395. kmem_cache_free(slab, sk);
  1396. else
  1397. kfree(sk);
  1398. module_put(owner);
  1399. }
  1400. /**
  1401. * sk_alloc - All socket objects are allocated here
  1402. * @net: the applicable net namespace
  1403. * @family: protocol family
  1404. * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
  1405. * @prot: struct proto associated with this new sock instance
  1406. * @kern: is this to be a kernel socket?
  1407. */
  1408. struct sock *sk_alloc(struct net *net, int family, gfp_t priority,
  1409. struct proto *prot, int kern)
  1410. {
  1411. struct sock *sk;
  1412. sk = sk_prot_alloc(prot, priority | __GFP_ZERO, family);
  1413. if (sk) {
  1414. sk->sk_family = family;
  1415. /*
  1416. * See comment in struct sock definition to understand
  1417. * why we need sk_prot_creator -acme
  1418. */
  1419. sk->sk_prot = sk->sk_prot_creator = prot;
  1420. sk->sk_kern_sock = kern;
  1421. sock_lock_init(sk);
  1422. sk->sk_net_refcnt = kern ? 0 : 1;
  1423. if (likely(sk->sk_net_refcnt)) {
  1424. get_net(net);
  1425. sock_inuse_add(net, 1);
  1426. }
  1427. sock_net_set(sk, net);
  1428. refcount_set(&sk->sk_wmem_alloc, 1);
  1429. mem_cgroup_sk_alloc(sk);
  1430. cgroup_sk_alloc(&sk->sk_cgrp_data);
  1431. sock_update_classid(&sk->sk_cgrp_data);
  1432. sock_update_netprioidx(&sk->sk_cgrp_data);
  1433. }
  1434. return sk;
  1435. }
  1436. EXPORT_SYMBOL(sk_alloc);
  1437. /* Sockets having SOCK_RCU_FREE will call this function after one RCU
  1438. * grace period. This is the case for UDP sockets and TCP listeners.
  1439. */
  1440. static void __sk_destruct(struct rcu_head *head)
  1441. {
  1442. struct sock *sk = container_of(head, struct sock, sk_rcu);
  1443. struct sk_filter *filter;
  1444. if (sk->sk_destruct)
  1445. sk->sk_destruct(sk);
  1446. filter = rcu_dereference_check(sk->sk_filter,
  1447. refcount_read(&sk->sk_wmem_alloc) == 0);
  1448. if (filter) {
  1449. sk_filter_uncharge(sk, filter);
  1450. RCU_INIT_POINTER(sk->sk_filter, NULL);
  1451. }
  1452. sock_disable_timestamp(sk, SK_FLAGS_TIMESTAMP);
  1453. #ifdef CONFIG_BPF_SYSCALL
  1454. bpf_sk_storage_free(sk);
  1455. #endif
  1456. if (atomic_read(&sk->sk_omem_alloc))
  1457. pr_debug("%s: optmem leakage (%d bytes) detected\n",
  1458. __func__, atomic_read(&sk->sk_omem_alloc));
  1459. if (sk->sk_frag.page) {
  1460. put_page(sk->sk_frag.page);
  1461. sk->sk_frag.page = NULL;
  1462. }
  1463. if (sk->sk_peer_cred)
  1464. put_cred(sk->sk_peer_cred);
  1465. put_pid(sk->sk_peer_pid);
  1466. if (likely(sk->sk_net_refcnt))
  1467. put_net(sock_net(sk));
  1468. sk_prot_free(sk->sk_prot_creator, sk);
  1469. }
  1470. void sk_destruct(struct sock *sk)
  1471. {
  1472. bool use_call_rcu = sock_flag(sk, SOCK_RCU_FREE);
  1473. if (rcu_access_pointer(sk->sk_reuseport_cb)) {
  1474. reuseport_detach_sock(sk);
  1475. use_call_rcu = true;
  1476. }
  1477. if (use_call_rcu)
  1478. call_rcu(&sk->sk_rcu, __sk_destruct);
  1479. else
  1480. __sk_destruct(&sk->sk_rcu);
  1481. }
  1482. static void __sk_free(struct sock *sk)
  1483. {
  1484. if (likely(sk->sk_net_refcnt))
  1485. sock_inuse_add(sock_net(sk), -1);
  1486. if (unlikely(sk->sk_net_refcnt && sock_diag_has_destroy_listeners(sk)))
  1487. sock_diag_broadcast_destroy(sk);
  1488. else
  1489. sk_destruct(sk);
  1490. }
  1491. void sk_free(struct sock *sk)
  1492. {
  1493. /*
  1494. * We subtract one from sk_wmem_alloc and can know if
  1495. * some packets are still in some tx queue.
  1496. * If not null, sock_wfree() will call __sk_free(sk) later
  1497. */
  1498. if (refcount_dec_and_test(&sk->sk_wmem_alloc))
  1499. __sk_free(sk);
  1500. }
  1501. EXPORT_SYMBOL(sk_free);
  1502. static void sk_init_common(struct sock *sk)
  1503. {
  1504. skb_queue_head_init(&sk->sk_receive_queue);
  1505. skb_queue_head_init(&sk->sk_write_queue);
  1506. skb_queue_head_init(&sk->sk_error_queue);
  1507. rwlock_init(&sk->sk_callback_lock);
  1508. lockdep_set_class_and_name(&sk->sk_receive_queue.lock,
  1509. af_rlock_keys + sk->sk_family,
  1510. af_family_rlock_key_strings[sk->sk_family]);
  1511. lockdep_set_class_and_name(&sk->sk_write_queue.lock,
  1512. af_wlock_keys + sk->sk_family,
  1513. af_family_wlock_key_strings[sk->sk_family]);
  1514. lockdep_set_class_and_name(&sk->sk_error_queue.lock,
  1515. af_elock_keys + sk->sk_family,
  1516. af_family_elock_key_strings[sk->sk_family]);
  1517. lockdep_set_class_and_name(&sk->sk_callback_lock,
  1518. af_callback_keys + sk->sk_family,
  1519. af_family_clock_key_strings[sk->sk_family]);
  1520. }
  1521. /**
  1522. * sk_clone_lock - clone a socket, and lock its clone
  1523. * @sk: the socket to clone
  1524. * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
  1525. *
  1526. * Caller must unlock socket even in error path (bh_unlock_sock(newsk))
  1527. */
  1528. struct sock *sk_clone_lock(const struct sock *sk, const gfp_t priority)
  1529. {
  1530. struct proto *prot = READ_ONCE(sk->sk_prot);
  1531. struct sock *newsk;
  1532. bool is_charged = true;
  1533. newsk = sk_prot_alloc(prot, priority, sk->sk_family);
  1534. if (newsk != NULL) {
  1535. struct sk_filter *filter;
  1536. sock_copy(newsk, sk);
  1537. newsk->sk_prot_creator = prot;
  1538. /* SANITY */
  1539. if (likely(newsk->sk_net_refcnt))
  1540. get_net(sock_net(newsk));
  1541. sk_node_init(&newsk->sk_node);
  1542. sock_lock_init(newsk);
  1543. bh_lock_sock(newsk);
  1544. newsk->sk_backlog.head = newsk->sk_backlog.tail = NULL;
  1545. newsk->sk_backlog.len = 0;
  1546. atomic_set(&newsk->sk_rmem_alloc, 0);
  1547. /*
  1548. * sk_wmem_alloc set to one (see sk_free() and sock_wfree())
  1549. */
  1550. refcount_set(&newsk->sk_wmem_alloc, 1);
  1551. atomic_set(&newsk->sk_omem_alloc, 0);
  1552. sk_init_common(newsk);
  1553. newsk->sk_dst_cache = NULL;
  1554. newsk->sk_dst_pending_confirm = 0;
  1555. newsk->sk_wmem_queued = 0;
  1556. newsk->sk_forward_alloc = 0;
  1557. atomic_set(&newsk->sk_drops, 0);
  1558. newsk->sk_send_head = NULL;
  1559. newsk->sk_userlocks = sk->sk_userlocks & ~SOCK_BINDPORT_LOCK;
  1560. atomic_set(&newsk->sk_zckey, 0);
  1561. sock_reset_flag(newsk, SOCK_DONE);
  1562. /* sk->sk_memcg will be populated at accept() time */
  1563. newsk->sk_memcg = NULL;
  1564. cgroup_sk_alloc(&newsk->sk_cgrp_data);
  1565. rcu_read_lock();
  1566. filter = rcu_dereference(sk->sk_filter);
  1567. if (filter != NULL)
  1568. /* though it's an empty new sock, the charging may fail
  1569. * if sysctl_optmem_max was changed between creation of
  1570. * original socket and cloning
  1571. */
  1572. is_charged = sk_filter_charge(newsk, filter);
  1573. RCU_INIT_POINTER(newsk->sk_filter, filter);
  1574. rcu_read_unlock();
  1575. if (unlikely(!is_charged || xfrm_sk_clone_policy(newsk, sk))) {
  1576. /* We need to make sure that we don't uncharge the new
  1577. * socket if we couldn't charge it in the first place
  1578. * as otherwise we uncharge the parent's filter.
  1579. */
  1580. if (!is_charged)
  1581. RCU_INIT_POINTER(newsk->sk_filter, NULL);
  1582. sk_free_unlock_clone(newsk);
  1583. newsk = NULL;
  1584. goto out;
  1585. }
  1586. RCU_INIT_POINTER(newsk->sk_reuseport_cb, NULL);
  1587. if (bpf_sk_storage_clone(sk, newsk)) {
  1588. sk_free_unlock_clone(newsk);
  1589. newsk = NULL;
  1590. goto out;
  1591. }
  1592. /* Clear sk_user_data if parent had the pointer tagged
  1593. * as not suitable for copying when cloning.
  1594. */
  1595. if (sk_user_data_is_nocopy(newsk))
  1596. newsk->sk_user_data = NULL;
  1597. newsk->sk_err = 0;
  1598. newsk->sk_err_soft = 0;
  1599. newsk->sk_priority = 0;
  1600. newsk->sk_incoming_cpu = raw_smp_processor_id();
  1601. if (likely(newsk->sk_net_refcnt))
  1602. sock_inuse_add(sock_net(newsk), 1);
  1603. /*
  1604. * Before updating sk_refcnt, we must commit prior changes to memory
  1605. * (Documentation/RCU/rculist_nulls.txt for details)
  1606. */
  1607. smp_wmb();
  1608. refcount_set(&newsk->sk_refcnt, 2);
  1609. /*
  1610. * Increment the counter in the same struct proto as the master
  1611. * sock (sk_refcnt_debug_inc uses newsk->sk_prot->socks, that
  1612. * is the same as sk->sk_prot->socks, as this field was copied
  1613. * with memcpy).
  1614. *
  1615. * This _changes_ the previous behaviour, where
  1616. * tcp_create_openreq_child always was incrementing the
  1617. * equivalent to tcp_prot->socks (inet_sock_nr), so this have
  1618. * to be taken into account in all callers. -acme
  1619. */
  1620. sk_refcnt_debug_inc(newsk);
  1621. sk_set_socket(newsk, NULL);
  1622. RCU_INIT_POINTER(newsk->sk_wq, NULL);
  1623. if (newsk->sk_prot->sockets_allocated)
  1624. sk_sockets_allocated_inc(newsk);
  1625. if (sock_needs_netstamp(sk) &&
  1626. newsk->sk_flags & SK_FLAGS_TIMESTAMP)
  1627. net_enable_timestamp();
  1628. }
  1629. out:
  1630. return newsk;
  1631. }
  1632. EXPORT_SYMBOL_GPL(sk_clone_lock);
  1633. void sk_free_unlock_clone(struct sock *sk)
  1634. {
  1635. /* It is still raw copy of parent, so invalidate
  1636. * destructor and make plain sk_free() */
  1637. sk->sk_destruct = NULL;
  1638. bh_unlock_sock(sk);
  1639. sk_free(sk);
  1640. }
  1641. EXPORT_SYMBOL_GPL(sk_free_unlock_clone);
  1642. void sk_setup_caps(struct sock *sk, struct dst_entry *dst)
  1643. {
  1644. u32 max_segs = 1;
  1645. sk_dst_set(sk, dst);
  1646. sk->sk_route_caps = dst->dev->features | sk->sk_route_forced_caps;
  1647. if (sk->sk_route_caps & NETIF_F_GSO)
  1648. sk->sk_route_caps |= NETIF_F_GSO_SOFTWARE;
  1649. sk->sk_route_caps &= ~sk->sk_route_nocaps;
  1650. if (sk_can_gso(sk)) {
  1651. if (dst->header_len && !xfrm_dst_offload_ok(dst)) {
  1652. sk->sk_route_caps &= ~NETIF_F_GSO_MASK;
  1653. } else {
  1654. sk->sk_route_caps |= NETIF_F_SG | NETIF_F_HW_CSUM;
  1655. sk->sk_gso_max_size = dst->dev->gso_max_size;
  1656. max_segs = max_t(u32, dst->dev->gso_max_segs, 1);
  1657. }
  1658. }
  1659. sk->sk_gso_max_segs = max_segs;
  1660. }
  1661. EXPORT_SYMBOL_GPL(sk_setup_caps);
  1662. /*
  1663. * Simple resource managers for sockets.
  1664. */
  1665. /*
  1666. * Write buffer destructor automatically called from kfree_skb.
  1667. */
  1668. void sock_wfree(struct sk_buff *skb)
  1669. {
  1670. struct sock *sk = skb->sk;
  1671. unsigned int len = skb->truesize;
  1672. if (!sock_flag(sk, SOCK_USE_WRITE_QUEUE)) {
  1673. /*
  1674. * Keep a reference on sk_wmem_alloc, this will be released
  1675. * after sk_write_space() call
  1676. */
  1677. WARN_ON(refcount_sub_and_test(len - 1, &sk->sk_wmem_alloc));
  1678. sk->sk_write_space(sk);
  1679. len = 1;
  1680. }
  1681. /*
  1682. * if sk_wmem_alloc reaches 0, we must finish what sk_free()
  1683. * could not do because of in-flight packets
  1684. */
  1685. if (refcount_sub_and_test(len, &sk->sk_wmem_alloc))
  1686. __sk_free(sk);
  1687. }
  1688. EXPORT_SYMBOL(sock_wfree);
  1689. /* This variant of sock_wfree() is used by TCP,
  1690. * since it sets SOCK_USE_WRITE_QUEUE.
  1691. */
  1692. void __sock_wfree(struct sk_buff *skb)
  1693. {
  1694. struct sock *sk = skb->sk;
  1695. if (refcount_sub_and_test(skb->truesize, &sk->sk_wmem_alloc))
  1696. __sk_free(sk);
  1697. }
  1698. void skb_set_owner_w(struct sk_buff *skb, struct sock *sk)
  1699. {
  1700. skb_orphan(skb);
  1701. skb->sk = sk;
  1702. #ifdef CONFIG_INET
  1703. if (unlikely(!sk_fullsock(sk))) {
  1704. skb->destructor = sock_edemux;
  1705. sock_hold(sk);
  1706. return;
  1707. }
  1708. #endif
  1709. skb->destructor = sock_wfree;
  1710. skb_set_hash_from_sk(skb, sk);
  1711. /*
  1712. * We used to take a refcount on sk, but following operation
  1713. * is enough to guarantee sk_free() wont free this sock until
  1714. * all in-flight packets are completed
  1715. */
  1716. refcount_add(skb->truesize, &sk->sk_wmem_alloc);
  1717. }
  1718. EXPORT_SYMBOL(skb_set_owner_w);
  1719. static bool can_skb_orphan_partial(const struct sk_buff *skb)
  1720. {
  1721. #ifdef CONFIG_TLS_DEVICE
  1722. /* Drivers depend on in-order delivery for crypto offload,
  1723. * partial orphan breaks out-of-order-OK logic.
  1724. */
  1725. if (skb->decrypted)
  1726. return false;
  1727. #endif
  1728. return (skb->destructor == sock_wfree ||
  1729. (IS_ENABLED(CONFIG_INET) && skb->destructor == tcp_wfree));
  1730. }
  1731. /* This helper is used by netem, as it can hold packets in its
  1732. * delay queue. We want to allow the owner socket to send more
  1733. * packets, as if they were already TX completed by a typical driver.
  1734. * But we also want to keep skb->sk set because some packet schedulers
  1735. * rely on it (sch_fq for example).
  1736. */
  1737. void skb_orphan_partial(struct sk_buff *skb)
  1738. {
  1739. if (skb_is_tcp_pure_ack(skb))
  1740. return;
  1741. if (can_skb_orphan_partial(skb)) {
  1742. struct sock *sk = skb->sk;
  1743. if (refcount_inc_not_zero(&sk->sk_refcnt)) {
  1744. WARN_ON(refcount_sub_and_test(skb->truesize, &sk->sk_wmem_alloc));
  1745. skb->destructor = sock_efree;
  1746. }
  1747. } else {
  1748. skb_orphan(skb);
  1749. }
  1750. }
  1751. EXPORT_SYMBOL(skb_orphan_partial);
  1752. /*
  1753. * Read buffer destructor automatically called from kfree_skb.
  1754. */
  1755. void sock_rfree(struct sk_buff *skb)
  1756. {
  1757. struct sock *sk = skb->sk;
  1758. unsigned int len = skb->truesize;
  1759. atomic_sub(len, &sk->sk_rmem_alloc);
  1760. sk_mem_uncharge(sk, len);
  1761. }
  1762. EXPORT_SYMBOL(sock_rfree);
  1763. /*
  1764. * Buffer destructor for skbs that are not used directly in read or write
  1765. * path, e.g. for error handler skbs. Automatically called from kfree_skb.
  1766. */
  1767. void sock_efree(struct sk_buff *skb)
  1768. {
  1769. sock_put(skb->sk);
  1770. }
  1771. EXPORT_SYMBOL(sock_efree);
  1772. /* Buffer destructor for prefetch/receive path where reference count may
  1773. * not be held, e.g. for listen sockets.
  1774. */
  1775. #ifdef CONFIG_INET
  1776. void sock_pfree(struct sk_buff *skb)
  1777. {
  1778. if (sk_is_refcounted(skb->sk))
  1779. sock_gen_put(skb->sk);
  1780. }
  1781. EXPORT_SYMBOL(sock_pfree);
  1782. #endif /* CONFIG_INET */
  1783. kuid_t sock_i_uid(struct sock *sk)
  1784. {
  1785. kuid_t uid;
  1786. read_lock_bh(&sk->sk_callback_lock);
  1787. uid = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_uid : GLOBAL_ROOT_UID;
  1788. read_unlock_bh(&sk->sk_callback_lock);
  1789. return uid;
  1790. }
  1791. EXPORT_SYMBOL(sock_i_uid);
  1792. unsigned long sock_i_ino(struct sock *sk)
  1793. {
  1794. unsigned long ino;
  1795. read_lock_bh(&sk->sk_callback_lock);
  1796. ino = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_ino : 0;
  1797. read_unlock_bh(&sk->sk_callback_lock);
  1798. return ino;
  1799. }
  1800. EXPORT_SYMBOL(sock_i_ino);
  1801. /*
  1802. * Allocate a skb from the socket's send buffer.
  1803. */
  1804. struct sk_buff *sock_wmalloc(struct sock *sk, unsigned long size, int force,
  1805. gfp_t priority)
  1806. {
  1807. if (force ||
  1808. refcount_read(&sk->sk_wmem_alloc) < READ_ONCE(sk->sk_sndbuf)) {
  1809. struct sk_buff *skb = alloc_skb(size, priority);
  1810. if (skb) {
  1811. skb_set_owner_w(skb, sk);
  1812. return skb;
  1813. }
  1814. }
  1815. return NULL;
  1816. }
  1817. EXPORT_SYMBOL(sock_wmalloc);
  1818. static void sock_ofree(struct sk_buff *skb)
  1819. {
  1820. struct sock *sk = skb->sk;
  1821. atomic_sub(skb->truesize, &sk->sk_omem_alloc);
  1822. }
  1823. struct sk_buff *sock_omalloc(struct sock *sk, unsigned long size,
  1824. gfp_t priority)
  1825. {
  1826. struct sk_buff *skb;
  1827. /* small safe race: SKB_TRUESIZE may differ from final skb->truesize */
  1828. if (atomic_read(&sk->sk_omem_alloc) + SKB_TRUESIZE(size) >
  1829. sysctl_optmem_max)
  1830. return NULL;
  1831. skb = alloc_skb(size, priority);
  1832. if (!skb)
  1833. return NULL;
  1834. atomic_add(skb->truesize, &sk->sk_omem_alloc);
  1835. skb->sk = sk;
  1836. skb->destructor = sock_ofree;
  1837. return skb;
  1838. }
  1839. /*
  1840. * Allocate a memory block from the socket's option memory buffer.
  1841. */
  1842. void *sock_kmalloc(struct sock *sk, int size, gfp_t priority)
  1843. {
  1844. if ((unsigned int)size <= sysctl_optmem_max &&
  1845. atomic_read(&sk->sk_omem_alloc) + size < sysctl_optmem_max) {
  1846. void *mem;
  1847. /* First do the add, to avoid the race if kmalloc
  1848. * might sleep.
  1849. */
  1850. atomic_add(size, &sk->sk_omem_alloc);
  1851. mem = kmalloc(size, priority);
  1852. if (mem)
  1853. return mem;
  1854. atomic_sub(size, &sk->sk_omem_alloc);
  1855. }
  1856. return NULL;
  1857. }
  1858. EXPORT_SYMBOL(sock_kmalloc);
  1859. /* Free an option memory block. Note, we actually want the inline
  1860. * here as this allows gcc to detect the nullify and fold away the
  1861. * condition entirely.
  1862. */
  1863. static inline void __sock_kfree_s(struct sock *sk, void *mem, int size,
  1864. const bool nullify)
  1865. {
  1866. if (WARN_ON_ONCE(!mem))
  1867. return;
  1868. if (nullify)
  1869. kzfree(mem);
  1870. else
  1871. kfree(mem);
  1872. atomic_sub(size, &sk->sk_omem_alloc);
  1873. }
  1874. void sock_kfree_s(struct sock *sk, void *mem, int size)
  1875. {
  1876. __sock_kfree_s(sk, mem, size, false);
  1877. }
  1878. EXPORT_SYMBOL(sock_kfree_s);
  1879. void sock_kzfree_s(struct sock *sk, void *mem, int size)
  1880. {
  1881. __sock_kfree_s(sk, mem, size, true);
  1882. }
  1883. EXPORT_SYMBOL(sock_kzfree_s);
  1884. /* It is almost wait_for_tcp_memory minus release_sock/lock_sock.
  1885. I think, these locks should be removed for datagram sockets.
  1886. */
  1887. static long sock_wait_for_wmem(struct sock *sk, long timeo)
  1888. {
  1889. DEFINE_WAIT(wait);
  1890. sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
  1891. for (;;) {
  1892. if (!timeo)
  1893. break;
  1894. if (signal_pending(current))
  1895. break;
  1896. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  1897. prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
  1898. if (refcount_read(&sk->sk_wmem_alloc) < READ_ONCE(sk->sk_sndbuf))
  1899. break;
  1900. if (sk->sk_shutdown & SEND_SHUTDOWN)
  1901. break;
  1902. if (sk->sk_err)
  1903. break;
  1904. timeo = schedule_timeout(timeo);
  1905. }
  1906. finish_wait(sk_sleep(sk), &wait);
  1907. return timeo;
  1908. }
  1909. /*
  1910. * Generic send/receive buffer handlers
  1911. */
  1912. struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
  1913. unsigned long data_len, int noblock,
  1914. int *errcode, int max_page_order)
  1915. {
  1916. struct sk_buff *skb;
  1917. long timeo;
  1918. int err;
  1919. timeo = sock_sndtimeo(sk, noblock);
  1920. for (;;) {
  1921. err = sock_error(sk);
  1922. if (err != 0)
  1923. goto failure;
  1924. err = -EPIPE;
  1925. if (sk->sk_shutdown & SEND_SHUTDOWN)
  1926. goto failure;
  1927. if (sk_wmem_alloc_get(sk) < READ_ONCE(sk->sk_sndbuf))
  1928. break;
  1929. sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
  1930. set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
  1931. err = -EAGAIN;
  1932. if (!timeo)
  1933. goto failure;
  1934. if (signal_pending(current))
  1935. goto interrupted;
  1936. timeo = sock_wait_for_wmem(sk, timeo);
  1937. }
  1938. skb = alloc_skb_with_frags(header_len, data_len, max_page_order,
  1939. errcode, sk->sk_allocation);
  1940. if (skb)
  1941. skb_set_owner_w(skb, sk);
  1942. return skb;
  1943. interrupted:
  1944. err = sock_intr_errno(timeo);
  1945. failure:
  1946. *errcode = err;
  1947. return NULL;
  1948. }
  1949. EXPORT_SYMBOL(sock_alloc_send_pskb);
  1950. struct sk_buff *sock_alloc_send_skb(struct sock *sk, unsigned long size,
  1951. int noblock, int *errcode)
  1952. {
  1953. return sock_alloc_send_pskb(sk, size, 0, noblock, errcode, 0);
  1954. }
  1955. EXPORT_SYMBOL(sock_alloc_send_skb);
  1956. int __sock_cmsg_send(struct sock *sk, struct msghdr *msg, struct cmsghdr *cmsg,
  1957. struct sockcm_cookie *sockc)
  1958. {
  1959. u32 tsflags;
  1960. switch (cmsg->cmsg_type) {
  1961. case SO_MARK:
  1962. if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
  1963. return -EPERM;
  1964. if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32)))
  1965. return -EINVAL;
  1966. sockc->mark = *(u32 *)CMSG_DATA(cmsg);
  1967. break;
  1968. case SO_TIMESTAMPING_OLD:
  1969. if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32)))
  1970. return -EINVAL;
  1971. tsflags = *(u32 *)CMSG_DATA(cmsg);
  1972. if (tsflags & ~SOF_TIMESTAMPING_TX_RECORD_MASK)
  1973. return -EINVAL;
  1974. sockc->tsflags &= ~SOF_TIMESTAMPING_TX_RECORD_MASK;
  1975. sockc->tsflags |= tsflags;
  1976. break;
  1977. case SCM_TXTIME:
  1978. if (!sock_flag(sk, SOCK_TXTIME))
  1979. return -EINVAL;
  1980. if (cmsg->cmsg_len != CMSG_LEN(sizeof(u64)))
  1981. return -EINVAL;
  1982. sockc->transmit_time = get_unaligned((u64 *)CMSG_DATA(cmsg));
  1983. break;
  1984. /* SCM_RIGHTS and SCM_CREDENTIALS are semantically in SOL_UNIX. */
  1985. case SCM_RIGHTS:
  1986. case SCM_CREDENTIALS:
  1987. break;
  1988. default:
  1989. return -EINVAL;
  1990. }
  1991. return 0;
  1992. }
  1993. EXPORT_SYMBOL(__sock_cmsg_send);
  1994. int sock_cmsg_send(struct sock *sk, struct msghdr *msg,
  1995. struct sockcm_cookie *sockc)
  1996. {
  1997. struct cmsghdr *cmsg;
  1998. int ret;
  1999. for_each_cmsghdr(cmsg, msg) {
  2000. if (!CMSG_OK(msg, cmsg))
  2001. return -EINVAL;
  2002. if (cmsg->cmsg_level != SOL_SOCKET)
  2003. continue;
  2004. ret = __sock_cmsg_send(sk, msg, cmsg, sockc);
  2005. if (ret)
  2006. return ret;
  2007. }
  2008. return 0;
  2009. }
  2010. EXPORT_SYMBOL(sock_cmsg_send);
  2011. static void sk_enter_memory_pressure(struct sock *sk)
  2012. {
  2013. if (!sk->sk_prot->enter_memory_pressure)
  2014. return;
  2015. sk->sk_prot->enter_memory_pressure(sk);
  2016. }
  2017. static void sk_leave_memory_pressure(struct sock *sk)
  2018. {
  2019. if (sk->sk_prot->leave_memory_pressure) {
  2020. sk->sk_prot->leave_memory_pressure(sk);
  2021. } else {
  2022. unsigned long *memory_pressure = sk->sk_prot->memory_pressure;
  2023. if (memory_pressure && READ_ONCE(*memory_pressure))
  2024. WRITE_ONCE(*memory_pressure, 0);
  2025. }
  2026. }
  2027. #define SKB_FRAG_PAGE_ORDER get_order(32768)
  2028. DEFINE_STATIC_KEY_FALSE(net_high_order_alloc_disable_key);
  2029. /**
  2030. * skb_page_frag_refill - check that a page_frag contains enough room
  2031. * @sz: minimum size of the fragment we want to get
  2032. * @pfrag: pointer to page_frag
  2033. * @gfp: priority for memory allocation
  2034. *
  2035. * Note: While this allocator tries to use high order pages, there is
  2036. * no guarantee that allocations succeed. Therefore, @sz MUST be
  2037. * less or equal than PAGE_SIZE.
  2038. */
  2039. bool skb_page_frag_refill(unsigned int sz, struct page_frag *pfrag, gfp_t gfp)
  2040. {
  2041. if (pfrag->page) {
  2042. if (page_ref_count(pfrag->page) == 1) {
  2043. pfrag->offset = 0;
  2044. return true;
  2045. }
  2046. if (pfrag->offset + sz <= pfrag->size)
  2047. return true;
  2048. put_page(pfrag->page);
  2049. }
  2050. pfrag->offset = 0;
  2051. if (SKB_FRAG_PAGE_ORDER &&
  2052. !static_branch_unlikely(&net_high_order_alloc_disable_key)) {
  2053. /* Avoid direct reclaim but allow kswapd to wake */
  2054. pfrag->page = alloc_pages((gfp & ~__GFP_DIRECT_RECLAIM) |
  2055. __GFP_COMP | __GFP_NOWARN |
  2056. __GFP_NORETRY,
  2057. SKB_FRAG_PAGE_ORDER);
  2058. if (likely(pfrag->page)) {
  2059. pfrag->size = PAGE_SIZE << SKB_FRAG_PAGE_ORDER;
  2060. return true;
  2061. }
  2062. }
  2063. pfrag->page = alloc_page(gfp);
  2064. if (likely(pfrag->page)) {
  2065. pfrag->size = PAGE_SIZE;
  2066. return true;
  2067. }
  2068. return false;
  2069. }
  2070. EXPORT_SYMBOL(skb_page_frag_refill);
  2071. bool sk_page_frag_refill(struct sock *sk, struct page_frag *pfrag)
  2072. {
  2073. if (likely(skb_page_frag_refill(32U, pfrag, sk->sk_allocation)))
  2074. return true;
  2075. sk_enter_memory_pressure(sk);
  2076. sk_stream_moderate_sndbuf(sk);
  2077. return false;
  2078. }
  2079. EXPORT_SYMBOL(sk_page_frag_refill);
  2080. static void __lock_sock(struct sock *sk)
  2081. __releases(&sk->sk_lock.slock)
  2082. __acquires(&sk->sk_lock.slock)
  2083. {
  2084. DEFINE_WAIT(wait);
  2085. for (;;) {
  2086. prepare_to_wait_exclusive(&sk->sk_lock.wq, &wait,
  2087. TASK_UNINTERRUPTIBLE);
  2088. spin_unlock_bh(&sk->sk_lock.slock);
  2089. schedule();
  2090. spin_lock_bh(&sk->sk_lock.slock);
  2091. if (!sock_owned_by_user(sk))
  2092. break;
  2093. }
  2094. finish_wait(&sk->sk_lock.wq, &wait);
  2095. }
  2096. void __release_sock(struct sock *sk)
  2097. __releases(&sk->sk_lock.slock)
  2098. __acquires(&sk->sk_lock.slock)
  2099. {
  2100. struct sk_buff *skb, *next;
  2101. while ((skb = sk->sk_backlog.head) != NULL) {
  2102. sk->sk_backlog.head = sk->sk_backlog.tail = NULL;
  2103. spin_unlock_bh(&sk->sk_lock.slock);
  2104. do {
  2105. next = skb->next;
  2106. prefetch(next);
  2107. WARN_ON_ONCE(skb_dst_is_noref(skb));
  2108. skb_mark_not_on_list(skb);
  2109. sk_backlog_rcv(sk, skb);
  2110. cond_resched();
  2111. skb = next;
  2112. } while (skb != NULL);
  2113. spin_lock_bh(&sk->sk_lock.slock);
  2114. }
  2115. /*
  2116. * Doing the zeroing here guarantee we can not loop forever
  2117. * while a wild producer attempts to flood us.
  2118. */
  2119. sk->sk_backlog.len = 0;
  2120. }
  2121. void __sk_flush_backlog(struct sock *sk)
  2122. {
  2123. spin_lock_bh(&sk->sk_lock.slock);
  2124. __release_sock(sk);
  2125. spin_unlock_bh(&sk->sk_lock.slock);
  2126. }
  2127. /**
  2128. * sk_wait_data - wait for data to arrive at sk_receive_queue
  2129. * @sk: sock to wait on
  2130. * @timeo: for how long
  2131. * @skb: last skb seen on sk_receive_queue
  2132. *
  2133. * Now socket state including sk->sk_err is changed only under lock,
  2134. * hence we may omit checks after joining wait queue.
  2135. * We check receive queue before schedule() only as optimization;
  2136. * it is very likely that release_sock() added new data.
  2137. */
  2138. int sk_wait_data(struct sock *sk, long *timeo, const struct sk_buff *skb)
  2139. {
  2140. DEFINE_WAIT_FUNC(wait, woken_wake_function);
  2141. int rc;
  2142. add_wait_queue(sk_sleep(sk), &wait);
  2143. sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
  2144. rc = sk_wait_event(sk, timeo, skb_peek_tail(&sk->sk_receive_queue) != skb, &wait);
  2145. sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
  2146. remove_wait_queue(sk_sleep(sk), &wait);
  2147. return rc;
  2148. }
  2149. EXPORT_SYMBOL(sk_wait_data);
  2150. /**
  2151. * __sk_mem_raise_allocated - increase memory_allocated
  2152. * @sk: socket
  2153. * @size: memory size to allocate
  2154. * @amt: pages to allocate
  2155. * @kind: allocation type
  2156. *
  2157. * Similar to __sk_mem_schedule(), but does not update sk_forward_alloc
  2158. */
  2159. int __sk_mem_raise_allocated(struct sock *sk, int size, int amt, int kind)
  2160. {
  2161. struct proto *prot = sk->sk_prot;
  2162. long allocated = sk_memory_allocated_add(sk, amt);
  2163. bool charged = true;
  2164. if (mem_cgroup_sockets_enabled && sk->sk_memcg &&
  2165. !(charged = mem_cgroup_charge_skmem(sk->sk_memcg, amt)))
  2166. goto suppress_allocation;
  2167. /* Under limit. */
  2168. if (allocated <= sk_prot_mem_limits(sk, 0)) {
  2169. sk_leave_memory_pressure(sk);
  2170. return 1;
  2171. }
  2172. /* Under pressure. */
  2173. if (allocated > sk_prot_mem_limits(sk, 1))
  2174. sk_enter_memory_pressure(sk);
  2175. /* Over hard limit. */
  2176. if (allocated > sk_prot_mem_limits(sk, 2))
  2177. goto suppress_allocation;
  2178. /* guarantee minimum buffer size under pressure */
  2179. if (kind == SK_MEM_RECV) {
  2180. if (atomic_read(&sk->sk_rmem_alloc) < sk_get_rmem0(sk, prot))
  2181. return 1;
  2182. } else { /* SK_MEM_SEND */
  2183. int wmem0 = sk_get_wmem0(sk, prot);
  2184. if (sk->sk_type == SOCK_STREAM) {
  2185. if (sk->sk_wmem_queued < wmem0)
  2186. return 1;
  2187. } else if (refcount_read(&sk->sk_wmem_alloc) < wmem0) {
  2188. return 1;
  2189. }
  2190. }
  2191. if (sk_has_memory_pressure(sk)) {
  2192. u64 alloc;
  2193. if (!sk_under_memory_pressure(sk))
  2194. return 1;
  2195. alloc = sk_sockets_allocated_read_positive(sk);
  2196. if (sk_prot_mem_limits(sk, 2) > alloc *
  2197. sk_mem_pages(sk->sk_wmem_queued +
  2198. atomic_read(&sk->sk_rmem_alloc) +
  2199. sk->sk_forward_alloc))
  2200. return 1;
  2201. }
  2202. suppress_allocation:
  2203. if (kind == SK_MEM_SEND && sk->sk_type == SOCK_STREAM) {
  2204. sk_stream_moderate_sndbuf(sk);
  2205. /* Fail only if socket is _under_ its sndbuf.
  2206. * In this case we cannot block, so that we have to fail.
  2207. */
  2208. if (sk->sk_wmem_queued + size >= sk->sk_sndbuf)
  2209. return 1;
  2210. }
  2211. if (kind == SK_MEM_SEND || (kind == SK_MEM_RECV && charged))
  2212. trace_sock_exceed_buf_limit(sk, prot, allocated, kind);
  2213. sk_memory_allocated_sub(sk, amt);
  2214. if (mem_cgroup_sockets_enabled && sk->sk_memcg)
  2215. mem_cgroup_uncharge_skmem(sk->sk_memcg, amt);
  2216. return 0;
  2217. }
  2218. EXPORT_SYMBOL(__sk_mem_raise_allocated);
  2219. /**
  2220. * __sk_mem_schedule - increase sk_forward_alloc and memory_allocated
  2221. * @sk: socket
  2222. * @size: memory size to allocate
  2223. * @kind: allocation type
  2224. *
  2225. * If kind is SK_MEM_SEND, it means wmem allocation. Otherwise it means
  2226. * rmem allocation. This function assumes that protocols which have
  2227. * memory_pressure use sk_wmem_queued as write buffer accounting.
  2228. */
  2229. int __sk_mem_schedule(struct sock *sk, int size, int kind)
  2230. {
  2231. int ret, amt = sk_mem_pages(size);
  2232. sk->sk_forward_alloc += amt << SK_MEM_QUANTUM_SHIFT;
  2233. ret = __sk_mem_raise_allocated(sk, size, amt, kind);
  2234. if (!ret)
  2235. sk->sk_forward_alloc -= amt << SK_MEM_QUANTUM_SHIFT;
  2236. return ret;
  2237. }
  2238. EXPORT_SYMBOL(__sk_mem_schedule);
  2239. /**
  2240. * __sk_mem_reduce_allocated - reclaim memory_allocated
  2241. * @sk: socket
  2242. * @amount: number of quanta
  2243. *
  2244. * Similar to __sk_mem_reclaim(), but does not update sk_forward_alloc
  2245. */
  2246. void __sk_mem_reduce_allocated(struct sock *sk, int amount)
  2247. {
  2248. sk_memory_allocated_sub(sk, amount);
  2249. if (mem_cgroup_sockets_enabled && sk->sk_memcg)
  2250. mem_cgroup_uncharge_skmem(sk->sk_memcg, amount);
  2251. if (sk_under_memory_pressure(sk) &&
  2252. (sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0)))
  2253. sk_leave_memory_pressure(sk);
  2254. }
  2255. EXPORT_SYMBOL(__sk_mem_reduce_allocated);
  2256. /**
  2257. * __sk_mem_reclaim - reclaim sk_forward_alloc and memory_allocated
  2258. * @sk: socket
  2259. * @amount: number of bytes (rounded down to a SK_MEM_QUANTUM multiple)
  2260. */
  2261. void __sk_mem_reclaim(struct sock *sk, int amount)
  2262. {
  2263. amount >>= SK_MEM_QUANTUM_SHIFT;
  2264. sk->sk_forward_alloc -= amount << SK_MEM_QUANTUM_SHIFT;
  2265. __sk_mem_reduce_allocated(sk, amount);
  2266. }
  2267. EXPORT_SYMBOL(__sk_mem_reclaim);
  2268. int sk_set_peek_off(struct sock *sk, int val)
  2269. {
  2270. sk->sk_peek_off = val;
  2271. return 0;
  2272. }
  2273. EXPORT_SYMBOL_GPL(sk_set_peek_off);
  2274. /*
  2275. * Set of default routines for initialising struct proto_ops when
  2276. * the protocol does not support a particular function. In certain
  2277. * cases where it makes no sense for a protocol to have a "do nothing"
  2278. * function, some default processing is provided.
  2279. */
  2280. int sock_no_bind(struct socket *sock, struct sockaddr *saddr, int len)
  2281. {
  2282. return -EOPNOTSUPP;
  2283. }
  2284. EXPORT_SYMBOL(sock_no_bind);
  2285. int sock_no_connect(struct socket *sock, struct sockaddr *saddr,
  2286. int len, int flags)
  2287. {
  2288. return -EOPNOTSUPP;
  2289. }
  2290. EXPORT_SYMBOL(sock_no_connect);
  2291. int sock_no_socketpair(struct socket *sock1, struct socket *sock2)
  2292. {
  2293. return -EOPNOTSUPP;
  2294. }
  2295. EXPORT_SYMBOL(sock_no_socketpair);
  2296. int sock_no_accept(struct socket *sock, struct socket *newsock, int flags,
  2297. bool kern)
  2298. {
  2299. return -EOPNOTSUPP;
  2300. }
  2301. EXPORT_SYMBOL(sock_no_accept);
  2302. int sock_no_getname(struct socket *sock, struct sockaddr *saddr,
  2303. int peer)
  2304. {
  2305. return -EOPNOTSUPP;
  2306. }
  2307. EXPORT_SYMBOL(sock_no_getname);
  2308. int sock_no_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
  2309. {
  2310. return -EOPNOTSUPP;
  2311. }
  2312. EXPORT_SYMBOL(sock_no_ioctl);
  2313. int sock_no_listen(struct socket *sock, int backlog)
  2314. {
  2315. return -EOPNOTSUPP;
  2316. }
  2317. EXPORT_SYMBOL(sock_no_listen);
  2318. int sock_no_shutdown(struct socket *sock, int how)
  2319. {
  2320. return -EOPNOTSUPP;
  2321. }
  2322. EXPORT_SYMBOL(sock_no_shutdown);
  2323. int sock_no_setsockopt(struct socket *sock, int level, int optname,
  2324. char __user *optval, unsigned int optlen)
  2325. {
  2326. return -EOPNOTSUPP;
  2327. }
  2328. EXPORT_SYMBOL(sock_no_setsockopt);
  2329. int sock_no_getsockopt(struct socket *sock, int level, int optname,
  2330. char __user *optval, int __user *optlen)
  2331. {
  2332. return -EOPNOTSUPP;
  2333. }
  2334. EXPORT_SYMBOL(sock_no_getsockopt);
  2335. int sock_no_sendmsg(struct socket *sock, struct msghdr *m, size_t len)
  2336. {
  2337. return -EOPNOTSUPP;
  2338. }
  2339. EXPORT_SYMBOL(sock_no_sendmsg);
  2340. int sock_no_sendmsg_locked(struct sock *sk, struct msghdr *m, size_t len)
  2341. {
  2342. return -EOPNOTSUPP;
  2343. }
  2344. EXPORT_SYMBOL(sock_no_sendmsg_locked);
  2345. int sock_no_recvmsg(struct socket *sock, struct msghdr *m, size_t len,
  2346. int flags)
  2347. {
  2348. return -EOPNOTSUPP;
  2349. }
  2350. EXPORT_SYMBOL(sock_no_recvmsg);
  2351. int sock_no_mmap(struct file *file, struct socket *sock, struct vm_area_struct *vma)
  2352. {
  2353. /* Mirror missing mmap method error code */
  2354. return -ENODEV;
  2355. }
  2356. EXPORT_SYMBOL(sock_no_mmap);
  2357. ssize_t sock_no_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags)
  2358. {
  2359. ssize_t res;
  2360. struct msghdr msg = {.msg_flags = flags};
  2361. struct kvec iov;
  2362. char *kaddr = kmap(page);
  2363. iov.iov_base = kaddr + offset;
  2364. iov.iov_len = size;
  2365. res = kernel_sendmsg(sock, &msg, &iov, 1, size);
  2366. kunmap(page);
  2367. return res;
  2368. }
  2369. EXPORT_SYMBOL(sock_no_sendpage);
  2370. ssize_t sock_no_sendpage_locked(struct sock *sk, struct page *page,
  2371. int offset, size_t size, int flags)
  2372. {
  2373. ssize_t res;
  2374. struct msghdr msg = {.msg_flags = flags};
  2375. struct kvec iov;
  2376. char *kaddr = kmap(page);
  2377. iov.iov_base = kaddr + offset;
  2378. iov.iov_len = size;
  2379. res = kernel_sendmsg_locked(sk, &msg, &iov, 1, size);
  2380. kunmap(page);
  2381. return res;
  2382. }
  2383. EXPORT_SYMBOL(sock_no_sendpage_locked);
  2384. /*
  2385. * Default Socket Callbacks
  2386. */
  2387. static void sock_def_wakeup(struct sock *sk)
  2388. {
  2389. struct socket_wq *wq;
  2390. rcu_read_lock();
  2391. wq = rcu_dereference(sk->sk_wq);
  2392. if (skwq_has_sleeper(wq))
  2393. wake_up_interruptible_all(&wq->wait);
  2394. rcu_read_unlock();
  2395. }
  2396. static void sock_def_error_report(struct sock *sk)
  2397. {
  2398. struct socket_wq *wq;
  2399. rcu_read_lock();
  2400. wq = rcu_dereference(sk->sk_wq);
  2401. if (skwq_has_sleeper(wq))
  2402. wake_up_interruptible_poll(&wq->wait, EPOLLERR);
  2403. sk_wake_async(sk, SOCK_WAKE_IO, POLL_ERR);
  2404. rcu_read_unlock();
  2405. }
  2406. void sock_def_readable(struct sock *sk)
  2407. {
  2408. struct socket_wq *wq;
  2409. rcu_read_lock();
  2410. wq = rcu_dereference(sk->sk_wq);
  2411. if (skwq_has_sleeper(wq))
  2412. wake_up_interruptible_sync_poll(&wq->wait, EPOLLIN | EPOLLPRI |
  2413. EPOLLRDNORM | EPOLLRDBAND);
  2414. sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
  2415. rcu_read_unlock();
  2416. }
  2417. static void sock_def_write_space(struct sock *sk)
  2418. {
  2419. struct socket_wq *wq;
  2420. rcu_read_lock();
  2421. /* Do not wake up a writer until he can make "significant"
  2422. * progress. --DaveM
  2423. */
  2424. if ((refcount_read(&sk->sk_wmem_alloc) << 1) <= READ_ONCE(sk->sk_sndbuf)) {
  2425. wq = rcu_dereference(sk->sk_wq);
  2426. if (skwq_has_sleeper(wq))
  2427. wake_up_interruptible_sync_poll(&wq->wait, EPOLLOUT |
  2428. EPOLLWRNORM | EPOLLWRBAND);
  2429. /* Should agree with poll, otherwise some programs break */
  2430. if (sock_writeable(sk))
  2431. sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
  2432. }
  2433. rcu_read_unlock();
  2434. }
  2435. static void sock_def_destruct(struct sock *sk)
  2436. {
  2437. }
  2438. void sk_send_sigurg(struct sock *sk)
  2439. {
  2440. if (sk->sk_socket && sk->sk_socket->file)
  2441. if (send_sigurg(&sk->sk_socket->file->f_owner))
  2442. sk_wake_async(sk, SOCK_WAKE_URG, POLL_PRI);
  2443. }
  2444. EXPORT_SYMBOL(sk_send_sigurg);
  2445. void sk_reset_timer(struct sock *sk, struct timer_list* timer,
  2446. unsigned long expires)
  2447. {
  2448. if (!mod_timer(timer, expires))
  2449. sock_hold(sk);
  2450. }
  2451. EXPORT_SYMBOL(sk_reset_timer);
  2452. void sk_stop_timer(struct sock *sk, struct timer_list* timer)
  2453. {
  2454. if (del_timer(timer))
  2455. __sock_put(sk);
  2456. }
  2457. EXPORT_SYMBOL(sk_stop_timer);
  2458. void sock_init_data(struct socket *sock, struct sock *sk)
  2459. {
  2460. sk_init_common(sk);
  2461. sk->sk_send_head = NULL;
  2462. timer_setup(&sk->sk_timer, NULL, 0);
  2463. sk->sk_allocation = GFP_KERNEL;
  2464. sk->sk_rcvbuf = sysctl_rmem_default;
  2465. sk->sk_sndbuf = sysctl_wmem_default;
  2466. sk->sk_state = TCP_CLOSE;
  2467. sk_set_socket(sk, sock);
  2468. sock_set_flag(sk, SOCK_ZAPPED);
  2469. if (sock) {
  2470. sk->sk_type = sock->type;
  2471. RCU_INIT_POINTER(sk->sk_wq, &sock->wq);
  2472. sock->sk = sk;
  2473. sk->sk_uid = SOCK_INODE(sock)->i_uid;
  2474. } else {
  2475. RCU_INIT_POINTER(sk->sk_wq, NULL);
  2476. sk->sk_uid = make_kuid(sock_net(sk)->user_ns, 0);
  2477. }
  2478. rwlock_init(&sk->sk_callback_lock);
  2479. if (sk->sk_kern_sock)
  2480. lockdep_set_class_and_name(
  2481. &sk->sk_callback_lock,
  2482. af_kern_callback_keys + sk->sk_family,
  2483. af_family_kern_clock_key_strings[sk->sk_family]);
  2484. else
  2485. lockdep_set_class_and_name(
  2486. &sk->sk_callback_lock,
  2487. af_callback_keys + sk->sk_family,
  2488. af_family_clock_key_strings[sk->sk_family]);
  2489. sk->sk_state_change = sock_def_wakeup;
  2490. sk->sk_data_ready = sock_def_readable;
  2491. sk->sk_write_space = sock_def_write_space;
  2492. sk->sk_error_report = sock_def_error_report;
  2493. sk->sk_destruct = sock_def_destruct;
  2494. sk->sk_frag.page = NULL;
  2495. sk->sk_frag.offset = 0;
  2496. sk->sk_peek_off = -1;
  2497. sk->sk_peer_pid = NULL;
  2498. sk->sk_peer_cred = NULL;
  2499. sk->sk_write_pending = 0;
  2500. sk->sk_rcvlowat = 1;
  2501. sk->sk_rcvtimeo = MAX_SCHEDULE_TIMEOUT;
  2502. sk->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT;
  2503. sk->sk_stamp = SK_DEFAULT_STAMP;
  2504. #if BITS_PER_LONG==32
  2505. seqlock_init(&sk->sk_stamp_seq);
  2506. #endif
  2507. atomic_set(&sk->sk_zckey, 0);
  2508. #ifdef CONFIG_NET_RX_BUSY_POLL
  2509. sk->sk_napi_id = 0;
  2510. sk->sk_ll_usec = sysctl_net_busy_read;
  2511. #endif
  2512. sk->sk_max_pacing_rate = ~0UL;
  2513. sk->sk_pacing_rate = ~0UL;
  2514. WRITE_ONCE(sk->sk_pacing_shift, 10);
  2515. sk->sk_incoming_cpu = -1;
  2516. sk_rx_queue_clear(sk);
  2517. /*
  2518. * Before updating sk_refcnt, we must commit prior changes to memory
  2519. * (Documentation/RCU/rculist_nulls.txt for details)
  2520. */
  2521. smp_wmb();
  2522. refcount_set(&sk->sk_refcnt, 1);
  2523. atomic_set(&sk->sk_drops, 0);
  2524. }
  2525. EXPORT_SYMBOL(sock_init_data);
  2526. void lock_sock_nested(struct sock *sk, int subclass)
  2527. {
  2528. might_sleep();
  2529. spin_lock_bh(&sk->sk_lock.slock);
  2530. if (sk->sk_lock.owned)
  2531. __lock_sock(sk);
  2532. sk->sk_lock.owned = 1;
  2533. spin_unlock(&sk->sk_lock.slock);
  2534. /*
  2535. * The sk_lock has mutex_lock() semantics here:
  2536. */
  2537. mutex_acquire(&sk->sk_lock.dep_map, subclass, 0, _RET_IP_);
  2538. local_bh_enable();
  2539. }
  2540. EXPORT_SYMBOL(lock_sock_nested);
  2541. void release_sock(struct sock *sk)
  2542. {
  2543. spin_lock_bh(&sk->sk_lock.slock);
  2544. if (sk->sk_backlog.tail)
  2545. __release_sock(sk);
  2546. /* Warning : release_cb() might need to release sk ownership,
  2547. * ie call sock_release_ownership(sk) before us.
  2548. */
  2549. if (sk->sk_prot->release_cb)
  2550. sk->sk_prot->release_cb(sk);
  2551. sock_release_ownership(sk);
  2552. if (waitqueue_active(&sk->sk_lock.wq))
  2553. wake_up(&sk->sk_lock.wq);
  2554. spin_unlock_bh(&sk->sk_lock.slock);
  2555. }
  2556. EXPORT_SYMBOL(release_sock);
  2557. /**
  2558. * lock_sock_fast - fast version of lock_sock
  2559. * @sk: socket
  2560. *
  2561. * This version should be used for very small section, where process wont block
  2562. * return false if fast path is taken:
  2563. *
  2564. * sk_lock.slock locked, owned = 0, BH disabled
  2565. *
  2566. * return true if slow path is taken:
  2567. *
  2568. * sk_lock.slock unlocked, owned = 1, BH enabled
  2569. */
  2570. bool lock_sock_fast(struct sock *sk)
  2571. {
  2572. might_sleep();
  2573. spin_lock_bh(&sk->sk_lock.slock);
  2574. if (!sk->sk_lock.owned)
  2575. /*
  2576. * Note : We must disable BH
  2577. */
  2578. return false;
  2579. __lock_sock(sk);
  2580. sk->sk_lock.owned = 1;
  2581. spin_unlock(&sk->sk_lock.slock);
  2582. /*
  2583. * The sk_lock has mutex_lock() semantics here:
  2584. */
  2585. mutex_acquire(&sk->sk_lock.dep_map, 0, 0, _RET_IP_);
  2586. local_bh_enable();
  2587. return true;
  2588. }
  2589. EXPORT_SYMBOL(lock_sock_fast);
  2590. int sock_gettstamp(struct socket *sock, void __user *userstamp,
  2591. bool timeval, bool time32)
  2592. {
  2593. struct sock *sk = sock->sk;
  2594. struct timespec64 ts;
  2595. sock_enable_timestamp(sk, SOCK_TIMESTAMP);
  2596. ts = ktime_to_timespec64(sock_read_timestamp(sk));
  2597. if (ts.tv_sec == -1)
  2598. return -ENOENT;
  2599. if (ts.tv_sec == 0) {
  2600. ktime_t kt = ktime_get_real();
  2601. sock_write_timestamp(sk, kt);
  2602. ts = ktime_to_timespec64(kt);
  2603. }
  2604. if (timeval)
  2605. ts.tv_nsec /= 1000;
  2606. #ifdef CONFIG_COMPAT_32BIT_TIME
  2607. if (time32)
  2608. return put_old_timespec32(&ts, userstamp);
  2609. #endif
  2610. #ifdef CONFIG_SPARC64
  2611. /* beware of padding in sparc64 timeval */
  2612. if (timeval && !in_compat_syscall()) {
  2613. struct __kernel_old_timeval __user tv = {
  2614. .tv_sec = ts.tv_sec,
  2615. .tv_usec = ts.tv_nsec,
  2616. };
  2617. if (copy_to_user(userstamp, &tv, sizeof(tv)))
  2618. return -EFAULT;
  2619. return 0;
  2620. }
  2621. #endif
  2622. return put_timespec64(&ts, userstamp);
  2623. }
  2624. EXPORT_SYMBOL(sock_gettstamp);
  2625. void sock_enable_timestamp(struct sock *sk, enum sock_flags flag)
  2626. {
  2627. if (!sock_flag(sk, flag)) {
  2628. unsigned long previous_flags = sk->sk_flags;
  2629. sock_set_flag(sk, flag);
  2630. /*
  2631. * we just set one of the two flags which require net
  2632. * time stamping, but time stamping might have been on
  2633. * already because of the other one
  2634. */
  2635. if (sock_needs_netstamp(sk) &&
  2636. !(previous_flags & SK_FLAGS_TIMESTAMP))
  2637. net_enable_timestamp();
  2638. }
  2639. }
  2640. int sock_recv_errqueue(struct sock *sk, struct msghdr *msg, int len,
  2641. int level, int type)
  2642. {
  2643. struct sock_exterr_skb *serr;
  2644. struct sk_buff *skb;
  2645. int copied, err;
  2646. err = -EAGAIN;
  2647. skb = sock_dequeue_err_skb(sk);
  2648. if (skb == NULL)
  2649. goto out;
  2650. copied = skb->len;
  2651. if (copied > len) {
  2652. msg->msg_flags |= MSG_TRUNC;
  2653. copied = len;
  2654. }
  2655. err = skb_copy_datagram_msg(skb, 0, msg, copied);
  2656. if (err)
  2657. goto out_free_skb;
  2658. sock_recv_timestamp(msg, sk, skb);
  2659. serr = SKB_EXT_ERR(skb);
  2660. put_cmsg(msg, level, type, sizeof(serr->ee), &serr->ee);
  2661. msg->msg_flags |= MSG_ERRQUEUE;
  2662. err = copied;
  2663. out_free_skb:
  2664. kfree_skb(skb);
  2665. out:
  2666. return err;
  2667. }
  2668. EXPORT_SYMBOL(sock_recv_errqueue);
  2669. /*
  2670. * Get a socket option on an socket.
  2671. *
  2672. * FIX: POSIX 1003.1g is very ambiguous here. It states that
  2673. * asynchronous errors should be reported by getsockopt. We assume
  2674. * this means if you specify SO_ERROR (otherwise whats the point of it).
  2675. */
  2676. int sock_common_getsockopt(struct socket *sock, int level, int optname,
  2677. char __user *optval, int __user *optlen)
  2678. {
  2679. struct sock *sk = sock->sk;
  2680. return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen);
  2681. }
  2682. EXPORT_SYMBOL(sock_common_getsockopt);
  2683. #ifdef CONFIG_COMPAT
  2684. int compat_sock_common_getsockopt(struct socket *sock, int level, int optname,
  2685. char __user *optval, int __user *optlen)
  2686. {
  2687. struct sock *sk = sock->sk;
  2688. if (sk->sk_prot->compat_getsockopt != NULL)
  2689. return sk->sk_prot->compat_getsockopt(sk, level, optname,
  2690. optval, optlen);
  2691. return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen);
  2692. }
  2693. EXPORT_SYMBOL(compat_sock_common_getsockopt);
  2694. #endif
  2695. int sock_common_recvmsg(struct socket *sock, struct msghdr *msg, size_t size,
  2696. int flags)
  2697. {
  2698. struct sock *sk = sock->sk;
  2699. int addr_len = 0;
  2700. int err;
  2701. err = sk->sk_prot->recvmsg(sk, msg, size, flags & MSG_DONTWAIT,
  2702. flags & ~MSG_DONTWAIT, &addr_len);
  2703. if (err >= 0)
  2704. msg->msg_namelen = addr_len;
  2705. return err;
  2706. }
  2707. EXPORT_SYMBOL(sock_common_recvmsg);
  2708. /*
  2709. * Set socket options on an inet socket.
  2710. */
  2711. int sock_common_setsockopt(struct socket *sock, int level, int optname,
  2712. char __user *optval, unsigned int optlen)
  2713. {
  2714. struct sock *sk = sock->sk;
  2715. return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen);
  2716. }
  2717. EXPORT_SYMBOL(sock_common_setsockopt);
  2718. #ifdef CONFIG_COMPAT
  2719. int compat_sock_common_setsockopt(struct socket *sock, int level, int optname,
  2720. char __user *optval, unsigned int optlen)
  2721. {
  2722. struct sock *sk = sock->sk;
  2723. if (sk->sk_prot->compat_setsockopt != NULL)
  2724. return sk->sk_prot->compat_setsockopt(sk, level, optname,
  2725. optval, optlen);
  2726. return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen);
  2727. }
  2728. EXPORT_SYMBOL(compat_sock_common_setsockopt);
  2729. #endif
  2730. void sk_common_release(struct sock *sk)
  2731. {
  2732. if (sk->sk_prot->destroy)
  2733. sk->sk_prot->destroy(sk);
  2734. /*
  2735. * Observation: when sock_common_release is called, processes have
  2736. * no access to socket. But net still has.
  2737. * Step one, detach it from networking:
  2738. *
  2739. * A. Remove from hash tables.
  2740. */
  2741. sk->sk_prot->unhash(sk);
  2742. /*
  2743. * In this point socket cannot receive new packets, but it is possible
  2744. * that some packets are in flight because some CPU runs receiver and
  2745. * did hash table lookup before we unhashed socket. They will achieve
  2746. * receive queue and will be purged by socket destructor.
  2747. *
  2748. * Also we still have packets pending on receive queue and probably,
  2749. * our own packets waiting in device queues. sock_destroy will drain
  2750. * receive queue, but transmitted packets will delay socket destruction
  2751. * until the last reference will be released.
  2752. */
  2753. sock_orphan(sk);
  2754. xfrm_sk_free_policy(sk);
  2755. sk_refcnt_debug_release(sk);
  2756. sock_put(sk);
  2757. }
  2758. EXPORT_SYMBOL(sk_common_release);
  2759. void sk_get_meminfo(const struct sock *sk, u32 *mem)
  2760. {
  2761. memset(mem, 0, sizeof(*mem) * SK_MEMINFO_VARS);
  2762. mem[SK_MEMINFO_RMEM_ALLOC] = sk_rmem_alloc_get(sk);
  2763. mem[SK_MEMINFO_RCVBUF] = READ_ONCE(sk->sk_rcvbuf);
  2764. mem[SK_MEMINFO_WMEM_ALLOC] = sk_wmem_alloc_get(sk);
  2765. mem[SK_MEMINFO_SNDBUF] = READ_ONCE(sk->sk_sndbuf);
  2766. mem[SK_MEMINFO_FWD_ALLOC] = sk->sk_forward_alloc;
  2767. mem[SK_MEMINFO_WMEM_QUEUED] = READ_ONCE(sk->sk_wmem_queued);
  2768. mem[SK_MEMINFO_OPTMEM] = atomic_read(&sk->sk_omem_alloc);
  2769. mem[SK_MEMINFO_BACKLOG] = READ_ONCE(sk->sk_backlog.len);
  2770. mem[SK_MEMINFO_DROPS] = atomic_read(&sk->sk_drops);
  2771. }
  2772. #ifdef CONFIG_PROC_FS
  2773. #define PROTO_INUSE_NR 64 /* should be enough for the first time */
  2774. struct prot_inuse {
  2775. int val[PROTO_INUSE_NR];
  2776. };
  2777. static DECLARE_BITMAP(proto_inuse_idx, PROTO_INUSE_NR);
  2778. void sock_prot_inuse_add(struct net *net, struct proto *prot, int val)
  2779. {
  2780. __this_cpu_add(net->core.prot_inuse->val[prot->inuse_idx], val);
  2781. }
  2782. EXPORT_SYMBOL_GPL(sock_prot_inuse_add);
  2783. int sock_prot_inuse_get(struct net *net, struct proto *prot)
  2784. {
  2785. int cpu, idx = prot->inuse_idx;
  2786. int res = 0;
  2787. for_each_possible_cpu(cpu)
  2788. res += per_cpu_ptr(net->core.prot_inuse, cpu)->val[idx];
  2789. return res >= 0 ? res : 0;
  2790. }
  2791. EXPORT_SYMBOL_GPL(sock_prot_inuse_get);
  2792. static void sock_inuse_add(struct net *net, int val)
  2793. {
  2794. this_cpu_add(*net->core.sock_inuse, val);
  2795. }
  2796. int sock_inuse_get(struct net *net)
  2797. {
  2798. int cpu, res = 0;
  2799. for_each_possible_cpu(cpu)
  2800. res += *per_cpu_ptr(net->core.sock_inuse, cpu);
  2801. return res;
  2802. }
  2803. EXPORT_SYMBOL_GPL(sock_inuse_get);
  2804. static int __net_init sock_inuse_init_net(struct net *net)
  2805. {
  2806. net->core.prot_inuse = alloc_percpu(struct prot_inuse);
  2807. if (net->core.prot_inuse == NULL)
  2808. return -ENOMEM;
  2809. net->core.sock_inuse = alloc_percpu(int);
  2810. if (net->core.sock_inuse == NULL)
  2811. goto out;
  2812. return 0;
  2813. out:
  2814. free_percpu(net->core.prot_inuse);
  2815. return -ENOMEM;
  2816. }
  2817. static void __net_exit sock_inuse_exit_net(struct net *net)
  2818. {
  2819. free_percpu(net->core.prot_inuse);
  2820. free_percpu(net->core.sock_inuse);
  2821. }
  2822. static struct pernet_operations net_inuse_ops = {
  2823. .init = sock_inuse_init_net,
  2824. .exit = sock_inuse_exit_net,
  2825. };
  2826. static __init int net_inuse_init(void)
  2827. {
  2828. if (register_pernet_subsys(&net_inuse_ops))
  2829. panic("Cannot initialize net inuse counters");
  2830. return 0;
  2831. }
  2832. core_initcall(net_inuse_init);
  2833. static int assign_proto_idx(struct proto *prot)
  2834. {
  2835. prot->inuse_idx = find_first_zero_bit(proto_inuse_idx, PROTO_INUSE_NR);
  2836. if (unlikely(prot->inuse_idx == PROTO_INUSE_NR - 1)) {
  2837. pr_err("PROTO_INUSE_NR exhausted\n");
  2838. return -ENOSPC;
  2839. }
  2840. set_bit(prot->inuse_idx, proto_inuse_idx);
  2841. return 0;
  2842. }
  2843. static void release_proto_idx(struct proto *prot)
  2844. {
  2845. if (prot->inuse_idx != PROTO_INUSE_NR - 1)
  2846. clear_bit(prot->inuse_idx, proto_inuse_idx);
  2847. }
  2848. #else
  2849. static inline int assign_proto_idx(struct proto *prot)
  2850. {
  2851. return 0;
  2852. }
  2853. static inline void release_proto_idx(struct proto *prot)
  2854. {
  2855. }
  2856. static void sock_inuse_add(struct net *net, int val)
  2857. {
  2858. }
  2859. #endif
  2860. static void req_prot_cleanup(struct request_sock_ops *rsk_prot)
  2861. {
  2862. if (!rsk_prot)
  2863. return;
  2864. kfree(rsk_prot->slab_name);
  2865. rsk_prot->slab_name = NULL;
  2866. kmem_cache_destroy(rsk_prot->slab);
  2867. rsk_prot->slab = NULL;
  2868. }
  2869. static int req_prot_init(const struct proto *prot)
  2870. {
  2871. struct request_sock_ops *rsk_prot = prot->rsk_prot;
  2872. if (!rsk_prot)
  2873. return 0;
  2874. rsk_prot->slab_name = kasprintf(GFP_KERNEL, "request_sock_%s",
  2875. prot->name);
  2876. if (!rsk_prot->slab_name)
  2877. return -ENOMEM;
  2878. rsk_prot->slab = kmem_cache_create(rsk_prot->slab_name,
  2879. rsk_prot->obj_size, 0,
  2880. SLAB_ACCOUNT | prot->slab_flags,
  2881. NULL);
  2882. if (!rsk_prot->slab) {
  2883. pr_crit("%s: Can't create request sock SLAB cache!\n",
  2884. prot->name);
  2885. return -ENOMEM;
  2886. }
  2887. return 0;
  2888. }
  2889. int proto_register(struct proto *prot, int alloc_slab)
  2890. {
  2891. int ret = -ENOBUFS;
  2892. if (alloc_slab) {
  2893. prot->slab = kmem_cache_create_usercopy(prot->name,
  2894. prot->obj_size, 0,
  2895. SLAB_HWCACHE_ALIGN | SLAB_ACCOUNT |
  2896. prot->slab_flags,
  2897. prot->useroffset, prot->usersize,
  2898. NULL);
  2899. if (prot->slab == NULL) {
  2900. pr_crit("%s: Can't create sock SLAB cache!\n",
  2901. prot->name);
  2902. goto out;
  2903. }
  2904. if (req_prot_init(prot))
  2905. goto out_free_request_sock_slab;
  2906. if (prot->twsk_prot != NULL) {
  2907. prot->twsk_prot->twsk_slab_name = kasprintf(GFP_KERNEL, "tw_sock_%s", prot->name);
  2908. if (prot->twsk_prot->twsk_slab_name == NULL)
  2909. goto out_free_request_sock_slab;
  2910. prot->twsk_prot->twsk_slab =
  2911. kmem_cache_create(prot->twsk_prot->twsk_slab_name,
  2912. prot->twsk_prot->twsk_obj_size,
  2913. 0,
  2914. SLAB_ACCOUNT |
  2915. prot->slab_flags,
  2916. NULL);
  2917. if (prot->twsk_prot->twsk_slab == NULL)
  2918. goto out_free_timewait_sock_slab_name;
  2919. }
  2920. }
  2921. mutex_lock(&proto_list_mutex);
  2922. ret = assign_proto_idx(prot);
  2923. if (ret) {
  2924. mutex_unlock(&proto_list_mutex);
  2925. goto out_free_timewait_sock_slab_name;
  2926. }
  2927. list_add(&prot->node, &proto_list);
  2928. mutex_unlock(&proto_list_mutex);
  2929. return ret;
  2930. out_free_timewait_sock_slab_name:
  2931. if (alloc_slab && prot->twsk_prot)
  2932. kfree(prot->twsk_prot->twsk_slab_name);
  2933. out_free_request_sock_slab:
  2934. if (alloc_slab) {
  2935. req_prot_cleanup(prot->rsk_prot);
  2936. kmem_cache_destroy(prot->slab);
  2937. prot->slab = NULL;
  2938. }
  2939. out:
  2940. return ret;
  2941. }
  2942. EXPORT_SYMBOL(proto_register);
  2943. void proto_unregister(struct proto *prot)
  2944. {
  2945. mutex_lock(&proto_list_mutex);
  2946. release_proto_idx(prot);
  2947. list_del(&prot->node);
  2948. mutex_unlock(&proto_list_mutex);
  2949. kmem_cache_destroy(prot->slab);
  2950. prot->slab = NULL;
  2951. req_prot_cleanup(prot->rsk_prot);
  2952. if (prot->twsk_prot != NULL && prot->twsk_prot->twsk_slab != NULL) {
  2953. kmem_cache_destroy(prot->twsk_prot->twsk_slab);
  2954. kfree(prot->twsk_prot->twsk_slab_name);
  2955. prot->twsk_prot->twsk_slab = NULL;
  2956. }
  2957. }
  2958. EXPORT_SYMBOL(proto_unregister);
  2959. int sock_load_diag_module(int family, int protocol)
  2960. {
  2961. if (!protocol) {
  2962. if (!sock_is_registered(family))
  2963. return -ENOENT;
  2964. return request_module("net-pf-%d-proto-%d-type-%d", PF_NETLINK,
  2965. NETLINK_SOCK_DIAG, family);
  2966. }
  2967. #ifdef CONFIG_INET
  2968. if (family == AF_INET &&
  2969. protocol != IPPROTO_RAW &&
  2970. !rcu_access_pointer(inet_protos[protocol]))
  2971. return -ENOENT;
  2972. #endif
  2973. return request_module("net-pf-%d-proto-%d-type-%d-%d", PF_NETLINK,
  2974. NETLINK_SOCK_DIAG, family, protocol);
  2975. }
  2976. EXPORT_SYMBOL(sock_load_diag_module);
  2977. #ifdef CONFIG_PROC_FS
  2978. static void *proto_seq_start(struct seq_file *seq, loff_t *pos)
  2979. __acquires(proto_list_mutex)
  2980. {
  2981. mutex_lock(&proto_list_mutex);
  2982. return seq_list_start_head(&proto_list, *pos);
  2983. }
  2984. static void *proto_seq_next(struct seq_file *seq, void *v, loff_t *pos)
  2985. {
  2986. return seq_list_next(v, &proto_list, pos);
  2987. }
  2988. static void proto_seq_stop(struct seq_file *seq, void *v)
  2989. __releases(proto_list_mutex)
  2990. {
  2991. mutex_unlock(&proto_list_mutex);
  2992. }
  2993. static char proto_method_implemented(const void *method)
  2994. {
  2995. return method == NULL ? 'n' : 'y';
  2996. }
  2997. static long sock_prot_memory_allocated(struct proto *proto)
  2998. {
  2999. return proto->memory_allocated != NULL ? proto_memory_allocated(proto) : -1L;
  3000. }
  3001. static const char *sock_prot_memory_pressure(struct proto *proto)
  3002. {
  3003. return proto->memory_pressure != NULL ?
  3004. proto_memory_pressure(proto) ? "yes" : "no" : "NI";
  3005. }
  3006. static void proto_seq_printf(struct seq_file *seq, struct proto *proto)
  3007. {
  3008. seq_printf(seq, "%-9s %4u %6d %6ld %-3s %6u %-3s %-10s "
  3009. "%2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c\n",
  3010. proto->name,
  3011. proto->obj_size,
  3012. sock_prot_inuse_get(seq_file_net(seq), proto),
  3013. sock_prot_memory_allocated(proto),
  3014. sock_prot_memory_pressure(proto),
  3015. proto->max_header,
  3016. proto->slab == NULL ? "no" : "yes",
  3017. module_name(proto->owner),
  3018. proto_method_implemented(proto->close),
  3019. proto_method_implemented(proto->connect),
  3020. proto_method_implemented(proto->disconnect),
  3021. proto_method_implemented(proto->accept),
  3022. proto_method_implemented(proto->ioctl),
  3023. proto_method_implemented(proto->init),
  3024. proto_method_implemented(proto->destroy),
  3025. proto_method_implemented(proto->shutdown),
  3026. proto_method_implemented(proto->setsockopt),
  3027. proto_method_implemented(proto->getsockopt),
  3028. proto_method_implemented(proto->sendmsg),
  3029. proto_method_implemented(proto->recvmsg),
  3030. proto_method_implemented(proto->sendpage),
  3031. proto_method_implemented(proto->bind),
  3032. proto_method_implemented(proto->backlog_rcv),
  3033. proto_method_implemented(proto->hash),
  3034. proto_method_implemented(proto->unhash),
  3035. proto_method_implemented(proto->get_port),
  3036. proto_method_implemented(proto->enter_memory_pressure));
  3037. }
  3038. static int proto_seq_show(struct seq_file *seq, void *v)
  3039. {
  3040. if (v == &proto_list)
  3041. seq_printf(seq, "%-9s %-4s %-8s %-6s %-5s %-7s %-4s %-10s %s",
  3042. "protocol",
  3043. "size",
  3044. "sockets",
  3045. "memory",
  3046. "press",
  3047. "maxhdr",
  3048. "slab",
  3049. "module",
  3050. "cl co di ac io in de sh ss gs se re sp bi br ha uh gp em\n");
  3051. else
  3052. proto_seq_printf(seq, list_entry(v, struct proto, node));
  3053. return 0;
  3054. }
  3055. static const struct seq_operations proto_seq_ops = {
  3056. .start = proto_seq_start,
  3057. .next = proto_seq_next,
  3058. .stop = proto_seq_stop,
  3059. .show = proto_seq_show,
  3060. };
  3061. static __net_init int proto_init_net(struct net *net)
  3062. {
  3063. if (!proc_create_net("protocols", 0444, net->proc_net, &proto_seq_ops,
  3064. sizeof(struct seq_net_private)))
  3065. return -ENOMEM;
  3066. return 0;
  3067. }
  3068. static __net_exit void proto_exit_net(struct net *net)
  3069. {
  3070. remove_proc_entry("protocols", net->proc_net);
  3071. }
  3072. static __net_initdata struct pernet_operations proto_net_ops = {
  3073. .init = proto_init_net,
  3074. .exit = proto_exit_net,
  3075. };
  3076. static int __init proto_init(void)
  3077. {
  3078. return register_pernet_subsys(&proto_net_ops);
  3079. }
  3080. subsys_initcall(proto_init);
  3081. #endif /* PROC_FS */
  3082. #ifdef CONFIG_NET_RX_BUSY_POLL
  3083. bool sk_busy_loop_end(void *p, unsigned long start_time)
  3084. {
  3085. struct sock *sk = p;
  3086. return !skb_queue_empty_lockless(&sk->sk_receive_queue) ||
  3087. sk_busy_loop_timeout(sk, start_time);
  3088. }
  3089. EXPORT_SYMBOL(sk_busy_loop_end);
  3090. #endif /* CONFIG_NET_RX_BUSY_POLL */