kgdb: fix gdb serial thread queries
[sfrench/cifs-2.6.git] / kernel / kgdb.c
1 /*
2  * KGDB stub.
3  *
4  * Maintainer: Jason Wessel <jason.wessel@windriver.com>
5  *
6  * Copyright (C) 2000-2001 VERITAS Software Corporation.
7  * Copyright (C) 2002-2004 Timesys Corporation
8  * Copyright (C) 2003-2004 Amit S. Kale <amitkale@linsyssoft.com>
9  * Copyright (C) 2004 Pavel Machek <pavel@suse.cz>
10  * Copyright (C) 2004-2006 Tom Rini <trini@kernel.crashing.org>
11  * Copyright (C) 2004-2006 LinSysSoft Technologies Pvt. Ltd.
12  * Copyright (C) 2005-2008 Wind River Systems, Inc.
13  * Copyright (C) 2007 MontaVista Software, Inc.
14  * Copyright (C) 2008 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
15  *
16  * Contributors at various stages not listed above:
17  *  Jason Wessel ( jason.wessel@windriver.com )
18  *  George Anzinger <george@mvista.com>
19  *  Anurekh Saxena (anurekh.saxena@timesys.com)
20  *  Lake Stevens Instrument Division (Glenn Engel)
21  *  Jim Kingdon, Cygnus Support.
22  *
23  * Original KGDB stub: David Grothe <dave@gcom.com>,
24  * Tigran Aivazian <tigran@sco.com>
25  *
26  * This file is licensed under the terms of the GNU General Public License
27  * version 2. This program is licensed "as is" without any warranty of any
28  * kind, whether express or implied.
29  */
30 #include <linux/pid_namespace.h>
31 #include <linux/clocksource.h>
32 #include <linux/interrupt.h>
33 #include <linux/spinlock.h>
34 #include <linux/console.h>
35 #include <linux/threads.h>
36 #include <linux/uaccess.h>
37 #include <linux/kernel.h>
38 #include <linux/module.h>
39 #include <linux/ptrace.h>
40 #include <linux/reboot.h>
41 #include <linux/string.h>
42 #include <linux/delay.h>
43 #include <linux/sched.h>
44 #include <linux/sysrq.h>
45 #include <linux/init.h>
46 #include <linux/kgdb.h>
47 #include <linux/pid.h>
48 #include <linux/smp.h>
49 #include <linux/mm.h>
50
51 #include <asm/cacheflush.h>
52 #include <asm/byteorder.h>
53 #include <asm/atomic.h>
54 #include <asm/system.h>
55 #include <asm/unaligned.h>
56
57 static int kgdb_break_asap;
58
59 #define KGDB_MAX_THREAD_QUERY 17
60 struct kgdb_state {
61         int                     ex_vector;
62         int                     signo;
63         int                     err_code;
64         int                     cpu;
65         int                     pass_exception;
66         unsigned long           thr_query;
67         unsigned long           threadid;
68         long                    kgdb_usethreadid;
69         struct pt_regs          *linux_regs;
70 };
71
72 static struct debuggerinfo_struct {
73         void                    *debuggerinfo;
74         struct task_struct      *task;
75 } kgdb_info[NR_CPUS];
76
77 /**
78  * kgdb_connected - Is a host GDB connected to us?
79  */
80 int                             kgdb_connected;
81 EXPORT_SYMBOL_GPL(kgdb_connected);
82
83 /* All the KGDB handlers are installed */
84 static int                      kgdb_io_module_registered;
85
86 /* Guard for recursive entry */
87 static int                      exception_level;
88
89 static struct kgdb_io           *kgdb_io_ops;
90 static DEFINE_SPINLOCK(kgdb_registration_lock);
91
92 /* kgdb console driver is loaded */
93 static int kgdb_con_registered;
94 /* determine if kgdb console output should be used */
95 static int kgdb_use_con;
96
97 static int __init opt_kgdb_con(char *str)
98 {
99         kgdb_use_con = 1;
100         return 0;
101 }
102
103 early_param("kgdbcon", opt_kgdb_con);
104
105 module_param(kgdb_use_con, int, 0644);
106
107 /*
108  * Holds information about breakpoints in a kernel. These breakpoints are
109  * added and removed by gdb.
110  */
111 static struct kgdb_bkpt         kgdb_break[KGDB_MAX_BREAKPOINTS] = {
112         [0 ... KGDB_MAX_BREAKPOINTS-1] = { .state = BP_UNDEFINED }
113 };
114
115 /*
116  * The CPU# of the active CPU, or -1 if none:
117  */
118 atomic_t                        kgdb_active = ATOMIC_INIT(-1);
119
120 /*
121  * We use NR_CPUs not PERCPU, in case kgdb is used to debug early
122  * bootup code (which might not have percpu set up yet):
123  */
124 static atomic_t                 passive_cpu_wait[NR_CPUS];
125 static atomic_t                 cpu_in_kgdb[NR_CPUS];
126 atomic_t                        kgdb_setting_breakpoint;
127
128 struct task_struct              *kgdb_usethread;
129 struct task_struct              *kgdb_contthread;
130
131 int                             kgdb_single_step;
132
133 /* Our I/O buffers. */
134 static char                     remcom_in_buffer[BUFMAX];
135 static char                     remcom_out_buffer[BUFMAX];
136
137 /* Storage for the registers, in GDB format. */
138 static unsigned long            gdb_regs[(NUMREGBYTES +
139                                         sizeof(unsigned long) - 1) /
140                                         sizeof(unsigned long)];
141
142 /* to keep track of the CPU which is doing the single stepping*/
143 atomic_t                        kgdb_cpu_doing_single_step = ATOMIC_INIT(-1);
144
145 /*
146  * If you are debugging a problem where roundup (the collection of
147  * all other CPUs) is a problem [this should be extremely rare],
148  * then use the nokgdbroundup option to avoid roundup. In that case
149  * the other CPUs might interfere with your debugging context, so
150  * use this with care:
151  */
152 static int kgdb_do_roundup = 1;
153
154 static int __init opt_nokgdbroundup(char *str)
155 {
156         kgdb_do_roundup = 0;
157
158         return 0;
159 }
160
161 early_param("nokgdbroundup", opt_nokgdbroundup);
162
163 /*
164  * Finally, some KGDB code :-)
165  */
166
167 /*
168  * Weak aliases for breakpoint management,
169  * can be overriden by architectures when needed:
170  */
171 int __weak kgdb_arch_set_breakpoint(unsigned long addr, char *saved_instr)
172 {
173         int err;
174
175         err = probe_kernel_read(saved_instr, (char *)addr, BREAK_INSTR_SIZE);
176         if (err)
177                 return err;
178
179         return probe_kernel_write((char *)addr, arch_kgdb_ops.gdb_bpt_instr,
180                                   BREAK_INSTR_SIZE);
181 }
182
183 int __weak kgdb_arch_remove_breakpoint(unsigned long addr, char *bundle)
184 {
185         return probe_kernel_write((char *)addr,
186                                   (char *)bundle, BREAK_INSTR_SIZE);
187 }
188
189 int __weak kgdb_validate_break_address(unsigned long addr)
190 {
191         char tmp_variable[BREAK_INSTR_SIZE];
192         int err;
193         /* Validate setting the breakpoint and then removing it.  In the
194          * remove fails, the kernel needs to emit a bad message because we
195          * are deep trouble not being able to put things back the way we
196          * found them.
197          */
198         err = kgdb_arch_set_breakpoint(addr, tmp_variable);
199         if (err)
200                 return err;
201         err = kgdb_arch_remove_breakpoint(addr, tmp_variable);
202         if (err)
203                 printk(KERN_ERR "KGDB: Critical breakpoint error, kernel "
204                    "memory destroyed at: %lx", addr);
205         return err;
206 }
207
208 unsigned long __weak kgdb_arch_pc(int exception, struct pt_regs *regs)
209 {
210         return instruction_pointer(regs);
211 }
212
213 int __weak kgdb_arch_init(void)
214 {
215         return 0;
216 }
217
218 int __weak kgdb_skipexception(int exception, struct pt_regs *regs)
219 {
220         return 0;
221 }
222
223 void __weak
224 kgdb_post_primary_code(struct pt_regs *regs, int e_vector, int err_code)
225 {
226         return;
227 }
228
229 /**
230  *      kgdb_disable_hw_debug - Disable hardware debugging while we in kgdb.
231  *      @regs: Current &struct pt_regs.
232  *
233  *      This function will be called if the particular architecture must
234  *      disable hardware debugging while it is processing gdb packets or
235  *      handling exception.
236  */
237 void __weak kgdb_disable_hw_debug(struct pt_regs *regs)
238 {
239 }
240
241 /*
242  * GDB remote protocol parser:
243  */
244
245 static int hex(char ch)
246 {
247         if ((ch >= 'a') && (ch <= 'f'))
248                 return ch - 'a' + 10;
249         if ((ch >= '0') && (ch <= '9'))
250                 return ch - '0';
251         if ((ch >= 'A') && (ch <= 'F'))
252                 return ch - 'A' + 10;
253         return -1;
254 }
255
256 /* scan for the sequence $<data>#<checksum> */
257 static void get_packet(char *buffer)
258 {
259         unsigned char checksum;
260         unsigned char xmitcsum;
261         int count;
262         char ch;
263
264         do {
265                 /*
266                  * Spin and wait around for the start character, ignore all
267                  * other characters:
268                  */
269                 while ((ch = (kgdb_io_ops->read_char())) != '$')
270                         /* nothing */;
271
272                 kgdb_connected = 1;
273                 checksum = 0;
274                 xmitcsum = -1;
275
276                 count = 0;
277
278                 /*
279                  * now, read until a # or end of buffer is found:
280                  */
281                 while (count < (BUFMAX - 1)) {
282                         ch = kgdb_io_ops->read_char();
283                         if (ch == '#')
284                                 break;
285                         checksum = checksum + ch;
286                         buffer[count] = ch;
287                         count = count + 1;
288                 }
289                 buffer[count] = 0;
290
291                 if (ch == '#') {
292                         xmitcsum = hex(kgdb_io_ops->read_char()) << 4;
293                         xmitcsum += hex(kgdb_io_ops->read_char());
294
295                         if (checksum != xmitcsum)
296                                 /* failed checksum */
297                                 kgdb_io_ops->write_char('-');
298                         else
299                                 /* successful transfer */
300                                 kgdb_io_ops->write_char('+');
301                         if (kgdb_io_ops->flush)
302                                 kgdb_io_ops->flush();
303                 }
304         } while (checksum != xmitcsum);
305 }
306
307 /*
308  * Send the packet in buffer.
309  * Check for gdb connection if asked for.
310  */
311 static void put_packet(char *buffer)
312 {
313         unsigned char checksum;
314         int count;
315         char ch;
316
317         /*
318          * $<packet info>#<checksum>.
319          */
320         while (1) {
321                 kgdb_io_ops->write_char('$');
322                 checksum = 0;
323                 count = 0;
324
325                 while ((ch = buffer[count])) {
326                         kgdb_io_ops->write_char(ch);
327                         checksum += ch;
328                         count++;
329                 }
330
331                 kgdb_io_ops->write_char('#');
332                 kgdb_io_ops->write_char(hex_asc_hi(checksum));
333                 kgdb_io_ops->write_char(hex_asc_lo(checksum));
334                 if (kgdb_io_ops->flush)
335                         kgdb_io_ops->flush();
336
337                 /* Now see what we get in reply. */
338                 ch = kgdb_io_ops->read_char();
339
340                 if (ch == 3)
341                         ch = kgdb_io_ops->read_char();
342
343                 /* If we get an ACK, we are done. */
344                 if (ch == '+')
345                         return;
346
347                 /*
348                  * If we get the start of another packet, this means
349                  * that GDB is attempting to reconnect.  We will NAK
350                  * the packet being sent, and stop trying to send this
351                  * packet.
352                  */
353                 if (ch == '$') {
354                         kgdb_io_ops->write_char('-');
355                         if (kgdb_io_ops->flush)
356                                 kgdb_io_ops->flush();
357                         return;
358                 }
359         }
360 }
361
362 /*
363  * Convert the memory pointed to by mem into hex, placing result in buf.
364  * Return a pointer to the last char put in buf (null). May return an error.
365  */
366 int kgdb_mem2hex(char *mem, char *buf, int count)
367 {
368         char *tmp;
369         int err;
370
371         /*
372          * We use the upper half of buf as an intermediate buffer for the
373          * raw memory copy.  Hex conversion will work against this one.
374          */
375         tmp = buf + count;
376
377         err = probe_kernel_read(tmp, mem, count);
378         if (!err) {
379                 while (count > 0) {
380                         buf = pack_hex_byte(buf, *tmp);
381                         tmp++;
382                         count--;
383                 }
384
385                 *buf = 0;
386         }
387
388         return err;
389 }
390
391 /*
392  * Copy the binary array pointed to by buf into mem.  Fix $, #, and
393  * 0x7d escaped with 0x7d.  Return a pointer to the character after
394  * the last byte written.
395  */
396 static int kgdb_ebin2mem(char *buf, char *mem, int count)
397 {
398         int err = 0;
399         char c;
400
401         while (count-- > 0) {
402                 c = *buf++;
403                 if (c == 0x7d)
404                         c = *buf++ ^ 0x20;
405
406                 err = probe_kernel_write(mem, &c, 1);
407                 if (err)
408                         break;
409
410                 mem++;
411         }
412
413         return err;
414 }
415
416 /*
417  * Convert the hex array pointed to by buf into binary to be placed in mem.
418  * Return a pointer to the character AFTER the last byte written.
419  * May return an error.
420  */
421 int kgdb_hex2mem(char *buf, char *mem, int count)
422 {
423         char *tmp_raw;
424         char *tmp_hex;
425
426         /*
427          * We use the upper half of buf as an intermediate buffer for the
428          * raw memory that is converted from hex.
429          */
430         tmp_raw = buf + count * 2;
431
432         tmp_hex = tmp_raw - 1;
433         while (tmp_hex >= buf) {
434                 tmp_raw--;
435                 *tmp_raw = hex(*tmp_hex--);
436                 *tmp_raw |= hex(*tmp_hex--) << 4;
437         }
438
439         return probe_kernel_write(mem, tmp_raw, count);
440 }
441
442 /*
443  * While we find nice hex chars, build a long_val.
444  * Return number of chars processed.
445  */
446 int kgdb_hex2long(char **ptr, unsigned long *long_val)
447 {
448         int hex_val;
449         int num = 0;
450         int negate = 0;
451
452         *long_val = 0;
453
454         if (**ptr == '-') {
455                 negate = 1;
456                 (*ptr)++;
457         }
458         while (**ptr) {
459                 hex_val = hex(**ptr);
460                 if (hex_val < 0)
461                         break;
462
463                 *long_val = (*long_val << 4) | hex_val;
464                 num++;
465                 (*ptr)++;
466         }
467
468         if (negate)
469                 *long_val = -*long_val;
470
471         return num;
472 }
473
474 /* Write memory due to an 'M' or 'X' packet. */
475 static int write_mem_msg(int binary)
476 {
477         char *ptr = &remcom_in_buffer[1];
478         unsigned long addr;
479         unsigned long length;
480         int err;
481
482         if (kgdb_hex2long(&ptr, &addr) > 0 && *(ptr++) == ',' &&
483             kgdb_hex2long(&ptr, &length) > 0 && *(ptr++) == ':') {
484                 if (binary)
485                         err = kgdb_ebin2mem(ptr, (char *)addr, length);
486                 else
487                         err = kgdb_hex2mem(ptr, (char *)addr, length);
488                 if (err)
489                         return err;
490                 if (CACHE_FLUSH_IS_SAFE)
491                         flush_icache_range(addr, addr + length + 1);
492                 return 0;
493         }
494
495         return -EINVAL;
496 }
497
498 static void error_packet(char *pkt, int error)
499 {
500         error = -error;
501         pkt[0] = 'E';
502         pkt[1] = hex_asc[(error / 10)];
503         pkt[2] = hex_asc[(error % 10)];
504         pkt[3] = '\0';
505 }
506
507 /*
508  * Thread ID accessors. We represent a flat TID space to GDB, where
509  * the per CPU idle threads (which under Linux all have PID 0) are
510  * remapped to negative TIDs.
511  */
512
513 #define BUF_THREAD_ID_SIZE      16
514
515 static char *pack_threadid(char *pkt, unsigned char *id)
516 {
517         char *limit;
518
519         limit = pkt + BUF_THREAD_ID_SIZE;
520         while (pkt < limit)
521                 pkt = pack_hex_byte(pkt, *id++);
522
523         return pkt;
524 }
525
526 static void int_to_threadref(unsigned char *id, int value)
527 {
528         unsigned char *scan;
529         int i = 4;
530
531         scan = (unsigned char *)id;
532         while (i--)
533                 *scan++ = 0;
534         put_unaligned_be32(value, scan);
535 }
536
537 static struct task_struct *getthread(struct pt_regs *regs, int tid)
538 {
539         /*
540          * Non-positive TIDs are remapped to the cpu shadow information
541          */
542         if (tid == 0 || tid == -1)
543                 tid = -atomic_read(&kgdb_active) - 2;
544         if (tid < 0) {
545                 if (kgdb_info[-tid - 2].task)
546                         return kgdb_info[-tid - 2].task;
547                 else
548                         return idle_task(-tid - 2);
549         }
550
551         /*
552          * find_task_by_pid_ns() does not take the tasklist lock anymore
553          * but is nicely RCU locked - hence is a pretty resilient
554          * thing to use:
555          */
556         return find_task_by_pid_ns(tid, &init_pid_ns);
557 }
558
559 /*
560  * CPU debug state control:
561  */
562
563 #ifdef CONFIG_SMP
564 static void kgdb_wait(struct pt_regs *regs)
565 {
566         unsigned long flags;
567         int cpu;
568
569         local_irq_save(flags);
570         cpu = raw_smp_processor_id();
571         kgdb_info[cpu].debuggerinfo = regs;
572         kgdb_info[cpu].task = current;
573         /*
574          * Make sure the above info reaches the primary CPU before
575          * our cpu_in_kgdb[] flag setting does:
576          */
577         smp_wmb();
578         atomic_set(&cpu_in_kgdb[cpu], 1);
579
580         /* Wait till primary CPU is done with debugging */
581         while (atomic_read(&passive_cpu_wait[cpu]))
582                 cpu_relax();
583
584         kgdb_info[cpu].debuggerinfo = NULL;
585         kgdb_info[cpu].task = NULL;
586
587         /* fix up hardware debug registers on local cpu */
588         if (arch_kgdb_ops.correct_hw_break)
589                 arch_kgdb_ops.correct_hw_break();
590
591         /* Signal the primary CPU that we are done: */
592         atomic_set(&cpu_in_kgdb[cpu], 0);
593         clocksource_touch_watchdog();
594         local_irq_restore(flags);
595 }
596 #endif
597
598 /*
599  * Some architectures need cache flushes when we set/clear a
600  * breakpoint:
601  */
602 static void kgdb_flush_swbreak_addr(unsigned long addr)
603 {
604         if (!CACHE_FLUSH_IS_SAFE)
605                 return;
606
607         if (current->mm && current->mm->mmap_cache) {
608                 flush_cache_range(current->mm->mmap_cache,
609                                   addr, addr + BREAK_INSTR_SIZE);
610         }
611         /* Force flush instruction cache if it was outside the mm */
612         flush_icache_range(addr, addr + BREAK_INSTR_SIZE);
613 }
614
615 /*
616  * SW breakpoint management:
617  */
618 static int kgdb_activate_sw_breakpoints(void)
619 {
620         unsigned long addr;
621         int error = 0;
622         int i;
623
624         for (i = 0; i < KGDB_MAX_BREAKPOINTS; i++) {
625                 if (kgdb_break[i].state != BP_SET)
626                         continue;
627
628                 addr = kgdb_break[i].bpt_addr;
629                 error = kgdb_arch_set_breakpoint(addr,
630                                 kgdb_break[i].saved_instr);
631                 if (error)
632                         return error;
633
634                 kgdb_flush_swbreak_addr(addr);
635                 kgdb_break[i].state = BP_ACTIVE;
636         }
637         return 0;
638 }
639
640 static int kgdb_set_sw_break(unsigned long addr)
641 {
642         int err = kgdb_validate_break_address(addr);
643         int breakno = -1;
644         int i;
645
646         if (err)
647                 return err;
648
649         for (i = 0; i < KGDB_MAX_BREAKPOINTS; i++) {
650                 if ((kgdb_break[i].state == BP_SET) &&
651                                         (kgdb_break[i].bpt_addr == addr))
652                         return -EEXIST;
653         }
654         for (i = 0; i < KGDB_MAX_BREAKPOINTS; i++) {
655                 if (kgdb_break[i].state == BP_REMOVED &&
656                                         kgdb_break[i].bpt_addr == addr) {
657                         breakno = i;
658                         break;
659                 }
660         }
661
662         if (breakno == -1) {
663                 for (i = 0; i < KGDB_MAX_BREAKPOINTS; i++) {
664                         if (kgdb_break[i].state == BP_UNDEFINED) {
665                                 breakno = i;
666                                 break;
667                         }
668                 }
669         }
670
671         if (breakno == -1)
672                 return -E2BIG;
673
674         kgdb_break[breakno].state = BP_SET;
675         kgdb_break[breakno].type = BP_BREAKPOINT;
676         kgdb_break[breakno].bpt_addr = addr;
677
678         return 0;
679 }
680
681 static int kgdb_deactivate_sw_breakpoints(void)
682 {
683         unsigned long addr;
684         int error = 0;
685         int i;
686
687         for (i = 0; i < KGDB_MAX_BREAKPOINTS; i++) {
688                 if (kgdb_break[i].state != BP_ACTIVE)
689                         continue;
690                 addr = kgdb_break[i].bpt_addr;
691                 error = kgdb_arch_remove_breakpoint(addr,
692                                         kgdb_break[i].saved_instr);
693                 if (error)
694                         return error;
695
696                 kgdb_flush_swbreak_addr(addr);
697                 kgdb_break[i].state = BP_SET;
698         }
699         return 0;
700 }
701
702 static int kgdb_remove_sw_break(unsigned long addr)
703 {
704         int i;
705
706         for (i = 0; i < KGDB_MAX_BREAKPOINTS; i++) {
707                 if ((kgdb_break[i].state == BP_SET) &&
708                                 (kgdb_break[i].bpt_addr == addr)) {
709                         kgdb_break[i].state = BP_REMOVED;
710                         return 0;
711                 }
712         }
713         return -ENOENT;
714 }
715
716 int kgdb_isremovedbreak(unsigned long addr)
717 {
718         int i;
719
720         for (i = 0; i < KGDB_MAX_BREAKPOINTS; i++) {
721                 if ((kgdb_break[i].state == BP_REMOVED) &&
722                                         (kgdb_break[i].bpt_addr == addr))
723                         return 1;
724         }
725         return 0;
726 }
727
728 static int remove_all_break(void)
729 {
730         unsigned long addr;
731         int error;
732         int i;
733
734         /* Clear memory breakpoints. */
735         for (i = 0; i < KGDB_MAX_BREAKPOINTS; i++) {
736                 if (kgdb_break[i].state != BP_ACTIVE)
737                         goto setundefined;
738                 addr = kgdb_break[i].bpt_addr;
739                 error = kgdb_arch_remove_breakpoint(addr,
740                                 kgdb_break[i].saved_instr);
741                 if (error)
742                         printk(KERN_ERR "KGDB: breakpoint remove failed: %lx\n",
743                            addr);
744 setundefined:
745                 kgdb_break[i].state = BP_UNDEFINED;
746         }
747
748         /* Clear hardware breakpoints. */
749         if (arch_kgdb_ops.remove_all_hw_break)
750                 arch_kgdb_ops.remove_all_hw_break();
751
752         return 0;
753 }
754
755 /*
756  * Remap normal tasks to their real PID,
757  * CPU shadow threads are mapped to -CPU - 2
758  */
759 static inline int shadow_pid(int realpid)
760 {
761         if (realpid)
762                 return realpid;
763
764         return -raw_smp_processor_id() - 2;
765 }
766
767 static char gdbmsgbuf[BUFMAX + 1];
768
769 static void kgdb_msg_write(const char *s, int len)
770 {
771         char *bufptr;
772         int wcount;
773         int i;
774
775         /* 'O'utput */
776         gdbmsgbuf[0] = 'O';
777
778         /* Fill and send buffers... */
779         while (len > 0) {
780                 bufptr = gdbmsgbuf + 1;
781
782                 /* Calculate how many this time */
783                 if ((len << 1) > (BUFMAX - 2))
784                         wcount = (BUFMAX - 2) >> 1;
785                 else
786                         wcount = len;
787
788                 /* Pack in hex chars */
789                 for (i = 0; i < wcount; i++)
790                         bufptr = pack_hex_byte(bufptr, s[i]);
791                 *bufptr = '\0';
792
793                 /* Move up */
794                 s += wcount;
795                 len -= wcount;
796
797                 /* Write packet */
798                 put_packet(gdbmsgbuf);
799         }
800 }
801
802 /*
803  * Return true if there is a valid kgdb I/O module.  Also if no
804  * debugger is attached a message can be printed to the console about
805  * waiting for the debugger to attach.
806  *
807  * The print_wait argument is only to be true when called from inside
808  * the core kgdb_handle_exception, because it will wait for the
809  * debugger to attach.
810  */
811 static int kgdb_io_ready(int print_wait)
812 {
813         if (!kgdb_io_ops)
814                 return 0;
815         if (kgdb_connected)
816                 return 1;
817         if (atomic_read(&kgdb_setting_breakpoint))
818                 return 1;
819         if (print_wait)
820                 printk(KERN_CRIT "KGDB: Waiting for remote debugger\n");
821         return 1;
822 }
823
824 /*
825  * All the functions that start with gdb_cmd are the various
826  * operations to implement the handlers for the gdbserial protocol
827  * where KGDB is communicating with an external debugger
828  */
829
830 /* Handle the '?' status packets */
831 static void gdb_cmd_status(struct kgdb_state *ks)
832 {
833         /*
834          * We know that this packet is only sent
835          * during initial connect.  So to be safe,
836          * we clear out our breakpoints now in case
837          * GDB is reconnecting.
838          */
839         remove_all_break();
840
841         remcom_out_buffer[0] = 'S';
842         pack_hex_byte(&remcom_out_buffer[1], ks->signo);
843 }
844
845 /* Handle the 'g' get registers request */
846 static void gdb_cmd_getregs(struct kgdb_state *ks)
847 {
848         struct task_struct *thread;
849         void *local_debuggerinfo;
850         int i;
851
852         thread = kgdb_usethread;
853         if (!thread) {
854                 thread = kgdb_info[ks->cpu].task;
855                 local_debuggerinfo = kgdb_info[ks->cpu].debuggerinfo;
856         } else {
857                 local_debuggerinfo = NULL;
858                 for_each_online_cpu(i) {
859                         /*
860                          * Try to find the task on some other
861                          * or possibly this node if we do not
862                          * find the matching task then we try
863                          * to approximate the results.
864                          */
865                         if (thread == kgdb_info[i].task)
866                                 local_debuggerinfo = kgdb_info[i].debuggerinfo;
867                 }
868         }
869
870         /*
871          * All threads that don't have debuggerinfo should be
872          * in __schedule() sleeping, since all other CPUs
873          * are in kgdb_wait, and thus have debuggerinfo.
874          */
875         if (local_debuggerinfo) {
876                 pt_regs_to_gdb_regs(gdb_regs, local_debuggerinfo);
877         } else {
878                 /*
879                  * Pull stuff saved during switch_to; nothing
880                  * else is accessible (or even particularly
881                  * relevant).
882                  *
883                  * This should be enough for a stack trace.
884                  */
885                 sleeping_thread_to_gdb_regs(gdb_regs, thread);
886         }
887         kgdb_mem2hex((char *)gdb_regs, remcom_out_buffer, NUMREGBYTES);
888 }
889
890 /* Handle the 'G' set registers request */
891 static void gdb_cmd_setregs(struct kgdb_state *ks)
892 {
893         kgdb_hex2mem(&remcom_in_buffer[1], (char *)gdb_regs, NUMREGBYTES);
894
895         if (kgdb_usethread && kgdb_usethread != current) {
896                 error_packet(remcom_out_buffer, -EINVAL);
897         } else {
898                 gdb_regs_to_pt_regs(gdb_regs, ks->linux_regs);
899                 strcpy(remcom_out_buffer, "OK");
900         }
901 }
902
903 /* Handle the 'm' memory read bytes */
904 static void gdb_cmd_memread(struct kgdb_state *ks)
905 {
906         char *ptr = &remcom_in_buffer[1];
907         unsigned long length;
908         unsigned long addr;
909         int err;
910
911         if (kgdb_hex2long(&ptr, &addr) > 0 && *ptr++ == ',' &&
912                                         kgdb_hex2long(&ptr, &length) > 0) {
913                 err = kgdb_mem2hex((char *)addr, remcom_out_buffer, length);
914                 if (err)
915                         error_packet(remcom_out_buffer, err);
916         } else {
917                 error_packet(remcom_out_buffer, -EINVAL);
918         }
919 }
920
921 /* Handle the 'M' memory write bytes */
922 static void gdb_cmd_memwrite(struct kgdb_state *ks)
923 {
924         int err = write_mem_msg(0);
925
926         if (err)
927                 error_packet(remcom_out_buffer, err);
928         else
929                 strcpy(remcom_out_buffer, "OK");
930 }
931
932 /* Handle the 'X' memory binary write bytes */
933 static void gdb_cmd_binwrite(struct kgdb_state *ks)
934 {
935         int err = write_mem_msg(1);
936
937         if (err)
938                 error_packet(remcom_out_buffer, err);
939         else
940                 strcpy(remcom_out_buffer, "OK");
941 }
942
943 /* Handle the 'D' or 'k', detach or kill packets */
944 static void gdb_cmd_detachkill(struct kgdb_state *ks)
945 {
946         int error;
947
948         /* The detach case */
949         if (remcom_in_buffer[0] == 'D') {
950                 error = remove_all_break();
951                 if (error < 0) {
952                         error_packet(remcom_out_buffer, error);
953                 } else {
954                         strcpy(remcom_out_buffer, "OK");
955                         kgdb_connected = 0;
956                 }
957                 put_packet(remcom_out_buffer);
958         } else {
959                 /*
960                  * Assume the kill case, with no exit code checking,
961                  * trying to force detach the debugger:
962                  */
963                 remove_all_break();
964                 kgdb_connected = 0;
965         }
966 }
967
968 /* Handle the 'R' reboot packets */
969 static int gdb_cmd_reboot(struct kgdb_state *ks)
970 {
971         /* For now, only honor R0 */
972         if (strcmp(remcom_in_buffer, "R0") == 0) {
973                 printk(KERN_CRIT "Executing emergency reboot\n");
974                 strcpy(remcom_out_buffer, "OK");
975                 put_packet(remcom_out_buffer);
976
977                 /*
978                  * Execution should not return from
979                  * machine_emergency_restart()
980                  */
981                 machine_emergency_restart();
982                 kgdb_connected = 0;
983
984                 return 1;
985         }
986         return 0;
987 }
988
989 /* Handle the 'q' query packets */
990 static void gdb_cmd_query(struct kgdb_state *ks)
991 {
992         struct task_struct *g;
993         struct task_struct *p;
994         unsigned char thref[8];
995         char *ptr;
996         int i;
997         int cpu;
998         int finished = 0;
999
1000         switch (remcom_in_buffer[1]) {
1001         case 's':
1002         case 'f':
1003                 if (memcmp(remcom_in_buffer + 2, "ThreadInfo", 10)) {
1004                         error_packet(remcom_out_buffer, -EINVAL);
1005                         break;
1006                 }
1007
1008                 i = 0;
1009                 remcom_out_buffer[0] = 'm';
1010                 ptr = remcom_out_buffer + 1;
1011                 if (remcom_in_buffer[1] == 'f') {
1012                         /* Each cpu is a shadow thread */
1013                         for_each_online_cpu(cpu) {
1014                                 ks->thr_query = 0;
1015                                 int_to_threadref(thref, -cpu - 2);
1016                                 pack_threadid(ptr, thref);
1017                                 ptr += BUF_THREAD_ID_SIZE;
1018                                 *(ptr++) = ',';
1019                                 i++;
1020                         }
1021                 }
1022
1023                 do_each_thread(g, p) {
1024                         if (i >= ks->thr_query && !finished) {
1025                                 int_to_threadref(thref, p->pid);
1026                                 pack_threadid(ptr, thref);
1027                                 ptr += BUF_THREAD_ID_SIZE;
1028                                 *(ptr++) = ',';
1029                                 ks->thr_query++;
1030                                 if (ks->thr_query % KGDB_MAX_THREAD_QUERY == 0)
1031                                         finished = 1;
1032                         }
1033                         i++;
1034                 } while_each_thread(g, p);
1035
1036                 *(--ptr) = '\0';
1037                 break;
1038
1039         case 'C':
1040                 /* Current thread id */
1041                 strcpy(remcom_out_buffer, "QC");
1042                 ks->threadid = shadow_pid(current->pid);
1043                 int_to_threadref(thref, ks->threadid);
1044                 pack_threadid(remcom_out_buffer + 2, thref);
1045                 break;
1046         case 'T':
1047                 if (memcmp(remcom_in_buffer + 1, "ThreadExtraInfo,", 16)) {
1048                         error_packet(remcom_out_buffer, -EINVAL);
1049                         break;
1050                 }
1051                 ks->threadid = 0;
1052                 ptr = remcom_in_buffer + 17;
1053                 kgdb_hex2long(&ptr, &ks->threadid);
1054                 if (!getthread(ks->linux_regs, ks->threadid)) {
1055                         error_packet(remcom_out_buffer, -EINVAL);
1056                         break;
1057                 }
1058                 if ((int)ks->threadid > 0) {
1059                         kgdb_mem2hex(getthread(ks->linux_regs,
1060                                         ks->threadid)->comm,
1061                                         remcom_out_buffer, 16);
1062                 } else {
1063                         static char tmpstr[23 + BUF_THREAD_ID_SIZE];
1064
1065                         sprintf(tmpstr, "shadowCPU%d",
1066                                         (int)(-ks->threadid - 2));
1067                         kgdb_mem2hex(tmpstr, remcom_out_buffer, strlen(tmpstr));
1068                 }
1069                 break;
1070         }
1071 }
1072
1073 /* Handle the 'H' task query packets */
1074 static void gdb_cmd_task(struct kgdb_state *ks)
1075 {
1076         struct task_struct *thread;
1077         char *ptr;
1078
1079         switch (remcom_in_buffer[1]) {
1080         case 'g':
1081                 ptr = &remcom_in_buffer[2];
1082                 kgdb_hex2long(&ptr, &ks->threadid);
1083                 thread = getthread(ks->linux_regs, ks->threadid);
1084                 if (!thread && ks->threadid > 0) {
1085                         error_packet(remcom_out_buffer, -EINVAL);
1086                         break;
1087                 }
1088                 kgdb_usethread = thread;
1089                 ks->kgdb_usethreadid = ks->threadid;
1090                 strcpy(remcom_out_buffer, "OK");
1091                 break;
1092         case 'c':
1093                 ptr = &remcom_in_buffer[2];
1094                 kgdb_hex2long(&ptr, &ks->threadid);
1095                 if (!ks->threadid) {
1096                         kgdb_contthread = NULL;
1097                 } else {
1098                         thread = getthread(ks->linux_regs, ks->threadid);
1099                         if (!thread && ks->threadid > 0) {
1100                                 error_packet(remcom_out_buffer, -EINVAL);
1101                                 break;
1102                         }
1103                         kgdb_contthread = thread;
1104                 }
1105                 strcpy(remcom_out_buffer, "OK");
1106                 break;
1107         }
1108 }
1109
1110 /* Handle the 'T' thread query packets */
1111 static void gdb_cmd_thread(struct kgdb_state *ks)
1112 {
1113         char *ptr = &remcom_in_buffer[1];
1114         struct task_struct *thread;
1115
1116         kgdb_hex2long(&ptr, &ks->threadid);
1117         thread = getthread(ks->linux_regs, ks->threadid);
1118         if (thread)
1119                 strcpy(remcom_out_buffer, "OK");
1120         else
1121                 error_packet(remcom_out_buffer, -EINVAL);
1122 }
1123
1124 /* Handle the 'z' or 'Z' breakpoint remove or set packets */
1125 static void gdb_cmd_break(struct kgdb_state *ks)
1126 {
1127         /*
1128          * Since GDB-5.3, it's been drafted that '0' is a software
1129          * breakpoint, '1' is a hardware breakpoint, so let's do that.
1130          */
1131         char *bpt_type = &remcom_in_buffer[1];
1132         char *ptr = &remcom_in_buffer[2];
1133         unsigned long addr;
1134         unsigned long length;
1135         int error = 0;
1136
1137         if (arch_kgdb_ops.set_hw_breakpoint && *bpt_type >= '1') {
1138                 /* Unsupported */
1139                 if (*bpt_type > '4')
1140                         return;
1141         } else {
1142                 if (*bpt_type != '0' && *bpt_type != '1')
1143                         /* Unsupported. */
1144                         return;
1145         }
1146
1147         /*
1148          * Test if this is a hardware breakpoint, and
1149          * if we support it:
1150          */
1151         if (*bpt_type == '1' && !(arch_kgdb_ops.flags & KGDB_HW_BREAKPOINT))
1152                 /* Unsupported. */
1153                 return;
1154
1155         if (*(ptr++) != ',') {
1156                 error_packet(remcom_out_buffer, -EINVAL);
1157                 return;
1158         }
1159         if (!kgdb_hex2long(&ptr, &addr)) {
1160                 error_packet(remcom_out_buffer, -EINVAL);
1161                 return;
1162         }
1163         if (*(ptr++) != ',' ||
1164                 !kgdb_hex2long(&ptr, &length)) {
1165                 error_packet(remcom_out_buffer, -EINVAL);
1166                 return;
1167         }
1168
1169         if (remcom_in_buffer[0] == 'Z' && *bpt_type == '0')
1170                 error = kgdb_set_sw_break(addr);
1171         else if (remcom_in_buffer[0] == 'z' && *bpt_type == '0')
1172                 error = kgdb_remove_sw_break(addr);
1173         else if (remcom_in_buffer[0] == 'Z')
1174                 error = arch_kgdb_ops.set_hw_breakpoint(addr,
1175                         (int)length, *bpt_type - '0');
1176         else if (remcom_in_buffer[0] == 'z')
1177                 error = arch_kgdb_ops.remove_hw_breakpoint(addr,
1178                         (int) length, *bpt_type - '0');
1179
1180         if (error == 0)
1181                 strcpy(remcom_out_buffer, "OK");
1182         else
1183                 error_packet(remcom_out_buffer, error);
1184 }
1185
1186 /* Handle the 'C' signal / exception passing packets */
1187 static int gdb_cmd_exception_pass(struct kgdb_state *ks)
1188 {
1189         /* C09 == pass exception
1190          * C15 == detach kgdb, pass exception
1191          */
1192         if (remcom_in_buffer[1] == '0' && remcom_in_buffer[2] == '9') {
1193
1194                 ks->pass_exception = 1;
1195                 remcom_in_buffer[0] = 'c';
1196
1197         } else if (remcom_in_buffer[1] == '1' && remcom_in_buffer[2] == '5') {
1198
1199                 ks->pass_exception = 1;
1200                 remcom_in_buffer[0] = 'D';
1201                 remove_all_break();
1202                 kgdb_connected = 0;
1203                 return 1;
1204
1205         } else {
1206                 error_packet(remcom_out_buffer, -EINVAL);
1207                 return 0;
1208         }
1209
1210         /* Indicate fall through */
1211         return -1;
1212 }
1213
1214 /*
1215  * This function performs all gdbserial command procesing
1216  */
1217 static int gdb_serial_stub(struct kgdb_state *ks)
1218 {
1219         int error = 0;
1220         int tmp;
1221
1222         /* Clear the out buffer. */
1223         memset(remcom_out_buffer, 0, sizeof(remcom_out_buffer));
1224
1225         if (kgdb_connected) {
1226                 unsigned char thref[8];
1227                 char *ptr;
1228
1229                 /* Reply to host that an exception has occurred */
1230                 ptr = remcom_out_buffer;
1231                 *ptr++ = 'T';
1232                 ptr = pack_hex_byte(ptr, ks->signo);
1233                 ptr += strlen(strcpy(ptr, "thread:"));
1234                 int_to_threadref(thref, shadow_pid(current->pid));
1235                 ptr = pack_threadid(ptr, thref);
1236                 *ptr++ = ';';
1237                 put_packet(remcom_out_buffer);
1238         }
1239
1240         kgdb_usethread = kgdb_info[ks->cpu].task;
1241         ks->kgdb_usethreadid = shadow_pid(kgdb_info[ks->cpu].task->pid);
1242         ks->pass_exception = 0;
1243
1244         while (1) {
1245                 error = 0;
1246
1247                 /* Clear the out buffer. */
1248                 memset(remcom_out_buffer, 0, sizeof(remcom_out_buffer));
1249
1250                 get_packet(remcom_in_buffer);
1251
1252                 switch (remcom_in_buffer[0]) {
1253                 case '?': /* gdbserial status */
1254                         gdb_cmd_status(ks);
1255                         break;
1256                 case 'g': /* return the value of the CPU registers */
1257                         gdb_cmd_getregs(ks);
1258                         break;
1259                 case 'G': /* set the value of the CPU registers - return OK */
1260                         gdb_cmd_setregs(ks);
1261                         break;
1262                 case 'm': /* mAA..AA,LLLL  Read LLLL bytes at address AA..AA */
1263                         gdb_cmd_memread(ks);
1264                         break;
1265                 case 'M': /* MAA..AA,LLLL: Write LLLL bytes at address AA..AA */
1266                         gdb_cmd_memwrite(ks);
1267                         break;
1268                 case 'X': /* XAA..AA,LLLL: Write LLLL bytes at address AA..AA */
1269                         gdb_cmd_binwrite(ks);
1270                         break;
1271                         /* kill or detach. KGDB should treat this like a
1272                          * continue.
1273                          */
1274                 case 'D': /* Debugger detach */
1275                 case 'k': /* Debugger detach via kill */
1276                         gdb_cmd_detachkill(ks);
1277                         goto default_handle;
1278                 case 'R': /* Reboot */
1279                         if (gdb_cmd_reboot(ks))
1280                                 goto default_handle;
1281                         break;
1282                 case 'q': /* query command */
1283                         gdb_cmd_query(ks);
1284                         break;
1285                 case 'H': /* task related */
1286                         gdb_cmd_task(ks);
1287                         break;
1288                 case 'T': /* Query thread status */
1289                         gdb_cmd_thread(ks);
1290                         break;
1291                 case 'z': /* Break point remove */
1292                 case 'Z': /* Break point set */
1293                         gdb_cmd_break(ks);
1294                         break;
1295                 case 'C': /* Exception passing */
1296                         tmp = gdb_cmd_exception_pass(ks);
1297                         if (tmp > 0)
1298                                 goto default_handle;
1299                         if (tmp == 0)
1300                                 break;
1301                         /* Fall through on tmp < 0 */
1302                 case 'c': /* Continue packet */
1303                 case 's': /* Single step packet */
1304                         if (kgdb_contthread && kgdb_contthread != current) {
1305                                 /* Can't switch threads in kgdb */
1306                                 error_packet(remcom_out_buffer, -EINVAL);
1307                                 break;
1308                         }
1309                         kgdb_activate_sw_breakpoints();
1310                         /* Fall through to default processing */
1311                 default:
1312 default_handle:
1313                         error = kgdb_arch_handle_exception(ks->ex_vector,
1314                                                 ks->signo,
1315                                                 ks->err_code,
1316                                                 remcom_in_buffer,
1317                                                 remcom_out_buffer,
1318                                                 ks->linux_regs);
1319                         /*
1320                          * Leave cmd processing on error, detach,
1321                          * kill, continue, or single step.
1322                          */
1323                         if (error >= 0 || remcom_in_buffer[0] == 'D' ||
1324                             remcom_in_buffer[0] == 'k') {
1325                                 error = 0;
1326                                 goto kgdb_exit;
1327                         }
1328
1329                 }
1330
1331                 /* reply to the request */
1332                 put_packet(remcom_out_buffer);
1333         }
1334
1335 kgdb_exit:
1336         if (ks->pass_exception)
1337                 error = 1;
1338         return error;
1339 }
1340
1341 static int kgdb_reenter_check(struct kgdb_state *ks)
1342 {
1343         unsigned long addr;
1344
1345         if (atomic_read(&kgdb_active) != raw_smp_processor_id())
1346                 return 0;
1347
1348         /* Panic on recursive debugger calls: */
1349         exception_level++;
1350         addr = kgdb_arch_pc(ks->ex_vector, ks->linux_regs);
1351         kgdb_deactivate_sw_breakpoints();
1352
1353         /*
1354          * If the break point removed ok at the place exception
1355          * occurred, try to recover and print a warning to the end
1356          * user because the user planted a breakpoint in a place that
1357          * KGDB needs in order to function.
1358          */
1359         if (kgdb_remove_sw_break(addr) == 0) {
1360                 exception_level = 0;
1361                 kgdb_skipexception(ks->ex_vector, ks->linux_regs);
1362                 kgdb_activate_sw_breakpoints();
1363                 printk(KERN_CRIT "KGDB: re-enter error: breakpoint removed %lx\n",
1364                         addr);
1365                 WARN_ON_ONCE(1);
1366
1367                 return 1;
1368         }
1369         remove_all_break();
1370         kgdb_skipexception(ks->ex_vector, ks->linux_regs);
1371
1372         if (exception_level > 1) {
1373                 dump_stack();
1374                 panic("Recursive entry to debugger");
1375         }
1376
1377         printk(KERN_CRIT "KGDB: re-enter exception: ALL breakpoints killed\n");
1378         dump_stack();
1379         panic("Recursive entry to debugger");
1380
1381         return 1;
1382 }
1383
1384 /*
1385  * kgdb_handle_exception() - main entry point from a kernel exception
1386  *
1387  * Locking hierarchy:
1388  *      interface locks, if any (begin_session)
1389  *      kgdb lock (kgdb_active)
1390  */
1391 int
1392 kgdb_handle_exception(int evector, int signo, int ecode, struct pt_regs *regs)
1393 {
1394         struct kgdb_state kgdb_var;
1395         struct kgdb_state *ks = &kgdb_var;
1396         unsigned long flags;
1397         int error = 0;
1398         int i, cpu;
1399
1400         ks->cpu                 = raw_smp_processor_id();
1401         ks->ex_vector           = evector;
1402         ks->signo               = signo;
1403         ks->ex_vector           = evector;
1404         ks->err_code            = ecode;
1405         ks->kgdb_usethreadid    = 0;
1406         ks->linux_regs          = regs;
1407
1408         if (kgdb_reenter_check(ks))
1409                 return 0; /* Ouch, double exception ! */
1410
1411 acquirelock:
1412         /*
1413          * Interrupts will be restored by the 'trap return' code, except when
1414          * single stepping.
1415          */
1416         local_irq_save(flags);
1417
1418         cpu = raw_smp_processor_id();
1419
1420         /*
1421          * Acquire the kgdb_active lock:
1422          */
1423         while (atomic_cmpxchg(&kgdb_active, -1, cpu) != -1)
1424                 cpu_relax();
1425
1426         /*
1427          * Do not start the debugger connection on this CPU if the last
1428          * instance of the exception handler wanted to come into the
1429          * debugger on a different CPU via a single step
1430          */
1431         if (atomic_read(&kgdb_cpu_doing_single_step) != -1 &&
1432             atomic_read(&kgdb_cpu_doing_single_step) != cpu) {
1433
1434                 atomic_set(&kgdb_active, -1);
1435                 clocksource_touch_watchdog();
1436                 local_irq_restore(flags);
1437
1438                 goto acquirelock;
1439         }
1440
1441         if (!kgdb_io_ready(1)) {
1442                 error = 1;
1443                 goto kgdb_restore; /* No I/O connection, so resume the system */
1444         }
1445
1446         /*
1447          * Don't enter if we have hit a removed breakpoint.
1448          */
1449         if (kgdb_skipexception(ks->ex_vector, ks->linux_regs))
1450                 goto kgdb_restore;
1451
1452         /* Call the I/O driver's pre_exception routine */
1453         if (kgdb_io_ops->pre_exception)
1454                 kgdb_io_ops->pre_exception();
1455
1456         kgdb_info[ks->cpu].debuggerinfo = ks->linux_regs;
1457         kgdb_info[ks->cpu].task = current;
1458
1459         kgdb_disable_hw_debug(ks->linux_regs);
1460
1461         /*
1462          * Get the passive CPU lock which will hold all the non-primary
1463          * CPU in a spin state while the debugger is active
1464          */
1465         if (!kgdb_single_step || !kgdb_contthread) {
1466                 for (i = 0; i < NR_CPUS; i++)
1467                         atomic_set(&passive_cpu_wait[i], 1);
1468         }
1469
1470         /*
1471          * spin_lock code is good enough as a barrier so we don't
1472          * need one here:
1473          */
1474         atomic_set(&cpu_in_kgdb[ks->cpu], 1);
1475
1476 #ifdef CONFIG_SMP
1477         /* Signal the other CPUs to enter kgdb_wait() */
1478         if ((!kgdb_single_step || !kgdb_contthread) && kgdb_do_roundup)
1479                 kgdb_roundup_cpus(flags);
1480 #endif
1481
1482         /*
1483          * Wait for the other CPUs to be notified and be waiting for us:
1484          */
1485         for_each_online_cpu(i) {
1486                 while (!atomic_read(&cpu_in_kgdb[i]))
1487                         cpu_relax();
1488         }
1489
1490         /*
1491          * At this point the primary processor is completely
1492          * in the debugger and all secondary CPUs are quiescent
1493          */
1494         kgdb_post_primary_code(ks->linux_regs, ks->ex_vector, ks->err_code);
1495         kgdb_deactivate_sw_breakpoints();
1496         kgdb_single_step = 0;
1497         kgdb_contthread = NULL;
1498         exception_level = 0;
1499
1500         /* Talk to debugger with gdbserial protocol */
1501         error = gdb_serial_stub(ks);
1502
1503         /* Call the I/O driver's post_exception routine */
1504         if (kgdb_io_ops->post_exception)
1505                 kgdb_io_ops->post_exception();
1506
1507         kgdb_info[ks->cpu].debuggerinfo = NULL;
1508         kgdb_info[ks->cpu].task = NULL;
1509         atomic_set(&cpu_in_kgdb[ks->cpu], 0);
1510
1511         if (!kgdb_single_step || !kgdb_contthread) {
1512                 for (i = NR_CPUS-1; i >= 0; i--)
1513                         atomic_set(&passive_cpu_wait[i], 0);
1514                 /*
1515                  * Wait till all the CPUs have quit
1516                  * from the debugger.
1517                  */
1518                 for_each_online_cpu(i) {
1519                         while (atomic_read(&cpu_in_kgdb[i]))
1520                                 cpu_relax();
1521                 }
1522         }
1523
1524 kgdb_restore:
1525         /* Free kgdb_active */
1526         atomic_set(&kgdb_active, -1);
1527         clocksource_touch_watchdog();
1528         local_irq_restore(flags);
1529
1530         return error;
1531 }
1532
1533 int kgdb_nmicallback(int cpu, void *regs)
1534 {
1535 #ifdef CONFIG_SMP
1536         if (!atomic_read(&cpu_in_kgdb[cpu]) &&
1537                         atomic_read(&kgdb_active) != cpu &&
1538                         atomic_read(&cpu_in_kgdb[atomic_read(&kgdb_active)])) {
1539                 kgdb_wait((struct pt_regs *)regs);
1540                 return 0;
1541         }
1542 #endif
1543         return 1;
1544 }
1545
1546 static void kgdb_console_write(struct console *co, const char *s,
1547    unsigned count)
1548 {
1549         unsigned long flags;
1550
1551         /* If we're debugging, or KGDB has not connected, don't try
1552          * and print. */
1553         if (!kgdb_connected || atomic_read(&kgdb_active) != -1)
1554                 return;
1555
1556         local_irq_save(flags);
1557         kgdb_msg_write(s, count);
1558         local_irq_restore(flags);
1559 }
1560
1561 static struct console kgdbcons = {
1562         .name           = "kgdb",
1563         .write          = kgdb_console_write,
1564         .flags          = CON_PRINTBUFFER | CON_ENABLED,
1565         .index          = -1,
1566 };
1567
1568 #ifdef CONFIG_MAGIC_SYSRQ
1569 static void sysrq_handle_gdb(int key, struct tty_struct *tty)
1570 {
1571         if (!kgdb_io_ops) {
1572                 printk(KERN_CRIT "ERROR: No KGDB I/O module available\n");
1573                 return;
1574         }
1575         if (!kgdb_connected)
1576                 printk(KERN_CRIT "Entering KGDB\n");
1577
1578         kgdb_breakpoint();
1579 }
1580
1581 static struct sysrq_key_op sysrq_gdb_op = {
1582         .handler        = sysrq_handle_gdb,
1583         .help_msg       = "Gdb",
1584         .action_msg     = "GDB",
1585 };
1586 #endif
1587
1588 static void kgdb_register_callbacks(void)
1589 {
1590         if (!kgdb_io_module_registered) {
1591                 kgdb_io_module_registered = 1;
1592                 kgdb_arch_init();
1593 #ifdef CONFIG_MAGIC_SYSRQ
1594                 register_sysrq_key('g', &sysrq_gdb_op);
1595 #endif
1596                 if (kgdb_use_con && !kgdb_con_registered) {
1597                         register_console(&kgdbcons);
1598                         kgdb_con_registered = 1;
1599                 }
1600         }
1601 }
1602
1603 static void kgdb_unregister_callbacks(void)
1604 {
1605         /*
1606          * When this routine is called KGDB should unregister from the
1607          * panic handler and clean up, making sure it is not handling any
1608          * break exceptions at the time.
1609          */
1610         if (kgdb_io_module_registered) {
1611                 kgdb_io_module_registered = 0;
1612                 kgdb_arch_exit();
1613 #ifdef CONFIG_MAGIC_SYSRQ
1614                 unregister_sysrq_key('g', &sysrq_gdb_op);
1615 #endif
1616                 if (kgdb_con_registered) {
1617                         unregister_console(&kgdbcons);
1618                         kgdb_con_registered = 0;
1619                 }
1620         }
1621 }
1622
1623 static void kgdb_initial_breakpoint(void)
1624 {
1625         kgdb_break_asap = 0;
1626
1627         printk(KERN_CRIT "kgdb: Waiting for connection from remote gdb...\n");
1628         kgdb_breakpoint();
1629 }
1630
1631 /**
1632  *      kgdb_register_io_module - register KGDB IO module
1633  *      @new_kgdb_io_ops: the io ops vector
1634  *
1635  *      Register it with the KGDB core.
1636  */
1637 int kgdb_register_io_module(struct kgdb_io *new_kgdb_io_ops)
1638 {
1639         int err;
1640
1641         spin_lock(&kgdb_registration_lock);
1642
1643         if (kgdb_io_ops) {
1644                 spin_unlock(&kgdb_registration_lock);
1645
1646                 printk(KERN_ERR "kgdb: Another I/O driver is already "
1647                                 "registered with KGDB.\n");
1648                 return -EBUSY;
1649         }
1650
1651         if (new_kgdb_io_ops->init) {
1652                 err = new_kgdb_io_ops->init();
1653                 if (err) {
1654                         spin_unlock(&kgdb_registration_lock);
1655                         return err;
1656                 }
1657         }
1658
1659         kgdb_io_ops = new_kgdb_io_ops;
1660
1661         spin_unlock(&kgdb_registration_lock);
1662
1663         printk(KERN_INFO "kgdb: Registered I/O driver %s.\n",
1664                new_kgdb_io_ops->name);
1665
1666         /* Arm KGDB now. */
1667         kgdb_register_callbacks();
1668
1669         if (kgdb_break_asap)
1670                 kgdb_initial_breakpoint();
1671
1672         return 0;
1673 }
1674 EXPORT_SYMBOL_GPL(kgdb_register_io_module);
1675
1676 /**
1677  *      kkgdb_unregister_io_module - unregister KGDB IO module
1678  *      @old_kgdb_io_ops: the io ops vector
1679  *
1680  *      Unregister it with the KGDB core.
1681  */
1682 void kgdb_unregister_io_module(struct kgdb_io *old_kgdb_io_ops)
1683 {
1684         BUG_ON(kgdb_connected);
1685
1686         /*
1687          * KGDB is no longer able to communicate out, so
1688          * unregister our callbacks and reset state.
1689          */
1690         kgdb_unregister_callbacks();
1691
1692         spin_lock(&kgdb_registration_lock);
1693
1694         WARN_ON_ONCE(kgdb_io_ops != old_kgdb_io_ops);
1695         kgdb_io_ops = NULL;
1696
1697         spin_unlock(&kgdb_registration_lock);
1698
1699         printk(KERN_INFO
1700                 "kgdb: Unregistered I/O driver %s, debugger disabled.\n",
1701                 old_kgdb_io_ops->name);
1702 }
1703 EXPORT_SYMBOL_GPL(kgdb_unregister_io_module);
1704
1705 /**
1706  * kgdb_breakpoint - generate breakpoint exception
1707  *
1708  * This function will generate a breakpoint exception.  It is used at the
1709  * beginning of a program to sync up with a debugger and can be used
1710  * otherwise as a quick means to stop program execution and "break" into
1711  * the debugger.
1712  */
1713 void kgdb_breakpoint(void)
1714 {
1715         atomic_set(&kgdb_setting_breakpoint, 1);
1716         wmb(); /* Sync point before breakpoint */
1717         arch_kgdb_breakpoint();
1718         wmb(); /* Sync point after breakpoint */
1719         atomic_set(&kgdb_setting_breakpoint, 0);
1720 }
1721 EXPORT_SYMBOL_GPL(kgdb_breakpoint);
1722
1723 static int __init opt_kgdb_wait(char *str)
1724 {
1725         kgdb_break_asap = 1;
1726
1727         if (kgdb_io_module_registered)
1728                 kgdb_initial_breakpoint();
1729
1730         return 0;
1731 }
1732
1733 early_param("kgdbwait", opt_kgdb_wait);