15 线程模型:lcore、绑核与远程启动


 TL;DR
DPDK 的快,一半来自线程模型:lcore 到底是什么、EAL 怎么把活派到各个核、主线程与 worker 之间的管道握手怎么实现,以及主从多进程怎么协作。逐行读 rte_eal_init 到 rte_eal_remote_launch。源码基于 27.03.0-rc0。
难度 中等

DPDK 的性能神话有一半来自「网卡」,另一半来自「线程」。
这一章讲后半���:DPDK 是怎么把一段代码放到某个特定的核上跑的,
以及主线程怎么把活派给它。

读完之后你应该能回答:

  1. lcore id 和物理 CPU id 是一回事吗?
  2. --lcores '(0-3)@10' 这个写法在源码里被谁解析?
  3. 主线程调用 rte_eal_remote_launch() 之后,worker 是怎么知道「该干活了」的?
  4. 每一篇老教程里写的 rte_eal_launch(),现在还在吗?

本文所有行号基于 /Users/growduduan/cwork/dpdk(27.03.0-rc0)。

本文不讨论:内存怎么分配(02 章)、EAL 启动的十五步全貌(03 章)、
网卡队列(06 章)、软件网卡(14 章)。

15.1 问题边界:为什么线程模型值得单独一章

很多教程把 DPDK 的快归因于「轮询模式,不用中断」。
这只说对了一半 —— 轮询解决的是「不用等中断」,
但谁来轮询、轮询哪块网卡、用哪个核,是另一套机制。

DPDK 的线程模型有三条硬规则:

  1. 一个线程固定跑在一个核上(绑核),不迁移 —— 所以没有调度抖动,
    也没有跨核的缓存行失效。
  2. 应用代码不写自己的线程(除了主线程),所有 worker 都是 EAL 起的,
    空闲时阻塞在管道上 —— 所以不会有线程创建/销毁的开销,
    也不会有不可控的上下文切换。
  3. 主线程通过一个状态机把活派给 worker —— 所以「谁负责哪个队列」
    是应用显式指定的,不是运行时猜测的。

这三条决定了 DPDK 程序的骨架长什么样。搞懂它们,
你就知道为什么 DPDK 应用几乎都是「一个主循环 + 一堆 worker」的结构。

15.2 lcore:逻辑核 id 不是物理核 id

15.2.1 两套编号

概念 是什么 范围
物理核 id(CPU id) Linux 里的 CPU 编号 0 ~ nproc-1
lcore id DPDK 的逻辑核编号 0 ~ RTE_MAX_LCORE-1

默认情况下两者一一对应(lcore 0 = CPU 0),但可以拆开。
--lcores '(0-3)@10' 的意思是:
lcore 0、1、2、3 这四个逻辑核,全都绑到物理 CPU 10 上。

/**
 * Return the Application thread ID of the execution unit.
 *
 * Note: in most cases, the lcore id returned here will also correspond
 *   to the processor id of the CPU on which the thread is pinned, this
 *   will not be the case if the user has explicitly changed the thread to
 *   core affinities using --lcores EAL argument e.g. --lcores '(0-3)@10'
 *   to run threads with lcore IDs 0, 1, 2 and 3 on physical core 10..
 */
static inline unsigned
rte_lcore_id(void)
{
  return RTE_PER_LCORE(_lcore_id);
}

lib/eal/include/rte_lcore.h:83-87(注释在 :70-82)。

这是 per-lcore 变量:每个线程一份,读它不花时间。
实现是编译器扩展的线程局部存储:

#define RTE_DEFINE_PER_LCORE(type, name)			\
  __thread type per_lcore_##name

lib/eal/include/rte_per_lcore.h:33-34。

为什么每个线程要一份 _lcore_id?
因为热路径上要反复问「我是谁」。如果每次都去查全局表,
那就是一次随机内存访问 —— 而这个访问很可能落在别的核的缓存行上。
放在 TLS 里,读的是本核的缓存行,永远命中。

