2 * Copyright (C) 2008 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 * System clock functions.
23 #include <linux/ioctl.h>
24 #include <linux/rtc.h>
25 #include <utils/Atomic.h>
26 #include <linux/android_alarm.h>
35 #include <utils/SystemClock.h>
36 #include <utils/Timers.h>
38 #define LOG_TAG "SystemClock"
39 #include "utils/Log.h"
44 * Set the current time. This only works when running as root.
46 int setCurrentTimeMillis(int64_t millis)
60 if (millis <= 0 || millis / 1000LL >= INT_MAX) {
64 tv.tv_sec = (time_t) (millis / 1000LL);
65 tv.tv_usec = (suseconds_t) ((millis % 1000LL) * 1000LL);
67 LOGD("Setting time of day to sec=%d\n", (int) tv.tv_sec);
70 fd = open("/dev/alarm", O_RDWR);
72 LOGW("Unable to open alarm driver: %s\n", strerror(errno));
75 ts.tv_sec = tv.tv_sec;
76 ts.tv_nsec = tv.tv_usec * 1000;
77 res = ioctl(fd, ANDROID_ALARM_SET_RTC, &ts);
79 LOGW("Unable to set rtc to %ld: %s\n", tv.tv_sec, strerror(errno));
84 if (settimeofday(&tv, NULL) != 0) {
85 LOGW("Unable to set clock to %d.%d: %s\n",
86 (int) tv.tv_sec, (int) tv.tv_usec, strerror(errno));
96 * native public static long uptimeMillis();
98 int64_t uptimeMillis()
100 int64_t when = systemTime(SYSTEM_TIME_MONOTONIC);
101 return (int64_t) nanoseconds_to_milliseconds(when);
105 * native public static long elapsedRealtime();
107 int64_t elapsedRealtime()
110 static int s_fd = -1;
113 int fd = open("/dev/alarm", O_RDONLY);
114 if (android_atomic_cmpxchg(-1, fd, &s_fd)) {
120 int result = ioctl(s_fd,
121 ANDROID_ALARM_GET_TIME(ANDROID_ALARM_ELAPSED_REALTIME), &ts);
124 int64_t when = seconds_to_nanoseconds(ts.tv_sec) + ts.tv_nsec;
125 return (int64_t) nanoseconds_to_milliseconds(when);
127 // XXX: there was an error, probably because the driver didn't
128 // exist ... this should return
129 // a real error, like an exception!
130 int64_t when = systemTime(SYSTEM_TIME_MONOTONIC);
131 return (int64_t) nanoseconds_to_milliseconds(when);
134 int64_t when = systemTime(SYSTEM_TIME_MONOTONIC);
135 return (int64_t) nanoseconds_to_milliseconds(when);
139 }; // namespace android