Duncan Laurie | c88c54c | 2014-04-30 16:36:13 -0700 | [diff] [blame] | 1 | /* |
| 2 | * This file is part of the coreboot project. |
| 3 | * |
| 4 | * Copyright (C) 2014 Google Inc. |
| 5 | * |
| 6 | * This program is free software; you can redistribute it and/or modify |
| 7 | * it under the terms of the GNU General Public License as published by |
| 8 | * the Free Software Foundation; version 2 of the License. |
| 9 | * |
| 10 | * This program is distributed in the hope that it will be useful, |
| 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | * GNU General Public License for more details. |
Duncan Laurie | c88c54c | 2014-04-30 16:36:13 -0700 | [diff] [blame] | 14 | */ |
| 15 | |
| 16 | #include <stdint.h> |
| 17 | #include <cpu/x86/msr.h> |
| 18 | #include <timer.h> |
Julius Werner | 4ee4bd5 | 2014-10-20 13:46:39 -0700 | [diff] [blame] | 19 | #include <soc/msr.h> |
Duncan Laurie | c88c54c | 2014-04-30 16:36:13 -0700 | [diff] [blame] | 20 | |
| 21 | static struct monotonic_counter { |
| 22 | int initialized; |
| 23 | struct mono_time time; |
| 24 | uint32_t last_value; |
| 25 | } mono_counter; |
| 26 | |
| 27 | static inline uint32_t read_counter_msr(void) |
| 28 | { |
| 29 | /* Even though the MSR is 64-bit it is assumed that the hardware |
| 30 | * is polled frequently enough to only use the lower 32-bits. */ |
| 31 | msr_t counter_msr; |
| 32 | |
| 33 | counter_msr = rdmsr(MSR_COUNTER_24_MHZ); |
| 34 | |
| 35 | return counter_msr.lo; |
| 36 | } |
| 37 | |
| 38 | void timer_monotonic_get(struct mono_time *mt) |
| 39 | { |
| 40 | uint32_t current_tick; |
| 41 | uint32_t usecs_elapsed; |
| 42 | |
| 43 | if (!mono_counter.initialized) { |
| 44 | mono_counter.last_value = read_counter_msr(); |
| 45 | mono_counter.initialized = 1; |
| 46 | } |
| 47 | |
| 48 | current_tick = read_counter_msr(); |
| 49 | usecs_elapsed = (current_tick - mono_counter.last_value) / 24; |
| 50 | |
| 51 | /* Update current time and tick values only if a full tick occurred. */ |
| 52 | if (usecs_elapsed) { |
| 53 | mono_time_add_usecs(&mono_counter.time, usecs_elapsed); |
| 54 | mono_counter.last_value = current_tick; |
| 55 | } |
| 56 | |
| 57 | /* Save result. */ |
| 58 | *mt = mono_counter.time; |
| 59 | } |