118 lines
2.0 KiB
C
118 lines
2.0 KiB
C
#include <types.h>
|
|
#include <string.h>
|
|
#include <stdlib.h>
|
|
#include <math.h>
|
|
#include <drivers/ide.h>
|
|
|
|
#include <fs/ssfs.h>
|
|
|
|
|
|
|
|
#define SSFS_START_LBA 16
|
|
#define SSFS_FILE_HEADER_SIZE_BYTES 32
|
|
|
|
|
|
int ssfs_read_file(const char* name, void* buffer, int size)
|
|
{
|
|
if (strlen(name) > 15)
|
|
{
|
|
return -1;
|
|
}
|
|
|
|
uint8_t header_buf[512];
|
|
int r = read_sector(16, header_buf);
|
|
|
|
if (r != 0)
|
|
{
|
|
return -2;
|
|
}
|
|
|
|
ssfs_file_header_t f;
|
|
memcpy(&f, header_buf, sizeof(f));
|
|
|
|
if (strncmp(f.filename, name, 15) != 0)
|
|
{
|
|
return -3;
|
|
}
|
|
|
|
/* Clamp read size to actual file size */
|
|
if (size > (int)f.num_bytes)
|
|
size = (int)f.num_bytes;
|
|
|
|
int total_read = 0;
|
|
int sector_count = div_round_up(size, 512);
|
|
uint8_t sector_data[512];
|
|
|
|
for (int k = 0; k < sector_count; k++)
|
|
{
|
|
r = read_sector(f.start_sector + k, sector_data);
|
|
|
|
if (r != 0)
|
|
{
|
|
return -4; /* I/O error */
|
|
}
|
|
|
|
int to_copy = size - total_read;
|
|
|
|
if (to_copy > 512)
|
|
{
|
|
to_copy = 512;
|
|
}
|
|
|
|
memcpy((uint8_t*)buffer + total_read, sector_data, to_copy);
|
|
total_read += to_copy;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
|
|
/* size is number of bytes */
|
|
int ssfs_write_file(const char* name, void* data, int size)
|
|
{
|
|
ssfs_file_header_t* f = (ssfs_file_header_t*) malloc(sizeof(ssfs_file_header_t));
|
|
memset(f, 0, sizeof(ssfs_file_header_t));
|
|
|
|
if (strlen(name) > 15)
|
|
{
|
|
return -1;
|
|
}
|
|
|
|
strcpy(f->filename, name);
|
|
f->num_sectors = 0;
|
|
|
|
int sector_count = div_round_up(size, 512);
|
|
|
|
uint8_t* buffer = (uint8_t*) malloc(sector_count * 512);
|
|
|
|
memset(buffer, 0, sector_count * 512);
|
|
memcpy(buffer, data, (size_t) size);
|
|
|
|
int r = 0;
|
|
|
|
f->start_sector = 32;
|
|
|
|
for (int k = 0; k < sector_count; k++)
|
|
{
|
|
r = write_sector(f->start_sector + k, buffer + (k * 512));
|
|
|
|
if (r != 0)
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
|
|
f->num_sectors = sector_count;
|
|
f->num_bytes = (uint32_t) size;
|
|
|
|
uint8_t header_buf[512];
|
|
memset(header_buf, 0, 512);
|
|
memcpy(header_buf, f, sizeof(*f));
|
|
write_sector(16, header_buf);
|
|
|
|
free(buffer);
|
|
free(f);
|
|
|
|
return 0;
|
|
}
|