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