summaryrefslogtreecommitdiff
path: root/core/cortex-m/panic.c
blob: 5b0bff89e727d2f4fd3bb4569ffd67edbc5ac7b8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include <stdarg.h>

#include "config.h"
#include "console.h"
#include "cpu.h"
#include "host_command.h"
#include "panic.h"
#include "system.h"
#include "task.h"
#include "timer.h"
#include "uart.h"
#include "util.h"
#include "watchdog.h"

/* Whether bus fault is ignored */
static int bus_fault_ignored;

/*
 * Panic data goes at the end of RAM.  This is safe because we don't context
 * switch away from the panic handler before rebooting, and stacks and data
 * start at the beginning of RAM.
 */
static struct panic_data * const pdata_ptr =
	(struct panic_data *)(CONFIG_RAM_BASE + CONFIG_RAM_SIZE
			     - sizeof(struct panic_data));

/* Preceded by stack, rounded down to nearest 64-bit-aligned boundary */
static const uint32_t pstack_addr = (CONFIG_RAM_BASE + CONFIG_RAM_SIZE
				     - sizeof(struct panic_data)) & ~7;

void panic_putc(int ch)
{
	uart_emergency_flush();
	if (ch == '\n')
		panic_putc('\r');
	uart_write_char(ch);
	uart_tx_flush();
}

void panic_puts(const char *s)
{
	while (*s)
		panic_putc(*s++);
}

void panic_vprintf(const char *format, va_list args)
{
	int pad_width;

	while (*format) {
		int c = *format++;

		/* Copy normal characters */
		if (c != '%') {
			panic_putc(c);
			continue;
		}

		/* Get first format character */
		c = *format++;

		/* Handle %c */
		if (c == 'c') {
			c = va_arg(args, int);
			panic_putc(c);
			continue;
		}

		/* Count padding length (only supported for hex) */
		pad_width = 0;
		while (c >= '0' && c <= '9') {
			pad_width = (10 * pad_width) + c - '0';
			c = *format++;
		}

		if (c == 's') {
			char *vstr;

			vstr = va_arg(args, char *);
			panic_puts(vstr ? vstr : "(null)");
		} else { /* assume 'x' */
			uint32_t v, shift;
			int i;

			v = va_arg(args, uint32_t);
			if (!pad_width)
				pad_width = 8;
			shift = pad_width * 4 - 4;
			for (i = 0; i < pad_width; i++) {
				int ch = '0' + ((v >> shift) & 0xf);

				if (ch > '9')
					ch += 'a' - '9' - 1;
				panic_putc(ch);
				shift -= 4;
			}
		}
	}
}

void panic_printf(const char *format, ...)
{
	va_list args;

	va_start(args, format);
	panic_vprintf(format, args);
	va_end(args);
}

/**
 * Print the name and value of a register
 *
 * This is a convenient helper function for displaying a register value.
 * It shows the register name in a 3 character field, followed by a colon.
 * The register value is regs[index], and this is shown in hex. If regs is
 * NULL, then we display spaces instead.
 *
 * After displaying the value, either a space or \n is displayed depending
 * on the register number, so that (assuming the caller passes all 16
 * registers in sequence) we put 4 values per line like this
 *
 * r0 :0000000b r1 :00000047 r2 :60000000 r3 :200012b5
 * r4 :00000000 r5 :08004e64 r6 :08004e1c r7 :200012a8
 * r8 :08004e64 r9 :00000002 r10:00000000 r11:00000000
 * r12:0000003f sp :200009a0 lr :0800270d pc :0800351a
 *
 * @param regnum	Register number to display (0-15)
 * @param regs		Pointer to array holding the registers, or NULL
 * @param index		Index into array where the register value is present
 */
static void print_reg(int regnum, const uint32_t *regs, int index)
{
	static const char regname[] = "r10r11r12sp lr pc ";
	static char rname[3] = "r  ";
	const char *name;

	rname[1] = '0' + regnum;
	name = regnum < 10 ? rname : &regname[(regnum - 10) * 3];
	panic_printf("%c%c%c:", name[0], name[1], name[2]);
	if (regs)
		panic_printf("%8x", regs[index]);
	else
		panic_puts("        ");
	panic_putc((regnum & 3) == 3 ? '\n' : ' ');
}

#ifdef CONFIG_PANIC_HELP
/* Names for each of the bits in the mmfs register, starting at bit 0 */
static const char * const mmfs_name[32] = {
	"Instruction access violation",
	"Data access violation",
	NULL,
	"Unstack from exception violation",
	"Stack from exception violation",
	NULL,
	NULL,
	NULL,

	"Instruction bus error",
	"Precise data bus error",
	"Imprecise data bus error",
	"Unstack from exception bus fault",
	"Stack from exception bus fault",
	NULL,
	NULL,
	NULL,

	"Undefined instructions",
	"Invalid state",
	"Invalid PC",
	"No coprocessor",
	NULL,
	NULL,
	NULL,
	NULL,

	"Unaligned",
	"Divide by 0",
	NULL,
	NULL,

	NULL,
	NULL,
	NULL,
	NULL,
};