15.2.2 lcore 的四种角色

enum rte_lcore_role_t {
  RTE_LCORE_ROLE_RTE,
  RTE_LCORE_ROLE_OFF,
  RTE_LCORE_ROLE_SERVICE,
  RTE_LCORE_ROLE_NON_EAL,
};

lib/eal/include/rte_lcore.h:33-37。

角色 含义
RTE_LCORE_ROLE_RTE 给应用数据面用的核(worker 和 main 都在这个角色里)
RTE_LCORE_ROLE_OFF 不用这个核
RTE_LCORE_ROLE_SERVICE 给 EAL 的服务线程(timer、pmd 健康检查等)用
RTE_LCORE_ROLE_NON_EAL 不是 EAL 起的线程,但注册成了 lcore

15.2.3 RTE_MAX_LCORE 现在是编译期可配的

老文章里 RTE_MAX_LCORE = 128 是个写死的常数。现在不是了:

max_lcores = get_option('max_lcores')
if max_lcores == 'detect'
  ...
  max_lcores = run_command(get_cpu_count_cmd, check: true).stdout().to_int()
  ...
  dpdk_conf.set('RTE_MAX_LCORE', max_lcores)
elif max_lcores != 'default'
  dpdk_conf.set('RTE_MAX_LCORE', max_lcores.to_int())
endif

config/meson.build:428-448。

x86 的默认值仍是 128(config/x86/meson.build:25),
但可以用 -Dmax_lcores=detect 让它等于构建机的 CPU 数,
也可以 -Dmax_lcores=512 手工指定。

为什么这件事重要:RTE_MAX_LCORE 决定了很多数组的大小
(lcore_config[RTE_MAX_LCORE]、time_count[RTE_MAX_LCORE]……),
也就是说它直接影响内存占用。在 256 核机器上按默认 128 编,
就有一半核用不了;调大它则每个数组都变大。这是编译期的取舍,不是运行期的。

15.2.4 遍历 lcore 的两个宏

#define RTE_LCORE_FOREACH(i)						\
  for (i = rte_get_next_lcore(-1, 0, 0);				\
       i < RTE_MAX_LCORE;						\
       i = rte_get_next_lcore(i, 0, 0))

#define RTE_LCORE_FOREACH_WORKER(i)					\
  for (i = rte_get_next_lcore(-1, 1, 0);				\
       i < RTE_MAX_LCORE;						\
       i = rte_get_next_lcore(i, 1, 0))

lib/eal/include/rte_lcore.h:241-252。

两者的区别只有一个参数:skip_main。
RTE_LCORE_FOREACH_WORKER 跳过主线程所在的那个核。

这是写 DPDK 应用的第一条纪律:
worker 循环里必须用 RTE_LCORE_FOREACH_WORKER,
写 RTE_LCORE_FOREACH 会让主线程也进来,
结果主线程和 worker 抢同一个队列,数据错乱。

15.3 EAL 怎么发现这些核

启动早期,EAL 先要知道「这台机器有哪些核、分别在哪个 NUMA 节点上」:

int
rte_eal_cpu_init(void)
{
  ...
  for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
    lcore_config[lcore_id].core_index = count;
    CPU_ZERO(&lcore_config[lcore_id].cpuset);
    socket_id = eal_cpu_socket_id(lcore_id);
    lcore_to_socket_id[lcore_id] = socket_id;
    if (eal_cpu_detected(lcore_id) == 0) {
      config->lcore_role[lcore_id] = RTE_LCORE_ROLE_OFF;
      lcore_config[lcore_id].core_index = -1;
      continue;
    }
    /* By default, lcore 1:1 map to cpu id */
    CPU_SET(lcore_id, &lcore_config[lcore_id].cpuset);
    ...
    config->lcore_role[lcore_id] = RTE_LCORE_ROLE_RTE;
    lcore_config[lcore_id].core_role = RTE_LCORE_ROLE_RTE;
    lcore_config[lcore_id].core_id = eal_cpu_core_id(lcore_id);
    lcore_config[lcore_id].numa_id = socket_id;
    ...
  }
  ...
}

