xref: /openbmc/linux/kernel/profile.c (revision 93696d8f)
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 
57 int profile_setup(char *str)
58 {
59 	static const char schedstr[] = "schedule";
60 	static const char kvmstr[] = "kvm";
61 	const char *select = NULL;
62 	int par;
63 
64 	if (!strncmp(str, schedstr, strlen(schedstr))) {
65 		prof_on = SCHED_PROFILING;
66 		select = schedstr;
67 	} else if (!strncmp(str, kvmstr, strlen(kvmstr))) {
68 		prof_on = KVM_PROFILING;
69 		select = kvmstr;
70 	} else if (get_option(&str, &par)) {
71 		prof_shift = clamp(par, 0, BITS_PER_LONG - 1);
72 		prof_on = CPU_PROFILING;
73 		pr_info("kernel profiling enabled (shift: %u)\n",
74 			prof_shift);
75 	}
76 
77 	if (select) {
78 		if (str[strlen(select)] == ',')
79 			str += strlen(select) + 1;
80 		if (get_option(&str, &par))
81 			prof_shift = clamp(par, 0, BITS_PER_LONG - 1);
82 		pr_info("kernel %s profiling enabled (shift: %u)\n",
83 			select, prof_shift);
84 	}
85 
86 	return 1;
87 }
88 __setup("profile=", profile_setup);
89 
90 
91 int __ref profile_init(void)
92 {
93 	int buffer_bytes;
94 	if (!prof_on)
95 		return 0;
96 
97 	/* only text is profiled */
98 	prof_len = (_etext - _stext) >> prof_shift;
99 
100 	if (!prof_len) {
101 		pr_warn("profiling shift: %u too large\n", prof_shift);
102 		prof_on = 0;
103 		return -EINVAL;
104 	}
105 
106 	buffer_bytes = prof_len*sizeof(atomic_t);
107 
108 	if (!alloc_cpumask_var(&prof_cpu_mask, GFP_KERNEL))
109 		return -ENOMEM;
110 
111 	cpumask_copy(prof_cpu_mask, cpu_possible_mask);
112 
113 	prof_buffer = kzalloc(buffer_bytes, GFP_KERNEL|__GFP_NOWARN);
114 	if (prof_buffer)
115 		return 0;
116 
117 	prof_buffer = alloc_pages_exact(buffer_bytes,
118 					GFP_KERNEL|__GFP_ZERO|__GFP_NOWARN);
119 	if (prof_buffer)
120 		return 0;
121 
122 	prof_buffer = vzalloc(buffer_bytes);
123 	if (prof_buffer)
124 		return 0;
125 
126 	free_cpumask_var(prof_cpu_mask);
127 	return -ENOMEM;
128 }
129 
130 #if defined(CONFIG_SMP) && defined(CONFIG_PROC_FS)
131 /*
132  * Each cpu has a pair of open-addressed hashtables for pending
133  * profile hits. read_profile() IPI's all cpus to request them
134  * to flip buffers and flushes their contents to prof_buffer itself.
135  * Flip requests are serialized by the profile_flip_mutex. The sole
136  * use of having a second hashtable is for avoiding cacheline
137  * contention that would otherwise happen during flushes of pending
138  * profile hits required for the accuracy of reported profile hits
139  * and so resurrect the interrupt livelock issue.
140  *
141  * The open-addressed hashtables are indexed by profile buffer slot
142  * and hold the number of pending hits to that profile buffer slot on
143  * a cpu in an entry. When the hashtable overflows, all pending hits
144  * are accounted to their corresponding profile buffer slots with
145  * atomic_add() and the hashtable emptied. As numerous pending hits
146  * may be accounted to a profile buffer slot in a hashtable entry,
147  * this amortizes a number of atomic profile buffer increments likely
148  * to be far larger than the number of entries in the hashtable,
149  * particularly given that the number of distinct profile buffer
150  * positions to which hits are accounted during short intervals (e.g.
151  * several seconds) is usually very small. Exclusion from buffer
152  * flipping is provided by interrupt disablement (note that for
153  * SCHED_PROFILING or SLEEP_PROFILING profile_hit() may be called from
154  * process context).
155  * The hash function is meant to be lightweight as opposed to strong,
156  * and was vaguely inspired by ppc64 firmware-supported inverted
157  * pagetable hash functions, but uses a full hashtable full of finite
158  * collision chains, not just pairs of them.
159  *
160  * -- nyc
161  */
162 static void __profile_flip_buffers(void *unused)
163 {
164 	int cpu = smp_processor_id();
165 
166 	per_cpu(cpu_profile_flip, cpu) = !per_cpu(cpu_profile_flip, cpu);
167 }
168 
169 static void profile_flip_buffers(void)
170 {
171 	int i, j, cpu;
172 
173 	mutex_lock(&profile_flip_mutex);
174 	j = per_cpu(cpu_profile_flip, get_cpu());
175 	put_cpu();
176 	on_each_cpu(__profile_flip_buffers, NULL, 1);
177 	for_each_online_cpu(cpu) {
178 		struct profile_hit *hits = per_cpu(cpu_profile_hits, cpu)[j];
179 		for (i = 0; i < NR_PROFILE_HIT; ++i) {
180 			if (!hits[i].hits) {
181 				if (hits[i].pc)
182 					hits[i].pc = 0;
183 				continue;
184 			}
185 			atomic_add(hits[i].hits, &prof_buffer[hits[i].pc]);
186 			hits[i].hits = hits[i].pc = 0;
187 		}
188 	}
189 	mutex_unlock(&profile_flip_mutex);
190 }
191 
192 static void profile_discard_flip_buffers(void)
193 {
194 	int i, cpu;
195 
196 	mutex_lock(&profile_flip_mutex);
197 	i = per_cpu(cpu_profile_flip, get_cpu());
198 	put_cpu();
199 	on_each_cpu(__profile_flip_buffers, NULL, 1);
200 	for_each_online_cpu(cpu) {
201 		struct profile_hit *hits = per_cpu(cpu_profile_hits, cpu)[i];
202 		memset(hits, 0, NR_PROFILE_HIT*sizeof(struct profile_hit));
203 	}
204 	mutex_unlock(&profile_flip_mutex);
205 }
206 
207 static void do_profile_hits(int type, void *__pc, unsigned int nr_hits)
208 {
209 	unsigned long primary, secondary, flags, pc = (unsigned long)__pc;
210 	int i, j, cpu;
211 	struct profile_hit *hits;
212 
213 	pc = min((pc - (unsigned long)_stext) >> prof_shift, prof_len - 1);
214 	i = primary = (pc & (NR_PROFILE_GRP - 1)) << PROFILE_GRPSHIFT;
215 	secondary = (~(pc << 1) & (NR_PROFILE_GRP - 1)) << PROFILE_GRPSHIFT;
216 	cpu = get_cpu();
217 	hits = per_cpu(cpu_profile_hits, cpu)[per_cpu(cpu_profile_flip, cpu)];
218 	if (!hits) {
219 		put_cpu();
220 		return;
221 	}
222 	/*
223 	 * We buffer the global profiler buffer into a per-CPU
224 	 * queue and thus reduce the number of global (and possibly
225 	 * NUMA-alien) accesses. The write-queue is self-coalescing:
226 	 */
227 	local_irq_save(flags);
228 	do {
229 		for (j = 0; j < PROFILE_GRPSZ; ++j) {
230 			if (hits[i + j].pc == pc) {
231 				hits[i + j].hits += nr_hits;
232 				goto out;
233 			} else if (!hits[i + j].hits) {
234 				hits[i + j].pc = pc;
235 				hits[i + j].hits = nr_hits;
236 				goto out;
237 			}
238 		}
239 		i = (i + secondary) & (NR_PROFILE_HIT - 1);
240 	} while (i != primary);
241 
242 	/*
243 	 * Add the current hit(s) and flush the write-queue out
244 	 * to the global buffer:
245 	 */
246 	atomic_add(nr_hits, &prof_buffer[pc]);
247 	for (i = 0; i < NR_PROFILE_HIT; ++i) {
248 		atomic_add(hits[i].hits, &prof_buffer[hits[i].pc]);
249 		hits[i].pc = hits[i].hits = 0;
250 	}
251 out:
252 	local_irq_restore(flags);
253 	put_cpu();
254 }
255 
256 static int profile_dead_cpu(unsigned int cpu)
257 {
258 	struct page *page;
259 	int i;
260 
261 	if (cpumask_available(prof_cpu_mask))
262 		cpumask_clear_cpu(cpu, prof_cpu_mask);
263 
264 	for (i = 0; i < 2; i++) {
265 		if (per_cpu(cpu_profile_hits, cpu)[i]) {
266 			page = virt_to_page(per_cpu(cpu_profile_hits, cpu)[i]);
267 			per_cpu(cpu_profile_hits, cpu)[i] = NULL;
268 			__free_page(page);
269 		}
270 	}
271 	return 0;
272 }
273 
274 static int profile_prepare_cpu(unsigned int cpu)
275 {
276 	int i, node = cpu_to_mem(cpu);
277 	struct page *page;
278 
279 	per_cpu(cpu_profile_flip, cpu) = 0;
280 
281 	for (i = 0; i < 2; i++) {
282 		if (per_cpu(cpu_profile_hits, cpu)[i])
283 			continue;
284 
285 		page = __alloc_pages_node(node, GFP_KERNEL | __GFP_ZERO, 0);
286 		if (!page) {
287 			profile_dead_cpu(cpu);
288 			return -ENOMEM;
289 		}
290 		per_cpu(cpu_profile_hits, cpu)[i] = page_address(page);
291 
292 	}
293 	return 0;
294 }
295 
296 static int profile_online_cpu(unsigned int cpu)
297 {
298 	if (cpumask_available(prof_cpu_mask))
299 		cpumask_set_cpu(cpu, prof_cpu_mask);
300 
301 	return 0;
302 }
303 
304 #else /* !CONFIG_SMP */
305 #define profile_flip_buffers()		do { } while (0)
306 #define profile_discard_flip_buffers()	do { } while (0)
307 
308 static void do_profile_hits(int type, void *__pc, unsigned int nr_hits)
309 {
310 	unsigned long pc;
311 	pc = ((unsigned long)__pc - (unsigned long)_stext) >> prof_shift;
312 	atomic_add(nr_hits, &prof_buffer[min(pc, prof_len - 1)]);
313 }
314 #endif /* !CONFIG_SMP */
315 
316 void profile_hits(int type, void *__pc, unsigned int nr_hits)
317 {
318 	if (prof_on != type || !prof_buffer)
319 		return;
320 	do_profile_hits(type, __pc, nr_hits);
321 }
322 EXPORT_SYMBOL_GPL(profile_hits);
323 
324 void profile_tick(int type)
325 {
326 	struct pt_regs *regs = get_irq_regs();
327 
328 	if (!user_mode(regs) && cpumask_available(prof_cpu_mask) &&
329 	    cpumask_test_cpu(smp_processor_id(), prof_cpu_mask))
330 		profile_hit(type, (void *)profile_pc(regs));
331 }
332 
333 #ifdef CONFIG_PROC_FS
334 #include <linux/proc_fs.h>
335 #include <linux/seq_file.h>
336 #include <linux/uaccess.h>
337 
338 static int prof_cpu_mask_proc_show(struct seq_file *m, void *v)
339 {
340 	seq_printf(m, "%*pb\n", cpumask_pr_args(prof_cpu_mask));
341 	return 0;
342 }
343 
344 static int prof_cpu_mask_proc_open(struct inode *inode, struct file *file)
345 {
346 	return single_open(file, prof_cpu_mask_proc_show, NULL);
347 }
348 
349 static ssize_t prof_cpu_mask_proc_write(struct file *file,
350 	const char __user *buffer, size_t count, loff_t *pos)
351 {
352 	cpumask_var_t new_value;
353 	int err;
354 
355 	if (!zalloc_cpumask_var(&new_value, GFP_KERNEL))
356 		return -ENOMEM;
357 
358 	err = cpumask_parse_user(buffer, count, new_value);
359 	if (!err) {
360 		cpumask_copy(prof_cpu_mask, new_value);
361 		err = count;
362 	}
363 	free_cpumask_var(new_value);
364 	return err;
365 }
366 
367 static const struct proc_ops prof_cpu_mask_proc_ops = {
368 	.proc_open	= prof_cpu_mask_proc_open,
369 	.proc_read	= seq_read,
370 	.proc_lseek	= seq_lseek,
371 	.proc_release	= single_release,
372 	.proc_write	= prof_cpu_mask_proc_write,
373 };
374 
375 void create_prof_cpu_mask(void)
376 {
377 	/* create /proc/irq/prof_cpu_mask */
378 	proc_create("irq/prof_cpu_mask", 0600, NULL, &prof_cpu_mask_proc_ops);
379 }
380 
381 /*
382  * This function accesses profiling information. The returned data is
383  * binary: the sampling step and the actual contents of the profile
384  * buffer. Use of the program readprofile is recommended in order to
385  * get meaningful info out of these data.
386  */
387 static ssize_t
388 read_profile(struct file *file, char __user *buf, size_t count, loff_t *ppos)
389 {
390 	unsigned long p = *ppos;
391 	ssize_t read;
392 	char *pnt;
393 	unsigned long sample_step = 1UL << prof_shift;
394 
395 	profile_flip_buffers();
396 	if (p >= (prof_len+1)*sizeof(unsigned int))
397 		return 0;
398 	if (count > (prof_len+1)*sizeof(unsigned int) - p)
399 		count = (prof_len+1)*sizeof(unsigned int) - p;
400 	read = 0;
401 
402 	while (p < sizeof(unsigned int) && count > 0) {
403 		if (put_user(*((char *)(&sample_step)+p), buf))
404 			return -EFAULT;
405 		buf++; p++; count--; read++;
406 	}
407 	pnt = (char *)prof_buffer + p - sizeof(atomic_t);
408 	if (copy_to_user(buf, (void *)pnt, count))
409 		return -EFAULT;
410 	read += count;
411 	*ppos += read;
412 	return read;
413 }
414 
415 /* default is to not implement this call */
416 int __weak setup_profiling_timer(unsigned mult)
417 {
418 	return -EINVAL;
419 }
420 
421 /*
422  * Writing to /proc/profile resets the counters
423  *
424  * Writing a 'profiling multiplier' value into it also re-sets the profiling
425  * interrupt frequency, on architectures that support this.
426  */
427 static ssize_t write_profile(struct file *file, const char __user *buf,
428 			     size_t count, loff_t *ppos)
429 {
430 #ifdef CONFIG_SMP
431 	if (count == sizeof(int)) {
432 		unsigned int multiplier;
433 
434 		if (copy_from_user(&multiplier, buf, sizeof(int)))
435 			return -EFAULT;
436 
437 		if (setup_profiling_timer(multiplier))
438 			return -EINVAL;
439 	}
440 #endif
441 	profile_discard_flip_buffers();
442 	memset(prof_buffer, 0, prof_len * sizeof(atomic_t));
443 	return count;
444 }
445 
446 static const struct proc_ops profile_proc_ops = {
447 	.proc_read	= read_profile,
448 	.proc_write	= write_profile,
449 	.proc_lseek	= default_llseek,
450 };
451 
452 int __ref create_proc_profile(void)
453 {
454 	struct proc_dir_entry *entry;
455 #ifdef CONFIG_SMP
456 	enum cpuhp_state online_state;
457 #endif
458 
459 	int err = 0;
460 
461 	if (!prof_on)
462 		return 0;
463 #ifdef CONFIG_SMP
464 	err = cpuhp_setup_state(CPUHP_PROFILE_PREPARE, "PROFILE_PREPARE",
465 				profile_prepare_cpu, profile_dead_cpu);
466 	if (err)
467 		return err;
468 
469 	err = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "AP_PROFILE_ONLINE",
470 				profile_online_cpu, NULL);
471 	if (err < 0)
472 		goto err_state_prep;
473 	online_state = err;
474 	err = 0;
475 #endif
476 	entry = proc_create("profile", S_IWUSR | S_IRUGO,
477 			    NULL, &profile_proc_ops);
478 	if (!entry)
479 		goto err_state_onl;
480 	proc_set_size(entry, (1 + prof_len) * sizeof(atomic_t));
481 
482 	return err;
483 err_state_onl:
484 #ifdef CONFIG_SMP
485 	cpuhp_remove_state(online_state);
486 err_state_prep:
487 	cpuhp_remove_state(CPUHP_PROFILE_PREPARE);
488 #endif
489 	return err;
490 }
491 subsys_initcall(create_proc_profile);
492 #endif /* CONFIG_PROC_FS */
493