Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a syscall to count context switches of a process

I have to do a system call to count the voluntary & involuntary context switches of a process. I already know the steps to add a new system call to a linux kernel but i have no clue of where i should start for the context-switch function. Any idea?

like image 617
Nausikaa Avatar asked Feb 14 '12 23:02

Nausikaa


2 Answers

If your syscall should only report statistics, you can use context switch counting code that is already in the kernel.

wait3 syscall or getrusage syscall already reports context switch count in struct rusage fields:

struct rusage {
 ...
    long   ru_nvcsw;         /* voluntary context switches */
    long   ru_nivcsw;        /* involuntary context switches */
};

You can try it by running:

$ /usr/bin/time -v /bin/ls -R
....
    Voluntary context switches: 1669
    Involuntary context switches: 207

where "/bin/ls -R" is any program.

By searching an "struct rusage" in kernel sources, you can find this accumulate_thread_rusage in kernel/sys.c, which updates rusage struct. It reads from struct task_struct *t; the fields t->nvcsw; and t->nivcsw;:

1477  static void accumulate_thread_rusage(struct task_struct *t, struct rusage *r)
1478  {
1479        r->ru_nvcsw += t->nvcsw;    // <<=== here
1480        r->ru_nivcsw += t->nivcsw;
1481        r->ru_minflt += t->min_flt;
1482        r->ru_majflt += t->maj_flt;

Then you should search nvcsw and nivcsw in kernel folder to find how they are updated by kernel.

asmlinkage void __sched schedule(void):

4124     if (likely(prev != next)) {         // <= if we are switching between different tasks
4125            sched_info_switch(prev, next);
4126            perf_event_task_sched_out(prev, next);
4127
4128            rq->nr_switches++;          
4129            rq->curr = next;
4130            ++*switch_count;     // <= increment nvcsw or nivcsw via pointer
4131
4132            context_switch(rq, prev, next); /* unlocks the rq */

Pointer switch_count is from line 4091 or line 4111 of the same file.

PS: Link from perreal is great: http://oreilly.com/catalog/linuxkernel/chapter/ch10.html (search context_swtch)

like image 84
osgx Avatar answered Sep 23 '22 01:09

osgx


This already exists: the virtual file /proc/NNNN/status (where NNNN is the decimal process ID of the process you want to know about) contains, among other things, counts of both voluntary and involuntary context switches. Unlike getrusage this allows you to learn the context switch counts for any process, not just children. See the proc(5) manpage for more details.

like image 20
zwol Avatar answered Sep 22 '22 01:09

zwol