lib/eal/common/eal_common_lcore.c:163-247(核心循环在 :180-212)。

三个动作:

  1. 探测:eal_cpu_detected() 逐个问内核这个 CPU 在不在。
  2. 默认 1:1 映射:CPU_SET(lcore_id, ...) 把 lcore id 直接当 CPU id 用。
  3. 记 NUMA:lcore_config[lcore_id].numa_id = socket_id ——
    这是 02 章那条 NUMA 传递线的起点:后面分配内存时,
    队列、mempool 都要按这个 numa_id 放到本地的节点上。

它被调用的位置在 EAL 主流程里:

if (rte_eal_cpu_init() < 0) {
  rte_eal_init_alert("Cannot init CPU");
  return -1;
}

lib/eal/linux/eal.c:621(rte_eal_init 从 :566 开始)。

15.4 --lcores:改映射的语法

15.4.1 语法本身

/*
 * The format pattern: --lcores='<lcores[@cpus]>[<,lcores[@cpus]>...]'
 * lcores, cpus could be a single digit/range or a group.
 * '(' and ')' are necessary if it's a group.
 * If not supply '@cpus', the value of cpus uses the same as lcores.
 * e.g. '1,2@(5-7),(3-5)@(0,2),(0,6),7-8' means start 9 EAL thread as below
 *   lcore 0 runs on cpuset 0x41 (cpu 0,6)
 *   lcore 1 runs on cpuset 0x2 (cpu 1)
 *   lcore 2 runs on cpuset 0xe0 (cpu 5,6,7)
 *   lcore 3,4,5 runs on cpuset 0x5 (cpu 0,2)
 *   lcore 6 runs on cpuset 0x41 (cpu 0,6)
 *   lcore 7 runs on cpuset 0x80 (cpu 7)
 *   lcore 8 runs on cpuset 0x100 (cpu 8)
 */

lib/eal/common/eal_common_options.c:1355-1368。

注释里的例子很说明问题:--lcores 描述的是逻辑核到 CPU 集合的映射,
一个逻辑核可以对应多个物理 CPU(0x41 = CPU 0 和 CPU 6),
这在超线程场景下有用 —— 把两个超线程兄弟核分给不同的 lcore,
可以避开同一条物理核上的资源争用。

15.4.2 解析函数

static int
eal_parse_lcores(const char *lcores)
{
  ...
  /* Reset lcore config */
  rte_bitset_clear_all(cfg->core_indices, RTE_MAX_LCORE);
  for (idx = 0; idx < RTE_MAX_LCORE; idx++) {
    cfg->lcore_role[idx] = RTE_LCORE_ROLE_OFF;
    lcore_config[idx].core_index = -1;
    CPU_ZERO(&lcore_config[idx].cpuset);
  }
  ...
}

lib/eal/common/eal_common_options.c:1369-1399(解析主循环从 :1402 开始)。

注意解析的第一步是把之前探测出来的映射全部清零 ——
--lcores 一旦出现,就完全以它为准,不再用默认的 1:1 映射。

-c/--coremask 已经废弃:
LIST_ARG("--coremask", "-c", "[Deprecated] Hexadecimal bitmask of cores to use", coremask)
(lib/eal/common/eal_option_list.h:39)。
现在用 -l/--lcores(:45)。老教程里 -c 0xf 的写法要改。

15.5 worker 线程是怎么起来的

15.5.1 创建

