OSDN Git Service

ANDROID: netfilter: xt_qtaguid: add qtaguid matching module
[android-x86/kernel.git] / net / ipv4 / af_inet.c
1 /*
2  * INET         An implementation of the TCP/IP protocol suite for the LINUX
3  *              operating system.  INET is implemented using the  BSD Socket
4  *              interface as the means of communication with the user level.
5  *
6  *              PF_INET protocol family socket handler.
7  *
8  * Authors:     Ross Biro
9  *              Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
10  *              Florian La Roche, <flla@stud.uni-sb.de>
11  *              Alan Cox, <A.Cox@swansea.ac.uk>
12  *
13  * Changes (see also sock.c)
14  *
15  *              piggy,
16  *              Karl Knutson    :       Socket protocol table
17  *              A.N.Kuznetsov   :       Socket death error in accept().
18  *              John Richardson :       Fix non blocking error in connect()
19  *                                      so sockets that fail to connect
20  *                                      don't return -EINPROGRESS.
21  *              Alan Cox        :       Asynchronous I/O support
22  *              Alan Cox        :       Keep correct socket pointer on sock
23  *                                      structures
24  *                                      when accept() ed
25  *              Alan Cox        :       Semantics of SO_LINGER aren't state
26  *                                      moved to close when you look carefully.
27  *                                      With this fixed and the accept bug fixed
28  *                                      some RPC stuff seems happier.
29  *              Niibe Yutaka    :       4.4BSD style write async I/O
30  *              Alan Cox,
31  *              Tony Gale       :       Fixed reuse semantics.
32  *              Alan Cox        :       bind() shouldn't abort existing but dead
33  *                                      sockets. Stops FTP netin:.. I hope.
34  *              Alan Cox        :       bind() works correctly for RAW sockets.
35  *                                      Note that FreeBSD at least was broken
36  *                                      in this respect so be careful with
37  *                                      compatibility tests...
38  *              Alan Cox        :       routing cache support
39  *              Alan Cox        :       memzero the socket structure for
40  *                                      compactness.
41  *              Matt Day        :       nonblock connect error handler
42  *              Alan Cox        :       Allow large numbers of pending sockets
43  *                                      (eg for big web sites), but only if
44  *                                      specifically application requested.
45  *              Alan Cox        :       New buffering throughout IP. Used
46  *                                      dumbly.
47  *              Alan Cox        :       New buffering now used smartly.
48  *              Alan Cox        :       BSD rather than common sense
49  *                                      interpretation of listen.
50  *              Germano Caronni :       Assorted small races.
51  *              Alan Cox        :       sendmsg/recvmsg basic support.
52  *              Alan Cox        :       Only sendmsg/recvmsg now supported.
53  *              Alan Cox        :       Locked down bind (see security list).
54  *              Alan Cox        :       Loosened bind a little.
55  *              Mike McLagan    :       ADD/DEL DLCI Ioctls
56  *      Willy Konynenberg       :       Transparent proxying support.
57  *              David S. Miller :       New socket lookup architecture.
58  *                                      Some other random speedups.
59  *              Cyrus Durgin    :       Cleaned up file for kmod hacks.
60  *              Andi Kleen      :       Fix inet_stream_connect TCP race.
61  *
62  *              This program is free software; you can redistribute it and/or
63  *              modify it under the terms of the GNU General Public License
64  *              as published by the Free Software Foundation; either version
65  *              2 of the License, or (at your option) any later version.
66  */
67
68 #define pr_fmt(fmt) "IPv4: " fmt
69
70 #include <linux/err.h>
71 #include <linux/errno.h>
72 #include <linux/types.h>
73 #include <linux/socket.h>
74 #include <linux/in.h>
75 #include <linux/kernel.h>
76 #include <linux/kmod.h>
77 #include <linux/sched.h>
78 #include <linux/timer.h>
79 #include <linux/string.h>
80 #include <linux/sockios.h>
81 #include <linux/net.h>
82 #include <linux/capability.h>
83 #include <linux/fcntl.h>
84 #include <linux/mm.h>
85 #include <linux/interrupt.h>
86 #include <linux/stat.h>
87 #include <linux/init.h>
88 #include <linux/poll.h>
89 #include <linux/netfilter_ipv4.h>
90 #include <linux/random.h>
91 #include <linux/slab.h>
92 #include <linux/netfilter/xt_qtaguid.h>
93
94 #include <linux/uaccess.h>
95
96 #include <linux/inet.h>
97 #include <linux/igmp.h>
98 #include <linux/inetdevice.h>
99 #include <linux/netdevice.h>
100 #include <net/checksum.h>
101 #include <net/ip.h>
102 #include <net/protocol.h>
103 #include <net/arp.h>
104 #include <net/route.h>
105 #include <net/ip_fib.h>
106 #include <net/inet_connection_sock.h>
107 #include <net/tcp.h>
108 #include <net/udp.h>
109 #include <net/udplite.h>
110 #include <net/ping.h>
111 #include <linux/skbuff.h>
112 #include <net/sock.h>
113 #include <net/raw.h>
114 #include <net/icmp.h>
115 #include <net/inet_common.h>
116 #include <net/ip_tunnels.h>
117 #include <net/xfrm.h>
118 #include <net/net_namespace.h>
119 #include <net/secure_seq.h>
120 #ifdef CONFIG_IP_MROUTE
121 #include <linux/mroute.h>
122 #endif
123 #include <net/l3mdev.h>
124
125 #include <trace/events/sock.h>
126
127 #ifdef CONFIG_ANDROID_PARANOID_NETWORK
128 #include <linux/android_aid.h>
129
130 static inline int current_has_network(void)
131 {
132         return in_egroup_p(AID_INET) || capable(CAP_NET_RAW);
133 }
134 #else
135 static inline int current_has_network(void)
136 {
137         return 1;
138 }
139 #endif
140
141 /* The inetsw table contains everything that inet_create needs to
142  * build a new socket.
143  */
144 static struct list_head inetsw[SOCK_MAX];
145 static DEFINE_SPINLOCK(inetsw_lock);
146
147 /* New destruction routine */
148
149 void inet_sock_destruct(struct sock *sk)
150 {
151         struct inet_sock *inet = inet_sk(sk);
152
153         __skb_queue_purge(&sk->sk_receive_queue);
154         __skb_queue_purge(&sk->sk_error_queue);
155
156         sk_mem_reclaim(sk);
157
158         if (sk->sk_type == SOCK_STREAM && sk->sk_state != TCP_CLOSE) {
159                 pr_err("Attempt to release TCP socket in state %d %p\n",
160                        sk->sk_state, sk);
161                 return;
162         }
163         if (!sock_flag(sk, SOCK_DEAD)) {
164                 pr_err("Attempt to release alive inet socket %p\n", sk);
165                 return;
166         }
167
168         WARN_ON(atomic_read(&sk->sk_rmem_alloc));
169         WARN_ON(refcount_read(&sk->sk_wmem_alloc));
170         WARN_ON(sk->sk_wmem_queued);
171         WARN_ON(sk->sk_forward_alloc);
172
173         kfree(rcu_dereference_protected(inet->inet_opt, 1));
174         dst_release(rcu_dereference_check(sk->sk_dst_cache, 1));
175         dst_release(sk->sk_rx_dst);
176         sk_refcnt_debug_dec(sk);
177 }
178 EXPORT_SYMBOL(inet_sock_destruct);
179
180 /*
181  *      The routines beyond this point handle the behaviour of an AF_INET
182  *      socket object. Mostly it punts to the subprotocols of IP to do
183  *      the work.
184  */
185
186 /*
187  *      Automatically bind an unbound socket.
188  */
189
190 static int inet_autobind(struct sock *sk)
191 {
192         struct inet_sock *inet;
193         /* We may need to bind the socket. */
194         lock_sock(sk);
195         inet = inet_sk(sk);
196         if (!inet->inet_num) {
197                 if (sk->sk_prot->get_port(sk, 0)) {
198                         release_sock(sk);
199                         return -EAGAIN;
200                 }
201                 inet->inet_sport = htons(inet->inet_num);
202         }
203         release_sock(sk);
204         return 0;
205 }
206
207 /*
208  *      Move a socket into listening state.
209  */
210 int inet_listen(struct socket *sock, int backlog)
211 {
212         struct sock *sk = sock->sk;
213         unsigned char old_state;
214         int err, tcp_fastopen;
215
216         lock_sock(sk);
217
218         err = -EINVAL;
219         if (sock->state != SS_UNCONNECTED || sock->type != SOCK_STREAM)
220                 goto out;
221
222         old_state = sk->sk_state;
223         if (!((1 << old_state) & (TCPF_CLOSE | TCPF_LISTEN)))
224                 goto out;
225
226         /* Really, if the socket is already in listen state
227          * we can only allow the backlog to be adjusted.
228          */
229         if (old_state != TCP_LISTEN) {
230                 /* Enable TFO w/o requiring TCP_FASTOPEN socket option.
231                  * Note that only TCP sockets (SOCK_STREAM) will reach here.
232                  * Also fastopen backlog may already been set via the option
233                  * because the socket was in TCP_LISTEN state previously but
234                  * was shutdown() rather than close().
235                  */
236                 tcp_fastopen = sock_net(sk)->ipv4.sysctl_tcp_fastopen;
237                 if ((tcp_fastopen & TFO_SERVER_WO_SOCKOPT1) &&
238                     (tcp_fastopen & TFO_SERVER_ENABLE) &&
239                     !inet_csk(sk)->icsk_accept_queue.fastopenq.max_qlen) {
240                         fastopen_queue_tune(sk, backlog);
241                         tcp_fastopen_init_key_once(sock_net(sk));
242                 }
243
244                 err = inet_csk_listen_start(sk, backlog);
245                 if (err)
246                         goto out;
247                 tcp_call_bpf(sk, BPF_SOCK_OPS_TCP_LISTEN_CB, 0, NULL);
248         }
249         sk->sk_max_ack_backlog = backlog;
250         err = 0;
251
252 out:
253         release_sock(sk);
254         return err;
255 }
256 EXPORT_SYMBOL(inet_listen);
257
258 /*
259  *      Create an inet socket.
260  */
261
262 static int inet_create(struct net *net, struct socket *sock, int protocol,
263                        int kern)
264 {
265         struct sock *sk;
266         struct inet_protosw *answer;
267         struct inet_sock *inet;
268         struct proto *answer_prot;
269         unsigned char answer_flags;
270         int try_loading_module = 0;
271         int err;
272
273         if (protocol < 0 || protocol >= IPPROTO_MAX)
274                 return -EINVAL;
275
276         if (!current_has_network())
277                 return -EACCES;
278
279         sock->state = SS_UNCONNECTED;
280
281         /* Look for the requested type/protocol pair. */
282 lookup_protocol:
283         err = -ESOCKTNOSUPPORT;
284         rcu_read_lock();
285         list_for_each_entry_rcu(answer, &inetsw[sock->type], list) {
286
287                 err = 0;
288                 /* Check the non-wild match. */
289                 if (protocol == answer->protocol) {
290                         if (protocol != IPPROTO_IP)
291                                 break;
292                 } else {
293                         /* Check for the two wild cases. */
294                         if (IPPROTO_IP == protocol) {
295                                 protocol = answer->protocol;
296                                 break;
297                         }
298                         if (IPPROTO_IP == answer->protocol)
299                                 break;
300                 }
301                 err = -EPROTONOSUPPORT;
302         }
303
304         if (unlikely(err)) {
305                 if (try_loading_module < 2) {
306                         rcu_read_unlock();
307                         /*
308                          * Be more specific, e.g. net-pf-2-proto-132-type-1
309                          * (net-pf-PF_INET-proto-IPPROTO_SCTP-type-SOCK_STREAM)
310                          */
311                         if (++try_loading_module == 1)
312                                 request_module("net-pf-%d-proto-%d-type-%d",
313                                                PF_INET, protocol, sock->type);
314                         /*
315                          * Fall back to generic, e.g. net-pf-2-proto-132
316                          * (net-pf-PF_INET-proto-IPPROTO_SCTP)
317                          */
318                         else
319                                 request_module("net-pf-%d-proto-%d",
320                                                PF_INET, protocol);
321                         goto lookup_protocol;
322                 } else
323                         goto out_rcu_unlock;
324         }
325
326         err = -EPERM;
327         if (sock->type == SOCK_RAW && !kern && !capable(CAP_NET_RAW))
328                 goto out_rcu_unlock;
329
330         sock->ops = answer->ops;
331         answer_prot = answer->prot;
332         answer_flags = answer->flags;
333         rcu_read_unlock();
334
335         WARN_ON(!answer_prot->slab);
336
337         err = -ENOBUFS;
338         sk = sk_alloc(net, PF_INET, GFP_KERNEL, answer_prot, kern);
339         if (!sk)
340                 goto out;
341
342         err = 0;
343         if (INET_PROTOSW_REUSE & answer_flags)
344                 sk->sk_reuse = SK_CAN_REUSE;
345
346         inet = inet_sk(sk);
347         inet->is_icsk = (INET_PROTOSW_ICSK & answer_flags) != 0;
348
349         inet->nodefrag = 0;
350
351         if (SOCK_RAW == sock->type) {
352                 inet->inet_num = protocol;
353                 if (IPPROTO_RAW == protocol)
354                         inet->hdrincl = 1;
355         }
356
357         if (net->ipv4.sysctl_ip_no_pmtu_disc)
358                 inet->pmtudisc = IP_PMTUDISC_DONT;
359         else
360                 inet->pmtudisc = IP_PMTUDISC_WANT;
361
362         inet->inet_id = 0;
363
364         sock_init_data(sock, sk);
365
366         sk->sk_destruct    = inet_sock_destruct;
367         sk->sk_protocol    = protocol;
368         sk->sk_backlog_rcv = sk->sk_prot->backlog_rcv;
369
370         inet->uc_ttl    = -1;
371         inet->mc_loop   = 1;
372         inet->mc_ttl    = 1;
373         inet->mc_all    = 1;
374         inet->mc_index  = 0;
375         inet->mc_list   = NULL;
376         inet->rcv_tos   = 0;
377
378         sk_refcnt_debug_inc(sk);
379
380         if (inet->inet_num) {
381                 /* It assumes that any protocol which allows
382                  * the user to assign a number at socket
383                  * creation time automatically
384                  * shares.
385                  */
386                 inet->inet_sport = htons(inet->inet_num);
387                 /* Add to protocol hash chains. */
388                 err = sk->sk_prot->hash(sk);
389                 if (err) {
390                         sk_common_release(sk);
391                         goto out;
392                 }
393         }
394
395         if (sk->sk_prot->init) {
396                 err = sk->sk_prot->init(sk);
397                 if (err) {
398                         sk_common_release(sk);
399                         goto out;
400                 }
401         }
402
403         if (!kern) {
404                 err = BPF_CGROUP_RUN_PROG_INET_SOCK(sk);
405                 if (err) {
406                         sk_common_release(sk);
407                         goto out;
408                 }
409         }
410 out:
411         return err;
412 out_rcu_unlock:
413         rcu_read_unlock();
414         goto out;
415 }
416
417
418 /*
419  *      The peer socket should always be NULL (or else). When we call this
420  *      function we are destroying the object and from then on nobody
421  *      should refer to it.
422  */
423 int inet_release(struct socket *sock)
424 {
425         struct sock *sk = sock->sk;
426
427         if (sk) {
428                 long timeout;
429
430 #ifdef CONFIG_NETFILTER_XT_MATCH_QTAGUID
431                 qtaguid_untag(sock, true);
432 #endif
433                 /* Applications forget to leave groups before exiting */
434                 ip_mc_drop_socket(sk);
435
436                 /* If linger is set, we don't return until the close
437                  * is complete.  Otherwise we return immediately. The
438                  * actually closing is done the same either way.
439                  *
440                  * If the close is due to the process exiting, we never
441                  * linger..
442                  */
443                 timeout = 0;
444                 if (sock_flag(sk, SOCK_LINGER) &&
445                     !(current->flags & PF_EXITING))
446                         timeout = sk->sk_lingertime;
447                 sock->sk = NULL;
448                 sk->sk_prot->close(sk, timeout);
449         }
450         return 0;
451 }
452 EXPORT_SYMBOL(inet_release);
453
454 int inet_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
455 {
456         struct sock *sk = sock->sk;
457         int err;
458
459         /* If the socket has its own bind function then use it. (RAW) */
460         if (sk->sk_prot->bind) {
461                 return sk->sk_prot->bind(sk, uaddr, addr_len);
462         }
463         if (addr_len < sizeof(struct sockaddr_in))
464                 return -EINVAL;
465
466         /* BPF prog is run before any checks are done so that if the prog
467          * changes context in a wrong way it will be caught.
468          */
469         err = BPF_CGROUP_RUN_PROG_INET4_BIND(sk, uaddr);
470         if (err)
471                 return err;
472
473         return __inet_bind(sk, uaddr, addr_len, false, true);
474 }
475 EXPORT_SYMBOL(inet_bind);
476
477 int __inet_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len,
478                 bool force_bind_address_no_port, bool with_lock)
479 {
480         struct sockaddr_in *addr = (struct sockaddr_in *)uaddr;
481         struct inet_sock *inet = inet_sk(sk);
482         struct net *net = sock_net(sk);
483         unsigned short snum;
484         int chk_addr_ret;
485         u32 tb_id = RT_TABLE_LOCAL;
486         int err;
487
488         if (addr->sin_family != AF_INET) {
489                 /* Compatibility games : accept AF_UNSPEC (mapped to AF_INET)
490                  * only if s_addr is INADDR_ANY.
491                  */
492                 err = -EAFNOSUPPORT;
493                 if (addr->sin_family != AF_UNSPEC ||
494                     addr->sin_addr.s_addr != htonl(INADDR_ANY))
495                         goto out;
496         }
497
498         tb_id = l3mdev_fib_table_by_index(net, sk->sk_bound_dev_if) ? : tb_id;
499         chk_addr_ret = inet_addr_type_table(net, addr->sin_addr.s_addr, tb_id);
500
501         /* Not specified by any standard per-se, however it breaks too
502          * many applications when removed.  It is unfortunate since
503          * allowing applications to make a non-local bind solves
504          * several problems with systems using dynamic addressing.
505          * (ie. your servers still start up even if your ISDN link
506          *  is temporarily down)
507          */
508         err = -EADDRNOTAVAIL;
509         if (!inet_can_nonlocal_bind(net, inet) &&
510             addr->sin_addr.s_addr != htonl(INADDR_ANY) &&
511             chk_addr_ret != RTN_LOCAL &&
512             chk_addr_ret != RTN_MULTICAST &&
513             chk_addr_ret != RTN_BROADCAST)
514                 goto out;
515
516         snum = ntohs(addr->sin_port);
517         err = -EACCES;
518         if (snum && snum < inet_prot_sock(net) &&
519             !ns_capable(net->user_ns, CAP_NET_BIND_SERVICE))
520                 goto out;
521
522         /*      We keep a pair of addresses. rcv_saddr is the one
523          *      used by hash lookups, and saddr is used for transmit.
524          *
525          *      In the BSD API these are the same except where it
526          *      would be illegal to use them (multicast/broadcast) in
527          *      which case the sending device address is used.
528          */
529         if (with_lock)
530                 lock_sock(sk);
531
532         /* Check these errors (active socket, double bind). */
533         err = -EINVAL;
534         if (sk->sk_state != TCP_CLOSE || inet->inet_num)
535                 goto out_release_sock;
536
537         inet->inet_rcv_saddr = inet->inet_saddr = addr->sin_addr.s_addr;
538         if (chk_addr_ret == RTN_MULTICAST || chk_addr_ret == RTN_BROADCAST)
539                 inet->inet_saddr = 0;  /* Use device */
540
541         /* Make sure we are allowed to bind here. */
542         if (snum || !(inet->bind_address_no_port ||
543                       force_bind_address_no_port)) {
544                 if (sk->sk_prot->get_port(sk, snum)) {
545                         inet->inet_saddr = inet->inet_rcv_saddr = 0;
546                         err = -EADDRINUSE;
547                         goto out_release_sock;
548                 }
549                 err = BPF_CGROUP_RUN_PROG_INET4_POST_BIND(sk);
550                 if (err) {
551                         inet->inet_saddr = inet->inet_rcv_saddr = 0;
552                         goto out_release_sock;
553                 }
554         }
555
556         if (inet->inet_rcv_saddr)
557                 sk->sk_userlocks |= SOCK_BINDADDR_LOCK;
558         if (snum)
559                 sk->sk_userlocks |= SOCK_BINDPORT_LOCK;
560         inet->inet_sport = htons(inet->inet_num);
561         inet->inet_daddr = 0;
562         inet->inet_dport = 0;
563         sk_dst_reset(sk);
564         err = 0;
565 out_release_sock:
566         if (with_lock)
567                 release_sock(sk);
568 out:
569         return err;
570 }
571
572 int inet_dgram_connect(struct socket *sock, struct sockaddr *uaddr,
573                        int addr_len, int flags)
574 {
575         struct sock *sk = sock->sk;
576         int err;
577
578         if (addr_len < sizeof(uaddr->sa_family))
579                 return -EINVAL;
580         if (uaddr->sa_family == AF_UNSPEC)
581                 return sk->sk_prot->disconnect(sk, flags);
582
583         if (BPF_CGROUP_PRE_CONNECT_ENABLED(sk)) {
584                 err = sk->sk_prot->pre_connect(sk, uaddr, addr_len);
585                 if (err)
586                         return err;
587         }
588
589         if (!inet_sk(sk)->inet_num && inet_autobind(sk))
590                 return -EAGAIN;
591         return sk->sk_prot->connect(sk, uaddr, addr_len);
592 }
593 EXPORT_SYMBOL(inet_dgram_connect);
594
595 static long inet_wait_for_connect(struct sock *sk, long timeo, int writebias)
596 {
597         DEFINE_WAIT_FUNC(wait, woken_wake_function);
598
599         add_wait_queue(sk_sleep(sk), &wait);
600         sk->sk_write_pending += writebias;
601
602         /* Basic assumption: if someone sets sk->sk_err, he _must_
603          * change state of the socket from TCP_SYN_*.
604          * Connect() does not allow to get error notifications
605          * without closing the socket.
606          */
607         while ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) {
608                 release_sock(sk);
609                 timeo = wait_woken(&wait, TASK_INTERRUPTIBLE, timeo);
610                 lock_sock(sk);
611                 if (signal_pending(current) || !timeo)
612                         break;
613         }
614         remove_wait_queue(sk_sleep(sk), &wait);
615         sk->sk_write_pending -= writebias;
616         return timeo;
617 }
618
619 /*
620  *      Connect to a remote host. There is regrettably still a little
621  *      TCP 'magic' in here.
622  */
623 int __inet_stream_connect(struct socket *sock, struct sockaddr *uaddr,
624                           int addr_len, int flags, int is_sendmsg)
625 {
626         struct sock *sk = sock->sk;
627         int err;
628         long timeo;
629
630         /*
631          * uaddr can be NULL and addr_len can be 0 if:
632          * sk is a TCP fastopen active socket and
633          * TCP_FASTOPEN_CONNECT sockopt is set and
634          * we already have a valid cookie for this socket.
635          * In this case, user can call write() after connect().
636          * write() will invoke tcp_sendmsg_fastopen() which calls
637          * __inet_stream_connect().
638          */
639         if (uaddr) {
640                 if (addr_len < sizeof(uaddr->sa_family))
641                         return -EINVAL;
642
643                 if (uaddr->sa_family == AF_UNSPEC) {
644                         err = sk->sk_prot->disconnect(sk, flags);
645                         sock->state = err ? SS_DISCONNECTING : SS_UNCONNECTED;
646                         goto out;
647                 }
648         }
649
650         switch (sock->state) {
651         default:
652                 err = -EINVAL;
653                 goto out;
654         case SS_CONNECTED:
655                 err = -EISCONN;
656                 goto out;
657         case SS_CONNECTING:
658                 if (inet_sk(sk)->defer_connect)
659                         err = is_sendmsg ? -EINPROGRESS : -EISCONN;
660                 else
661                         err = -EALREADY;
662                 /* Fall out of switch with err, set for this state */
663                 break;
664         case SS_UNCONNECTED:
665                 err = -EISCONN;
666                 if (sk->sk_state != TCP_CLOSE)
667                         goto out;
668
669                 if (BPF_CGROUP_PRE_CONNECT_ENABLED(sk)) {
670                         err = sk->sk_prot->pre_connect(sk, uaddr, addr_len);
671                         if (err)
672                                 goto out;
673                 }
674
675                 err = sk->sk_prot->connect(sk, uaddr, addr_len);
676                 if (err < 0)
677                         goto out;
678
679                 sock->state = SS_CONNECTING;
680
681                 if (!err && inet_sk(sk)->defer_connect)
682                         goto out;
683
684                 /* Just entered SS_CONNECTING state; the only
685                  * difference is that return value in non-blocking
686                  * case is EINPROGRESS, rather than EALREADY.
687                  */
688                 err = -EINPROGRESS;
689                 break;
690         }
691
692         timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
693
694         if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) {
695                 int writebias = (sk->sk_protocol == IPPROTO_TCP) &&
696                                 tcp_sk(sk)->fastopen_req &&
697                                 tcp_sk(sk)->fastopen_req->data ? 1 : 0;
698
699                 /* Error code is set above */
700                 if (!timeo || !inet_wait_for_connect(sk, timeo, writebias))
701                         goto out;
702
703                 err = sock_intr_errno(timeo);
704                 if (signal_pending(current))
705                         goto out;
706         }
707
708         /* Connection was closed by RST, timeout, ICMP error
709          * or another process disconnected us.
710          */
711         if (sk->sk_state == TCP_CLOSE)
712                 goto sock_error;
713
714         /* sk->sk_err may be not zero now, if RECVERR was ordered by user
715          * and error was received after socket entered established state.
716          * Hence, it is handled normally after connect() return successfully.
717          */
718
719         sock->state = SS_CONNECTED;
720         err = 0;
721 out:
722         return err;
723
724 sock_error:
725         err = sock_error(sk) ? : -ECONNABORTED;
726         sock->state = SS_UNCONNECTED;
727         if (sk->sk_prot->disconnect(sk, flags))
728                 sock->state = SS_DISCONNECTING;
729         goto out;
730 }
731 EXPORT_SYMBOL(__inet_stream_connect);
732
733 int inet_stream_connect(struct socket *sock, struct sockaddr *uaddr,
734                         int addr_len, int flags)
735 {
736         int err;
737
738         lock_sock(sock->sk);
739         err = __inet_stream_connect(sock, uaddr, addr_len, flags, 0);
740         release_sock(sock->sk);
741         return err;
742 }
743 EXPORT_SYMBOL(inet_stream_connect);
744
745 /*
746  *      Accept a pending connection. The TCP layer now gives BSD semantics.
747  */
748
749 int inet_accept(struct socket *sock, struct socket *newsock, int flags,
750                 bool kern)
751 {
752         struct sock *sk1 = sock->sk;
753         int err = -EINVAL;
754         struct sock *sk2 = sk1->sk_prot->accept(sk1, flags, &err, kern);
755
756         if (!sk2)
757                 goto do_err;
758
759         lock_sock(sk2);
760
761         sock_rps_record_flow(sk2);
762         WARN_ON(!((1 << sk2->sk_state) &
763                   (TCPF_ESTABLISHED | TCPF_SYN_RECV |
764                   TCPF_CLOSE_WAIT | TCPF_CLOSE)));
765
766         sock_graft(sk2, newsock);
767
768         newsock->state = SS_CONNECTED;
769         err = 0;
770         release_sock(sk2);
771 do_err:
772         return err;
773 }
774 EXPORT_SYMBOL(inet_accept);
775
776
777 /*
778  *      This does both peername and sockname.
779  */
780 int inet_getname(struct socket *sock, struct sockaddr *uaddr,
781                         int peer)
782 {
783         struct sock *sk         = sock->sk;
784         struct inet_sock *inet  = inet_sk(sk);
785         DECLARE_SOCKADDR(struct sockaddr_in *, sin, uaddr);
786
787         sin->sin_family = AF_INET;
788         if (peer) {
789                 if (!inet->inet_dport ||
790                     (((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_SYN_SENT)) &&
791                      peer == 1))
792                         return -ENOTCONN;
793                 sin->sin_port = inet->inet_dport;
794                 sin->sin_addr.s_addr = inet->inet_daddr;
795         } else {
796                 __be32 addr = inet->inet_rcv_saddr;
797                 if (!addr)
798                         addr = inet->inet_saddr;
799                 sin->sin_port = inet->inet_sport;
800                 sin->sin_addr.s_addr = addr;
801         }
802         memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
803         return sizeof(*sin);
804 }
805 EXPORT_SYMBOL(inet_getname);
806
807 int inet_sendmsg(struct socket *sock, struct msghdr *msg, size_t size)
808 {
809         struct sock *sk = sock->sk;
810
811         sock_rps_record_flow(sk);
812
813         /* We may need to bind the socket. */
814         if (!inet_sk(sk)->inet_num && !sk->sk_prot->no_autobind &&
815             inet_autobind(sk))
816                 return -EAGAIN;
817
818         return sk->sk_prot->sendmsg(sk, msg, size);
819 }
820 EXPORT_SYMBOL(inet_sendmsg);
821
822 ssize_t inet_sendpage(struct socket *sock, struct page *page, int offset,
823                       size_t size, int flags)
824 {
825         struct sock *sk = sock->sk;
826
827         sock_rps_record_flow(sk);
828
829         /* We may need to bind the socket. */
830         if (!inet_sk(sk)->inet_num && !sk->sk_prot->no_autobind &&
831             inet_autobind(sk))
832                 return -EAGAIN;
833
834         if (sk->sk_prot->sendpage)
835                 return sk->sk_prot->sendpage(sk, page, offset, size, flags);
836         return sock_no_sendpage(sock, page, offset, size, flags);
837 }
838 EXPORT_SYMBOL(inet_sendpage);
839
840 int inet_recvmsg(struct socket *sock, struct msghdr *msg, size_t size,
841                  int flags)
842 {
843         struct sock *sk = sock->sk;
844         int addr_len = 0;
845         int err;
846
847         if (likely(!(flags & MSG_ERRQUEUE)))
848                 sock_rps_record_flow(sk);
849
850         err = sk->sk_prot->recvmsg(sk, msg, size, flags & MSG_DONTWAIT,
851                                    flags & ~MSG_DONTWAIT, &addr_len);
852         if (err >= 0)
853                 msg->msg_namelen = addr_len;
854         return err;
855 }
856 EXPORT_SYMBOL(inet_recvmsg);
857
858 int inet_shutdown(struct socket *sock, int how)
859 {
860         struct sock *sk = sock->sk;
861         int err = 0;
862
863         /* This should really check to make sure
864          * the socket is a TCP socket. (WHY AC...)
865          */
866         how++; /* maps 0->1 has the advantage of making bit 1 rcvs and
867                        1->2 bit 2 snds.
868                        2->3 */
869         if ((how & ~SHUTDOWN_MASK) || !how)     /* MAXINT->0 */
870                 return -EINVAL;
871
872         lock_sock(sk);
873         if (sock->state == SS_CONNECTING) {
874                 if ((1 << sk->sk_state) &
875                     (TCPF_SYN_SENT | TCPF_SYN_RECV | TCPF_CLOSE))
876                         sock->state = SS_DISCONNECTING;
877                 else
878                         sock->state = SS_CONNECTED;
879         }
880
881         switch (sk->sk_state) {
882         case TCP_CLOSE:
883                 err = -ENOTCONN;
884                 /* Hack to wake up other listeners, who can poll for
885                    EPOLLHUP, even on eg. unconnected UDP sockets -- RR */
886                 /* fall through */
887         default:
888                 sk->sk_shutdown |= how;
889                 if (sk->sk_prot->shutdown)
890                         sk->sk_prot->shutdown(sk, how);
891                 break;
892
893         /* Remaining two branches are temporary solution for missing
894          * close() in multithreaded environment. It is _not_ a good idea,
895          * but we have no choice until close() is repaired at VFS level.
896          */
897         case TCP_LISTEN:
898                 if (!(how & RCV_SHUTDOWN))
899                         break;
900                 /* fall through */
901         case TCP_SYN_SENT:
902                 err = sk->sk_prot->disconnect(sk, O_NONBLOCK);
903                 sock->state = err ? SS_DISCONNECTING : SS_UNCONNECTED;
904                 break;
905         }
906
907         /* Wake up anyone sleeping in poll. */
908         sk->sk_state_change(sk);
909         release_sock(sk);
910         return err;
911 }
912 EXPORT_SYMBOL(inet_shutdown);
913
914 /*
915  *      ioctl() calls you can issue on an INET socket. Most of these are
916  *      device configuration and stuff and very rarely used. Some ioctls
917  *      pass on to the socket itself.
918  *
919  *      NOTE: I like the idea of a module for the config stuff. ie ifconfig
920  *      loads the devconfigure module does its configuring and unloads it.
921  *      There's a good 20K of config code hanging around the kernel.
922  */
923
924 int inet_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
925 {
926         struct sock *sk = sock->sk;
927         int err = 0;
928         struct net *net = sock_net(sk);
929         void __user *p = (void __user *)arg;
930         struct ifreq ifr;
931         struct rtentry rt;
932
933         switch (cmd) {
934         case SIOCGSTAMP:
935                 err = sock_get_timestamp(sk, (struct timeval __user *)arg);
936                 break;
937         case SIOCGSTAMPNS:
938                 err = sock_get_timestampns(sk, (struct timespec __user *)arg);
939                 break;
940         case SIOCADDRT:
941         case SIOCDELRT:
942                 if (copy_from_user(&rt, p, sizeof(struct rtentry)))
943                         return -EFAULT;
944                 err = ip_rt_ioctl(net, cmd, &rt);
945                 break;
946         case SIOCRTMSG:
947                 err = -EINVAL;
948                 break;
949         case SIOCDARP:
950         case SIOCGARP:
951         case SIOCSARP:
952                 err = arp_ioctl(net, cmd, (void __user *)arg);
953                 break;
954         case SIOCGIFADDR:
955         case SIOCGIFBRDADDR:
956         case SIOCGIFNETMASK:
957         case SIOCGIFDSTADDR:
958         case SIOCGIFPFLAGS:
959                 if (copy_from_user(&ifr, p, sizeof(struct ifreq)))
960                         return -EFAULT;
961                 err = devinet_ioctl(net, cmd, &ifr);
962                 if (!err && copy_to_user(p, &ifr, sizeof(struct ifreq)))
963                         err = -EFAULT;
964                 break;
965
966         case SIOCSIFADDR:
967         case SIOCSIFBRDADDR:
968         case SIOCSIFNETMASK:
969         case SIOCSIFDSTADDR:
970         case SIOCSIFPFLAGS:
971         case SIOCSIFFLAGS:
972                 if (copy_from_user(&ifr, p, sizeof(struct ifreq)))
973                         return -EFAULT;
974                 err = devinet_ioctl(net, cmd, &ifr);
975                 break;
976         default:
977                 if (sk->sk_prot->ioctl)
978                         err = sk->sk_prot->ioctl(sk, cmd, arg);
979                 else
980                         err = -ENOIOCTLCMD;
981                 break;
982         }
983         return err;
984 }
985 EXPORT_SYMBOL(inet_ioctl);
986
987 #ifdef CONFIG_COMPAT
988 static int inet_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
989 {
990         struct sock *sk = sock->sk;
991         int err = -ENOIOCTLCMD;
992
993         if (sk->sk_prot->compat_ioctl)
994                 err = sk->sk_prot->compat_ioctl(sk, cmd, arg);
995
996         return err;
997 }
998 #endif
999
1000 const struct proto_ops inet_stream_ops = {
1001         .family            = PF_INET,
1002         .owner             = THIS_MODULE,
1003         .release           = inet_release,
1004         .bind              = inet_bind,
1005         .connect           = inet_stream_connect,
1006         .socketpair        = sock_no_socketpair,
1007         .accept            = inet_accept,
1008         .getname           = inet_getname,
1009         .poll              = tcp_poll,
1010         .ioctl             = inet_ioctl,
1011         .listen            = inet_listen,
1012         .shutdown          = inet_shutdown,
1013         .setsockopt        = sock_common_setsockopt,
1014         .getsockopt        = sock_common_getsockopt,
1015         .sendmsg           = inet_sendmsg,
1016         .recvmsg           = inet_recvmsg,
1017 #ifdef CONFIG_MMU
1018         .mmap              = tcp_mmap,
1019 #endif
1020         .sendpage          = inet_sendpage,
1021         .splice_read       = tcp_splice_read,
1022         .read_sock         = tcp_read_sock,
1023         .sendmsg_locked    = tcp_sendmsg_locked,
1024         .sendpage_locked   = tcp_sendpage_locked,
1025         .peek_len          = tcp_peek_len,
1026 #ifdef CONFIG_COMPAT
1027         .compat_setsockopt = compat_sock_common_setsockopt,
1028         .compat_getsockopt = compat_sock_common_getsockopt,
1029         .compat_ioctl      = inet_compat_ioctl,
1030 #endif
1031         .set_rcvlowat      = tcp_set_rcvlowat,
1032 };
1033 EXPORT_SYMBOL(inet_stream_ops);
1034
1035 const struct proto_ops inet_dgram_ops = {
1036         .family            = PF_INET,
1037         .owner             = THIS_MODULE,
1038         .release           = inet_release,
1039         .bind              = inet_bind,
1040         .connect           = inet_dgram_connect,
1041         .socketpair        = sock_no_socketpair,
1042         .accept            = sock_no_accept,
1043         .getname           = inet_getname,
1044         .poll              = udp_poll,
1045         .ioctl             = inet_ioctl,
1046         .listen            = sock_no_listen,
1047         .shutdown          = inet_shutdown,
1048         .setsockopt        = sock_common_setsockopt,
1049         .getsockopt        = sock_common_getsockopt,
1050         .sendmsg           = inet_sendmsg,
1051         .recvmsg           = inet_recvmsg,
1052         .mmap              = sock_no_mmap,
1053         .sendpage          = inet_sendpage,
1054         .set_peek_off      = sk_set_peek_off,
1055 #ifdef CONFIG_COMPAT
1056         .compat_setsockopt = compat_sock_common_setsockopt,
1057         .compat_getsockopt = compat_sock_common_getsockopt,
1058         .compat_ioctl      = inet_compat_ioctl,
1059 #endif
1060 };
1061 EXPORT_SYMBOL(inet_dgram_ops);
1062
1063 /*
1064  * For SOCK_RAW sockets; should be the same as inet_dgram_ops but without
1065  * udp_poll
1066  */
1067 static const struct proto_ops inet_sockraw_ops = {
1068         .family            = PF_INET,
1069         .owner             = THIS_MODULE,
1070         .release           = inet_release,
1071         .bind              = inet_bind,
1072         .connect           = inet_dgram_connect,
1073         .socketpair        = sock_no_socketpair,
1074         .accept            = sock_no_accept,
1075         .getname           = inet_getname,
1076         .poll              = datagram_poll,
1077         .ioctl             = inet_ioctl,
1078         .listen            = sock_no_listen,
1079         .shutdown          = inet_shutdown,
1080         .setsockopt        = sock_common_setsockopt,
1081         .getsockopt        = sock_common_getsockopt,
1082         .sendmsg           = inet_sendmsg,
1083         .recvmsg           = inet_recvmsg,
1084         .mmap              = sock_no_mmap,
1085         .sendpage          = inet_sendpage,
1086 #ifdef CONFIG_COMPAT
1087         .compat_setsockopt = compat_sock_common_setsockopt,
1088         .compat_getsockopt = compat_sock_common_getsockopt,
1089         .compat_ioctl      = inet_compat_ioctl,
1090 #endif
1091 };
1092
1093 static const struct net_proto_family inet_family_ops = {
1094         .family = PF_INET,
1095         .create = inet_create,
1096         .owner  = THIS_MODULE,
1097 };
1098
1099 /* Upon startup we insert all the elements in inetsw_array[] into
1100  * the linked list inetsw.
1101  */
1102 static struct inet_protosw inetsw_array[] =
1103 {
1104         {
1105                 .type =       SOCK_STREAM,
1106                 .protocol =   IPPROTO_TCP,
1107                 .prot =       &tcp_prot,
1108                 .ops =        &inet_stream_ops,
1109                 .flags =      INET_PROTOSW_PERMANENT |
1110                               INET_PROTOSW_ICSK,
1111         },
1112
1113         {
1114                 .type =       SOCK_DGRAM,
1115                 .protocol =   IPPROTO_UDP,
1116                 .prot =       &udp_prot,
1117                 .ops =        &inet_dgram_ops,
1118                 .flags =      INET_PROTOSW_PERMANENT,
1119        },
1120
1121        {
1122                 .type =       SOCK_DGRAM,
1123                 .protocol =   IPPROTO_ICMP,
1124                 .prot =       &ping_prot,
1125                 .ops =        &inet_sockraw_ops,
1126                 .flags =      INET_PROTOSW_REUSE,
1127        },
1128
1129        {
1130                .type =       SOCK_RAW,
1131                .protocol =   IPPROTO_IP,        /* wild card */
1132                .prot =       &raw_prot,
1133                .ops =        &inet_sockraw_ops,
1134                .flags =      INET_PROTOSW_REUSE,
1135        }
1136 };
1137
1138 #define INETSW_ARRAY_LEN ARRAY_SIZE(inetsw_array)
1139
1140 void inet_register_protosw(struct inet_protosw *p)
1141 {
1142         struct list_head *lh;
1143         struct inet_protosw *answer;
1144         int protocol = p->protocol;
1145         struct list_head *last_perm;
1146
1147         spin_lock_bh(&inetsw_lock);
1148
1149         if (p->type >= SOCK_MAX)
1150                 goto out_illegal;
1151
1152         /* If we are trying to override a permanent protocol, bail. */
1153         last_perm = &inetsw[p->type];
1154         list_for_each(lh, &inetsw[p->type]) {
1155                 answer = list_entry(lh, struct inet_protosw, list);
1156                 /* Check only the non-wild match. */
1157                 if ((INET_PROTOSW_PERMANENT & answer->flags) == 0)
1158                         break;
1159                 if (protocol == answer->protocol)
1160                         goto out_permanent;
1161                 last_perm = lh;
1162         }
1163
1164         /* Add the new entry after the last permanent entry if any, so that
1165          * the new entry does not override a permanent entry when matched with
1166          * a wild-card protocol. But it is allowed to override any existing
1167          * non-permanent entry.  This means that when we remove this entry, the
1168          * system automatically returns to the old behavior.
1169          */
1170         list_add_rcu(&p->list, last_perm);
1171 out:
1172         spin_unlock_bh(&inetsw_lock);
1173
1174         return;
1175
1176 out_permanent:
1177         pr_err("Attempt to override permanent protocol %d\n", protocol);
1178         goto out;
1179
1180 out_illegal:
1181         pr_err("Ignoring attempt to register invalid socket type %d\n",
1182                p->type);
1183         goto out;
1184 }
1185 EXPORT_SYMBOL(inet_register_protosw);
1186
1187 void inet_unregister_protosw(struct inet_protosw *p)
1188 {
1189         if (INET_PROTOSW_PERMANENT & p->flags) {
1190                 pr_err("Attempt to unregister permanent protocol %d\n",
1191                        p->protocol);
1192         } else {
1193                 spin_lock_bh(&inetsw_lock);
1194                 list_del_rcu(&p->list);
1195                 spin_unlock_bh(&inetsw_lock);
1196
1197                 synchronize_net();
1198         }
1199 }
1200 EXPORT_SYMBOL(inet_unregister_protosw);
1201
1202 static int inet_sk_reselect_saddr(struct sock *sk)
1203 {
1204         struct inet_sock *inet = inet_sk(sk);
1205         __be32 old_saddr = inet->inet_saddr;
1206         __be32 daddr = inet->inet_daddr;
1207         struct flowi4 *fl4;
1208         struct rtable *rt;
1209         __be32 new_saddr;
1210         struct ip_options_rcu *inet_opt;
1211
1212         inet_opt = rcu_dereference_protected(inet->inet_opt,
1213                                              lockdep_sock_is_held(sk));
1214         if (inet_opt && inet_opt->opt.srr)
1215                 daddr = inet_opt->opt.faddr;
1216
1217         /* Query new route. */
1218         fl4 = &inet->cork.fl.u.ip4;
1219         rt = ip_route_connect(fl4, daddr, 0, RT_CONN_FLAGS(sk),
1220                               sk->sk_bound_dev_if, sk->sk_protocol,
1221                               inet->inet_sport, inet->inet_dport, sk);
1222         if (IS_ERR(rt))
1223                 return PTR_ERR(rt);
1224
1225         sk_setup_caps(sk, &rt->dst);
1226
1227         new_saddr = fl4->saddr;
1228
1229         if (new_saddr == old_saddr)
1230                 return 0;
1231
1232         if (sock_net(sk)->ipv4.sysctl_ip_dynaddr > 1) {
1233                 pr_info("%s(): shifting inet->saddr from %pI4 to %pI4\n",
1234                         __func__, &old_saddr, &new_saddr);
1235         }
1236
1237         inet->inet_saddr = inet->inet_rcv_saddr = new_saddr;
1238
1239         /*
1240          * XXX The only one ugly spot where we need to
1241          * XXX really change the sockets identity after
1242          * XXX it has entered the hashes. -DaveM
1243          *
1244          * Besides that, it does not check for connection
1245          * uniqueness. Wait for troubles.
1246          */
1247         return __sk_prot_rehash(sk);
1248 }
1249
1250 int inet_sk_rebuild_header(struct sock *sk)
1251 {
1252         struct inet_sock *inet = inet_sk(sk);
1253         struct rtable *rt = (struct rtable *)__sk_dst_check(sk, 0);
1254         __be32 daddr;
1255         struct ip_options_rcu *inet_opt;
1256         struct flowi4 *fl4;
1257         int err;
1258
1259         /* Route is OK, nothing to do. */
1260         if (rt)
1261                 return 0;
1262
1263         /* Reroute. */
1264         rcu_read_lock();
1265         inet_opt = rcu_dereference(inet->inet_opt);
1266         daddr = inet->inet_daddr;
1267         if (inet_opt && inet_opt->opt.srr)
1268                 daddr = inet_opt->opt.faddr;
1269         rcu_read_unlock();
1270         fl4 = &inet->cork.fl.u.ip4;
1271         rt = ip_route_output_ports(sock_net(sk), fl4, sk, daddr, inet->inet_saddr,
1272                                    inet->inet_dport, inet->inet_sport,
1273                                    sk->sk_protocol, RT_CONN_FLAGS(sk),
1274                                    sk->sk_bound_dev_if);
1275         if (!IS_ERR(rt)) {
1276                 err = 0;
1277                 sk_setup_caps(sk, &rt->dst);
1278         } else {
1279                 err = PTR_ERR(rt);
1280
1281                 /* Routing failed... */
1282                 sk->sk_route_caps = 0;
1283                 /*
1284                  * Other protocols have to map its equivalent state to TCP_SYN_SENT.
1285                  * DCCP maps its DCCP_REQUESTING state to TCP_SYN_SENT. -acme
1286                  */
1287                 if (!sock_net(sk)->ipv4.sysctl_ip_dynaddr ||
1288                     sk->sk_state != TCP_SYN_SENT ||
1289                     (sk->sk_userlocks & SOCK_BINDADDR_LOCK) ||
1290                     (err = inet_sk_reselect_saddr(sk)) != 0)
1291                         sk->sk_err_soft = -err;
1292         }
1293
1294         return err;
1295 }
1296 EXPORT_SYMBOL(inet_sk_rebuild_header);
1297
1298 void inet_sk_set_state(struct sock *sk, int state)
1299 {
1300         trace_inet_sock_set_state(sk, sk->sk_state, state);
1301         sk->sk_state = state;
1302 }
1303 EXPORT_SYMBOL(inet_sk_set_state);
1304
1305 void inet_sk_state_store(struct sock *sk, int newstate)
1306 {
1307         trace_inet_sock_set_state(sk, sk->sk_state, newstate);
1308         smp_store_release(&sk->sk_state, newstate);
1309 }
1310
1311 struct sk_buff *inet_gso_segment(struct sk_buff *skb,
1312                                  netdev_features_t features)
1313 {
1314         bool udpfrag = false, fixedid = false, gso_partial, encap;
1315         struct sk_buff *segs = ERR_PTR(-EINVAL);
1316         const struct net_offload *ops;
1317         unsigned int offset = 0;
1318         struct iphdr *iph;
1319         int proto, tot_len;
1320         int nhoff;
1321         int ihl;
1322         int id;
1323
1324         skb_reset_network_header(skb);
1325         nhoff = skb_network_header(skb) - skb_mac_header(skb);
1326         if (unlikely(!pskb_may_pull(skb, sizeof(*iph))))
1327                 goto out;
1328
1329         iph = ip_hdr(skb);
1330         ihl = iph->ihl * 4;
1331         if (ihl < sizeof(*iph))
1332                 goto out;
1333
1334         id = ntohs(iph->id);
1335         proto = iph->protocol;
1336
1337         /* Warning: after this point, iph might be no longer valid */
1338         if (unlikely(!pskb_may_pull(skb, ihl)))
1339                 goto out;
1340         __skb_pull(skb, ihl);
1341
1342         encap = SKB_GSO_CB(skb)->encap_level > 0;
1343         if (encap)
1344                 features &= skb->dev->hw_enc_features;
1345         SKB_GSO_CB(skb)->encap_level += ihl;
1346
1347         skb_reset_transport_header(skb);
1348
1349         segs = ERR_PTR(-EPROTONOSUPPORT);
1350
1351         if (!skb->encapsulation || encap) {
1352                 udpfrag = !!(skb_shinfo(skb)->gso_type & SKB_GSO_UDP);
1353                 fixedid = !!(skb_shinfo(skb)->gso_type & SKB_GSO_TCP_FIXEDID);
1354
1355                 /* fixed ID is invalid if DF bit is not set */
1356                 if (fixedid && !(ip_hdr(skb)->frag_off & htons(IP_DF)))
1357                         goto out;
1358         }
1359
1360         ops = rcu_dereference(inet_offloads[proto]);
1361         if (likely(ops && ops->callbacks.gso_segment))
1362                 segs = ops->callbacks.gso_segment(skb, features);
1363
1364         if (IS_ERR_OR_NULL(segs))
1365                 goto out;
1366
1367         gso_partial = !!(skb_shinfo(segs)->gso_type & SKB_GSO_PARTIAL);
1368
1369         skb = segs;
1370         do {
1371                 iph = (struct iphdr *)(skb_mac_header(skb) + nhoff);
1372                 if (udpfrag) {
1373                         iph->frag_off = htons(offset >> 3);
1374                         if (skb->next)
1375                                 iph->frag_off |= htons(IP_MF);
1376                         offset += skb->len - nhoff - ihl;
1377                         tot_len = skb->len - nhoff;
1378                 } else if (skb_is_gso(skb)) {
1379                         if (!fixedid) {
1380                                 iph->id = htons(id);
1381                                 id += skb_shinfo(skb)->gso_segs;
1382                         }
1383
1384                         if (gso_partial)
1385                                 tot_len = skb_shinfo(skb)->gso_size +
1386                                           SKB_GSO_CB(skb)->data_offset +
1387                                           skb->head - (unsigned char *)iph;
1388                         else
1389                                 tot_len = skb->len - nhoff;
1390                 } else {
1391                         if (!fixedid)
1392                                 iph->id = htons(id++);
1393                         tot_len = skb->len - nhoff;
1394                 }
1395                 iph->tot_len = htons(tot_len);
1396                 ip_send_check(iph);
1397                 if (encap)
1398                         skb_reset_inner_headers(skb);
1399                 skb->network_header = (u8 *)iph - skb->head;
1400                 skb_reset_mac_len(skb);
1401         } while ((skb = skb->next));
1402
1403 out:
1404         return segs;
1405 }
1406 EXPORT_SYMBOL(inet_gso_segment);
1407
1408 struct sk_buff *inet_gro_receive(struct list_head *head, struct sk_buff *skb)
1409 {
1410         const struct net_offload *ops;
1411         struct sk_buff *pp = NULL;
1412         const struct iphdr *iph;
1413         struct sk_buff *p;
1414         unsigned int hlen;
1415         unsigned int off;
1416         unsigned int id;
1417         int flush = 1;
1418         int proto;
1419
1420         off = skb_gro_offset(skb);
1421         hlen = off + sizeof(*iph);
1422         iph = skb_gro_header_fast(skb, off);
1423         if (skb_gro_header_hard(skb, hlen)) {
1424                 iph = skb_gro_header_slow(skb, hlen, off);
1425                 if (unlikely(!iph))
1426                         goto out;
1427         }
1428
1429         proto = iph->protocol;
1430
1431         rcu_read_lock();
1432         ops = rcu_dereference(inet_offloads[proto]);
1433         if (!ops || !ops->callbacks.gro_receive)
1434                 goto out_unlock;
1435
1436         if (*(u8 *)iph != 0x45)
1437                 goto out_unlock;
1438
1439         if (ip_is_fragment(iph))
1440                 goto out_unlock;
1441
1442         if (unlikely(ip_fast_csum((u8 *)iph, 5)))
1443                 goto out_unlock;
1444
1445         id = ntohl(*(__be32 *)&iph->id);
1446         flush = (u16)((ntohl(*(__be32 *)iph) ^ skb_gro_len(skb)) | (id & ~IP_DF));
1447         id >>= 16;
1448
1449         list_for_each_entry(p, head, list) {
1450                 struct iphdr *iph2;
1451                 u16 flush_id;
1452
1453                 if (!NAPI_GRO_CB(p)->same_flow)
1454                         continue;
1455
1456                 iph2 = (struct iphdr *)(p->data + off);
1457                 /* The above works because, with the exception of the top
1458                  * (inner most) layer, we only aggregate pkts with the same
1459                  * hdr length so all the hdrs we'll need to verify will start
1460                  * at the same offset.
1461                  */
1462                 if ((iph->protocol ^ iph2->protocol) |
1463                     ((__force u32)iph->saddr ^ (__force u32)iph2->saddr) |
1464                     ((__force u32)iph->daddr ^ (__force u32)iph2->daddr)) {
1465                         NAPI_GRO_CB(p)->same_flow = 0;
1466                         continue;
1467                 }
1468
1469                 /* All fields must match except length and checksum. */
1470                 NAPI_GRO_CB(p)->flush |=
1471                         (iph->ttl ^ iph2->ttl) |
1472                         (iph->tos ^ iph2->tos) |
1473                         ((iph->frag_off ^ iph2->frag_off) & htons(IP_DF));
1474
1475                 NAPI_GRO_CB(p)->flush |= flush;
1476
1477                 /* We need to store of the IP ID check to be included later
1478                  * when we can verify that this packet does in fact belong
1479                  * to a given flow.
1480                  */
1481                 flush_id = (u16)(id - ntohs(iph2->id));
1482
1483                 /* This bit of code makes it much easier for us to identify
1484                  * the cases where we are doing atomic vs non-atomic IP ID
1485                  * checks.  Specifically an atomic check can return IP ID
1486                  * values 0 - 0xFFFF, while a non-atomic check can only
1487                  * return 0 or 0xFFFF.
1488                  */
1489                 if (!NAPI_GRO_CB(p)->is_atomic ||
1490                     !(iph->frag_off & htons(IP_DF))) {
1491                         flush_id ^= NAPI_GRO_CB(p)->count;
1492                         flush_id = flush_id ? 0xFFFF : 0;
1493                 }
1494
1495                 /* If the previous IP ID value was based on an atomic
1496                  * datagram we can overwrite the value and ignore it.
1497                  */
1498                 if (NAPI_GRO_CB(skb)->is_atomic)
1499                         NAPI_GRO_CB(p)->flush_id = flush_id;
1500                 else
1501                         NAPI_GRO_CB(p)->flush_id |= flush_id;
1502         }
1503
1504         NAPI_GRO_CB(skb)->is_atomic = !!(iph->frag_off & htons(IP_DF));
1505         NAPI_GRO_CB(skb)->flush |= flush;
1506         skb_set_network_header(skb, off);
1507         /* The above will be needed by the transport layer if there is one
1508          * immediately following this IP hdr.
1509          */
1510
1511         /* Note : No need to call skb_gro_postpull_rcsum() here,
1512          * as we already checked checksum over ipv4 header was 0
1513          */
1514         skb_gro_pull(skb, sizeof(*iph));
1515         skb_set_transport_header(skb, skb_gro_offset(skb));
1516
1517         pp = call_gro_receive(ops->callbacks.gro_receive, head, skb);
1518
1519 out_unlock:
1520         rcu_read_unlock();
1521
1522 out:
1523         skb_gro_flush_final(skb, pp, flush);
1524
1525         return pp;
1526 }
1527 EXPORT_SYMBOL(inet_gro_receive);
1528
1529 static struct sk_buff *ipip_gro_receive(struct list_head *head,
1530                                         struct sk_buff *skb)
1531 {
1532         if (NAPI_GRO_CB(skb)->encap_mark) {
1533                 NAPI_GRO_CB(skb)->flush = 1;
1534                 return NULL;
1535         }
1536
1537         NAPI_GRO_CB(skb)->encap_mark = 1;
1538
1539         return inet_gro_receive(head, skb);
1540 }
1541
1542 #define SECONDS_PER_DAY 86400
1543
1544 /* inet_current_timestamp - Return IP network timestamp
1545  *
1546  * Return milliseconds since midnight in network byte order.
1547  */
1548 __be32 inet_current_timestamp(void)
1549 {
1550         u32 secs;
1551         u32 msecs;
1552         struct timespec64 ts;
1553
1554         ktime_get_real_ts64(&ts);
1555
1556         /* Get secs since midnight. */
1557         (void)div_u64_rem(ts.tv_sec, SECONDS_PER_DAY, &secs);
1558         /* Convert to msecs. */
1559         msecs = secs * MSEC_PER_SEC;
1560         /* Convert nsec to msec. */
1561         msecs += (u32)ts.tv_nsec / NSEC_PER_MSEC;
1562
1563         /* Convert to network byte order. */
1564         return htonl(msecs);
1565 }
1566 EXPORT_SYMBOL(inet_current_timestamp);
1567
1568 int inet_recv_error(struct sock *sk, struct msghdr *msg, int len, int *addr_len)
1569 {
1570         if (sk->sk_family == AF_INET)
1571                 return ip_recv_error(sk, msg, len, addr_len);
1572 #if IS_ENABLED(CONFIG_IPV6)
1573         if (sk->sk_family == AF_INET6)
1574                 return pingv6_ops.ipv6_recv_error(sk, msg, len, addr_len);
1575 #endif
1576         return -EINVAL;
1577 }
1578
1579 int inet_gro_complete(struct sk_buff *skb, int nhoff)
1580 {
1581         __be16 newlen = htons(skb->len - nhoff);
1582         struct iphdr *iph = (struct iphdr *)(skb->data + nhoff);
1583         const struct net_offload *ops;
1584         int proto = iph->protocol;
1585         int err = -ENOSYS;
1586
1587         if (skb->encapsulation) {
1588                 skb_set_inner_protocol(skb, cpu_to_be16(ETH_P_IP));
1589                 skb_set_inner_network_header(skb, nhoff);
1590         }
1591
1592         csum_replace2(&iph->check, iph->tot_len, newlen);
1593         iph->tot_len = newlen;
1594
1595         rcu_read_lock();
1596         ops = rcu_dereference(inet_offloads[proto]);
1597         if (WARN_ON(!ops || !ops->callbacks.gro_complete))
1598                 goto out_unlock;
1599
1600         /* Only need to add sizeof(*iph) to get to the next hdr below
1601          * because any hdr with option will have been flushed in
1602          * inet_gro_receive().
1603          */
1604         err = ops->callbacks.gro_complete(skb, nhoff + sizeof(*iph));
1605
1606 out_unlock:
1607         rcu_read_unlock();
1608
1609         return err;
1610 }
1611 EXPORT_SYMBOL(inet_gro_complete);
1612
1613 static int ipip_gro_complete(struct sk_buff *skb, int nhoff)
1614 {
1615         skb->encapsulation = 1;
1616         skb_shinfo(skb)->gso_type |= SKB_GSO_IPXIP4;
1617         return inet_gro_complete(skb, nhoff);
1618 }
1619
1620 int inet_ctl_sock_create(struct sock **sk, unsigned short family,
1621                          unsigned short type, unsigned char protocol,
1622                          struct net *net)
1623 {
1624         struct socket *sock;
1625         int rc = sock_create_kern(net, family, type, protocol, &sock);
1626
1627         if (rc == 0) {
1628                 *sk = sock->sk;
1629                 (*sk)->sk_allocation = GFP_ATOMIC;
1630                 /*
1631                  * Unhash it so that IP input processing does not even see it,
1632                  * we do not wish this socket to see incoming packets.
1633                  */
1634                 (*sk)->sk_prot->unhash(*sk);
1635         }
1636         return rc;
1637 }
1638 EXPORT_SYMBOL_GPL(inet_ctl_sock_create);
1639
1640 u64 snmp_get_cpu_field(void __percpu *mib, int cpu, int offt)
1641 {
1642         return  *(((unsigned long *)per_cpu_ptr(mib, cpu)) + offt);
1643 }
1644 EXPORT_SYMBOL_GPL(snmp_get_cpu_field);
1645
1646 unsigned long snmp_fold_field(void __percpu *mib, int offt)
1647 {
1648         unsigned long res = 0;
1649         int i;
1650
1651         for_each_possible_cpu(i)
1652                 res += snmp_get_cpu_field(mib, i, offt);
1653         return res;
1654 }
1655 EXPORT_SYMBOL_GPL(snmp_fold_field);
1656
1657 #if BITS_PER_LONG==32
1658
1659 u64 snmp_get_cpu_field64(void __percpu *mib, int cpu, int offt,
1660                          size_t syncp_offset)
1661 {
1662         void *bhptr;
1663         struct u64_stats_sync *syncp;
1664         u64 v;
1665         unsigned int start;
1666
1667         bhptr = per_cpu_ptr(mib, cpu);
1668         syncp = (struct u64_stats_sync *)(bhptr + syncp_offset);
1669         do {
1670                 start = u64_stats_fetch_begin_irq(syncp);
1671                 v = *(((u64 *)bhptr) + offt);
1672         } while (u64_stats_fetch_retry_irq(syncp, start));
1673
1674         return v;
1675 }
1676 EXPORT_SYMBOL_GPL(snmp_get_cpu_field64);
1677
1678 u64 snmp_fold_field64(void __percpu *mib, int offt, size_t syncp_offset)
1679 {
1680         u64 res = 0;
1681         int cpu;
1682
1683         for_each_possible_cpu(cpu) {
1684                 res += snmp_get_cpu_field64(mib, cpu, offt, syncp_offset);
1685         }
1686         return res;
1687 }
1688 EXPORT_SYMBOL_GPL(snmp_fold_field64);
1689 #endif
1690
1691 #ifdef CONFIG_IP_MULTICAST
1692 static const struct net_protocol igmp_protocol = {
1693         .handler =      igmp_rcv,
1694         .netns_ok =     1,
1695 };
1696 #endif
1697
1698 /* thinking of making this const? Don't.
1699  * early_demux can change based on sysctl.
1700  */
1701 static struct net_protocol tcp_protocol = {
1702         .early_demux    =       tcp_v4_early_demux,
1703         .early_demux_handler =  tcp_v4_early_demux,
1704         .handler        =       tcp_v4_rcv,
1705         .err_handler    =       tcp_v4_err,
1706         .no_policy      =       1,
1707         .netns_ok       =       1,
1708         .icmp_strict_tag_validation = 1,
1709 };
1710
1711 /* thinking of making this const? Don't.
1712  * early_demux can change based on sysctl.
1713  */
1714 static struct net_protocol udp_protocol = {
1715         .early_demux =  udp_v4_early_demux,
1716         .early_demux_handler =  udp_v4_early_demux,
1717         .handler =      udp_rcv,
1718         .err_handler =  udp_err,
1719         .no_policy =    1,
1720         .netns_ok =     1,
1721 };
1722
1723 static const struct net_protocol icmp_protocol = {
1724         .handler =      icmp_rcv,
1725         .err_handler =  icmp_err,
1726         .no_policy =    1,
1727         .netns_ok =     1,
1728 };
1729
1730 static __net_init int ipv4_mib_init_net(struct net *net)
1731 {
1732         int i;
1733
1734         net->mib.tcp_statistics = alloc_percpu(struct tcp_mib);
1735         if (!net->mib.tcp_statistics)
1736                 goto err_tcp_mib;
1737         net->mib.ip_statistics = alloc_percpu(struct ipstats_mib);
1738         if (!net->mib.ip_statistics)
1739                 goto err_ip_mib;
1740
1741         for_each_possible_cpu(i) {
1742                 struct ipstats_mib *af_inet_stats;
1743                 af_inet_stats = per_cpu_ptr(net->mib.ip_statistics, i);
1744                 u64_stats_init(&af_inet_stats->syncp);
1745         }
1746
1747         net->mib.net_statistics = alloc_percpu(struct linux_mib);
1748         if (!net->mib.net_statistics)
1749                 goto err_net_mib;
1750         net->mib.udp_statistics = alloc_percpu(struct udp_mib);
1751         if (!net->mib.udp_statistics)
1752                 goto err_udp_mib;
1753         net->mib.udplite_statistics = alloc_percpu(struct udp_mib);
1754         if (!net->mib.udplite_statistics)
1755                 goto err_udplite_mib;
1756         net->mib.icmp_statistics = alloc_percpu(struct icmp_mib);
1757         if (!net->mib.icmp_statistics)
1758                 goto err_icmp_mib;
1759         net->mib.icmpmsg_statistics = kzalloc(sizeof(struct icmpmsg_mib),
1760                                               GFP_KERNEL);
1761         if (!net->mib.icmpmsg_statistics)
1762                 goto err_icmpmsg_mib;
1763
1764         tcp_mib_init(net);
1765         return 0;
1766
1767 err_icmpmsg_mib:
1768         free_percpu(net->mib.icmp_statistics);
1769 err_icmp_mib:
1770         free_percpu(net->mib.udplite_statistics);
1771 err_udplite_mib:
1772         free_percpu(net->mib.udp_statistics);
1773 err_udp_mib:
1774         free_percpu(net->mib.net_statistics);
1775 err_net_mib:
1776         free_percpu(net->mib.ip_statistics);
1777 err_ip_mib:
1778         free_percpu(net->mib.tcp_statistics);
1779 err_tcp_mib:
1780         return -ENOMEM;
1781 }
1782
1783 static __net_exit void ipv4_mib_exit_net(struct net *net)
1784 {
1785         kfree(net->mib.icmpmsg_statistics);
1786         free_percpu(net->mib.icmp_statistics);
1787         free_percpu(net->mib.udplite_statistics);
1788         free_percpu(net->mib.udp_statistics);
1789         free_percpu(net->mib.net_statistics);
1790         free_percpu(net->mib.ip_statistics);
1791         free_percpu(net->mib.tcp_statistics);
1792 }
1793
1794 static __net_initdata struct pernet_operations ipv4_mib_ops = {
1795         .init = ipv4_mib_init_net,
1796         .exit = ipv4_mib_exit_net,
1797 };
1798
1799 static int __init init_ipv4_mibs(void)
1800 {
1801         return register_pernet_subsys(&ipv4_mib_ops);
1802 }
1803
1804 static __net_init int inet_init_net(struct net *net)
1805 {
1806         /*
1807          * Set defaults for local port range
1808          */
1809         seqlock_init(&net->ipv4.ip_local_ports.lock);
1810         net->ipv4.ip_local_ports.range[0] =  32768;
1811         net->ipv4.ip_local_ports.range[1] =  60999;
1812
1813         seqlock_init(&net->ipv4.ping_group_range.lock);
1814         /*
1815          * Sane defaults - nobody may create ping sockets.
1816          * Boot scripts should set this to distro-specific group.
1817          */
1818         net->ipv4.ping_group_range.range[0] = make_kgid(&init_user_ns, 1);
1819         net->ipv4.ping_group_range.range[1] = make_kgid(&init_user_ns, 0);
1820
1821         /* Default values for sysctl-controlled parameters.
1822          * We set them here, in case sysctl is not compiled.
1823          */
1824         net->ipv4.sysctl_ip_default_ttl = IPDEFTTL;
1825         net->ipv4.sysctl_ip_fwd_update_priority = 1;
1826         net->ipv4.sysctl_ip_dynaddr = 0;
1827         net->ipv4.sysctl_ip_early_demux = 1;
1828         net->ipv4.sysctl_udp_early_demux = 1;
1829         net->ipv4.sysctl_tcp_early_demux = 1;
1830 #ifdef CONFIG_SYSCTL
1831         net->ipv4.sysctl_ip_prot_sock = PROT_SOCK;
1832 #endif
1833
1834         /* Some igmp sysctl, whose values are always used */
1835         net->ipv4.sysctl_igmp_max_memberships = 20;
1836         net->ipv4.sysctl_igmp_max_msf = 10;
1837         /* IGMP reports for link-local multicast groups are enabled by default */
1838         net->ipv4.sysctl_igmp_llm_reports = 1;
1839         net->ipv4.sysctl_igmp_qrv = 2;
1840
1841         return 0;
1842 }
1843
1844 static __net_exit void inet_exit_net(struct net *net)
1845 {
1846 }
1847
1848 static __net_initdata struct pernet_operations af_inet_ops = {
1849         .init = inet_init_net,
1850         .exit = inet_exit_net,
1851 };
1852
1853 static int __init init_inet_pernet_ops(void)
1854 {
1855         return register_pernet_subsys(&af_inet_ops);
1856 }
1857
1858 static int ipv4_proc_init(void);
1859
1860 /*
1861  *      IP protocol layer initialiser
1862  */
1863
1864 static struct packet_offload ip_packet_offload __read_mostly = {
1865         .type = cpu_to_be16(ETH_P_IP),
1866         .callbacks = {
1867                 .gso_segment = inet_gso_segment,
1868                 .gro_receive = inet_gro_receive,
1869                 .gro_complete = inet_gro_complete,
1870         },
1871 };
1872
1873 static const struct net_offload ipip_offload = {
1874         .callbacks = {
1875                 .gso_segment    = inet_gso_segment,
1876                 .gro_receive    = ipip_gro_receive,
1877                 .gro_complete   = ipip_gro_complete,
1878         },
1879 };
1880
1881 static int __init ipip_offload_init(void)
1882 {
1883         return inet_add_offload(&ipip_offload, IPPROTO_IPIP);
1884 }
1885
1886 static int __init ipv4_offload_init(void)
1887 {
1888         /*
1889          * Add offloads
1890          */
1891         if (udpv4_offload_init() < 0)
1892                 pr_crit("%s: Cannot add UDP protocol offload\n", __func__);
1893         if (tcpv4_offload_init() < 0)
1894                 pr_crit("%s: Cannot add TCP protocol offload\n", __func__);
1895         if (ipip_offload_init() < 0)
1896                 pr_crit("%s: Cannot add IPIP protocol offload\n", __func__);
1897
1898         dev_add_offload(&ip_packet_offload);
1899         return 0;
1900 }
1901
1902 fs_initcall(ipv4_offload_init);
1903
1904 static struct packet_type ip_packet_type __read_mostly = {
1905         .type = cpu_to_be16(ETH_P_IP),
1906         .func = ip_rcv,
1907         .list_func = ip_list_rcv,
1908 };
1909
1910 static int __init inet_init(void)
1911 {
1912         struct inet_protosw *q;
1913         struct list_head *r;
1914         int rc = -EINVAL;
1915
1916         sock_skb_cb_check_size(sizeof(struct inet_skb_parm));
1917
1918         rc = proto_register(&tcp_prot, 1);
1919         if (rc)
1920                 goto out;
1921
1922         rc = proto_register(&udp_prot, 1);
1923         if (rc)
1924                 goto out_unregister_tcp_proto;
1925
1926         rc = proto_register(&raw_prot, 1);
1927         if (rc)
1928                 goto out_unregister_udp_proto;
1929
1930         rc = proto_register(&ping_prot, 1);
1931         if (rc)
1932                 goto out_unregister_raw_proto;
1933
1934         /*
1935          *      Tell SOCKET that we are alive...
1936          */
1937
1938         (void)sock_register(&inet_family_ops);
1939
1940 #ifdef CONFIG_SYSCTL
1941         ip_static_sysctl_init();
1942 #endif
1943
1944         /*
1945          *      Add all the base protocols.
1946          */
1947
1948         if (inet_add_protocol(&icmp_protocol, IPPROTO_ICMP) < 0)
1949                 pr_crit("%s: Cannot add ICMP protocol\n", __func__);
1950         if (inet_add_protocol(&udp_protocol, IPPROTO_UDP) < 0)
1951                 pr_crit("%s: Cannot add UDP protocol\n", __func__);
1952         if (inet_add_protocol(&tcp_protocol, IPPROTO_TCP) < 0)
1953                 pr_crit("%s: Cannot add TCP protocol\n", __func__);
1954 #ifdef CONFIG_IP_MULTICAST
1955         if (inet_add_protocol(&igmp_protocol, IPPROTO_IGMP) < 0)
1956                 pr_crit("%s: Cannot add IGMP protocol\n", __func__);
1957 #endif
1958
1959         /* Register the socket-side information for inet_create. */
1960         for (r = &inetsw[0]; r < &inetsw[SOCK_MAX]; ++r)
1961                 INIT_LIST_HEAD(r);
1962
1963         for (q = inetsw_array; q < &inetsw_array[INETSW_ARRAY_LEN]; ++q)
1964                 inet_register_protosw(q);
1965
1966         /*
1967          *      Set the ARP module up
1968          */
1969
1970         arp_init();
1971
1972         /*
1973          *      Set the IP module up
1974          */
1975
1976         ip_init();
1977
1978         /* Setup TCP slab cache for open requests. */
1979         tcp_init();
1980
1981         /* Setup UDP memory threshold */
1982         udp_init();
1983
1984         /* Add UDP-Lite (RFC 3828) */
1985         udplite4_register();
1986
1987         ping_init();
1988
1989         /*
1990          *      Set the ICMP layer up
1991          */
1992
1993         if (icmp_init() < 0)
1994                 panic("Failed to create the ICMP control socket.\n");
1995
1996         /*
1997          *      Initialise the multicast router
1998          */
1999 #if defined(CONFIG_IP_MROUTE)
2000         if (ip_mr_init())
2001                 pr_crit("%s: Cannot init ipv4 mroute\n", __func__);
2002 #endif
2003
2004         if (init_inet_pernet_ops())
2005                 pr_crit("%s: Cannot init ipv4 inet pernet ops\n", __func__);
2006         /*
2007          *      Initialise per-cpu ipv4 mibs
2008          */
2009
2010         if (init_ipv4_mibs())
2011                 pr_crit("%s: Cannot init ipv4 mibs\n", __func__);
2012
2013         ipv4_proc_init();
2014
2015         ipfrag_init();
2016
2017         dev_add_pack(&ip_packet_type);
2018
2019         ip_tunnel_core_init();
2020
2021         rc = 0;
2022 out:
2023         return rc;
2024 out_unregister_raw_proto:
2025         proto_unregister(&raw_prot);
2026 out_unregister_udp_proto:
2027         proto_unregister(&udp_prot);
2028 out_unregister_tcp_proto:
2029         proto_unregister(&tcp_prot);
2030         goto out;
2031 }
2032
2033 fs_initcall(inet_init);
2034
2035 /* ------------------------------------------------------------------------ */
2036
2037 #ifdef CONFIG_PROC_FS
2038 static int __init ipv4_proc_init(void)
2039 {
2040         int rc = 0;
2041
2042         if (raw_proc_init())
2043                 goto out_raw;
2044         if (tcp4_proc_init())
2045                 goto out_tcp;
2046         if (udp4_proc_init())
2047                 goto out_udp;
2048         if (ping_proc_init())
2049                 goto out_ping;
2050         if (ip_misc_proc_init())
2051                 goto out_misc;
2052 out:
2053         return rc;
2054 out_misc:
2055         ping_proc_exit();
2056 out_ping:
2057         udp4_proc_exit();
2058 out_udp:
2059         tcp4_proc_exit();
2060 out_tcp:
2061         raw_proc_exit();
2062 out_raw:
2063         rc = -ENOMEM;
2064         goto out;
2065 }
2066
2067 #else /* CONFIG_PROC_FS */
2068 static int __init ipv4_proc_init(void)
2069 {
2070         return 0;
2071 }
2072 #endif /* CONFIG_PROC_FS */