1 /* SPDX-License-Identifier: GPL-2.0-only */
2
3 #include <inttypes.h>
4 #include <stdbool.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <unistd.h>
9 #include <getopt.h>
10 #include <dirent.h>
11 #include <errno.h>
12 #include <fcntl.h>
13 #include <ctype.h>
14 #include <arpa/inet.h>
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 #include <sys/mman.h>
18 #include <libgen.h>
19 #include <assert.h>
20 #include <regex.h>
21 #include <commonlib/bsd/cbmem_id.h>
22 #include <commonlib/bsd/ipchksum.h>
23 #include <commonlib/bsd/tpm_log_defs.h>
24 #include <commonlib/loglevel.h>
25 #include <commonlib/timestamp_serialized.h>
26 #include <commonlib/tpm_log_serialized.h>
27 #include <commonlib/coreboot_tables.h>
28
29 #ifdef __OpenBSD__
30 #include <sys/param.h>
31 #include <sys/sysctl.h>
32 #endif
33
34 #if defined(__i386__) || defined(__x86_64__)
35 #include <x86intrin.h>
36 #endif
37
38 typedef uint8_t u8;
39 typedef uint16_t u16;
40 typedef uint32_t u32;
41 typedef uint64_t u64;
42
43 /* Return < 0 on error, 0 on success. */
44 static int parse_cbtable(u64 address, size_t table_size);
45
46 struct mapping {
47 void *virt;
48 size_t offset;
49 size_t virt_size;
50 unsigned long long phys;
51 size_t size;
52 };
53
54 #define CBMEM_VERSION "1.1"
55
56 /* verbose output? */
57 static int verbose = 0;
58 #define debug(x...) if(verbose) printf(x)
59
60 /* File handle used to access /dev/mem */
61 static int mem_fd;
62 static struct mapping lbtable_mapping;
63
64 /* TSC frequency from the LB_TAG_TSC_INFO record. 0 if not present. */
65 static uint32_t tsc_freq_khz = 0;
66
die(const char * msg)67 static void die(const char *msg)
68 {
69 if (msg)
70 fputs(msg, stderr);
71 exit(1);
72 }
73
system_page_size(void)74 static unsigned long long system_page_size(void)
75 {
76 static unsigned long long page_size;
77
78 if (!page_size)
79 page_size = getpagesize();
80
81 return page_size;
82 }
83
size_to_mib(size_t sz)84 static inline size_t size_to_mib(size_t sz)
85 {
86 return sz >> 20;
87 }
88
89 /* Return mapping of physical address requested. */
mapping_virt(const struct mapping * mapping)90 static void *mapping_virt(const struct mapping *mapping)
91 {
92 char *v = mapping->virt;
93
94 if (v == NULL)
95 return NULL;
96
97 return v + mapping->offset;
98 }
99
100 /* Returns virtual address on success, NULL on error. mapping is filled in. */
map_memory_with_prot(struct mapping * mapping,unsigned long long phys,size_t sz,int prot)101 static void *map_memory_with_prot(struct mapping *mapping,
102 unsigned long long phys, size_t sz, int prot)
103 {
104 void *v;
105 unsigned long long page_size;
106
107 page_size = system_page_size();
108
109 mapping->virt = NULL;
110 mapping->offset = phys % page_size;
111 mapping->virt_size = sz + mapping->offset;
112 mapping->size = sz;
113 mapping->phys = phys;
114
115 if (size_to_mib(mapping->virt_size) == 0) {
116 debug("Mapping %zuB of physical memory at 0x%llx (requested 0x%llx).\n",
117 mapping->virt_size, phys - mapping->offset, phys);
118 } else {
119 debug("Mapping %zuMB of physical memory at 0x%llx (requested 0x%llx).\n",
120 size_to_mib(mapping->virt_size), phys - mapping->offset,
121 phys);
122 }
123
124 v = mmap(NULL, mapping->virt_size, prot, MAP_SHARED, mem_fd,
125 phys - mapping->offset);
126
127 if (v == MAP_FAILED) {
128 debug("Mapping failed %zuB of physical memory at 0x%llx.\n",
129 mapping->virt_size, phys - mapping->offset);
130 return NULL;
131 }
132
133 mapping->virt = v;
134
135 if (mapping->offset != 0)
136 debug(" ... padding virtual address with 0x%zx bytes.\n",
137 mapping->offset);
138
139 return mapping_virt(mapping);
140 }
141
142 /* Convenience helper for the common case of read-only mappings. */
map_memory(struct mapping * mapping,unsigned long long phys,size_t sz)143 static const void *map_memory(struct mapping *mapping, unsigned long long phys,
144 size_t sz)
145 {
146 return map_memory_with_prot(mapping, phys, sz, PROT_READ);
147 }
148
149
150 /* Returns 0 on success, < 0 on error. mapping is cleared if successful. */
unmap_memory(struct mapping * mapping)151 static int unmap_memory(struct mapping *mapping)
152 {
153 if (mapping->virt == NULL)
154 return -1;
155
156 munmap(mapping->virt, mapping->virt_size);
157 mapping->virt = NULL;
158 mapping->offset = 0;
159 mapping->virt_size = 0;
160
161 return 0;
162 }
163
164 /* Return size of physical address mapping requested. */
mapping_size(const struct mapping * mapping)165 static size_t mapping_size(const struct mapping *mapping)
166 {
167 if (mapping->virt == NULL)
168 return 0;
169
170 return mapping->size;
171 }
172
173 /*
174 * Some architectures map /dev/mem memory in a way that doesn't support
175 * unaligned accesses. Most normal libc memcpy()s aren't safe to use in this
176 * case, so build our own which makes sure to never do unaligned accesses on
177 * *src (*dest is fine since we never map /dev/mem for writing).
178 */
aligned_memcpy(void * dest,const void * src,size_t n)179 static void *aligned_memcpy(void *dest, const void *src, size_t n)
180 {
181 u8 *d = dest;
182 const volatile u8 *s = src; /* volatile to prevent optimization */
183
184 while ((uintptr_t)s & (sizeof(size_t) - 1)) {
185 if (n-- == 0)
186 return dest;
187 *d++ = *s++;
188 }
189
190 while (n >= sizeof(size_t)) {
191 *(size_t *)d = *(const volatile size_t *)s;
192 d += sizeof(size_t);
193 s += sizeof(size_t);
194 n -= sizeof(size_t);
195 }
196
197 while (n-- > 0)
198 *d++ = *s++;
199
200 return dest;
201 }
202
203 /* Find the first cbmem entry filling in the details. */
find_cbmem_entry(uint32_t id,uint64_t * addr,size_t * size)204 static int find_cbmem_entry(uint32_t id, uint64_t *addr, size_t *size)
205 {
206 const uint8_t *table;
207 size_t offset;
208 int ret = -1;
209
210 table = mapping_virt(&lbtable_mapping);
211
212 if (table == NULL)
213 return -1;
214
215 offset = 0;
216
217 while (offset < mapping_size(&lbtable_mapping)) {
218 const struct lb_record *lbr;
219 struct lb_cbmem_entry lbe;
220
221 lbr = (const void *)(table + offset);
222 offset += lbr->size;
223
224 if (lbr->tag != LB_TAG_CBMEM_ENTRY)
225 continue;
226
227 aligned_memcpy(&lbe, lbr, sizeof(lbe));
228 if (lbe.id != id)
229 continue;
230
231 *addr = lbe.address;
232 *size = lbe.entry_size;
233 ret = 0;
234 break;
235 }
236
237 return ret;
238 }
239
240 /*
241 * Try finding the timestamp table and coreboot cbmem console starting from the
242 * passed in memory offset. Could be called recursively in case a forwarding
243 * entry is found.
244 *
245 * Returns pointer to a memory buffer containing the timestamp table or zero if
246 * none found.
247 */
248
249 static struct lb_cbmem_ref timestamps;
250 static struct lb_cbmem_ref console;
251 static struct lb_cbmem_ref tpm_cb_log;
252 static struct lb_memory_range cbmem;
253
254 /* This is a work-around for a nasty problem introduced by initially having
255 * pointer sized entries in the lb_cbmem_ref structures. This caused problems
256 * on 64bit x86 systems because coreboot is 32bit on those systems.
257 * When the problem was found, it was corrected, but there are a lot of
258 * systems out there with a firmware that does not produce the right
259 * lb_cbmem_ref structure. Hence we try to autocorrect this issue here.
260 */
parse_cbmem_ref(const struct lb_cbmem_ref * cbmem_ref)261 static struct lb_cbmem_ref parse_cbmem_ref(const struct lb_cbmem_ref *cbmem_ref)
262 {
263 struct lb_cbmem_ref ret;
264
265 aligned_memcpy(&ret, cbmem_ref, sizeof(ret));
266
267 if (cbmem_ref->size < sizeof(*cbmem_ref))
268 ret.cbmem_addr = (uint32_t)ret.cbmem_addr;
269
270 debug(" cbmem_addr = %" PRIx64 "\n", ret.cbmem_addr);
271
272 return ret;
273 }
274
parse_memory_tags(const struct lb_memory * mem)275 static void parse_memory_tags(const struct lb_memory *mem)
276 {
277 int num_entries;
278 int i;
279
280 /* Peel off the header size and calculate the number of entries. */
281 num_entries = (mem->size - sizeof(*mem)) / sizeof(mem->map[0]);
282
283 for (i = 0; i < num_entries; i++) {
284 if (mem->map[i].type != LB_MEM_TABLE)
285 continue;
286 debug(" LB_MEM_TABLE found.\n");
287 /* The last one found is CBMEM */
288 aligned_memcpy(&cbmem, &mem->map[i], sizeof(cbmem));
289 }
290 }
291
292 /* Return < 0 on error, 0 on success, 1 if forwarding table entry found. */
parse_cbtable_entries(const struct mapping * table_mapping)293 static int parse_cbtable_entries(const struct mapping *table_mapping)
294 {
295 size_t i;
296 const struct lb_record *lbr_p;
297 size_t table_size = mapping_size(table_mapping);
298 const void *lbtable = mapping_virt(table_mapping);
299 int forwarding_table_found = 0;
300
301 for (i = 0; i < table_size; i += lbr_p->size) {
302 lbr_p = lbtable + i;
303 debug(" coreboot table entry 0x%02x\n", lbr_p->tag);
304 switch (lbr_p->tag) {
305 case LB_TAG_MEMORY:
306 debug(" Found memory map.\n");
307 parse_memory_tags(lbtable + i);
308 continue;
309 case LB_TAG_TIMESTAMPS: {
310 debug(" Found timestamp table.\n");
311 timestamps =
312 parse_cbmem_ref((struct lb_cbmem_ref *)lbr_p);
313 continue;
314 }
315 case LB_TAG_CBMEM_CONSOLE: {
316 debug(" Found cbmem console.\n");
317 console = parse_cbmem_ref((struct lb_cbmem_ref *)lbr_p);
318 continue;
319 }
320 case LB_TAG_TPM_CB_LOG: {
321 debug(" Found TPM CB log table.\n");
322 tpm_cb_log =
323 parse_cbmem_ref((struct lb_cbmem_ref *)lbr_p);
324 continue;
325 }
326 case LB_TAG_TSC_INFO:
327 debug(" Found TSC info.\n");
328 tsc_freq_khz = ((struct lb_tsc_info *)lbr_p)->freq_khz;
329 continue;
330 case LB_TAG_FORWARD: {
331 int ret;
332 /*
333 * This is a forwarding entry - repeat the
334 * search at the new address.
335 */
336 struct lb_forward lbf_p =
337 *(const struct lb_forward *)lbr_p;
338 debug(" Found forwarding entry.\n");
339 ret = parse_cbtable(lbf_p.forward, 0);
340
341 /* Assume the forwarding entry is valid. If this fails
342 * then there's a total failure. */
343 if (ret < 0)
344 return -1;
345 forwarding_table_found = 1;
346 }
347 default:
348 break;
349 }
350 }
351
352 return forwarding_table_found;
353 }
354
355 /* Return < 0 on error, 0 on success. */
parse_cbtable(u64 address,size_t table_size)356 static int parse_cbtable(u64 address, size_t table_size)
357 {
358 const void *buf;
359 struct mapping header_mapping;
360 size_t req_size;
361 size_t i;
362
363 req_size = table_size;
364 /* Default to 4 KiB search space. */
365 if (req_size == 0)
366 req_size = 4 * 1024;
367
368 debug("Looking for coreboot table at %" PRIx64 " %zd bytes.\n",
369 address, req_size);
370
371 buf = map_memory(&header_mapping, address, req_size);
372
373 if (!buf)
374 return -1;
375
376 /* look at every 16 bytes */
377 for (i = 0; i <= req_size - sizeof(struct lb_header); i += 16) {
378 int ret;
379 const struct lb_header *lbh;
380 struct mapping table_mapping;
381
382 lbh = buf + i;
383 if (memcmp(lbh->signature, "LBIO", sizeof(lbh->signature)) ||
384 !lbh->header_bytes ||
385 ipchksum(lbh, sizeof(*lbh))) {
386 continue;
387 }
388
389 /* Map in the whole table to parse. */
390 if (!map_memory(&table_mapping, address + i + lbh->header_bytes,
391 lbh->table_bytes)) {
392 debug("Couldn't map in table\n");
393 continue;
394 }
395
396 if (ipchksum(mapping_virt(&table_mapping), lbh->table_bytes) !=
397 lbh->table_checksum) {
398 debug("Signature found, but wrong checksum.\n");
399 unmap_memory(&table_mapping);
400 continue;
401 }
402
403 debug("Found!\n");
404
405 ret = parse_cbtable_entries(&table_mapping);
406
407 /* Table parsing failed. */
408 if (ret < 0) {
409 unmap_memory(&table_mapping);
410 continue;
411 }
412
413 /* Succeeded in parsing the table. Header not needed anymore. */
414 unmap_memory(&header_mapping);
415
416 /*
417 * Table parsing succeeded. If forwarding table not found update
418 * coreboot table mapping for future use.
419 */
420 if (ret == 0)
421 lbtable_mapping = table_mapping;
422 else
423 unmap_memory(&table_mapping);
424
425 return 0;
426 }
427
428 unmap_memory(&header_mapping);
429
430 return -1;
431 }
432
433 #if defined(linux) && (defined(__i386__) || defined(__x86_64__))
434 /*
435 * read CPU frequency from a sysfs file, return an frequency in Megahertz as
436 * an int or exit on any error.
437 */
arch_tick_frequency(void)438 static unsigned long arch_tick_frequency(void)
439 {
440 FILE *cpuf;
441 char freqs[100];
442 int size;
443 char *endp;
444 u64 rv;
445
446 const char* freq_file =
447 "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq";
448
449 cpuf = fopen(freq_file, "r");
450 if (!cpuf) {
451 fprintf(stderr, "Could not open %s: %s\n",
452 freq_file, strerror(errno));
453 exit(1);
454 }
455
456 memset(freqs, 0, sizeof(freqs));
457 size = fread(freqs, 1, sizeof(freqs), cpuf);
458 if (!size || (size == sizeof(freqs))) {
459 fprintf(stderr, "Wrong number of bytes(%d) read from %s\n",
460 size, freq_file);
461 exit(1);
462 }
463 fclose(cpuf);
464 rv = strtoull(freqs, &endp, 10);
465
466 if (*endp == '\0' || *endp == '\n')
467 /* cpuinfo_max_freq is in kHz. Convert it to MHz. */
468 return rv / 1000;
469 fprintf(stderr, "Wrong formatted value ^%s^ read from %s\n",
470 freqs, freq_file);
471 exit(1);
472 }
473 #elif defined(__OpenBSD__) && (defined(__i386__) || defined(__x86_64__))
arch_tick_frequency(void)474 static unsigned long arch_tick_frequency(void)
475 {
476 int mib[2] = { CTL_HW, HW_CPUSPEED };
477 static int value = 0;
478 size_t value_len = sizeof(value);
479
480 /* Return 1 MHz when sysctl fails. */
481 if ((value == 0) && (sysctl(mib, 2, &value, &value_len, NULL, 0) == -1))
482 return 1;
483
484 return value;
485 }
486 #else
arch_tick_frequency(void)487 static unsigned long arch_tick_frequency(void)
488 {
489 /* 1 MHz = 1us. */
490 return 1;
491 }
492 #endif
493
494 static unsigned long tick_freq_mhz;
495
timestamp_set_tick_freq(unsigned long table_tick_freq_mhz)496 static void timestamp_set_tick_freq(unsigned long table_tick_freq_mhz)
497 {
498 tick_freq_mhz = table_tick_freq_mhz;
499
500 /* Honor table frequency if present. */
501 if (!tick_freq_mhz)
502 tick_freq_mhz = arch_tick_frequency();
503
504 if (!tick_freq_mhz) {
505 fprintf(stderr, "Cannot determine timestamp tick frequency.\n");
506 exit(1);
507 }
508
509 debug("Timestamp tick frequency: %ld MHz\n", tick_freq_mhz);
510 }
511
arch_convert_raw_ts_entry(u64 ts)512 static u64 arch_convert_raw_ts_entry(u64 ts)
513 {
514 return ts / tick_freq_mhz;
515 }
516
517 /*
518 * Print an integer in 'normalized' form - with commas separating every three
519 * decimal orders.
520 */
print_norm(u64 v)521 static void print_norm(u64 v)
522 {
523 if (v >= 1000) {
524 /* print the higher order sections first */
525 print_norm(v / 1000);
526 printf(",%3.3u", (u32)(v % 1000));
527 } else {
528 printf("%u", (u32)(v % 1000));
529 }
530 }
531
timestamp_get(uint64_t table_tick_freq_mhz)532 static uint64_t timestamp_get(uint64_t table_tick_freq_mhz)
533 {
534 #if defined(__i386__) || defined(__x86_64__)
535 uint64_t tsc = __rdtsc();
536
537 /* No tick frequency specified means raw TSC values. */
538 if (!table_tick_freq_mhz)
539 return tsc;
540
541 if (tsc_freq_khz)
542 return tsc * table_tick_freq_mhz * 1000 / tsc_freq_khz;
543 #else
544 (void)table_tick_freq_mhz;
545 #endif
546 die("Don't know how to obtain timestamps on this platform.\n");
547 return 0;
548 }
549
timestamp_name(uint32_t id)550 static const char *timestamp_name(uint32_t id)
551 {
552 for (size_t i = 0; i < ARRAY_SIZE(timestamp_ids); i++) {
553 if (timestamp_ids[i].id == id)
554 return timestamp_ids[i].name;
555 }
556 return "<unknown>";
557 }
558
timestamp_enum_name_to_id(const char * name)559 static uint32_t timestamp_enum_name_to_id(const char *name)
560 {
561 for (size_t i = 0; i < ARRAY_SIZE(timestamp_ids); i++) {
562 if (!strcmp(timestamp_ids[i].enum_name, name))
563 return timestamp_ids[i].id;
564 }
565 return 0;
566 }
567
timestamp_print_parseable_entry(uint32_t id,uint64_t stamp,uint64_t prev_stamp)568 static uint64_t timestamp_print_parseable_entry(uint32_t id, uint64_t stamp,
569 uint64_t prev_stamp)
570 {
571 const char *name;
572 uint64_t step_time;
573
574 name = timestamp_name(id);
575
576 step_time = arch_convert_raw_ts_entry(stamp - prev_stamp);
577
578 /* ID<tab>absolute time<tab>relative time<tab>description */
579 printf("%d\t", id);
580 printf("%llu\t", (long long)arch_convert_raw_ts_entry(stamp));
581 printf("%llu\t", (long long)step_time);
582 printf("%s\n", name);
583
584 return step_time;
585 }
586
timestamp_print_entry(uint32_t id,uint64_t stamp,uint64_t prev_stamp)587 static uint64_t timestamp_print_entry(uint32_t id, uint64_t stamp, uint64_t prev_stamp)
588 {
589 const char *name;
590 uint64_t step_time;
591
592 name = timestamp_name(id);
593
594 printf("%4d:", id);
595 printf("%-50s", name);
596 print_norm(arch_convert_raw_ts_entry(stamp));
597 step_time = arch_convert_raw_ts_entry(stamp - prev_stamp);
598 if (prev_stamp) {
599 printf(" (");
600 print_norm(step_time);
601 printf(")");
602 }
603 printf("\n");
604
605 return step_time;
606 }
607
compare_timestamp_entries(const void * a,const void * b)608 static int compare_timestamp_entries(const void *a, const void *b)
609 {
610 const struct timestamp_entry *tse_a = (struct timestamp_entry *)a;
611 const struct timestamp_entry *tse_b = (struct timestamp_entry *)b;
612
613 if (tse_a->entry_stamp > tse_b->entry_stamp)
614 return 1;
615 else if (tse_a->entry_stamp < tse_b->entry_stamp)
616 return -1;
617
618 return 0;
619 }
620
find_matching_end(struct timestamp_table * sorted_tst_p,uint32_t start,uint32_t end)621 static int find_matching_end(struct timestamp_table *sorted_tst_p, uint32_t start, uint32_t end)
622 {
623 uint32_t id = sorted_tst_p->entries[start].entry_id;
624 uint32_t possible_match = 0;
625
626 for (uint32_t i = 0; i < ARRAY_SIZE(timestamp_ids); ++i) {
627 if (timestamp_ids[i].id == id) {
628 possible_match = timestamp_ids[i].id_end;
629 break;
630 }
631 }
632
633 /* No match found or timestamp not defined in IDs table */
634 if (!possible_match)
635 return -1;
636
637 for (uint32_t i = start + 1; i < end; i++)
638 if (sorted_tst_p->entries[i].entry_id == possible_match)
639 return i;
640
641 return -1;
642 }
643
get_timestamp_name(const uint32_t id)644 static const char *get_timestamp_name(const uint32_t id)
645 {
646 for (uint32_t i = 0; i < ARRAY_SIZE(timestamp_ids); i++)
647 if (timestamp_ids[i].id == id)
648 return timestamp_ids[i].enum_name;
649
650 return "UNKNOWN";
651 }
652
653 struct ts_range_stack {
654 const char *name;
655 const char *end_name;
656 uint32_t end;
657 };
658
print_with_path(struct ts_range_stack * range_stack,const int stacklvl,const uint64_t stamp,const char * last_part)659 static void print_with_path(struct ts_range_stack *range_stack, const int stacklvl,
660 const uint64_t stamp, const char *last_part)
661 {
662 for (int i = 1; i <= stacklvl; ++i) {
663 printf("%s -> %s", range_stack[i].name, range_stack[i].end_name);
664 if (i < stacklvl || last_part)
665 putchar(';');
666 }
667 if (last_part)
668 printf("%s", last_part);
669 printf(" %llu\n", (long long)arch_convert_raw_ts_entry(stamp));
670 }
671
672 enum timestamps_print_type {
673 TIMESTAMPS_PRINT_NONE,
674 TIMESTAMPS_PRINT_NORMAL,
675 TIMESTAMPS_PRINT_MACHINE_READABLE,
676 TIMESTAMPS_PRINT_STACKED,
677 };
678
679 /* dump the timestamp table */
dump_timestamps(enum timestamps_print_type output_type)680 static void dump_timestamps(enum timestamps_print_type output_type)
681 {
682 const struct timestamp_table *tst_p;
683 struct timestamp_table *sorted_tst_p;
684 size_t size;
685 uint64_t prev_stamp = 0;
686 uint64_t total_time = 0;
687 struct mapping timestamp_mapping;
688
689 if (timestamps.tag != LB_TAG_TIMESTAMPS) {
690 fprintf(stderr, "No timestamps found in coreboot table.\n");
691 return;
692 }
693
694 size = sizeof(*tst_p);
695 tst_p = map_memory(×tamp_mapping, timestamps.cbmem_addr, size);
696 if (!tst_p)
697 die("Unable to map timestamp header\n");
698
699 timestamp_set_tick_freq(tst_p->tick_freq_mhz);
700
701 if (output_type == TIMESTAMPS_PRINT_NORMAL)
702 printf("%d entries total:\n\n", tst_p->num_entries);
703 size += tst_p->num_entries * sizeof(tst_p->entries[0]);
704
705 unmap_memory(×tamp_mapping);
706
707 tst_p = map_memory(×tamp_mapping, timestamps.cbmem_addr, size);
708 if (!tst_p)
709 die("Unable to map full timestamp table\n");
710
711 sorted_tst_p = malloc(size + sizeof(struct timestamp_entry));
712 if (!sorted_tst_p)
713 die("Failed to allocate memory");
714 aligned_memcpy(sorted_tst_p, tst_p, size);
715
716 /*
717 * Insert a timestamp to represent the base time (start of coreboot),
718 * in case we have to rebase for negative timestamps below.
719 */
720 sorted_tst_p->entries[tst_p->num_entries].entry_id = 0;
721 sorted_tst_p->entries[tst_p->num_entries].entry_stamp = 0;
722 sorted_tst_p->num_entries += 1;
723
724 qsort(&sorted_tst_p->entries[0], sorted_tst_p->num_entries,
725 sizeof(struct timestamp_entry), compare_timestamp_entries);
726
727 /*
728 * If there are negative timestamp entries, rebase all of the
729 * timestamps to the lowest one in the list.
730 */
731 if (sorted_tst_p->entries[0].entry_stamp < 0) {
732 sorted_tst_p->base_time = -sorted_tst_p->entries[0].entry_stamp;
733 prev_stamp = 0;
734 } else {
735 prev_stamp = tst_p->base_time;
736 }
737
738 struct ts_range_stack range_stack[20];
739 range_stack[0].end = sorted_tst_p->num_entries;
740 int stacklvl = 0;
741
742 for (uint32_t i = 0; i < sorted_tst_p->num_entries; i++) {
743 uint64_t stamp;
744 const struct timestamp_entry *tse = &sorted_tst_p->entries[i];
745
746 /* Make all timestamps absolute. */
747 stamp = tse->entry_stamp + sorted_tst_p->base_time;
748 if (output_type == TIMESTAMPS_PRINT_MACHINE_READABLE) {
749 timestamp_print_parseable_entry(tse->entry_id, stamp, prev_stamp);
750 } else if (output_type == TIMESTAMPS_PRINT_NORMAL) {
751 total_time += timestamp_print_entry(tse->entry_id, stamp, prev_stamp);
752 } else if (output_type == TIMESTAMPS_PRINT_STACKED) {
753 bool end_of_range = false;
754 /* Iterate over stacked entries to pop all ranges, which are closed by
755 current element. For example, assuming two ranges: (TS_A, TS_C),
756 (TS_B, TS_C) it will pop all of them instead of just last one. */
757 while (stacklvl > 0 && range_stack[stacklvl].end == i) {
758 end_of_range = true;
759 stacklvl--;
760 }
761
762 int match =
763 find_matching_end(sorted_tst_p, i, range_stack[stacklvl].end);
764 if (match != -1) {
765 const uint64_t match_stamp =
766 sorted_tst_p->entries[match].entry_stamp
767 + sorted_tst_p->base_time;
768 stacklvl++;
769 assert(stacklvl < (int)ARRAY_SIZE(range_stack));
770 range_stack[stacklvl].name = get_timestamp_name(tse->entry_id);
771 range_stack[stacklvl].end_name = get_timestamp_name(
772 sorted_tst_p->entries[match].entry_id);
773 range_stack[stacklvl].end = match;
774 print_with_path(range_stack, stacklvl, match_stamp - stamp,
775 NULL);
776 } else if (!end_of_range) {
777 print_with_path(range_stack, stacklvl, stamp - prev_stamp,
778 get_timestamp_name(tse->entry_id));
779 }
780 /* else: No match && end_of_range == true */
781 }
782 prev_stamp = stamp;
783 }
784
785 if (output_type == TIMESTAMPS_PRINT_NORMAL) {
786 printf("\nTotal Time: ");
787 print_norm(total_time);
788 printf("\n");
789 }
790
791 unmap_memory(×tamp_mapping);
792 free(sorted_tst_p);
793 }
794
795 /* add a timestamp entry */
timestamp_add_now(uint32_t timestamp_id)796 static void timestamp_add_now(uint32_t timestamp_id)
797 {
798 struct timestamp_table *tst_p;
799 struct mapping timestamp_mapping;
800
801 if (timestamps.tag != LB_TAG_TIMESTAMPS) {
802 die("No timestamps found in coreboot table.\n");
803 }
804
805 tst_p = map_memory_with_prot(×tamp_mapping, timestamps.cbmem_addr,
806 timestamps.size, PROT_READ | PROT_WRITE);
807 if (!tst_p)
808 die("Unable to map timestamp table\n");
809
810 /*
811 * Note that coreboot sizes the cbmem entry in the table according to
812 * max_entries, so it's OK to just add more entries if there's room.
813 */
814 if (tst_p->num_entries >= tst_p->max_entries) {
815 die("Not enough space to add timestamp.\n");
816 } else {
817 int64_t time =
818 timestamp_get(tst_p->tick_freq_mhz) - tst_p->base_time;
819 tst_p->entries[tst_p->num_entries].entry_id = timestamp_id;
820 tst_p->entries[tst_p->num_entries].entry_stamp = time;
821 tst_p->num_entries += 1;
822 }
823
824 unmap_memory(×tamp_mapping);
825 }
826
can_print(const uint8_t * data,size_t len)827 static bool can_print(const uint8_t *data, size_t len)
828 {
829 unsigned int i;
830 for (i = 0; i < len; i++) {
831 if (!isprint(data[i]) && !isspace(data[i])) {
832 /* If printable prefix is followed by zeroes, this is a valid string */
833 for (; i < len; i++) {
834 if (data[i] != 0)
835 return false;
836 }
837 return true;
838 }
839 }
840 return true;
841 }
842
print_hex_string(const uint8_t * hex,size_t len)843 static void print_hex_string(const uint8_t *hex, size_t len)
844 {
845 unsigned int i;
846 for (i = 0; i < len; i++)
847 printf("%02x", hex[i]);
848 }
849
print_hex_line(const uint8_t * hex,size_t len)850 static void print_hex_line(const uint8_t *hex, size_t len)
851 {
852 print_hex_string(hex, len);
853 printf("\n");
854 }
855
print_event_type(uint32_t event_type)856 static void print_event_type(uint32_t event_type)
857 {
858 unsigned int known_event_count = ARRAY_SIZE(tpm_event_types);
859 if (event_type >= known_event_count)
860 printf("Unknown (0x%x >= %u)", event_type, known_event_count);
861 else
862 printf("%s", tpm_event_types[event_type]);
863 }
864
parse_tpm12_log(const struct tcpa_spec_entry * spec_log)865 static void parse_tpm12_log(const struct tcpa_spec_entry *spec_log)
866 {
867 const uint8_t zero_block[sizeof(struct tcpa_spec_entry)] = {0};
868
869 uintptr_t current;
870 uint32_t counter = 0;
871
872 printf("TCPA log:\n");
873 printf("\tSpecification: %d.%d%d\n",
874 spec_log->spec_version_major,
875 spec_log->spec_version_minor,
876 spec_log->spec_errata);
877 printf("\tPlatform class: %s\n",
878 le32toh(spec_log->platform_class) == 0 ? "PC Client" :
879 le32toh(spec_log->platform_class) == 1 ? "Server" : "Unknown");
880
881 current = (uintptr_t)&spec_log->vendor_info[spec_log->vendor_info_size];
882 while (memcmp((const void *)current, (const void *)zero_block, sizeof(zero_block))) {
883 uint32_t len;
884 struct tcpa_log_entry *log_entry = (void *)current;
885 uint32_t event_type = le32toh(log_entry->event_type);
886
887 printf("TCPA log entry %u:\n", ++counter);
888 printf("\tPCR: %d\n", le32toh(log_entry->pcr));
889 printf("\tEvent type: ");
890 print_event_type(event_type);
891 printf("\n");
892 printf("\tDigest: ");
893 print_hex_line(log_entry->digest, SHA1_DIGEST_SIZE);
894 current += sizeof(struct tcpa_log_entry);
895 len = le32toh(log_entry->event_data_size);
896 if (len != 0) {
897 current += len;
898 printf("\tEvent data: ");
899 if (can_print(log_entry->event, len))
900 printf("%.*s\n", len, log_entry->event);
901 else
902 print_hex_line(log_entry->event, len);
903 } else {
904 printf("\tEvent data not provided\n");
905 }
906 }
907 }
908
print_tpm2_digests(struct tcg_pcr_event2_header * log_entry)909 static uint32_t print_tpm2_digests(struct tcg_pcr_event2_header *log_entry)
910 {
911 unsigned int i;
912 uintptr_t current = (uintptr_t)log_entry->digests;
913
914 for (i = 0; i < le32toh(log_entry->digest_count); i++) {
915 struct tpm_hash_algorithm *hash = (struct tpm_hash_algorithm *)current;
916 switch (le16toh(hash->hashAlg)) {
917 case TPM2_ALG_SHA1:
918 printf("\t\t SHA1: ");
919 print_hex_line(hash->digest.sha1, SHA1_DIGEST_SIZE);
920 current += sizeof(hash->hashAlg) + SHA1_DIGEST_SIZE;
921 break;
922 case TPM2_ALG_SHA256:
923 printf("\t\t SHA256: ");
924 print_hex_line(hash->digest.sha256, SHA256_DIGEST_SIZE);
925 current += sizeof(hash->hashAlg) + SHA256_DIGEST_SIZE;
926 break;
927 case TPM2_ALG_SHA384:
928 printf("\t\t SHA384: ");
929 print_hex_line(hash->digest.sha384, SHA384_DIGEST_SIZE);
930 current += sizeof(hash->hashAlg) + SHA384_DIGEST_SIZE;
931 break;
932 case TPM2_ALG_SHA512:
933 printf("\t\t SHA512: ");
934 print_hex_line(hash->digest.sha512, SHA512_DIGEST_SIZE);
935 current += sizeof(hash->hashAlg) + SHA512_DIGEST_SIZE;
936 break;
937 case TPM2_ALG_SM3_256:
938 printf("\t\t SM3: ");
939 print_hex_line(hash->digest.sm3_256, SM3_256_DIGEST_SIZE);
940 current += sizeof(hash->hashAlg) + SM3_256_DIGEST_SIZE;
941 break;
942 default:
943 die("Unknown hash algorithm\n");
944 }
945 }
946
947 return current - (uintptr_t)&log_entry->digest_count;
948 }
949
parse_tpm2_log(const struct tcg_efi_spec_id_event * tpm2_log)950 static void parse_tpm2_log(const struct tcg_efi_spec_id_event *tpm2_log)
951 {
952 const uint8_t zero_block[12] = {0}; /* Only PCR index, event type and digest count */
953
954 uintptr_t current;
955 uint32_t counter = 0;
956
957 printf("TPM2 log:\n");
958 printf("\tSpecification: %d.%d%d\n",
959 tpm2_log->spec_version_major,
960 tpm2_log->spec_version_minor,
961 tpm2_log->spec_errata);
962 printf("\tPlatform class: %s\n",
963 le32toh(tpm2_log->platform_class) == 0 ? "PC Client" :
964 le32toh(tpm2_log->platform_class) == 1 ? "Server" : "Unknown");
965
966 /* Start after the first variable-sized part of the header */
967 current = (uintptr_t)&tpm2_log->digest_sizes[le32toh(tpm2_log->num_of_algorithms)];
968 /* current is at `uint8_t vendor_info_size` here */
969 current += 1 + *(uint8_t *)current;
970
971 while (memcmp((const void *)current, (const void *)zero_block, sizeof(zero_block))) {
972 uint32_t len;
973 struct tcg_pcr_event2_header *log_entry = (void *)current;
974 uint32_t event_type = le32toh(log_entry->event_type);
975
976 printf("TPM2 log entry %u:\n", ++counter);
977 printf("\tPCR: %d\n", le32toh(log_entry->pcr_index));
978 printf("\tEvent type: ");
979 print_event_type(event_type);
980 printf("\n");
981
982 current = (uintptr_t)&log_entry->digest_count;
983 if (le32toh(log_entry->digest_count) > 0) {
984 printf("\tDigests:\n");
985 current += print_tpm2_digests(log_entry);
986 } else {
987 printf("\tNo digests in this log entry\n");
988 current += sizeof(log_entry->digest_count);
989 }
990 /* Now event size and event are left to be parsed */
991 len = le32toh(*(uint32_t *)current);
992 current += sizeof(uint32_t);
993 if (len != 0) {
994 printf("\tEvent data: %.*s\n", len, (const char *)current);
995 current += len;
996 } else {
997 printf("\tEvent data not provided\n");
998 }
999 }
1000 }
1001
1002 /* Dump the TPM log table in format defined by specifications */
dump_tpm_std_log(uint64_t addr,size_t size)1003 static void dump_tpm_std_log(uint64_t addr, size_t size)
1004 {
1005 const void *event_log;
1006 const struct tcpa_spec_entry *tspec_entry;
1007 const struct tcg_efi_spec_id_event *tcg_spec_entry;
1008 struct mapping log_mapping;
1009
1010 event_log = map_memory(&log_mapping, addr, size);
1011 if (!event_log)
1012 die("Unable to map TPM eventlog\n");
1013
1014 tspec_entry = event_log;
1015 if (!strcmp((const char *)tspec_entry->signature, TCPA_SPEC_ID_EVENT_SIGNATURE)) {
1016 if (tspec_entry->spec_version_major == 1 &&
1017 tspec_entry->spec_version_minor == 2 &&
1018 tspec_entry->spec_errata >= 1 &&
1019 le32toh(tspec_entry->entry.event_type) == EV_NO_ACTION) {
1020 parse_tpm12_log(tspec_entry);
1021 } else {
1022 fprintf(stderr, "Unknown TPM1.2 log specification\n");
1023 }
1024 unmap_memory(&log_mapping);
1025 return;
1026 }
1027
1028 tcg_spec_entry = event_log;
1029 if (!strcmp((const char *)tcg_spec_entry->signature, TCG_EFI_SPEC_ID_EVENT_SIGNATURE)) {
1030 if (tcg_spec_entry->spec_version_major == 2 &&
1031 tcg_spec_entry->spec_version_minor == 0 &&
1032 le32toh(tcg_spec_entry->event_type) == EV_NO_ACTION) {
1033 parse_tpm2_log(tcg_spec_entry);
1034 } else {
1035 fprintf(stderr, "Unknown TPM2 log specification.\n");
1036 }
1037 unmap_memory(&log_mapping);
1038 return;
1039 }
1040
1041 fprintf(stderr, "Unknown TPM log specification: %.*s\n",
1042 (int)sizeof(tcg_spec_entry->signature),
1043 (const char *)tcg_spec_entry->signature);
1044
1045 unmap_memory(&log_mapping);
1046 }
1047
1048 /* dump the TPM CB log table */
dump_tpm_cb_log(void)1049 static void dump_tpm_cb_log(void)
1050 {
1051 const struct tpm_cb_log_table *tclt_p;
1052 size_t size;
1053 struct mapping log_mapping;
1054
1055 if (tpm_cb_log.tag != LB_TAG_TPM_CB_LOG) {
1056 fprintf(stderr, "No TPM log found in coreboot table.\n");
1057 return;
1058 }
1059
1060 size = sizeof(*tclt_p);
1061 tclt_p = map_memory(&log_mapping, tpm_cb_log.cbmem_addr, size);
1062 if (!tclt_p)
1063 die("Unable to map TPM log header\n");
1064
1065 size += tclt_p->num_entries * sizeof(tclt_p->entries[0]);
1066
1067 unmap_memory(&log_mapping);
1068
1069 tclt_p = map_memory(&log_mapping, tpm_cb_log.cbmem_addr, size);
1070 if (!tclt_p)
1071 die("Unable to map full TPM log table\n");
1072
1073 printf("coreboot TPM log:\n\n");
1074
1075 for (uint16_t i = 0; i < tclt_p->num_entries; i++) {
1076 const struct tpm_cb_log_entry *tce = &tclt_p->entries[i];
1077
1078 printf(" PCR-%u ", tce->pcr);
1079 print_hex_string(tce->digest, tce->digest_length);
1080 printf(" %s [%s]\n", tce->digest_type, tce->name);
1081 }
1082
1083 unmap_memory(&log_mapping);
1084 }
1085
dump_tpm_log(void)1086 static void dump_tpm_log(void)
1087 {
1088 uint64_t start;
1089 size_t size;
1090
1091 if (!find_cbmem_entry(CBMEM_ID_TCPA_TCG_LOG, &start, &size) ||
1092 !find_cbmem_entry(CBMEM_ID_TPM2_TCG_LOG, &start, &size))
1093 dump_tpm_std_log(start, size);
1094 else
1095 dump_tpm_cb_log();
1096 }
1097
1098 struct cbmem_console {
1099 u32 size;
1100 u32 cursor;
1101 u8 body[];
1102 } __attribute__ ((__packed__));
1103
1104 #define CBMC_CURSOR_MASK ((1 << 28) - 1)
1105 #define CBMC_OVERFLOW (1 << 31)
1106
1107 enum console_print_type {
1108 CONSOLE_PRINT_FULL = 0,
1109 CONSOLE_PRINT_LAST,
1110 CONSOLE_PRINT_PREVIOUS,
1111 };
1112
parse_loglevel(char * arg,int * print_unknown_logs)1113 static int parse_loglevel(char *arg, int *print_unknown_logs)
1114 {
1115 if (arg[0] == '+') {
1116 *print_unknown_logs = 1;
1117 arg++;
1118 } else {
1119 *print_unknown_logs = 0;
1120 }
1121
1122 char *endptr;
1123 int loglevel = strtol(arg, &endptr, 0);
1124 if (*endptr == '\0' && loglevel >= BIOS_EMERG && loglevel <= BIOS_LOG_PREFIX_MAX_LEVEL)
1125 return loglevel;
1126
1127 /* Only match first 3 characters so `NOTE` and `NOTICE` both match. */
1128 for (int i = BIOS_EMERG; i <= BIOS_LOG_PREFIX_MAX_LEVEL; i++)
1129 if (!strncasecmp(arg, bios_log_prefix[i], 3))
1130 return i;
1131
1132 *print_unknown_logs = 1;
1133 return BIOS_NEVER;
1134 }
1135
1136 /* dump the cbmem console */
dump_console(enum console_print_type type,int max_loglevel,int print_unknown_logs)1137 static void dump_console(enum console_print_type type, int max_loglevel, int print_unknown_logs)
1138 {
1139 const struct cbmem_console *console_p;
1140 char *console_c;
1141 size_t size, cursor, previous;
1142 struct mapping console_mapping;
1143
1144 if (console.tag != LB_TAG_CBMEM_CONSOLE) {
1145 fprintf(stderr, "No console found in coreboot table.\n");
1146 return;
1147 }
1148
1149 size = sizeof(*console_p);
1150 console_p = map_memory(&console_mapping, console.cbmem_addr, size);
1151 if (!console_p)
1152 die("Unable to map console object.\n");
1153
1154 cursor = console_p->cursor & CBMC_CURSOR_MASK;
1155 if (!(console_p->cursor & CBMC_OVERFLOW) && cursor < console_p->size)
1156 size = cursor;
1157 else
1158 size = console_p->size;
1159 unmap_memory(&console_mapping);
1160
1161 console_c = malloc(size + 1);
1162 if (!console_c) {
1163 fprintf(stderr, "Not enough memory for console.\n");
1164 exit(1);
1165 }
1166 console_c[size] = '\0';
1167
1168 console_p = map_memory(&console_mapping, console.cbmem_addr,
1169 size + sizeof(*console_p));
1170
1171 if (!console_p)
1172 die("Unable to map full console object.\n");
1173
1174 if (console_p->cursor & CBMC_OVERFLOW) {
1175 if (cursor >= size) {
1176 printf("cbmem: ERROR: CBMEM console struct is illegal, "
1177 "output may be corrupt or out of order!\n\n");
1178 cursor = 0;
1179 }
1180 aligned_memcpy(console_c, console_p->body + cursor,
1181 size - cursor);
1182 aligned_memcpy(console_c + size - cursor,
1183 console_p->body, cursor);
1184 } else {
1185 aligned_memcpy(console_c, console_p->body, size);
1186 }
1187
1188 /* Slight memory corruption may occur between reboots and give us a few
1189 unprintable characters like '\0'. Replace them with '?' on output. */
1190 for (cursor = 0; cursor < size; cursor++)
1191 if (!isprint(console_c[cursor]) && !isspace(console_c[cursor])
1192 && !BIOS_LOG_IS_MARKER(console_c[cursor]))
1193 console_c[cursor] = '?';
1194
1195 /* We detect the reboot cutoff by looking for a bootblock, romstage or
1196 ramstage banner, in that order (to account for platforms without
1197 CONFIG_BOOTBLOCK_CONSOLE and/or CONFIG_EARLY_CONSOLE). Once we find
1198 a banner, store the last two matches for that stage and stop. */
1199 cursor = previous = 0;
1200 if (type != CONSOLE_PRINT_FULL) {
1201 #define BANNER_REGEX(stage) \
1202 "\n\n.?coreboot-[^\n]* " stage " starting.*\\.\\.\\.\n"
1203 #define OVERFLOW_REGEX(stage) "\n.?\\*\\*\\* Pre-CBMEM " stage " console overflow"
1204 const char *regex[] = { BANNER_REGEX("verstage-before-bootblock"),
1205 BANNER_REGEX("bootblock"),
1206 BANNER_REGEX("verstage"),
1207 OVERFLOW_REGEX("romstage"),
1208 BANNER_REGEX("romstage"),
1209 OVERFLOW_REGEX("ramstage"),
1210 BANNER_REGEX("ramstage") };
1211
1212 for (size_t i = 0; !cursor && i < ARRAY_SIZE(regex); i++) {
1213 regex_t re;
1214 regmatch_t match;
1215 int res = regcomp(&re, regex[i], REG_EXTENDED | REG_NEWLINE);
1216 assert(res == 0);
1217
1218 /* Keep looking for matches so we find the last one. */
1219 while (!regexec(&re, console_c + cursor, 1, &match, 0)) {
1220 previous = cursor;
1221 cursor += match.rm_so + 1;
1222 }
1223 regfree(&re);
1224 }
1225 }
1226
1227 if (type == CONSOLE_PRINT_PREVIOUS) {
1228 console_c[cursor] = '\0';
1229 cursor = previous;
1230 }
1231
1232 char c;
1233 int suppressed = 0;
1234 int tty = isatty(fileno(stdout));
1235 while ((c = console_c[cursor++])) {
1236 if (BIOS_LOG_IS_MARKER(c)) {
1237 int lvl = BIOS_LOG_MARKER_TO_LEVEL(c);
1238 if (lvl > max_loglevel) {
1239 suppressed = 1;
1240 continue;
1241 }
1242 suppressed = 0;
1243 if (tty)
1244 printf(BIOS_LOG_ESCAPE_PATTERN, bios_log_escape[lvl]);
1245 printf(BIOS_LOG_PREFIX_PATTERN, bios_log_prefix[lvl]);
1246 } else {
1247 if (!suppressed)
1248 putchar(c);
1249 if (c == '\n') {
1250 if (tty && !suppressed)
1251 printf(BIOS_LOG_ESCAPE_RESET);
1252 suppressed = !print_unknown_logs;
1253 }
1254 }
1255 }
1256 if (tty)
1257 printf(BIOS_LOG_ESCAPE_RESET);
1258
1259 free(console_c);
1260 unmap_memory(&console_mapping);
1261 }
1262
hexdump(unsigned long memory,int length)1263 static void hexdump(unsigned long memory, int length)
1264 {
1265 int i;
1266 const uint8_t *m;
1267 int all_zero = 0;
1268 struct mapping hexdump_mapping;
1269
1270 m = map_memory(&hexdump_mapping, memory, length);
1271 if (!m)
1272 die("Unable to map hexdump memory.\n");
1273
1274 for (i = 0; i < length; i += 16) {
1275 int j;
1276
1277 all_zero++;
1278 for (j = 0; j < 16; j++) {
1279 if(m[i+j] != 0) {
1280 all_zero = 0;
1281 break;
1282 }
1283 }
1284
1285 if (all_zero < 2) {
1286 printf("%08lx:", memory + i);
1287 for (j = 0; j < 16; j++)
1288 printf(" %02x", m[i+j]);
1289 printf(" ");
1290 for (j = 0; j < 16; j++)
1291 printf("%c", isprint(m[i+j]) ? m[i+j] : '.');
1292 printf("\n");
1293 } else if (all_zero == 2) {
1294 printf("...\n");
1295 }
1296 }
1297
1298 unmap_memory(&hexdump_mapping);
1299 }
1300
dump_cbmem_hex(void)1301 static void dump_cbmem_hex(void)
1302 {
1303 if (cbmem.type != LB_MEM_TABLE) {
1304 fprintf(stderr, "No coreboot CBMEM area found!\n");
1305 return;
1306 }
1307
1308 hexdump(cbmem.start, cbmem.size);
1309 }
1310
rawdump(uint64_t base,uint64_t size)1311 static void rawdump(uint64_t base, uint64_t size)
1312 {
1313 const uint8_t *m;
1314 struct mapping dump_mapping;
1315
1316 m = map_memory(&dump_mapping, base, size);
1317 if (!m)
1318 die("Unable to map rawdump memory\n");
1319
1320 for (uint64_t i = 0 ; i < size; i++)
1321 printf("%c", m[i]);
1322
1323 unmap_memory(&dump_mapping);
1324 }
1325
dump_cbmem_raw(unsigned int id)1326 static void dump_cbmem_raw(unsigned int id)
1327 {
1328 const uint8_t *table;
1329 size_t offset;
1330 uint64_t base = 0;
1331 uint64_t size = 0;
1332
1333 table = mapping_virt(&lbtable_mapping);
1334
1335 if (table == NULL)
1336 return;
1337
1338 offset = 0;
1339
1340 while (offset < mapping_size(&lbtable_mapping)) {
1341 const struct lb_record *lbr;
1342 struct lb_cbmem_entry lbe;
1343
1344 lbr = (const void *)(table + offset);
1345 offset += lbr->size;
1346
1347 if (lbr->tag != LB_TAG_CBMEM_ENTRY)
1348 continue;
1349
1350 aligned_memcpy(&lbe, lbr, sizeof(lbe));
1351 if (lbe.id == id) {
1352 debug("found id for raw dump %0x", lbe.id);
1353 base = lbe.address;
1354 size = lbe.entry_size;
1355 break;
1356 }
1357 }
1358
1359 if (!base)
1360 fprintf(stderr, "id %0x not found in cbtable\n", id);
1361 else
1362 rawdump(base, size);
1363 }
1364
1365 struct cbmem_id_to_name {
1366 uint32_t id;
1367 const char *name;
1368 };
1369 static const struct cbmem_id_to_name cbmem_ids[] = { CBMEM_ID_TO_NAME_TABLE };
1370
1371 #define MAX_STAGEx 10
cbmem_print_entry(int n,uint32_t id,uint64_t base,uint64_t size)1372 static void cbmem_print_entry(int n, uint32_t id, uint64_t base, uint64_t size)
1373 {
1374 const char *name;
1375 char stage_x[20];
1376
1377 name = NULL;
1378 for (size_t i = 0; i < ARRAY_SIZE(cbmem_ids); i++) {
1379 if (cbmem_ids[i].id == id) {
1380 name = cbmem_ids[i].name;
1381 break;
1382 }
1383 if (id >= CBMEM_ID_STAGEx_META &&
1384 id < CBMEM_ID_STAGEx_META + MAX_STAGEx) {
1385 snprintf(stage_x, sizeof(stage_x), "STAGE%d META",
1386 (id - CBMEM_ID_STAGEx_META));
1387 name = stage_x;
1388 }
1389 if (id >= CBMEM_ID_STAGEx_CACHE &&
1390 id < CBMEM_ID_STAGEx_CACHE + MAX_STAGEx) {
1391 snprintf(stage_x, sizeof(stage_x), "STAGE%d $ ",
1392 (id - CBMEM_ID_STAGEx_CACHE));
1393 name = stage_x;
1394 }
1395 }
1396
1397 printf("%2d. ", n);
1398 if (name == NULL)
1399 name = "(unknown)";
1400 printf("%-20s %08x", name, id);
1401 printf(" %08" PRIx64 " ", base);
1402 printf(" %08" PRIx64 "\n", size);
1403 }
1404
dump_cbmem_toc(void)1405 static void dump_cbmem_toc(void)
1406 {
1407 int i;
1408 const uint8_t *table;
1409 size_t offset;
1410
1411 table = mapping_virt(&lbtable_mapping);
1412
1413 if (table == NULL)
1414 return;
1415
1416 printf("CBMEM table of contents:\n");
1417 printf(" %-20s %-8s %-8s %-8s\n", "NAME", "ID", "START",
1418 "LENGTH");
1419
1420 i = 0;
1421 offset = 0;
1422
1423 while (offset < mapping_size(&lbtable_mapping)) {
1424 const struct lb_record *lbr;
1425 struct lb_cbmem_entry lbe;
1426
1427 lbr = (const void *)(table + offset);
1428 offset += lbr->size;
1429
1430 if (lbr->tag != LB_TAG_CBMEM_ENTRY)
1431 continue;
1432
1433 aligned_memcpy(&lbe, lbr, sizeof(lbe));
1434 cbmem_print_entry(i, lbe.id, lbe.address, lbe.entry_size);
1435 i++;
1436 }
1437 }
1438
1439 #define COVERAGE_MAGIC 0x584d4153
1440 struct file {
1441 uint32_t magic;
1442 uint32_t next;
1443 uint32_t filename;
1444 uint32_t data;
1445 int offset;
1446 int len;
1447 };
1448
mkpath(char * path,mode_t mode)1449 static int mkpath(char *path, mode_t mode)
1450 {
1451 assert (path && *path);
1452 char *p;
1453 for (p = strchr(path+1, '/'); p; p = strchr(p + 1, '/')) {
1454 *p = '\0';
1455 if (mkdir(path, mode) == -1) {
1456 if (errno != EEXIST) {
1457 *p = '/';
1458 return -1;
1459 }
1460 }
1461 *p = '/';
1462 }
1463 return 0;
1464 }
1465
dump_coverage(void)1466 static void dump_coverage(void)
1467 {
1468 uint64_t start;
1469 size_t size;
1470 const void *coverage;
1471 struct mapping coverage_mapping;
1472 unsigned long phys_offset;
1473 #define phys_to_virt(x) ((void *)(unsigned long)(x) + phys_offset)
1474
1475 if (find_cbmem_entry(CBMEM_ID_COVERAGE, &start, &size)) {
1476 fprintf(stderr, "No coverage information found\n");
1477 return;
1478 }
1479
1480 /* Map coverage area */
1481 coverage = map_memory(&coverage_mapping, start, size);
1482 if (!coverage)
1483 die("Unable to map coverage area.\n");
1484 phys_offset = (unsigned long)coverage - (unsigned long)start;
1485
1486 printf("Dumping coverage data...\n");
1487
1488 struct file *file = (struct file *)coverage;
1489 while (file && file->magic == COVERAGE_MAGIC) {
1490 FILE *f;
1491 char *filename;
1492
1493 debug(" -> %s\n", (char *)phys_to_virt(file->filename));
1494 filename = strdup((char *)phys_to_virt(file->filename));
1495 if (mkpath(filename, 0755) == -1) {
1496 perror("Directory for coverage data could "
1497 "not be created");
1498 exit(1);
1499 }
1500 f = fopen(filename, "wb");
1501 if (!f) {
1502 printf("Could not open %s: %s\n",
1503 filename, strerror(errno));
1504 exit(1);
1505 }
1506 if (fwrite((void *)phys_to_virt(file->data),
1507 file->len, 1, f) != 1) {
1508 printf("Could not write to %s: %s\n",
1509 filename, strerror(errno));
1510 exit(1);
1511 }
1512 fclose(f);
1513 free(filename);
1514
1515 if (file->next)
1516 file = (struct file *)phys_to_virt(file->next);
1517 else
1518 file = NULL;
1519 }
1520 unmap_memory(&coverage_mapping);
1521 }
1522
print_version(void)1523 static void print_version(void)
1524 {
1525 printf("cbmem v%s -- ", CBMEM_VERSION);
1526 printf("Copyright (C) 2012 The ChromiumOS Authors. All rights reserved.\n\n");
1527 printf(
1528 "This program is free software: you can redistribute it and/or modify\n"
1529 "it under the terms of the GNU General Public License as published by\n"
1530 "the Free Software Foundation, version 2 of the License.\n\n"
1531 "This program is distributed in the hope that it will be useful,\n"
1532 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1533 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
1534 "GNU General Public License for more details.\n\n");
1535 }
1536
print_usage(const char * name,int exit_code)1537 static void print_usage(const char *name, int exit_code)
1538 {
1539 printf("usage: %s [-cCltTLxVvh?]\n", name);
1540 printf("\n"
1541 " -c | --console: print cbmem console\n"
1542 " -1 | --oneboot: print cbmem console for last boot only\n"
1543 " -2 | --2ndtolast: print cbmem console for the boot that came before the last one only\n"
1544 " -B | --loglevel: maximum loglevel to print; prefix `+` (e.g. -B +INFO) to also print lines that have no level\n"
1545 " -C | --coverage: dump coverage information\n"
1546 " -l | --list: print cbmem table of contents\n"
1547 " -x | --hexdump: print hexdump of cbmem area\n"
1548 " -r | --rawdump ID: print rawdump of specific ID (in hex) of cbtable\n"
1549 " -t | --timestamps: print timestamp information\n"
1550 " -T | --parseable-timestamps: print parseable timestamps\n"
1551 " -S | --stacked-timestamps: print stacked timestamps (e.g. for flame graph tools)\n"
1552 " -a | --add-timestamp ID: append timestamp with ID\n"
1553 " -L | --tcpa-log print TPM log\n"
1554 " -V | --verbose: verbose (debugging) output\n"
1555 " -v | --version: print the version\n"
1556 " -h | --help: print this help\n"
1557 "\n");
1558 exit(exit_code);
1559 }
1560
1561 #if defined(__arm__) || defined(__aarch64__)
dt_update_cells(const char * name,int * addr_cells_ptr,int * size_cells_ptr)1562 static void dt_update_cells(const char *name, int *addr_cells_ptr,
1563 int *size_cells_ptr)
1564 {
1565 if (*addr_cells_ptr >= 0 && *size_cells_ptr >= 0)
1566 return;
1567
1568 int buffer;
1569 size_t nlen = strlen(name);
1570 char *prop = alloca(nlen + sizeof("/#address-cells"));
1571 strcpy(prop, name);
1572
1573 if (*addr_cells_ptr < 0) {
1574 strcpy(prop + nlen, "/#address-cells");
1575 int fd = open(prop, O_RDONLY);
1576 if (fd < 0 && errno != ENOENT) {
1577 perror(prop);
1578 } else if (fd >= 0) {
1579 if (read(fd, &buffer, sizeof(int)) < 0)
1580 perror(prop);
1581 else
1582 *addr_cells_ptr = ntohl(buffer);
1583 close(fd);
1584 }
1585 }
1586
1587 if (*size_cells_ptr < 0) {
1588 strcpy(prop + nlen, "/#size-cells");
1589 int fd = open(prop, O_RDONLY);
1590 if (fd < 0 && errno != ENOENT) {
1591 perror(prop);
1592 } else if (fd >= 0) {
1593 if (read(fd, &buffer, sizeof(int)) < 0)
1594 perror(prop);
1595 else
1596 *size_cells_ptr = ntohl(buffer);
1597 close(fd);
1598 }
1599 }
1600 }
1601
dt_find_compat(const char * parent,const char * compat,int * addr_cells_ptr,int * size_cells_ptr)1602 static char *dt_find_compat(const char *parent, const char *compat,
1603 int *addr_cells_ptr, int *size_cells_ptr)
1604 {
1605 char *ret = NULL;
1606 struct dirent *entry;
1607 DIR *dir;
1608
1609 if (!(dir = opendir(parent))) {
1610 perror(parent);
1611 return NULL;
1612 }
1613
1614 /* Loop through all files in the directory (DT node). */
1615 while ((entry = readdir(dir))) {
1616 /* We only care about compatible props or subnodes. */
1617 if (entry->d_name[0] == '.' || !((entry->d_type & DT_DIR) ||
1618 !strcmp(entry->d_name, "compatible")))
1619 continue;
1620
1621 /* Assemble the file name (on the stack, for speed). */
1622 size_t plen = strlen(parent);
1623 char *name = alloca(plen + strlen(entry->d_name) + 2);
1624
1625 strcpy(name, parent);
1626 name[plen] = '/';
1627 strcpy(name + plen + 1, entry->d_name);
1628
1629 /* If it's a subnode, recurse. */
1630 if (entry->d_type & DT_DIR) {
1631 ret = dt_find_compat(name, compat, addr_cells_ptr,
1632 size_cells_ptr);
1633
1634 /* There is only one matching node to find, abort. */
1635 if (ret) {
1636 /* Gather cells values on the way up. */
1637 dt_update_cells(parent, addr_cells_ptr,
1638 size_cells_ptr);
1639 break;
1640 }
1641 continue;
1642 }
1643
1644 /* If it's a compatible string, see if it's the right one. */
1645 int fd = open(name, O_RDONLY);
1646 int clen = strlen(compat);
1647 char *buffer = alloca(clen + 1);
1648
1649 if (fd < 0) {
1650 perror(name);
1651 continue;
1652 }
1653
1654 if (read(fd, buffer, clen + 1) < 0) {
1655 perror(name);
1656 close(fd);
1657 continue;
1658 }
1659 close(fd);
1660
1661 if (!strcmp(compat, buffer)) {
1662 /* Initialize these to "unset" for the way up. */
1663 *addr_cells_ptr = *size_cells_ptr = -1;
1664
1665 /* Can't leave string on the stack or we'll lose it! */
1666 ret = strdup(parent);
1667 break;
1668 }
1669 }
1670
1671 closedir(dir);
1672 return ret;
1673 }
1674 #endif /* defined(__arm__) || defined(__aarch64__) */
1675
main(int argc,char ** argv)1676 int main(int argc, char** argv)
1677 {
1678 int print_defaults = 1;
1679 int print_console = 0;
1680 int print_coverage = 0;
1681 int print_list = 0;
1682 int print_hexdump = 0;
1683 int print_rawdump = 0;
1684 int print_tcpa_log = 0;
1685 enum timestamps_print_type timestamp_type = TIMESTAMPS_PRINT_NONE;
1686 enum console_print_type console_type = CONSOLE_PRINT_FULL;
1687 unsigned int rawdump_id = 0;
1688 int max_loglevel = BIOS_NEVER;
1689 int print_unknown_logs = 1;
1690 uint32_t timestamp_id = 0;
1691
1692 int opt, option_index = 0;
1693 static struct option long_options[] = {
1694 {"console", 0, 0, 'c'},
1695 {"oneboot", 0, 0, '1'},
1696 {"2ndtolast", 0, 0, '2'},
1697 {"loglevel", required_argument, 0, 'B'},
1698 {"coverage", 0, 0, 'C'},
1699 {"list", 0, 0, 'l'},
1700 {"tcpa-log", 0, 0, 'L'},
1701 {"timestamps", 0, 0, 't'},
1702 {"parseable-timestamps", 0, 0, 'T'},
1703 {"stacked-timestamps", 0, 0, 'S'},
1704 {"add-timestamp", required_argument, 0, 'a'},
1705 {"hexdump", 0, 0, 'x'},
1706 {"rawdump", required_argument, 0, 'r'},
1707 {"verbose", 0, 0, 'V'},
1708 {"version", 0, 0, 'v'},
1709 {"help", 0, 0, 'h'},
1710 {0, 0, 0, 0}
1711 };
1712 while ((opt = getopt_long(argc, argv, "c12B:CltTSa:LxVvh?r:",
1713 long_options, &option_index)) != EOF) {
1714 switch (opt) {
1715 case 'c':
1716 print_console = 1;
1717 print_defaults = 0;
1718 break;
1719 case '1':
1720 print_console = 1;
1721 console_type = CONSOLE_PRINT_LAST;
1722 print_defaults = 0;
1723 break;
1724 case '2':
1725 print_console = 1;
1726 console_type = CONSOLE_PRINT_PREVIOUS;
1727 print_defaults = 0;
1728 break;
1729 case 'B':
1730 max_loglevel = parse_loglevel(optarg, &print_unknown_logs);
1731 break;
1732 case 'C':
1733 print_coverage = 1;
1734 print_defaults = 0;
1735 break;
1736 case 'l':
1737 print_list = 1;
1738 print_defaults = 0;
1739 break;
1740 case 'L':
1741 print_tcpa_log = 1;
1742 print_defaults = 0;
1743 break;
1744 case 'x':
1745 print_hexdump = 1;
1746 print_defaults = 0;
1747 break;
1748 case 'r':
1749 print_rawdump = 1;
1750 print_defaults = 0;
1751 rawdump_id = strtoul(optarg, NULL, 16);
1752 break;
1753 case 't':
1754 timestamp_type = TIMESTAMPS_PRINT_NORMAL;
1755 print_defaults = 0;
1756 break;
1757 case 'T':
1758 timestamp_type = TIMESTAMPS_PRINT_MACHINE_READABLE;
1759 print_defaults = 0;
1760 break;
1761 case 'S':
1762 timestamp_type = TIMESTAMPS_PRINT_STACKED;
1763 print_defaults = 0;
1764 break;
1765 case 'a':
1766 print_defaults = 0;
1767 timestamp_id = timestamp_enum_name_to_id(optarg);
1768 /* Parse numeric value if name is unknown */
1769 if (timestamp_id == 0)
1770 timestamp_id = strtoul(optarg, NULL, 0);
1771 break;
1772 case 'V':
1773 verbose = 1;
1774 break;
1775 case 'v':
1776 print_version();
1777 exit(0);
1778 break;
1779 case 'h':
1780 print_usage(argv[0], 0);
1781 break;
1782 case '?':
1783 default:
1784 print_usage(argv[0], 1);
1785 break;
1786 }
1787 }
1788
1789 if (optind < argc) {
1790 fprintf(stderr, "Error: Extra parameter found.\n");
1791 print_usage(argv[0], 1);
1792 }
1793
1794 mem_fd = open("/dev/mem", timestamp_id ? O_RDWR : O_RDONLY, 0);
1795 if (mem_fd < 0) {
1796 fprintf(stderr, "Failed to gain memory access: %s\n",
1797 strerror(errno));
1798 return 1;
1799 }
1800
1801 #if defined(__arm__) || defined(__aarch64__)
1802 int addr_cells, size_cells;
1803 char *coreboot_node = dt_find_compat("/proc/device-tree", "coreboot",
1804 &addr_cells, &size_cells);
1805
1806 if (!coreboot_node) {
1807 fprintf(stderr, "Could not find 'coreboot' compatible node!\n");
1808 return 1;
1809 }
1810
1811 if (addr_cells < 0) {
1812 fprintf(stderr, "Warning: no #address-cells node in tree!\n");
1813 addr_cells = 1;
1814 }
1815
1816 int nlen = strlen(coreboot_node);
1817 char *reg = alloca(nlen + sizeof("/reg"));
1818
1819 strcpy(reg, coreboot_node);
1820 strcpy(reg + nlen, "/reg");
1821 free(coreboot_node);
1822
1823 int fd = open(reg, O_RDONLY);
1824 if (fd < 0) {
1825 perror(reg);
1826 return 1;
1827 }
1828
1829 int i;
1830 size_t size_to_read = addr_cells * 4 + size_cells * 4;
1831 u8 *dtbuffer = alloca(size_to_read);
1832 if (read(fd, dtbuffer, size_to_read) < 0) {
1833 perror(reg);
1834 return 1;
1835 }
1836 close(fd);
1837
1838 /* No variable-length byte swap function anywhere in C... how sad. */
1839 u64 baseaddr = 0;
1840 for (i = 0; i < addr_cells * 4; i++) {
1841 baseaddr <<= 8;
1842 baseaddr |= *dtbuffer;
1843 dtbuffer++;
1844 }
1845 u64 cb_table_size = 0;
1846 for (i = 0; i < size_cells * 4; i++) {
1847 cb_table_size <<= 8;
1848 cb_table_size |= *dtbuffer;
1849 dtbuffer++;
1850 }
1851
1852 parse_cbtable(baseaddr, cb_table_size);
1853 #else
1854 unsigned long long possible_base_addresses[] = { 0, 0xf0000 };
1855
1856 /* Find and parse coreboot table */
1857 for (size_t j = 0; j < ARRAY_SIZE(possible_base_addresses); j++) {
1858 if (!parse_cbtable(possible_base_addresses[j], 0))
1859 break;
1860 }
1861 #endif
1862
1863 if (mapping_virt(&lbtable_mapping) == NULL)
1864 die("Table not found.\n");
1865
1866 if (print_console)
1867 dump_console(console_type, max_loglevel, print_unknown_logs);
1868
1869 if (print_coverage)
1870 dump_coverage();
1871
1872 if (print_list)
1873 dump_cbmem_toc();
1874
1875 if (print_hexdump)
1876 dump_cbmem_hex();
1877
1878 if (print_rawdump)
1879 dump_cbmem_raw(rawdump_id);
1880
1881 if (timestamp_id)
1882 timestamp_add_now(timestamp_id);
1883
1884 if (print_defaults)
1885 timestamp_type = TIMESTAMPS_PRINT_NORMAL;
1886
1887 if (timestamp_type != TIMESTAMPS_PRINT_NONE)
1888 dump_timestamps(timestamp_type);
1889
1890 if (print_tcpa_log)
1891 dump_tpm_log();
1892
1893 unmap_memory(&lbtable_mapping);
1894
1895 close(mem_fd);
1896 return 0;
1897 }
1898