static int
eal_worker_thread_create(unsigned int lcore_id)
{
  ...
  stack_size = eal_get_internal_configuration()->huge_worker_stack_size;
  if (stack_size != 0) {
    /* Allocate NUMA aware stack memory and set pthread attributes */
    stack_ptr = rte_zmalloc_socket("lcore_stack", stack_size,
      RTE_CACHE_LINE_SIZE, rte_lcore_to_socket_id(lcore_id));
    ...
    pthread_attr_setstack(attrp, stack_ptr, stack_size);
  }
  if (pthread_create((pthread_t *)&lcore_config[lcore_id].thread_id.opaque_id,
      attrp, eal_worker_thread_loop, (void *)(uintptr_t)lcore_id) == 0)
    ret = 0;
  ...
}

lib/eal/linux/eal.c:518-561。

两个细节:

  1. 线程栈默认从普通内存分;只有开了 --huge-worker-stack 才从巨页分
    (OPT_STR_ARG("--huge-worker-stack", ...),lib/eal/common/eal_option_list.h:86),
    而且分的时候按 rte_lcore_to_socket_id(lcore_id) 放在本 NUMA 节点上 ——
    栈在远端节点会导致每次调用碰一次跨 NUMA 访存。
  2. 每个 worker 一个 pthread,入口参数就是它的 lcore id。

15.5.2 主循环

/* main loop of threads */
__rte_noreturn uint32_t
eal_thread_loop(void *arg)
{
  unsigned int lcore_id = (uintptr_t)arg;
  ...
  __rte_thread_init(lcore_id, &lcore_config[lcore_id].cpuset);
  ...
  /* read on our pipe to get commands */
  while (1) {
    lcore_function_t *f;
    void *fct_arg;

    eal_thread_wait_command();

    /* Set the state to 'RUNNING'. Use release order
     * since 'state' variable is used as the guard variable.
     */
    rte_atomic_store_explicit(&lcore_config[lcore_id].state, RUNNING,
      rte_memory_order_release);

    eal_thread_ack_command();

    /* Load 'f' with acquire order ... */
    while ((f = rte_atomic_load_explicit(&lcore_config[lcore_id].f,
        rte_memory_order_acquire)) == NULL)
      rte_pause();

    fct_arg = lcore_config[lcore_id].arg;
    ret = f(fct_arg);
    lcore_config[lcore_id].ret = ret;
    lcore_config[lcore_id].f = NULL;
    lcore_config[lcore_id].arg = NULL;

    rte_atomic_store_explicit(&lcore_config[lcore_id].state, WAIT,
      rte_memory_order_release);
  }
}

lib/eal/common/eal_common_thread.c:155-217。

这个循环是整章的核心。worker 线程一生只做三件事:
等命令 → 跑函数 → 等命令。它从不返回,也从不自己找活干。

15.5.3 绑核:主线程替 worker 绑

这一段是本文最容易记错的地方,绑核不是 worker 自己做的,是主线程替它做的。

主线程在 rte_eal_init() 的后半段,逐个处理 worker:

RTE_LCORE_FOREACH_WORKER(i) {

  /*
   * create communication pipes between main thread
   * and children
   */
  if (pipe(lcore_config[i].pipe_main2worker) < 0)
    rte_panic("Cannot create pipe\n");
  if (pipe(lcore_config[i].pipe_worker2main) < 0)
    rte_panic("Cannot create pipe\n");

  lcore_config[i].state = WAIT;

  /* create a thread for each lcore */
  ret = eal_worker_thread_create(i);
  if (ret != 0)
    rte_panic("Cannot create thread\n");

  /* Set thread_name for aid in debugging. */
  ret = snprintf(thread_name, sizeof(thread_name), "dpdk-worker%d", i);
  ...
  rte_thread_set_name(lcore_config[i].thread_id, thread_name);

  ret = rte_thread_set_affinity_by_id(lcore_config[i].thread_id,
    &lcore_config[i].cpuset);
  if (ret != 0)
    rte_panic("Cannot set affinity\n");
}

/*
 * Launch a dummy function on all worker lcores, so that main lcore
 * knows they are all ready when this function returns.
 */
rte_eal_mp_remote_launch(sync_func, NULL, SKIP_MAIN);
rte_eal_mp_wait_lcore();

