套接字 API 提供了一个SO_INCOMING_CPU
选项,其详细信息在手册页:
SO_INCOMING_CPU (gettable since Linux 3.19, settable since Linux 4.4) Sets or gets the CPU affinity of a socket. Expects an integer flag. int cpu = 1; setsockopt(fd, SOL_SOCKET, SO_INCOMING_CPU, &cpu, sizeof(cpu)); Because all of the packets for a single stream (i.e., all packets for the same 4-tuple) arrive on the single RX queue that is associated with a particular CPU, the typical use case is to employ one listening process per RX queue, with the incoming flow being handled by a listener on the same CPU that is handling the RX queue. This provides optimal NUMA behavior and keeps CPU caches hot.
我有一个服务器,它创建 UDP 套接字、绑定到接口和recv()
数据。我想得到SO_INCOMING_CPU
这个套接字的。那可能吗?
我写了一个测试程序,测试程序始终返回-1。
我做了一些printk()
调试,看起来问题是没有inet_daddr
与套接字关联:https://github.com/torvalds/linux/blob/v4.20-rc2/net/ipv4/udp.c#L1870
我认为这是有道理的:UDP 是无连接的,因此套接字可以从任何地址接收数据包。我想我在某处读到套接字的 CPU 亲和力是 4 元组的函数,因此,套接字不一定具有固定的 CPU 亲和力。
然而,考虑到 udp.c 中有初始化 CPU 亲和力的代码,我想我可能会遗漏一些东西。
有什么方法可以SO_INCOMING_CPU
使用服务器端 UDP 套接字吗?
这是我提到的(稍微草率的)测试程序:
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
int main()
{
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
{
perror("Error opening socket");
return 0;
}
struct sockaddr_in myaddr;
memset((char *)&myaddr, 0, sizeof(myaddr));
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
myaddr.sin_port = htons(4242);
if (bind(sockfd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) {
perror("bind failed");
return 0;
}
#define BUFSIZE 20
unsigned char buf[BUFSIZE]; /* receive buffer */
struct sockaddr_in remaddr; /* remote address */
socklen_t addrlen = sizeof(remaddr); /* length of addresses */
int recvlen = recvfrom(sockfd, buf, BUFSIZE, 0, (struct sockaddr *)&remaddr, &addrlen);
sleep(1);
int cpu = 0;
socklen_t len = sizeof(cpu);
int ret = getsockopt(sockfd, SOL_SOCKET, SO_INCOMING_CPU, &cpu, &len);
// Sample Output: Incoming CPU is -1 (ret = 0, recvlen = 5)
printf("Incoming CPU is %d (ret = %d, recvlen = %d)\n", cpu, ret, recvlen);
}