/* Names for the first 5 bits in the DFSR */
static const char * const dfsr_name[] = {
	"Halt request",
	"Breakpoint",
	"Data watchpoint/trace",
	"Vector catch",
	"External debug request",
};

/**
 * Helper function to display a separator after the previous item
 *
 * If items have been displayed already, we display a comma separator.
 * In any case, the count of items displayed is incremeneted.
 *
 * @param count		Number of items displayed so far (0 for none)
 */
static void do_separate(int *count)
{
	if (*count)
		panic_puts(", ");
	(*count)++;
}

/**
 * Show a textual representaton of the fault registers
 *
 * A list of detected faults is shown, with no trailing newline.
 *
 * @param mmfs		Value of Memory Manage Fault Status
 * @param hfsr		Value of Hard Fault Status
 * @param dfsr		Value of Debug Fault Status
 */
static void show_fault(uint32_t mmfs, uint32_t hfsr, uint32_t dfsr)
{
	unsigned int upto;
	int count = 0;

	for (upto = 0; upto < 32; upto++) {
		if ((mmfs & (1 << upto)) && mmfs_name[upto]) {
			do_separate(&count);
			panic_puts(mmfs_name[upto]);
		}
	}

	if (hfsr & CPU_NVIC_HFSR_DEBUGEVT) {
		do_separate(&count);
		panic_puts("Debug event");
	}
	if (hfsr & CPU_NVIC_HFSR_FORCED) {
		do_separate(&count);
		panic_puts("Forced hard fault");
	}
	if (hfsr & CPU_NVIC_HFSR_VECTTBL) {
		do_separate(&count);
		panic_puts("Vector table bus fault");
	}

	for (upto = 0; upto < 5; upto++) {
		if ((dfsr & (1 << upto))) {
			do_separate(&count);
			panic_puts(dfsr_name[upto]);
		}
	}
}

/**
 * Show extra information that might be useful to understand a panic()
 *
 * We show fault register information, including the fault address registers
 * if valid.
 */
static void panic_show_extra(const struct panic_data *pdata)
{
	show_fault(pdata->mmfs, pdata->hfsr, pdata->dfsr);
	if (pdata->mmfs & CPU_NVIC_MMFS_BFARVALID)
		panic_printf(", bfar = %x", pdata->bfar);
	if (pdata->mmfs & CPU_NVIC_MMFS_MFARVALID)
		panic_printf(", mfar = %x", pdata->mfar);
	panic_putc('\n');
	panic_printf("mmfs = %x, ", pdata->mmfs);
	panic_printf("shcsr = %x, ", pdata->shcsr);
	panic_printf("hfsr = %x, ", pdata->hfsr);
	panic_printf("dfsr = %x\n", pdata->dfsr);
}
#endif /* CONFIG_PANIC_HELP */


/**
 * Display a message and reboot
 */
static void panic_reboot(void)
{
	panic_puts("\n\nRebooting...\n");
	system_reset(0);
}

/**
 * Print panic data
 */
static void panic_print(const struct panic_data *pdata)
{
	const uint32_t *lregs = pdata->regs;
	const uint32_t *sregs = NULL;
	int i;

	if (pdata->flags & PANIC_DATA_FLAG_FRAME_VALID)
		sregs = pdata->frame;

	panic_printf("\n=== EXCEPTION: %2x ====== xPSR: %8x ===========\n",
		     lregs[1] & 7, sregs ? sregs[7] : -1);
	for (i = 0; i < 4; i++)
		print_reg(i, sregs, i);
	for (i = 4; i < 10; i++)
		print_reg(i, lregs, i - 1);
	print_reg(10, lregs, 9);
	print_reg(11, lregs, 10);
	print_reg(12, sregs, 4);
	print_reg(13, lregs, 0);
	print_reg(14, sregs, 5);
	print_reg(15, sregs, 6);

#ifdef CONFIG_PANIC_HELP
	panic_show_extra(pdata);
#endif
}

void report_panic(void)
{
	struct panic_data *pdata = pdata_ptr;
	const uint32_t psp = pdata->regs[0];

	pdata->magic = PANIC_DATA_MAGIC;
	pdata->struct_size = sizeof(*pdata);
	pdata->struct_version = 1;
	pdata->arch = PANIC_ARCH_CORTEX_M;
	pdata->flags = 0;
	pdata->reserved = 0;

	/* If stack is valid, save exception frame */
	if (psp >= CONFIG_RAM_BASE &&
	    psp <= CONFIG_RAM_BASE + CONFIG_RAM_SIZE + 8 * sizeof(uint32_t)) {
		const uint32_t *sregs = (const uint32_t *)psp;
		int i;

		for (i = 0; i < 8; i++)
			pdata->frame[i] = sregs[i];
		pdata->flags |= PANIC_DATA_FLAG_FRAME_VALID;
	}

	/* Save extra information */
	pdata->mmfs = CPU_NVIC_MMFS;
	pdata->bfar = CPU_NVIC_BFAR;
	pdata->mfar = CPU_NVIC_MFAR;
	pdata->shcsr = CPU_NVIC_SHCSR;
	pdata->hfsr = CPU_NVIC_HFSR;
	pdata->dfsr = CPU_NVIC_DFSR;

	panic_print(pdata);
	panic_reboot();
}