lib/eal/linux/eal.c:862-898。

这段代码一次做完五件事:

动作 位置 说明
建两条管道 :868-871 每个 worker 一对 pipe(),主从各留一端
置初始状态 :873 state = WAIT —— worker 一上来就在等命令
建线程 :876 见 15.5.1
起名字 :881-885 dpdk-worker%d,ps -T 能直接对上 lcore id
绑核 :887-888 主线程对 worker 的 tid 调 pthread_setaffinity_np

绑核的落点是:

RTE_EXPORT_SYMBOL(rte_thread_set_affinity_by_id)
int
rte_thread_set_affinity_by_id(rte_thread_t thread_id,
    const rte_cpuset_t *cpuset)
{
  return pthread_setaffinity_np((pthread_t)thread_id.opaque_id,
    sizeof(*cpuset), cpuset);
}

lib/eal/unix/rte_thread.c:405-412。

为什么主线程能替 worker 绑核:
pthread_setaffinity_np 接受的是线程 id,
不要求调用者就是那个线程。主线程拿着 worker 的 tid 就能改它的亲和性。
这样做的额外好处是:绑核失败会立刻在主线程里 rte_panic,
而不是让 worker 在自己的上下文里悄悄失败。

主线程自己也是同样处理,只是用的 rte_thread_self():

if (rte_thread_set_affinity_by_id(rte_thread_self(),
    &lcore_config[config->main_lcore].cpuset) != 0) {
  rte_eal_init_alert("Cannot set affinity");
  ...
}
__rte_thread_init(config->main_lcore,
  &lcore_config[config->main_lcore].cpuset);

lib/eal/linux/eal.c:848-855。

而 worker 线程自己的初始化只做「认领身份」:

void
__rte_thread_init(unsigned int lcore_id, rte_cpuset_t *cpuset)
{
  /* set the lcore ID in per-lcore memory area */
  RTE_PER_LCORE(_lcore_id) = lcore_id;

  /* acquire system unique id */
  rte_gettid();

  thread_update_affinity(cpuset);

  __rte_trace_mem_per_thread_alloc();
}

lib/eal/common/eal_common_thread.c:132-144。

thread_update_affinity()(:69-87)把 NUMA id 和 cpuset 存进 TLS,
供 rte_socket_id()、rte_thread_get_affinity() 这类热路径 API 读取。

最后那两句是本章的收尾:
rte_eal_mp_remote_launch(sync_func, NULL, SKIP_MAIN) 往每个 worker 派一个
空函数(sync_func 在 lib/eal/linux/eal.c:458),
紧接着 rte_eal_mp_wait_lcore() 等它们都跑完。
这是一次握手:从此以后主线程才知道「所有 worker 都活着且绑好了」,
可以放心地把真活派下去。

15.6 主线程怎么把活派出去

15.6.1 状态机

enum rte_lcore_state_t {
  WAIT,
  /**< waiting for new command */
  RUNNING,
  /**< executing command */
};

lib/eal/include/rte_launch.h:21-26。

只有两个状态。约定是:

  • WAIT:worker 空闲,等命令。
  • RUNNING:worker 正在执行函数。

主线程只往 WAIT 的 worker 派活,执行完 worker 把自己改回 WAIT。

15.6.2 唤醒靠管道

int
eal_thread_wake_worker(unsigned int worker_id)
{
  int m2w = lcore_config[worker_id].pipe_main2worker[1];
  int w2m = lcore_config[worker_id].pipe_worker2main[0];
  char c = 0;
  int n;

  do {
    n = write(m2w, &c, 1);
  } while (n == 0 || (n < 0 && errno == EINTR));
  ...
  do {
    n = read(w2m, &c, 1);
  } while (n < 0 && errno == EINTR);
  ...
  return 0;
}

lib/eal/unix/eal_unix_thread.c:13-32。

