]> git.proxmox.com Git - mirror_edk2.git/blob - ArmPlatformPkg/Library/PL031RealTimeClockLib/PL031RealTimeClockLib.c
ArmPlatformPkg: Fixed unsigned type to be architecture independent
[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 CHAR16 mTimeZoneVariableName[] = L"PL031_TimeZone";
38 CHAR16 mDaylightVariableName[] = L"PL031_Daylight";
39 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 if (Time->Daylight == TRUE) {
133
134 }
135
136 J = (EpochSeconds / 86400) + 2440588;
137 j = J + 32044;
138 g = j / 146097;
139 dg = j % 146097;
140 c = (((dg / 36524) + 1) * 3) / 4;
141 dc = dg - (c * 36524);
142 b = dc / 1461;
143 db = dc % 1461;
144 a = (((db / 365) + 1) * 3) / 4;
145 da = db - (a * 365);
146 y = (g * 400) + (c * 100) + (b * 4) + a;
147 m = (((da * 5) + 308) / 153) - 2;
148 d = da - (((m + 4) * 153) / 5) + 122;
149
150 Time->Year = y - 4800 + ((m + 2) / 12);
151 Time->Month = ((m + 2) % 12) + 1;
152 Time->Day = d + 1;
153
154 ss = EpochSeconds % 60;
155 a = (EpochSeconds - ss) / 60;
156 mm = a % 60;
157 b = (a - mm) / 60;
158 hh = b % 24;
159
160 Time->Hour = hh;
161 Time->Minute = mm;
162 Time->Second = ss;
163 Time->Nanosecond = 0;
164
165 }
166
167 /**
168 Converts EFI_TIME to Epoch seconds (elapsed since 1970 JANUARY 01, 00:00:00 UTC)
169 **/
170 UINTN
171 EfiTimeToEpoch (
172 IN EFI_TIME *Time
173 )
174 {
175 UINTN a;
176 UINTN y;
177 UINTN m;
178 UINTN JulianDate; // Absolute Julian Date representation of the supplied Time
179 UINTN EpochDays; // Number of days elapsed since EPOCH_JULIAN_DAY
180 UINTN EpochSeconds;
181
182 a = (14 - Time->Month) / 12 ;
183 y = Time->Year + 4800 - a;
184 m = Time->Month + (12*a) - 3;
185
186 JulianDate = Time->Day + ((153*m + 2)/5) + (365*y) + (y/4) - (y/100) + (y/400) - 32045;
187
188 ASSERT(JulianDate > EPOCH_JULIAN_DATE);
189 EpochDays = JulianDate - EPOCH_JULIAN_DATE;
190
191 EpochSeconds = (EpochDays * SEC_PER_DAY) + ((UINTN)Time->Hour * SEC_PER_HOUR) + (Time->Minute * SEC_PER_MIN) + Time->Second;
192
193 return EpochSeconds;
194 }
195
196 BOOLEAN
197 IsLeapYear (
198 IN EFI_TIME *Time
199 )
200 {
201 if (Time->Year % 4 == 0) {
202 if (Time->Year % 100 == 0) {
203 if (Time->Year % 400 == 0) {
204 return TRUE;
205 } else {
206 return FALSE;
207 }
208 } else {
209 return TRUE;
210 }
211 } else {
212 return FALSE;
213 }
214 }
215
216 BOOLEAN
217 DayValid (
218 IN EFI_TIME *Time
219 )
220 {
221 INTN DayOfMonth[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
222
223 if (Time->Day < 1 ||
224 Time->Day > DayOfMonth[Time->Month - 1] ||
225 (Time->Month == 2 && (!IsLeapYear (Time) && Time->Day > 28))
226 ) {
227 return FALSE;
228 }
229
230 return TRUE;
231 }
232
233 /**
234 Returns the current time and date information, and the time-keeping capabilities
235 of the hardware platform.
236
237 @param Time A pointer to storage to receive a snapshot of the current time.
238 @param Capabilities An optional pointer to a buffer to receive the real time clock
239 device's capabilities.
240
241 @retval EFI_SUCCESS The operation completed successfully.
242 @retval EFI_INVALID_PARAMETER Time is NULL.
243 @retval EFI_DEVICE_ERROR The time could not be retrieved due to hardware error.
244
245 **/
246 EFI_STATUS
247 EFIAPI
248 LibGetTime (
249 OUT EFI_TIME *Time,
250 OUT EFI_TIME_CAPABILITIES *Capabilities
251 )
252 {
253 EFI_STATUS Status = EFI_SUCCESS;
254 UINT32 EpochSeconds;
255 INT16 *TimeZone = 0;
256 UINTN *Daylight = 0;
257
258 // Initialize the hardware if not already done
259 if (!mPL031Initialized) {
260 Status = InitializePL031 ();
261 if (EFI_ERROR (Status)) {
262 goto EXIT;
263 }
264 }
265
266 // Snapshot the time as early in the function call as possible
267 // On some platforms we may have access to a battery backed up hardware clock.
268 // If such RTC exists try to use it first.
269 Status = ArmPlatformSysConfigGet (SYS_CFG_RTC, &EpochSeconds);
270 if (Status == EFI_UNSUPPORTED) {
271 // Battery backed up hardware RTC does not exist, revert to PL031
272 EpochSeconds = MmioRead32 (PL031_RTC_DR_DATA_REGISTER);
273 Status = EFI_SUCCESS;
274 } else if (EFI_ERROR (Status)) {
275 // Battery backed up hardware RTC exists but could not be read due to error. Abort.
276 goto EXIT;
277 } else {
278 // Battery backed up hardware RTC exists and we read the time correctly from it.
279 // Now sync the PL031 to the new time.
280 MmioWrite32 (PL031_RTC_LR_LOAD_REGISTER, EpochSeconds);
281 }
282
283 // Ensure Time is a valid pointer
284 if (Time == NULL) {
285 Status = EFI_INVALID_PARAMETER;
286 goto EXIT;
287 }
288
289 // Get the current time zone information from non-volatile storage
290 TimeZone = (INT16 *)GetVariable(mTimeZoneVariableName, &gEfiGlobalVariableGuid);
291
292 if (TimeZone == NULL) {
293 // The time zone variable does not exist in non-volatile storage, so create it.
294 Time->TimeZone = EFI_UNSPECIFIED_TIMEZONE;
295 // Store it
296 Status = gRT->SetVariable (
297 mTimeZoneVariableName,
298 &gEfiGlobalVariableGuid,
299 EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
300 sizeof(Time->TimeZone),
301 &(Time->TimeZone)
302 );
303 if (EFI_ERROR (Status)) {
304 DEBUG((EFI_D_ERROR,"LibGetTime: ERROR: TimeZone\n"));
305 goto EXIT;
306 }
307 } else {
308 // Got the time zone
309 Time->TimeZone = *TimeZone;
310 FreePool(TimeZone);
311
312 // Check TimeZone bounds: -1440 to 1440 or 2047
313 if (((Time->TimeZone < -1440) || (Time->TimeZone > 1440))
314 && (Time->TimeZone != EFI_UNSPECIFIED_TIMEZONE)) {
315 Time->TimeZone = EFI_UNSPECIFIED_TIMEZONE;
316 }
317
318 // Adjust for the correct time zone
319 if (Time->TimeZone != EFI_UNSPECIFIED_TIMEZONE) {
320 EpochSeconds += Time->TimeZone * SEC_PER_MIN;
321 }
322 }
323
324 // Get the current daylight information from non-volatile storage
325 Daylight = (UINTN *)GetVariable(mDaylightVariableName, &gEfiGlobalVariableGuid);
326
327 if (Daylight == NULL) {
328 // The daylight variable does not exist in non-volatile storage, so create it.
329 Time->Daylight = 0;
330 // Store it
331 Status = gRT->SetVariable (
332 mDaylightVariableName,
333 &gEfiGlobalVariableGuid,
334 EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
335 sizeof(Time->Daylight),
336 &(Time->Daylight)
337 );
338 if (EFI_ERROR (Status)) {
339 DEBUG((EFI_D_ERROR,"LibGetTime: ERROR: Daylight\n"));
340 goto EXIT;
341 }
342 } else {
343 // Got the daylight information
344 Time->Daylight = *Daylight;
345 FreePool(Daylight);
346
347 // Adjust for the correct period
348 if ((Time->Daylight & EFI_TIME_IN_DAYLIGHT) == EFI_TIME_IN_DAYLIGHT) {
349 // Convert to adjusted time, i.e. spring forwards one hour
350 EpochSeconds += SEC_PER_HOUR;
351 }
352 }
353
354 // Convert from internal 32-bit time to UEFI time
355 EpochToEfiTime (EpochSeconds, Time);
356
357 // Update the Capabilities info
358 if (Capabilities != NULL) {
359 // PL031 runs at frequency 1Hz
360 Capabilities->Resolution = PL031_COUNTS_PER_SECOND;
361 // Accuracy in ppm multiplied by 1,000,000, e.g. for 50ppm set 50,000,000
362 Capabilities->Accuracy = (UINT32)PcdGet32 (PcdPL031RtcPpmAccuracy);
363 // FALSE: Setting the time does not clear the values below the resolution level
364 Capabilities->SetsToZero = FALSE;
365 }
366
367 EXIT:
368 return Status;
369 }
370
371
372 /**
373 Sets the current local time and date information.
374
375 @param Time A pointer to the current time.
376
377 @retval EFI_SUCCESS The operation completed successfully.
378 @retval EFI_INVALID_PARAMETER A time field is out of range.
379 @retval EFI_DEVICE_ERROR The time could not be set due due to hardware error.
380
381 **/
382 EFI_STATUS
383 EFIAPI
384 LibSetTime (
385 IN EFI_TIME *Time
386 )
387 {
388 EFI_STATUS Status;
389 UINTN EpochSeconds;
390
391 // Because the PL031 is a 32-bit counter counting seconds,
392 // the maximum time span is just over 136 years.
393 // Time is stored in Unix Epoch format, so it starts in 1970,
394 // Therefore it can not exceed the year 2106.
395 // This is not a problem for UEFI, as the current spec limits the years
396 // to the range 1998 .. 2011
397
398 // Check the input parameters' range.
399 if ((Time->Year < 1998) ||
400 (Time->Year > 2099) ||
401 (Time->Month < 1 ) ||
402 (Time->Month > 12 ) ||
403 (!DayValid (Time) ) ||
404 (Time->Hour > 23 ) ||
405 (Time->Minute > 59 ) ||
406 (Time->Second > 59 ) ||
407 (Time->Nanosecond > 999999999) ||
408 (!((Time->TimeZone == EFI_UNSPECIFIED_TIMEZONE) || ((Time->TimeZone >= -1440) && (Time->TimeZone <= 1440)))) ||
409 (Time->Daylight & (~(EFI_TIME_ADJUST_DAYLIGHT | EFI_TIME_IN_DAYLIGHT)))
410 ) {
411 Status = EFI_INVALID_PARAMETER;
412 goto EXIT;
413 }
414
415 // Initialize the hardware if not already done
416 if (!mPL031Initialized) {
417 Status = InitializePL031 ();
418 if (EFI_ERROR (Status)) {
419 goto EXIT;
420 }
421 }
422
423 EpochSeconds = EfiTimeToEpoch (Time);
424
425 // Adjust for the correct time zone, i.e. convert to UTC time zone
426 if (Time->TimeZone != EFI_UNSPECIFIED_TIMEZONE) {
427 EpochSeconds -= Time->TimeZone * SEC_PER_MIN;
428 }
429
430 // TODO: Automatic Daylight activation
431
432 // Adjust for the correct period
433 if ((Time->Daylight & EFI_TIME_IN_DAYLIGHT) == EFI_TIME_IN_DAYLIGHT) {
434 // Convert to un-adjusted time, i.e. fall back one hour
435 EpochSeconds -= SEC_PER_HOUR;
436 }
437
438 // On some platforms we may have access to a battery backed up hardware clock.
439 //
440 // If such RTC exists then it must be updated first, before the PL031,
441 // to minimise any time drift. This is important because the battery backed-up
442 // RTC maintains the master time for the platform across reboots.
443 //
444 // If such RTC does not exist then the following function returns UNSUPPORTED.
445 Status = ArmPlatformSysConfigSet (SYS_CFG_RTC, EpochSeconds);
446 if ((EFI_ERROR (Status)) && (Status != EFI_UNSUPPORTED)){
447 // Any status message except SUCCESS and UNSUPPORTED indicates a hardware failure.
448 goto EXIT;
449 }
450
451
452 // Set the PL031
453 MmioWrite32 (PL031_RTC_LR_LOAD_REGISTER, EpochSeconds);
454
455 // The accesses to Variable Services can be very slow, because we may be writing to Flash.
456 // Do this after having set the RTC.
457
458 // Save the current time zone information into non-volatile storage
459 Status = gRT->SetVariable (
460 mTimeZoneVariableName,
461 &gEfiGlobalVariableGuid,
462 EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
463 sizeof(Time->TimeZone),
464 &(Time->TimeZone)
465 );
466 if (EFI_ERROR (Status)) {
467 DEBUG((EFI_D_ERROR,"LibSetTime: ERROR: TimeZone\n"));
468 goto EXIT;
469 }
470
471 // Save the current daylight information into non-volatile storage
472 Status = gRT->SetVariable (
473 mDaylightVariableName,
474 &gEfiGlobalVariableGuid,
475 EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
476 sizeof(Time->Daylight),
477 &(Time->Daylight)
478 );
479 if (EFI_ERROR (Status)) {
480 DEBUG((EFI_D_ERROR,"LibSetTime: ERROR: Daylight\n"));
481 goto EXIT;
482 }
483
484 EXIT:
485 return Status;
486 }
487
488
489 /**
490 Returns the current wakeup alarm clock setting.
491
492 @param Enabled Indicates if the alarm is currently enabled or disabled.
493 @param Pending Indicates if the alarm signal is pending and requires acknowledgement.
494 @param Time The current alarm setting.
495
496 @retval EFI_SUCCESS The alarm settings were returned.
497 @retval EFI_INVALID_PARAMETER Any parameter is NULL.
498 @retval EFI_DEVICE_ERROR The wakeup time could not be retrieved due to a hardware error.
499
500 **/
501 EFI_STATUS
502 EFIAPI
503 LibGetWakeupTime (
504 OUT BOOLEAN *Enabled,
505 OUT BOOLEAN *Pending,
506 OUT EFI_TIME *Time
507 )
508 {
509 // Not a required feature
510 return EFI_UNSUPPORTED;
511 }
512
513
514 /**
515 Sets the system wakeup alarm clock time.
516
517 @param Enabled Enable or disable the wakeup alarm.
518 @param Time If Enable is TRUE, the time to set the wakeup alarm for.
519
520 @retval EFI_SUCCESS If Enable is TRUE, then the wakeup alarm was enabled. If
521 Enable is FALSE, then the wakeup alarm was disabled.
522 @retval EFI_INVALID_PARAMETER A time field is out of range.
523 @retval EFI_DEVICE_ERROR The wakeup time could not be set due to a hardware error.
524 @retval EFI_UNSUPPORTED A wakeup timer is not supported on this platform.
525
526 **/
527 EFI_STATUS
528 EFIAPI
529 LibSetWakeupTime (
530 IN BOOLEAN Enabled,
531 OUT EFI_TIME *Time
532 )
533 {
534 // Not a required feature
535 return EFI_UNSUPPORTED;
536 }
537
538
539
540 /**
541 This is the declaration of an EFI image entry point. This can be the entry point to an application
542 written to this specification, an EFI boot service driver, or an EFI runtime driver.
543
544 @param ImageHandle Handle that identifies the loaded image.
545 @param SystemTable System Table for this image.
546
547 @retval EFI_SUCCESS The operation completed successfully.
548
549 **/
550 EFI_STATUS
551 EFIAPI
552 LibRtcInitialize (
553 IN EFI_HANDLE ImageHandle,
554 IN EFI_SYSTEM_TABLE *SystemTable
555 )
556 {
557 EFI_STATUS Status;
558 EFI_HANDLE Handle;
559
560 // Setup the setters and getters
561 gRT->GetTime = LibGetTime;
562 gRT->SetTime = LibSetTime;
563 gRT->GetWakeupTime = LibGetWakeupTime;
564 gRT->SetWakeupTime = LibSetWakeupTime;
565
566 // Install the protocol
567 Handle = NULL;
568 Status = gBS->InstallMultipleProtocolInterfaces (
569 &Handle,
570 &gEfiRealTimeClockArchProtocolGuid, NULL,
571 NULL
572 );
573
574 return Status;
575 }
576
577
578 /**
579 Fixup internal data so that EFI can be call in virtual mode.
580 Call the passed in Child Notify event and convert any pointers in
581 lib to virtual mode.
582
583 @param[in] Event The Event that is being processed
584 @param[in] Context Event Context
585 **/
586 VOID
587 EFIAPI
588 LibRtcVirtualNotifyEvent (
589 IN EFI_EVENT Event,
590 IN VOID *Context
591 )
592 {
593 //
594 // Only needed if you are going to support the OS calling RTC functions in virtual mode.
595 // You will need to call EfiConvertPointer (). To convert any stored physical addresses
596 // to virtual address. After the OS transitions to calling in virtual mode, all future
597 // runtime calls will be made in virtual mode.
598 //
599 return;
600 }