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