#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: disksubr.c,v 1.8 2009/08/02 12:04:28 uch Exp $");
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/disk.h>
#include <sys/buf.h>
#include <sys/disklabel.h>
#include <machine/sector.h>
#define DISKLABEL_DEBUG
#ifdef DISKLABEL_DEBUG
#define DPRINTF(fmt, args...) printf(fmt, ##args)
#else
#define DPRINTF(arg...) ((void)0)
#endif
const char *
readdisklabel(dev_t dev, void (*strategy)(struct buf *), struct disklabel *d,
struct cpu_disklabel *ux)
{
uint8_t buf[DEV_BSIZE];
struct pdinfo_sector *pdinfo = &ux->pdinfo;
struct vtoc_sector *vtoc = &ux->vtoc;
bool disklabel_available = false;
bool vtoc_available = false;
void *rwops;
if ((rwops = sector_init(dev, strategy)) == 0)
return "can't read/write disk";
if (!pdinfo_sector(rwops, pdinfo) || !pdinfo_sanity(pdinfo)) {
DPRINTF("%s: PDINFO not found.\n", __func__);
} else if (vtoc_sector(rwops, vtoc, pdinfo->logical_sector) &&
vtoc_sanity(vtoc)) {
vtoc_available = true;
sector_read(rwops, buf, LABELSECTOR);
if (disklabel_sanity((struct disklabel *)buf)) {
disklabel_available = true;
memcpy(d, buf, sizeof(struct disklabel));
} else {
DPRINTF("%s: no BSD disklabel.\n", __func__);
}
} else {
DPRINTF("%s: PDINFO found, but VTOC not found.\n", __func__);
}
sector_fini(rwops);
if (!disklabel_available) {
if (vtoc_available) {
DPRINTF("%s: creating disklabel from VTOC.\n",
__func__);
} else {
DPRINTF("%s: no VTOC. creating default disklabel.\n",
__func__);
vtoc_set_default(ux, d);
}
disklabel_set_default(d);
vtoc_to_disklabel(ux, d);
}
return 0;
}
int
setdisklabel(struct disklabel *od, struct disklabel *nd, u_long openmask,
struct cpu_disklabel *ux)
{
KDASSERT(openmask == 0);
if (!disklabel_sanity(nd))
return EINVAL;
*od = *nd;
return 0;
}
int
writedisklabel(dev_t dev, void (*strategy)(struct buf *), struct disklabel *d,
struct cpu_disklabel *ux)
{
uint8_t buf[DEV_BSIZE];
int err = 0;
void *rwops;
if (!disklabel_sanity(d))
return EINVAL;
disklabel_to_vtoc(ux, d);
DPRINTF("%s: logical_sector=%d\n", __func__, ux->pdinfo.logical_sector);
if ((rwops = sector_init(dev, strategy)) == 0)
return ENOMEM;
pdinfo_sanity(&ux->pdinfo);
vtoc_sanity(&ux->vtoc);
sector_write(rwops, (void *)&ux->pdinfo, PDINFO_SECTOR);
sector_write(rwops, (void *)&ux->vtoc,
ux->pdinfo.logical_sector + VTOC_SECTOR);
memset(buf, 0, sizeof buf);
memcpy(buf, d, sizeof *d);
if (!sector_write(rwops, buf, LABELSECTOR)) {
DPRINTF("%s: failed to write disklabel.\n", __func__);
err = EIO;
}
sector_fini(rwops);
return err;
}