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