96 lines
2 KiB
C
96 lines
2 KiB
C
/* SPDX-License-Identifier: GPL-2.0-only */
|
|
#include <kernel/mem.h>
|
|
#include <lib/string.h>
|
|
#include <lib/stdio.h>
|
|
|
|
#include "gpt.h"
|
|
#include "partition.h"
|
|
|
|
bool block_has_gpt_header(struct block_device *bdev)
|
|
{
|
|
bool ret = false;
|
|
char *lba1 = kzalloc(bdev->block_size, ALLOC_KERN);
|
|
if (!lba1)
|
|
return false;
|
|
|
|
int res = block_read(bdev, lba1, 1, 1);
|
|
|
|
if (res < 0)
|
|
goto out;
|
|
|
|
if (!memcmp("EFI PART", lba1, 8))
|
|
ret = true;
|
|
|
|
out:
|
|
kfree(lba1);
|
|
return ret;
|
|
}
|
|
|
|
int gpt_parse_partitions(struct block_device *bdev, struct gpt_partition **out)
|
|
{
|
|
if (!block_has_gpt_header(bdev))
|
|
return -EINVAL;
|
|
struct gpt_header *header = kzalloc(bdev->block_size, ALLOC_KERN);
|
|
int ret = 0;
|
|
|
|
if (!header)
|
|
return -ENOMEM;
|
|
|
|
int res = block_read(bdev, (void *)header, 1, 1);
|
|
|
|
if (res < 0) {
|
|
ret = res;
|
|
goto out;
|
|
}
|
|
|
|
size_t n_blocks_pentry = ALIGN_UP(header->n_pentries * header->pentry_size, bdev->block_size) / bdev->block_size;
|
|
struct gpt_partition *ptables = kzalloc(n_blocks_pentry * bdev->block_size, ALLOC_KERN);
|
|
if (!ptables) {
|
|
ret = -ENOMEM;
|
|
goto out;
|
|
}
|
|
|
|
res = block_read(bdev, (void *)ptables, header->pentry_lba, n_blocks_pentry);
|
|
|
|
if (res < 0) {
|
|
ret = res;
|
|
goto out_ptables;
|
|
}
|
|
|
|
if (header->pentry_size < sizeof(struct gpt_partition))
|
|
goto out_ptables;
|
|
|
|
if (header->n_pentries > 128) {
|
|
kwarn("bdev /dev/%s: too many GPT entries (%u), limiting to 128\n", bdev->name, header->n_pentries);
|
|
header->n_pentries = 128;
|
|
}
|
|
|
|
static const char null_guid[16] = {0};
|
|
|
|
(*out) = kalloc(header->n_pentries * sizeof(struct gpt_partition), ALLOC_KERN);
|
|
if (!(*out)) {
|
|
ret = -ENOMEM;
|
|
goto out_ptables;
|
|
}
|
|
|
|
ret = 0;
|
|
for (size_t i = 0; i < header->n_pentries; i++) {
|
|
void *start = ptables;
|
|
start += i * header->pentry_size;
|
|
|
|
struct gpt_partition *part = start;
|
|
|
|
if (!memcmp(part->ptypeguid, null_guid, 16))
|
|
continue;
|
|
|
|
struct gpt_partition *desc = (*out) + ret;
|
|
memcpy(desc, part, sizeof(struct gpt_partition));
|
|
ret += 1;
|
|
}
|
|
|
|
out_ptables:
|
|
kfree(ptables);
|
|
out:
|
|
kfree(header);
|
|
return ret;
|
|
}
|