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