]> git.proxmox.com Git - mirror_edk2.git/blob - ArmPlatformPkg/Library/PL031RealTimeClockLib/PL031RealTimeClockLib.c
ArmPlatformPkg/PL031RealTimeClockLib: Fixed the conditions in LibSetTime()
[mirror_edk2.git] / ArmPlatformPkg / Library / PL031RealTimeClockLib / PL031RealTimeClockLib.c
1 /** @file
2 Implement EFI RealTimeClock runtime services via RTC Lib.
3
4 Currently this driver does not support runtime virtual calling.
5
6 Copyright (c) 2008 - 2010, Apple Inc. All rights reserved.<BR>
7 Copyright (c) 2011-2013, ARM Ltd. All rights reserved.<BR>
8
9 This program and the accompanying materials
10 are licensed and made available under the terms and conditions of the BSD License
11 which accompanies this distribution. The full text of the license may be found at
12 http://opensource.org/licenses/bsd-license.php
13
14 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
15 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
16
17 **/
18
19 #include <Uefi.h>
20 #include <PiDxe.h>
21 #include <Library/BaseLib.h>
22 #include <Library/DebugLib.h>
23 #include <Library/UefiLib.h>
24 #include <Library/IoLib.h>
25 #include <Library/RealTimeClockLib.h>
26 #include <Library/MemoryAllocationLib.h>
27 #include <Library/PcdLib.h>
28 #include <Library/ArmPlatformSysConfigLib.h>
29 #include <Library/UefiBootServicesTableLib.h>
30 #include <Library/UefiRuntimeServicesTableLib.h>
31 #include <Protocol/RealTimeClock.h>
32 #include <Guid/GlobalVariable.h>
33 #include <Drivers/PL031RealTimeClock.h>
34
35 #include <ArmPlatform.h>
36
37 STATIC CONST CHAR16 mTimeZoneVariableName[] = L"PL031RtcTimeZone";
38 STATIC CONST CHAR16 mDaylightVariableName[] = L"PL031RtcDaylight";
39 STATIC BOOLEAN mPL031Initialized = FALSE;
40
41 EFI_STATUS
42 IdentifyPL031 (
43 VOID
44 )
45 {
46 EFI_STATUS Status;
47
48 // Check if this is a PrimeCell Peripheral
49 if ( (MmioRead8 (PL031_RTC_PCELL_ID0) != 0x0D)
50 || (MmioRead8 (PL031_RTC_PCELL_ID1) != 0xF0)
51 || (MmioRead8 (PL031_RTC_PCELL_ID2) != 0x05)
52 || (MmioRead8 (PL031_RTC_PCELL_ID3) != 0xB1)) {
53 Status = EFI_NOT_FOUND;
54 goto EXIT;
55 }
56
57 // Check if this PrimeCell Peripheral is the PL031 Real Time Clock
58 if ( (MmioRead8 (PL031_RTC_PERIPH_ID0) != 0x31)
59 || (MmioRead8 (PL031_RTC_PERIPH_ID1) != 0x10)
60 || ((MmioRead8 (PL031_RTC_PERIPH_ID2) & 0xF) != 0x04)
61 || (MmioRead8 (PL031_RTC_PERIPH_ID3) != 0x00)) {
62 Status = EFI_NOT_FOUND;
63 goto EXIT;
64 }
65
66 Status = EFI_SUCCESS;
67
68 EXIT:
69 return Status;
70 }
71
72 EFI_STATUS
73 InitializePL031 (
74 VOID
75 )
76 {
77 EFI_STATUS Status;
78
79 // Prepare the hardware
80 Status = IdentifyPL031();
81 if (EFI_ERROR (Status)) {
82 goto EXIT;
83 }
84
85 // Ensure interrupts are masked. We do not want RTC interrupts in UEFI
86 if ((MmioRead32 (PL031_RTC_IMSC_IRQ_MASK_SET_CLEAR_REGISTER) & PL031_SET_IRQ_MASK) != PL031_SET_IRQ_MASK) {
87 MmioOr32 (PL031_RTC_IMSC_IRQ_MASK_SET_CLEAR_REGISTER, PL031_SET_IRQ_MASK);
88 }
89
90 // Clear any existing interrupts
91 if ((MmioRead32 (PL031_RTC_RIS_RAW_IRQ_STATUS_REGISTER) & PL031_IRQ_TRIGGERED) == PL031_IRQ_TRIGGERED) {
92 MmioOr32 (PL031_RTC_ICR_IRQ_CLEAR_REGISTER, PL031_CLEAR_IRQ);
93 }
94
95 // Start the clock counter
96 if ((MmioRead32 (PL031_RTC_CR_CONTROL_REGISTER) & PL031_RTC_ENABLED) != PL031_RTC_ENABLED) {
97 MmioOr32 (PL031_RTC_CR_CONTROL_REGISTER, PL031_RTC_ENABLED);
98 }
99
100 mPL031Initialized = TRUE;
101
102 EXIT:
103 return Status;
104 }
105
106 /**
107 Converts Epoch seconds (elapsed since 1970 JANUARY 01, 00:00:00 UTC) to EFI_TIME
108 **/
109 VOID
110 EpochToEfiTime (
111 IN UINTN EpochSeconds,
112 OUT EFI_TIME *Time
113 )
114 {
115 UINTN a;
116 UINTN b;
117 UINTN c;
118 UINTN d;
119 UINTN g;
120 UINTN j;
121 UINTN m;
122 UINTN y;
123 UINTN da;
124 UINTN db;
125 UINTN dc;
126 UINTN dg;
127 UINTN hh;
128 UINTN mm;
129 UINTN ss;
130 UINTN J;
131
132 J = (EpochSeconds / 86400) + 2440588;
133 j = J + 32044;
134 g = j / 146097;
135 dg = j % 146097;
136 c = (((dg / 36524) + 1) * 3) / 4;
137 dc = dg - (c * 36524);
138 b = dc / 1461;
139 db = dc % 1461;
140 a = (((db / 365) + 1) * 3) / 4;
141 da = db - (a * 365);
142 y = (g * 400) + (c * 100) + (b * 4) + a;
143 m = (((da * 5) + 308) / 153) - 2;
144 d = da - (((m + 4) * 153) / 5) + 122;
145
146 Time->Year = y - 4800 + ((m + 2) / 12);
147 Time->Month = ((m + 2) % 12) + 1;
148 Time->Day = d + 1;
149
150 ss = EpochSeconds % 60;
151 a = (EpochSeconds - ss) / 60;
152 mm = a % 60;
153 b = (a - mm) / 60;
154 hh = b % 24;
155
156 Time->Hour = hh;
157 Time->Minute = mm;
158 Time->Second = ss;
159 Time->Nanosecond = 0;
160
161 }
162
163 /**
164 Converts EFI_TIME to Epoch seconds (elapsed since 1970 JANUARY 01, 00:00:00 UTC)
165 **/
166 UINTN
167 EfiTimeToEpoch (
168 IN EFI_TIME *Time
169 )
170 {
171 UINTN a;
172 UINTN y;
173 UINTN m;
174 UINTN JulianDate; // Absolute Julian Date representation of the supplied Time
175 UINTN EpochDays; // Number of days elapsed since EPOCH_JULIAN_DAY
176 UINTN EpochSeconds;
177
178 a = (14 - Time->Month) / 12 ;
179 y = Time->Year + 4800 - a;
180 m = Time->Month + (12*a) - 3;
181
182 JulianDate = Time->Day + ((153*m + 2)/5) + (365*y) + (y/4) - (y/100) + (y/400) - 32045;
183
184 ASSERT (JulianDate >= EPOCH_JULIAN_DATE);
185 EpochDays = JulianDate - EPOCH_JULIAN_DATE;
186
187 EpochSeconds = (EpochDays * SEC_PER_DAY) + ((UINTN)Time->Hour * SEC_PER_HOUR) + (Time->Minute * SEC_PER_MIN) + Time->Second;
188
189 return EpochSeconds;
190 }
191
192 BOOLEAN
193 IsLeapYear (
194 IN EFI_TIME *Time
195 )
196 {
197 if (Time->Year % 4 == 0) {
198 if (Time->Year % 100 == 0) {
199 if (Time->Year % 400 == 0) {
200 return TRUE;
201 } else {
202 return FALSE;
203 }
204 } else {
205 return TRUE;
206 }
207 } else {
208 return FALSE;
209 }
210 }
211
212 BOOLEAN
213 DayValid (
214 IN EFI_TIME *Time
215 )
216 {
217 INTN DayOfMonth[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
218
219 if (Time->Day < 1 ||
220 Time->Day > DayOfMonth[Time->Month - 1] ||
221 (Time->Month == 2 && (!IsLeapYear (Time) && Time->Day > 28))
222 ) {
223 return FALSE;
224 }
225
226 return TRUE;
227 }
228
229 /**
230 Returns the current time and date information, and the time-keeping capabilities
231 of the hardware platform.
232
233 @param Time A pointer to storage to receive a snapshot of the current time.
234 @param Capabilities An optional pointer to a buffer to receive the real time clock
235 device's capabilities.
236
237 @retval EFI_SUCCESS The operation completed successfully.
238 @retval EFI_INVALID_PARAMETER Time is NULL.
239 @retval EFI_DEVICE_ERROR The time could not be retrieved due to hardware error.
240 @retval EFI_SECURITY_VIOLATION The time could not be retrieved due to an authentication failure.
241
242 **/
243 EFI_STATUS
244 EFIAPI
245 LibGetTime (
246 OUT EFI_TIME *Time,
247 OUT EFI_TIME_CAPABILITIES *Capabilities
248 )
249 {
250 EFI_STATUS Status = EFI_SUCCESS;
251 UINT32 EpochSeconds;
252 INT16 TimeZone;
253 UINT8 Daylight;
254 UINTN Size;
255
256 // Initialize the hardware if not already done
257 if (!mPL031Initialized) {
258 Status = InitializePL031 ();
259 if (EFI_ERROR (Status)) {
260 goto EXIT;
261 }
262 }
263
264 // Snapshot the time as early in the function call as possible
265 // On some platforms we may have access to a battery backed up hardware clock.
266 // If such RTC exists try to use it first.
267 Status = ArmPlatformSysConfigGet (SYS_CFG_RTC, &EpochSeconds);
268 if (Status == EFI_UNSUPPORTED) {
269 // Battery backed up hardware RTC does not exist, revert to PL031
270 EpochSeconds = MmioRead32 (PL031_RTC_DR_DATA_REGISTER);
271 Status = EFI_SUCCESS;
272 } else if (EFI_ERROR (Status)) {
273 // Battery backed up hardware RTC exists but could not be read due to error. Abort.
274 goto EXIT;
275 } else {
276 // Battery backed up hardware RTC exists and we read the time correctly from it.
277 // Now sync the PL031 to the new time.
278 MmioWrite32 (PL031_RTC_LR_LOAD_REGISTER, EpochSeconds);
279 }
280
281 // Ensure Time is a valid pointer
282 if (Time == NULL) {
283 Status = EFI_INVALID_PARAMETER;
284 goto EXIT;
285 }
286
287 // Get the current time zone information from non-volatile storage
288 Size = sizeof (TimeZone);
289 Status = gRT->GetVariable (
290 (CHAR16 *)mTimeZoneVariableName,
291 &gEfiCallerIdGuid,
292 NULL,
293 &Size,
294 (VOID *)&TimeZone
295 );
296
297 if (EFI_ERROR (Status)) {
298 ASSERT(Status != EFI_INVALID_PARAMETER);
299 ASSERT(Status != EFI_BUFFER_TOO_SMALL);
300
301 if (Status != EFI_NOT_FOUND)
302 goto EXIT;
303
304 // The time zone variable does not exist in non-volatile storage, so create it.
305 Time->TimeZone = EFI_UNSPECIFIED_TIMEZONE;
306 // Store it
307 Status = gRT->SetVariable (
308 (CHAR16 *)mTimeZoneVariableName,
309 &gEfiCallerIdGuid,
310 EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
311 Size,
312 (VOID *)&(Time->TimeZone)
313 );
314 if (EFI_ERROR (Status)) {
315 DEBUG ((
316 EFI_D_ERROR,
317 "LibGetTime: Failed to save %s variable to non-volatile storage, Status = %r\n",
318 mTimeZoneVariableName,
319 Status
320 ));
321 goto EXIT;
322 }
323 } else {
324 // Got the time zone
325 Time->TimeZone = TimeZone;
326
327 // Check TimeZone bounds: -1440 to 1440 or 2047
328 if (((Time->TimeZone < -1440) || (Time->TimeZone > 1440))
329 && (Time->TimeZone != EFI_UNSPECIFIED_TIMEZONE)) {
330 Time->TimeZone = EFI_UNSPECIFIED_TIMEZONE;
331 }
332
333 // Adjust for the correct time zone
334 if (Time->TimeZone != EFI_UNSPECIFIED_TIMEZONE) {
335 EpochSeconds += Time->TimeZone * SEC_PER_MIN;
336 }
337 }
338
339 // Get the current daylight information from non-volatile storage
340 Size = sizeof (Daylight);
341 Status = gRT->GetVariable (
342 (CHAR16 *)mDaylightVariableName,
343 &gEfiCallerIdGuid,
344 NULL,
345 &Size,
346 (VOID *)&Daylight
347 );
348
349 if (EFI_ERROR (Status)) {
350 ASSERT(Status != EFI_INVALID_PARAMETER);
351 ASSERT(Status != EFI_BUFFER_TOO_SMALL);
352
353 if (Status != EFI_NOT_FOUND)
354 goto EXIT;
355
356 // The daylight variable does not exist in non-volatile storage, so create it.
357 Time->Daylight = 0;
358 // Store it
359 Status = gRT->SetVariable (
360 (CHAR16 *)mDaylightVariableName,
361 &gEfiCallerIdGuid,
362 EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
363 Size,
364 (VOID *)&(Time->Daylight)
365 );
366 if (EFI_ERROR (Status)) {
367 DEBUG ((
368 EFI_D_ERROR,
369 "LibGetTime: Failed to save %s variable to non-volatile storage, Status = %r\n",
370 mDaylightVariableName,
371 Status
372 ));
373 goto EXIT;
374 }
375 } else {
376 // Got the daylight information
377 Time->Daylight = Daylight;
378
379 // Adjust for the correct period
380 if ((Time->Daylight & EFI_TIME_IN_DAYLIGHT) == EFI_TIME_IN_DAYLIGHT) {
381 // Convert to adjusted time, i.e. spring forwards one hour
382 EpochSeconds += SEC_PER_HOUR;
383 }
384 }
385
386 // Convert from internal 32-bit time to UEFI time
387 EpochToEfiTime (EpochSeconds, Time);
388
389 // Update the Capabilities info
390 if (Capabilities != NULL) {
391 // PL031 runs at frequency 1Hz
392 Capabilities->Resolution = PL031_COUNTS_PER_SECOND;
393 // Accuracy in ppm multiplied by 1,000,000, e.g. for 50ppm set 50,000,000
394 Capabilities->Accuracy = (UINT32)PcdGet32 (PcdPL031RtcPpmAccuracy);
395 // FALSE: Setting the time does not clear the values below the resolution level
396 Capabilities->SetsToZero = FALSE;
397 }
398
399 EXIT:
400 return Status;
401 }
402
403
404 /**
405 Sets the current local time and date information.
406
407 @param Time A pointer to the current time.
408
409 @retval EFI_SUCCESS The operation completed successfully.
410 @retval EFI_INVALID_PARAMETER A time field is out of range.
411 @retval EFI_DEVICE_ERROR The time could not be set due due to hardware error.
412
413 **/
414 EFI_STATUS
415 EFIAPI
416 LibSetTime (
417 IN EFI_TIME *Time
418 )
419 {
420 EFI_STATUS Status;
421 UINTN EpochSeconds;
422
423 // Check the input parameters are within the range specified by UEFI
424 if ((Time->Year < 1900) ||
425 (Time->Year > 9999) ||
426 (Time->Month < 1 ) ||
427 (Time->Month > 12 ) ||
428 (!DayValid (Time) ) ||
429 (Time->Hour > 23 ) ||
430 (Time->Minute > 59 ) ||
431 (Time->Second > 59 ) ||
432 (Time->Nanosecond > 999999999) ||
433 (!((Time->TimeZone == EFI_UNSPECIFIED_TIMEZONE) || ((Time->TimeZone >= -1440) && (Time->TimeZone <= 1440)))) ||
434 (Time->Daylight & (~(EFI_TIME_ADJUST_DAYLIGHT | EFI_TIME_IN_DAYLIGHT)))
435 ) {
436 Status = EFI_INVALID_PARAMETER;
437 goto EXIT;
438 }
439
440 // Because the PL031 is a 32-bit counter counting seconds,
441 // the maximum time span is just over 136 years.
442 // Time is stored in Unix Epoch format, so it starts in 1970,
443 // Therefore it can not exceed the year 2106.
444 if ((Time->Year < 1970) || (Time->Year >= 2106)) {
445 Status = EFI_UNSUPPORTED;
446 goto EXIT;
447 }
448
449 // Initialize the hardware if not already done
450 if (!mPL031Initialized) {
451 Status = InitializePL031 ();
452 if (EFI_ERROR (Status)) {
453 goto EXIT;
454 }
455 }
456
457 EpochSeconds = EfiTimeToEpoch (Time);
458
459 // Adjust for the correct time zone, i.e. convert to UTC time zone
460 if (Time->TimeZone != EFI_UNSPECIFIED_TIMEZONE) {
461 EpochSeconds -= Time->TimeZone * SEC_PER_MIN;
462 }
463
464 // TODO: Automatic Daylight activation
465
466 // Adjust for the correct period
467 if ((Time->Daylight & EFI_TIME_IN_DAYLIGHT) == EFI_TIME_IN_DAYLIGHT) {
468 // Convert to un-adjusted time, i.e. fall back one hour
469 EpochSeconds -= SEC_PER_HOUR;
470 }
471
472 // On some platforms we may have access to a battery backed up hardware clock.
473 //
474 // If such RTC exists then it must be updated first, before the PL031,
475 // to minimise any time drift. This is important because the battery backed-up
476 // RTC maintains the master time for the platform across reboots.
477 //
478 // If such RTC does not exist then the following function returns UNSUPPORTED.
479 Status = ArmPlatformSysConfigSet (SYS_CFG_RTC, EpochSeconds);
480 if ((EFI_ERROR (Status)) && (Status != EFI_UNSUPPORTED)){
481 // Any status message except SUCCESS and UNSUPPORTED indicates a hardware failure.
482 goto EXIT;
483 }
484
485
486 // Set the PL031
487 MmioWrite32 (PL031_RTC_LR_LOAD_REGISTER, EpochSeconds);
488
489 // The accesses to Variable Services can be very slow, because we may be writing to Flash.
490 // Do this after having set the RTC.
491
492 // Save the current time zone information into non-volatile storage
493 Status = gRT->SetVariable (
494 (CHAR16 *)mTimeZoneVariableName,
495 &gEfiCallerIdGuid,
496 EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
497 sizeof (Time->TimeZone),
498 (VOID *)&(Time->TimeZone)
499 );
500 if (EFI_ERROR (Status)) {
501 DEBUG ((
502 EFI_D_ERROR,
503 "LibSetTime: Failed to save %s variable to non-volatile storage, Status = %r\n",
504 mTimeZoneVariableName,
505 Status
506 ));
507 goto EXIT;
508 }
509
510 // Save the current daylight information into non-volatile storage
511 Status = gRT->SetVariable (
512 (CHAR16 *)mDaylightVariableName,
513 &gEfiCallerIdGuid,
514 EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
515 sizeof(Time->Daylight),
516 (VOID *)&(Time->Daylight)
517 );
518 if (EFI_ERROR (Status)) {
519 DEBUG ((
520 EFI_D_ERROR,
521 "LibSetTime: Failed to save %s variable to non-volatile storage, Status = %r\n",
522 mDaylightVariableName,
523 Status
524 ));
525 goto EXIT;
526 }
527
528 EXIT:
529 return Status;
530 }
531
532
533 /**
534 Returns the current wakeup alarm clock setting.
535
536 @param Enabled Indicates if the alarm is currently enabled or disabled.
537 @param Pending Indicates if the alarm signal is pending and requires acknowledgement.
538 @param Time The current alarm setting.
539
540 @retval EFI_SUCCESS The alarm settings were returned.
541 @retval EFI_INVALID_PARAMETER Any parameter is NULL.
542 @retval EFI_DEVICE_ERROR The wakeup time could not be retrieved due to a hardware error.
543
544 **/
545 EFI_STATUS
546 EFIAPI
547 LibGetWakeupTime (
548 OUT BOOLEAN *Enabled,
549 OUT BOOLEAN *Pending,
550 OUT EFI_TIME *Time
551 )
552 {
553 // Not a required feature
554 return EFI_UNSUPPORTED;
555 }
556
557
558 /**
559 Sets the system wakeup alarm clock time.
560
561 @param Enabled Enable or disable the wakeup alarm.
562 @param Time If Enable is TRUE, the time to set the wakeup alarm for.
563
564 @retval EFI_SUCCESS If Enable is TRUE, then the wakeup alarm was enabled. If
565 Enable is FALSE, then the wakeup alarm was disabled.
566 @retval EFI_INVALID_PARAMETER A time field is out of range.
567 @retval EFI_DEVICE_ERROR The wakeup time could not be set due to a hardware error.
568 @retval EFI_UNSUPPORTED A wakeup timer is not supported on this platform.
569
570 **/
571 EFI_STATUS
572 EFIAPI
573 LibSetWakeupTime (
574 IN BOOLEAN Enabled,
575 OUT EFI_TIME *Time
576 )
577 {
578 // Not a required feature
579 return EFI_UNSUPPORTED;
580 }
581
582
583
584 /**
585 This is the declaration of an EFI image entry point. This can be the entry point to an application
586 written to this specification, an EFI boot service driver, or an EFI runtime driver.
587
588 @param ImageHandle Handle that identifies the loaded image.
589 @param SystemTable System Table for this image.
590
591 @retval EFI_SUCCESS The operation completed successfully.
592
593 **/
594 EFI_STATUS
595 EFIAPI
596 LibRtcInitialize (
597 IN EFI_HANDLE ImageHandle,
598 IN EFI_SYSTEM_TABLE *SystemTable
599 )
600 {
601 EFI_STATUS Status;
602 EFI_HANDLE Handle;
603
604 // Setup the setters and getters
605 gRT->GetTime = LibGetTime;
606 gRT->SetTime = LibSetTime;
607 gRT->GetWakeupTime = LibGetWakeupTime;
608 gRT->SetWakeupTime = LibSetWakeupTime;
609
610 // Install the protocol
611 Handle = NULL;
612 Status = gBS->InstallMultipleProtocolInterfaces (
613 &Handle,
614 &gEfiRealTimeClockArchProtocolGuid, NULL,
615 NULL
616 );
617
618 return Status;
619 }
620
621
622 /**
623 Fixup internal data so that EFI can be call in virtual mode.
624 Call the passed in Child Notify event and convert any pointers in
625 lib to virtual mode.
626
627 @param[in] Event The Event that is being processed
628 @param[in] Context Event Context
629 **/
630 VOID
631 EFIAPI
632 LibRtcVirtualNotifyEvent (
633 IN EFI_EVENT Event,
634 IN VOID *Context
635 )
636 {
637 //
638 // Only needed if you are going to support the OS calling RTC functions in virtual mode.
639 // You will need to call EfiConvertPointer (). To convert any stored physical addresses
640 // to virtual address. After the OS transitions to calling in virtual mode, all future
641 // runtime calls will be made in virtual mode.
642 //
643 return;
644 }