1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * linux/kernel/profile.c
4 * Simple profiling. Manages a direct-mapped profile hit count buffer,
5 * with configurable resolution, support for restricting the cpus on
6 * which profiling is done, and switching between cpu time and
7 * schedule() calls via kernel command line parameters passed at boot.
8 *
9 * Scheduler profiling support, Arjan van de Ven and Ingo Molnar,
10 * Red Hat, July 2004
11 * Consolidation of architecture support code for profiling,
12 * Nadia Yvette Chambers, Oracle, July 2004
13 * Amortized hit count accounting via per-cpu open-addressed hashtables
14 * to resolve timer interrupt livelocks, Nadia Yvette Chambers,
15 * Oracle, 2004
16 */
17
18 #include <linux/export.h>
19 #include <linux/profile.h>
20 #include <linux/memblock.h>
21 #include <linux/notifier.h>
22 #include <linux/mm.h>
23 #include <linux/cpumask.h>
24 #include <linux/cpu.h>
25 #include <linux/highmem.h>
26 #include <linux/mutex.h>
27 #include <linux/slab.h>
28 #include <linux/vmalloc.h>
29 #include <linux/sched/stat.h>
30
31 #include <asm/sections.h>
32 #include <asm/irq_regs.h>
33 #include <asm/ptrace.h>
34
35 struct profile_hit {
36 u32 pc, hits;
37 };
38 #define PROFILE_GRPSHIFT 3
39 #define PROFILE_GRPSZ (1 << PROFILE_GRPSHIFT)
40 #define NR_PROFILE_HIT (PAGE_SIZE/sizeof(struct profile_hit))
41 #define NR_PROFILE_GRP (NR_PROFILE_HIT/PROFILE_GRPSZ)
42
43 static atomic_t *prof_buffer;
44 static unsigned long prof_len;
45 static unsigned short int prof_shift;
46
47 int prof_on __read_mostly;
48 EXPORT_SYMBOL_GPL(prof_on);
49
50 static cpumask_var_t prof_cpu_mask;
51 #if defined(CONFIG_SMP) && defined(CONFIG_PROC_FS)
52 static DEFINE_PER_CPU(struct profile_hit *[2], cpu_profile_hits);
53 static DEFINE_PER_CPU(int, cpu_profile_flip);
54 static DEFINE_MUTEX(profile_flip_mutex);
55 #endif /* CONFIG_SMP */
56
profile_setup(char * str)57 int profile_setup(char *str)
58 {
59 static const char schedstr[] = "schedule";
60 static const char sleepstr[] = "sleep";
61 static const char kvmstr[] = "kvm";
62 const char *select = NULL;
63 int par;
64
65 if (!strncmp(str, sleepstr, strlen(sleepstr))) {
66 #ifdef CONFIG_SCHEDSTATS
67 force_schedstat_enabled();
68 prof_on = SLEEP_PROFILING;
69 select = sleepstr;
70 #else
71 pr_warn("kernel sleep profiling requires CONFIG_SCHEDSTATS\n");
72 #endif /* CONFIG_SCHEDSTATS */
73 } else if (!strncmp(str, schedstr, strlen(schedstr))) {
74 prof_on = SCHED_PROFILING;
75 select = schedstr;
76 } else if (!strncmp(str, kvmstr, strlen(kvmstr))) {
77 prof_on = KVM_PROFILING;
78 select = kvmstr;
79 } else if (get_option(&str, &par)) {
80 prof_shift = clamp(par, 0, BITS_PER_LONG - 1);
81 prof_on = CPU_PROFILING;
82 pr_info("kernel profiling enabled (shift: %u)\n",
83 prof_shift);
84 }
85
86 if (select) {
87 if (str[strlen(select)] == ',')
88 str += strlen(select) + 1;
89 if (get_option(&str, &par))
90 prof_shift = clamp(par, 0, BITS_PER_LONG - 1);
91 pr_info("kernel %s profiling enabled (shift: %u)\n",
92 select, prof_shift);
93 }
94
95 return 1;
96 }
97 __setup("profile=", profile_setup);
98
99
profile_init(void)100 int __ref profile_init(void)
101 {
102 int buffer_bytes;
103 if (!prof_on)
104 return 0;
105
106 /* only text is profiled */
107 prof_len = (_etext - _stext) >> prof_shift;
108
109 if (!prof_len) {
110 pr_warn("profiling shift: %u too large\n", prof_shift);
111 prof_on = 0;
112 return -EINVAL;
113 }
114
115 buffer_bytes = prof_len*sizeof(atomic_t);
116
117 if (!alloc_cpumask_var(&prof_cpu_mask, GFP_KERNEL))
118 return -ENOMEM;
119
120 cpumask_copy(prof_cpu_mask, cpu_possible_mask);
121
122 prof_buffer = kzalloc(buffer_bytes, GFP_KERNEL|__GFP_NOWARN);
123 if (prof_buffer)
124 return 0;
125
126 prof_buffer = alloc_pages_exact(buffer_bytes,
127 GFP_KERNEL|__GFP_ZERO|__GFP_NOWARN);
128 if (prof_buffer)
129 return 0;
130
131 prof_buffer = vzalloc(buffer_bytes);
132 if (prof_buffer)
133 return 0;
134
135 free_cpumask_var(prof_cpu_mask);
136 return -ENOMEM;
137 }
138
139 /* Profile event notifications */
140
141 static BLOCKING_NOTIFIER_HEAD(task_exit_notifier);
142 static BLOCKING_NOTIFIER_HEAD(munmap_notifier);
143
profile_task_exit(struct task_struct * task)144 void profile_task_exit(struct task_struct *task)
145 {
146 blocking_notifier_call_chain(&task_exit_notifier, 0, task);
147 }
148
profile_munmap(unsigned long addr)149 void profile_munmap(unsigned long addr)
150 {
151 blocking_notifier_call_chain(&munmap_notifier, 0, (void *)addr);
152 }
153
profile_event_register(enum profile_type type,struct notifier_block * n)154 int profile_event_register(enum profile_type type, struct notifier_block *n)
155 {
156 int err = -EINVAL;
157
158 switch (type) {
159 case PROFILE_TASK_EXIT:
160 err = blocking_notifier_chain_register(
161 &task_exit_notifier, n);
162 break;
163 case PROFILE_MUNMAP:
164 err = blocking_notifier_chain_register(
165 &munmap_notifier, n);
166 break;
167 }
168
169 return err;
170 }
171 EXPORT_SYMBOL_GPL(profile_event_register);
172
profile_event_unregister(enum profile_type type,struct notifier_block * n)173 int profile_event_unregister(enum profile_type type, struct notifier_block *n)
174 {
175 int err = -EINVAL;
176
177 switch (type) {
178 case PROFILE_TASK_EXIT:
179 err = blocking_notifier_chain_unregister(
180 &task_exit_notifier, n);
181 break;
182 case PROFILE_MUNMAP:
183 err = blocking_notifier_chain_unregister(
184 &munmap_notifier, n);
185 break;
186 }
187
188 return err;
189 }
190 EXPORT_SYMBOL_GPL(profile_event_unregister);
191
192 #if defined(CONFIG_SMP) && defined(CONFIG_PROC_FS)
193 /*
194 * Each cpu has a pair of open-addressed hashtables for pending
195 * profile hits. read_profile() IPI's all cpus to request them
196 * to flip buffers and flushes their contents to prof_buffer itself.
197 * Flip requests are serialized by the profile_flip_mutex. The sole
198 * use of having a second hashtable is for avoiding cacheline
199 * contention that would otherwise happen during flushes of pending
200 * profile hits required for the accuracy of reported profile hits
201 * and so resurrect the interrupt livelock issue.
202 *
203 * The open-addressed hashtables are indexed by profile buffer slot
204 * and hold the number of pending hits to that profile buffer slot on
205 * a cpu in an entry. When the hashtable overflows, all pending hits
206 * are accounted to their corresponding profile buffer slots with
207 * atomic_add() and the hashtable emptied. As numerous pending hits
208 * may be accounted to a profile buffer slot in a hashtable entry,
209 * this amortizes a number of atomic profile buffer increments likely
210 * to be far larger than the number of entries in the hashtable,
211 * particularly given that the number of distinct profile buffer
212 * positions to which hits are accounted during short intervals (e.g.
213 * several seconds) is usually very small. Exclusion from buffer
214 * flipping is provided by interrupt disablement (note that for
215 * SCHED_PROFILING or SLEEP_PROFILING profile_hit() may be called from
216 * process context).
217 * The hash function is meant to be lightweight as opposed to strong,
218 * and was vaguely inspired by ppc64 firmware-supported inverted
219 * pagetable hash functions, but uses a full hashtable full of finite
220 * collision chains, not just pairs of them.
221 *
222 * -- nyc
223 */
__profile_flip_buffers(void * unused)224 static void __profile_flip_buffers(void *unused)
225 {
226 int cpu = smp_processor_id();
227
228 per_cpu(cpu_profile_flip, cpu) = !per_cpu(cpu_profile_flip, cpu);
229 }
230
profile_flip_buffers(void)231 static void profile_flip_buffers(void)
232 {
233 int i, j, cpu;
234
235 mutex_lock(&profile_flip_mutex);
236 j = per_cpu(cpu_profile_flip, get_cpu());
237 put_cpu();
238 on_each_cpu(__profile_flip_buffers, NULL, 1);
239 for_each_online_cpu(cpu) {
240 struct profile_hit *hits = per_cpu(cpu_profile_hits, cpu)[j];
241 for (i = 0; i < NR_PROFILE_HIT; ++i) {
242 if (!hits[i].hits) {
243 if (hits[i].pc)
244 hits[i].pc = 0;
245 continue;
246 }
247 atomic_add(hits[i].hits, &prof_buffer[hits[i].pc]);
248 hits[i].hits = hits[i].pc = 0;
249 }
250 }
251 mutex_unlock(&profile_flip_mutex);
252 }
253
profile_discard_flip_buffers(void)254 static void profile_discard_flip_buffers(void)
255 {
256 int i, cpu;
257
258 mutex_lock(&profile_flip_mutex);
259 i = per_cpu(cpu_profile_flip, get_cpu());
260 put_cpu();
261 on_each_cpu(__profile_flip_buffers, NULL, 1);
262 for_each_online_cpu(cpu) {
263 struct profile_hit *hits = per_cpu(cpu_profile_hits, cpu)[i];
264 memset(hits, 0, NR_PROFILE_HIT*sizeof(struct profile_hit));
265 }
266 mutex_unlock(&profile_flip_mutex);
267 }
268
do_profile_hits(int type,void * __pc,unsigned int nr_hits)269 static void do_profile_hits(int type, void *__pc, unsigned int nr_hits)
270 {
271 unsigned long primary, secondary, flags, pc = (unsigned long)__pc;
272 int i, j, cpu;
273 struct profile_hit *hits;
274
275 pc = min((pc - (unsigned long)_stext) >> prof_shift, prof_len - 1);
276 i = primary = (pc & (NR_PROFILE_GRP - 1)) << PROFILE_GRPSHIFT;
277 secondary = (~(pc << 1) & (NR_PROFILE_GRP - 1)) << PROFILE_GRPSHIFT;
278 cpu = get_cpu();
279 hits = per_cpu(cpu_profile_hits, cpu)[per_cpu(cpu_profile_flip, cpu)];
280 if (!hits) {
281 put_cpu();
282 return;
283 }
284 /*
285 * We buffer the global profiler buffer into a per-CPU
286 * queue and thus reduce the number of global (and possibly
287 * NUMA-alien) accesses. The write-queue is self-coalescing:
288 */
289 local_irq_save(flags);
290 do {
291 for (j = 0; j < PROFILE_GRPSZ; ++j) {
292 if (hits[i + j].pc == pc) {
293 hits[i + j].hits += nr_hits;
294 goto out;
295 } else if (!hits[i + j].hits) {
296 hits[i + j].pc = pc;
297 hits[i + j].hits = nr_hits;
298 goto out;
299 }
300 }
301 i = (i + secondary) & (NR_PROFILE_HIT - 1);
302 } while (i != primary);
303
304 /*
305 * Add the current hit(s) and flush the write-queue out
306 * to the global buffer:
307 */
308 atomic_add(nr_hits, &prof_buffer[pc]);
309 for (i = 0; i < NR_PROFILE_HIT; ++i) {
310 atomic_add(hits[i].hits, &prof_buffer[hits[i].pc]);
311 hits[i].pc = hits[i].hits = 0;
312 }
313 out:
314 local_irq_restore(flags);
315 put_cpu();
316 }
317
profile_dead_cpu(unsigned int cpu)318 static int profile_dead_cpu(unsigned int cpu)
319 {
320 struct page *page;
321 int i;
322
323 if (cpumask_available(prof_cpu_mask))
324 cpumask_clear_cpu(cpu, prof_cpu_mask);
325
326 for (i = 0; i < 2; i++) {
327 if (per_cpu(cpu_profile_hits, cpu)[i]) {
328 page = virt_to_page(per_cpu(cpu_profile_hits, cpu)[i]);
329 per_cpu(cpu_profile_hits, cpu)[i] = NULL;
330 __free_page(page);
331 }
332 }
333 return 0;
334 }
335
profile_prepare_cpu(unsigned int cpu)336 static int profile_prepare_cpu(unsigned int cpu)
337 {
338 int i, node = cpu_to_mem(cpu);
339 struct page *page;
340
341 per_cpu(cpu_profile_flip, cpu) = 0;
342
343 for (i = 0; i < 2; i++) {
344 if (per_cpu(cpu_profile_hits, cpu)[i])
345 continue;
346
347 page = __alloc_pages_node(node, GFP_KERNEL | __GFP_ZERO, 0);
348 if (!page) {
349 profile_dead_cpu(cpu);
350 return -ENOMEM;
351 }
352 per_cpu(cpu_profile_hits, cpu)[i] = page_address(page);
353
354 }
355 return 0;
356 }
357
profile_online_cpu(unsigned int cpu)358 static int profile_online_cpu(unsigned int cpu)
359 {
360 if (cpumask_available(prof_cpu_mask))
361 cpumask_set_cpu(cpu, prof_cpu_mask);
362
363 return 0;
364 }
365
366 #else /* !CONFIG_SMP */
367 #define profile_flip_buffers() do { } while (0)
368 #define profile_discard_flip_buffers() do { } while (0)
369
do_profile_hits(int type,void * __pc,unsigned int nr_hits)370 static void do_profile_hits(int type, void *__pc, unsigned int nr_hits)
371 {
372 unsigned long pc;
373 pc = ((unsigned long)__pc - (unsigned long)_stext) >> prof_shift;
374 atomic_add(nr_hits, &prof_buffer[min(pc, prof_len - 1)]);
375 }
376 #endif /* !CONFIG_SMP */
377
profile_hits(int type,void * __pc,unsigned int nr_hits)378 void profile_hits(int type, void *__pc, unsigned int nr_hits)
379 {
380 if (prof_on != type || !prof_buffer)
381 return;
382 do_profile_hits(type, __pc, nr_hits);
383 }
384 EXPORT_SYMBOL_GPL(profile_hits);
385
profile_tick(int type)386 void profile_tick(int type)
387 {
388 struct pt_regs *regs = get_irq_regs();
389
390 if (!user_mode(regs) && cpumask_available(prof_cpu_mask) &&
391 cpumask_test_cpu(smp_processor_id(), prof_cpu_mask))
392 profile_hit(type, (void *)profile_pc(regs));
393 }
394
395 #ifdef CONFIG_PROC_FS
396 #include <linux/proc_fs.h>
397 #include <linux/seq_file.h>
398 #include <linux/uaccess.h>
399
prof_cpu_mask_proc_show(struct seq_file * m,void * v)400 static int prof_cpu_mask_proc_show(struct seq_file *m, void *v)
401 {
402 seq_printf(m, "%*pb\n", cpumask_pr_args(prof_cpu_mask));
403 return 0;
404 }
405
prof_cpu_mask_proc_open(struct inode * inode,struct file * file)406 static int prof_cpu_mask_proc_open(struct inode *inode, struct file *file)
407 {
408 return single_open(file, prof_cpu_mask_proc_show, NULL);
409 }
410
prof_cpu_mask_proc_write(struct file * file,const char __user * buffer,size_t count,loff_t * pos)411 static ssize_t prof_cpu_mask_proc_write(struct file *file,
412 const char __user *buffer, size_t count, loff_t *pos)
413 {
414 cpumask_var_t new_value;
415 int err;
416
417 if (!zalloc_cpumask_var(&new_value, GFP_KERNEL))
418 return -ENOMEM;
419
420 err = cpumask_parse_user(buffer, count, new_value);
421 if (!err) {
422 cpumask_copy(prof_cpu_mask, new_value);
423 err = count;
424 }
425 free_cpumask_var(new_value);
426 return err;
427 }
428
429 static const struct proc_ops prof_cpu_mask_proc_ops = {
430 .proc_open = prof_cpu_mask_proc_open,
431 .proc_read = seq_read,
432 .proc_lseek = seq_lseek,
433 .proc_release = single_release,
434 .proc_write = prof_cpu_mask_proc_write,
435 };
436
create_prof_cpu_mask(void)437 void create_prof_cpu_mask(void)
438 {
439 /* create /proc/irq/prof_cpu_mask */
440 proc_create("irq/prof_cpu_mask", 0600, NULL, &prof_cpu_mask_proc_ops);
441 }
442
443 /*
444 * This function accesses profiling information. The returned data is
445 * binary: the sampling step and the actual contents of the profile
446 * buffer. Use of the program readprofile is recommended in order to
447 * get meaningful info out of these data.
448 */
449 static ssize_t
read_profile(struct file * file,char __user * buf,size_t count,loff_t * ppos)450 read_profile(struct file *file, char __user *buf, size_t count, loff_t *ppos)
451 {
452 unsigned long p = *ppos;
453 ssize_t read;
454 char *pnt;
455 unsigned long sample_step = 1UL << prof_shift;
456
457 profile_flip_buffers();
458 if (p >= (prof_len+1)*sizeof(unsigned int))
459 return 0;
460 if (count > (prof_len+1)*sizeof(unsigned int) - p)
461 count = (prof_len+1)*sizeof(unsigned int) - p;
462 read = 0;
463
464 while (p < sizeof(unsigned int) && count > 0) {
465 if (put_user(*((char *)(&sample_step)+p), buf))
466 return -EFAULT;
467 buf++; p++; count--; read++;
468 }
469 pnt = (char *)prof_buffer + p - sizeof(atomic_t);
470 if (copy_to_user(buf, (void *)pnt, count))
471 return -EFAULT;
472 read += count;
473 *ppos += read;
474 return read;
475 }
476
477 /* default is to not implement this call */
setup_profiling_timer(unsigned mult)478 int __weak setup_profiling_timer(unsigned mult)
479 {
480 return -EINVAL;
481 }
482
483 /*
484 * Writing to /proc/profile resets the counters
485 *
486 * Writing a 'profiling multiplier' value into it also re-sets the profiling
487 * interrupt frequency, on architectures that support this.
488 */
write_profile(struct file * file,const char __user * buf,size_t count,loff_t * ppos)489 static ssize_t write_profile(struct file *file, const char __user *buf,
490 size_t count, loff_t *ppos)
491 {
492 #ifdef CONFIG_SMP
493 if (count == sizeof(int)) {
494 unsigned int multiplier;
495
496 if (copy_from_user(&multiplier, buf, sizeof(int)))
497 return -EFAULT;
498
499 if (setup_profiling_timer(multiplier))
500 return -EINVAL;
501 }
502 #endif
503 profile_discard_flip_buffers();
504 memset(prof_buffer, 0, prof_len * sizeof(atomic_t));
505 return count;
506 }
507
508 static const struct proc_ops profile_proc_ops = {
509 .proc_read = read_profile,
510 .proc_write = write_profile,
511 .proc_lseek = default_llseek,
512 };
513
create_proc_profile(void)514 int __ref create_proc_profile(void)
515 {
516 struct proc_dir_entry *entry;
517 #ifdef CONFIG_SMP
518 enum cpuhp_state online_state;
519 #endif
520
521 int err = 0;
522
523 if (!prof_on)
524 return 0;
525 #ifdef CONFIG_SMP
526 err = cpuhp_setup_state(CPUHP_PROFILE_PREPARE, "PROFILE_PREPARE",
527 profile_prepare_cpu, profile_dead_cpu);
528 if (err)
529 return err;
530
531 err = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "AP_PROFILE_ONLINE",
532 profile_online_cpu, NULL);
533 if (err < 0)
534 goto err_state_prep;
535 online_state = err;
536 err = 0;
537 #endif
538 entry = proc_create("profile", S_IWUSR | S_IRUGO,
539 NULL, &profile_proc_ops);
540 if (!entry)
541 goto err_state_onl;
542 proc_set_size(entry, (1 + prof_len) * sizeof(atomic_t));
543
544 return err;
545 err_state_onl:
546 #ifdef CONFIG_SMP
547 cpuhp_remove_state(online_state);
548 err_state_prep:
549 cpuhp_remove_state(CPUHP_PROFILE_PREPARE);
550 #endif
551 return err;
552 }
553 subsys_initcall(create_proc_profile);
554 #endif /* CONFIG_PROC_FS */
555