sam
sam

Reputation: 2579

finding amount of cpu time process spent in kernel routines

I am creating a kernel module for linux. I need it to check how much time each process has spent inside kernel routines. I know the kernel keeps this information inside stime within task_struct. My problem is that I am not sure how I get this information into my module for each process. do I create a task_struct in my module? How do I get the information from every process?

Upvotes: 0

Views: 1917

Answers (2)

Dan Aloni
Dan Aloni

Reputation: 4118

Iterating all processes from a Linux kernel module is a bit tricky because the kernel might not export all the necessary symbols. You might need to modify the kernel a tiny bit and/or depend on deeper APIs for this job, which is not an action usually being taken by kernel modules.

Let's look at an example from existing kernel code. Linux 2.6.39, kernel/cpu.c:

static inline void check_for_tasks(int cpu)
{
    struct task_struct *p;

    write_lock_irq(&tasklist_lock);
    for_each_process(p) {
            if (task_cpu(p) == cpu && p->state == TASK_RUNNING &&
                (!cputime_eq(p->utime, cputime_zero) ||
                 !cputime_eq(p->stime, cputime_zero)))
                    printk(KERN_WARNING "Task %s (pid = %d) is on cpu %d "
                            "(state = %ld, flags = %x)\n",
                            p->comm, task_pid_nr(p), cpu,
                            p->state, p->flags);
    }
    write_unlock_irq(&tasklist_lock);
}

This function iterates the task list. Of course, for your usage you can use a read lock instead of write lock, if you are not modifying the list.

Note that tasklist_lock is not exported (i.e. there's no EXPORT_SYMBOL(tasklist_lock) anywhere in the sources. Adding that and recompiling the kernel will allow your kernel module to dynamically link).

Upvotes: 2

ott--
ott--

Reputation: 5722

Look at the file linux/kernel/taskstats.c, how it collects the data from the runnings tasks. Maybe you can reuse some of the code.

Upvotes: 2

Related Questions