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