每个 lcore 有两条管道(struct lcore_config 的 pipe_main2worker 与
pipe_worker2main,lib/eal/common/eal_private.h:26-27)。
唤醒的过程是:

  1. 主线程往 main2worker 写 1 个字节;
  2. worker 阻塞在 read() 上,被唤醒(eal_thread_wait_command,:35-48);
  3. worker 回写 1 个字节到 worker2main,表示「我醒了」(eal_thread_ack_command,:51-64);
  4. 主线程 read() 到这个字节才返回。

为什么用管道而不是信号量?
因为管道天然表达「有东西要处理」,且唤醒是阻塞的 ——
worker 不需要忙等,也不需要在热路径上轮询一个标志位。
这就是 DPDK 空闲时不烧 CPU 的原因。

15.6.3 rte_eal_remote_launch()

RTE_EXPORT_SYMBOL(rte_eal_remote_launch)
int
rte_eal_remote_launch(lcore_function_t *f, void *arg, unsigned int worker_id)
{
  int rc = -EBUSY;

  /* Check if the worker is in 'WAIT' state. Use acquire order
   * since 'state' variable is used as the guard variable.
   */
  if (rte_atomic_load_explicit(&lcore_config[worker_id].state,
      rte_memory_order_acquire) != WAIT)
    goto finish;

  lcore_config[worker_id].arg = arg;
  /* Ensure that all the memory operations are completed
   * before the worker thread starts running the function.
   * Use worker thread function as the guard variable.
   */
  rte_atomic_store_explicit(&lcore_config[worker_id].f, f, rte_memory_order_release);

  rc = eal_thread_wake_worker(worker_id);

finish:
  rte_eal_trace_thread_remote_launch(f, arg, worker_id, rc);
  return rc;
}

lib/eal/common/eal_common_launch.c:35-60。

这里有两处内存序,值得单独看:

位置 序 为什么
读 state acquire 保证看到主线程之前写的 arg
写 f release 保证 f 和 arg 对 worker 可见

worker 那边是对称的:读 f 用 acquire(eal_common_thread.c:191-193),
写 state = WAIT 用 release(:209-210)。

一句话记住这个协议:state 是守卫变量,
所有跨线程的数据都靠它的 release/acquire 配对来保证可见性。
这和 04 章 ring 里的 head/tail 是同一种手法。

15.6.4 一次派给所有 worker

RTE_EXPORT_SYMBOL(rte_eal_mp_remote_launch)
int
rte_eal_mp_remote_launch(int (*f)(void *), void *arg,
       enum rte_rmt_call_main_t call_main)
{
  int lcore_id;
  int main_lcore = rte_get_main_lcore();

  /* check state of lcores */
  RTE_LCORE_FOREACH_WORKER(lcore_id) {
    if (lcore_config[lcore_id].state != WAIT)
      return -EBUSY;
  }

  /* send messages to cores */
  RTE_LCORE_FOREACH_WORKER(lcore_id) {
    rte_eal_remote_launch(f, arg, lcore_id);
  }

  if (call_main == CALL_MAIN) {
    lcore_config[main_lcore].ret = f(arg);
    lcore_config[main_lcore].state = WAIT;
  }

  return 0;
}

lib/eal/common/eal_common_launch.c:67-92。

先全部检查,再全部派发 —— 这样不会出现「派了一半发现有 worker 不空闲」
的半吊子状态。对应的等待接口是 rte_eal_mp_wait_lcore()(:108-117),
它对每个 worker 调一次 rte_eal_wait_lcore()(:19-28),后者是自旋等状态变回 WAIT。

rte_eal_launch() 已经不存在了。
全树搜索零命中 —— 每一篇老教程里的
rte_eal_launch(lcore_id, f, arg),现在都要改成
rte_eal_remote_launch(f, arg, lcore_id)。
注意参数顺序也变了:老 API 是 (lcore_id, f, arg),
新 API 是 (f, arg, lcore_id)。

15.6.5 一次派活的全过程

