Linux内核协议栈(7)listen函数分析

时间:2021-11-09 21:37:40

监听函数主要干了两件事:

1.建立接受队列,并为接受队列分配空间

2.将sock对象设置为监听状态,并放入监听哈希表

/*
*Perform a listen. Basically, we allow the protocol to do anything
*necessary for a listen, and if that works, we mark the socket as
*ready for listening.
*/
/*
*
* 就是把套接字挂到监听链表下
*/
SYSCALL_DEFINE2(listen, int, fd, int, backlog)
{
struct socket *sock;
int err, fput_needed;
int somaxconn;

sock = sockfd_lookup_light(fd, &err, &fput_needed);//查找sock
if (sock) {
somaxconn = sock_net(sock->sk)->core.sysctl_somaxconn;
if ((unsigned)backlog > somaxconn)
backlog = somaxconn;

err = security_socket_listen(sock, backlog);
if (!err)
err = sock->ops->listen(sock, backlog);/**/inet_listen

fput_light(sock->file, fput_needed);
}
return err;
}
调用链为:sys_listen-->inet_listen-->inet_csk_listen_start


int inet_csk_listen_start(struct sock *sk, const int nr_table_entries)
{
struct inet_sock *inet = inet_sk(sk);
struct inet_connection_sock *icsk = inet_csk(sk);
int rc = reqsk_queue_alloc(&icsk->icsk_accept_queue, nr_table_entries);//创建请求队列及为队列分配空间,listen_sock + nr_table_entries * request_sock
if (rc != 0)
return rc;

sk->sk_max_ack_backlog = 0;
sk->sk_ack_backlog = 0;
inet_csk_delack_init(sk);//将sock中的icsk_ack置0 ---> Delayed ACK control data

/* There is race window here: we announce ourselves listening,
* but this transition is still not validated by get_port().
* It is OK, because this socket enters to hash table only
* after validation is complete.
*/

/*
* 要么把自己加入到tcp_hashinfo 中的ehash 中,要么加入到listening_hash 中,这要根据
* sk_state 的值来操作,如果是LISTEN,就加入后者,如果是除LISTEN 之外的值,那么就加入
* ehash 表,我们会在研究connect 的代码中看到。
*/
sk->sk_state = TCP_LISTEN;
if (!sk->sk_prot->get_port(sk, inet->num)) { /*获取可用端口*/inetsw_array --> tcp_prot --> inet_csk_get_port
inet->sport = htons(inet->num);

sk_dst_reset(sk);
sk->sk_prot->hash(sk);/*------------------------>加入监听哈希表*/ inetsw_array --> tcp_prot --> __inet_hash

return 0;
}

sk->sk_state = TCP_CLOSE;
__reqsk_queue_destroy(&icsk->icsk_accept_queue);
return -EADDRINUSE;
}