xref: /linux-6.15/lib/dynamic_debug.c (revision ee879be3)
1 /*
2  * lib/dynamic_debug.c
3  *
4  * make pr_debug()/dev_dbg() calls runtime configurable based upon their
5  * source module.
6  *
7  * Copyright (C) 2008 Jason Baron <[email protected]>
8  * By Greg Banks <[email protected]>
9  * Copyright (c) 2008 Silicon Graphics Inc.  All Rights Reserved.
10  * Copyright (C) 2011 Bart Van Assche.  All Rights Reserved.
11  * Copyright (C) 2013 Du, Changbin <[email protected]>
12  */
13 
14 #define pr_fmt(fmt) "dyndbg: " fmt
15 
16 #include <linux/kernel.h>
17 #include <linux/module.h>
18 #include <linux/moduleparam.h>
19 #include <linux/kallsyms.h>
20 #include <linux/types.h>
21 #include <linux/mutex.h>
22 #include <linux/proc_fs.h>
23 #include <linux/seq_file.h>
24 #include <linux/list.h>
25 #include <linux/sysctl.h>
26 #include <linux/ctype.h>
27 #include <linux/string.h>
28 #include <linux/parser.h>
29 #include <linux/string_helpers.h>
30 #include <linux/uaccess.h>
31 #include <linux/dynamic_debug.h>
32 #include <linux/debugfs.h>
33 #include <linux/slab.h>
34 #include <linux/jump_label.h>
35 #include <linux/hardirq.h>
36 #include <linux/sched.h>
37 #include <linux/device.h>
38 #include <linux/netdevice.h>
39 
40 #include <rdma/ib_verbs.h>
41 
42 extern struct _ddebug __start___dyndbg[];
43 extern struct _ddebug __stop___dyndbg[];
44 
45 struct ddebug_table {
46 	struct list_head link;
47 	const char *mod_name;
48 	unsigned int num_ddebugs;
49 	struct _ddebug *ddebugs;
50 };
51 
52 struct ddebug_query {
53 	const char *filename;
54 	const char *module;
55 	const char *function;
56 	const char *format;
57 	unsigned int first_lineno, last_lineno;
58 };
59 
60 struct ddebug_iter {
61 	struct ddebug_table *table;
62 	unsigned int idx;
63 };
64 
65 struct flag_settings {
66 	unsigned int flags;
67 	unsigned int mask;
68 };
69 
70 static DEFINE_MUTEX(ddebug_lock);
71 static LIST_HEAD(ddebug_tables);
72 static int verbose;
73 module_param(verbose, int, 0644);
74 MODULE_PARM_DESC(verbose, " dynamic_debug/control processing "
75 		 "( 0 = off (default), 1 = module add/rm, 2 = >control summary, 3 = parsing, 4 = per-site changes)");
76 
77 /* Return the path relative to source root */
78 static inline const char *trim_prefix(const char *path)
79 {
80 	int skip = strlen(__FILE__) - strlen("lib/dynamic_debug.c");
81 
82 	if (strncmp(path, __FILE__, skip))
83 		skip = 0; /* prefix mismatch, don't skip */
84 
85 	return path + skip;
86 }
87 
88 static struct { unsigned flag:8; char opt_char; } opt_array[] = {
89 	{ _DPRINTK_FLAGS_PRINT, 'p' },
90 	{ _DPRINTK_FLAGS_INCL_MODNAME, 'm' },
91 	{ _DPRINTK_FLAGS_INCL_FUNCNAME, 'f' },
92 	{ _DPRINTK_FLAGS_INCL_LINENO, 'l' },
93 	{ _DPRINTK_FLAGS_INCL_TID, 't' },
94 	{ _DPRINTK_FLAGS_NONE, '_' },
95 };
96 
97 struct flagsbuf { char buf[ARRAY_SIZE(opt_array)+1]; };
98 
99 /* format a string into buf[] which describes the _ddebug's flags */
100 static char *ddebug_describe_flags(unsigned int flags, struct flagsbuf *fb)
101 {
102 	char *p = fb->buf;
103 	int i;
104 
105 	for (i = 0; i < ARRAY_SIZE(opt_array); ++i)
106 		if (flags & opt_array[i].flag)
107 			*p++ = opt_array[i].opt_char;
108 	if (p == fb->buf)
109 		*p++ = '_';
110 	*p = '\0';
111 
112 	return fb->buf;
113 }
114 
115 #define vnpr_info(lvl, fmt, ...)				\
116 do {								\
117 	if (verbose >= lvl)					\
118 		pr_info(fmt, ##__VA_ARGS__);			\
119 } while (0)
120 
121 #define vpr_info(fmt, ...)	vnpr_info(1, fmt, ##__VA_ARGS__)
122 #define v2pr_info(fmt, ...)	vnpr_info(2, fmt, ##__VA_ARGS__)
123 #define v3pr_info(fmt, ...)	vnpr_info(3, fmt, ##__VA_ARGS__)
124 #define v4pr_info(fmt, ...)	vnpr_info(4, fmt, ##__VA_ARGS__)
125 
126 static void vpr_info_dq(const struct ddebug_query *query, const char *msg)
127 {
128 	/* trim any trailing newlines */
129 	int fmtlen = 0;
130 
131 	if (query->format) {
132 		fmtlen = strlen(query->format);
133 		while (fmtlen && query->format[fmtlen - 1] == '\n')
134 			fmtlen--;
135 	}
136 
137 	v3pr_info("%s: func=\"%s\" file=\"%s\" module=\"%s\" format=\"%.*s\" lineno=%u-%u\n",
138 		 msg,
139 		 query->function ?: "",
140 		 query->filename ?: "",
141 		 query->module ?: "",
142 		 fmtlen, query->format ?: "",
143 		 query->first_lineno, query->last_lineno);
144 }
145 
146 /*
147  * Search the tables for _ddebug's which match the given `query' and
148  * apply the `flags' and `mask' to them.  Returns number of matching
149  * callsites, normally the same as number of changes.  If verbose,
150  * logs the changes.  Takes ddebug_lock.
151  */
152 static int ddebug_change(const struct ddebug_query *query,
153 			 struct flag_settings *modifiers)
154 {
155 	int i;
156 	struct ddebug_table *dt;
157 	unsigned int newflags;
158 	unsigned int nfound = 0;
159 	struct flagsbuf fbuf;
160 
161 	/* search for matching ddebugs */
162 	mutex_lock(&ddebug_lock);
163 	list_for_each_entry(dt, &ddebug_tables, link) {
164 
165 		/* match against the module name */
166 		if (query->module &&
167 		    !match_wildcard(query->module, dt->mod_name))
168 			continue;
169 
170 		for (i = 0; i < dt->num_ddebugs; i++) {
171 			struct _ddebug *dp = &dt->ddebugs[i];
172 
173 			/* match against the source filename */
174 			if (query->filename &&
175 			    !match_wildcard(query->filename, dp->filename) &&
176 			    !match_wildcard(query->filename,
177 					   kbasename(dp->filename)) &&
178 			    !match_wildcard(query->filename,
179 					   trim_prefix(dp->filename)))
180 				continue;
181 
182 			/* match against the function */
183 			if (query->function &&
184 			    !match_wildcard(query->function, dp->function))
185 				continue;
186 
187 			/* match against the format */
188 			if (query->format) {
189 				if (*query->format == '^') {
190 					char *p;
191 					/* anchored search. match must be at beginning */
192 					p = strstr(dp->format, query->format+1);
193 					if (p != dp->format)
194 						continue;
195 				} else if (!strstr(dp->format, query->format))
196 					continue;
197 			}
198 
199 			/* match against the line number range */
200 			if (query->first_lineno &&
201 			    dp->lineno < query->first_lineno)
202 				continue;
203 			if (query->last_lineno &&
204 			    dp->lineno > query->last_lineno)
205 				continue;
206 
207 			nfound++;
208 
209 			newflags = (dp->flags & modifiers->mask) | modifiers->flags;
210 			if (newflags == dp->flags)
211 				continue;
212 #ifdef CONFIG_JUMP_LABEL
213 			if (dp->flags & _DPRINTK_FLAGS_PRINT) {
214 				if (!(newflags & _DPRINTK_FLAGS_PRINT))
215 					static_branch_disable(&dp->key.dd_key_true);
216 			} else if (newflags & _DPRINTK_FLAGS_PRINT) {
217 				static_branch_enable(&dp->key.dd_key_true);
218 			}
219 #endif
220 			dp->flags = newflags;
221 			v4pr_info("changed %s:%d [%s]%s =%s\n",
222 				 trim_prefix(dp->filename), dp->lineno,
223 				 dt->mod_name, dp->function,
224 				 ddebug_describe_flags(dp->flags, &fbuf));
225 		}
226 	}
227 	mutex_unlock(&ddebug_lock);
228 
229 	if (!nfound && verbose)
230 		pr_info("no matches for query\n");
231 
232 	return nfound;
233 }
234 
235 /*
236  * Split the buffer `buf' into space-separated words.
237  * Handles simple " and ' quoting, i.e. without nested,
238  * embedded or escaped \".  Return the number of words
239  * or <0 on error.
240  */
241 static int ddebug_tokenize(char *buf, char *words[], int maxwords)
242 {
243 	int nwords = 0;
244 
245 	while (*buf) {
246 		char *end;
247 
248 		/* Skip leading whitespace */
249 		buf = skip_spaces(buf);
250 		if (!*buf)
251 			break;	/* oh, it was trailing whitespace */
252 		if (*buf == '#')
253 			break;	/* token starts comment, skip rest of line */
254 
255 		/* find `end' of word, whitespace separated or quoted */
256 		if (*buf == '"' || *buf == '\'') {
257 			int quote = *buf++;
258 			for (end = buf; *end && *end != quote; end++)
259 				;
260 			if (!*end) {
261 				pr_err("unclosed quote: %s\n", buf);
262 				return -EINVAL;	/* unclosed quote */
263 			}
264 		} else {
265 			for (end = buf; *end && !isspace(*end); end++)
266 				;
267 			BUG_ON(end == buf);
268 		}
269 
270 		/* `buf' is start of word, `end' is one past its end */
271 		if (nwords == maxwords) {
272 			pr_err("too many words, legal max <=%d\n", maxwords);
273 			return -EINVAL;	/* ran out of words[] before bytes */
274 		}
275 		if (*end)
276 			*end++ = '\0';	/* terminate the word */
277 		words[nwords++] = buf;
278 		buf = end;
279 	}
280 
281 	if (verbose >= 3) {
282 		int i;
283 		pr_info("split into words:");
284 		for (i = 0; i < nwords; i++)
285 			pr_cont(" \"%s\"", words[i]);
286 		pr_cont("\n");
287 	}
288 
289 	return nwords;
290 }
291 
292 /*
293  * Parse a single line number.  Note that the empty string ""
294  * is treated as a special case and converted to zero, which
295  * is later treated as a "don't care" value.
296  */
297 static inline int parse_lineno(const char *str, unsigned int *val)
298 {
299 	BUG_ON(str == NULL);
300 	if (*str == '\0') {
301 		*val = 0;
302 		return 0;
303 	}
304 	if (kstrtouint(str, 10, val) < 0) {
305 		pr_err("bad line-number: %s\n", str);
306 		return -EINVAL;
307 	}
308 	return 0;
309 }
310 
311 static int parse_linerange(struct ddebug_query *query, const char *first)
312 {
313 	char *last = strchr(first, '-');
314 
315 	if (query->first_lineno || query->last_lineno) {
316 		pr_err("match-spec: line used 2x\n");
317 		return -EINVAL;
318 	}
319 	if (last)
320 		*last++ = '\0';
321 	if (parse_lineno(first, &query->first_lineno) < 0)
322 		return -EINVAL;
323 	if (last) {
324 		/* range <first>-<last> */
325 		if (parse_lineno(last, &query->last_lineno) < 0)
326 			return -EINVAL;
327 
328 		/* special case for last lineno not specified */
329 		if (query->last_lineno == 0)
330 			query->last_lineno = UINT_MAX;
331 
332 		if (query->last_lineno < query->first_lineno) {
333 			pr_err("last-line:%d < 1st-line:%d\n",
334 			       query->last_lineno,
335 			       query->first_lineno);
336 			return -EINVAL;
337 		}
338 	} else {
339 		query->last_lineno = query->first_lineno;
340 	}
341 	v3pr_info("parsed line %d-%d\n", query->first_lineno,
342 		 query->last_lineno);
343 	return 0;
344 }
345 
346 static int check_set(const char **dest, char *src, char *name)
347 {
348 	int rc = 0;
349 
350 	if (*dest) {
351 		rc = -EINVAL;
352 		pr_err("match-spec:%s val:%s overridden by %s\n",
353 		       name, *dest, src);
354 	}
355 	*dest = src;
356 	return rc;
357 }
358 
359 /*
360  * Parse words[] as a ddebug query specification, which is a series
361  * of (keyword, value) pairs chosen from these possibilities:
362  *
363  * func <function-name>
364  * file <full-pathname>
365  * file <base-filename>
366  * module <module-name>
367  * format <escaped-string-to-find-in-format>
368  * line <lineno>
369  * line <first-lineno>-<last-lineno> // where either may be empty
370  *
371  * Only 1 of each type is allowed.
372  * Returns 0 on success, <0 on error.
373  */
374 static int ddebug_parse_query(char *words[], int nwords,
375 			struct ddebug_query *query, const char *modname)
376 {
377 	unsigned int i;
378 	int rc = 0;
379 	char *fline;
380 
381 	/* check we have an even number of words */
382 	if (nwords % 2 != 0) {
383 		pr_err("expecting pairs of match-spec <value>\n");
384 		return -EINVAL;
385 	}
386 
387 	if (modname)
388 		/* support $modname.dyndbg=<multiple queries> */
389 		query->module = modname;
390 
391 	for (i = 0; i < nwords; i += 2) {
392 		char *keyword = words[i];
393 		char *arg = words[i+1];
394 
395 		if (!strcmp(keyword, "func")) {
396 			rc = check_set(&query->function, arg, "func");
397 		} else if (!strcmp(keyword, "file")) {
398 			if (check_set(&query->filename, arg, "file"))
399 				return -EINVAL;
400 
401 			/* tail :$info is function or line-range */
402 			fline = strchr(query->filename, ':');
403 			if (!fline)
404 				continue;
405 			*fline++ = '\0';
406 			if (isalpha(*fline) || *fline == '*' || *fline == '?') {
407 				/* take as function name */
408 				if (check_set(&query->function, fline, "func"))
409 					return -EINVAL;
410 			} else {
411 				if (parse_linerange(query, fline))
412 					return -EINVAL;
413 			}
414 		} else if (!strcmp(keyword, "module")) {
415 			rc = check_set(&query->module, arg, "module");
416 		} else if (!strcmp(keyword, "format")) {
417 			string_unescape_inplace(arg, UNESCAPE_SPACE |
418 							    UNESCAPE_OCTAL |
419 							    UNESCAPE_SPECIAL);
420 			rc = check_set(&query->format, arg, "format");
421 		} else if (!strcmp(keyword, "line")) {
422 			if (parse_linerange(query, arg))
423 				return -EINVAL;
424 		} else {
425 			pr_err("unknown keyword \"%s\"\n", keyword);
426 			return -EINVAL;
427 		}
428 		if (rc)
429 			return rc;
430 	}
431 	vpr_info_dq(query, "parsed");
432 	return 0;
433 }
434 
435 /*
436  * Parse `str' as a flags specification, format [-+=][p]+.
437  * Sets up *maskp and *flagsp to be used when changing the
438  * flags fields of matched _ddebug's.  Returns 0 on success
439  * or <0 on error.
440  */
441 static int ddebug_parse_flags(const char *str, struct flag_settings *modifiers)
442 {
443 	int op, i;
444 
445 	switch (*str) {
446 	case '+':
447 	case '-':
448 	case '=':
449 		op = *str++;
450 		break;
451 	default:
452 		pr_err("bad flag-op %c, at start of %s\n", *str, str);
453 		return -EINVAL;
454 	}
455 	v3pr_info("op='%c'\n", op);
456 
457 	for (; *str ; ++str) {
458 		for (i = ARRAY_SIZE(opt_array) - 1; i >= 0; i--) {
459 			if (*str == opt_array[i].opt_char) {
460 				modifiers->flags |= opt_array[i].flag;
461 				break;
462 			}
463 		}
464 		if (i < 0) {
465 			pr_err("unknown flag '%c'\n", *str);
466 			return -EINVAL;
467 		}
468 	}
469 	v3pr_info("flags=0x%x\n", modifiers->flags);
470 
471 	/* calculate final flags, mask based upon op */
472 	switch (op) {
473 	case '=':
474 		/* modifiers->flags already set */
475 		modifiers->mask = 0;
476 		break;
477 	case '+':
478 		modifiers->mask = ~0U;
479 		break;
480 	case '-':
481 		modifiers->mask = ~modifiers->flags;
482 		modifiers->flags = 0;
483 		break;
484 	}
485 	v3pr_info("*flagsp=0x%x *maskp=0x%x\n", modifiers->flags, modifiers->mask);
486 
487 	return 0;
488 }
489 
490 static int ddebug_exec_query(char *query_string, const char *modname)
491 {
492 	struct flag_settings modifiers = {};
493 	struct ddebug_query query = {};
494 #define MAXWORDS 9
495 	int nwords, nfound;
496 	char *words[MAXWORDS];
497 
498 	nwords = ddebug_tokenize(query_string, words, MAXWORDS);
499 	if (nwords <= 0) {
500 		pr_err("tokenize failed\n");
501 		return -EINVAL;
502 	}
503 	/* check flags 1st (last arg) so query is pairs of spec,val */
504 	if (ddebug_parse_flags(words[nwords-1], &modifiers)) {
505 		pr_err("flags parse failed\n");
506 		return -EINVAL;
507 	}
508 	if (ddebug_parse_query(words, nwords-1, &query, modname)) {
509 		pr_err("query parse failed\n");
510 		return -EINVAL;
511 	}
512 	/* actually go and implement the change */
513 	nfound = ddebug_change(&query, &modifiers);
514 	vpr_info_dq(&query, nfound ? "applied" : "no-match");
515 
516 	return nfound;
517 }
518 
519 /* handle multiple queries in query string, continue on error, return
520    last error or number of matching callsites.  Module name is either
521    in param (for boot arg) or perhaps in query string.
522 */
523 static int ddebug_exec_queries(char *query, const char *modname)
524 {
525 	char *split;
526 	int i, errs = 0, exitcode = 0, rc, nfound = 0;
527 
528 	for (i = 0; query; query = split) {
529 		split = strpbrk(query, ";\n");
530 		if (split)
531 			*split++ = '\0';
532 
533 		query = skip_spaces(query);
534 		if (!query || !*query || *query == '#')
535 			continue;
536 
537 		vpr_info("query %d: \"%s\" mod:%s\n", i, query, modname ?: "*");
538 
539 		rc = ddebug_exec_query(query, modname);
540 		if (rc < 0) {
541 			errs++;
542 			exitcode = rc;
543 		} else {
544 			nfound += rc;
545 		}
546 		i++;
547 	}
548 	if (i)
549 		v2pr_info("processed %d queries, with %d matches, %d errs\n",
550 			 i, nfound, errs);
551 
552 	if (exitcode)
553 		return exitcode;
554 	return nfound;
555 }
556 
557 /**
558  * dynamic_debug_exec_queries - select and change dynamic-debug prints
559  * @query: query-string described in admin-guide/dynamic-debug-howto
560  * @modname: string containing module name, usually &module.mod_name
561  *
562  * This uses the >/proc/dynamic_debug/control reader, allowing module
563  * authors to modify their dynamic-debug callsites. The modname is
564  * canonically struct module.mod_name, but can also be null or a
565  * module-wildcard, for example: "drm*".
566  */
567 int dynamic_debug_exec_queries(const char *query, const char *modname)
568 {
569 	int rc;
570 	char *qry; /* writable copy of query */
571 
572 	if (!query) {
573 		pr_err("non-null query/command string expected\n");
574 		return -EINVAL;
575 	}
576 	qry = kstrndup(query, PAGE_SIZE, GFP_KERNEL);
577 	if (!qry)
578 		return -ENOMEM;
579 
580 	rc = ddebug_exec_queries(qry, modname);
581 	kfree(qry);
582 	return rc;
583 }
584 EXPORT_SYMBOL_GPL(dynamic_debug_exec_queries);
585 
586 #define PREFIX_SIZE 64
587 
588 static int remaining(int wrote)
589 {
590 	if (PREFIX_SIZE - wrote > 0)
591 		return PREFIX_SIZE - wrote;
592 	return 0;
593 }
594 
595 static char *__dynamic_emit_prefix(const struct _ddebug *desc, char *buf)
596 {
597 	int pos_after_tid;
598 	int pos = 0;
599 
600 	if (desc->flags & _DPRINTK_FLAGS_INCL_TID) {
601 		if (in_interrupt())
602 			pos += snprintf(buf + pos, remaining(pos), "<intr> ");
603 		else
604 			pos += snprintf(buf + pos, remaining(pos), "[%d] ",
605 					task_pid_vnr(current));
606 	}
607 	pos_after_tid = pos;
608 	if (desc->flags & _DPRINTK_FLAGS_INCL_MODNAME)
609 		pos += snprintf(buf + pos, remaining(pos), "%s:",
610 				desc->modname);
611 	if (desc->flags & _DPRINTK_FLAGS_INCL_FUNCNAME)
612 		pos += snprintf(buf + pos, remaining(pos), "%s:",
613 				desc->function);
614 	if (desc->flags & _DPRINTK_FLAGS_INCL_LINENO)
615 		pos += snprintf(buf + pos, remaining(pos), "%d:",
616 				desc->lineno);
617 	if (pos - pos_after_tid)
618 		pos += snprintf(buf + pos, remaining(pos), " ");
619 	if (pos >= PREFIX_SIZE)
620 		buf[PREFIX_SIZE - 1] = '\0';
621 
622 	return buf;
623 }
624 
625 static inline char *dynamic_emit_prefix(struct _ddebug *desc, char *buf)
626 {
627 	if (unlikely(desc->flags & _DPRINTK_FLAGS_INCL_ANY))
628 		return __dynamic_emit_prefix(desc, buf);
629 	return buf;
630 }
631 
632 void __dynamic_pr_debug(struct _ddebug *descriptor, const char *fmt, ...)
633 {
634 	va_list args;
635 	struct va_format vaf;
636 	char buf[PREFIX_SIZE] = "";
637 
638 	BUG_ON(!descriptor);
639 	BUG_ON(!fmt);
640 
641 	va_start(args, fmt);
642 
643 	vaf.fmt = fmt;
644 	vaf.va = &args;
645 
646 	printk(KERN_DEBUG "%s%pV", dynamic_emit_prefix(descriptor, buf), &vaf);
647 
648 	va_end(args);
649 }
650 EXPORT_SYMBOL(__dynamic_pr_debug);
651 
652 void __dynamic_dev_dbg(struct _ddebug *descriptor,
653 		      const struct device *dev, const char *fmt, ...)
654 {
655 	struct va_format vaf;
656 	va_list args;
657 
658 	BUG_ON(!descriptor);
659 	BUG_ON(!fmt);
660 
661 	va_start(args, fmt);
662 
663 	vaf.fmt = fmt;
664 	vaf.va = &args;
665 
666 	if (!dev) {
667 		printk(KERN_DEBUG "(NULL device *): %pV", &vaf);
668 	} else {
669 		char buf[PREFIX_SIZE] = "";
670 
671 		dev_printk_emit(LOGLEVEL_DEBUG, dev, "%s%s %s: %pV",
672 				dynamic_emit_prefix(descriptor, buf),
673 				dev_driver_string(dev), dev_name(dev),
674 				&vaf);
675 	}
676 
677 	va_end(args);
678 }
679 EXPORT_SYMBOL(__dynamic_dev_dbg);
680 
681 #ifdef CONFIG_NET
682 
683 void __dynamic_netdev_dbg(struct _ddebug *descriptor,
684 			  const struct net_device *dev, const char *fmt, ...)
685 {
686 	struct va_format vaf;
687 	va_list args;
688 
689 	BUG_ON(!descriptor);
690 	BUG_ON(!fmt);
691 
692 	va_start(args, fmt);
693 
694 	vaf.fmt = fmt;
695 	vaf.va = &args;
696 
697 	if (dev && dev->dev.parent) {
698 		char buf[PREFIX_SIZE] = "";
699 
700 		dev_printk_emit(LOGLEVEL_DEBUG, dev->dev.parent,
701 				"%s%s %s %s%s: %pV",
702 				dynamic_emit_prefix(descriptor, buf),
703 				dev_driver_string(dev->dev.parent),
704 				dev_name(dev->dev.parent),
705 				netdev_name(dev), netdev_reg_state(dev),
706 				&vaf);
707 	} else if (dev) {
708 		printk(KERN_DEBUG "%s%s: %pV", netdev_name(dev),
709 		       netdev_reg_state(dev), &vaf);
710 	} else {
711 		printk(KERN_DEBUG "(NULL net_device): %pV", &vaf);
712 	}
713 
714 	va_end(args);
715 }
716 EXPORT_SYMBOL(__dynamic_netdev_dbg);
717 
718 #endif
719 
720 #if IS_ENABLED(CONFIG_INFINIBAND)
721 
722 void __dynamic_ibdev_dbg(struct _ddebug *descriptor,
723 			 const struct ib_device *ibdev, const char *fmt, ...)
724 {
725 	struct va_format vaf;
726 	va_list args;
727 
728 	va_start(args, fmt);
729 
730 	vaf.fmt = fmt;
731 	vaf.va = &args;
732 
733 	if (ibdev && ibdev->dev.parent) {
734 		char buf[PREFIX_SIZE] = "";
735 
736 		dev_printk_emit(LOGLEVEL_DEBUG, ibdev->dev.parent,
737 				"%s%s %s %s: %pV",
738 				dynamic_emit_prefix(descriptor, buf),
739 				dev_driver_string(ibdev->dev.parent),
740 				dev_name(ibdev->dev.parent),
741 				dev_name(&ibdev->dev),
742 				&vaf);
743 	} else if (ibdev) {
744 		printk(KERN_DEBUG "%s: %pV", dev_name(&ibdev->dev), &vaf);
745 	} else {
746 		printk(KERN_DEBUG "(NULL ib_device): %pV", &vaf);
747 	}
748 
749 	va_end(args);
750 }
751 EXPORT_SYMBOL(__dynamic_ibdev_dbg);
752 
753 #endif
754 
755 /*
756  * Install a noop handler to make dyndbg look like a normal kernel cli param.
757  * This avoids warnings about dyndbg being an unknown cli param when supplied
758  * by a user.
759  */
760 static __init int dyndbg_setup(char *str)
761 {
762 	return 1;
763 }
764 
765 __setup("dyndbg=", dyndbg_setup);
766 
767 /*
768  * File_ops->write method for <debugfs>/dynamic_debug/control.  Gathers the
769  * command text from userspace, parses and executes it.
770  */
771 #define USER_BUF_PAGE 4096
772 static ssize_t ddebug_proc_write(struct file *file, const char __user *ubuf,
773 				  size_t len, loff_t *offp)
774 {
775 	char *tmpbuf;
776 	int ret;
777 
778 	if (len == 0)
779 		return 0;
780 	if (len > USER_BUF_PAGE - 1) {
781 		pr_warn("expected <%d bytes into control\n", USER_BUF_PAGE);
782 		return -E2BIG;
783 	}
784 	tmpbuf = memdup_user_nul(ubuf, len);
785 	if (IS_ERR(tmpbuf))
786 		return PTR_ERR(tmpbuf);
787 	v2pr_info("read %zu bytes from userspace\n", len);
788 
789 	ret = ddebug_exec_queries(tmpbuf, NULL);
790 	kfree(tmpbuf);
791 	if (ret < 0)
792 		return ret;
793 
794 	*offp += len;
795 	return len;
796 }
797 
798 /*
799  * Set the iterator to point to the first _ddebug object
800  * and return a pointer to that first object.  Returns
801  * NULL if there are no _ddebugs at all.
802  */
803 static struct _ddebug *ddebug_iter_first(struct ddebug_iter *iter)
804 {
805 	if (list_empty(&ddebug_tables)) {
806 		iter->table = NULL;
807 		iter->idx = 0;
808 		return NULL;
809 	}
810 	iter->table = list_entry(ddebug_tables.next,
811 				 struct ddebug_table, link);
812 	iter->idx = 0;
813 	return &iter->table->ddebugs[iter->idx];
814 }
815 
816 /*
817  * Advance the iterator to point to the next _ddebug
818  * object from the one the iterator currently points at,
819  * and returns a pointer to the new _ddebug.  Returns
820  * NULL if the iterator has seen all the _ddebugs.
821  */
822 static struct _ddebug *ddebug_iter_next(struct ddebug_iter *iter)
823 {
824 	if (iter->table == NULL)
825 		return NULL;
826 	if (++iter->idx == iter->table->num_ddebugs) {
827 		/* iterate to next table */
828 		iter->idx = 0;
829 		if (list_is_last(&iter->table->link, &ddebug_tables)) {
830 			iter->table = NULL;
831 			return NULL;
832 		}
833 		iter->table = list_entry(iter->table->link.next,
834 					 struct ddebug_table, link);
835 	}
836 	return &iter->table->ddebugs[iter->idx];
837 }
838 
839 /*
840  * Seq_ops start method.  Called at the start of every
841  * read() call from userspace.  Takes the ddebug_lock and
842  * seeks the seq_file's iterator to the given position.
843  */
844 static void *ddebug_proc_start(struct seq_file *m, loff_t *pos)
845 {
846 	struct ddebug_iter *iter = m->private;
847 	struct _ddebug *dp;
848 	int n = *pos;
849 
850 	mutex_lock(&ddebug_lock);
851 
852 	if (!n)
853 		return SEQ_START_TOKEN;
854 	if (n < 0)
855 		return NULL;
856 	dp = ddebug_iter_first(iter);
857 	while (dp != NULL && --n > 0)
858 		dp = ddebug_iter_next(iter);
859 	return dp;
860 }
861 
862 /*
863  * Seq_ops next method.  Called several times within a read()
864  * call from userspace, with ddebug_lock held.  Walks to the
865  * next _ddebug object with a special case for the header line.
866  */
867 static void *ddebug_proc_next(struct seq_file *m, void *p, loff_t *pos)
868 {
869 	struct ddebug_iter *iter = m->private;
870 	struct _ddebug *dp;
871 
872 	if (p == SEQ_START_TOKEN)
873 		dp = ddebug_iter_first(iter);
874 	else
875 		dp = ddebug_iter_next(iter);
876 	++*pos;
877 	return dp;
878 }
879 
880 /*
881  * Seq_ops show method.  Called several times within a read()
882  * call from userspace, with ddebug_lock held.  Formats the
883  * current _ddebug as a single human-readable line, with a
884  * special case for the header line.
885  */
886 static int ddebug_proc_show(struct seq_file *m, void *p)
887 {
888 	struct ddebug_iter *iter = m->private;
889 	struct _ddebug *dp = p;
890 	struct flagsbuf flags;
891 
892 	if (p == SEQ_START_TOKEN) {
893 		seq_puts(m,
894 			 "# filename:lineno [module]function flags format\n");
895 		return 0;
896 	}
897 
898 	seq_printf(m, "%s:%u [%s]%s =%s \"",
899 		   trim_prefix(dp->filename), dp->lineno,
900 		   iter->table->mod_name, dp->function,
901 		   ddebug_describe_flags(dp->flags, &flags));
902 	seq_escape(m, dp->format, "\t\r\n\"");
903 	seq_puts(m, "\"\n");
904 
905 	return 0;
906 }
907 
908 /*
909  * Seq_ops stop method.  Called at the end of each read()
910  * call from userspace.  Drops ddebug_lock.
911  */
912 static void ddebug_proc_stop(struct seq_file *m, void *p)
913 {
914 	mutex_unlock(&ddebug_lock);
915 }
916 
917 static const struct seq_operations ddebug_proc_seqops = {
918 	.start = ddebug_proc_start,
919 	.next = ddebug_proc_next,
920 	.show = ddebug_proc_show,
921 	.stop = ddebug_proc_stop
922 };
923 
924 static int ddebug_proc_open(struct inode *inode, struct file *file)
925 {
926 	return seq_open_private(file, &ddebug_proc_seqops,
927 				sizeof(struct ddebug_iter));
928 }
929 
930 static const struct file_operations ddebug_proc_fops = {
931 	.owner = THIS_MODULE,
932 	.open = ddebug_proc_open,
933 	.read = seq_read,
934 	.llseek = seq_lseek,
935 	.release = seq_release_private,
936 	.write = ddebug_proc_write
937 };
938 
939 static const struct proc_ops proc_fops = {
940 	.proc_open = ddebug_proc_open,
941 	.proc_read = seq_read,
942 	.proc_lseek = seq_lseek,
943 	.proc_release = seq_release_private,
944 	.proc_write = ddebug_proc_write
945 };
946 
947 /*
948  * Allocate a new ddebug_table for the given module
949  * and add it to the global list.
950  */
951 int ddebug_add_module(struct _ddebug *tab, unsigned int n,
952 			     const char *name)
953 {
954 	struct ddebug_table *dt;
955 
956 	dt = kzalloc(sizeof(*dt), GFP_KERNEL);
957 	if (dt == NULL) {
958 		pr_err("error adding module: %s\n", name);
959 		return -ENOMEM;
960 	}
961 	/*
962 	 * For built-in modules, name lives in .rodata and is
963 	 * immortal. For loaded modules, name points at the name[]
964 	 * member of struct module, which lives at least as long as
965 	 * this struct ddebug_table.
966 	 */
967 	dt->mod_name = name;
968 	dt->num_ddebugs = n;
969 	dt->ddebugs = tab;
970 
971 	mutex_lock(&ddebug_lock);
972 	list_add(&dt->link, &ddebug_tables);
973 	mutex_unlock(&ddebug_lock);
974 
975 	vpr_info("%3u debug prints in module %s\n", n, dt->mod_name);
976 	return 0;
977 }
978 
979 /* helper for ddebug_dyndbg_(boot|module)_param_cb */
980 static int ddebug_dyndbg_param_cb(char *param, char *val,
981 				const char *modname, int on_err)
982 {
983 	char *sep;
984 
985 	sep = strchr(param, '.');
986 	if (sep) {
987 		/* needed only for ddebug_dyndbg_boot_param_cb */
988 		*sep = '\0';
989 		modname = param;
990 		param = sep + 1;
991 	}
992 	if (strcmp(param, "dyndbg"))
993 		return on_err; /* determined by caller */
994 
995 	ddebug_exec_queries((val ? val : "+p"), modname);
996 
997 	return 0; /* query failure shouldn't stop module load */
998 }
999 
1000 /* handle both dyndbg and $module.dyndbg params at boot */
1001 static int ddebug_dyndbg_boot_param_cb(char *param, char *val,
1002 				const char *unused, void *arg)
1003 {
1004 	vpr_info("%s=\"%s\"\n", param, val);
1005 	return ddebug_dyndbg_param_cb(param, val, NULL, 0);
1006 }
1007 
1008 /*
1009  * modprobe foo finds foo.params in boot-args, strips "foo.", and
1010  * passes them to load_module().  This callback gets unknown params,
1011  * processes dyndbg params, rejects others.
1012  */
1013 int ddebug_dyndbg_module_param_cb(char *param, char *val, const char *module)
1014 {
1015 	vpr_info("module: %s %s=\"%s\"\n", module, param, val);
1016 	return ddebug_dyndbg_param_cb(param, val, module, -ENOENT);
1017 }
1018 
1019 static void ddebug_table_free(struct ddebug_table *dt)
1020 {
1021 	list_del_init(&dt->link);
1022 	kfree(dt);
1023 }
1024 
1025 /*
1026  * Called in response to a module being unloaded.  Removes
1027  * any ddebug_table's which point at the module.
1028  */
1029 int ddebug_remove_module(const char *mod_name)
1030 {
1031 	struct ddebug_table *dt, *nextdt;
1032 	int ret = -ENOENT;
1033 
1034 	mutex_lock(&ddebug_lock);
1035 	list_for_each_entry_safe(dt, nextdt, &ddebug_tables, link) {
1036 		if (dt->mod_name == mod_name) {
1037 			ddebug_table_free(dt);
1038 			ret = 0;
1039 			break;
1040 		}
1041 	}
1042 	mutex_unlock(&ddebug_lock);
1043 	if (!ret)
1044 		v2pr_info("removed module \"%s\"\n", mod_name);
1045 	return ret;
1046 }
1047 
1048 static void ddebug_remove_all_tables(void)
1049 {
1050 	mutex_lock(&ddebug_lock);
1051 	while (!list_empty(&ddebug_tables)) {
1052 		struct ddebug_table *dt = list_entry(ddebug_tables.next,
1053 						      struct ddebug_table,
1054 						      link);
1055 		ddebug_table_free(dt);
1056 	}
1057 	mutex_unlock(&ddebug_lock);
1058 }
1059 
1060 static __initdata int ddebug_init_success;
1061 
1062 static int __init dynamic_debug_init_control(void)
1063 {
1064 	struct proc_dir_entry *procfs_dir;
1065 	struct dentry *debugfs_dir;
1066 
1067 	if (!ddebug_init_success)
1068 		return -ENODEV;
1069 
1070 	/* Create the control file in debugfs if it is enabled */
1071 	if (debugfs_initialized()) {
1072 		debugfs_dir = debugfs_create_dir("dynamic_debug", NULL);
1073 		debugfs_create_file("control", 0644, debugfs_dir, NULL,
1074 				    &ddebug_proc_fops);
1075 	}
1076 
1077 	/* Also create the control file in procfs */
1078 	procfs_dir = proc_mkdir("dynamic_debug", NULL);
1079 	if (procfs_dir)
1080 		proc_create("control", 0644, procfs_dir, &proc_fops);
1081 
1082 	return 0;
1083 }
1084 
1085 static int __init dynamic_debug_init(void)
1086 {
1087 	struct _ddebug *iter, *iter_start;
1088 	const char *modname = NULL;
1089 	char *cmdline;
1090 	int ret = 0;
1091 	int n = 0, entries = 0, modct = 0;
1092 
1093 	if (&__start___dyndbg == &__stop___dyndbg) {
1094 		if (IS_ENABLED(CONFIG_DYNAMIC_DEBUG)) {
1095 			pr_warn("_ddebug table is empty in a CONFIG_DYNAMIC_DEBUG build\n");
1096 			return 1;
1097 		}
1098 		pr_info("Ignore empty _ddebug table in a CONFIG_DYNAMIC_DEBUG_CORE build\n");
1099 		ddebug_init_success = 1;
1100 		return 0;
1101 	}
1102 	iter = __start___dyndbg;
1103 	modname = iter->modname;
1104 	iter_start = iter;
1105 	for (; iter < __stop___dyndbg; iter++) {
1106 		entries++;
1107 		if (strcmp(modname, iter->modname)) {
1108 			modct++;
1109 			ret = ddebug_add_module(iter_start, n, modname);
1110 			if (ret)
1111 				goto out_err;
1112 			n = 0;
1113 			modname = iter->modname;
1114 			iter_start = iter;
1115 		}
1116 		n++;
1117 	}
1118 	ret = ddebug_add_module(iter_start, n, modname);
1119 	if (ret)
1120 		goto out_err;
1121 
1122 	ddebug_init_success = 1;
1123 	vpr_info("%d prdebugs in %d modules, %d KiB in ddebug tables, %d kiB in __dyndbg section\n",
1124 		 entries, modct, (int)((modct * sizeof(struct ddebug_table)) >> 10),
1125 		 (int)((entries * sizeof(struct _ddebug)) >> 10));
1126 
1127 	/* now that ddebug tables are loaded, process all boot args
1128 	 * again to find and activate queries given in dyndbg params.
1129 	 * While this has already been done for known boot params, it
1130 	 * ignored the unknown ones (dyndbg in particular).  Reusing
1131 	 * parse_args avoids ad-hoc parsing.  This will also attempt
1132 	 * to activate queries for not-yet-loaded modules, which is
1133 	 * slightly noisy if verbose, but harmless.
1134 	 */
1135 	cmdline = kstrdup(saved_command_line, GFP_KERNEL);
1136 	parse_args("dyndbg params", cmdline, NULL,
1137 		   0, 0, 0, NULL, &ddebug_dyndbg_boot_param_cb);
1138 	kfree(cmdline);
1139 	return 0;
1140 
1141 out_err:
1142 	ddebug_remove_all_tables();
1143 	return 0;
1144 }
1145 /* Allow early initialization for boot messages via boot param */
1146 early_initcall(dynamic_debug_init);
1147 
1148 /* Debugfs setup must be done later */
1149 fs_initcall(dynamic_debug_init_control);
1150