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