sequenceDiagram participant M as 主线程 participant P as 管道 main2worker participant W as worker 线程 M->>M: 写 state=RUNNING? 不,是读 state,确认是 WAIT M->>M: lcore_config[id].arg = arg M->>M: release 写 lcore_config[id].f = f M->>P: write(m2w, 1 byte) P->>W: read 阻塞返回 W->>W: release 写 state = RUNNING W->>M: write(w2m, 1 byte) 确认已醒 M->>M: read 返回,派活完成 W->>W: acquire 读 f(等它非 NULL) W->>W: ret = f(arg) W->>W: release 写 state = WAIT

15.7 主从多进程

15.7.1 进程类型

enum rte_proc_type_t rte_eal_process_type(void);

lib/eal/include/rte_eal.h:48;命令行选项 --proc-type=primary|secondary|auto
(lib/eal/common/eal_option_list.h:62)。

主进程负责创建网卡、队列、mempool 等资源;
从进程通过共享内存附着到这些资源上。
这是 DPDK 唯一支持的「多进程共享硬件」模型。

15.7.2 通信通道

int
rte_mp_channel_init(void)
{
  char path[UNIX_PATH_MAX];
  int dir_fd;
  ...
  /* create filter path */
  if (create_socket_path("*", path, sizeof(path)) < 0) {
    ...
  }
  ...
  /* lock the directory */
  dir_fd = open(mp_dir_path, O_RDONLY);
  ...
  if (flock(dir_fd, LOCK_EX)) {
    ...
  }
  if (open_socket_fd() < 0) {
    ...
  }
  ...
  /* listen for quit message from primary */
  if (rte_eal_process_type() == RTE_PROC_SECONDARY)
    rte_mp_action_register(EAL_MP, mp_primary_exited);

  if (rte_thread_create_internal_control(&mp_handle_tid, "mp-msg",
      mp_handle, NULL) < 0) {
    ...
  }
  ...
}

lib/eal/common/eal_common_proc.c:646-705。

要点:

  • 通信介质是 UNIX socket(open_socket_fd()),不是共享内存。
  • 共享内存只用来放数据(memzone、mempool、网卡队列),
    UNIX socket 用来传控制消息(比如「primary 退出了」)。
  • 主进程退出时,从进程会收到 mp_primary_exited 回调 ——
    不处理这个回调,从进程会一直拿着已经失效的网卡资源。

它在 EAL 里的调用位置有讲究:

/* Put mp channel init before bus scan so that we can init the vdev
 * devices before the other devices.
 */
