#include #include #include #include "dcpu16.h" #include "hw_clock.h" #define MSG_(__level__, __vm__, ...) do { ((__vm__) ? ((struct dcpu16 *)(__vm__))->msg_cb_ : dcpu16_msg_)(__level__, __VA_ARGS__); } while (0) #define MSG_INFO(__vm__, ...) MSG_(DCPU16_MSG_INFO, __vm__, __VA_ARGS__) #define MSG_ERROR(__vm__, ...) MSG_(DCPU16_MSG_ERROR, __vm__, __VA_ARGS__) #ifdef DEBUG #define MSG_DEBUG(__vm__, ...) MSG_(DCPU16_MSG_DEBUG, __vm__, __VA_ARGS__) #else /* DEBUG */ #define MSG_DEBUG(__vm__, ...) do { } while (0) #endif /* DEBUG */ struct clock_ { DCPU16_WORD cycle_; DCPU16_WORD rate; DCPU16_WORD tick; DCPU16_WORD interrupt_message; }; static void clock_reset_(struct dcpu16 *vm, struct dcpu16_hw *hw) { struct clock_ *clock = (struct clock_ *)hw->data; (void)vm; memset(clock, 0, sizeof *clock); } static void clock_cycle_(struct dcpu16 *vm, struct dcpu16_hw *hw) { struct clock_ *clock = (struct clock_ *)hw->data; /* cycle is only called 100000 times per second */ /* maximum rate is 60hz / word_max = 3932160 */ if (clock->rate == 0) return; clock->cycle_++; if (clock->cycle_ >= clock->rate) { /* THIS CHECK IS WRONG, JUST A PLACEHOLDER */ clock->cycle_ = 0; clock->tick += 1; if (clock->interrupt_message) { if (dcpu16_interrupt(vm, clock->interrupt_message)) MSG_ERROR(vm, "%s: could not send interrupt", hw->mod->name_); } } } static void clock_hwi_(struct dcpu16 *vm, struct dcpu16_hw *hw) { struct clock_ *clock = (struct clock_ *)hw->data; DCPU16_WORD reg_a = vm->reg[DCPU16_REG_A]; DCPU16_WORD reg_b = vm->reg[DCPU16_REG_B]; switch (reg_a) { case 0: /* set tick gather rate, 60hz/B */ clock->rate = reg_b; break; case 1: /* fetch elapsed count since rate was set */ vm->reg[DCPU16_REG_C] = clock->tick; break; case 2: clock->interrupt_message = reg_b; break; } } static int clock_data_init_(struct dcpu16_hw *hw, void *data) { (void)data; hw->data = calloc(1, sizeof(struct clock_)); if (hw->data == NULL) { MSG_ERROR(hw->vm, "%s():%s", "calloc", strerror(errno)); return -1; } return 0; } static void clock_data_free_(struct dcpu16_hw *hw) { if (hw) { if (hw->data) { free(hw->data); hw->data = NULL; } } } struct dcpu16_hw_module dcpu16_hw_module_clock = { .name_ = "Generic Clock (compatible)", .id_l = 0xb402, .id_h = 0x12d0, .ver = 0x0001, .mfg_l = 0x0000, .mfg_h = 0x0000, .hwi = clock_hwi_, .cycle = clock_cycle_, .reset = clock_reset_, .data_init = clock_data_init_, .data_free = clock_data_free_, .ctl = NULL, .ctl_cmd = NULL, };