Merge branch 'linux-linaro-lsk' into linux-linaro-lsk-android
[firefly-linux-kernel-4.4.55.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/module.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
93 #include <asm/uaccess.h>
94
95 #include <linux/inet.h>
96 #include <linux/igmp.h>
97 #include <linux/inetdevice.h>
98 #include <linux/netdevice.h>
99 #include <net/checksum.h>
100 #include <net/ip.h>
101 #include <net/protocol.h>
102 #include <net/arp.h>
103 #include <net/route.h>
104 #include <net/ip_fib.h>
105 #include <net/inet_connection_sock.h>
106 #include <net/tcp.h>
107 #include <net/udp.h>
108 #include <net/udplite.h>
109 #include <net/ping.h>
110 #include <linux/skbuff.h>
111 #include <net/sock.h>
112 #include <net/raw.h>
113 #include <net/icmp.h>
114 #include <net/inet_common.h>
115 #include <net/xfrm.h>
116 #include <net/net_namespace.h>
117 #include <net/secure_seq.h>
118 #ifdef CONFIG_IP_MROUTE
119 #include <linux/mroute.h>
120 #endif
121
122 #ifdef CONFIG_ANDROID_PARANOID_NETWORK
123 #include <linux/android_aid.h>
124
125 static inline int current_has_network(void)
126 {
127         return in_egroup_p(AID_INET) || capable(CAP_NET_RAW);
128 }
129 #else
130 static inline int current_has_network(void)
131 {
132         return 1;
133 }
134 #endif
135
136 /* The inetsw table contains everything that inet_create needs to
137  * build a new socket.
138  */
139 static struct list_head inetsw[SOCK_MAX];
140 static DEFINE_SPINLOCK(inetsw_lock);
141
142 struct ipv4_config ipv4_config;
143 EXPORT_SYMBOL(ipv4_config);
144
145 /* New destruction routine */
146
147 void inet_sock_destruct(struct sock *sk)
148 {
149         struct inet_sock *inet = inet_sk(sk);
150
151         __skb_queue_purge(&sk->sk_receive_queue);
152         __skb_queue_purge(&sk->sk_error_queue);
153
154         sk_mem_reclaim(sk);
155
156         if (sk->sk_type == SOCK_STREAM && sk->sk_state != TCP_CLOSE) {
157                 pr_err("Attempt to release TCP socket in state %d %p\n",
158                        sk->sk_state, sk);
159                 return;
160         }
161         if (!sock_flag(sk, SOCK_DEAD)) {
162                 pr_err("Attempt to release alive inet socket %p\n", sk);
163                 return;
164         }
165
166         WARN_ON(atomic_read(&sk->sk_rmem_alloc));
167         WARN_ON(atomic_read(&sk->sk_wmem_alloc));
168         WARN_ON(sk->sk_wmem_queued);
169         WARN_ON(sk->sk_forward_alloc);
170
171         kfree(rcu_dereference_protected(inet->inet_opt, 1));
172         dst_release(rcu_dereference_check(sk->sk_dst_cache, 1));
173         dst_release(sk->sk_rx_dst);
174         sk_refcnt_debug_dec(sk);
175 }
176 EXPORT_SYMBOL(inet_sock_destruct);
177
178 /*
179  *      The routines beyond this point handle the behaviour of an AF_INET
180  *      socket object. Mostly it punts to the subprotocols of IP to do
181  *      the work.
182  */
183
184 /*
185  *      Automatically bind an unbound socket.
186  */
187
188 static int inet_autobind(struct sock *sk)
189 {
190         struct inet_sock *inet;
191         /* We may need to bind the socket. */
192         lock_sock(sk);
193         inet = inet_sk(sk);
194         if (!inet->inet_num) {
195                 if (sk->sk_prot->get_port(sk, 0)) {
196                         release_sock(sk);
197                         return -EAGAIN;
198                 }
199                 inet->inet_sport = htons(inet->inet_num);
200         }
201         release_sock(sk);
202         return 0;
203 }
204
205 /*
206  *      Move a socket into listening state.
207  */
208 int inet_listen(struct socket *sock, int backlog)
209 {
210         struct sock *sk = sock->sk;
211         unsigned char old_state;
212         int err;
213
214         lock_sock(sk);
215
216         err = -EINVAL;
217         if (sock->state != SS_UNCONNECTED || sock->type != SOCK_STREAM)
218                 goto out;
219
220         old_state = sk->sk_state;
221         if (!((1 << old_state) & (TCPF_CLOSE | TCPF_LISTEN)))
222                 goto out;
223
224         /* Really, if the socket is already in listen state
225          * we can only allow the backlog to be adjusted.
226          */
227         if (old_state != TCP_LISTEN) {
228                 /* Check special setups for testing purpose to enable TFO w/o
229                  * requiring TCP_FASTOPEN sockopt.
230                  * Note that only TCP sockets (SOCK_STREAM) will reach here.
231                  * Also fastopenq may already been allocated because this
232                  * socket was in TCP_LISTEN state previously but was
233                  * shutdown() (rather than close()).
234                  */
235                 if ((sysctl_tcp_fastopen & TFO_SERVER_ENABLE) != 0 &&
236                     inet_csk(sk)->icsk_accept_queue.fastopenq == NULL) {
237                         if ((sysctl_tcp_fastopen & TFO_SERVER_WO_SOCKOPT1) != 0)
238                                 err = fastopen_init_queue(sk, backlog);
239                         else if ((sysctl_tcp_fastopen &
240                                   TFO_SERVER_WO_SOCKOPT2) != 0)
241                                 err = fastopen_init_queue(sk,
242                                     ((uint)sysctl_tcp_fastopen) >> 16);
243                         else
244                                 err = 0;
245                         if (err)
246                                 goto out;
247                 }
248                 err = inet_csk_listen_start(sk, backlog);
249                 if (err)
250                         goto out;
251         }
252         sk->sk_max_ack_backlog = backlog;
253         err = 0;
254
255 out:
256         release_sock(sk);
257         return err;
258 }
259 EXPORT_SYMBOL(inet_listen);
260
261 u32 inet_ehash_secret __read_mostly;
262 EXPORT_SYMBOL(inet_ehash_secret);
263
264 u32 ipv6_hash_secret __read_mostly;
265 EXPORT_SYMBOL(ipv6_hash_secret);
266
267 /*
268  * inet_ehash_secret must be set exactly once, and to a non nul value
269  * ipv6_hash_secret must be set exactly once.
270  */
271 void build_ehash_secret(void)
272 {
273         u32 rnd;
274
275         do {
276                 get_random_bytes(&rnd, sizeof(rnd));
277         } while (rnd == 0);
278
279         if (cmpxchg(&inet_ehash_secret, 0, rnd) == 0)
280                 get_random_bytes(&ipv6_hash_secret, sizeof(ipv6_hash_secret));
281 }
282 EXPORT_SYMBOL(build_ehash_secret);
283
284 /*
285  *      Create an inet socket.
286  */
287
288 static int inet_create(struct net *net, struct socket *sock, int protocol,
289                        int kern)
290 {
291         struct sock *sk;
292         struct inet_protosw *answer;
293         struct inet_sock *inet;
294         struct proto *answer_prot;
295         unsigned char answer_flags;
296         char answer_no_check;
297         int try_loading_module = 0;
298         int err;
299
300         if (!current_has_network())
301                 return -EACCES;
302
303         if (unlikely(!inet_ehash_secret))
304                 if (sock->type != SOCK_RAW && sock->type != SOCK_DGRAM)
305                         build_ehash_secret();
306
307         sock->state = SS_UNCONNECTED;
308
309         /* Look for the requested type/protocol pair. */
310 lookup_protocol:
311         err = -ESOCKTNOSUPPORT;
312         rcu_read_lock();
313         list_for_each_entry_rcu(answer, &inetsw[sock->type], list) {
314
315                 err = 0;
316                 /* Check the non-wild match. */
317                 if (protocol == answer->protocol) {
318                         if (protocol != IPPROTO_IP)
319                                 break;
320                 } else {
321                         /* Check for the two wild cases. */
322                         if (IPPROTO_IP == protocol) {
323                                 protocol = answer->protocol;
324                                 break;
325                         }
326                         if (IPPROTO_IP == answer->protocol)
327                                 break;
328                 }
329                 err = -EPROTONOSUPPORT;
330         }
331
332         if (unlikely(err)) {
333                 if (try_loading_module < 2) {
334                         rcu_read_unlock();
335                         /*
336                          * Be more specific, e.g. net-pf-2-proto-132-type-1
337                          * (net-pf-PF_INET-proto-IPPROTO_SCTP-type-SOCK_STREAM)
338                          */
339                         if (++try_loading_module == 1)
340                                 request_module("net-pf-%d-proto-%d-type-%d",
341                                                PF_INET, protocol, sock->type);
342                         /*
343                          * Fall back to generic, e.g. net-pf-2-proto-132
344                          * (net-pf-PF_INET-proto-IPPROTO_SCTP)
345                          */
346                         else
347                                 request_module("net-pf-%d-proto-%d",
348                                                PF_INET, protocol);
349                         goto lookup_protocol;
350                 } else
351                         goto out_rcu_unlock;
352         }
353
354         err = -EPERM;
355         if (sock->type == SOCK_RAW && !kern && !capable(CAP_NET_RAW))
356                 goto out_rcu_unlock;
357
358         sock->ops = answer->ops;
359         answer_prot = answer->prot;
360         answer_no_check = answer->no_check;
361         answer_flags = answer->flags;
362         rcu_read_unlock();
363
364         WARN_ON(answer_prot->slab == NULL);
365
366         err = -ENOBUFS;
367         sk = sk_alloc(net, PF_INET, GFP_KERNEL, answer_prot);
368         if (sk == NULL)
369                 goto out;
370
371         err = 0;
372         sk->sk_no_check = answer_no_check;
373         if (INET_PROTOSW_REUSE & answer_flags)
374                 sk->sk_reuse = SK_CAN_REUSE;
375
376         inet = inet_sk(sk);
377         inet->is_icsk = (INET_PROTOSW_ICSK & answer_flags) != 0;
378
379         inet->nodefrag = 0;
380
381         if (SOCK_RAW == sock->type) {
382                 inet->inet_num = protocol;
383                 if (IPPROTO_RAW == protocol)
384                         inet->hdrincl = 1;
385         }
386
387         if (ipv4_config.no_pmtu_disc)
388                 inet->pmtudisc = IP_PMTUDISC_DONT;
389         else
390                 inet->pmtudisc = IP_PMTUDISC_WANT;
391
392         inet->inet_id = 0;
393
394         sock_init_data(sock, sk);
395
396         sk->sk_destruct    = inet_sock_destruct;
397         sk->sk_protocol    = protocol;
398         sk->sk_backlog_rcv = sk->sk_prot->backlog_rcv;
399
400         inet->uc_ttl    = -1;
401         inet->mc_loop   = 1;
402         inet->mc_ttl    = 1;
403         inet->mc_all    = 1;
404         inet->mc_index  = 0;
405         inet->mc_list   = NULL;
406         inet->rcv_tos   = 0;
407
408         sk_refcnt_debug_inc(sk);
409
410         if (inet->inet_num) {
411                 /* It assumes that any protocol which allows
412                  * the user to assign a number at socket
413                  * creation time automatically
414                  * shares.
415                  */
416                 inet->inet_sport = htons(inet->inet_num);
417                 /* Add to protocol hash chains. */
418                 sk->sk_prot->hash(sk);
419         }
420
421         if (sk->sk_prot->init) {
422                 err = sk->sk_prot->init(sk);
423                 if (err)
424                         sk_common_release(sk);
425         }
426 out:
427         return err;
428 out_rcu_unlock:
429         rcu_read_unlock();
430         goto out;
431 }
432
433
434 /*
435  *      The peer socket should always be NULL (or else). When we call this
436  *      function we are destroying the object and from then on nobody
437  *      should refer to it.
438  */
439 int inet_release(struct socket *sock)
440 {
441         struct sock *sk = sock->sk;
442
443         if (sk) {
444                 long timeout;
445
446                 sock_rps_reset_flow(sk);
447
448                 /* Applications forget to leave groups before exiting */
449                 ip_mc_drop_socket(sk);
450
451                 /* If linger is set, we don't return until the close
452                  * is complete.  Otherwise we return immediately. The
453                  * actually closing is done the same either way.
454                  *
455                  * If the close is due to the process exiting, we never
456                  * linger..
457                  */
458                 timeout = 0;
459                 if (sock_flag(sk, SOCK_LINGER) &&
460                     !(current->flags & PF_EXITING))
461                         timeout = sk->sk_lingertime;
462                 sock->sk = NULL;
463                 sk->sk_prot->close(sk, timeout);
464         }
465         return 0;
466 }
467 EXPORT_SYMBOL(inet_release);
468
469 /* It is off by default, see below. */
470 int sysctl_ip_nonlocal_bind __read_mostly;
471 EXPORT_SYMBOL(sysctl_ip_nonlocal_bind);
472
473 int inet_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
474 {
475         struct sockaddr_in *addr = (struct sockaddr_in *)uaddr;
476         struct sock *sk = sock->sk;
477         struct inet_sock *inet = inet_sk(sk);
478         struct net *net = sock_net(sk);
479         unsigned short snum;
480         int chk_addr_ret;
481         int err;
482
483         /* If the socket has its own bind function then use it. (RAW) */
484         if (sk->sk_prot->bind) {
485                 err = sk->sk_prot->bind(sk, uaddr, addr_len);
486                 goto out;
487         }
488         err = -EINVAL;
489         if (addr_len < sizeof(struct sockaddr_in))
490                 goto out;
491
492         if (addr->sin_family != AF_INET) {
493                 /* Compatibility games : accept AF_UNSPEC (mapped to AF_INET)
494                  * only if s_addr is INADDR_ANY.
495                  */
496                 err = -EAFNOSUPPORT;
497                 if (addr->sin_family != AF_UNSPEC ||
498                     addr->sin_addr.s_addr != htonl(INADDR_ANY))
499                         goto out;
500         }
501
502         chk_addr_ret = inet_addr_type(net, addr->sin_addr.s_addr);
503
504         /* Not specified by any standard per-se, however it breaks too
505          * many applications when removed.  It is unfortunate since
506          * allowing applications to make a non-local bind solves
507          * several problems with systems using dynamic addressing.
508          * (ie. your servers still start up even if your ISDN link
509          *  is temporarily down)
510          */
511         err = -EADDRNOTAVAIL;
512         if (!sysctl_ip_nonlocal_bind &&
513             !(inet->freebind || inet->transparent) &&
514             addr->sin_addr.s_addr != htonl(INADDR_ANY) &&
515             chk_addr_ret != RTN_LOCAL &&
516             chk_addr_ret != RTN_MULTICAST &&
517             chk_addr_ret != RTN_BROADCAST)
518                 goto out;
519
520         snum = ntohs(addr->sin_port);
521         err = -EACCES;
522         if (snum && snum < PROT_SOCK &&
523             !ns_capable(net->user_ns, CAP_NET_BIND_SERVICE))
524                 goto out;
525
526         /*      We keep a pair of addresses. rcv_saddr is the one
527          *      used by hash lookups, and saddr is used for transmit.
528          *
529          *      In the BSD API these are the same except where it
530          *      would be illegal to use them (multicast/broadcast) in
531          *      which case the sending device address is used.
532          */
533         lock_sock(sk);
534
535         /* Check these errors (active socket, double bind). */
536         err = -EINVAL;
537         if (sk->sk_state != TCP_CLOSE || inet->inet_num)
538                 goto out_release_sock;
539
540         inet->inet_rcv_saddr = inet->inet_saddr = addr->sin_addr.s_addr;
541         if (chk_addr_ret == RTN_MULTICAST || chk_addr_ret == RTN_BROADCAST)
542                 inet->inet_saddr = 0;  /* Use device */
543
544         /* Make sure we are allowed to bind here. */
545         if (sk->sk_prot->get_port(sk, snum)) {
546                 inet->inet_saddr = inet->inet_rcv_saddr = 0;
547                 err = -EADDRINUSE;
548                 goto out_release_sock;
549         }
550
551         if (inet->inet_rcv_saddr)
552                 sk->sk_userlocks |= SOCK_BINDADDR_LOCK;
553         if (snum)
554                 sk->sk_userlocks |= SOCK_BINDPORT_LOCK;
555         inet->inet_sport = htons(inet->inet_num);
556         inet->inet_daddr = 0;
557         inet->inet_dport = 0;
558         sk_dst_reset(sk);
559         err = 0;
560 out_release_sock:
561         release_sock(sk);
562 out:
563         return err;
564 }
565 EXPORT_SYMBOL(inet_bind);
566
567 int inet_dgram_connect(struct socket *sock, struct sockaddr *uaddr,
568                        int addr_len, int flags)
569 {
570         struct sock *sk = sock->sk;
571
572         if (addr_len < sizeof(uaddr->sa_family))
573                 return -EINVAL;
574         if (uaddr->sa_family == AF_UNSPEC)
575                 return sk->sk_prot->disconnect(sk, flags);
576
577         if (!inet_sk(sk)->inet_num && inet_autobind(sk))
578                 return -EAGAIN;
579         return sk->sk_prot->connect(sk, uaddr, addr_len);
580 }
581 EXPORT_SYMBOL(inet_dgram_connect);
582
583 static long inet_wait_for_connect(struct sock *sk, long timeo, int writebias)
584 {
585         DEFINE_WAIT(wait);
586
587         prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
588         sk->sk_write_pending += writebias;
589
590         /* Basic assumption: if someone sets sk->sk_err, he _must_
591          * change state of the socket from TCP_SYN_*.
592          * Connect() does not allow to get error notifications
593          * without closing the socket.
594          */
595         while ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) {
596                 release_sock(sk);
597                 timeo = schedule_timeout(timeo);
598                 lock_sock(sk);
599                 if (signal_pending(current) || !timeo)
600                         break;
601                 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
602         }
603         finish_wait(sk_sleep(sk), &wait);
604         sk->sk_write_pending -= writebias;
605         return timeo;
606 }
607
608 /*
609  *      Connect to a remote host. There is regrettably still a little
610  *      TCP 'magic' in here.
611  */
612 int __inet_stream_connect(struct socket *sock, struct sockaddr *uaddr,
613                           int addr_len, int flags)
614 {
615         struct sock *sk = sock->sk;
616         int err;
617         long timeo;
618
619         if (addr_len < sizeof(uaddr->sa_family))
620                 return -EINVAL;
621
622         if (uaddr->sa_family == AF_UNSPEC) {
623                 err = sk->sk_prot->disconnect(sk, flags);
624                 sock->state = err ? SS_DISCONNECTING : SS_UNCONNECTED;
625                 goto out;
626         }
627
628         switch (sock->state) {
629         default:
630                 err = -EINVAL;
631                 goto out;
632         case SS_CONNECTED:
633                 err = -EISCONN;
634                 goto out;
635         case SS_CONNECTING:
636                 err = -EALREADY;
637                 /* Fall out of switch with err, set for this state */
638                 break;
639         case SS_UNCONNECTED:
640                 err = -EISCONN;
641                 if (sk->sk_state != TCP_CLOSE)
642                         goto out;
643
644                 err = sk->sk_prot->connect(sk, uaddr, addr_len);
645                 if (err < 0)
646                         goto out;
647
648                 sock->state = SS_CONNECTING;
649
650                 /* Just entered SS_CONNECTING state; the only
651                  * difference is that return value in non-blocking
652                  * case is EINPROGRESS, rather than EALREADY.
653                  */
654                 err = -EINPROGRESS;
655                 break;
656         }
657
658         timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
659
660         if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) {
661                 int writebias = (sk->sk_protocol == IPPROTO_TCP) &&
662                                 tcp_sk(sk)->fastopen_req &&
663                                 tcp_sk(sk)->fastopen_req->data ? 1 : 0;
664
665                 /* Error code is set above */
666                 if (!timeo || !inet_wait_for_connect(sk, timeo, writebias))
667                         goto out;
668
669                 err = sock_intr_errno(timeo);
670                 if (signal_pending(current))
671                         goto out;
672         }
673
674         /* Connection was closed by RST, timeout, ICMP error
675          * or another process disconnected us.
676          */
677         if (sk->sk_state == TCP_CLOSE)
678                 goto sock_error;
679
680         /* sk->sk_err may be not zero now, if RECVERR was ordered by user
681          * and error was received after socket entered established state.
682          * Hence, it is handled normally after connect() return successfully.
683          */
684
685         sock->state = SS_CONNECTED;
686         err = 0;
687 out:
688         return err;
689
690 sock_error:
691         err = sock_error(sk) ? : -ECONNABORTED;
692         sock->state = SS_UNCONNECTED;
693         if (sk->sk_prot->disconnect(sk, flags))
694                 sock->state = SS_DISCONNECTING;
695         goto out;
696 }
697 EXPORT_SYMBOL(__inet_stream_connect);
698
699 int inet_stream_connect(struct socket *sock, struct sockaddr *uaddr,
700                         int addr_len, int flags)
701 {
702         int err;
703
704         lock_sock(sock->sk);
705         err = __inet_stream_connect(sock, uaddr, addr_len, flags);
706         release_sock(sock->sk);
707         return err;
708 }
709 EXPORT_SYMBOL(inet_stream_connect);
710
711 /*
712  *      Accept a pending connection. The TCP layer now gives BSD semantics.
713  */
714
715 int inet_accept(struct socket *sock, struct socket *newsock, int flags)
716 {
717         struct sock *sk1 = sock->sk;
718         int err = -EINVAL;
719         struct sock *sk2 = sk1->sk_prot->accept(sk1, flags, &err);
720
721         if (!sk2)
722                 goto do_err;
723
724         lock_sock(sk2);
725
726         sock_rps_record_flow(sk2);
727         WARN_ON(!((1 << sk2->sk_state) &
728                   (TCPF_ESTABLISHED | TCPF_SYN_RECV |
729                   TCPF_CLOSE_WAIT | TCPF_CLOSE)));
730
731         sock_graft(sk2, newsock);
732
733         newsock->state = SS_CONNECTED;
734         err = 0;
735         release_sock(sk2);
736 do_err:
737         return err;
738 }
739 EXPORT_SYMBOL(inet_accept);
740
741
742 /*
743  *      This does both peername and sockname.
744  */
745 int inet_getname(struct socket *sock, struct sockaddr *uaddr,
746                         int *uaddr_len, int peer)
747 {
748         struct sock *sk         = sock->sk;
749         struct inet_sock *inet  = inet_sk(sk);
750         DECLARE_SOCKADDR(struct sockaddr_in *, sin, uaddr);
751
752         sin->sin_family = AF_INET;
753         if (peer) {
754                 if (!inet->inet_dport ||
755                     (((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_SYN_SENT)) &&
756                      peer == 1))
757                         return -ENOTCONN;
758                 sin->sin_port = inet->inet_dport;
759                 sin->sin_addr.s_addr = inet->inet_daddr;
760         } else {
761                 __be32 addr = inet->inet_rcv_saddr;
762                 if (!addr)
763                         addr = inet->inet_saddr;
764                 sin->sin_port = inet->inet_sport;
765                 sin->sin_addr.s_addr = addr;
766         }
767         memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
768         *uaddr_len = sizeof(*sin);
769         return 0;
770 }
771 EXPORT_SYMBOL(inet_getname);
772
773 int inet_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg,
774                  size_t size)
775 {
776         struct sock *sk = sock->sk;
777
778         sock_rps_record_flow(sk);
779
780         /* We may need to bind the socket. */
781         if (!inet_sk(sk)->inet_num && !sk->sk_prot->no_autobind &&
782             inet_autobind(sk))
783                 return -EAGAIN;
784
785         return sk->sk_prot->sendmsg(iocb, sk, msg, size);
786 }
787 EXPORT_SYMBOL(inet_sendmsg);
788
789 ssize_t inet_sendpage(struct socket *sock, struct page *page, int offset,
790                       size_t size, int flags)
791 {
792         struct sock *sk = sock->sk;
793
794         sock_rps_record_flow(sk);
795
796         /* We may need to bind the socket. */
797         if (!inet_sk(sk)->inet_num && !sk->sk_prot->no_autobind &&
798             inet_autobind(sk))
799                 return -EAGAIN;
800
801         if (sk->sk_prot->sendpage)
802                 return sk->sk_prot->sendpage(sk, page, offset, size, flags);
803         return sock_no_sendpage(sock, page, offset, size, flags);
804 }
805 EXPORT_SYMBOL(inet_sendpage);
806
807 int inet_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg,
808                  size_t size, int flags)
809 {
810         struct sock *sk = sock->sk;
811         int addr_len = 0;
812         int err;
813
814         sock_rps_record_flow(sk);
815
816         err = sk->sk_prot->recvmsg(iocb, sk, msg, size, flags & MSG_DONTWAIT,
817                                    flags & ~MSG_DONTWAIT, &addr_len);
818         if (err >= 0)
819                 msg->msg_namelen = addr_len;
820         return err;
821 }
822 EXPORT_SYMBOL(inet_recvmsg);
823
824 int inet_shutdown(struct socket *sock, int how)
825 {
826         struct sock *sk = sock->sk;
827         int err = 0;
828
829         /* This should really check to make sure
830          * the socket is a TCP socket. (WHY AC...)
831          */
832         how++; /* maps 0->1 has the advantage of making bit 1 rcvs and
833                        1->2 bit 2 snds.
834                        2->3 */
835         if ((how & ~SHUTDOWN_MASK) || !how)     /* MAXINT->0 */
836                 return -EINVAL;
837
838         lock_sock(sk);
839         if (sock->state == SS_CONNECTING) {
840                 if ((1 << sk->sk_state) &
841                     (TCPF_SYN_SENT | TCPF_SYN_RECV | TCPF_CLOSE))
842                         sock->state = SS_DISCONNECTING;
843                 else
844                         sock->state = SS_CONNECTED;
845         }
846
847         switch (sk->sk_state) {
848         case TCP_CLOSE:
849                 err = -ENOTCONN;
850                 /* Hack to wake up other listeners, who can poll for
851                    POLLHUP, even on eg. unconnected UDP sockets -- RR */
852         default:
853                 sk->sk_shutdown |= how;
854                 if (sk->sk_prot->shutdown)
855                         sk->sk_prot->shutdown(sk, how);
856                 break;
857
858         /* Remaining two branches are temporary solution for missing
859          * close() in multithreaded environment. It is _not_ a good idea,
860          * but we have no choice until close() is repaired at VFS level.
861          */
862         case TCP_LISTEN:
863                 if (!(how & RCV_SHUTDOWN))
864                         break;
865                 /* Fall through */
866         case TCP_SYN_SENT:
867                 err = sk->sk_prot->disconnect(sk, O_NONBLOCK);
868                 sock->state = err ? SS_DISCONNECTING : SS_UNCONNECTED;
869                 break;
870         }
871
872         /* Wake up anyone sleeping in poll. */
873         sk->sk_state_change(sk);
874         release_sock(sk);
875         return err;
876 }
877 EXPORT_SYMBOL(inet_shutdown);
878
879 /*
880  *      ioctl() calls you can issue on an INET socket. Most of these are
881  *      device configuration and stuff and very rarely used. Some ioctls
882  *      pass on to the socket itself.
883  *
884  *      NOTE: I like the idea of a module for the config stuff. ie ifconfig
885  *      loads the devconfigure module does its configuring and unloads it.
886  *      There's a good 20K of config code hanging around the kernel.
887  */
888
889 int inet_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
890 {
891         struct sock *sk = sock->sk;
892         int err = 0;
893         struct net *net = sock_net(sk);
894
895         switch (cmd) {
896         case SIOCGSTAMP:
897                 err = sock_get_timestamp(sk, (struct timeval __user *)arg);
898                 break;
899         case SIOCGSTAMPNS:
900                 err = sock_get_timestampns(sk, (struct timespec __user *)arg);
901                 break;
902         case SIOCADDRT:
903         case SIOCDELRT:
904         case SIOCRTMSG:
905                 err = ip_rt_ioctl(net, cmd, (void __user *)arg);
906                 break;
907         case SIOCDARP:
908         case SIOCGARP:
909         case SIOCSARP:
910                 err = arp_ioctl(net, cmd, (void __user *)arg);
911                 break;
912         case SIOCGIFADDR:
913         case SIOCSIFADDR:
914         case SIOCGIFBRDADDR:
915         case SIOCSIFBRDADDR:
916         case SIOCGIFNETMASK:
917         case SIOCSIFNETMASK:
918         case SIOCGIFDSTADDR:
919         case SIOCSIFDSTADDR:
920         case SIOCSIFPFLAGS:
921         case SIOCGIFPFLAGS:
922         case SIOCSIFFLAGS:
923         case SIOCKILLADDR:
924                 err = devinet_ioctl(net, cmd, (void __user *)arg);
925                 break;
926         default:
927                 if (sk->sk_prot->ioctl)
928                         err = sk->sk_prot->ioctl(sk, cmd, arg);
929                 else
930                         err = -ENOIOCTLCMD;
931                 break;
932         }
933         return err;
934 }
935 EXPORT_SYMBOL(inet_ioctl);
936
937 #ifdef CONFIG_COMPAT
938 static int inet_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
939 {
940         struct sock *sk = sock->sk;
941         int err = -ENOIOCTLCMD;
942
943         if (sk->sk_prot->compat_ioctl)
944                 err = sk->sk_prot->compat_ioctl(sk, cmd, arg);
945
946         return err;
947 }
948 #endif
949
950 const struct proto_ops inet_stream_ops = {
951         .family            = PF_INET,
952         .owner             = THIS_MODULE,
953         .release           = inet_release,
954         .bind              = inet_bind,
955         .connect           = inet_stream_connect,
956         .socketpair        = sock_no_socketpair,
957         .accept            = inet_accept,
958         .getname           = inet_getname,
959         .poll              = tcp_poll,
960         .ioctl             = inet_ioctl,
961         .listen            = inet_listen,
962         .shutdown          = inet_shutdown,
963         .setsockopt        = sock_common_setsockopt,
964         .getsockopt        = sock_common_getsockopt,
965         .sendmsg           = inet_sendmsg,
966         .recvmsg           = inet_recvmsg,
967         .mmap              = sock_no_mmap,
968         .sendpage          = inet_sendpage,
969         .splice_read       = tcp_splice_read,
970 #ifdef CONFIG_COMPAT
971         .compat_setsockopt = compat_sock_common_setsockopt,
972         .compat_getsockopt = compat_sock_common_getsockopt,
973         .compat_ioctl      = inet_compat_ioctl,
974 #endif
975 };
976 EXPORT_SYMBOL(inet_stream_ops);
977
978 const struct proto_ops inet_dgram_ops = {
979         .family            = PF_INET,
980         .owner             = THIS_MODULE,
981         .release           = inet_release,
982         .bind              = inet_bind,
983         .connect           = inet_dgram_connect,
984         .socketpair        = sock_no_socketpair,
985         .accept            = sock_no_accept,
986         .getname           = inet_getname,
987         .poll              = udp_poll,
988         .ioctl             = inet_ioctl,
989         .listen            = sock_no_listen,
990         .shutdown          = inet_shutdown,
991         .setsockopt        = sock_common_setsockopt,
992         .getsockopt        = sock_common_getsockopt,
993         .sendmsg           = inet_sendmsg,
994         .recvmsg           = inet_recvmsg,
995         .mmap              = sock_no_mmap,
996         .sendpage          = inet_sendpage,
997 #ifdef CONFIG_COMPAT
998         .compat_setsockopt = compat_sock_common_setsockopt,
999         .compat_getsockopt = compat_sock_common_getsockopt,
1000         .compat_ioctl      = inet_compat_ioctl,
1001 #endif
1002 };
1003 EXPORT_SYMBOL(inet_dgram_ops);
1004
1005 /*
1006  * For SOCK_RAW sockets; should be the same as inet_dgram_ops but without
1007  * udp_poll
1008  */
1009 static const struct proto_ops inet_sockraw_ops = {
1010         .family            = PF_INET,
1011         .owner             = THIS_MODULE,
1012         .release           = inet_release,
1013         .bind              = inet_bind,
1014         .connect           = inet_dgram_connect,
1015         .socketpair        = sock_no_socketpair,
1016         .accept            = sock_no_accept,
1017         .getname           = inet_getname,
1018         .poll              = datagram_poll,
1019         .ioctl             = inet_ioctl,
1020         .listen            = sock_no_listen,
1021         .shutdown          = inet_shutdown,
1022         .setsockopt        = sock_common_setsockopt,
1023         .getsockopt        = sock_common_getsockopt,
1024         .sendmsg           = inet_sendmsg,
1025         .recvmsg           = inet_recvmsg,
1026         .mmap              = sock_no_mmap,
1027         .sendpage          = inet_sendpage,
1028 #ifdef CONFIG_COMPAT
1029         .compat_setsockopt = compat_sock_common_setsockopt,
1030         .compat_getsockopt = compat_sock_common_getsockopt,
1031         .compat_ioctl      = inet_compat_ioctl,
1032 #endif
1033 };
1034
1035 static const struct net_proto_family inet_family_ops = {
1036         .family = PF_INET,
1037         .create = inet_create,
1038         .owner  = THIS_MODULE,
1039 };
1040
1041 /* Upon startup we insert all the elements in inetsw_array[] into
1042  * the linked list inetsw.
1043  */
1044 static struct inet_protosw inetsw_array[] =
1045 {
1046         {
1047                 .type =       SOCK_STREAM,
1048                 .protocol =   IPPROTO_TCP,
1049                 .prot =       &tcp_prot,
1050                 .ops =        &inet_stream_ops,
1051                 .no_check =   0,
1052                 .flags =      INET_PROTOSW_PERMANENT |
1053                               INET_PROTOSW_ICSK,
1054         },
1055
1056         {
1057                 .type =       SOCK_DGRAM,
1058                 .protocol =   IPPROTO_UDP,
1059                 .prot =       &udp_prot,
1060                 .ops =        &inet_dgram_ops,
1061                 .no_check =   UDP_CSUM_DEFAULT,
1062                 .flags =      INET_PROTOSW_PERMANENT,
1063        },
1064
1065        {
1066                 .type =       SOCK_DGRAM,
1067                 .protocol =   IPPROTO_ICMP,
1068                 .prot =       &ping_prot,
1069                 .ops =        &inet_dgram_ops,
1070                 .no_check =   UDP_CSUM_DEFAULT,
1071                 .flags =      INET_PROTOSW_REUSE,
1072        },
1073
1074        {
1075                .type =       SOCK_RAW,
1076                .protocol =   IPPROTO_IP,        /* wild card */
1077                .prot =       &raw_prot,
1078                .ops =        &inet_sockraw_ops,
1079                .no_check =   UDP_CSUM_DEFAULT,
1080                .flags =      INET_PROTOSW_REUSE,
1081        }
1082 };
1083
1084 #define INETSW_ARRAY_LEN ARRAY_SIZE(inetsw_array)
1085
1086 void inet_register_protosw(struct inet_protosw *p)
1087 {
1088         struct list_head *lh;
1089         struct inet_protosw *answer;
1090         int protocol = p->protocol;
1091         struct list_head *last_perm;
1092
1093         spin_lock_bh(&inetsw_lock);
1094
1095         if (p->type >= SOCK_MAX)
1096                 goto out_illegal;
1097
1098         /* If we are trying to override a permanent protocol, bail. */
1099         answer = NULL;
1100         last_perm = &inetsw[p->type];
1101         list_for_each(lh, &inetsw[p->type]) {
1102                 answer = list_entry(lh, struct inet_protosw, list);
1103
1104                 /* Check only the non-wild match. */
1105                 if (INET_PROTOSW_PERMANENT & answer->flags) {
1106                         if (protocol == answer->protocol)
1107                                 break;
1108                         last_perm = lh;
1109                 }
1110
1111                 answer = NULL;
1112         }
1113         if (answer)
1114                 goto out_permanent;
1115
1116         /* Add the new entry after the last permanent entry if any, so that
1117          * the new entry does not override a permanent entry when matched with
1118          * a wild-card protocol. But it is allowed to override any existing
1119          * non-permanent entry.  This means that when we remove this entry, the
1120          * system automatically returns to the old behavior.
1121          */
1122         list_add_rcu(&p->list, last_perm);
1123 out:
1124         spin_unlock_bh(&inetsw_lock);
1125
1126         return;
1127
1128 out_permanent:
1129         pr_err("Attempt to override permanent protocol %d\n", protocol);
1130         goto out;
1131
1132 out_illegal:
1133         pr_err("Ignoring attempt to register invalid socket type %d\n",
1134                p->type);
1135         goto out;
1136 }
1137 EXPORT_SYMBOL(inet_register_protosw);
1138
1139 void inet_unregister_protosw(struct inet_protosw *p)
1140 {
1141         if (INET_PROTOSW_PERMANENT & p->flags) {
1142                 pr_err("Attempt to unregister permanent protocol %d\n",
1143                        p->protocol);
1144         } else {
1145                 spin_lock_bh(&inetsw_lock);
1146                 list_del_rcu(&p->list);
1147                 spin_unlock_bh(&inetsw_lock);
1148
1149                 synchronize_net();
1150         }
1151 }
1152 EXPORT_SYMBOL(inet_unregister_protosw);
1153
1154 /*
1155  *      Shall we try to damage output packets if routing dev changes?
1156  */
1157
1158 int sysctl_ip_dynaddr __read_mostly;
1159
1160 static int inet_sk_reselect_saddr(struct sock *sk)
1161 {
1162         struct inet_sock *inet = inet_sk(sk);
1163         __be32 old_saddr = inet->inet_saddr;
1164         __be32 daddr = inet->inet_daddr;
1165         struct flowi4 *fl4;
1166         struct rtable *rt;
1167         __be32 new_saddr;
1168         struct ip_options_rcu *inet_opt;
1169
1170         inet_opt = rcu_dereference_protected(inet->inet_opt,
1171                                              sock_owned_by_user(sk));
1172         if (inet_opt && inet_opt->opt.srr)
1173                 daddr = inet_opt->opt.faddr;
1174
1175         /* Query new route. */
1176         fl4 = &inet->cork.fl.u.ip4;
1177         rt = ip_route_connect(fl4, daddr, 0, RT_CONN_FLAGS(sk),
1178                               sk->sk_bound_dev_if, sk->sk_protocol,
1179                               inet->inet_sport, inet->inet_dport, sk, false);
1180         if (IS_ERR(rt))
1181                 return PTR_ERR(rt);
1182
1183         sk_setup_caps(sk, &rt->dst);
1184
1185         new_saddr = fl4->saddr;
1186
1187         if (new_saddr == old_saddr)
1188                 return 0;
1189
1190         if (sysctl_ip_dynaddr > 1) {
1191                 pr_info("%s(): shifting inet->saddr from %pI4 to %pI4\n",
1192                         __func__, &old_saddr, &new_saddr);
1193         }
1194
1195         inet->inet_saddr = inet->inet_rcv_saddr = new_saddr;
1196
1197         /*
1198          * XXX The only one ugly spot where we need to
1199          * XXX really change the sockets identity after
1200          * XXX it has entered the hashes. -DaveM
1201          *
1202          * Besides that, it does not check for connection
1203          * uniqueness. Wait for troubles.
1204          */
1205         __sk_prot_rehash(sk);
1206         return 0;
1207 }
1208
1209 int inet_sk_rebuild_header(struct sock *sk)
1210 {
1211         struct inet_sock *inet = inet_sk(sk);
1212         struct rtable *rt = (struct rtable *)__sk_dst_check(sk, 0);
1213         __be32 daddr;
1214         struct ip_options_rcu *inet_opt;
1215         struct flowi4 *fl4;
1216         int err;
1217
1218         /* Route is OK, nothing to do. */
1219         if (rt)
1220                 return 0;
1221
1222         /* Reroute. */
1223         rcu_read_lock();
1224         inet_opt = rcu_dereference(inet->inet_opt);
1225         daddr = inet->inet_daddr;
1226         if (inet_opt && inet_opt->opt.srr)
1227                 daddr = inet_opt->opt.faddr;
1228         rcu_read_unlock();
1229         fl4 = &inet->cork.fl.u.ip4;
1230         rt = ip_route_output_ports(sock_net(sk), fl4, sk, daddr, inet->inet_saddr,
1231                                    inet->inet_dport, inet->inet_sport,
1232                                    sk->sk_protocol, RT_CONN_FLAGS(sk),
1233                                    sk->sk_bound_dev_if);
1234         if (!IS_ERR(rt)) {
1235                 err = 0;
1236                 sk_setup_caps(sk, &rt->dst);
1237         } else {
1238                 err = PTR_ERR(rt);
1239
1240                 /* Routing failed... */
1241                 sk->sk_route_caps = 0;
1242                 /*
1243                  * Other protocols have to map its equivalent state to TCP_SYN_SENT.
1244                  * DCCP maps its DCCP_REQUESTING state to TCP_SYN_SENT. -acme
1245                  */
1246                 if (!sysctl_ip_dynaddr ||
1247                     sk->sk_state != TCP_SYN_SENT ||
1248                     (sk->sk_userlocks & SOCK_BINDADDR_LOCK) ||
1249                     (err = inet_sk_reselect_saddr(sk)) != 0)
1250                         sk->sk_err_soft = -err;
1251         }
1252
1253         return err;
1254 }
1255 EXPORT_SYMBOL(inet_sk_rebuild_header);
1256
1257 static int inet_gso_send_check(struct sk_buff *skb)
1258 {
1259         const struct net_offload *ops;
1260         const struct iphdr *iph;
1261         int proto;
1262         int ihl;
1263         int err = -EINVAL;
1264
1265         if (unlikely(!pskb_may_pull(skb, sizeof(*iph))))
1266                 goto out;
1267
1268         iph = ip_hdr(skb);
1269         ihl = iph->ihl * 4;
1270         if (ihl < sizeof(*iph))
1271                 goto out;
1272
1273         if (unlikely(!pskb_may_pull(skb, ihl)))
1274                 goto out;
1275
1276         __skb_pull(skb, ihl);
1277         skb_reset_transport_header(skb);
1278         iph = ip_hdr(skb);
1279         proto = iph->protocol;
1280         err = -EPROTONOSUPPORT;
1281
1282         rcu_read_lock();
1283         ops = rcu_dereference(inet_offloads[proto]);
1284         if (likely(ops && ops->callbacks.gso_send_check))
1285                 err = ops->callbacks.gso_send_check(skb);
1286         rcu_read_unlock();
1287
1288 out:
1289         return err;
1290 }
1291
1292 static struct sk_buff *inet_gso_segment(struct sk_buff *skb,
1293         netdev_features_t features)
1294 {
1295         struct sk_buff *segs = ERR_PTR(-EINVAL);
1296         const struct net_offload *ops;
1297         struct iphdr *iph;
1298         int proto;
1299         int ihl;
1300         int id;
1301         unsigned int offset = 0;
1302         bool tunnel;
1303
1304         if (unlikely(skb_shinfo(skb)->gso_type &
1305                      ~(SKB_GSO_TCPV4 |
1306                        SKB_GSO_UDP |
1307                        SKB_GSO_DODGY |
1308                        SKB_GSO_TCP_ECN |
1309                        SKB_GSO_GRE |
1310                        SKB_GSO_TCPV6 |
1311                        SKB_GSO_UDP_TUNNEL |
1312                        0)))
1313                 goto out;
1314
1315         if (unlikely(!pskb_may_pull(skb, sizeof(*iph))))
1316                 goto out;
1317
1318         iph = ip_hdr(skb);
1319         ihl = iph->ihl * 4;
1320         if (ihl < sizeof(*iph))
1321                 goto out;
1322
1323         if (unlikely(!pskb_may_pull(skb, ihl)))
1324                 goto out;
1325
1326         tunnel = !!skb->encapsulation;
1327
1328         __skb_pull(skb, ihl);
1329         skb_reset_transport_header(skb);
1330         iph = ip_hdr(skb);
1331         id = ntohs(iph->id);
1332         proto = iph->protocol;
1333         segs = ERR_PTR(-EPROTONOSUPPORT);
1334
1335         rcu_read_lock();
1336         ops = rcu_dereference(inet_offloads[proto]);
1337         if (likely(ops && ops->callbacks.gso_segment))
1338                 segs = ops->callbacks.gso_segment(skb, features);
1339         rcu_read_unlock();
1340
1341         if (IS_ERR_OR_NULL(segs))
1342                 goto out;
1343
1344         skb = segs;
1345         do {
1346                 iph = ip_hdr(skb);
1347                 if (!tunnel && proto == IPPROTO_UDP) {
1348                         iph->id = htons(id);
1349                         iph->frag_off = htons(offset >> 3);
1350                         if (skb->next != NULL)
1351                                 iph->frag_off |= htons(IP_MF);
1352                         offset += (skb->len - skb->mac_len - iph->ihl * 4);
1353                 } else  {
1354                         iph->id = htons(id++);
1355                 }
1356                 iph->tot_len = htons(skb->len - skb->mac_len);
1357                 iph->check = 0;
1358                 iph->check = ip_fast_csum(skb_network_header(skb), iph->ihl);
1359         } while ((skb = skb->next));
1360
1361 out:
1362         return segs;
1363 }
1364
1365 static struct sk_buff **inet_gro_receive(struct sk_buff **head,
1366                                          struct sk_buff *skb)
1367 {
1368         const struct net_offload *ops;
1369         struct sk_buff **pp = NULL;
1370         struct sk_buff *p;
1371         const struct iphdr *iph;
1372         unsigned int hlen;
1373         unsigned int off;
1374         unsigned int id;
1375         int flush = 1;
1376         int proto;
1377
1378         off = skb_gro_offset(skb);
1379         hlen = off + sizeof(*iph);
1380         iph = skb_gro_header_fast(skb, off);
1381         if (skb_gro_header_hard(skb, hlen)) {
1382                 iph = skb_gro_header_slow(skb, hlen, off);
1383                 if (unlikely(!iph))
1384                         goto out;
1385         }
1386
1387         proto = iph->protocol;
1388
1389         rcu_read_lock();
1390         ops = rcu_dereference(inet_offloads[proto]);
1391         if (!ops || !ops->callbacks.gro_receive)
1392                 goto out_unlock;
1393
1394         if (*(u8 *)iph != 0x45)
1395                 goto out_unlock;
1396
1397         if (unlikely(ip_fast_csum((u8 *)iph, 5)))
1398                 goto out_unlock;
1399
1400         id = ntohl(*(__be32 *)&iph->id);
1401         flush = (u16)((ntohl(*(__be32 *)iph) ^ skb_gro_len(skb)) | (id ^ IP_DF));
1402         id >>= 16;
1403
1404         for (p = *head; p; p = p->next) {
1405                 struct iphdr *iph2;
1406
1407                 if (!NAPI_GRO_CB(p)->same_flow)
1408                         continue;
1409
1410                 iph2 = ip_hdr(p);
1411
1412                 if ((iph->protocol ^ iph2->protocol) |
1413                     ((__force u32)iph->saddr ^ (__force u32)iph2->saddr) |
1414                     ((__force u32)iph->daddr ^ (__force u32)iph2->daddr)) {
1415                         NAPI_GRO_CB(p)->same_flow = 0;
1416                         continue;
1417                 }
1418
1419                 /* All fields must match except length and checksum. */
1420                 NAPI_GRO_CB(p)->flush |=
1421                         (iph->ttl ^ iph2->ttl) |
1422                         (iph->tos ^ iph2->tos) |
1423                         ((u16)(ntohs(iph2->id) + NAPI_GRO_CB(p)->count) ^ id);
1424
1425                 NAPI_GRO_CB(p)->flush |= flush;
1426         }
1427
1428         NAPI_GRO_CB(skb)->flush |= flush;
1429         skb_gro_pull(skb, sizeof(*iph));
1430         skb_set_transport_header(skb, skb_gro_offset(skb));
1431
1432         pp = ops->callbacks.gro_receive(head, skb);
1433
1434 out_unlock:
1435         rcu_read_unlock();
1436
1437 out:
1438         NAPI_GRO_CB(skb)->flush |= flush;
1439
1440         return pp;
1441 }
1442
1443 static int inet_gro_complete(struct sk_buff *skb)
1444 {
1445         __be16 newlen = htons(skb->len - skb_network_offset(skb));
1446         struct iphdr *iph = ip_hdr(skb);
1447         const struct net_offload *ops;
1448         int proto = iph->protocol;
1449         int err = -ENOSYS;
1450
1451         csum_replace2(&iph->check, iph->tot_len, newlen);
1452         iph->tot_len = newlen;
1453
1454         rcu_read_lock();
1455         ops = rcu_dereference(inet_offloads[proto]);
1456         if (WARN_ON(!ops || !ops->callbacks.gro_complete))
1457                 goto out_unlock;
1458
1459         err = ops->callbacks.gro_complete(skb);
1460
1461 out_unlock:
1462         rcu_read_unlock();
1463
1464         return err;
1465 }
1466
1467 int inet_ctl_sock_create(struct sock **sk, unsigned short family,
1468                          unsigned short type, unsigned char protocol,
1469                          struct net *net)
1470 {
1471         struct socket *sock;
1472         int rc = sock_create_kern(family, type, protocol, &sock);
1473
1474         if (rc == 0) {
1475                 *sk = sock->sk;
1476                 (*sk)->sk_allocation = GFP_ATOMIC;
1477                 /*
1478                  * Unhash it so that IP input processing does not even see it,
1479                  * we do not wish this socket to see incoming packets.
1480                  */
1481                 (*sk)->sk_prot->unhash(*sk);
1482
1483                 sk_change_net(*sk, net);
1484         }
1485         return rc;
1486 }
1487 EXPORT_SYMBOL_GPL(inet_ctl_sock_create);
1488
1489 unsigned long snmp_fold_field(void __percpu *mib[], int offt)
1490 {
1491         unsigned long res = 0;
1492         int i, j;
1493
1494         for_each_possible_cpu(i) {
1495                 for (j = 0; j < SNMP_ARRAY_SZ; j++)
1496                         res += *(((unsigned long *) per_cpu_ptr(mib[j], i)) + offt);
1497         }
1498         return res;
1499 }
1500 EXPORT_SYMBOL_GPL(snmp_fold_field);
1501
1502 #if BITS_PER_LONG==32
1503
1504 u64 snmp_fold_field64(void __percpu *mib[], int offt, size_t syncp_offset)
1505 {
1506         u64 res = 0;
1507         int cpu;
1508
1509         for_each_possible_cpu(cpu) {
1510                 void *bhptr;
1511                 struct u64_stats_sync *syncp;
1512                 u64 v;
1513                 unsigned int start;
1514
1515                 bhptr = per_cpu_ptr(mib[0], cpu);
1516                 syncp = (struct u64_stats_sync *)(bhptr + syncp_offset);
1517                 do {
1518                         start = u64_stats_fetch_begin_bh(syncp);
1519                         v = *(((u64 *) bhptr) + offt);
1520                 } while (u64_stats_fetch_retry_bh(syncp, start));
1521
1522                 res += v;
1523         }
1524         return res;
1525 }
1526 EXPORT_SYMBOL_GPL(snmp_fold_field64);
1527 #endif
1528
1529 int snmp_mib_init(void __percpu *ptr[2], size_t mibsize, size_t align)
1530 {
1531         BUG_ON(ptr == NULL);
1532         ptr[0] = __alloc_percpu(mibsize, align);
1533         if (!ptr[0])
1534                 return -ENOMEM;
1535 #if SNMP_ARRAY_SZ == 2
1536         ptr[1] = __alloc_percpu(mibsize, align);
1537         if (!ptr[1]) {
1538                 free_percpu(ptr[0]);
1539                 ptr[0] = NULL;
1540                 return -ENOMEM;
1541         }
1542 #endif
1543         return 0;
1544 }
1545 EXPORT_SYMBOL_GPL(snmp_mib_init);
1546
1547 void snmp_mib_free(void __percpu *ptr[SNMP_ARRAY_SZ])
1548 {
1549         int i;
1550
1551         BUG_ON(ptr == NULL);
1552         for (i = 0; i < SNMP_ARRAY_SZ; i++) {
1553                 free_percpu(ptr[i]);
1554                 ptr[i] = NULL;
1555         }
1556 }
1557 EXPORT_SYMBOL_GPL(snmp_mib_free);
1558
1559 #ifdef CONFIG_IP_MULTICAST
1560 static const struct net_protocol igmp_protocol = {
1561         .handler =      igmp_rcv,
1562         .netns_ok =     1,
1563 };
1564 #endif
1565
1566 static const struct net_protocol tcp_protocol = {
1567         .early_demux    =       tcp_v4_early_demux,
1568         .handler        =       tcp_v4_rcv,
1569         .err_handler    =       tcp_v4_err,
1570         .no_policy      =       1,
1571         .netns_ok       =       1,
1572 };
1573
1574 static const struct net_offload tcp_offload = {
1575         .callbacks = {
1576                 .gso_send_check =       tcp_v4_gso_send_check,
1577                 .gso_segment    =       tcp_tso_segment,
1578                 .gro_receive    =       tcp4_gro_receive,
1579                 .gro_complete   =       tcp4_gro_complete,
1580         },
1581 };
1582
1583 static const struct net_protocol udp_protocol = {
1584         .handler =      udp_rcv,
1585         .err_handler =  udp_err,
1586         .no_policy =    1,
1587         .netns_ok =     1,
1588 };
1589
1590 static const struct net_offload udp_offload = {
1591         .callbacks = {
1592                 .gso_send_check = udp4_ufo_send_check,
1593                 .gso_segment = udp4_ufo_fragment,
1594         },
1595 };
1596
1597 static const struct net_protocol icmp_protocol = {
1598         .handler =      icmp_rcv,
1599         .err_handler =  icmp_err,
1600         .no_policy =    1,
1601         .netns_ok =     1,
1602 };
1603
1604 static __net_init int ipv4_mib_init_net(struct net *net)
1605 {
1606         if (snmp_mib_init((void __percpu **)net->mib.tcp_statistics,
1607                           sizeof(struct tcp_mib),
1608                           __alignof__(struct tcp_mib)) < 0)
1609                 goto err_tcp_mib;
1610         if (snmp_mib_init((void __percpu **)net->mib.ip_statistics,
1611                           sizeof(struct ipstats_mib),
1612                           __alignof__(struct ipstats_mib)) < 0)
1613                 goto err_ip_mib;
1614         if (snmp_mib_init((void __percpu **)net->mib.net_statistics,
1615                           sizeof(struct linux_mib),
1616                           __alignof__(struct linux_mib)) < 0)
1617                 goto err_net_mib;
1618         if (snmp_mib_init((void __percpu **)net->mib.udp_statistics,
1619                           sizeof(struct udp_mib),
1620                           __alignof__(struct udp_mib)) < 0)
1621                 goto err_udp_mib;
1622         if (snmp_mib_init((void __percpu **)net->mib.udplite_statistics,
1623                           sizeof(struct udp_mib),
1624                           __alignof__(struct udp_mib)) < 0)
1625                 goto err_udplite_mib;
1626         if (snmp_mib_init((void __percpu **)net->mib.icmp_statistics,
1627                           sizeof(struct icmp_mib),
1628                           __alignof__(struct icmp_mib)) < 0)
1629                 goto err_icmp_mib;
1630         net->mib.icmpmsg_statistics = kzalloc(sizeof(struct icmpmsg_mib),
1631                                               GFP_KERNEL);
1632         if (!net->mib.icmpmsg_statistics)
1633                 goto err_icmpmsg_mib;
1634
1635         tcp_mib_init(net);
1636         return 0;
1637
1638 err_icmpmsg_mib:
1639         snmp_mib_free((void __percpu **)net->mib.icmp_statistics);
1640 err_icmp_mib:
1641         snmp_mib_free((void __percpu **)net->mib.udplite_statistics);
1642 err_udplite_mib:
1643         snmp_mib_free((void __percpu **)net->mib.udp_statistics);
1644 err_udp_mib:
1645         snmp_mib_free((void __percpu **)net->mib.net_statistics);
1646 err_net_mib:
1647         snmp_mib_free((void __percpu **)net->mib.ip_statistics);
1648 err_ip_mib:
1649         snmp_mib_free((void __percpu **)net->mib.tcp_statistics);
1650 err_tcp_mib:
1651         return -ENOMEM;
1652 }
1653
1654 static __net_exit void ipv4_mib_exit_net(struct net *net)
1655 {
1656         kfree(net->mib.icmpmsg_statistics);
1657         snmp_mib_free((void __percpu **)net->mib.icmp_statistics);
1658         snmp_mib_free((void __percpu **)net->mib.udplite_statistics);
1659         snmp_mib_free((void __percpu **)net->mib.udp_statistics);
1660         snmp_mib_free((void __percpu **)net->mib.net_statistics);
1661         snmp_mib_free((void __percpu **)net->mib.ip_statistics);
1662         snmp_mib_free((void __percpu **)net->mib.tcp_statistics);
1663 }
1664
1665 static __net_initdata struct pernet_operations ipv4_mib_ops = {
1666         .init = ipv4_mib_init_net,
1667         .exit = ipv4_mib_exit_net,
1668 };
1669
1670 static int __init init_ipv4_mibs(void)
1671 {
1672         return register_pernet_subsys(&ipv4_mib_ops);
1673 }
1674
1675 static int ipv4_proc_init(void);
1676
1677 /*
1678  *      IP protocol layer initialiser
1679  */
1680
1681 static struct packet_offload ip_packet_offload __read_mostly = {
1682         .type = cpu_to_be16(ETH_P_IP),
1683         .callbacks = {
1684                 .gso_send_check = inet_gso_send_check,
1685                 .gso_segment = inet_gso_segment,
1686                 .gro_receive = inet_gro_receive,
1687                 .gro_complete = inet_gro_complete,
1688         },
1689 };
1690
1691 static int __init ipv4_offload_init(void)
1692 {
1693         /*
1694          * Add offloads
1695          */
1696         if (inet_add_offload(&udp_offload, IPPROTO_UDP) < 0)
1697                 pr_crit("%s: Cannot add UDP protocol offload\n", __func__);
1698         if (inet_add_offload(&tcp_offload, IPPROTO_TCP) < 0)
1699                 pr_crit("%s: Cannot add TCP protocol offlaod\n", __func__);
1700
1701         dev_add_offload(&ip_packet_offload);
1702         return 0;
1703 }
1704
1705 fs_initcall(ipv4_offload_init);
1706
1707 static struct packet_type ip_packet_type __read_mostly = {
1708         .type = cpu_to_be16(ETH_P_IP),
1709         .func = ip_rcv,
1710 };
1711
1712 static int __init inet_init(void)
1713 {
1714         struct inet_protosw *q;
1715         struct list_head *r;
1716         int rc = -EINVAL;
1717
1718         BUILD_BUG_ON(sizeof(struct inet_skb_parm) > FIELD_SIZEOF(struct sk_buff, cb));
1719
1720         sysctl_local_reserved_ports = kzalloc(65536 / 8, GFP_KERNEL);
1721         if (!sysctl_local_reserved_ports)
1722                 goto out;
1723
1724         rc = proto_register(&tcp_prot, 1);
1725         if (rc)
1726                 goto out_free_reserved_ports;
1727
1728         rc = proto_register(&udp_prot, 1);
1729         if (rc)
1730                 goto out_unregister_tcp_proto;
1731
1732         rc = proto_register(&raw_prot, 1);
1733         if (rc)
1734                 goto out_unregister_udp_proto;
1735
1736         rc = proto_register(&ping_prot, 1);
1737         if (rc)
1738                 goto out_unregister_raw_proto;
1739
1740         /*
1741          *      Tell SOCKET that we are alive...
1742          */
1743
1744         (void)sock_register(&inet_family_ops);
1745
1746 #ifdef CONFIG_SYSCTL
1747         ip_static_sysctl_init();
1748 #endif
1749
1750         tcp_prot.sysctl_mem = init_net.ipv4.sysctl_tcp_mem;
1751
1752         /*
1753          *      Add all the base protocols.
1754          */
1755
1756         if (inet_add_protocol(&icmp_protocol, IPPROTO_ICMP) < 0)
1757                 pr_crit("%s: Cannot add ICMP protocol\n", __func__);
1758         if (inet_add_protocol(&udp_protocol, IPPROTO_UDP) < 0)
1759                 pr_crit("%s: Cannot add UDP protocol\n", __func__);
1760         if (inet_add_protocol(&tcp_protocol, IPPROTO_TCP) < 0)
1761                 pr_crit("%s: Cannot add TCP protocol\n", __func__);
1762 #ifdef CONFIG_IP_MULTICAST
1763         if (inet_add_protocol(&igmp_protocol, IPPROTO_IGMP) < 0)
1764                 pr_crit("%s: Cannot add IGMP protocol\n", __func__);
1765 #endif
1766
1767         /* Register the socket-side information for inet_create. */
1768         for (r = &inetsw[0]; r < &inetsw[SOCK_MAX]; ++r)
1769                 INIT_LIST_HEAD(r);
1770
1771         for (q = inetsw_array; q < &inetsw_array[INETSW_ARRAY_LEN]; ++q)
1772                 inet_register_protosw(q);
1773
1774         /*
1775          *      Set the ARP module up
1776          */
1777
1778         arp_init();
1779
1780         /*
1781          *      Set the IP module up
1782          */
1783
1784         ip_init();
1785
1786         tcp_v4_init();
1787
1788         /* Setup TCP slab cache for open requests. */
1789         tcp_init();
1790
1791         /* Setup UDP memory threshold */
1792         udp_init();
1793
1794         /* Add UDP-Lite (RFC 3828) */
1795         udplite4_register();
1796
1797         ping_init();
1798
1799         /*
1800          *      Set the ICMP layer up
1801          */
1802
1803         if (icmp_init() < 0)
1804                 panic("Failed to create the ICMP control socket.\n");
1805
1806         /*
1807          *      Initialise the multicast router
1808          */
1809 #if defined(CONFIG_IP_MROUTE)
1810         if (ip_mr_init())
1811                 pr_crit("%s: Cannot init ipv4 mroute\n", __func__);
1812 #endif
1813         /*
1814          *      Initialise per-cpu ipv4 mibs
1815          */
1816
1817         if (init_ipv4_mibs())
1818                 pr_crit("%s: Cannot init ipv4 mibs\n", __func__);
1819
1820         ipv4_proc_init();
1821
1822         ipfrag_init();
1823
1824         dev_add_pack(&ip_packet_type);
1825
1826         rc = 0;
1827 out:
1828         return rc;
1829 out_unregister_raw_proto:
1830         proto_unregister(&raw_prot);
1831 out_unregister_udp_proto:
1832         proto_unregister(&udp_prot);
1833 out_unregister_tcp_proto:
1834         proto_unregister(&tcp_prot);
1835 out_free_reserved_ports:
1836         kfree(sysctl_local_reserved_ports);
1837         goto out;
1838 }
1839
1840 fs_initcall(inet_init);
1841
1842 /* ------------------------------------------------------------------------ */
1843
1844 #ifdef CONFIG_PROC_FS
1845 static int __init ipv4_proc_init(void)
1846 {
1847         int rc = 0;
1848
1849         if (raw_proc_init())
1850                 goto out_raw;
1851         if (tcp4_proc_init())
1852                 goto out_tcp;
1853         if (udp4_proc_init())
1854                 goto out_udp;
1855         if (ping_proc_init())
1856                 goto out_ping;
1857         if (ip_misc_proc_init())
1858                 goto out_misc;
1859 out:
1860         return rc;
1861 out_misc:
1862         ping_proc_exit();
1863 out_ping:
1864         udp4_proc_exit();
1865 out_udp:
1866         tcp4_proc_exit();
1867 out_tcp:
1868         raw_proc_exit();
1869 out_raw:
1870         rc = -ENOMEM;
1871         goto out;
1872 }
1873
1874 #else /* CONFIG_PROC_FS */
1875 static int __init ipv4_proc_init(void)
1876 {
1877         return 0;
1878 }
1879 #endif /* CONFIG_PROC_FS */
1880
1881 MODULE_ALIAS_NETPROTO(PF_INET);
1882