pang-o-lin/src/defrag.c

45 lines
1.0 KiB
C
Raw Normal View History

#include "io.h"
#define try(x) do { int i = (x); if (i == -1) { return -1 } } while (0)
int fat12_defrag(int fd) {
uint8_t buf[512];
// Read in MBR and figure out where the FAT begins and ends
try(pang_seek(fd, 0, SEEK_SET));
// Actually read in the MBR
try(pang_read(fd, buf, sizeof(buf)));
// We only operate on 512-byte sector sizes
if (fat12_read_u16(buf + 0x0b) != 512) {
return -2;
}
// We require the cluster size to be 4096 (8 * 512)
if (buf[0x0d] != 8) {
return -2;
}
// To ensure the erase block is correct, require 4096-bytes
// of reserved data
if (fat12_read_u16(buf + 0x0e) != 4096) {
return -2;
}
// Also, we only support 1 FAT
if (buf[0x10] != 1) {
return -2;
}
// 32 root entries keeps it padded correctly.
if (fat12_read_u16(mbr + 0x11, 32) != 32) {
return -2;
}
// Total number of 512-byte sectors
fat12_write_u16(mbr + 0x13, bytes / sector_size);
return 0;
}