1

I've been trying to understand the try_to_wake_up() function in the linux kernel somewhat better. Conceptually, I (think) that to wake up a process we must be adding it to the CPU runqueue, but I have trouble seeing where this is occurring.

    //try_to_wake_up()

    if (p == current) {
        /* I omitted some comments here*/

        success = 1;
        cpu = task_cpu(p);        //task_cpu(p) returns READ_ONCE(p->cpu);
        trace_sched_waking(p);    //This is just a logging call
        p->state = TASK_RUNNING; 
        trace_sched_wakeup(p);    //Another logging call
        goto out;
    }

So task_cpu() doesn't seem to be modifying the CPU runqueue at all, so I decide to go look at the label out, which is calling ttwu_stat():

/*I omitted some intermediate code here*/
out:
    if (success)
        ttwu_stat(p, cpu, wake_flags);
    preempt_enable();

    return success;

But then when I go look at ttwu_stat(), it just seems to be a bunch of calls to this __schedstat_inc macro that just increments its input argument.

So... where are we actually adding the task_struct* p to the CPU run queue?

Any thoughts appreciated.

Thanks.

1
  • Is p == current a special case? What does that function do if that condition isn't true? Mar 8, 2021 at 1:59

1 Answer 1

1

The code block you’ve quoted is a special case, as explained in the elided comments:

         * We're waking current, this means 'p->on_rq' and 'task_cpu(p)
         * == smp_processor_id()'. Together this means we can special
         * case the whole 'p->on_rq && ttwu_remote()' case below
         * without taking any locks.

Since the task to awake is the current task, it’s already on a run queue (p->on_rq) so it doesn’t need to be added to one.

Adding a task to a run queue is dealt with further down:

    cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);

This adds the task to a run queue and returns the CPU on which it is scheduled, so migration can be dealt with if necessary.

The #ifdef CONFIG_SMP condition merits some explanation: if SMP isn’t supported, then multiple tasks can’t run concurrently, and since we know we’re not waking the current task, the only scenario to deal with is I/O wait.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .