从函数指针调用函数而不分配?

Amu*_*umu 0 c linux kernel linux-kernel

通常我们必须这样做以从函数指针调用函数:

int foo()
{
}

int main()
{
    int (*pFoo)() = foo; // pFoo points to function foo()
    foo();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在Linux内核代码中,sched_class有许多函数指针:

struct sched_class {
        const struct sched_class *next;

        void (*enqueue_task) (struct rq *rq, struct task_struct *p, int flags);
        void (*dequeue_task) (struct rq *rq, struct task_struct *p, int flags);
        void (*yield_task) (struct rq *rq);
        bool (*yield_to_task) (struct rq *rq, struct task_struct *p, bool preempt);
        .....
}
Run Code Online (Sandbox Code Playgroud)

pick_next_task函数中,它定义了一个本地的sched_classnamed 实例class,并直接调用其中的函数,而不分配具有相同签名的外部函数(从...开始for_each_class):

static inline struct task_struct *
pick_next_task(struct rq *rq)
{
        const struct sched_class *class;
        struct task_struct *p;
    /*
     * Optimization: we know that if all tasks are in
     * the fair class we can call that function directly:
     */
    if (likely(rq->nr_running == rq->cfs.h_nr_running)) {
            p = fair_sched_class.pick_next_task(rq);
            if (likely(p))
                    return p;
    }

    for_each_class(class) {
            p = class->pick_next_task(rq);
            if (p)
                    return p;
    }

    BUG(); /* the idle class will always have a runnable task */
}
Run Code Online (Sandbox Code Playgroud)

这是因为每个函数指针sched_class都与实际实现的函数同名,所以每次通过函数指针调用时sched_class,它会自动在内核地址空间中找到匹配的符号吗?

Pav*_*ath 5

定义for_each_class应该为你清除它

 #define for_each_class(class) \
       for (class = sched_class_highest; class; class = class->next)
Run Code Online (Sandbox Code Playgroud)

如果你继续跟踪,sched_class_highest最终会结束这样的事情

#define sched_class_highest (&stop_sched_class)
extern const struct sched_class stop_sched_class;

/*
* Simple, special scheduling class for the per-CPU stop tasks:
*/
const struct sched_class stop_sched_class = {
      .next                   = &rt_sched_class,

      .enqueue_task           = enqueue_task_stop,
      .dequeue_task           = dequeue_task_stop,
      .yield_task             = yield_task_stop,

      .check_preempt_curr     = check_preempt_curr_stop,

      .pick_next_task         = pick_next_task_stop,
      .put_prev_task          = put_prev_task_stop,

#ifdef CONFIG_SMP
      .select_task_rq         = select_task_rq_stop,
#endif

     .set_curr_task          = set_curr_task_stop,
     .task_tick              = task_tick_stop,

     .get_rr_interval        = get_rr_interval_stop,

     .prio_changed           = prio_changed_stop,
     .switched_to            = switched_to_stop,
};
Run Code Online (Sandbox Code Playgroud)

你快乐吗?:)