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