2 * Kernel Debugger Architecture Independent Console I/O handler
4 * This file is subject to the terms and conditions of the GNU General Public
5 * License. See the file "COPYING" in the main directory of this archive
8 * Copyright (c) 1999-2006 Silicon Graphics, Inc. All Rights Reserved.
9 * Copyright (c) 2009 Wind River Systems, Inc. All Rights Reserved.
12 #include <linux/types.h>
13 #include <linux/ctype.h>
14 #include <linux/kernel.h>
15 #include <linux/init.h>
16 #include <linux/kdev_t.h>
17 #include <linux/console.h>
18 #include <linux/string.h>
19 #include <linux/sched.h>
20 #include <linux/smp.h>
21 #include <linux/nmi.h>
22 #include <linux/delay.h>
23 #include <linux/kgdb.h>
24 #include <linux/kdb.h>
25 #include <linux/kallsyms.h>
26 #include "kdb_private.h"
28 #define CMD_BUFLEN 256
29 char kdb_prompt_str[CMD_BUFLEN];
32 int kdb_printf_cpu = -1;
34 static int kgdb_transition_check(char *buffer)
36 if (buffer[0] != '+' && buffer[0] != '$') {
37 KDB_STATE_SET(KGDB_TRANS);
38 kdb_printf("%s", buffer);
40 int slen = strlen(buffer);
41 if (slen > 3 && buffer[slen - 3] == '#') {
42 kdb_gdb_state_pass(buffer);
43 strcpy(buffer, "kgdb");
44 KDB_STATE_SET(DOING_KGDB);
52 * kdb_handle_escape() - validity check on an accumulated escape sequence.
53 * @buf: Accumulated escape characters to be examined. Note that buf
54 * is not a string, it is an array of characters and need not be
56 * @sz: Number of accumulated escape characters.
58 * Return: -1 if the escape sequence is unwanted, 0 if it is incomplete,
59 * otherwise it returns a mapped key value to pass to the upper layers.
61 static int kdb_handle_escape(char *buf, size_t sz)
63 char *lastkey = buf + sz - 1;
71 case 2: /* \e<something> */
78 case 'A': /* \e[A, up arrow */
80 case 'B': /* \e[B, down arrow */
82 case 'C': /* \e[C, right arrow */
84 case 'D': /* \e[D, left arrow */
86 case '1': /* \e[<1,3,4>], may be home, del, end */
94 if (*lastkey == '~') {
96 case '1': /* \e[1~, home */
98 case '3': /* \e[3~, del */
100 case '4': /* \e[4~, end */
111 * kdb_getchar() - Read a single character from a kdb console (or consoles).
113 * Other than polling the various consoles that are currently enabled,
114 * most of the work done in this function is dealing with escape sequences.
116 * An escape key could be the start of a vt100 control sequence such as \e[D
117 * (left arrow) or it could be a character in its own right. The standard
118 * method for detecting the difference is to wait for 2 seconds to see if there
119 * are any other characters. kdb is complicated by the lack of a timer service
120 * (interrupts are off), by multiple input sources. Escape sequence processing
121 * has to be done as states in the polling loop.
123 * Return: The key pressed or a control code derived from an escape sequence.
125 char kdb_getchar(void)
127 #define ESCAPE_UDELAY 1000
128 #define ESCAPE_DELAY (2*1000000/ESCAPE_UDELAY) /* 2 seconds worth of udelays */
129 char buf[4]; /* longest vt100 escape sequence is 4 bytes */
131 int escape_delay = 0;
132 get_char_func *f, *f_prev = NULL;
135 for (f = &kdb_poll_funcs[0]; ; ++f) {
137 /* Reset NMI watchdog once per poll loop */
138 touch_nmi_watchdog();
139 f = &kdb_poll_funcs[0];
145 udelay(ESCAPE_UDELAY);
146 if (--escape_delay == 0)
153 * When the first character is received (or we get a change
154 * input source) we set ourselves up to handle an escape
155 * sequences (just in case).
160 escape_delay = ESCAPE_DELAY;
164 key = kdb_handle_escape(buf, pbuf - buf);
165 if (key < 0) /* no escape sequence; return best character */
166 return buf[pbuf - buf == 2 ? 1 : 0];
177 * This function reads a string of characters, terminated by
178 * a newline, or by reaching the end of the supplied buffer,
179 * from the current kernel debugger console device.
181 * buffer - Address of character buffer to receive input characters.
182 * bufsize - size, in bytes, of the character buffer
184 * Returns a pointer to the buffer containing the received
185 * character string. This string will be terminated by a
188 * No locks are required to be held upon entry to this
189 * function. It is not reentrant - it relies on the fact
190 * that while kdb is running on only one "master debug" cpu.
192 * The buffer size must be >= 2.
195 static char *kdb_read(char *buffer, size_t bufsize)
198 char *bufend = buffer+bufsize-2; /* Reserve space for newline
203 static char tmpbuffer[CMD_BUFLEN];
204 int len = strlen(buffer);
209 int diag, dtab_count;
210 int key, buf_size, ret;
213 diag = kdbgetintenv("DTABCOUNT", &dtab_count);
219 if (*(buffer+len-1) == '\n')
225 kdb_printf("%s", buffer);
231 case 8: /* backspace */
234 memcpy(tmpbuffer, cp, lastchar - cp);
235 memcpy(cp-1, tmpbuffer, lastchar - cp);
237 *(--lastchar) = '\0';
239 kdb_printf("\b%s \r", cp);
242 kdb_printf(kdb_prompt_str);
243 kdb_printf("%s", buffer);
250 if (!KDB_STATE(KGDB_TRANS)) {
251 KDB_STATE_SET(KGDB_TRANS);
252 kdb_printf("%s", buffer);
258 memcpy(tmpbuffer, cp+1, lastchar - cp - 1);
259 memcpy(cp, tmpbuffer, lastchar - cp - 1);
260 *(--lastchar) = '\0';
261 kdb_printf("%s \r", cp);
264 kdb_printf(kdb_prompt_str);
265 kdb_printf("%s", buffer);
272 kdb_printf(kdb_prompt_str);
278 kdb_printf("%s", cp);
289 memset(tmpbuffer, ' ',
290 strlen(kdb_prompt_str) + (lastchar-buffer));
291 *(tmpbuffer+strlen(kdb_prompt_str) +
292 (lastchar-buffer)) = '\0';
293 kdb_printf("\r%s\r", tmpbuffer);
294 *lastchar = (char)key;
295 *(lastchar+1) = '\0';
299 kdb_printf("%c", *cp);
304 memset(tmpbuffer, ' ',
305 strlen(kdb_prompt_str) + (lastchar-buffer));
306 *(tmpbuffer+strlen(kdb_prompt_str) +
307 (lastchar-buffer)) = '\0';
308 kdb_printf("\r%s\r", tmpbuffer);
309 *lastchar = (char)key;
310 *(lastchar+1) = '\0';
316 while (*p_tmp == ' ')
320 memcpy(tmpbuffer, p_tmp, cp-p_tmp);
321 *(tmpbuffer + (cp-p_tmp)) = '\0';
322 p_tmp = strrchr(tmpbuffer, ' ');
328 buf_size = sizeof(tmpbuffer) - (p_tmp - tmpbuffer);
329 count = kallsyms_symbol_complete(p_tmp, buf_size);
330 if (tab == 2 && count > 0) {
331 kdb_printf("\n%d symbols are found.", count);
332 if (count > dtab_count) {
334 kdb_printf(" But only first %d symbols will"
335 " be printed.\nYou can change the"
336 " environment variable DTABCOUNT.",
340 for (i = 0; i < count; i++) {
341 ret = kallsyms_symbol_next(p_tmp, i, buf_size);
345 kdb_printf("%s ", p_tmp);
347 kdb_printf("%s... ", p_tmp);
348 *(p_tmp + len) = '\0';
353 kdb_printf(kdb_prompt_str);
354 kdb_printf("%s", buffer);
355 } else if (tab != 2 && count > 0) {
356 len_tmp = strlen(p_tmp);
357 strncpy(p_tmp+len_tmp, cp, lastchar-cp+1);
358 len_tmp = strlen(p_tmp);
359 strncpy(cp, p_tmp+len, len_tmp-len + 1);
361 kdb_printf("%s", cp);
365 kdb_nextline = 1; /* reset output line number */
368 if (key >= 32 && lastchar < bufend) {
370 memcpy(tmpbuffer, cp, lastchar - cp);
371 memcpy(cp+1, tmpbuffer, lastchar - cp);
374 kdb_printf("%s\r", cp);
378 kdb_printf(kdb_prompt_str);
379 kdb_printf("%s", buffer);
384 /* The kgdb transition check will hide
385 * printed characters if we think that
386 * kgdb is connecting, until the check
388 if (!KDB_STATE(KGDB_TRANS)) {
389 if (kgdb_transition_check(buffer))
392 kdb_printf("%c", key);
395 /* Special escape to kgdb */
396 if (lastchar - buffer >= 5 &&
397 strcmp(lastchar - 5, "$?#3f") == 0) {
398 kdb_gdb_state_pass(lastchar - 5);
399 strcpy(buffer, "kgdb");
400 KDB_STATE_SET(DOING_KGDB);
403 if (lastchar - buffer >= 11 &&
404 strcmp(lastchar - 11, "$qSupported") == 0) {
405 kdb_gdb_state_pass(lastchar - 11);
406 strcpy(buffer, "kgdb");
407 KDB_STATE_SET(DOING_KGDB);
419 * Print the prompt string and read a command from the
423 * buffer Address of buffer to receive command
424 * bufsize Size of buffer in bytes
425 * prompt Pointer to string to use as prompt string
427 * Pointer to command buffer.
431 * For SMP kernels, the processor number will be
432 * substituted for %d, %x or %o in the prompt.
435 char *kdb_getstr(char *buffer, size_t bufsize, const char *prompt)
437 if (prompt && kdb_prompt_str != prompt)
438 strscpy(kdb_prompt_str, prompt, CMD_BUFLEN);
439 kdb_printf(kdb_prompt_str);
440 kdb_nextline = 1; /* Prompt and input resets line number */
441 return kdb_read(buffer, bufsize);
447 * Get rid of any buffered console input.
456 * Call this function whenever you want to flush input. If there is any
457 * outstanding input, it ignores all characters until there has been no
458 * data for approximately 1ms.
461 static void kdb_input_flush(void)
466 while (flush_delay) {
469 touch_nmi_watchdog();
470 for (f = &kdb_poll_funcs[0]; *f; ++f) {
485 * Print a string to the output device(s).
488 * printf-like format and optional args.
494 * use 'kdbcons->write()' to avoid polluting 'log_buf' with
497 * If the user is doing a cmd args | grep srch
498 * then kdb_grepping_flag is set.
499 * In that case we need to accumulate full lines (ending in \n) before
500 * searching for the pattern.
503 static char kdb_buffer[256]; /* A bit too big to go on stack */
504 static char *next_avail = kdb_buffer;
505 static int size_avail;
506 static int suspend_grep;
509 * search arg1 to see if it contains arg2
510 * (kdmain.c provides flags for ^pat and pat$)
512 * return 1 for found, 0 for not found
514 static int kdb_search_string(char *searched, char *searchfor)
519 /* not counting the newline at the end of "searched" */
520 len1 = strlen(searched)-1;
521 len2 = strlen(searchfor);
524 if (kdb_grep_leading && kdb_grep_trailing && len1 != len2)
526 if (kdb_grep_leading) {
527 if (!strncmp(searched, searchfor, len2))
529 } else if (kdb_grep_trailing) {
530 if (!strncmp(searched+len1-len2, searchfor, len2))
533 firstchar = *searchfor;
535 while ((cp = strchr(cp, firstchar))) {
536 if (!strncmp(cp, searchfor, len2))
544 static void kdb_msg_write(const char *msg, int msg_len)
558 dbg_io_ops->write_char(*cp);
563 * The console_srcu_read_lock() only provides safe console list
564 * traversal. The use of the ->write() callback relies on all other
565 * CPUs being stopped at the moment and console drivers being able to
566 * handle reentrance when @oops_in_progress is set.
568 * There is no guarantee that every console driver can handle
569 * reentrance in this way; the developer deploying the debugger
570 * is responsible for ensuring that the console drivers they
571 * have selected handle reentrance appropriately.
573 cookie = console_srcu_read_lock();
574 for_each_console_srcu(c) {
575 if (!(console_srcu_read_flags(c) & CON_ENABLED))
577 if (c == dbg_io_ops->cons)
580 * Set oops_in_progress to encourage the console drivers to
581 * disregard their internal spin locks: in the current calling
582 * context the risk of deadlock is a bigger problem than risks
583 * due to re-entering the console driver. We operate directly on
584 * oops_in_progress rather than using bust_spinlocks() because
585 * the calls bust_spinlocks() makes on exit are not appropriate
586 * for this calling context.
589 c->write(c, msg, msg_len);
591 touch_nmi_watchdog();
593 console_srcu_read_unlock(cookie);
596 int vkdb_printf(enum kdb_msgsrc src, const char *fmt, va_list ap)
601 int logging, saved_loglevel = 0;
604 int this_cpu, old_cpu;
605 char *cp, *cp2, *cphold = NULL, replaced_byte = ' ';
606 char *moreprompt = "more> ";
609 /* Serialize kdb_printf if multiple cpus try to write at once.
610 * But if any cpu goes recursive in kdb, just print the output,
611 * even if it is interleaved with any other text.
613 local_irq_save(flags);
614 this_cpu = smp_processor_id();
616 old_cpu = cmpxchg(&kdb_printf_cpu, -1, this_cpu);
617 if (old_cpu == -1 || old_cpu == this_cpu)
623 diag = kdbgetintenv("LINES", &linecount);
624 if (diag || linecount <= 1)
627 diag = kdbgetintenv("COLUMNS", &colcount);
628 if (diag || colcount <= 1)
631 diag = kdbgetintenv("LOGGING", &logging);
635 if (!kdb_grepping_flag || suspend_grep) {
636 /* normally, every vsnprintf starts a new buffer */
637 next_avail = kdb_buffer;
638 size_avail = sizeof(kdb_buffer);
640 vsnprintf(next_avail, size_avail, fmt, ap);
643 * If kdb_parse() found that the command was cmd xxx | grep yyy
644 * then kdb_grepping_flag is set, and kdb_grep_string contains yyy
646 * Accumulate the print data up to a newline before searching it.
647 * (vsnprintf does null-terminate the string that it generates)
650 /* skip the search if prints are temporarily unconditional */
651 if (!suspend_grep && kdb_grepping_flag) {
652 cp = strchr(kdb_buffer, '\n');
655 * Special cases that don't end with newlines
656 * but should be written without one:
657 * The "[nn]kdb> " prompt should
658 * appear at the front of the buffer.
660 * The "[nn]more " prompt should also be
661 * (MOREPROMPT -> moreprompt)
662 * written * but we print that ourselves,
663 * we set the suspend_grep flag to make
667 if (next_avail == kdb_buffer) {
669 * these should occur after a newline,
670 * so they will be at the front of the
674 len = strlen(kdb_prompt_str);
675 if (!strncmp(cp2, kdb_prompt_str, len)) {
677 * We're about to start a new
678 * command, so we can go back
681 kdb_grepping_flag = 0;
685 /* no newline; don't search/write the buffer
686 until one is there */
687 len = strlen(kdb_buffer);
688 next_avail = kdb_buffer + len;
689 size_avail = sizeof(kdb_buffer) - len;
694 * The newline is present; print through it or discard
695 * it, depending on the results of the search.
697 cp++; /* to byte after the newline */
698 replaced_byte = *cp; /* remember what/where it was */
700 *cp = '\0'; /* end the string for our search */
703 * We now have a newline at the end of the string
704 * Only continue with this output if it contains the
707 fnd = kdb_search_string(kdb_buffer, kdb_grep_string);
710 * At this point the complete line at the start
711 * of kdb_buffer can be discarded, as it does
712 * not contain what the user is looking for.
713 * Shift the buffer left.
715 *cphold = replaced_byte;
716 strcpy(kdb_buffer, cphold);
717 len = strlen(kdb_buffer);
718 next_avail = kdb_buffer + len;
719 size_avail = sizeof(kdb_buffer) - len;
722 if (kdb_grepping_flag >= KDB_GREPPING_FLAG_SEARCH) {
724 * This was a interactive search (using '/' at more
725 * prompt) and it has completed. Replace the \0 with
726 * its original value to ensure multi-line strings
727 * are handled properly, and return to normal mode.
729 *cphold = replaced_byte;
730 kdb_grepping_flag = 0;
733 * at this point the string is a full line and
734 * should be printed, up to the null.
740 * Write to all consoles.
742 retlen = strlen(kdb_buffer);
743 cp = (char *) printk_skip_headers(kdb_buffer);
744 if (!dbg_kdb_mode && kgdb_connected)
745 gdbstub_msg_write(cp, retlen - (cp - kdb_buffer));
747 kdb_msg_write(cp, retlen - (cp - kdb_buffer));
750 saved_loglevel = console_loglevel;
751 console_loglevel = CONSOLE_LOGLEVEL_SILENT;
752 if (printk_get_level(kdb_buffer) || src == KDB_MSGSRC_PRINTK)
753 printk("%s", kdb_buffer);
755 pr_info("%s", kdb_buffer);
758 if (KDB_STATE(PAGER)) {
760 * Check printed string to decide how to bump the
761 * kdb_nextline to control when the more prompt should
767 if (kdb_buffer[len] == '\n') {
770 } else if (kdb_buffer[len] == '\r') {
776 kdb_nextline += got / (colcount + 1);
779 /* check for having reached the LINES number of printed lines */
780 if (kdb_nextline >= linecount) {
783 /* Watch out for recursion here. Any routine that calls
784 * kdb_printf will come back through here. And kdb_read
785 * uses kdb_printf to echo on serial consoles ...
787 kdb_nextline = 1; /* In case of recursion */
792 moreprompt = kdbgetenv("MOREPROMPT");
793 if (moreprompt == NULL)
794 moreprompt = "more> ";
797 kdb_msg_write(moreprompt, strlen(moreprompt));
800 printk("%s", moreprompt);
803 kdb_nextline = 1; /* Really set output line 1 */
805 /* empty and reset the buffer: */
806 kdb_buffer[0] = '\0';
807 next_avail = kdb_buffer;
808 size_avail = sizeof(kdb_buffer);
809 if ((ch == 'q') || (ch == 'Q')) {
810 /* user hit q or Q */
811 KDB_FLAG_SET(CMD_INTERRUPT); /* command interrupted */
812 KDB_STATE_CLEAR(PAGER);
813 /* end of command output; back to normal mode */
814 kdb_grepping_flag = 0;
816 } else if (ch == ' ') {
818 suspend_grep = 1; /* for this recursion */
819 } else if (ch == '\n' || ch == '\r') {
820 kdb_nextline = linecount - 1;
822 suspend_grep = 1; /* for this recursion */
823 } else if (ch == '/' && !kdb_grepping_flag) {
825 kdb_getstr(kdb_grep_string, KDB_GREP_STRLEN,
826 kdbgetenv("SEARCHPROMPT") ?: "search> ");
827 *strchrnul(kdb_grep_string, '\n') = '\0';
828 kdb_grepping_flag += KDB_GREPPING_FLAG_SEARCH;
829 suspend_grep = 1; /* for this recursion */
831 /* user hit something unexpected */
832 suspend_grep = 1; /* for this recursion */
835 "\nOnly 'q', 'Q' or '/' are processed at "
836 "more prompt, input ignored\n");
838 kdb_printf("\n'/' cannot be used during | "
839 "grep filtering, input ignored\n");
840 } else if (kdb_grepping_flag) {
842 suspend_grep = 1; /* for this recursion */
849 * For grep searches, shift the printed string left.
850 * replaced_byte contains the character that was overwritten with
851 * the terminating null, and cphold points to the null.
852 * Then adjust the notion of available space in the buffer.
854 if (kdb_grepping_flag && !suspend_grep) {
855 *cphold = replaced_byte;
856 strcpy(kdb_buffer, cphold);
857 len = strlen(kdb_buffer);
858 next_avail = kdb_buffer + len;
859 size_avail = sizeof(kdb_buffer) - len;
863 suspend_grep = 0; /* end of what may have been a recursive call */
865 console_loglevel = saved_loglevel;
866 /* kdb_printf_cpu locked the code above. */
867 smp_store_release(&kdb_printf_cpu, old_cpu);
868 local_irq_restore(flags);
872 int kdb_printf(const char *fmt, ...)
878 r = vkdb_printf(KDB_MSGSRC_INTERNAL, fmt, ap);
883 EXPORT_SYMBOL_GPL(kdb_printf);