Hello.<div><div><br></div><div>I am hacking the kernel source for studying.</div><div>I just modified schedule() in kernel/sched.c for profiling processes.</div><div><br></div><div>I want to count the number of cache miss, so added the code using sys_perf_event_open.</div>
<div>However, it seems to returns always error fd.</div><div><br></div><div>I hope to know what should I do for getting the number of cache miss.</div></div><div><br></div><div><br></div><div>Here is the diff code based at kernel version 2.6.37</div>
<div>Thanks for reading this e-mail.</div><div><br></div><div><br></div><div><div>diff --git a/kernel/sched.c b/kernel/sched.c</div><div>index 297d1a0..afe68bc 100644</div><div>--- a/kernel/sched.c</div><div>+++ b/kernel/sched.c</div>
<div>@@ -72,6 +72,7 @@</div><div> #include &lt;linux/ctype.h&gt;</div><div> #include &lt;linux/ftrace.h&gt;</div><div> #include &lt;linux/slab.h&gt;</div><div>+#include &lt;linux/syscalls.h&gt;</div><div><br></div><div> #include &lt;asm/tlb.h&gt;</div>
<div> #include &lt;asm/irq_regs.h&gt;</div><div>@@ -4061,6 +4062,30 @@ pick_next_task(struct rq *rq)</div><div>        BUG(); /* the idle class will always have a runnable task */</div><div> }</div><div><br></div><div>+static void profile(struct task_struct *task)</div>
<div>+{</div><div>+        int fd;</div><div>+        size_t res;</div><div>+        u64 count;</div><div>+        struct perf_event_attr attr =</div><div>+        {</div><div>+                .type = PERF_TYPE_HARDWARE,</div>
<div>+                .config = PERF_COUNT_HW_CACHE_MISSES,</div><div>+                .size = sizeof(struct perf_event_attr)</div><div>+        };</div><div>+        int res_close;</div><div>+</div><div>+        BUG_ON(task == 0);</div>
<div>+</div><div>+        fd = sys_perf_event_open(&amp;attr, 0, -1, -1, 0);</div><div>+        BUG_ON(fd &lt; 0);</div><div>+        res = sys_read(fd, (char *)&amp;count, sizeof(u64));</div><div>+        BUG_ON(res != sizeof(u64));</div>
<div>+        res_close = sys_close(fd);</div><div>+        BUG_ON(res_close == -1);</div><div>+        pr_info(&quot;PERF: %d %u %llu %d&quot;, fd, res, count, res_close);</div><div>+}</div><div>+</div><div> /*</div><div>
  * schedule() is the main scheduler function.</div><div>  */</div><div>@@ -4080,6 +4105,7 @@ need_resched:</div><div><br></div><div>        release_kernel_lock(prev);</div><div> need_resched_nonpreemptible:</div><div>+       profile(prev);</div>
<div><br></div><div>        schedule_debug(prev);</div><div><br></div></div><div><br></div>