src/state.c

Sun, 12 Dec 2010 23:47:35 +0000

author
Philip Pemberton <philpem@philpem.me.uk>
date
Sun, 12 Dec 2010 23:47:35 +0000
changeset 55
ba6b8e570062
parent 52
a350dfa92895
child 60
96f3df0b3cbb
permissions
-rw-r--r--

improve error and DMA handling

     1 #define _STATE_C
     2 #include <stddef.h>
     3 #include <malloc.h>
     4 #include <stdio.h>
     5 #include "wd279x.h"
     6 #include "state.h"
     8 int state_init(size_t ramsize)
     9 {
    10 	// Free RAM if it's allocated
    11 	if (state.ram != NULL)
    12 		free(state.ram);
    14 	// Initialise hardware registers
    15 	state.romlmap = false;
    17 	// Allocate RAM, making sure the user has specified a valid RAM amount first
    18 	// Basically: 512KiB minimum, 4MiB maximum, in increments of 512KiB.
    19 	if ((ramsize < 512*1024) || ((ramsize % (512*1024)) != 0))
    20 		return -1;
    21 	state.ram = malloc(ramsize);
    22 	if (state.ram == NULL)
    23 		return -2;
    24 	state.ram_size = ramsize;
    26 	// Load ROMs
    27 	FILE *r14c, *r15c;
    28 	r14c = fopen("roms/14c.bin", "rb");
    29 	if (r14c == NULL) {
    30 		fprintf(stderr, "[state] Error loading roms/14c.bin.\n");
    31 		return -3;
    32 	}
    33 	r15c = fopen("roms/15c.bin", "rb");
    34 	if (r15c == NULL) {
    35 		fprintf(stderr, "[state] Error loading roms/15c.bin.\n");
    36 		return -3;
    37 	}
    39 	// get ROM file size
    40 	fseek(r14c, 0, SEEK_END);
    41 	size_t romlen = ftell(r14c);
    42 	fseek(r14c, 0, SEEK_SET);
    43 	fseek(r15c, 0, SEEK_END);
    44 	size_t romlen2 = ftell(r15c);
    45 	fseek(r15c, 0, SEEK_SET);
    46 	if (romlen2 != romlen) {
    47 		fprintf(stderr, "[state] ROMs are not the same size!\n");
    48 		return -3;
    49 	}
    50 	if ((romlen + romlen2) > ROM_SIZE) {
    51 		fprintf(stderr, "[state] ROM files are too large!\n");
    52 		return -3;
    53 	}
    55 	// sanity checks completed; load the ROMs!
    56 	uint8_t *romdat1, *romdat2;
    57 	romdat1 = malloc(romlen);
    58 	romdat2 = malloc(romlen2);
    59 	fread(romdat1, 1, romlen, r15c);
    60 	fread(romdat2, 1, romlen2, r14c);
    62 	// convert the ROM data
    63 	for (size_t i=0; i<(romlen + romlen2); i+=2) {
    64 		state.rom[i+0] = romdat1[i/2];
    65 		state.rom[i+1] = romdat2[i/2];
    66 	}
    68 	// TODO: if ROM buffer not filled, repeat the ROM data we read until it is (wraparound emulation)
    70 	// free the data arrays and close the files
    71 	free(romdat1);
    72 	free(romdat2);
    73 	fclose(r14c);
    74 	fclose(r15c);
    76 	// Initialise the disc controller
    77 	wd2797_init(&state.fdc_ctx);
    79 	return 0;
    80 }
    82 void state_done()
    83 {
    84 	if (state.ram != NULL) {
    85 		free(state.ram);
    86 		state.ram = NULL;
    87 	}
    89 	// Deinitialise the disc controller
    90 	wd2797_done(&state.fdc_ctx);
    91 }