xref: /cloud-hypervisor/devices/src/legacy/cmos.rs (revision 2571e59438597f53aa4993cd70d6462fe1364ba7)
1 // Copyright 2017 The Chromium OS Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 use libc::{clock_gettime, gmtime_r, timespec, tm, CLOCK_REALTIME};
6 use std::cmp::min;
7 use std::mem;
8 use std::sync::atomic::{AtomicBool, Ordering};
9 use std::sync::{Arc, Barrier};
10 use std::thread;
11 use vm_device::BusDevice;
12 use vmm_sys_util::eventfd::EventFd;
13 
14 // https://github.com/rust-lang/libc/issues/1848
15 #[cfg_attr(target_env = "musl", allow(deprecated))]
16 use libc::time_t;
17 
18 const INDEX_MASK: u8 = 0x7f;
19 const INDEX_OFFSET: u64 = 0x0;
20 const DATA_OFFSET: u64 = 0x1;
21 const DATA_LEN: usize = 128;
22 
23 /// A CMOS/RTC device commonly seen on x86 I/O port 0x70/0x71.
24 pub struct Cmos {
25     index: u8,
26     data: [u8; DATA_LEN],
27     reset_evt: EventFd,
28     vcpus_kill_signalled: Option<Arc<AtomicBool>>,
29 }
30 
31 impl Cmos {
32     /// Constructs a CMOS/RTC device with initial data.
33     /// `mem_below_4g` is the size of memory in bytes below the 32-bit gap.
34     /// `mem_above_4g` is the size of memory in bytes above the 32-bit gap.
35     pub fn new(
36         mem_below_4g: u64,
37         mem_above_4g: u64,
38         reset_evt: EventFd,
39         vcpus_kill_signalled: Option<Arc<AtomicBool>>,
40     ) -> Cmos {
41         let mut data = [0u8; DATA_LEN];
42 
43         // Extended memory from 16 MB to 4 GB in units of 64 KB
44         let ext_mem = min(
45             0xFFFF,
46             mem_below_4g.saturating_sub(16 * 1024 * 1024) / (64 * 1024),
47         );
48         data[0x34] = ext_mem as u8;
49         data[0x35] = (ext_mem >> 8) as u8;
50 
51         // High memory (> 4GB) in units of 64 KB
52         let high_mem = min(0x00FF_FFFF, mem_above_4g / (64 * 1024));
53         data[0x5b] = high_mem as u8;
54         data[0x5c] = (high_mem >> 8) as u8;
55         data[0x5d] = (high_mem >> 16) as u8;
56 
57         Cmos {
58             index: 0,
59             data,
60             reset_evt,
61             vcpus_kill_signalled,
62         }
63     }
64 }
65 
66 impl BusDevice for Cmos {
67     fn write(&mut self, _base: u64, offset: u64, data: &[u8]) -> Option<Arc<Barrier>> {
68         if data.len() != 1 {
69             warn!("Invalid write size on CMOS device: {}", data.len());
70             return None;
71         }
72 
73         match offset {
74             INDEX_OFFSET => self.index = data[0],
75             DATA_OFFSET => {
76                 if self.index == 0x8f && data[0] == 0 {
77                     info!("CMOS reset");
78                     self.reset_evt.write(1).unwrap();
79                     if let Some(vcpus_kill_signalled) = self.vcpus_kill_signalled.take() {
80                         // Spin until we are sure the reset_evt has been handled and that when
81                         // we return from the KVM_RUN we will exit rather than re-enter the guest.
82                         while !vcpus_kill_signalled.load(Ordering::SeqCst) {
83                             // This is more effective than thread::yield_now() at
84                             // avoiding a priority inversion with the VMM thread
85                             thread::sleep(std::time::Duration::from_millis(1));
86                         }
87                     }
88                 } else {
89                     self.data[(self.index & INDEX_MASK) as usize] = data[0]
90                 }
91             }
92             o => warn!("bad write offset on CMOS device: {}", o),
93         };
94         None
95     }
96 
97     fn read(&mut self, _base: u64, offset: u64, data: &mut [u8]) {
98         fn to_bcd(v: u8) -> u8 {
99             assert!(v < 100);
100             ((v / 10) << 4) | (v % 10)
101         }
102 
103         if data.len() != 1 {
104             warn!("Invalid read size on CMOS device: {}", data.len());
105             return;
106         }
107 
108         data[0] = match offset {
109             INDEX_OFFSET => self.index,
110             DATA_OFFSET => {
111                 let seconds;
112                 let minutes;
113                 let hours;
114                 let week_day;
115                 let day;
116                 let month;
117                 let year;
118                 // SAFETY: The clock_gettime and gmtime_r calls are safe as long as the structs they are
119                 // given are large enough, and neither of them fail. It is safe to zero initialize
120                 // the tm and timespec struct because it contains only plain data.
121                 let update_in_progress = unsafe {
122                     let mut timespec: timespec = mem::zeroed();
123                     clock_gettime(CLOCK_REALTIME, &mut timespec as *mut _);
124 
125                     // https://github.com/rust-lang/libc/issues/1848
126                     #[cfg_attr(target_env = "musl", allow(deprecated))]
127                     let now: time_t = timespec.tv_sec;
128                     let mut tm: tm = mem::zeroed();
129                     gmtime_r(&now, &mut tm as *mut _);
130 
131                     // The following lines of code are safe but depend on tm being in scope.
132                     seconds = tm.tm_sec;
133                     minutes = tm.tm_min;
134                     hours = tm.tm_hour;
135                     week_day = tm.tm_wday + 1;
136                     day = tm.tm_mday;
137                     month = tm.tm_mon + 1;
138                     year = tm.tm_year;
139 
140                     // Update in Progress bit held for last 224us of each second
141                     const NANOSECONDS_PER_SECOND: i64 = 1_000_000_000;
142                     const UIP_HOLD_LENGTH: i64 = 8 * NANOSECONDS_PER_SECOND / 32768;
143                     timespec.tv_nsec >= (NANOSECONDS_PER_SECOND - UIP_HOLD_LENGTH)
144                 };
145                 match self.index {
146                     0x00 => to_bcd(seconds as u8),
147                     0x02 => to_bcd(minutes as u8),
148                     0x04 => to_bcd(hours as u8),
149                     0x06 => to_bcd(week_day as u8),
150                     0x07 => to_bcd(day as u8),
151                     0x08 => to_bcd(month as u8),
152                     0x09 => to_bcd((year % 100) as u8),
153                     // Bit 5 for 32kHz clock. Bit 7 for Update in Progress
154                     0x0a => 1 << 5 | (update_in_progress as u8) << 7,
155                     // Bit 0-6 are reserved and must be 0.
156                     // Bit 7 must be 1 (CMOS has power)
157                     0x0d => 1 << 7,
158                     0x32 => to_bcd(((year + 1900) / 100) as u8),
159                     _ => {
160                         // self.index is always guaranteed to be in range via INDEX_MASK.
161                         self.data[(self.index & INDEX_MASK) as usize]
162                     }
163                 }
164             }
165             o => {
166                 warn!("bad read offset on CMOS device: {}", o);
167                 0
168             }
169         }
170     }
171 }
172