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