学习这个例子用于理解单纯的dpdk转发过程,L2和L3的转发是基于此:在rte_eth_rx_burst()收包后进行解包,提取mac、ip等信息然后在转发到输出网卡。
如果要写出自己的程序(例如发特定的包,做特定的流程),这个例子还是很有学习的必要。多看几遍,直到完全弄懂里面的流程和重要的API。
代码部分
main函数
/*
* The main function, which does initialization and calls the per-lcore
* functions.
*/
int
main(int argc, char *argv[])
{
struct rte_mempool *mbuf_pool; // 指向内存池结构的指针
unsigned nb_ports; // 网口个数
uint16_t portid; // 网口号
/* Initialize the Environment Abstraction Layer (EAL). */
int ret = rte_eal_init(argc, argv);
if (ret < 0)
rte_exit(EXIT_FAILURE, "Error with EAL initialization\n");
// ret是init函数的返回值,是命令行中被解析成功的参数个数
argc -= ret;
argv += ret; // 这两个操作有点摸不着头脑。。
/* Check that there is an even number of ports to send/receive on. */
nb_ports = rte_eth_dev_count(); // 获取当前可用以太网设备的总数
if (nb_ports < 2 || (nb_ports & 1)) // 检查端口个数是否小于两个或者是奇数,则出错。
rte_exit(EXIT_FAILURE, "Error: number of ports must be even\n");
// dpdk用mbuf保存packet,mempool用于操作mbuf
/* rte_pktmbuf_pool_create() 创建并初始化mbuf池,是 rte_mempool_create 这个函数的封装。
五个参数:
1. mbuf的名字 "MBUF_POOL"
2. mbuf中的元素个数。每个端口给了8191个
3. 每个核心的缓存大小,如果该参数为0 则可以禁用缓存。本程序中是250
4. 每个mbuf中的数据缓冲区大小
5. 应分配内存的套接字标识符。
返回值:分配成功时返回指向新分配的mempool的指针。
mempool的指针会传给 port_init 函数,用于 setup rx queue
*/
/* Creates a new mempool in memory to hold the mbufs. */
mbuf_pool = rte_pktmbuf_pool_create("MBUF_POOL", NUM_MBUFS * nb_ports,
MBUF_CACHE_SIZE, 0, RTE_MBUF_DEFAULT_BUF_SIZE, rte_socket_id()); //rte_socket_id()返回正在运行的lcore所对应的物理socket。socket的文档在 lcore中
if (mbuf_pool == NULL) // 若mempool分配失败
rte_exit(EXIT_FAILURE, "Cannot create mbuf pool\n");
/* Initialize all ports. 在每个网口上初始化 */
RTE_ETH_FOREACH_DEV(portid) // 必须使用RTE_ETH_FOREACH_DEV()宏来访问这些设备以处理非连续范围的设备。
if (port_init(portid, mbuf_pool) != 0)
rte_exit(EXIT_FAILURE, "Cannot init port %"PRIu16 "\n",
portid);
if (rte_lcore_count() > 1) // basicfwd只需要使用一个逻辑核
printf("\nWARNING: Too many lcores enabled. Only 1 used.\n");
/* Call lcore_main on the master core only. */
// 仅仅一个主线程调用
// 这个程序纯粹地把一个网口收到的包从另一个网口转发出去,就像是一个repeater,中间没有其他任何处理。
lcore_main();
return 0;
}
端口初始化port_init(portid, mbuf_pool)
/*
* Initializes a given port using global settings and with the RX buffers
* coming from the mbuf_pool passed as a parameter.
*/
static inline in