xref: /linux/drivers/tty/serial/kgdboc.c (revision 2da68a77)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Based on the same principle as kgdboe using the NETPOLL api, this
4  * driver uses a console polling api to implement a gdb serial inteface
5  * which is multiplexed on a console port.
6  *
7  * Maintainer: Jason Wessel <jason.wessel@windriver.com>
8  *
9  * 2007-2008 (c) Jason Wessel - Wind River Systems, Inc.
10  */
11 
12 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
13 
14 #include <linux/kernel.h>
15 #include <linux/ctype.h>
16 #include <linux/kgdb.h>
17 #include <linux/kdb.h>
18 #include <linux/tty.h>
19 #include <linux/console.h>
20 #include <linux/vt_kern.h>
21 #include <linux/input.h>
22 #include <linux/module.h>
23 #include <linux/platform_device.h>
24 #include <linux/serial_core.h>
25 
26 #define MAX_CONFIG_LEN		40
27 
28 static struct kgdb_io		kgdboc_io_ops;
29 
30 /* -1 = init not run yet, 0 = unconfigured, 1 = configured. */
31 static int configured		= -1;
32 static DEFINE_MUTEX(config_mutex);
33 
34 static char config[MAX_CONFIG_LEN];
35 static struct kparam_string kps = {
36 	.string			= config,
37 	.maxlen			= MAX_CONFIG_LEN,
38 };
39 
40 static int kgdboc_use_kms;  /* 1 if we use kernel mode switching */
41 static struct tty_driver	*kgdb_tty_driver;
42 static int			kgdb_tty_line;
43 
44 static struct platform_device *kgdboc_pdev;
45 
46 #if IS_BUILTIN(CONFIG_KGDB_SERIAL_CONSOLE)
47 static struct kgdb_io		kgdboc_earlycon_io_ops;
48 static int                      (*earlycon_orig_exit)(struct console *con);
49 #endif /* IS_BUILTIN(CONFIG_KGDB_SERIAL_CONSOLE) */
50 
51 #ifdef CONFIG_KDB_KEYBOARD
52 static int kgdboc_reset_connect(struct input_handler *handler,
53 				struct input_dev *dev,
54 				const struct input_device_id *id)
55 {
56 	input_reset_device(dev);
57 
58 	/* Return an error - we do not want to bind, just to reset */
59 	return -ENODEV;
60 }
61 
62 static void kgdboc_reset_disconnect(struct input_handle *handle)
63 {
64 	/* We do not expect anyone to actually bind to us */
65 	BUG();
66 }
67 
68 static const struct input_device_id kgdboc_reset_ids[] = {
69 	{
70 		.flags = INPUT_DEVICE_ID_MATCH_EVBIT,
71 		.evbit = { BIT_MASK(EV_KEY) },
72 	},
73 	{ }
74 };
75 
76 static struct input_handler kgdboc_reset_handler = {
77 	.connect	= kgdboc_reset_connect,
78 	.disconnect	= kgdboc_reset_disconnect,
79 	.name		= "kgdboc_reset",
80 	.id_table	= kgdboc_reset_ids,
81 };
82 
83 static DEFINE_MUTEX(kgdboc_reset_mutex);
84 
85 static void kgdboc_restore_input_helper(struct work_struct *dummy)
86 {
87 	/*
88 	 * We need to take a mutex to prevent several instances of
89 	 * this work running on different CPUs so they don't try
90 	 * to register again already registered handler.
91 	 */
92 	mutex_lock(&kgdboc_reset_mutex);
93 
94 	if (input_register_handler(&kgdboc_reset_handler) == 0)
95 		input_unregister_handler(&kgdboc_reset_handler);
96 
97 	mutex_unlock(&kgdboc_reset_mutex);
98 }
99 
100 static DECLARE_WORK(kgdboc_restore_input_work, kgdboc_restore_input_helper);
101 
102 static void kgdboc_restore_input(void)
103 {
104 	if (likely(system_state == SYSTEM_RUNNING))
105 		schedule_work(&kgdboc_restore_input_work);
106 }
107 
108 static int kgdboc_register_kbd(char **cptr)
109 {
110 	if (strncmp(*cptr, "kbd", 3) == 0 ||
111 		strncmp(*cptr, "kdb", 3) == 0) {
112 		if (kdb_poll_idx < KDB_POLL_FUNC_MAX) {
113 			kdb_poll_funcs[kdb_poll_idx] = kdb_get_kbd_char;
114 			kdb_poll_idx++;
115 			if (cptr[0][3] == ',')
116 				*cptr += 4;
117 			else
118 				return 1;
119 		}
120 	}
121 	return 0;
122 }
123 
124 static void kgdboc_unregister_kbd(void)
125 {
126 	int i;
127 
128 	for (i = 0; i < kdb_poll_idx; i++) {
129 		if (kdb_poll_funcs[i] == kdb_get_kbd_char) {
130 			kdb_poll_idx--;
131 			kdb_poll_funcs[i] = kdb_poll_funcs[kdb_poll_idx];
132 			kdb_poll_funcs[kdb_poll_idx] = NULL;
133 			i--;
134 		}
135 	}
136 	flush_work(&kgdboc_restore_input_work);
137 }
138 #else /* ! CONFIG_KDB_KEYBOARD */
139 #define kgdboc_register_kbd(x) 0
140 #define kgdboc_unregister_kbd()
141 #define kgdboc_restore_input()
142 #endif /* ! CONFIG_KDB_KEYBOARD */
143 
144 #if IS_BUILTIN(CONFIG_KGDB_SERIAL_CONSOLE)
145 static void cleanup_earlycon(void)
146 {
147 	if (kgdboc_earlycon_io_ops.cons)
148 		kgdb_unregister_io_module(&kgdboc_earlycon_io_ops);
149 }
150 #else /* !IS_BUILTIN(CONFIG_KGDB_SERIAL_CONSOLE) */
151 static inline void cleanup_earlycon(void) { }
152 #endif /* !IS_BUILTIN(CONFIG_KGDB_SERIAL_CONSOLE) */
153 
154 static void cleanup_kgdboc(void)
155 {
156 	cleanup_earlycon();
157 
158 	if (configured != 1)
159 		return;
160 
161 	if (kgdb_unregister_nmi_console())
162 		return;
163 	kgdboc_unregister_kbd();
164 	kgdb_unregister_io_module(&kgdboc_io_ops);
165 }
166 
167 static int configure_kgdboc(void)
168 {
169 	struct tty_driver *p;
170 	int tty_line = 0;
171 	int err = -ENODEV;
172 	char *cptr = config;
173 	struct console *cons;
174 
175 	if (!strlen(config) || isspace(config[0])) {
176 		err = 0;
177 		goto noconfig;
178 	}
179 
180 	kgdboc_io_ops.cons = NULL;
181 	kgdb_tty_driver = NULL;
182 
183 	kgdboc_use_kms = 0;
184 	if (strncmp(cptr, "kms,", 4) == 0) {
185 		cptr += 4;
186 		kgdboc_use_kms = 1;
187 	}
188 
189 	if (kgdboc_register_kbd(&cptr))
190 		goto do_register;
191 
192 	/*
193 	 * tty_find_polling_driver() can call uart_set_options()
194 	 * (via poll_init) to configure the uart. Take the console_list_lock
195 	 * in order to synchronize against register_console(), which can also
196 	 * configure the uart via uart_set_options(). This also allows safe
197 	 * traversal of the console list.
198 	 */
199 	console_list_lock();
200 
201 	p = tty_find_polling_driver(cptr, &tty_line);
202 	if (!p) {
203 		console_list_unlock();
204 		goto noconfig;
205 	}
206 
207 	/*
208 	 * Take console_lock to serialize device() callback with
209 	 * other console operations. For example, fg_console is
210 	 * modified under console_lock when switching vt.
211 	 */
212 	console_lock();
213 
214 	for_each_console(cons) {
215 		int idx;
216 		if (cons->device && cons->device(cons, &idx) == p &&
217 		    idx == tty_line) {
218 			kgdboc_io_ops.cons = cons;
219 			break;
220 		}
221 	}
222 
223 	console_unlock();
224 
225 	console_list_unlock();
226 
227 	kgdb_tty_driver = p;
228 	kgdb_tty_line = tty_line;
229 
230 do_register:
231 	err = kgdb_register_io_module(&kgdboc_io_ops);
232 	if (err)
233 		goto noconfig;
234 
235 	err = kgdb_register_nmi_console();
236 	if (err)
237 		goto nmi_con_failed;
238 
239 	configured = 1;
240 
241 	return 0;
242 
243 nmi_con_failed:
244 	kgdb_unregister_io_module(&kgdboc_io_ops);
245 noconfig:
246 	kgdboc_unregister_kbd();
247 	configured = 0;
248 
249 	return err;
250 }
251 
252 static int kgdboc_probe(struct platform_device *pdev)
253 {
254 	int ret = 0;
255 
256 	mutex_lock(&config_mutex);
257 	if (configured != 1) {
258 		ret = configure_kgdboc();
259 
260 		/* Convert "no device" to "defer" so we'll keep trying */
261 		if (ret == -ENODEV)
262 			ret = -EPROBE_DEFER;
263 	}
264 	mutex_unlock(&config_mutex);
265 
266 	return ret;
267 }
268 
269 static struct platform_driver kgdboc_platform_driver = {
270 	.probe = kgdboc_probe,
271 	.driver = {
272 		.name = "kgdboc",
273 		.suppress_bind_attrs = true,
274 	},
275 };
276 
277 static int __init init_kgdboc(void)
278 {
279 	int ret;
280 
281 	/*
282 	 * kgdboc is a little bit of an odd "platform_driver".  It can be
283 	 * up and running long before the platform_driver object is
284 	 * created and thus doesn't actually store anything in it.  There's
285 	 * only one instance of kgdb so anything is stored as global state.
286 	 * The platform_driver is only created so that we can leverage the
287 	 * kernel's mechanisms (like -EPROBE_DEFER) to call us when our
288 	 * underlying tty is ready.  Here we init our platform driver and
289 	 * then create the single kgdboc instance.
290 	 */
291 	ret = platform_driver_register(&kgdboc_platform_driver);
292 	if (ret)
293 		return ret;
294 
295 	kgdboc_pdev = platform_device_alloc("kgdboc", PLATFORM_DEVID_NONE);
296 	if (!kgdboc_pdev) {
297 		ret = -ENOMEM;
298 		goto err_did_register;
299 	}
300 
301 	ret = platform_device_add(kgdboc_pdev);
302 	if (!ret)
303 		return 0;
304 
305 	platform_device_put(kgdboc_pdev);
306 
307 err_did_register:
308 	platform_driver_unregister(&kgdboc_platform_driver);
309 	return ret;
310 }
311 
312 static void exit_kgdboc(void)
313 {
314 	mutex_lock(&config_mutex);
315 	cleanup_kgdboc();
316 	mutex_unlock(&config_mutex);
317 
318 	platform_device_unregister(kgdboc_pdev);
319 	platform_driver_unregister(&kgdboc_platform_driver);
320 }
321 
322 static int kgdboc_get_char(void)
323 {
324 	if (!kgdb_tty_driver)
325 		return -1;
326 	return kgdb_tty_driver->ops->poll_get_char(kgdb_tty_driver,
327 						kgdb_tty_line);
328 }
329 
330 static void kgdboc_put_char(u8 chr)
331 {
332 	if (!kgdb_tty_driver)
333 		return;
334 	kgdb_tty_driver->ops->poll_put_char(kgdb_tty_driver,
335 					kgdb_tty_line, chr);
336 }
337 
338 static int param_set_kgdboc_var(const char *kmessage,
339 				const struct kernel_param *kp)
340 {
341 	size_t len = strlen(kmessage);
342 	int ret = 0;
343 
344 	if (len >= MAX_CONFIG_LEN) {
345 		pr_err("config string too long\n");
346 		return -ENOSPC;
347 	}
348 
349 	if (kgdb_connected) {
350 		pr_err("Cannot reconfigure while KGDB is connected.\n");
351 		return -EBUSY;
352 	}
353 
354 	mutex_lock(&config_mutex);
355 
356 	strcpy(config, kmessage);
357 	/* Chop out \n char as a result of echo */
358 	if (len && config[len - 1] == '\n')
359 		config[len - 1] = '\0';
360 
361 	if (configured == 1)
362 		cleanup_kgdboc();
363 
364 	/*
365 	 * Configure with the new params as long as init already ran.
366 	 * Note that we can get called before init if someone loads us
367 	 * with "modprobe kgdboc kgdboc=..." or if they happen to use
368 	 * the odd syntax of "kgdboc.kgdboc=..." on the kernel command.
369 	 */
370 	if (configured >= 0)
371 		ret = configure_kgdboc();
372 
373 	/*
374 	 * If we couldn't configure then clear out the config.  Note that
375 	 * specifying an invalid config on the kernel command line vs.
376 	 * through sysfs have slightly different behaviors.  If we fail
377 	 * to configure what was specified on the kernel command line
378 	 * we'll leave it in the 'config' and return -EPROBE_DEFER from
379 	 * our probe.  When specified through sysfs userspace is
380 	 * responsible for loading the tty driver before setting up.
381 	 */
382 	if (ret)
383 		config[0] = '\0';
384 
385 	mutex_unlock(&config_mutex);
386 
387 	return ret;
388 }
389 
390 static int dbg_restore_graphics;
391 
392 static void kgdboc_pre_exp_handler(void)
393 {
394 	if (!dbg_restore_graphics && kgdboc_use_kms) {
395 		dbg_restore_graphics = 1;
396 		con_debug_enter(vc_cons[fg_console].d);
397 	}
398 	/* Increment the module count when the debugger is active */
399 	if (!kgdb_connected)
400 		try_module_get(THIS_MODULE);
401 }
402 
403 static void kgdboc_post_exp_handler(void)
404 {
405 	/* decrement the module count when the debugger detaches */
406 	if (!kgdb_connected)
407 		module_put(THIS_MODULE);
408 	if (kgdboc_use_kms && dbg_restore_graphics) {
409 		dbg_restore_graphics = 0;
410 		con_debug_leave();
411 	}
412 	kgdboc_restore_input();
413 }
414 
415 static struct kgdb_io kgdboc_io_ops = {
416 	.name			= "kgdboc",
417 	.read_char		= kgdboc_get_char,
418 	.write_char		= kgdboc_put_char,
419 	.pre_exception		= kgdboc_pre_exp_handler,
420 	.post_exception		= kgdboc_post_exp_handler,
421 };
422 
423 #if IS_BUILTIN(CONFIG_KGDB_SERIAL_CONSOLE)
424 static int kgdboc_option_setup(char *opt)
425 {
426 	if (!opt) {
427 		pr_err("config string not provided\n");
428 		return 1;
429 	}
430 
431 	if (strlen(opt) >= MAX_CONFIG_LEN) {
432 		pr_err("config string too long\n");
433 		return 1;
434 	}
435 	strcpy(config, opt);
436 
437 	return 1;
438 }
439 
440 __setup("kgdboc=", kgdboc_option_setup);
441 
442 
443 /* This is only available if kgdboc is a built in for early debugging */
444 static int __init kgdboc_early_init(char *opt)
445 {
446 	kgdboc_option_setup(opt);
447 	configure_kgdboc();
448 	return 0;
449 }
450 
451 early_param("ekgdboc", kgdboc_early_init);
452 
453 static int kgdboc_earlycon_get_char(void)
454 {
455 	char c;
456 
457 	if (!kgdboc_earlycon_io_ops.cons->read(kgdboc_earlycon_io_ops.cons,
458 					       &c, 1))
459 		return NO_POLL_CHAR;
460 
461 	return c;
462 }
463 
464 static void kgdboc_earlycon_put_char(u8 chr)
465 {
466 	kgdboc_earlycon_io_ops.cons->write(kgdboc_earlycon_io_ops.cons, &chr,
467 					   1);
468 }
469 
470 static void kgdboc_earlycon_pre_exp_handler(void)
471 {
472 	struct console *con;
473 	static bool already_warned;
474 	int cookie;
475 
476 	if (already_warned)
477 		return;
478 
479 	/*
480 	 * When the first normal console comes up the kernel will take all
481 	 * the boot consoles out of the list.  Really, we should stop using
482 	 * the boot console when it does that but until a TTY is registered
483 	 * we have no other choice so we keep using it.  Since not all
484 	 * serial drivers might be OK with this, print a warning once per
485 	 * boot if we detect this case.
486 	 */
487 	cookie = console_srcu_read_lock();
488 	for_each_console_srcu(con) {
489 		if (con == kgdboc_earlycon_io_ops.cons)
490 			break;
491 	}
492 	console_srcu_read_unlock(cookie);
493 	if (con)
494 		return;
495 
496 	already_warned = true;
497 	pr_warn("kgdboc_earlycon is still using bootconsole\n");
498 }
499 
500 static int kgdboc_earlycon_deferred_exit(struct console *con)
501 {
502 	/*
503 	 * If we get here it means the boot console is going away but we
504 	 * don't yet have a suitable replacement.  Don't pass through to
505 	 * the original exit routine.  We'll call it later in our deinit()
506 	 * function.  For now, restore the original exit() function pointer
507 	 * as a sentinal that we've hit this point.
508 	 */
509 	con->exit = earlycon_orig_exit;
510 
511 	return 0;
512 }
513 
514 static void kgdboc_earlycon_deinit(void)
515 {
516 	if (!kgdboc_earlycon_io_ops.cons)
517 		return;
518 
519 	if (kgdboc_earlycon_io_ops.cons->exit == kgdboc_earlycon_deferred_exit)
520 		/*
521 		 * kgdboc_earlycon is exiting but original boot console exit
522 		 * was never called (AKA kgdboc_earlycon_deferred_exit()
523 		 * didn't ever run).  Undo our trap.
524 		 */
525 		kgdboc_earlycon_io_ops.cons->exit = earlycon_orig_exit;
526 	else if (kgdboc_earlycon_io_ops.cons->exit)
527 		/*
528 		 * We skipped calling the exit() routine so we could try to
529 		 * keep using the boot console even after it went away.  We're
530 		 * finally done so call the function now.
531 		 */
532 		kgdboc_earlycon_io_ops.cons->exit(kgdboc_earlycon_io_ops.cons);
533 
534 	kgdboc_earlycon_io_ops.cons = NULL;
535 }
536 
537 static struct kgdb_io kgdboc_earlycon_io_ops = {
538 	.name			= "kgdboc_earlycon",
539 	.read_char		= kgdboc_earlycon_get_char,
540 	.write_char		= kgdboc_earlycon_put_char,
541 	.pre_exception		= kgdboc_earlycon_pre_exp_handler,
542 	.deinit			= kgdboc_earlycon_deinit,
543 };
544 
545 #define MAX_CONSOLE_NAME_LEN (sizeof((struct console *) 0)->name)
546 static char kgdboc_earlycon_param[MAX_CONSOLE_NAME_LEN] __initdata;
547 static bool kgdboc_earlycon_late_enable __initdata;
548 
549 static int __init kgdboc_earlycon_init(char *opt)
550 {
551 	struct console *con;
552 
553 	kdb_init(KDB_INIT_EARLY);
554 
555 	/*
556 	 * Look for a matching console, or if the name was left blank just
557 	 * pick the first one we find.
558 	 */
559 
560 	/*
561 	 * Hold the console_list_lock to guarantee that no consoles are
562 	 * unregistered until the kgdboc_earlycon setup is complete.
563 	 * Trapping the exit() callback relies on exit() not being
564 	 * called until the trap is setup. This also allows safe
565 	 * traversal of the console list and race-free reading of @flags.
566 	 */
567 	console_list_lock();
568 	for_each_console(con) {
569 		if (con->write && con->read &&
570 		    (con->flags & (CON_BOOT | CON_ENABLED)) &&
571 		    (!opt || !opt[0] || strcmp(con->name, opt) == 0))
572 			break;
573 	}
574 
575 	if (!con) {
576 		/*
577 		 * Both earlycon and kgdboc_earlycon are initialized during
578 		 * early parameter parsing. We cannot guarantee earlycon gets
579 		 * in first and, in any case, on ACPI systems earlycon may
580 		 * defer its own initialization (usually to somewhere within
581 		 * setup_arch() ). To cope with either of these situations
582 		 * we can defer our own initialization to a little later in
583 		 * the boot.
584 		 */
585 		if (!kgdboc_earlycon_late_enable) {
586 			pr_info("No suitable earlycon yet, will try later\n");
587 			if (opt)
588 				strscpy(kgdboc_earlycon_param, opt,
589 					sizeof(kgdboc_earlycon_param));
590 			kgdboc_earlycon_late_enable = true;
591 		} else {
592 			pr_info("Couldn't find kgdb earlycon\n");
593 		}
594 		goto unlock;
595 	}
596 
597 	kgdboc_earlycon_io_ops.cons = con;
598 	pr_info("Going to register kgdb with earlycon '%s'\n", con->name);
599 	if (kgdb_register_io_module(&kgdboc_earlycon_io_ops) != 0) {
600 		kgdboc_earlycon_io_ops.cons = NULL;
601 		pr_info("Failed to register kgdb with earlycon\n");
602 	} else {
603 		/* Trap exit so we can keep earlycon longer if needed. */
604 		earlycon_orig_exit = con->exit;
605 		con->exit = kgdboc_earlycon_deferred_exit;
606 	}
607 
608 unlock:
609 	console_list_unlock();
610 
611 	/* Non-zero means malformed option so we always return zero */
612 	return 0;
613 }
614 
615 early_param("kgdboc_earlycon", kgdboc_earlycon_init);
616 
617 /*
618  * This is only intended for the late adoption of an early console.
619  *
620  * It is not a reliable way to adopt regular consoles because we can not
621  * control what order console initcalls are made and, in any case, many
622  * regular consoles are registered much later in the boot process than
623  * the console initcalls!
624  */
625 static int __init kgdboc_earlycon_late_init(void)
626 {
627 	if (kgdboc_earlycon_late_enable)
628 		kgdboc_earlycon_init(kgdboc_earlycon_param);
629 	return 0;
630 }
631 console_initcall(kgdboc_earlycon_late_init);
632 
633 #endif /* IS_BUILTIN(CONFIG_KGDB_SERIAL_CONSOLE) */
634 
635 module_init(init_kgdboc);
636 module_exit(exit_kgdboc);
637 module_param_call(kgdboc, param_set_kgdboc_var, param_get_string, &kps, 0644);
638 MODULE_PARM_DESC(kgdboc, "<serial_device>[,baud]");
639 MODULE_DESCRIPTION("KGDB Console TTY Driver");
640 MODULE_LICENSE("GPL");
641