xref: /cloud-hypervisor/devices/src/legacy/rtc_pl031.rs (revision 3f8cd52ffd74627242cb7e8ea1c2bdedadf6741a)
1 // Copyright 2020 Arm Limited (or its affiliates). All rights reserved.
2 // Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 // SPDX-License-Identifier: Apache-2.0
4 
5 //! ARM PL031 Real Time Clock
6 //!
7 //! This module implements a PL031 Real Time Clock (RTC) that provides to provides long time base counter.
8 //! This is achieved by generating an interrupt signal after counting for a programmed number of cycles of
9 //! a real-time clock input.
10 //!
11 use crate::{read_le_u32, write_le_u32};
12 use std::fmt;
13 use std::sync::{Arc, Barrier};
14 use std::time::Instant;
15 use std::{io, result};
16 use vm_device::interrupt::InterruptSourceGroup;
17 use vm_device::BusDevice;
18 
19 // As you can see in https://static.docs.arm.com/ddi0224/c/real_time_clock_pl031_r1p3_technical_reference_manual_DDI0224C.pdf
20 // at section 3.2 Summary of RTC registers, the total size occupied by this device is 0x000 -> 0xFFC + 4 = 0x1000.
21 // From 0x0 to 0x1C we have following registers:
22 const RTCDR: u64 = 0x0; // Data Register.
23 const RTCMR: u64 = 0x4; // Match Register.
24 const RTCLR: u64 = 0x8; // Load Register.
25 const RTCCR: u64 = 0xc; // Control Register.
26 const RTCIMSC: u64 = 0x10; // Interrupt Mask Set or Clear Register.
27 const RTCRIS: u64 = 0x14; // Raw Interrupt Status.
28 const RTCMIS: u64 = 0x18; // Masked Interrupt Status.
29 const RTCICR: u64 = 0x1c; // Interrupt Clear Register.
30                           // From 0x020 to 0xFDC => reserved space.
31                           // From 0xFE0 to 0x1000 => Peripheral and PrimeCell Identification Registers which are Read Only registers.
32                           // AMBA standard devices have CIDs (Cell IDs) and PIDs (Peripheral IDs). The linux kernel will look for these in order to assert the identity
33                           // of these devices (i.e look at the `amba_device_try_add` function).
34                           // We are putting the expected values (look at 'Reset value' column from above mentioned document) in an array.
35 const PL031_ID: [u8; 8] = [0x31, 0x10, 0x14, 0x00, 0x0d, 0xf0, 0x05, 0xb1];
36 // We are only interested in the margins.
37 const AMBA_ID_LOW: u64 = 0xFE0;
38 const AMBA_ID_HIGH: u64 = 0x1000;
39 /// Constant to convert seconds to nanoseconds.
40 pub const NANOS_PER_SECOND: u64 = 1_000_000_000;
41 
42 #[derive(Debug)]
43 pub enum Error {
44     BadWriteOffset(u64),
45     InterruptFailure(io::Error),
46 }
47 
48 impl fmt::Display for Error {
49     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
50         match self {
51             Error::BadWriteOffset(offset) => write!(f, "Bad Write Offset: {offset}"),
52             Error::InterruptFailure(e) => write!(f, "Failed to trigger interrupt: {e}"),
53         }
54     }
55 }
56 
57 type Result<T> = result::Result<T, Error>;
58 
59 /// Wrapper over `libc::clockid_t` to specify Linux Kernel clock source.
60 pub enum ClockType {
61     /// Equivalent to `libc::CLOCK_MONOTONIC`.
62     Monotonic,
63     /// Equivalent to `libc::CLOCK_REALTIME`.
64     Real,
65     /// Equivalent to `libc::CLOCK_PROCESS_CPUTIME_ID`.
66     ProcessCpu,
67     /// Equivalent to `libc::CLOCK_THREAD_CPUTIME_ID`.
68     ThreadCpu,
69 }
70 
71 impl From<ClockType> for libc::clockid_t {
72     fn from(ct: ClockType) -> libc::clockid_t {
73         match ct {
74             ClockType::Monotonic => libc::CLOCK_MONOTONIC,
75             ClockType::Real => libc::CLOCK_REALTIME,
76             ClockType::ProcessCpu => libc::CLOCK_PROCESS_CPUTIME_ID,
77             ClockType::ThreadCpu => libc::CLOCK_THREAD_CPUTIME_ID,
78         }
79     }
80 }
81 
82 /// Structure representing the date in local time with nanosecond precision.
83 pub struct LocalTime {
84     /// Seconds in current minute.
85     sec: i32,
86     /// Minutes in current hour.
87     min: i32,
88     /// Hours in current day, 24H format.
89     hour: i32,
90     /// Days in current month.
91     mday: i32,
92     /// Months in current year.
93     mon: i32,
94     /// Years passed since 1900 BC.
95     year: i32,
96     /// Nanoseconds in current second.
97     nsec: i64,
98 }
99 
100 impl LocalTime {
101     /// Returns the [LocalTime](struct.LocalTime.html) structure for the calling moment.
102     #[cfg(test)]
103     pub fn now() -> LocalTime {
104         let mut timespec = libc::timespec {
105             tv_sec: 0,
106             tv_nsec: 0,
107         };
108         let mut tm: libc::tm = libc::tm {
109             tm_sec: 0,
110             tm_min: 0,
111             tm_hour: 0,
112             tm_mday: 0,
113             tm_mon: 0,
114             tm_year: 0,
115             tm_wday: 0,
116             tm_yday: 0,
117             tm_isdst: 0,
118             tm_gmtoff: 0,
119             tm_zone: std::ptr::null(),
120         };
121 
122         // SAFETY: the parameters are valid.
123         unsafe {
124             libc::clock_gettime(libc::CLOCK_REALTIME, &mut timespec);
125             libc::localtime_r(&timespec.tv_sec, &mut tm);
126         }
127 
128         LocalTime {
129             sec: tm.tm_sec,
130             min: tm.tm_min,
131             hour: tm.tm_hour,
132             mday: tm.tm_mday,
133             mon: tm.tm_mon,
134             year: tm.tm_year,
135             nsec: timespec.tv_nsec,
136         }
137     }
138 }
139 
140 impl fmt::Display for LocalTime {
141     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142         write!(
143             f,
144             "{}-{:02}-{:02}T{:02}:{:02}:{:02}.{:09}",
145             self.year + 1900,
146             self.mon + 1,
147             self.mday,
148             self.hour,
149             self.min,
150             self.sec,
151             self.nsec
152         )
153     }
154 }
155 
156 /// Returns a timestamp in nanoseconds based on the provided clock type.
157 ///
158 /// # Arguments
159 ///
160 /// * `clock_type` - Identifier of the Linux Kernel clock on which to act.
161 pub fn get_time(clock_type: ClockType) -> u64 {
162     let mut time_struct = libc::timespec {
163         tv_sec: 0,
164         tv_nsec: 0,
165     };
166     // SAFETY: the parameters are valid.
167     unsafe { libc::clock_gettime(clock_type.into(), &mut time_struct) };
168     seconds_to_nanoseconds(time_struct.tv_sec).unwrap() as u64 + (time_struct.tv_nsec as u64)
169 }
170 
171 /// Converts a timestamp in seconds to an equivalent one in nanoseconds.
172 /// Returns `None` if the conversion overflows.
173 ///
174 /// # Arguments
175 ///
176 /// * `value` - Timestamp in seconds.
177 pub fn seconds_to_nanoseconds(value: i64) -> Option<i64> {
178     value.checked_mul(NANOS_PER_SECOND as i64)
179 }
180 
181 /// A RTC device following the PL031 specification..
182 pub struct Rtc {
183     previous_now: Instant,
184     tick_offset: i64,
185     // This is used for implementing the RTC alarm. However, in Firecracker we do not need it.
186     match_value: u32,
187     // Writes to this register load an update value into the RTC.
188     load: u32,
189     imsc: u32,
190     ris: u32,
191     interrupt: Arc<dyn InterruptSourceGroup>,
192 }
193 
194 impl Rtc {
195     /// Constructs an AMBA PL031 RTC device.
196     pub fn new(interrupt: Arc<dyn InterruptSourceGroup>) -> Self {
197         Self {
198             // This is used only for duration measuring purposes.
199             previous_now: Instant::now(),
200             tick_offset: get_time(ClockType::Real) as i64,
201             match_value: 0,
202             load: 0,
203             imsc: 0,
204             ris: 0,
205             interrupt,
206         }
207     }
208 
209     fn trigger_interrupt(&mut self) -> Result<()> {
210         self.interrupt.trigger(0).map_err(Error::InterruptFailure)?;
211         Ok(())
212     }
213 
214     fn get_time(&self) -> u32 {
215         let ts = (self.tick_offset as i128)
216             + (Instant::now().duration_since(self.previous_now).as_nanos() as i128);
217         (ts / NANOS_PER_SECOND as i128) as u32
218     }
219 
220     fn handle_write(&mut self, offset: u64, val: u32) -> Result<()> {
221         match offset {
222             RTCMR => {
223                 // The MR register is used for implementing the RTC alarm. A real time clock alarm is
224                 // a feature that can be used to allow a computer to 'wake up' after shut down to execute
225                 // tasks every day or on a certain day. It can sometimes be found in the 'Power Management'
226                 // section of a motherboard's BIOS setup. This is functionality that extends beyond
227                 // Firecracker intended use. However, we increment a metric just in case.
228                 self.match_value = val;
229             }
230             RTCLR => {
231                 self.load = val;
232                 self.previous_now = Instant::now();
233                 // If the unwrap fails, then the internal value of the clock has been corrupted and
234                 // we want to terminate the execution of the process.
235                 self.tick_offset = seconds_to_nanoseconds(i64::from(val)).unwrap();
236             }
237             RTCIMSC => {
238                 self.imsc = val & 1;
239                 self.trigger_interrupt()?;
240             }
241             RTCICR => {
242                 // As per above mentioned doc, the interrupt is cleared by writing any data value to
243                 // the Interrupt Clear Register.
244                 self.ris = 0;
245                 self.trigger_interrupt()?;
246             }
247             RTCCR => (), // ignore attempts to turn off the timer.
248             o => {
249                 return Err(Error::BadWriteOffset(o));
250             }
251         }
252         Ok(())
253     }
254 }
255 
256 impl BusDevice for Rtc {
257     fn read(&mut self, _base: u64, offset: u64, data: &mut [u8]) {
258         let mut read_ok = true;
259 
260         let v = if (AMBA_ID_LOW..AMBA_ID_HIGH).contains(&offset) {
261             let index = ((offset - AMBA_ID_LOW) >> 2) as usize;
262             u32::from(PL031_ID[index])
263         } else {
264             match offset {
265                 RTCDR => self.get_time(),
266                 RTCMR => {
267                     // Even though we are not implementing RTC alarm we return the last value
268                     self.match_value
269                 }
270                 RTCLR => self.load,
271                 RTCCR => 1, // RTC is always enabled.
272                 RTCIMSC => self.imsc,
273                 RTCRIS => self.ris,
274                 RTCMIS => self.ris & self.imsc,
275                 _ => {
276                     read_ok = false;
277                     0
278                 }
279             }
280         };
281         if read_ok && data.len() <= 4 {
282             write_le_u32(data, v);
283         } else {
284             warn!(
285                 "Invalid RTC PL031 read: offset {}, data length {}",
286                 offset,
287                 data.len()
288             );
289         }
290     }
291 
292     fn write(&mut self, _base: u64, offset: u64, data: &[u8]) -> Option<Arc<Barrier>> {
293         if data.len() <= 4 {
294             let v = read_le_u32(data);
295             if let Err(e) = self.handle_write(offset, v) {
296                 warn!("Failed to write to RTC PL031 device: {}", e);
297             }
298         } else {
299             warn!(
300                 "Invalid RTC PL031 write: offset {}, data length {}",
301                 offset,
302                 data.len()
303             );
304         }
305 
306         None
307     }
308 }
309 
310 #[cfg(test)]
311 mod tests {
312     use super::*;
313     use crate::{
314         read_be_u16, read_be_u32, read_le_i32, read_le_u16, read_le_u64, write_be_u16,
315         write_be_u32, write_le_i32, write_le_u16, write_le_u64,
316     };
317     use vm_device::interrupt::{InterruptIndex, InterruptSourceConfig};
318     use vmm_sys_util::eventfd::EventFd;
319 
320     const LEGACY_RTC_MAPPED_IO_START: u64 = 0x0901_0000;
321 
322     #[test]
323     fn test_get_time() {
324         for _ in 0..1000 {
325             assert!(get_time(ClockType::Monotonic) <= get_time(ClockType::Monotonic));
326         }
327 
328         for _ in 0..1000 {
329             assert!(get_time(ClockType::ProcessCpu) <= get_time(ClockType::ProcessCpu));
330         }
331 
332         for _ in 0..1000 {
333             assert!(get_time(ClockType::ThreadCpu) <= get_time(ClockType::ThreadCpu));
334         }
335 
336         assert_ne!(get_time(ClockType::Real), 0);
337     }
338 
339     #[test]
340     fn test_local_time_display() {
341         let local_time = LocalTime {
342             sec: 30,
343             min: 15,
344             hour: 10,
345             mday: 4,
346             mon: 6,
347             year: 119,
348             nsec: 123_456_789,
349         };
350         assert_eq!(
351             String::from("2019-07-04T10:15:30.123456789"),
352             local_time.to_string()
353         );
354 
355         let local_time = LocalTime {
356             sec: 5,
357             min: 5,
358             hour: 5,
359             mday: 23,
360             mon: 7,
361             year: 44,
362             nsec: 123,
363         };
364         assert_eq!(
365             String::from("1944-08-23T05:05:05.000000123"),
366             local_time.to_string()
367         );
368 
369         let local_time = LocalTime::now();
370         assert!(local_time.mon >= 0 && local_time.mon <= 11);
371     }
372 
373     #[test]
374     fn test_seconds_to_nanoseconds() {
375         assert_eq!(
376             seconds_to_nanoseconds(100).unwrap() as u64,
377             100 * NANOS_PER_SECOND
378         );
379 
380         assert!(seconds_to_nanoseconds(9_223_372_037).is_none());
381     }
382 
383     struct TestInterrupt {
384         event_fd: EventFd,
385     }
386 
387     impl InterruptSourceGroup for TestInterrupt {
388         fn trigger(&self, _index: InterruptIndex) -> result::Result<(), std::io::Error> {
389             self.event_fd.write(1)
390         }
391 
392         fn update(
393             &self,
394             _index: InterruptIndex,
395             _config: InterruptSourceConfig,
396             _masked: bool,
397             _set_gsi: bool,
398         ) -> result::Result<(), std::io::Error> {
399             Ok(())
400         }
401 
402         fn set_gsi(&self) -> result::Result<(), std::io::Error> {
403             Ok(())
404         }
405 
406         fn notifier(&self, _index: InterruptIndex) -> Option<EventFd> {
407             Some(self.event_fd.try_clone().unwrap())
408         }
409     }
410 
411     impl TestInterrupt {
412         fn new(event_fd: EventFd) -> Self {
413             TestInterrupt { event_fd }
414         }
415     }
416 
417     #[test]
418     fn test_rtc_read_write_and_event() {
419         let intr_evt = EventFd::new(libc::EFD_NONBLOCK).unwrap();
420 
421         let mut rtc = Rtc::new(Arc::new(TestInterrupt::new(intr_evt.try_clone().unwrap())));
422         let mut data = [0; 4];
423 
424         // Read and write to the MR register.
425         write_le_u32(&mut data, 123);
426         rtc.write(LEGACY_RTC_MAPPED_IO_START, RTCMR, &data);
427         rtc.read(LEGACY_RTC_MAPPED_IO_START, RTCMR, &mut data);
428         let v = read_le_u32(&data);
429         assert_eq!(v, 123);
430 
431         // Read and write to the LR register.
432         let v = get_time(ClockType::Real);
433         write_le_u32(&mut data, (v / NANOS_PER_SECOND) as u32);
434         let previous_now_before = rtc.previous_now;
435         rtc.write(LEGACY_RTC_MAPPED_IO_START, RTCLR, &data);
436 
437         assert!(rtc.previous_now > previous_now_before);
438 
439         rtc.read(LEGACY_RTC_MAPPED_IO_START, RTCLR, &mut data);
440         let v_read = read_le_u32(&data);
441         assert_eq!((v / NANOS_PER_SECOND) as u32, v_read);
442 
443         // Read and write to IMSC register.
444         // Test with non zero value.
445         let non_zero = 1;
446         write_le_u32(&mut data, non_zero);
447         rtc.write(LEGACY_RTC_MAPPED_IO_START, RTCIMSC, &data);
448         // The interrupt line should be on.
449         assert!(rtc.interrupt.notifier(0).unwrap().read().unwrap() == 1);
450         rtc.read(LEGACY_RTC_MAPPED_IO_START, RTCIMSC, &mut data);
451         let v = read_le_u32(&data);
452         assert_eq!(non_zero & 1, v);
453 
454         // Now test with 0.
455         write_le_u32(&mut data, 0);
456         rtc.write(LEGACY_RTC_MAPPED_IO_START, RTCIMSC, &data);
457         rtc.read(LEGACY_RTC_MAPPED_IO_START, RTCIMSC, &mut data);
458         let v = read_le_u32(&data);
459         assert_eq!(0, v);
460 
461         // Read and write to the ICR register.
462         write_le_u32(&mut data, 1);
463         rtc.write(LEGACY_RTC_MAPPED_IO_START, RTCICR, &data);
464         // The interrupt line should be on.
465         assert!(rtc.interrupt.notifier(0).unwrap().read().unwrap() > 1);
466         let v_before = read_le_u32(&data);
467 
468         rtc.read(LEGACY_RTC_MAPPED_IO_START, RTCICR, &mut data);
469         let v = read_le_u32(&data);
470         // ICR is a  write only register. Data received should stay equal to data sent.
471         assert_eq!(v, v_before);
472 
473         // Attempts to turn off the RTC should not go through.
474         write_le_u32(&mut data, 0);
475         rtc.write(LEGACY_RTC_MAPPED_IO_START, RTCCR, &data);
476         rtc.read(LEGACY_RTC_MAPPED_IO_START, RTCCR, &mut data);
477         let v = read_le_u32(&data);
478         assert_eq!(v, 1);
479 
480         // Attempts to write beyond the writable space. Using here the space used to read
481         // the CID and PID from.
482         write_le_u32(&mut data, 0);
483         rtc.write(LEGACY_RTC_MAPPED_IO_START, AMBA_ID_LOW, &data);
484         // However, reading from the AMBA_ID_LOW should succeed upon read.
485 
486         let mut data = [0; 4];
487         rtc.read(LEGACY_RTC_MAPPED_IO_START, AMBA_ID_LOW, &mut data);
488         let index = AMBA_ID_LOW + 3;
489         assert_eq!(data[0], PL031_ID[((index - AMBA_ID_LOW) >> 2) as usize]);
490     }
491 
492     macro_rules! byte_order_test_read_write {
493         ($test_name: ident, $write_fn_name: ident, $read_fn_name: ident, $is_be: expr, $data_type: ty) => {
494             #[test]
495             fn $test_name() {
496                 let test_cases = [
497                     (
498                         0x0123_4567_89AB_CDEF as u64,
499                         [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef],
500                     ),
501                     (
502                         0x0000_0000_0000_0000 as u64,
503                         [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
504                     ),
505                     (
506                         0x1923_2345_ABF3_CCD4 as u64,
507                         [0x19, 0x23, 0x23, 0x45, 0xAB, 0xF3, 0xCC, 0xD4],
508                     ),
509                     (
510                         0x0FF0_0FF0_0FF0_0FF0 as u64,
511                         [0x0F, 0xF0, 0x0F, 0xF0, 0x0F, 0xF0, 0x0F, 0xF0],
512                     ),
513                     (
514                         0xFFFF_FFFF_FFFF_FFFF as u64,
515                         [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF],
516                     ),
517                     (
518                         0x89AB_12D4_C2D2_09BB as u64,
519                         [0x89, 0xAB, 0x12, 0xD4, 0xC2, 0xD2, 0x09, 0xBB],
520                     ),
521                 ];
522 
523                 let type_size = std::mem::size_of::<$data_type>();
524                 for (test_val, v_arr) in &test_cases {
525                     let v = *test_val as $data_type;
526                     let cmp_iter: Box<dyn Iterator<Item = _>> = if $is_be {
527                         Box::new(v_arr[(8 - type_size)..].iter())
528                     } else {
529                         Box::new(v_arr.iter().rev())
530                     };
531                     // test write
532                     let mut write_arr = vec![Default::default(); type_size];
533                     $write_fn_name(&mut write_arr, v);
534                     for (cmp, cur) in cmp_iter.zip(write_arr.iter()) {
535                         assert_eq!(*cmp, *cur as u8)
536                     }
537                     // test read
538                     let read_val = $read_fn_name(&write_arr);
539                     assert_eq!(v, read_val);
540                 }
541             }
542         };
543     }
544 
545     byte_order_test_read_write!(test_le_u16, write_le_u16, read_le_u16, false, u16);
546     byte_order_test_read_write!(test_le_u32, write_le_u32, read_le_u32, false, u32);
547     byte_order_test_read_write!(test_le_u64, write_le_u64, read_le_u64, false, u64);
548     byte_order_test_read_write!(test_le_i32, write_le_i32, read_le_i32, false, i32);
549     byte_order_test_read_write!(test_be_u16, write_be_u16, read_be_u16, true, u16);
550     byte_order_test_read_write!(test_be_u32, write_be_u32, read_be_u32, true, u32);
551 }
552