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.
6 * Support for INET connection oriented protocols.
8 * Authors: See the TCP sources
10 * This program is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU General Public License
12 * as published by the Free Software Foundation; either version
13 * 2 of the License, or(at your option) any later version.
16 #include <linux/config.h>
17 #include <linux/module.h>
18 #include <linux/jhash.h>
20 #include <net/inet_connection_sock.h>
21 #include <net/inet_hashtables.h>
22 #include <net/inet_timewait_sock.h>
24 #include <net/route.h>
25 #include <net/tcp_states.h>
29 const char inet_csk_timer_bug_msg[] = "inet_csk BUG: unknown timer value\n";
30 EXPORT_SYMBOL(inet_csk_timer_bug_msg);
34 * This array holds the first and last local port number.
35 * For high-usage systems, use sysctl to change this to
38 int sysctl_local_port_range[2] = { 1024, 4999 };
40 int inet_csk_bind_conflict(const struct sock *sk,
41 const struct inet_bind_bucket *tb)
44 struct hlist_node *node;
45 int reuse = sk->sk_reuse;
47 sk_for_each_bound(sk2, node, &tb->owners) {
49 !inet_v6_ipv6only(sk2) &&
50 (!sk->sk_bound_dev_if ||
51 !sk2->sk_bound_dev_if ||
52 sk->sk_bound_dev_if == sk2->sk_bound_dev_if)) {
53 if (!reuse || !sk2->sk_reuse ||
54 sk2->sk_state == TCP_LISTEN) {
55 if (nx_addr_conflict(sk->sk_nx_info,
56 inet_rcv_saddr(sk), sk2))
64 EXPORT_SYMBOL_GPL(inet_csk_bind_conflict);
66 /* Obtain a reference to a local port for the given sock,
67 * if snum is zero it means select any available local port.
69 int inet_csk_get_port(struct inet_hashinfo *hashinfo,
70 struct sock *sk, unsigned short snum,
71 int (*bind_conflict)(const struct sock *sk,
72 const struct inet_bind_bucket *tb))
74 struct inet_bind_hashbucket *head;
75 struct hlist_node *node;
76 struct inet_bind_bucket *tb;
81 int low = sysctl_local_port_range[0];
82 int high = sysctl_local_port_range[1];
83 int remaining = (high - low) + 1;
84 int rover = net_random() % (high - low) + low;
87 head = &hashinfo->bhash[inet_bhashfn(rover, hashinfo->bhash_size)];
88 spin_lock(&head->lock);
89 inet_bind_bucket_for_each(tb, node, &head->chain)
90 if (tb->port == rover)
94 spin_unlock(&head->lock);
97 } while (--remaining > 0);
99 /* Exhausted local port range during search? It is not
100 * possible for us to be holding one of the bind hash
101 * locks if this test triggers, because if 'remaining'
102 * drops to zero, we broke out of the do/while loop at
103 * the top level, not from the 'break;' statement.
109 /* OK, here is the one we will use. HEAD is
110 * non-NULL and we hold it's mutex.
114 head = &hashinfo->bhash[inet_bhashfn(snum, hashinfo->bhash_size)];
115 spin_lock(&head->lock);
116 inet_bind_bucket_for_each(tb, node, &head->chain)
117 if (tb->port == snum)
123 if (!hlist_empty(&tb->owners)) {
124 if (sk->sk_reuse > 1)
126 if (tb->fastreuse > 0 &&
127 sk->sk_reuse && sk->sk_state != TCP_LISTEN) {
131 if (bind_conflict(sk, tb))
137 if (!tb && (tb = inet_bind_bucket_create(hashinfo->bind_bucket_cachep, head, snum)) == NULL)
139 if (hlist_empty(&tb->owners)) {
140 if (sk->sk_reuse && sk->sk_state != TCP_LISTEN)
144 } else if (tb->fastreuse &&
145 (!sk->sk_reuse || sk->sk_state == TCP_LISTEN))
148 if (!inet_csk(sk)->icsk_bind_hash)
149 inet_bind_hash(sk, tb, snum);
150 BUG_TRAP(inet_csk(sk)->icsk_bind_hash == tb);
154 spin_unlock(&head->lock);
160 EXPORT_SYMBOL_GPL(inet_csk_get_port);
163 * Wait for an incoming connection, avoid race conditions. This must be called
164 * with the socket locked.
166 static int inet_csk_wait_for_connect(struct sock *sk, long timeo)
168 struct inet_connection_sock *icsk = inet_csk(sk);
173 * True wake-one mechanism for incoming connections: only
174 * one process gets woken up, not the 'whole herd'.
175 * Since we do not 'race & poll' for established sockets
176 * anymore, the common case will execute the loop only once.
178 * Subtle issue: "add_wait_queue_exclusive()" will be added
179 * after any current non-exclusive waiters, and we know that
180 * it will always _stay_ after any new non-exclusive waiters
181 * because all non-exclusive waiters are added at the
182 * beginning of the wait-queue. As such, it's ok to "drop"
183 * our exclusiveness temporarily when we get woken up without
184 * having to remove and re-insert us on the wait queue.
187 prepare_to_wait_exclusive(sk->sk_sleep, &wait,
190 if (reqsk_queue_empty(&icsk->icsk_accept_queue))
191 timeo = schedule_timeout(timeo);
194 if (!reqsk_queue_empty(&icsk->icsk_accept_queue))
197 if (sk->sk_state != TCP_LISTEN)
199 err = sock_intr_errno(timeo);
200 if (signal_pending(current))
206 finish_wait(sk->sk_sleep, &wait);
211 * This will accept the next outstanding connection.
213 struct sock *inet_csk_accept(struct sock *sk, int flags, int *err)
215 struct inet_connection_sock *icsk = inet_csk(sk);
221 /* We need to make sure that this socket is listening,
222 * and that it has something pending.
225 if (sk->sk_state != TCP_LISTEN)
228 /* Find already established connection */
229 if (reqsk_queue_empty(&icsk->icsk_accept_queue)) {
230 long timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
232 /* If this is a non blocking socket don't sleep */
237 error = inet_csk_wait_for_connect(sk, timeo);
242 newsk = reqsk_queue_get_child(&icsk->icsk_accept_queue, sk);
243 BUG_TRAP(newsk->sk_state != TCP_SYN_RECV);
253 EXPORT_SYMBOL(inet_csk_accept);
256 * Using different timers for retransmit, delayed acks and probes
257 * We may wish use just one timer maintaining a list of expire jiffies
260 void inet_csk_init_xmit_timers(struct sock *sk,
261 void (*retransmit_handler)(unsigned long),
262 void (*delack_handler)(unsigned long),
263 void (*keepalive_handler)(unsigned long))
265 struct inet_connection_sock *icsk = inet_csk(sk);
267 init_timer(&icsk->icsk_retransmit_timer);
268 init_timer(&icsk->icsk_delack_timer);
269 init_timer(&sk->sk_timer);
271 icsk->icsk_retransmit_timer.function = retransmit_handler;
272 icsk->icsk_delack_timer.function = delack_handler;
273 sk->sk_timer.function = keepalive_handler;
275 icsk->icsk_retransmit_timer.data =
276 icsk->icsk_delack_timer.data =
277 sk->sk_timer.data = (unsigned long)sk;
279 icsk->icsk_pending = icsk->icsk_ack.pending = 0;
282 EXPORT_SYMBOL(inet_csk_init_xmit_timers);
284 void inet_csk_clear_xmit_timers(struct sock *sk)
286 struct inet_connection_sock *icsk = inet_csk(sk);
288 icsk->icsk_pending = icsk->icsk_ack.pending = icsk->icsk_ack.blocked = 0;
290 sk_stop_timer(sk, &icsk->icsk_retransmit_timer);
291 sk_stop_timer(sk, &icsk->icsk_delack_timer);
292 sk_stop_timer(sk, &sk->sk_timer);
295 EXPORT_SYMBOL(inet_csk_clear_xmit_timers);
297 void inet_csk_delete_keepalive_timer(struct sock *sk)
299 sk_stop_timer(sk, &sk->sk_timer);
302 EXPORT_SYMBOL(inet_csk_delete_keepalive_timer);
304 void inet_csk_reset_keepalive_timer(struct sock *sk, unsigned long len)
306 sk_reset_timer(sk, &sk->sk_timer, jiffies + len);
309 EXPORT_SYMBOL(inet_csk_reset_keepalive_timer);
311 struct dst_entry* inet_csk_route_req(struct sock *sk,
312 const struct request_sock *req)
315 const struct inet_request_sock *ireq = inet_rsk(req);
316 struct ip_options *opt = inet_rsk(req)->opt;
317 struct flowi fl = { .oif = sk->sk_bound_dev_if,
319 { .daddr = ((opt && opt->srr) ?
322 .saddr = ireq->loc_addr,
323 .tos = RT_CONN_FLAGS(sk) } },
324 .proto = sk->sk_protocol,
326 { .sport = inet_sk(sk)->sport,
327 .dport = ireq->rmt_port } } };
329 if (ip_route_output_flow(&rt, &fl, sk, 0)) {
330 IP_INC_STATS_BH(IPSTATS_MIB_OUTNOROUTES);
333 if (opt && opt->is_strictroute && rt->rt_dst != rt->rt_gateway) {
335 IP_INC_STATS_BH(IPSTATS_MIB_OUTNOROUTES);
341 EXPORT_SYMBOL_GPL(inet_csk_route_req);
343 static inline u32 inet_synq_hash(const u32 raddr, const u16 rport,
344 const u32 rnd, const u16 synq_hsize)
346 return jhash_2words(raddr, (u32)rport, rnd) & (synq_hsize - 1);
349 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
350 #define AF_INET_FAMILY(fam) ((fam) == AF_INET)
352 #define AF_INET_FAMILY(fam) 1
355 struct request_sock *inet_csk_search_req(const struct sock *sk,
356 struct request_sock ***prevp,
357 const __u16 rport, const __u32 raddr,
360 const struct inet_connection_sock *icsk = inet_csk(sk);
361 struct listen_sock *lopt = icsk->icsk_accept_queue.listen_opt;
362 struct request_sock *req, **prev;
364 for (prev = &lopt->syn_table[inet_synq_hash(raddr, rport, lopt->hash_rnd,
365 lopt->nr_table_entries)];
366 (req = *prev) != NULL;
367 prev = &req->dl_next) {
368 const struct inet_request_sock *ireq = inet_rsk(req);
370 if (ireq->rmt_port == rport &&
371 ireq->rmt_addr == raddr &&
372 ireq->loc_addr == laddr &&
373 AF_INET_FAMILY(req->rsk_ops->family)) {
383 EXPORT_SYMBOL_GPL(inet_csk_search_req);
385 void inet_csk_reqsk_queue_hash_add(struct sock *sk, struct request_sock *req,
386 unsigned long timeout)
388 struct inet_connection_sock *icsk = inet_csk(sk);
389 struct listen_sock *lopt = icsk->icsk_accept_queue.listen_opt;
390 const u32 h = inet_synq_hash(inet_rsk(req)->rmt_addr, inet_rsk(req)->rmt_port,
391 lopt->hash_rnd, lopt->nr_table_entries);
393 reqsk_queue_hash_req(&icsk->icsk_accept_queue, h, req, timeout);
394 inet_csk_reqsk_queue_added(sk, timeout);
397 /* Only thing we need from tcp.h */
398 extern int sysctl_tcp_synack_retries;
400 EXPORT_SYMBOL_GPL(inet_csk_reqsk_queue_hash_add);
402 void inet_csk_reqsk_queue_prune(struct sock *parent,
403 const unsigned long interval,
404 const unsigned long timeout,
405 const unsigned long max_rto)
407 struct inet_connection_sock *icsk = inet_csk(parent);
408 struct request_sock_queue *queue = &icsk->icsk_accept_queue;
409 struct listen_sock *lopt = queue->listen_opt;
410 int max_retries = icsk->icsk_syn_retries ? : sysctl_tcp_synack_retries;
411 int thresh = max_retries;
412 unsigned long now = jiffies;
413 struct request_sock **reqp, *req;
416 if (lopt == NULL || lopt->qlen == 0)
419 /* Normally all the openreqs are young and become mature
420 * (i.e. converted to established socket) for first timeout.
421 * If synack was not acknowledged for 3 seconds, it means
422 * one of the following things: synack was lost, ack was lost,
423 * rtt is high or nobody planned to ack (i.e. synflood).
424 * When server is a bit loaded, queue is populated with old
425 * open requests, reducing effective size of queue.
426 * When server is well loaded, queue size reduces to zero
427 * after several minutes of work. It is not synflood,
428 * it is normal operation. The solution is pruning
429 * too old entries overriding normal timeout, when
430 * situation becomes dangerous.
432 * Essentially, we reserve half of room for young
433 * embrions; and abort old ones without pity, if old
434 * ones are about to clog our table.
436 if (lopt->qlen>>(lopt->max_qlen_log-1)) {
437 int young = (lopt->qlen_young<<1);
440 if (lopt->qlen < young)
447 if (queue->rskq_defer_accept)
448 max_retries = queue->rskq_defer_accept;
450 budget = 2 * (lopt->nr_table_entries / (timeout / interval));
451 i = lopt->clock_hand;
454 reqp=&lopt->syn_table[i];
455 while ((req = *reqp) != NULL) {
456 if (time_after_eq(now, req->expires)) {
457 if ((req->retrans < thresh ||
458 (inet_rsk(req)->acked && req->retrans < max_retries))
459 && !req->rsk_ops->rtx_syn_ack(parent, req, NULL)) {
462 if (req->retrans++ == 0)
464 timeo = min((timeout << req->retrans), max_rto);
465 req->expires = now + timeo;
466 reqp = &req->dl_next;
470 /* Drop this request */
471 inet_csk_reqsk_queue_unlink(parent, req, reqp);
472 reqsk_queue_removed(queue, req);
476 reqp = &req->dl_next;
479 i = (i + 1) & (lopt->nr_table_entries - 1);
481 } while (--budget > 0);
483 lopt->clock_hand = i;
486 inet_csk_reset_keepalive_timer(parent, interval);
489 EXPORT_SYMBOL_GPL(inet_csk_reqsk_queue_prune);
491 struct sock *inet_csk_clone(struct sock *sk, const struct request_sock *req,
492 const gfp_t priority)
494 struct sock *newsk = sk_clone(sk, priority);
497 struct inet_connection_sock *newicsk = inet_csk(newsk);
499 newsk->sk_state = TCP_SYN_RECV;
500 newicsk->icsk_bind_hash = NULL;
502 inet_sk(newsk)->dport = inet_rsk(req)->rmt_port;
503 newsk->sk_write_space = sk_stream_write_space;
505 newicsk->icsk_retransmits = 0;
506 newicsk->icsk_backoff = 0;
507 newicsk->icsk_probes_out = 0;
509 /* Deinitialize accept_queue to trap illegal accesses. */
510 memset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue));
515 EXPORT_SYMBOL_GPL(inet_csk_clone);
518 * At this point, there should be no process reference to this
519 * socket, and thus no user references at all. Therefore we
520 * can assume the socket waitqueue is inactive and nobody will
521 * try to jump onto it.
523 void inet_csk_destroy_sock(struct sock *sk)
525 BUG_TRAP(sk->sk_state == TCP_CLOSE);
526 BUG_TRAP(sock_flag(sk, SOCK_DEAD));
528 /* It cannot be in hash table! */
529 BUG_TRAP(sk_unhashed(sk));
531 /* If it has not 0 inet_sk(sk)->num, it must be bound */
532 BUG_TRAP(!inet_sk(sk)->num || inet_csk(sk)->icsk_bind_hash);
534 sk->sk_prot->destroy(sk);
536 sk_stream_kill_queues(sk);
538 xfrm_sk_free_policy(sk);
540 sk_refcnt_debug_release(sk);
542 atomic_dec(sk->sk_prot->orphan_count);
546 EXPORT_SYMBOL(inet_csk_destroy_sock);
548 int inet_csk_listen_start(struct sock *sk, const int nr_table_entries)
550 struct inet_sock *inet = inet_sk(sk);
551 struct inet_connection_sock *icsk = inet_csk(sk);
552 int rc = reqsk_queue_alloc(&icsk->icsk_accept_queue, nr_table_entries);
557 sk->sk_max_ack_backlog = 0;
558 sk->sk_ack_backlog = 0;
559 inet_csk_delack_init(sk);
561 /* There is race window here: we announce ourselves listening,
562 * but this transition is still not validated by get_port().
563 * It is OK, because this socket enters to hash table only
564 * after validation is complete.
566 sk->sk_state = TCP_LISTEN;
567 if (!sk->sk_prot->get_port(sk, inet->num)) {
568 inet->sport = htons(inet->num);
571 sk->sk_prot->hash(sk);
576 sk->sk_state = TCP_CLOSE;
577 __reqsk_queue_destroy(&icsk->icsk_accept_queue);
581 EXPORT_SYMBOL_GPL(inet_csk_listen_start);
584 * This routine closes sockets which have been at least partially
585 * opened, but not yet accepted.
587 void inet_csk_listen_stop(struct sock *sk)
589 struct inet_connection_sock *icsk = inet_csk(sk);
590 struct request_sock *acc_req;
591 struct request_sock *req;
593 inet_csk_delete_keepalive_timer(sk);
595 /* make all the listen_opt local to us */
596 acc_req = reqsk_queue_yank_acceptq(&icsk->icsk_accept_queue);
598 /* Following specs, it would be better either to send FIN
599 * (and enter FIN-WAIT-1, it is normal close)
600 * or to send active reset (abort).
601 * Certainly, it is pretty dangerous while synflood, but it is
602 * bad justification for our negligence 8)
603 * To be honest, we are not able to make either
604 * of the variants now. --ANK
606 reqsk_queue_destroy(&icsk->icsk_accept_queue);
608 while ((req = acc_req) != NULL) {
609 struct sock *child = req->sk;
611 acc_req = req->dl_next;
615 BUG_TRAP(!sock_owned_by_user(child));
618 sk->sk_prot->disconnect(child, O_NONBLOCK);
622 atomic_inc(sk->sk_prot->orphan_count);
624 inet_csk_destroy_sock(child);
626 bh_unlock_sock(child);
630 sk_acceptq_removed(sk);
633 BUG_TRAP(!sk->sk_ack_backlog);
636 EXPORT_SYMBOL_GPL(inet_csk_listen_stop);
638 void inet_csk_addr2sockaddr(struct sock *sk, struct sockaddr *uaddr)
640 struct sockaddr_in *sin = (struct sockaddr_in *)uaddr;
641 const struct inet_sock *inet = inet_sk(sk);
643 sin->sin_family = AF_INET;
644 sin->sin_addr.s_addr = inet->daddr;
645 sin->sin_port = inet->dport;
648 EXPORT_SYMBOL_GPL(inet_csk_addr2sockaddr);