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