if (rte_mp_channel_init() < 0 && rte_errno != ENOTSUP) {

lib/eal/linux/eal.c:666-669(注释在 :666-667)。

顺序很重要:多进程通道必须先于总线扫描初始化,
因为 vdev 设备在 secondary 里要靠这个通道去 primary 要清单(14 章 :485-506)。
顺序反了,secondary 就看不到 primary 的 vdev。

15.8 非 EAL 线程:自己起的线程怎么算 lcore

应用自己 pthread_create 出来的线程,默认不是 lcore
(rte_lcore_id() 返回 LCORE_ID_ANY)。但可以注册:

RTE_EXPORT_SYMBOL(rte_thread_register)
int
rte_thread_register(void)
{
  unsigned int lcore_id;
  rte_cpuset_t cpuset;

  /* EAL init flushes all lcores, we can't register before. */
  if (eal_get_internal_configuration()->init_complete != 1) {
    EAL_LOG(DEBUG, "Called %s before EAL init.", __func__);
    rte_errno = EINVAL;
    return -1;
  }
  if (!rte_mp_disable()) {
    EAL_LOG(ERR, "Multiprocess in use, registering non-EAL threads is not supported.");
    rte_errno = EINVAL;
    return -1;
  }
  ...
  lcore_id = eal_lcore_non_eal_allocate();
  ...
  __rte_thread_init(lcore_id, &cpuset);
  ...
}

lib/eal/common/eal_common_thread.c:353-384。

三个限制:

  1. 必须在 rte_eal_init() 之后(init_complete 没置 1 就返回 -EINVAL)。
  2. 多进程模式下不支持(rte_mp_disable() 为假就报错)。
  3. 注册的线程是独占一个 lcore id 的。

建议:非 EAL 线程在 DPDK 数据面里基本不该出现。
如果你需要一个额外的消费者,用 eventdev 的订阅模型(09 章),
而不是自己起线程 —— 后者会破坏「一个核一个线程」的模型,
绑核和缓存行亲和性全乱。

15.9 工程取舍

15.9.1 线程模型的三种选法

模型 怎么用 适合 代价
主循环 + worker(标准) rte_eal_mp_remote_launch() 派发 转发、网关 写起来啰嗦一点
每个 worker 自己开队列 worker 认领 rx/tx 队列 多队列打散 要自己保证队列归属不重叠
非 EAL 线程 + eventdev 自建线程订阅事件 需要复杂调度逻辑 破坏绑核模型,性能不可预测

15.9.2 绑核 vs 不绑核

做法 效果
不绑(让系统调度) 代码简单,但会有迁移、缓存失效、不可控的延迟毛刺
绑到物理核 稳定,但要注意避开同物理核的超线程兄弟
绑到同一物理核的多个 lcore 共享 L1/L2 缓存,延迟最低,但要手动分配

DPDK 的延迟敏感场景(NFV、金融交易)常用第三种:
把同一物理核的两个超线程分给同一个 lcore 组,
用共享缓存换延迟。代价是单个核的算力减半。

15.9.3 多线程 vs 多进程

多线程 多进程
共享网卡 ❌(一个网卡只能属于一个进程组) ✅(primary + secondary)
故障隔离 ❌(一个段错误全挂) ✅
通信成本 共享内存,几乎为零 要走 UNIX socket 或共享内存
调试 简单 复杂

要共享硬件,就多进程;不要共享硬件,多线程更省事。
这也是 DPDK 只支持多进程共享网卡、不支持多线程共享网卡的原因。

15.10 踩坑与校验

坑 1:worker 循环里用了 RTE_LCORE_FOREACH

主线程也会被遍历到,导致主线程也去收包。
校验办法:日志里看每个 lcore 的启动顺序;
rte_eal_wait_lcore() 之前别忘了主线程自己的 state。

坑 2:lcore id 当成 CPU id 用

--lcores '(0-3)@10' 之后,rte_lcore_id() 返回 0~3,但线程实际跑在 CPU 10 上。

校验办法:rte_thread_get_affinity() 读出真实 cpuset,
或者用 --log-level=7 看 EAL 启动日志里的
lcore %u is ready (tid=%zx;cpuset=[%s])
(lib/eal/common/eal_common_thread.c:165-167)。

坑 3:还在用 rte_eal_launch()

这个函数在 27.03 里已经不存在(全树零命中)。
改成 rte_eal_remote_launch(f, arg, lcore_id),注意参数顺序。

坑 4:worker 函数返回了,但主线程没等

rte_eal_remote_launch() 是异步的:它返回时 worker 可能还没开始跑。
要等结果必须调 rte_eal_wait_lcore(lcore_id),
或者用 rte_eal_mp_remote_launch() + rte_eal_mp_wait_lcore() 配对。

坑 5:多进程下从进程没处理 primary 退出

校验办法:在从进程里注册 mp_primary_exited 回调,
或者至少确保从进程在 primary 退出后能被信号终止。
14 章讲的 vdev 跨进程共享也依赖这条通道。

15.11 接下来

  • 16 章:发送路径 —— 06 章讲了收包那一侧,这一章讲发包那一侧:
    rte_eth_tx_burst() 做了什么、mbuf 的所有权什么时候从应用转到驱动、
    又什么时候被要回来。

文章作者: growdu
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 growdu !
  目录