Debian Codegraph @

util/cbmem/devmem_drv.c

raw symbols SCIP
1 /* SPDX-License-Identifier: GPL-2.0-only */
2
3 #include <alloca.h>
4 #include <errno.h>
5 #include <inttypes.h>
6 #include <stdbool.h>
7 #include <stdint.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11
12 #include <arpa/inet.h>
13 #include <dirent.h>
14 #include <endian.h>
15 #include <fcntl.h>
16 #include <unistd.h>
17 #include <sys/mman.h>
18 #include <sys/types.h>
19
20 #include <commonlib/bsd/cbmem_id.h>
21 #include <commonlib/bsd/ipchksum.h>
22 #include <commonlib/coreboot_tables.h>
23 #include <commonlib/helpers.h>
24 #include <commonlib/timestamp_serialized.h>
25 #include <commonlib/tpm_log_serialized.h>
26
27 #ifdef __OpenBSD__
28 #include <sys/param.h>
29 #include <sys/sysctl.h>
30 #endif
31
32 #include "cbmem_util.h"
33
34 struct mapping {
35 void *virt;
36 size_t offset;
37 size_t virt_size;
38 unsigned long long phys;
39 size_t size;
40 };
41
42 /* File handle used to access /dev/mem */
43 static int mem_fd;
44 static struct mapping lbtable_mapping;
45
46 static unsigned long long system_page_size(void)
47 {
48 static unsigned long long page_size;
49
50 if (!page_size)
51 page_size = getpagesize();
52
53 return page_size;
54 }
55
56 static inline size_t size_to_mib(size_t sz)
57 {
58 return sz >> 20;
59 }
60
61 /* Return mapping of physical address requested. */
62 static void *mapping_virt(const struct mapping *mapping)
63 {
64 char *v = mapping->virt;
65
66 if (v == NULL)
67 return NULL;
68
69 return v + mapping->offset;
70 }
71
72 /* Returns virtual address on success, NULL on error. mapping is filled in. */
73 static void *map_memory_with_prot(struct mapping *mapping, unsigned long long phys, size_t sz,
74 int prot)
75 {
76 void *v;
77 unsigned long long page_size;
78
79 page_size = system_page_size();
80
81 mapping->virt = NULL;
82 mapping->offset = phys % page_size;
83 mapping->virt_size = sz + mapping->offset;
84 mapping->size = sz;
85 mapping->phys = phys;
86
87 if (size_to_mib(mapping->virt_size) == 0) {
88 debug("Mapping %zuB of physical memory at 0x%llx (requested 0x%llx).\n",
89 mapping->virt_size, phys - mapping->offset, phys);
90 } else {
91 debug("Mapping %zuMB of physical memory at 0x%llx (requested 0x%llx).\n",
92 size_to_mib(mapping->virt_size), phys - mapping->offset, phys);
93 }
94
95 v = mmap(NULL, mapping->virt_size, prot, MAP_SHARED, mem_fd, phys - mapping->offset);
96
97 if (v == MAP_FAILED) {
98 debug("Mapping failed %zuB of physical memory at 0x%llx.\n", mapping->virt_size,
99 phys - mapping->offset);
100 return NULL;
101 }
102
103 mapping->virt = v;
104
105 if (mapping->offset != 0)
106 debug(" ... padding virtual address with 0x%zx bytes.\n", mapping->offset);
107
108 return mapping_virt(mapping);
109 }
110
111 /* Convenience helper for the common case of read-only mappings. */
112 static const void *map_memory(struct mapping *mapping, unsigned long long phys, size_t sz)
113 {
114 return map_memory_with_prot(mapping, phys, sz, PROT_READ);
115 }
116
117 /* Returns 0 on success, < 0 on error. mapping is cleared if successful. */
118 static int unmap_memory(struct mapping *mapping)
119 {
120 if (mapping->virt == NULL)
121 return -1;
122
123 munmap(mapping->virt, mapping->virt_size);
124 mapping->virt = NULL;
125 mapping->offset = 0;
126 mapping->virt_size = 0;
127
128 return 0;
129 }
130
131 /*
132 * Some architectures map /dev/mem memory in a way that doesn't support
133 * unaligned accesses. Most normal libc memcpy()s aren't safe to use in this
134 * case, so build our own which makes sure to never do unaligned accesses on
135 * *src (*dest is fine since we never map /dev/mem for writing).
136 */
137 static void *aligned_memcpy(void *dest, const void *src, size_t n)
138 {
139 uint8_t *d = dest;
140 const volatile uint8_t *s = src; /* volatile to prevent optimization */
141
142 while ((uintptr_t)s & (sizeof(size_t) - 1)) {
143 if (n-- == 0)
144 return dest;
145 *d++ = *s++;
146 }
147
148 while (n >= sizeof(size_t)) {
149 *(size_t *)d = *(const volatile size_t *)s;
150 d += sizeof(size_t);
151 s += sizeof(size_t);
152 n -= sizeof(size_t);
153 }
154
155 while (n-- > 0)
156 *d++ = *s++;
157
158 return dest;
159 }
160
161 /* Return < 0 on error, 0 on success. */
162 static int parse_cbtable(uint64_t address, size_t table_size)
163 {
164 const uint8_t *buf;
165 struct mapping header_mapping;
166 size_t req_size;
167 size_t i;
168
169 req_size = table_size;
170 /* Default to 4 KiB search space. */
171 if (req_size == 0)
172 req_size = 4 * 1024;
173
174 debug("Looking for coreboot table at %" PRIx64 " %zd bytes.\n", address, req_size);
175
176 buf = map_memory(&header_mapping, address, req_size);
177
178 if (!buf)
179 return -1;
180
181 /* look at every 16 bytes */
182 for (i = 0; i <= req_size - sizeof(struct lb_header); i += 16) {
183 const struct lb_header *lbh;
184 struct mapping table_mapping;
185
186 lbh = (const struct lb_header *)&buf[i];
187 if (memcmp(lbh->signature, "LBIO", sizeof(lbh->signature)) ||
188 !lbh->header_bytes || ipchksum(lbh, sizeof(*lbh))) {
189 continue;
190 }
191
192 /* Map in the whole table to parse. */
193 if (!map_memory(&table_mapping, address + i,
194 lbh->header_bytes + lbh->table_bytes)) {
195 debug("Couldn't map in table\n");
196 continue;
197 }
198
199 const uint8_t *table_contents =
200 &((uint8_t *)mapping_virt(&table_mapping))[lbh->header_bytes];
201 if (ipchksum(table_contents, lbh->table_bytes) !=
202 lbh->table_checksum) {
203 debug("Signature found, but wrong checksum.\n");
204 unmap_memory(&table_mapping);
205 continue;
206 }
207
208 debug("Found at %#" PRIx64 "\n", address + i);
209
210 const struct lb_record *lbr_p;
211
212 for (size_t offset = 0; offset < lbh->table_bytes; offset += lbr_p->size) {
213 lbr_p = (const struct lb_record *)&table_contents[offset];
214 debug(" coreboot table entry 0x%02x\n", lbr_p->tag);
215
216 if (lbr_p->tag != LB_TAG_FORWARD)
217 continue;
218
219 /* This is a forwarding entry. Repeat the search at the new address. */
220 struct lb_forward lbf_p = *(const struct lb_forward *)lbr_p;
221 debug(" Found forwarding entry.\n");
222
223 const uint64_t next_addr = lbf_p.forward;
224 unmap_memory(&header_mapping);
225 unmap_memory(&table_mapping);
226
227 return parse_cbtable(next_addr, 0);
228 }
229
230 debug("correct coreboot table found.\n");
231 unmap_memory(&header_mapping);
232 lbtable_mapping = table_mapping;
233
234 return 0;
235 }
236
237 unmap_memory(&header_mapping);
238
239 return -1;
240 }
241
242 #if defined(__arm__) || defined(__aarch64__)
243 static void dt_update_cells(const char *name, int *addr_cells_ptr, int *size_cells_ptr)
244 {
245 if (*addr_cells_ptr >= 0 && *size_cells_ptr >= 0)
246 return;
247
248 int buffer;
249 size_t nlen = strlen(name);
250 char *prop = alloca(nlen + sizeof("/#address-cells"));
251 strcpy(prop, name);
252
253 if (*addr_cells_ptr < 0) {
254 strcpy(prop + nlen, "/#address-cells");
255 int fd = open(prop, O_RDONLY);
256 if (fd < 0 && errno != ENOENT) {
257 perror(prop);
258 } else if (fd >= 0) {
259 if (read(fd, &buffer, sizeof(int)) < 0)
260 perror(prop);
261 else
262 *addr_cells_ptr = ntohl(buffer);
263 close(fd);
264 }
265 }
266
267 if (*size_cells_ptr < 0) {
268 strcpy(prop + nlen, "/#size-cells");
269 int fd = open(prop, O_RDONLY);
270 if (fd < 0 && errno != ENOENT) {
271 perror(prop);
272 } else if (fd >= 0) {
273 if (read(fd, &buffer, sizeof(int)) < 0)
274 perror(prop);
275 else
276 *size_cells_ptr = ntohl(buffer);
277 close(fd);
278 }
279 }
280 }
281
282 static char *dt_find_compat(const char *parent, const char *compat, int *addr_cells_ptr,
283 int *size_cells_ptr)
284 {
285 char *ret = NULL;
286 struct dirent *entry;
287 DIR *dir;
288
289 if (!(dir = opendir(parent))) {
290 perror(parent);
291 return NULL;
292 }
293
294 /* Loop through all files in the directory (DT node). */
295 while ((entry = readdir(dir))) {
296 /* We only care about compatible props or subnodes. */
297 if (entry->d_name[0] == '.' ||
298 !((entry->d_type & DT_DIR) || !strcmp(entry->d_name, "compatible")))
299 continue;
300
301 /* Assemble the file name (on the stack, for speed). */
302 size_t plen = strlen(parent);
303 char *name = alloca(plen + strlen(entry->d_name) + 2);
304
305 strcpy(name, parent);
306 name[plen] = '/';
307 strcpy(name + plen + 1, entry->d_name);
308
309 /* If it's a subnode, recurse. */
310 if (entry->d_type & DT_DIR) {
311 ret = dt_find_compat(name, compat, addr_cells_ptr, size_cells_ptr);
312
313 /* There is only one matching node to find, abort. */
314 if (ret) {
315 /* Gather cells values on the way up. */
316 dt_update_cells(parent, addr_cells_ptr, size_cells_ptr);
317 break;
318 }
319 continue;
320 }
321
322 /* If it's a compatible string, see if it's the right one. */
323 int fd = open(name, O_RDONLY);
324 int clen = strlen(compat);
325 char *buffer = alloca(clen + 1);
326
327 if (fd < 0) {
328 perror(name);
329 continue;
330 }
331
332 if (read(fd, buffer, clen + 1) < 0) {
333 perror(name);
334 close(fd);
335 continue;
336 }
337 close(fd);
338
339 if (!strcmp(compat, buffer)) {
340 /* Initialize these to "unset" for the way up. */
341 *addr_cells_ptr = *size_cells_ptr = -1;
342
343 /* Can't leave string on the stack or we'll lose it! */
344 ret = strdup(parent);
345 break;
346 }
347 }
348
349 closedir(dir);
350 return ret;
351 }
352 #endif /* defined(__arm__) || defined(__aarch64__) */
353
354 bool cbmem_devmem_init(bool writeable)
355 {
356 mem_fd = open("/dev/mem", writeable ? O_RDWR : O_RDONLY, 0);
357 if (mem_fd < 0) {
358 fprintf(stderr, "Failed to gain memory access: %s\n", strerror(errno));
359 return false;
360 }
361
362 #if defined(__arm__) || defined(__aarch64__)
363 int addr_cells, size_cells;
364 char *coreboot_node =
365 dt_find_compat("/proc/device-tree", "coreboot", &addr_cells, &size_cells);
366
367 if (!coreboot_node) {
368 fprintf(stderr, "Could not find 'coreboot' compatible node!\n");
369 return false;
370 }
371
372 if (addr_cells < 0) {
373 fprintf(stderr, "Warning: no #address-cells node in tree!\n");
374 addr_cells = 1;
375 }
376
377 int nlen = strlen(coreboot_node);
378 char *reg = alloca(nlen + sizeof("/reg"));
379
380 strcpy(reg, coreboot_node);
381 strcpy(reg + nlen, "/reg");
382 free(coreboot_node);
383
384 int fd = open(reg, O_RDONLY);
385 if (fd < 0) {
386 perror(reg);
387 return false;
388 }
389
390 int i;
391 size_t size_to_read = addr_cells * 4 + size_cells * 4;
392 uint8_t *dtbuffer = alloca(size_to_read);
393 if (read(fd, dtbuffer, size_to_read) < 0) {
394 perror(reg);
395 return false;
396 }
397 close(fd);
398
399 /* No variable-length byte swap function anywhere in C... how sad. */
400 uint64_t baseaddr = 0;
401 for (i = 0; i < addr_cells * 4; i++) {
402 baseaddr <<= 8;
403 baseaddr |= *dtbuffer;
404 dtbuffer++;
405 }
406 uint64_t cb_table_size = 0;
407 for (i = 0; i < size_cells * 4; i++) {
408 cb_table_size <<= 8;
409 cb_table_size |= *dtbuffer;
410 dtbuffer++;
411 }
412
413 parse_cbtable(baseaddr, cb_table_size);
414 #else
415 unsigned long long possible_base_addresses[] = {0, 0xf0000};
416
417 /* Find and parse coreboot table */
418 for (size_t j = 0; j < ARRAY_SIZE(possible_base_addresses); j++) {
419 if (!parse_cbtable(possible_base_addresses[j], 0))
420 break;
421 }
422 #endif
423
424 if (mapping_virt(&lbtable_mapping) == NULL) {
425 debug("Table not found.\n");
426 return false;
427 }
428
429 return true;
430 }
431
432 void cbmem_devmem_terminate(void)
433 {
434 unmap_memory(&lbtable_mapping);
435 close(mem_fd);
436 mem_fd = -1;
437 }
438
439 /* This is a work-around for a nasty problem introduced by initially having
440 * pointer sized entries in the lb_cbmem_ref structures. This caused problems
441 * on 64bit x86 systems because coreboot is 32bit on those systems.
442 * When the problem was found, it was corrected, but there are a lot of
443 * systems out there with a firmware that does not produce the right
444 * lb_cbmem_ref structure. Hence we try to autocorrect this issue here.
445 */
446 static struct lb_cbmem_ref parse_cbmem_ref(const struct lb_cbmem_ref *cbmem_ref)
447 {
448 struct lb_cbmem_ref ret;
449
450 aligned_memcpy(&ret, cbmem_ref, sizeof(ret));
451
452 if (cbmem_ref->size < sizeof(*cbmem_ref))
453 ret.cbmem_addr = (uint32_t)ret.cbmem_addr;
454
455 debug(" cbmem_addr = %" PRIx64 "\n", ret.cbmem_addr);
456
457 return ret;
458 }
459
460 static uint32_t cbmem_id_to_lb_tag(uint32_t tag)
461 {
462 /* Minimal subset. Expand based on the CBMEM to coreboot table
463 records mapping in lib/coreboot_table.c */
464 switch (tag) {
465 case CBMEM_ID_TIMESTAMP:
466 return LB_TAG_TIMESTAMPS;
467 case CBMEM_ID_CONSOLE:
468 return LB_TAG_CBMEM_CONSOLE;
469 case CBMEM_ID_TPM_CB_LOG:
470 return LB_TAG_TPM_CB_LOG;
471 }
472 return LB_TAG_UNUSED;
473 }
474
475 static bool cbmem_devmem_probe_cbmem_entry(uint32_t id, uint64_t *addr_out, size_t *size_out)
476 {
477 const uint8_t *table;
478 const struct lb_header *lbh;
479 const uint32_t legacy_tag = cbmem_id_to_lb_tag(id);
480 struct lb_cbmem_ref *ref = NULL;
481 const struct lb_record *lbr = NULL;
482
483 table = mapping_virt(&lbtable_mapping);
484 if (table == NULL)
485 die("No correct coreboot table found\n");
486
487 lbh = (const struct lb_header *)table;
488 table = &table[lbh->header_bytes];
489
490 /* Fast track for the coreboot table. */
491 if (id == CBMEM_ID_CBTABLE) {
492 *addr_out = lbtable_mapping.phys;
493 *size_out = lbtable_mapping.size;
494 return true;
495 }
496
497 for (size_t offset = 0; offset < lbh->table_bytes - sizeof(struct lb_cbmem_entry);) {
498 lbr = (const void *)(table + offset);
499 offset += lbr->size;
500
501 /* Store coreboot table entry for later if CBMEM entry does not exist.
502 CBMEM entry stores size including the reserved area, so prefer it,
503 so more potential data and/or space is available. */
504 if (legacy_tag != LB_TAG_UNUSED && lbr->tag == legacy_tag)
505 ref = (struct lb_cbmem_ref *)lbr;
506
507 if (lbr->tag != LB_TAG_CBMEM_ENTRY)
508 continue;
509
510 struct lb_cbmem_entry lbe;
511 aligned_memcpy(&lbe, lbr, sizeof(lbe));
512 if (lbe.id != id)
513 continue;
514
515 *addr_out = lbe.address;
516 *size_out = lbe.entry_size;
517 return true;
518 }
519
520 /* No mapping and/or no potential reference means that
521 the requested entry does not exit. */
522 if (legacy_tag == LB_TAG_UNUSED || ref == NULL)
523 return false;
524
525 debug("Found coreboot table record equivalent of CBMEM entry id: %#x, tag: %#x\n", id,
526 legacy_tag);
527
528 const struct lb_cbmem_ref lbc = parse_cbmem_ref(ref);
529 size_t header_map_size = 0;
530
531 /* Process legacy coreboot table entries */
532 switch (lbc.tag) {
533 case LB_TAG_TIMESTAMPS:
534 header_map_size = sizeof(struct timestamp_table);
535 break;
536 case LB_TAG_CBMEM_CONSOLE:
537 header_map_size = sizeof(struct cbmem_console);
538 break;
539 case LB_TAG_TPM_CB_LOG:
540 header_map_size = sizeof(struct tpm_cb_log_table);
541 break;
542 }
543
544 struct mapping entry_mapping;
545 const void *entry_header = NULL;
546
547 entry_header = map_memory(&entry_mapping, lbc.cbmem_addr, header_map_size);
548 if (!entry_header)
549 die("Unable to map header for coreboot table entry id: %#x\n", legacy_tag);
550
551 *addr_out = lbc.cbmem_addr;
552
553 switch (legacy_tag) {
554 case LB_TAG_TIMESTAMPS: {
555 const struct timestamp_table *tst_p = entry_header;
556 *size_out = sizeof(*tst_p) + tst_p->num_entries * sizeof(tst_p->entries[0]);
557 break;
558 }
559 case LB_TAG_CBMEM_CONSOLE: {
560 const struct cbmem_console *console_p = entry_header;
561 *size_out = sizeof(*console_p) + console_p->size;
562 break;
563 }
564 case LB_TAG_TPM_CB_LOG: {
565 const struct tpm_cb_log_table *tclt_p = entry_header;
566 *size_out = sizeof(*tclt_p) + tclt_p->num_entries * sizeof(tclt_p->entries[0]);
567 break;
568 }
569 }
570
571 unmap_memory(&entry_mapping);
572
573 return true;
574 }
575
576 static void fetch_cbmem_entry(const uint32_t id, const uint64_t addr, const size_t size,
577 uint8_t **buf_out)
578 {
579 struct mapping cbmem_mapping;
580 const uint8_t *buf = map_memory(&cbmem_mapping, addr, size);
581 if (!buf)
582 die("Unable to map CBMEM entry id: %#x, size: %zu\n", id, size);
583
584 *buf_out = malloc(size);
585 if (!*buf_out) {
586 unmap_memory(&cbmem_mapping);
587 die("Unable to allocate memory for CBMEM entry id: %#x, size: %zu\n", id, size);
588 }
589
590 aligned_memcpy(*buf_out, buf, size);
591 unmap_memory(&cbmem_mapping);
592 }
593
594 bool cbmem_devmem_get_cbmem_entry(uint32_t id, uint8_t **buf_out, size_t *size_out,
595 uint64_t *addr_out)
596 {
597 uint64_t addr;
598 size_t size;
599
600 if (!cbmem_devmem_probe_cbmem_entry(id, &addr, &size)) {
601 debug("CBMEM entry not found. CBMEM id: %#x\n", id);
602 return false;
603 }
604
605 fetch_cbmem_entry(id, addr, size, buf_out);
606
607 if (size_out)
608 *size_out = size;
609 if (addr_out)
610 *addr_out = addr;
611
612 return true;
613 }
614
615 bool cbmem_devmem_write_cbmem_entry(uint32_t id, uint8_t *buf, size_t buf_size)
616 {
617 uint64_t addr = 0;
618 size_t size = 0;
619 uint8_t *origin_buf = NULL;
620 struct mapping mapping;
621
622 if (!cbmem_devmem_probe_cbmem_entry(id, &addr, &size)) {
623 debug("CBMEM entry not found. CBMEM id: %#x\n", id);
624 return false;
625 }
626
627 if (buf_size > size)
628 die("Attempting to write %zu bytes to CBMEM entry id: %#x of %zu bytes. Operation not possible.\n",
629 buf_size, id, size);
630
631 origin_buf = map_memory_with_prot(&mapping, addr, size, PROT_READ | PROT_WRITE);
632 if (!origin_buf)
633 die("Unable to map CBMEM entry id: %#x, size: %zu for read-write access.\n", id,
634 size);
635
636 aligned_memcpy(origin_buf, buf, buf_size);
637 unmap_memory(&mapping);
638
639 return true;
640 }
641
642 void cbmem_devmem_foreach_cbmem_entry(cbmem_iterator_callback cb, void *data,
643 bool with_contents)
644 {
645 uint8_t *table = NULL;
646 size_t table_size = 0;
647
648 if (!cbmem_devmem_get_cbmem_entry(CBMEM_ID_CBTABLE, &table, &table_size, NULL))
649 die("coreboot table not found.\n");
650
651 const struct lb_header *lbh = (const struct lb_header *)table;
652 const struct lb_record *lbr = NULL;
653 bool should_iteration_end = false;
654 size_t offset = 0;
655 while (offset < lbh->table_bytes - sizeof(struct lb_cbmem_entry) &&
656 should_iteration_end == false) {
657 lbr = (const struct lb_record *)&table[lbh->header_bytes + offset];
658 offset += lbr->size;
659
660 if (lbr->tag != LB_TAG_CBMEM_ENTRY)
661 continue;
662
663 const struct lb_cbmem_entry *lbe = (const struct lb_cbmem_entry *)lbr;
664 uint8_t *buf = NULL;
665 if (with_contents)
666 fetch_cbmem_entry(lbe->id, lbe->address, lbe->entry_size, &buf);
667
668 should_iteration_end = cb(lbe->id, lbe->address, buf, lbe->entry_size, data);
669
670 if (with_contents)
671 free(buf);
672 }
673
674 free(table);
675 }