Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * Kernel Debug Core
0004  *
0005  * Maintainer: Jason Wessel <jason.wessel@windriver.com>
0006  *
0007  * Copyright (C) 2000-2001 VERITAS Software Corporation.
0008  * Copyright (C) 2002-2004 Timesys Corporation
0009  * Copyright (C) 2003-2004 Amit S. Kale <amitkale@linsyssoft.com>
0010  * Copyright (C) 2004 Pavel Machek <pavel@ucw.cz>
0011  * Copyright (C) 2004-2006 Tom Rini <trini@kernel.crashing.org>
0012  * Copyright (C) 2004-2006 LinSysSoft Technologies Pvt. Ltd.
0013  * Copyright (C) 2005-2009 Wind River Systems, Inc.
0014  * Copyright (C) 2007 MontaVista Software, Inc.
0015  * Copyright (C) 2008 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
0016  *
0017  * Contributors at various stages not listed above:
0018  *  Jason Wessel ( jason.wessel@windriver.com )
0019  *  George Anzinger <george@mvista.com>
0020  *  Anurekh Saxena (anurekh.saxena@timesys.com)
0021  *  Lake Stevens Instrument Division (Glenn Engel)
0022  *  Jim Kingdon, Cygnus Support.
0023  *
0024  * Original KGDB stub: David Grothe <dave@gcom.com>,
0025  * Tigran Aivazian <tigran@sco.com>
0026  */
0027 
0028 #define pr_fmt(fmt) "KGDB: " fmt
0029 
0030 #include <linux/pid_namespace.h>
0031 #include <linux/clocksource.h>
0032 #include <linux/serial_core.h>
0033 #include <linux/interrupt.h>
0034 #include <linux/spinlock.h>
0035 #include <linux/console.h>
0036 #include <linux/threads.h>
0037 #include <linux/uaccess.h>
0038 #include <linux/kernel.h>
0039 #include <linux/module.h>
0040 #include <linux/ptrace.h>
0041 #include <linux/string.h>
0042 #include <linux/delay.h>
0043 #include <linux/sched.h>
0044 #include <linux/sysrq.h>
0045 #include <linux/reboot.h>
0046 #include <linux/init.h>
0047 #include <linux/kgdb.h>
0048 #include <linux/kdb.h>
0049 #include <linux/nmi.h>
0050 #include <linux/pid.h>
0051 #include <linux/smp.h>
0052 #include <linux/mm.h>
0053 #include <linux/vmacache.h>
0054 #include <linux/rcupdate.h>
0055 #include <linux/irq.h>
0056 #include <linux/security.h>
0057 
0058 #include <asm/cacheflush.h>
0059 #include <asm/byteorder.h>
0060 #include <linux/atomic.h>
0061 
0062 #include "debug_core.h"
0063 
0064 static int kgdb_break_asap;
0065 
0066 struct debuggerinfo_struct kgdb_info[NR_CPUS];
0067 
0068 /* kgdb_connected - Is a host GDB connected to us? */
0069 int             kgdb_connected;
0070 EXPORT_SYMBOL_GPL(kgdb_connected);
0071 
0072 /* All the KGDB handlers are installed */
0073 int         kgdb_io_module_registered;
0074 
0075 /* Guard for recursive entry */
0076 static int          exception_level;
0077 
0078 struct kgdb_io      *dbg_io_ops;
0079 static DEFINE_SPINLOCK(kgdb_registration_lock);
0080 
0081 /* Action for the reboot notifier, a global allow kdb to change it */
0082 static int kgdbreboot;
0083 /* kgdb console driver is loaded */
0084 static int kgdb_con_registered;
0085 /* determine if kgdb console output should be used */
0086 static int kgdb_use_con;
0087 /* Flag for alternate operations for early debugging */
0088 bool dbg_is_early = true;
0089 /* Next cpu to become the master debug core */
0090 int dbg_switch_cpu;
0091 
0092 /* Use kdb or gdbserver mode */
0093 int dbg_kdb_mode = 1;
0094 
0095 module_param(kgdb_use_con, int, 0644);
0096 module_param(kgdbreboot, int, 0644);
0097 
0098 /*
0099  * Holds information about breakpoints in a kernel. These breakpoints are
0100  * added and removed by gdb.
0101  */
0102 static struct kgdb_bkpt     kgdb_break[KGDB_MAX_BREAKPOINTS] = {
0103     [0 ... KGDB_MAX_BREAKPOINTS-1] = { .state = BP_UNDEFINED }
0104 };
0105 
0106 /*
0107  * The CPU# of the active CPU, or -1 if none:
0108  */
0109 atomic_t            kgdb_active = ATOMIC_INIT(-1);
0110 EXPORT_SYMBOL_GPL(kgdb_active);
0111 static DEFINE_RAW_SPINLOCK(dbg_master_lock);
0112 static DEFINE_RAW_SPINLOCK(dbg_slave_lock);
0113 
0114 /*
0115  * We use NR_CPUs not PERCPU, in case kgdb is used to debug early
0116  * bootup code (which might not have percpu set up yet):
0117  */
0118 static atomic_t         masters_in_kgdb;
0119 static atomic_t         slaves_in_kgdb;
0120 atomic_t            kgdb_setting_breakpoint;
0121 
0122 struct task_struct      *kgdb_usethread;
0123 struct task_struct      *kgdb_contthread;
0124 
0125 int             kgdb_single_step;
0126 static pid_t            kgdb_sstep_pid;
0127 
0128 /* to keep track of the CPU which is doing the single stepping*/
0129 atomic_t            kgdb_cpu_doing_single_step = ATOMIC_INIT(-1);
0130 
0131 /*
0132  * If you are debugging a problem where roundup (the collection of
0133  * all other CPUs) is a problem [this should be extremely rare],
0134  * then use the nokgdbroundup option to avoid roundup. In that case
0135  * the other CPUs might interfere with your debugging context, so
0136  * use this with care:
0137  */
0138 static int kgdb_do_roundup = 1;
0139 
0140 static int __init opt_nokgdbroundup(char *str)
0141 {
0142     kgdb_do_roundup = 0;
0143 
0144     return 0;
0145 }
0146 
0147 early_param("nokgdbroundup", opt_nokgdbroundup);
0148 
0149 /*
0150  * Finally, some KGDB code :-)
0151  */
0152 
0153 /*
0154  * Weak aliases for breakpoint management,
0155  * can be overridden by architectures when needed:
0156  */
0157 int __weak kgdb_arch_set_breakpoint(struct kgdb_bkpt *bpt)
0158 {
0159     int err;
0160 
0161     err = copy_from_kernel_nofault(bpt->saved_instr, (char *)bpt->bpt_addr,
0162                 BREAK_INSTR_SIZE);
0163     if (err)
0164         return err;
0165     err = copy_to_kernel_nofault((char *)bpt->bpt_addr,
0166                  arch_kgdb_ops.gdb_bpt_instr, BREAK_INSTR_SIZE);
0167     return err;
0168 }
0169 NOKPROBE_SYMBOL(kgdb_arch_set_breakpoint);
0170 
0171 int __weak kgdb_arch_remove_breakpoint(struct kgdb_bkpt *bpt)
0172 {
0173     return copy_to_kernel_nofault((char *)bpt->bpt_addr,
0174                   (char *)bpt->saved_instr, BREAK_INSTR_SIZE);
0175 }
0176 NOKPROBE_SYMBOL(kgdb_arch_remove_breakpoint);
0177 
0178 int __weak kgdb_validate_break_address(unsigned long addr)
0179 {
0180     struct kgdb_bkpt tmp;
0181     int err;
0182 
0183     if (kgdb_within_blocklist(addr))
0184         return -EINVAL;
0185 
0186     /* Validate setting the breakpoint and then removing it.  If the
0187      * remove fails, the kernel needs to emit a bad message because we
0188      * are deep trouble not being able to put things back the way we
0189      * found them.
0190      */
0191     tmp.bpt_addr = addr;
0192     err = kgdb_arch_set_breakpoint(&tmp);
0193     if (err)
0194         return err;
0195     err = kgdb_arch_remove_breakpoint(&tmp);
0196     if (err)
0197         pr_err("Critical breakpoint error, kernel memory destroyed at: %lx\n",
0198                addr);
0199     return err;
0200 }
0201 
0202 unsigned long __weak kgdb_arch_pc(int exception, struct pt_regs *regs)
0203 {
0204     return instruction_pointer(regs);
0205 }
0206 NOKPROBE_SYMBOL(kgdb_arch_pc);
0207 
0208 int __weak kgdb_arch_init(void)
0209 {
0210     return 0;
0211 }
0212 
0213 int __weak kgdb_skipexception(int exception, struct pt_regs *regs)
0214 {
0215     return 0;
0216 }
0217 NOKPROBE_SYMBOL(kgdb_skipexception);
0218 
0219 #ifdef CONFIG_SMP
0220 
0221 /*
0222  * Default (weak) implementation for kgdb_roundup_cpus
0223  */
0224 
0225 void __weak kgdb_call_nmi_hook(void *ignored)
0226 {
0227     /*
0228      * NOTE: get_irq_regs() is supposed to get the registers from
0229      * before the IPI interrupt happened and so is supposed to
0230      * show where the processor was.  In some situations it's
0231      * possible we might be called without an IPI, so it might be
0232      * safer to figure out how to make kgdb_breakpoint() work
0233      * properly here.
0234      */
0235     kgdb_nmicallback(raw_smp_processor_id(), get_irq_regs());
0236 }
0237 NOKPROBE_SYMBOL(kgdb_call_nmi_hook);
0238 
0239 static DEFINE_PER_CPU(call_single_data_t, kgdb_roundup_csd) =
0240     CSD_INIT(kgdb_call_nmi_hook, NULL);
0241 
0242 void __weak kgdb_roundup_cpus(void)
0243 {
0244     call_single_data_t *csd;
0245     int this_cpu = raw_smp_processor_id();
0246     int cpu;
0247     int ret;
0248 
0249     for_each_online_cpu(cpu) {
0250         /* No need to roundup ourselves */
0251         if (cpu == this_cpu)
0252             continue;
0253 
0254         csd = &per_cpu(kgdb_roundup_csd, cpu);
0255 
0256         /*
0257          * If it didn't round up last time, don't try again
0258          * since smp_call_function_single_async() will block.
0259          *
0260          * If rounding_up is false then we know that the
0261          * previous call must have at least started and that
0262          * means smp_call_function_single_async() won't block.
0263          */
0264         if (kgdb_info[cpu].rounding_up)
0265             continue;
0266         kgdb_info[cpu].rounding_up = true;
0267 
0268         ret = smp_call_function_single_async(cpu, csd);
0269         if (ret)
0270             kgdb_info[cpu].rounding_up = false;
0271     }
0272 }
0273 NOKPROBE_SYMBOL(kgdb_roundup_cpus);
0274 
0275 #endif
0276 
0277 /*
0278  * Some architectures need cache flushes when we set/clear a
0279  * breakpoint:
0280  */
0281 static void kgdb_flush_swbreak_addr(unsigned long addr)
0282 {
0283     if (!CACHE_FLUSH_IS_SAFE)
0284         return;
0285 
0286     if (current->mm) {
0287         int i;
0288 
0289         for (i = 0; i < VMACACHE_SIZE; i++) {
0290             if (!current->vmacache.vmas[i])
0291                 continue;
0292             flush_cache_range(current->vmacache.vmas[i],
0293                       addr, addr + BREAK_INSTR_SIZE);
0294         }
0295     }
0296 
0297     /* Force flush instruction cache if it was outside the mm */
0298     flush_icache_range(addr, addr + BREAK_INSTR_SIZE);
0299 }
0300 NOKPROBE_SYMBOL(kgdb_flush_swbreak_addr);
0301 
0302 /*
0303  * SW breakpoint management:
0304  */
0305 int dbg_activate_sw_breakpoints(void)
0306 {
0307     int error;
0308     int ret = 0;
0309     int i;
0310 
0311     for (i = 0; i < KGDB_MAX_BREAKPOINTS; i++) {
0312         if (kgdb_break[i].state != BP_SET)
0313             continue;
0314 
0315         error = kgdb_arch_set_breakpoint(&kgdb_break[i]);
0316         if (error) {
0317             ret = error;
0318             pr_info("BP install failed: %lx\n",
0319                 kgdb_break[i].bpt_addr);
0320             continue;
0321         }
0322 
0323         kgdb_flush_swbreak_addr(kgdb_break[i].bpt_addr);
0324         kgdb_break[i].state = BP_ACTIVE;
0325     }
0326     return ret;
0327 }
0328 NOKPROBE_SYMBOL(dbg_activate_sw_breakpoints);
0329 
0330 int dbg_set_sw_break(unsigned long addr)
0331 {
0332     int err = kgdb_validate_break_address(addr);
0333     int breakno = -1;
0334     int i;
0335 
0336     if (err)
0337         return err;
0338 
0339     for (i = 0; i < KGDB_MAX_BREAKPOINTS; i++) {
0340         if ((kgdb_break[i].state == BP_SET) &&
0341                     (kgdb_break[i].bpt_addr == addr))
0342             return -EEXIST;
0343     }
0344     for (i = 0; i < KGDB_MAX_BREAKPOINTS; i++) {
0345         if (kgdb_break[i].state == BP_REMOVED &&
0346                     kgdb_break[i].bpt_addr == addr) {
0347             breakno = i;
0348             break;
0349         }
0350     }
0351 
0352     if (breakno == -1) {
0353         for (i = 0; i < KGDB_MAX_BREAKPOINTS; i++) {
0354             if (kgdb_break[i].state == BP_UNDEFINED) {
0355                 breakno = i;
0356                 break;
0357             }
0358         }
0359     }
0360 
0361     if (breakno == -1)
0362         return -E2BIG;
0363 
0364     kgdb_break[breakno].state = BP_SET;
0365     kgdb_break[breakno].type = BP_BREAKPOINT;
0366     kgdb_break[breakno].bpt_addr = addr;
0367 
0368     return 0;
0369 }
0370 
0371 int dbg_deactivate_sw_breakpoints(void)
0372 {
0373     int error;
0374     int ret = 0;
0375     int i;
0376 
0377     for (i = 0; i < KGDB_MAX_BREAKPOINTS; i++) {
0378         if (kgdb_break[i].state != BP_ACTIVE)
0379             continue;
0380         error = kgdb_arch_remove_breakpoint(&kgdb_break[i]);
0381         if (error) {
0382             pr_info("BP remove failed: %lx\n",
0383                 kgdb_break[i].bpt_addr);
0384             ret = error;
0385         }
0386 
0387         kgdb_flush_swbreak_addr(kgdb_break[i].bpt_addr);
0388         kgdb_break[i].state = BP_SET;
0389     }
0390     return ret;
0391 }
0392 NOKPROBE_SYMBOL(dbg_deactivate_sw_breakpoints);
0393 
0394 int dbg_remove_sw_break(unsigned long addr)
0395 {
0396     int i;
0397 
0398     for (i = 0; i < KGDB_MAX_BREAKPOINTS; i++) {
0399         if ((kgdb_break[i].state == BP_SET) &&
0400                 (kgdb_break[i].bpt_addr == addr)) {
0401             kgdb_break[i].state = BP_REMOVED;
0402             return 0;
0403         }
0404     }
0405     return -ENOENT;
0406 }
0407 
0408 int kgdb_isremovedbreak(unsigned long addr)
0409 {
0410     int i;
0411 
0412     for (i = 0; i < KGDB_MAX_BREAKPOINTS; i++) {
0413         if ((kgdb_break[i].state == BP_REMOVED) &&
0414                     (kgdb_break[i].bpt_addr == addr))
0415             return 1;
0416     }
0417     return 0;
0418 }
0419 
0420 int kgdb_has_hit_break(unsigned long addr)
0421 {
0422     int i;
0423 
0424     for (i = 0; i < KGDB_MAX_BREAKPOINTS; i++) {
0425         if (kgdb_break[i].state == BP_ACTIVE &&
0426             kgdb_break[i].bpt_addr == addr)
0427             return 1;
0428     }
0429     return 0;
0430 }
0431 
0432 int dbg_remove_all_break(void)
0433 {
0434     int error;
0435     int i;
0436 
0437     /* Clear memory breakpoints. */
0438     for (i = 0; i < KGDB_MAX_BREAKPOINTS; i++) {
0439         if (kgdb_break[i].state != BP_ACTIVE)
0440             goto setundefined;
0441         error = kgdb_arch_remove_breakpoint(&kgdb_break[i]);
0442         if (error)
0443             pr_err("breakpoint remove failed: %lx\n",
0444                    kgdb_break[i].bpt_addr);
0445 setundefined:
0446         kgdb_break[i].state = BP_UNDEFINED;
0447     }
0448 
0449     /* Clear hardware breakpoints. */
0450     if (arch_kgdb_ops.remove_all_hw_break)
0451         arch_kgdb_ops.remove_all_hw_break();
0452 
0453     return 0;
0454 }
0455 
0456 void kgdb_free_init_mem(void)
0457 {
0458     int i;
0459 
0460     /* Clear init memory breakpoints. */
0461     for (i = 0; i < KGDB_MAX_BREAKPOINTS; i++) {
0462         if (init_section_contains((void *)kgdb_break[i].bpt_addr, 0))
0463             kgdb_break[i].state = BP_UNDEFINED;
0464     }
0465 }
0466 
0467 #ifdef CONFIG_KGDB_KDB
0468 void kdb_dump_stack_on_cpu(int cpu)
0469 {
0470     if (cpu == raw_smp_processor_id() || !IS_ENABLED(CONFIG_SMP)) {
0471         dump_stack();
0472         return;
0473     }
0474 
0475     if (!(kgdb_info[cpu].exception_state & DCPU_IS_SLAVE)) {
0476         kdb_printf("ERROR: Task on cpu %d didn't stop in the debugger\n",
0477                cpu);
0478         return;
0479     }
0480 
0481     /*
0482      * In general, architectures don't support dumping the stack of a
0483      * "running" process that's not the current one.  From the point of
0484      * view of the Linux, kernel processes that are looping in the kgdb
0485      * slave loop are still "running".  There's also no API (that actually
0486      * works across all architectures) that can do a stack crawl based
0487      * on registers passed as a parameter.
0488      *
0489      * Solve this conundrum by asking slave CPUs to do the backtrace
0490      * themselves.
0491      */
0492     kgdb_info[cpu].exception_state |= DCPU_WANT_BT;
0493     while (kgdb_info[cpu].exception_state & DCPU_WANT_BT)
0494         cpu_relax();
0495 }
0496 #endif
0497 
0498 /*
0499  * Return true if there is a valid kgdb I/O module.  Also if no
0500  * debugger is attached a message can be printed to the console about
0501  * waiting for the debugger to attach.
0502  *
0503  * The print_wait argument is only to be true when called from inside
0504  * the core kgdb_handle_exception, because it will wait for the
0505  * debugger to attach.
0506  */
0507 static int kgdb_io_ready(int print_wait)
0508 {
0509     if (!dbg_io_ops)
0510         return 0;
0511     if (kgdb_connected)
0512         return 1;
0513     if (atomic_read(&kgdb_setting_breakpoint))
0514         return 1;
0515     if (print_wait) {
0516 #ifdef CONFIG_KGDB_KDB
0517         if (!dbg_kdb_mode)
0518             pr_crit("waiting... or $3#33 for KDB\n");
0519 #else
0520         pr_crit("Waiting for remote debugger\n");
0521 #endif
0522     }
0523     return 1;
0524 }
0525 NOKPROBE_SYMBOL(kgdb_io_ready);
0526 
0527 static int kgdb_reenter_check(struct kgdb_state *ks)
0528 {
0529     unsigned long addr;
0530 
0531     if (atomic_read(&kgdb_active) != raw_smp_processor_id())
0532         return 0;
0533 
0534     /* Panic on recursive debugger calls: */
0535     exception_level++;
0536     addr = kgdb_arch_pc(ks->ex_vector, ks->linux_regs);
0537     dbg_deactivate_sw_breakpoints();
0538 
0539     /*
0540      * If the break point removed ok at the place exception
0541      * occurred, try to recover and print a warning to the end
0542      * user because the user planted a breakpoint in a place that
0543      * KGDB needs in order to function.
0544      */
0545     if (dbg_remove_sw_break(addr) == 0) {
0546         exception_level = 0;
0547         kgdb_skipexception(ks->ex_vector, ks->linux_regs);
0548         dbg_activate_sw_breakpoints();
0549         pr_crit("re-enter error: breakpoint removed %lx\n", addr);
0550         WARN_ON_ONCE(1);
0551 
0552         return 1;
0553     }
0554     dbg_remove_all_break();
0555     kgdb_skipexception(ks->ex_vector, ks->linux_regs);
0556 
0557     if (exception_level > 1) {
0558         dump_stack();
0559         kgdb_io_module_registered = false;
0560         panic("Recursive entry to debugger");
0561     }
0562 
0563     pr_crit("re-enter exception: ALL breakpoints killed\n");
0564 #ifdef CONFIG_KGDB_KDB
0565     /* Allow kdb to debug itself one level */
0566     return 0;
0567 #endif
0568     dump_stack();
0569     panic("Recursive entry to debugger");
0570 
0571     return 1;
0572 }
0573 NOKPROBE_SYMBOL(kgdb_reenter_check);
0574 
0575 static void dbg_touch_watchdogs(void)
0576 {
0577     touch_softlockup_watchdog_sync();
0578     clocksource_touch_watchdog();
0579     rcu_cpu_stall_reset();
0580 }
0581 NOKPROBE_SYMBOL(dbg_touch_watchdogs);
0582 
0583 static int kgdb_cpu_enter(struct kgdb_state *ks, struct pt_regs *regs,
0584         int exception_state)
0585 {
0586     unsigned long flags;
0587     int sstep_tries = 100;
0588     int error;
0589     int cpu;
0590     int trace_on = 0;
0591     int online_cpus = num_online_cpus();
0592     u64 time_left;
0593 
0594     kgdb_info[ks->cpu].enter_kgdb++;
0595     kgdb_info[ks->cpu].exception_state |= exception_state;
0596 
0597     if (exception_state == DCPU_WANT_MASTER)
0598         atomic_inc(&masters_in_kgdb);
0599     else
0600         atomic_inc(&slaves_in_kgdb);
0601 
0602     if (arch_kgdb_ops.disable_hw_break)
0603         arch_kgdb_ops.disable_hw_break(regs);
0604 
0605 acquirelock:
0606     rcu_read_lock();
0607     /*
0608      * Interrupts will be restored by the 'trap return' code, except when
0609      * single stepping.
0610      */
0611     local_irq_save(flags);
0612 
0613     cpu = ks->cpu;
0614     kgdb_info[cpu].debuggerinfo = regs;
0615     kgdb_info[cpu].task = current;
0616     kgdb_info[cpu].ret_state = 0;
0617     kgdb_info[cpu].irq_depth = hardirq_count() >> HARDIRQ_SHIFT;
0618 
0619     /* Make sure the above info reaches the primary CPU */
0620     smp_mb();
0621 
0622     if (exception_level == 1) {
0623         if (raw_spin_trylock(&dbg_master_lock))
0624             atomic_xchg(&kgdb_active, cpu);
0625         goto cpu_master_loop;
0626     }
0627 
0628     /*
0629      * CPU will loop if it is a slave or request to become a kgdb
0630      * master cpu and acquire the kgdb_active lock:
0631      */
0632     while (1) {
0633 cpu_loop:
0634         if (kgdb_info[cpu].exception_state & DCPU_NEXT_MASTER) {
0635             kgdb_info[cpu].exception_state &= ~DCPU_NEXT_MASTER;
0636             goto cpu_master_loop;
0637         } else if (kgdb_info[cpu].exception_state & DCPU_WANT_MASTER) {
0638             if (raw_spin_trylock(&dbg_master_lock)) {
0639                 atomic_xchg(&kgdb_active, cpu);
0640                 break;
0641             }
0642         } else if (kgdb_info[cpu].exception_state & DCPU_WANT_BT) {
0643             dump_stack();
0644             kgdb_info[cpu].exception_state &= ~DCPU_WANT_BT;
0645         } else if (kgdb_info[cpu].exception_state & DCPU_IS_SLAVE) {
0646             if (!raw_spin_is_locked(&dbg_slave_lock))
0647                 goto return_normal;
0648         } else {
0649 return_normal:
0650             /* Return to normal operation by executing any
0651              * hw breakpoint fixup.
0652              */
0653             if (arch_kgdb_ops.correct_hw_break)
0654                 arch_kgdb_ops.correct_hw_break();
0655             if (trace_on)
0656                 tracing_on();
0657             kgdb_info[cpu].debuggerinfo = NULL;
0658             kgdb_info[cpu].task = NULL;
0659             kgdb_info[cpu].exception_state &=
0660                 ~(DCPU_WANT_MASTER | DCPU_IS_SLAVE);
0661             kgdb_info[cpu].enter_kgdb--;
0662             smp_mb__before_atomic();
0663             atomic_dec(&slaves_in_kgdb);
0664             dbg_touch_watchdogs();
0665             local_irq_restore(flags);
0666             rcu_read_unlock();
0667             return 0;
0668         }
0669         cpu_relax();
0670     }
0671 
0672     /*
0673      * For single stepping, try to only enter on the processor
0674      * that was single stepping.  To guard against a deadlock, the
0675      * kernel will only try for the value of sstep_tries before
0676      * giving up and continuing on.
0677      */
0678     if (atomic_read(&kgdb_cpu_doing_single_step) != -1 &&
0679         (kgdb_info[cpu].task &&
0680          kgdb_info[cpu].task->pid != kgdb_sstep_pid) && --sstep_tries) {
0681         atomic_set(&kgdb_active, -1);
0682         raw_spin_unlock(&dbg_master_lock);
0683         dbg_touch_watchdogs();
0684         local_irq_restore(flags);
0685         rcu_read_unlock();
0686 
0687         goto acquirelock;
0688     }
0689 
0690     if (!kgdb_io_ready(1)) {
0691         kgdb_info[cpu].ret_state = 1;
0692         goto kgdb_restore; /* No I/O connection, resume the system */
0693     }
0694 
0695     /*
0696      * Don't enter if we have hit a removed breakpoint.
0697      */
0698     if (kgdb_skipexception(ks->ex_vector, ks->linux_regs))
0699         goto kgdb_restore;
0700 
0701     atomic_inc(&ignore_console_lock_warning);
0702 
0703     /* Call the I/O driver's pre_exception routine */
0704     if (dbg_io_ops->pre_exception)
0705         dbg_io_ops->pre_exception();
0706 
0707     /*
0708      * Get the passive CPU lock which will hold all the non-primary
0709      * CPU in a spin state while the debugger is active
0710      */
0711     if (!kgdb_single_step)
0712         raw_spin_lock(&dbg_slave_lock);
0713 
0714 #ifdef CONFIG_SMP
0715     /* If send_ready set, slaves are already waiting */
0716     if (ks->send_ready)
0717         atomic_set(ks->send_ready, 1);
0718 
0719     /* Signal the other CPUs to enter kgdb_wait() */
0720     else if ((!kgdb_single_step) && kgdb_do_roundup)
0721         kgdb_roundup_cpus();
0722 #endif
0723 
0724     /*
0725      * Wait for the other CPUs to be notified and be waiting for us:
0726      */
0727     time_left = MSEC_PER_SEC;
0728     while (kgdb_do_roundup && --time_left &&
0729            (atomic_read(&masters_in_kgdb) + atomic_read(&slaves_in_kgdb)) !=
0730            online_cpus)
0731         udelay(1000);
0732     if (!time_left)
0733         pr_crit("Timed out waiting for secondary CPUs.\n");
0734 
0735     /*
0736      * At this point the primary processor is completely
0737      * in the debugger and all secondary CPUs are quiescent
0738      */
0739     dbg_deactivate_sw_breakpoints();
0740     kgdb_single_step = 0;
0741     kgdb_contthread = current;
0742     exception_level = 0;
0743     trace_on = tracing_is_on();
0744     if (trace_on)
0745         tracing_off();
0746 
0747     while (1) {
0748 cpu_master_loop:
0749         if (dbg_kdb_mode) {
0750             kgdb_connected = 1;
0751             error = kdb_stub(ks);
0752             if (error == -1)
0753                 continue;
0754             kgdb_connected = 0;
0755         } else {
0756             /*
0757              * This is a brutal way to interfere with the debugger
0758              * and prevent gdb being used to poke at kernel memory.
0759              * This could cause trouble if lockdown is applied when
0760              * there is already an active gdb session. For now the
0761              * answer is simply "don't do that". Typically lockdown
0762              * *will* be applied before the debug core gets started
0763              * so only developers using kgdb for fairly advanced
0764              * early kernel debug can be biten by this. Hopefully
0765              * they are sophisticated enough to take care of
0766              * themselves, especially with help from the lockdown
0767              * message printed on the console!
0768              */
0769             if (security_locked_down(LOCKDOWN_DBG_WRITE_KERNEL)) {
0770                 if (IS_ENABLED(CONFIG_KGDB_KDB)) {
0771                     /* Switch back to kdb if possible... */
0772                     dbg_kdb_mode = 1;
0773                     continue;
0774                 } else {
0775                     /* ... otherwise just bail */
0776                     break;
0777                 }
0778             }
0779             error = gdb_serial_stub(ks);
0780         }
0781 
0782         if (error == DBG_PASS_EVENT) {
0783             dbg_kdb_mode = !dbg_kdb_mode;
0784         } else if (error == DBG_SWITCH_CPU_EVENT) {
0785             kgdb_info[dbg_switch_cpu].exception_state |=
0786                 DCPU_NEXT_MASTER;
0787             goto cpu_loop;
0788         } else {
0789             kgdb_info[cpu].ret_state = error;
0790             break;
0791         }
0792     }
0793 
0794     dbg_activate_sw_breakpoints();
0795 
0796     /* Call the I/O driver's post_exception routine */
0797     if (dbg_io_ops->post_exception)
0798         dbg_io_ops->post_exception();
0799 
0800     atomic_dec(&ignore_console_lock_warning);
0801 
0802     if (!kgdb_single_step) {
0803         raw_spin_unlock(&dbg_slave_lock);
0804         /* Wait till all the CPUs have quit from the debugger. */
0805         while (kgdb_do_roundup && atomic_read(&slaves_in_kgdb))
0806             cpu_relax();
0807     }
0808 
0809 kgdb_restore:
0810     if (atomic_read(&kgdb_cpu_doing_single_step) != -1) {
0811         int sstep_cpu = atomic_read(&kgdb_cpu_doing_single_step);
0812         if (kgdb_info[sstep_cpu].task)
0813             kgdb_sstep_pid = kgdb_info[sstep_cpu].task->pid;
0814         else
0815             kgdb_sstep_pid = 0;
0816     }
0817     if (arch_kgdb_ops.correct_hw_break)
0818         arch_kgdb_ops.correct_hw_break();
0819     if (trace_on)
0820         tracing_on();
0821 
0822     kgdb_info[cpu].debuggerinfo = NULL;
0823     kgdb_info[cpu].task = NULL;
0824     kgdb_info[cpu].exception_state &=
0825         ~(DCPU_WANT_MASTER | DCPU_IS_SLAVE);
0826     kgdb_info[cpu].enter_kgdb--;
0827     smp_mb__before_atomic();
0828     atomic_dec(&masters_in_kgdb);
0829     /* Free kgdb_active */
0830     atomic_set(&kgdb_active, -1);
0831     raw_spin_unlock(&dbg_master_lock);
0832     dbg_touch_watchdogs();
0833     local_irq_restore(flags);
0834     rcu_read_unlock();
0835 
0836     return kgdb_info[cpu].ret_state;
0837 }
0838 NOKPROBE_SYMBOL(kgdb_cpu_enter);
0839 
0840 /*
0841  * kgdb_handle_exception() - main entry point from a kernel exception
0842  *
0843  * Locking hierarchy:
0844  *  interface locks, if any (begin_session)
0845  *  kgdb lock (kgdb_active)
0846  */
0847 int
0848 kgdb_handle_exception(int evector, int signo, int ecode, struct pt_regs *regs)
0849 {
0850     struct kgdb_state kgdb_var;
0851     struct kgdb_state *ks = &kgdb_var;
0852     int ret = 0;
0853 
0854     if (arch_kgdb_ops.enable_nmi)
0855         arch_kgdb_ops.enable_nmi(0);
0856     /*
0857      * Avoid entering the debugger if we were triggered due to an oops
0858      * but panic_timeout indicates the system should automatically
0859      * reboot on panic. We don't want to get stuck waiting for input
0860      * on such systems, especially if its "just" an oops.
0861      */
0862     if (signo != SIGTRAP && panic_timeout)
0863         return 1;
0864 
0865     memset(ks, 0, sizeof(struct kgdb_state));
0866     ks->cpu         = raw_smp_processor_id();
0867     ks->ex_vector       = evector;
0868     ks->signo       = signo;
0869     ks->err_code        = ecode;
0870     ks->linux_regs      = regs;
0871 
0872     if (kgdb_reenter_check(ks))
0873         goto out; /* Ouch, double exception ! */
0874     if (kgdb_info[ks->cpu].enter_kgdb != 0)
0875         goto out;
0876 
0877     ret = kgdb_cpu_enter(ks, regs, DCPU_WANT_MASTER);
0878 out:
0879     if (arch_kgdb_ops.enable_nmi)
0880         arch_kgdb_ops.enable_nmi(1);
0881     return ret;
0882 }
0883 NOKPROBE_SYMBOL(kgdb_handle_exception);
0884 
0885 /*
0886  * GDB places a breakpoint at this function to know dynamically loaded objects.
0887  */
0888 static int module_event(struct notifier_block *self, unsigned long val,
0889     void *data)
0890 {
0891     return 0;
0892 }
0893 
0894 static struct notifier_block dbg_module_load_nb = {
0895     .notifier_call  = module_event,
0896 };
0897 
0898 int kgdb_nmicallback(int cpu, void *regs)
0899 {
0900 #ifdef CONFIG_SMP
0901     struct kgdb_state kgdb_var;
0902     struct kgdb_state *ks = &kgdb_var;
0903 
0904     kgdb_info[cpu].rounding_up = false;
0905 
0906     memset(ks, 0, sizeof(struct kgdb_state));
0907     ks->cpu         = cpu;
0908     ks->linux_regs      = regs;
0909 
0910     if (kgdb_info[ks->cpu].enter_kgdb == 0 &&
0911             raw_spin_is_locked(&dbg_master_lock)) {
0912         kgdb_cpu_enter(ks, regs, DCPU_IS_SLAVE);
0913         return 0;
0914     }
0915 #endif
0916     return 1;
0917 }
0918 NOKPROBE_SYMBOL(kgdb_nmicallback);
0919 
0920 int kgdb_nmicallin(int cpu, int trapnr, void *regs, int err_code,
0921                             atomic_t *send_ready)
0922 {
0923 #ifdef CONFIG_SMP
0924     if (!kgdb_io_ready(0) || !send_ready)
0925         return 1;
0926 
0927     if (kgdb_info[cpu].enter_kgdb == 0) {
0928         struct kgdb_state kgdb_var;
0929         struct kgdb_state *ks = &kgdb_var;
0930 
0931         memset(ks, 0, sizeof(struct kgdb_state));
0932         ks->cpu         = cpu;
0933         ks->ex_vector       = trapnr;
0934         ks->signo       = SIGTRAP;
0935         ks->err_code        = err_code;
0936         ks->linux_regs      = regs;
0937         ks->send_ready      = send_ready;
0938         kgdb_cpu_enter(ks, regs, DCPU_WANT_MASTER);
0939         return 0;
0940     }
0941 #endif
0942     return 1;
0943 }
0944 NOKPROBE_SYMBOL(kgdb_nmicallin);
0945 
0946 static void kgdb_console_write(struct console *co, const char *s,
0947    unsigned count)
0948 {
0949     unsigned long flags;
0950 
0951     /* If we're debugging, or KGDB has not connected, don't try
0952      * and print. */
0953     if (!kgdb_connected || atomic_read(&kgdb_active) != -1 || dbg_kdb_mode)
0954         return;
0955 
0956     local_irq_save(flags);
0957     gdbstub_msg_write(s, count);
0958     local_irq_restore(flags);
0959 }
0960 
0961 static struct console kgdbcons = {
0962     .name       = "kgdb",
0963     .write      = kgdb_console_write,
0964     .flags      = CON_PRINTBUFFER | CON_ENABLED,
0965     .index      = -1,
0966 };
0967 
0968 static int __init opt_kgdb_con(char *str)
0969 {
0970     kgdb_use_con = 1;
0971 
0972     if (kgdb_io_module_registered && !kgdb_con_registered) {
0973         register_console(&kgdbcons);
0974         kgdb_con_registered = 1;
0975     }
0976 
0977     return 0;
0978 }
0979 
0980 early_param("kgdbcon", opt_kgdb_con);
0981 
0982 #ifdef CONFIG_MAGIC_SYSRQ
0983 static void sysrq_handle_dbg(int key)
0984 {
0985     if (!dbg_io_ops) {
0986         pr_crit("ERROR: No KGDB I/O module available\n");
0987         return;
0988     }
0989     if (!kgdb_connected) {
0990 #ifdef CONFIG_KGDB_KDB
0991         if (!dbg_kdb_mode)
0992             pr_crit("KGDB or $3#33 for KDB\n");
0993 #else
0994         pr_crit("Entering KGDB\n");
0995 #endif
0996     }
0997 
0998     kgdb_breakpoint();
0999 }
1000 
1001 static const struct sysrq_key_op sysrq_dbg_op = {
1002     .handler    = sysrq_handle_dbg,
1003     .help_msg   = "debug(g)",
1004     .action_msg = "DEBUG",
1005 };
1006 #endif
1007 
1008 void kgdb_panic(const char *msg)
1009 {
1010     if (!kgdb_io_module_registered)
1011         return;
1012 
1013     /*
1014      * We don't want to get stuck waiting for input from user if
1015      * "panic_timeout" indicates the system should automatically
1016      * reboot on panic.
1017      */
1018     if (panic_timeout)
1019         return;
1020 
1021     if (dbg_kdb_mode)
1022         kdb_printf("PANIC: %s\n", msg);
1023 
1024     kgdb_breakpoint();
1025 }
1026 
1027 static void kgdb_initial_breakpoint(void)
1028 {
1029     kgdb_break_asap = 0;
1030 
1031     pr_crit("Waiting for connection from remote gdb...\n");
1032     kgdb_breakpoint();
1033 }
1034 
1035 void __weak kgdb_arch_late(void)
1036 {
1037 }
1038 
1039 void __init dbg_late_init(void)
1040 {
1041     dbg_is_early = false;
1042     if (kgdb_io_module_registered)
1043         kgdb_arch_late();
1044     kdb_init(KDB_INIT_FULL);
1045 
1046     if (kgdb_io_module_registered && kgdb_break_asap)
1047         kgdb_initial_breakpoint();
1048 }
1049 
1050 static int
1051 dbg_notify_reboot(struct notifier_block *this, unsigned long code, void *x)
1052 {
1053     /*
1054      * Take the following action on reboot notify depending on value:
1055      *    1 == Enter debugger
1056      *    0 == [the default] detach debug client
1057      *   -1 == Do nothing... and use this until the board resets
1058      */
1059     switch (kgdbreboot) {
1060     case 1:
1061         kgdb_breakpoint();
1062         goto done;
1063     case -1:
1064         goto done;
1065     }
1066     if (!dbg_kdb_mode)
1067         gdbstub_exit(code);
1068 done:
1069     return NOTIFY_DONE;
1070 }
1071 
1072 static struct notifier_block dbg_reboot_notifier = {
1073     .notifier_call      = dbg_notify_reboot,
1074     .next           = NULL,
1075     .priority       = INT_MAX,
1076 };
1077 
1078 static void kgdb_register_callbacks(void)
1079 {
1080     if (!kgdb_io_module_registered) {
1081         kgdb_io_module_registered = 1;
1082         kgdb_arch_init();
1083         if (!dbg_is_early)
1084             kgdb_arch_late();
1085         register_module_notifier(&dbg_module_load_nb);
1086         register_reboot_notifier(&dbg_reboot_notifier);
1087 #ifdef CONFIG_MAGIC_SYSRQ
1088         register_sysrq_key('g', &sysrq_dbg_op);
1089 #endif
1090         if (kgdb_use_con && !kgdb_con_registered) {
1091             register_console(&kgdbcons);
1092             kgdb_con_registered = 1;
1093         }
1094     }
1095 }
1096 
1097 static void kgdb_unregister_callbacks(void)
1098 {
1099     /*
1100      * When this routine is called KGDB should unregister from
1101      * handlers and clean up, making sure it is not handling any
1102      * break exceptions at the time.
1103      */
1104     if (kgdb_io_module_registered) {
1105         kgdb_io_module_registered = 0;
1106         unregister_reboot_notifier(&dbg_reboot_notifier);
1107         unregister_module_notifier(&dbg_module_load_nb);
1108         kgdb_arch_exit();
1109 #ifdef CONFIG_MAGIC_SYSRQ
1110         unregister_sysrq_key('g', &sysrq_dbg_op);
1111 #endif
1112         if (kgdb_con_registered) {
1113             unregister_console(&kgdbcons);
1114             kgdb_con_registered = 0;
1115         }
1116     }
1117 }
1118 
1119 /**
1120  *  kgdb_register_io_module - register KGDB IO module
1121  *  @new_dbg_io_ops: the io ops vector
1122  *
1123  *  Register it with the KGDB core.
1124  */
1125 int kgdb_register_io_module(struct kgdb_io *new_dbg_io_ops)
1126 {
1127     struct kgdb_io *old_dbg_io_ops;
1128     int err;
1129 
1130     spin_lock(&kgdb_registration_lock);
1131 
1132     old_dbg_io_ops = dbg_io_ops;
1133     if (old_dbg_io_ops) {
1134         if (!old_dbg_io_ops->deinit) {
1135             spin_unlock(&kgdb_registration_lock);
1136 
1137             pr_err("KGDB I/O driver %s can't replace %s.\n",
1138                 new_dbg_io_ops->name, old_dbg_io_ops->name);
1139             return -EBUSY;
1140         }
1141         pr_info("Replacing I/O driver %s with %s\n",
1142             old_dbg_io_ops->name, new_dbg_io_ops->name);
1143     }
1144 
1145     if (new_dbg_io_ops->init) {
1146         err = new_dbg_io_ops->init();
1147         if (err) {
1148             spin_unlock(&kgdb_registration_lock);
1149             return err;
1150         }
1151     }
1152 
1153     dbg_io_ops = new_dbg_io_ops;
1154 
1155     spin_unlock(&kgdb_registration_lock);
1156 
1157     if (old_dbg_io_ops) {
1158         old_dbg_io_ops->deinit();
1159         return 0;
1160     }
1161 
1162     pr_info("Registered I/O driver %s\n", new_dbg_io_ops->name);
1163 
1164     /* Arm KGDB now. */
1165     kgdb_register_callbacks();
1166 
1167     if (kgdb_break_asap &&
1168         (!dbg_is_early || IS_ENABLED(CONFIG_ARCH_HAS_EARLY_DEBUG)))
1169         kgdb_initial_breakpoint();
1170 
1171     return 0;
1172 }
1173 EXPORT_SYMBOL_GPL(kgdb_register_io_module);
1174 
1175 /**
1176  *  kgdb_unregister_io_module - unregister KGDB IO module
1177  *  @old_dbg_io_ops: the io ops vector
1178  *
1179  *  Unregister it with the KGDB core.
1180  */
1181 void kgdb_unregister_io_module(struct kgdb_io *old_dbg_io_ops)
1182 {
1183     BUG_ON(kgdb_connected);
1184 
1185     /*
1186      * KGDB is no longer able to communicate out, so
1187      * unregister our callbacks and reset state.
1188      */
1189     kgdb_unregister_callbacks();
1190 
1191     spin_lock(&kgdb_registration_lock);
1192 
1193     WARN_ON_ONCE(dbg_io_ops != old_dbg_io_ops);
1194     dbg_io_ops = NULL;
1195 
1196     spin_unlock(&kgdb_registration_lock);
1197 
1198     if (old_dbg_io_ops->deinit)
1199         old_dbg_io_ops->deinit();
1200 
1201     pr_info("Unregistered I/O driver %s, debugger disabled\n",
1202         old_dbg_io_ops->name);
1203 }
1204 EXPORT_SYMBOL_GPL(kgdb_unregister_io_module);
1205 
1206 int dbg_io_get_char(void)
1207 {
1208     int ret = dbg_io_ops->read_char();
1209     if (ret == NO_POLL_CHAR)
1210         return -1;
1211     if (!dbg_kdb_mode)
1212         return ret;
1213     if (ret == 127)
1214         return 8;
1215     return ret;
1216 }
1217 
1218 /**
1219  * kgdb_breakpoint - generate breakpoint exception
1220  *
1221  * This function will generate a breakpoint exception.  It is used at the
1222  * beginning of a program to sync up with a debugger and can be used
1223  * otherwise as a quick means to stop program execution and "break" into
1224  * the debugger.
1225  */
1226 noinline void kgdb_breakpoint(void)
1227 {
1228     atomic_inc(&kgdb_setting_breakpoint);
1229     wmb(); /* Sync point before breakpoint */
1230     arch_kgdb_breakpoint();
1231     wmb(); /* Sync point after breakpoint */
1232     atomic_dec(&kgdb_setting_breakpoint);
1233 }
1234 EXPORT_SYMBOL_GPL(kgdb_breakpoint);
1235 
1236 static int __init opt_kgdb_wait(char *str)
1237 {
1238     kgdb_break_asap = 1;
1239 
1240     kdb_init(KDB_INIT_EARLY);
1241     if (kgdb_io_module_registered &&
1242         IS_ENABLED(CONFIG_ARCH_HAS_EARLY_DEBUG))
1243         kgdb_initial_breakpoint();
1244 
1245     return 0;
1246 }
1247 
1248 early_param("kgdbwait", opt_kgdb_wait);