/* Default exception handler, which reports a panic */
void exception_panic(void) __attribute__((naked));
void exception_panic(void)
{
	/* Naked call so we can extract raw LR and IPSR */

	/*
	 * Set a new stack pointer at the end of RAM, before the saved
	 * exception data.
	 */
	asm volatile(
		/*
		 * This instruction will generate ldr rx, [pc, #offset]
		 * followed by a mov sp, rx.  See below for more explanation.
		 *
		 * Oddly, gcc is able to add 4 to the value loaded here to
		 * compute [pregs] below if the asm blocks are separate, but if
		 * they are merged it uses two temporary registers and two
		 * immediate values.
		 */
		"mov sp, %[pstack]\n" : :
			[pstack] "r" (pstack_addr)
		);

	/* Save registers and branch directly to panic handler */
	asm volatile(
		/*
		 * This instruction will generate ldr rx, [pc, #offset]
		 * followed by a mov r0, rx. It would clearly be better if
		 * we could get ldr r0, [pc, #offset] but that doesn't seem
		 * to be supported. Nor does gcc seem to define which
		 * temporary register it uses. Therefore we put this
		 * instruction first so that it matters less.
		 *
		 * If you see a failure in the panic handler, please check
		 * the final assembler output here.
		 */
		"mov r0, %[pregs]\n"
		"mrs r1, psp\n"
		"mrs r2, ipsr\n"
		"mov r3, lr\n"
		"stmia r0, {r1-r11}\n"
		"b report_panic" : :
			[pregs] "r" (pdata_ptr->regs)
		);
}

void bus_fault_handler(void) __attribute__((naked));
void bus_fault_handler(void)
{
	if (!bus_fault_ignored)
		exception_panic();
}

void ignore_bus_fault(int ignored)
{
	bus_fault_ignored = ignored;
}

#ifdef CONFIG_ASSERT_HELP
void panic_assert_fail(const char *msg, const char *func, const char *fname,
		       int linenum)
{
	panic_printf("\nASSERTION FAILURE '%s' in %s() at %s:%d\n", msg, func,
		     fname, linenum);

	panic_reboot();
}
#endif

void panic(const char *msg)
{
	panic_printf("\n** PANIC: %s\n", msg);
	panic_reboot();
}

struct panic_data *panic_get_data(void)
{
	return pdata_ptr->magic == PANIC_DATA_MAGIC ? pdata_ptr : NULL;
}

/*****************************************************************************/
/* Console commands */

static int command_crash(int argc, char **argv)
{
	if (argc < 2)
		return EC_ERROR_PARAM1;

	if (!strcasecmp(argv[1], "divzero")) {
		int a = 1, b = 0;

		cflush();
		ccprintf("%08x", a / b);
	} else if (!strcasecmp(argv[1], "unaligned")) {
		cflush();
		ccprintf("%08x", *(int *)0xcdef);
	} else {
		return EC_ERROR_PARAM1;
	}

	/* Everything crashes, so shouldn't get back here */
	return EC_ERROR_UNKNOWN;
}
DECLARE_CONSOLE_COMMAND(crash, command_crash,
			"[divzero | unaligned]",
			"Crash the system (for testing)",
			NULL);

static int command_panicinfo(int argc, char **argv)
{
	if (pdata_ptr->magic == PANIC_DATA_MAGIC) {
		ccprintf("Saved panic data:%s\n",
			 (pdata_ptr->flags & PANIC_DATA_FLAG_OLD_CONSOLE ?
			  "" : " (NEW)"));

		panic_print(pdata_ptr);

		/* Data has now been printed */
		pdata_ptr->flags |= PANIC_DATA_FLAG_OLD_CONSOLE;
	} else {
		ccprintf("No saved panic data available.\n");
	}
	return EC_SUCCESS;
}
DECLARE_CONSOLE_COMMAND(panicinfo, command_panicinfo,
			NULL,
			"Print info from a previous panic",
			NULL);

/*****************************************************************************/
/* Host commands */

int host_command_panic_info(struct host_cmd_handler_args *args)
{
	if (pdata_ptr->magic == PANIC_DATA_MAGIC) {
		ASSERT(pdata_ptr->struct_size <= args->response_max);
		memcpy(args->response, pdata_ptr, pdata_ptr->struct_size);
		args->response_size = pdata_ptr->struct_size;

		/* Data has now been returned */
		pdata_ptr->flags |= PANIC_DATA_FLAG_OLD_HOSTCMD;
	}

	return EC_RES_SUCCESS;
}
DECLARE_HOST_COMMAND(EC_CMD_GET_PANIC_INFO,
		     host_command_panic_info,
		     EC_VER_MASK(0));