1 /* 2 * QEMU OpenRISC timer support 3 * 4 * Copyright (c) 2011-2012 Jia Liu <proljc@gmail.com> 5 * Zhizhou Zhang <etouzh@gmail.com> 6 * 7 * This library is free software; you can redistribute it and/or 8 * modify it under the terms of the GNU Lesser General Public 9 * License as published by the Free Software Foundation; either 10 * version 2 of the License, or (at your option) any later version. 11 * 12 * This library is distributed in the hope that it will be useful, 13 * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 * Lesser General Public License for more details. 16 * 17 * You should have received a copy of the GNU Lesser General Public 18 * License along with this library; if not, see <http://www.gnu.org/licenses/>. 19 */ 20 21 #include "cpu.h" 22 #include "hw/hw.h" 23 #include "qemu/timer.h" 24 25 #define TIMER_FREQ (20 * 1000 * 1000) /* 20MHz */ 26 27 /* The time when TTCR changes */ 28 static uint64_t last_clk; 29 static int is_counting; 30 31 void cpu_openrisc_count_update(OpenRISCCPU *cpu) 32 { 33 uint64_t now, next; 34 uint32_t wait; 35 36 now = qemu_get_clock_ns(vm_clock); 37 if (!is_counting) { 38 qemu_del_timer(cpu->env.timer); 39 last_clk = now; 40 return; 41 } 42 43 cpu->env.ttcr += (uint32_t)muldiv64(now - last_clk, TIMER_FREQ, 44 get_ticks_per_sec()); 45 last_clk = now; 46 47 if ((cpu->env.ttmr & TTMR_TP) <= (cpu->env.ttcr & TTMR_TP)) { 48 wait = TTMR_TP - (cpu->env.ttcr & TTMR_TP) + 1; 49 wait += cpu->env.ttmr & TTMR_TP; 50 } else { 51 wait = (cpu->env.ttmr & TTMR_TP) - (cpu->env.ttcr & TTMR_TP); 52 } 53 54 next = now + muldiv64(wait, get_ticks_per_sec(), TIMER_FREQ); 55 qemu_mod_timer(cpu->env.timer, next); 56 } 57 58 void cpu_openrisc_count_start(OpenRISCCPU *cpu) 59 { 60 is_counting = 1; 61 cpu_openrisc_count_update(cpu); 62 } 63 64 void cpu_openrisc_count_stop(OpenRISCCPU *cpu) 65 { 66 is_counting = 0; 67 cpu_openrisc_count_update(cpu); 68 } 69 70 static void openrisc_timer_cb(void *opaque) 71 { 72 OpenRISCCPU *cpu = opaque; 73 74 if ((cpu->env.ttmr & TTMR_IE) && 75 qemu_timer_expired(cpu->env.timer, qemu_get_clock_ns(vm_clock))) { 76 cpu->env.ttmr |= TTMR_IP; 77 cpu->env.interrupt_request |= CPU_INTERRUPT_TIMER; 78 } 79 80 switch (cpu->env.ttmr & TTMR_M) { 81 case TIMER_NONE: 82 break; 83 case TIMER_INTR: 84 cpu->env.ttcr = 0; 85 cpu_openrisc_count_start(cpu); 86 break; 87 case TIMER_SHOT: 88 cpu_openrisc_count_stop(cpu); 89 break; 90 case TIMER_CONT: 91 cpu_openrisc_count_start(cpu); 92 break; 93 } 94 } 95 96 void cpu_openrisc_clock_init(OpenRISCCPU *cpu) 97 { 98 cpu->env.timer = qemu_new_timer_ns(vm_clock, &openrisc_timer_cb, cpu); 99 cpu->env.ttmr = 0x00000000; 100 cpu->env.ttcr = 0x00000000; 101 } 102