1 /*
2 * Copyright (C) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #include "time_system_ability.h"
16
17 #include <chrono>
18 #include <dirent.h>
19 #include <fstream>
20 #include <linux/rtc.h>
21 #include <mutex>
22 #include <sstream>
23 #include <string>
24 #include <sys/ioctl.h>
25 #include <sys/time.h>
26 #include <sys/timerfd.h>
27
28 #include "iservice_registry.h"
29 #include "ntp_update_time.h"
30 #include "ntp_trusted_time.h"
31 #include "pthread.h"
32 #include "system_ability.h"
33 #include "system_ability_definition.h"
34 #include "time_common.h"
35 #include "time_tick_notify.h"
36 #include "time_zone_info.h"
37 #include "timer_notify_callback.h"
38 #include "timer_manager_interface.h"
39 #include "timer_proxy.h"
40 #include "timer_database.h"
41 #include "time_file_utils.h"
42 #include "common_event_manager.h"
43 #include "common_event_support.h"
44 #include "power_subscriber.h"
45 #include "nitz_subscriber.h"
46 #include "init_param.h"
47 #include "parameters.h"
48
49 using namespace std::chrono;
50 using namespace OHOS::EventFwk;
51
52 namespace OHOS {
53 namespace MiscServices {
54 namespace {
55 // Unit of measure conversion , BASE: second
56 static const int MILLI_TO_BASE = 1000LL;
57 static const int MICR_TO_BASE = 1000000LL;
58 static const int NANO_TO_BASE = 1000000000LL;
59 static const std::int32_t INIT_INTERVAL = 10L;
60 static const uint32_t TIMER_TYPE_REALTIME_MASK = 1 << 0;
61 static const uint32_t TIMER_TYPE_REALTIME_WAKEUP_MASK = 1 << 1;
62 static const uint32_t TIMER_TYPE_EXACT_MASK = 1 << 2;
63 static const uint32_t TIMER_TYPE_IDLE_MASK = 1 << 3;
64 static const uint32_t TIMER_TYPE_INEXACT_REMINDER_MASK = 1 << 4;
65 constexpr int32_t MILLI_TO_MICR = MICR_TO_BASE / MILLI_TO_BASE;
66 constexpr int32_t NANO_TO_MILLI = NANO_TO_BASE / MILLI_TO_BASE;
67 constexpr int32_t ONE_MILLI = 1000;
68 constexpr uint64_t TWO_MINUTES_TO_MILLI = 120000;
69 static const std::vector<std::string> ALL_DATA = { "timerId", "type", "flag", "windowLength", "interval", \
70 "uid", "bundleName", "wantAgent", "state", "triggerTime", \
71 "pid"};
72 const std::string BOOTEVENT_PARAMETER = "bootevent.boot.completed";
73 } // namespace
74
75 REGISTER_SYSTEM_ABILITY_BY_ID(TimeSystemAbility, TIME_SERVICE_ID, true);
76
77 std::mutex TimeSystemAbility::instanceLock_;
78 sptr<TimeSystemAbility> TimeSystemAbility::instance_;
79
TimeSystemAbility(int32_t systemAbilityId,bool runOnCreate)80 TimeSystemAbility::TimeSystemAbility(int32_t systemAbilityId, bool runOnCreate)
81 : SystemAbility(systemAbilityId, runOnCreate), state_(ServiceRunningState::STATE_NOT_START),
82 rtcId(GetWallClockRtcId())
83 {
84 TIME_HILOGD(TIME_MODULE_SERVICE, " TimeSystemAbility Start.");
85 }
86
TimeSystemAbility()87 TimeSystemAbility::TimeSystemAbility() : state_(ServiceRunningState::STATE_NOT_START), rtcId(GetWallClockRtcId())
88 {
89 }
90
~TimeSystemAbility()91 TimeSystemAbility::~TimeSystemAbility(){};
92
GetInstance()93 sptr<TimeSystemAbility> TimeSystemAbility::GetInstance()
94 {
95 if (instance_ == nullptr) {
96 std::lock_guard<std::mutex> autoLock(instanceLock_);
97 if (instance_ == nullptr) {
98 instance_ = new TimeSystemAbility;
99 }
100 }
101 return instance_;
102 }
103
InitDumpCmd()104 void TimeSystemAbility::InitDumpCmd()
105 {
106 auto cmdTime = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-time" }),
107 "dump current time info,include localtime,timezone info",
108 [this](int fd, const std::vector<std::string> &input) { DumpAllTimeInfo(fd, input); });
109 TimeCmdDispatcher::GetInstance().RegisterCommand(cmdTime);
110
111 auto cmdTimerAll = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-timer", "-a" }),
112 "dump all timer info", [this](int fd, const std::vector<std::string> &input) { DumpTimerInfo(fd, input); });
113 TimeCmdDispatcher::GetInstance().RegisterCommand(cmdTimerAll);
114
115 auto cmdTimerInfo = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-timer", "-i", "[n]" }),
116 "dump the timer info with timer id",
117 [this](int fd, const std::vector<std::string> &input) { DumpTimerInfoById(fd, input); });
118 TimeCmdDispatcher::GetInstance().RegisterCommand(cmdTimerInfo);
119
120 auto cmdTimerTrigger = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-timer", "-s", "[n]" }),
121 "dump current time info,include localtime,timezone info",
122 [this](int fd, const std::vector<std::string> &input) { DumpTimerTriggerById(fd, input); });
123 TimeCmdDispatcher::GetInstance().RegisterCommand(cmdTimerTrigger);
124
125 auto cmdTimerIdle = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-idle", "-a" }),
126 "dump idle state and timer info, include pending delay timers and delayed info.",
127 [this](int fd, const std::vector<std::string> &input) { DumpIdleTimerInfo(fd, input); });
128 TimeCmdDispatcher::GetInstance().RegisterCommand(cmdTimerIdle);
129
130 auto cmdProxyTimer = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-ProxyTimer", "-l" }),
131 "dump proxy timer info.",
132 [this](int fd, const std::vector<std::string> &input) { DumpProxyTimerInfo(fd, input); });
133 TimeCmdDispatcher::GetInstance().RegisterCommand(cmdProxyTimer);
134
135 auto cmdPidTimer = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-PidTimer", "-l" }),
136 "dump pid timer map.",
137 [this](int fd, const std::vector<std::string> &input) { DumpPidTimerMapInfo(fd, input); });
138 TimeCmdDispatcher::GetInstance().RegisterCommand(cmdPidTimer);
139
140 auto cmdUidTimer = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-UidTimer", "-l" }),
141 "dump uid timer map.",
142 [this](int fd, const std::vector<std::string> &input) { DumpUidTimerMapInfo(fd, input); });
143 TimeCmdDispatcher::GetInstance().RegisterCommand(cmdUidTimer);
144
145 auto cmdShowDelayTimer = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-ProxyDelayTime", "-l" }),
146 "dump proxy delay time.",
147 [this](int fd, const std::vector<std::string> &input) { DumpProxyDelayTime(fd, input); });
148 TimeCmdDispatcher::GetInstance().RegisterCommand(cmdShowDelayTimer);
149
150 auto cmdAdjustTimer = std::make_shared<TimeCmdParse>(std::vector<std::string>({ "-adjust", "-a" }),
151 "dump adjust time.",
152 [this](int fd, const std::vector<std::string> &input) { DumpAdjustTime(fd, input); });
153 TimeCmdDispatcher::GetInstance().RegisterCommand(cmdAdjustTimer);
154 }
155
OnStart()156 void TimeSystemAbility::OnStart()
157 {
158 TIME_HILOGI(TIME_MODULE_SERVICE, "TimeSystemAbility OnStart.");
159 if (state_ == ServiceRunningState::STATE_RUNNING) {
160 TIME_HILOGE(TIME_MODULE_SERVICE, "TimeSystemAbility is already running.");
161 return;
162 }
163 TimerManager::GetInstance();
164 TimeTickNotify::GetInstance().Init();
165 TimeZoneInfo::GetInstance().Init();
166 NtpUpdateTime::GetInstance().Init();
167 // This parameter is set to true by init only after all services have been started,
168 // and is automatically set to false after shutdown. Otherwise it will not be modified.
169 std::string bootCompleted = system::GetParameter(BOOTEVENT_PARAMETER, "");
170 TIME_HILOGI(TIME_MODULE_SERVICE, "bootCompleted: %{public}s", bootCompleted.c_str());
171 if (bootCompleted != "true") {
172 TimeDatabase::GetInstance().ClearDropOnReboot();
173 }
174 AddSystemAbilityListener(ABILITY_MGR_SERVICE_ID);
175 AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
176 AddSystemAbilityListener(DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID);
177 AddSystemAbilityListener(POWER_MANAGER_SERVICE_ID);
178 AddSystemAbilityListener(COMM_NET_CONN_MANAGER_SYS_ABILITY_ID);
179 InitDumpCmd();
180 if (Init() != ERR_OK) {
181 auto callback = [this]() {
182 sleep(INIT_INTERVAL);
183 Init();
184 };
185 std::thread thread(callback);
186 thread.detach();
187 TIME_HILOGE(TIME_MODULE_SERVICE, "Init failed. Try again 10s later.");
188 }
189 }
190
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)191 void TimeSystemAbility::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
192 {
193 TIME_HILOGD(TIME_MODULE_SERVICE, "OnAddSystemAbility systemAbilityId:%{public}d added!", systemAbilityId);
194 switch (systemAbilityId) {
195 case COMMON_EVENT_SERVICE_ID:
196 RegisterCommonEventSubscriber();
197 RemoveSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
198 break;
199 case DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID:
200 RegisterRSSDeathCallback();
201 break;
202 case POWER_MANAGER_SERVICE_ID:
203 RegisterPowerStateListener();
204 break;
205 case COMM_NET_CONN_MANAGER_SYS_ABILITY_ID:
206 NtpUpdateTime::GetInstance().MonitorNetwork();
207 break;
208 case ABILITY_MGR_SERVICE_ID:
209 AddSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
210 RemoveSystemAbilityListener(ABILITY_MGR_SERVICE_ID);
211 break;
212 case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID:
213 RecoverTimer();
214 RemoveSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
215 break;
216 default:
217 TIME_HILOGE(TIME_MODULE_SERVICE, "OnAddSystemAbility systemAbilityId is not valid, id is %{public}d",
218 systemAbilityId);
219 }
220 }
221
RegisterScreenOnSubscriber()222 void TimeSystemAbility::RegisterScreenOnSubscriber()
223 {
224 MatchingSkills matchingSkills;
225 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_SCREEN_ON);
226 CommonEventSubscribeInfo subscriberInfo(matchingSkills);
227 std::shared_ptr<PowerSubscriber> subscriberPtr = std::make_shared<PowerSubscriber>(subscriberInfo);
228 bool subscribeResult = CommonEventManager::SubscribeCommonEvent(subscriberPtr);
229 if (!subscribeResult) {
230 TIME_HILOGE(TIME_MODULE_SERVICE, "Register COMMON_EVENT_SCREEN_ON failed");
231 } else {
232 TIME_HILOGI(TIME_MODULE_SERVICE, "Register COMMON_EVENT_SCREEN_ON success.");
233 }
234 }
235
RegisterNitzTimeSubscriber()236 void TimeSystemAbility::RegisterNitzTimeSubscriber()
237 {
238 MatchingSkills matchingNITZSkills;
239 matchingNITZSkills.AddEvent(CommonEventSupport::COMMON_EVENT_NITZ_TIME_CHANGED);
240 CommonEventSubscribeInfo subscriberNITZInfo(matchingNITZSkills);
241 std::shared_ptr<NITZSubscriber> subscriberNITZPtr = std::make_shared<NITZSubscriber>(subscriberNITZInfo);
242 bool subscribeNITZResult = CommonEventManager::SubscribeCommonEvent(subscriberNITZPtr);
243 if (!subscribeNITZResult) {
244 TIME_HILOGE(TIME_MODULE_SERVICE, "Register COMMON_EVENT_NITZ_TIME_CHANGED failed");
245 } else {
246 TIME_HILOGI(TIME_MODULE_SERVICE, "Register COMMON_EVENT_NITZ_TIME_CHANGED success.");
247 }
248 }
249
RegisterCommonEventSubscriber()250 void TimeSystemAbility::RegisterCommonEventSubscriber()
251 {
252 TIME_HILOGD(TIME_MODULE_SERVICE, "RegisterCommonEventSubscriber Started");
253 bool subRes = TimeServiceNotify::GetInstance().RepublishEvents();
254 if (!subRes) {
255 TIME_HILOGE(TIME_MODULE_SERVICE, "failed to RegisterCommonEventSubscriber");
256 auto callback = [this]() {
257 sleep(INIT_INTERVAL);
258 TimeServiceNotify::GetInstance().RepublishEvents();
259 };
260 std::thread thread(callback);
261 thread.detach();
262 }
263 RegisterScreenOnSubscriber();
264 RegisterNitzTimeSubscriber();
265 }
266
Init()267 int32_t TimeSystemAbility::Init()
268 {
269 bool ret = Publish(TimeSystemAbility::GetInstance());
270 if (!ret) {
271 TIME_HILOGE(TIME_MODULE_SERVICE, "Init Failed.");
272 return E_TIME_PUBLISH_FAIL;
273 }
274 TIME_HILOGI(TIME_MODULE_SERVICE, "Init success.");
275 state_ = ServiceRunningState::STATE_RUNNING;
276 return ERR_OK;
277 }
278
OnStop()279 void TimeSystemAbility::OnStop()
280 {
281 TIME_HILOGD(TIME_MODULE_SERVICE, "OnStop Started.");
282 if (state_ != ServiceRunningState::STATE_RUNNING) {
283 TIME_HILOGI(TIME_MODULE_SERVICE, "state is running.");
284 return;
285 }
286 TimeTickNotify::GetInstance().Stop();
287 state_ = ServiceRunningState::STATE_NOT_START;
288 TIME_HILOGI(TIME_MODULE_SERVICE, "OnStop End.");
289 }
290
ParseTimerPara(const std::shared_ptr<ITimerInfo> & timerOptions,TimerPara & paras)291 void TimeSystemAbility::ParseTimerPara(const std::shared_ptr<ITimerInfo> &timerOptions, TimerPara ¶s)
292 {
293 auto uIntType = static_cast<uint32_t>(timerOptions->type);
294 auto disposable = timerOptions->disposable;
295 bool isRealtime = (uIntType & TIMER_TYPE_REALTIME_MASK) > 0;
296 bool isWakeup = (uIntType & TIMER_TYPE_REALTIME_WAKEUP_MASK) > 0;
297 paras.windowLength = (uIntType & TIMER_TYPE_EXACT_MASK) > 0 ? 0 : -1;
298 paras.flag = (uIntType & TIMER_TYPE_EXACT_MASK) > 0 ? 1 : 0;
299 if (isRealtime && isWakeup) {
300 paras.timerType = ITimerManager::TimerType::ELAPSED_REALTIME_WAKEUP;
301 } else if (isRealtime) {
302 paras.timerType = ITimerManager::TimerType::ELAPSED_REALTIME;
303 } else if (isWakeup) {
304 paras.timerType = ITimerManager::TimerType::RTC_WAKEUP;
305 } else {
306 paras.timerType = ITimerManager::TimerType::RTC;
307 }
308 if ((uIntType & TIMER_TYPE_IDLE_MASK) > 0) {
309 paras.flag += ITimerManager::TimerFlag::IDLE_UNTIL;
310 }
311 if ((uIntType & TIMER_TYPE_INEXACT_REMINDER_MASK) > 0) {
312 paras.flag += ITimerManager::TimerFlag::INEXACT_REMINDER;
313 }
314 if (disposable) {
315 paras.flag += ITimerManager::TimerFlag::IS_DISPOSABLE;
316 }
317 paras.interval = timerOptions->repeat ? timerOptions->interval : 0;
318 }
319
CreateTimer(const std::shared_ptr<ITimerInfo> & timerOptions,sptr<IRemoteObject> & obj,uint64_t & timerId)320 int32_t TimeSystemAbility::CreateTimer(const std::shared_ptr<ITimerInfo> &timerOptions, sptr<IRemoteObject> &obj,
321 uint64_t &timerId)
322 {
323 if (obj == nullptr) {
324 TIME_HILOGE(TIME_MODULE_SERVICE, "Input nullptr.");
325 return E_TIME_NULLPTR;
326 }
327 sptr<ITimerCallback> timerCallback = iface_cast<ITimerCallback>(obj);
328 if (timerCallback == nullptr) {
329 TIME_HILOGE(TIME_MODULE_SERVICE, "ITimerCallback nullptr.");
330 return E_TIME_NULLPTR;
331 }
332 struct TimerPara paras {};
333 ParseTimerPara(timerOptions, paras);
334 auto timerManager = TimerManager::GetInstance();
335 if (timerManager == nullptr) {
336 return E_TIME_NULLPTR;
337 }
338 auto callbackFunc = [timerCallback, timerOptions, timerManager](uint64_t id) -> int32_t {
339 #ifdef POWER_MANAGER_ENABLE
340 if (timerOptions->type == ITimerManager::TimerType::RTC_WAKEUP ||
341 timerOptions->type == ITimerManager::TimerType::ELAPSED_REALTIME_WAKEUP) {
342 auto notifyCallback = TimerNotifyCallback::GetInstance(timerManager);
343 return timerCallback->NotifyTimer(id, notifyCallback->AsObject());
344 } else {
345 return timerCallback->NotifyTimer(id, nullptr);
346 }
347 #else
348 return timerCallback->NotifyTimer(id, nullptr);
349 #endif
350 };
351 if ((static_cast<uint32_t>(paras.flag) & static_cast<uint32_t>(ITimerManager::TimerFlag::IDLE_UNTIL)) > 0 &&
352 !TimePermission::CheckProxyCallingPermission()) {
353 TIME_HILOGW(TIME_MODULE_SERVICE, "App not support create idle timer.");
354 paras.flag = 0;
355 }
356 auto type = DatabaseType::NOT_STORE;
357 if (timerOptions->wantAgent != nullptr) {
358 type = DatabaseType::STORE;
359 }
360 int uid = IPCSkeleton::GetCallingUid();
361 int pid = IPCSkeleton::GetCallingPid();
362 return timerManager->CreateTimer(paras, callbackFunc, timerOptions->wantAgent,
363 uid, pid, timerId, type);
364 }
365
CreateTimer(TimerPara & paras,std::function<int32_t (const uint64_t)> callback,uint64_t & timerId)366 int32_t TimeSystemAbility::CreateTimer(TimerPara ¶s, std::function<int32_t (const uint64_t)> callback,
367 uint64_t &timerId)
368 {
369 auto timerManager = TimerManager::GetInstance();
370 if (timerManager == nullptr) {
371 return E_TIME_NULLPTR;
372 }
373 return timerManager->CreateTimer(paras, std::move(callback), nullptr, 0, 0, timerId, NOT_STORE);
374 }
375
StartTimer(uint64_t timerId,uint64_t triggerTime)376 int32_t TimeSystemAbility::StartTimer(uint64_t timerId, uint64_t triggerTime)
377 {
378 auto timerManager = TimerManager::GetInstance();
379 if (timerManager == nullptr) {
380 return E_TIME_NULLPTR;
381 }
382 auto ret = timerManager->StartTimer(timerId, triggerTime);
383 return ret;
384 }
385
StopTimer(uint64_t timerId)386 int32_t TimeSystemAbility::StopTimer(uint64_t timerId)
387 {
388 auto timerManager = TimerManager::GetInstance();
389 if (timerManager == nullptr) {
390 return E_TIME_NULLPTR;
391 }
392 auto ret = timerManager->StopTimer(timerId);
393 return ret;
394 }
395
DestroyTimer(uint64_t timerId,bool isAsync)396 int32_t TimeSystemAbility::DestroyTimer(uint64_t timerId, bool isAsync)
397 {
398 auto timerManager = TimerManager::GetInstance();
399 if (timerManager == nullptr) {
400 return E_TIME_NULLPTR;
401 }
402 auto ret = timerManager->DestroyTimer(timerId);
403 return ret;
404 }
405
IsValidTime(int64_t time)406 bool TimeSystemAbility::IsValidTime(int64_t time)
407 {
408 #if __SIZEOF_POINTER__ == 4
409 if (time / MILLI_TO_BASE > LONG_MAX) {
410 return false;
411 }
412 #endif
413 return true;
414 }
415
SetRealTime(int64_t time)416 bool TimeSystemAbility::SetRealTime(int64_t time)
417 {
418 if (!IsValidTime(time)) {
419 TIME_HILOGE(TIME_MODULE_SERVICE, "time is invalid: %{public}s", std::to_string(time).c_str());
420 return false;
421 }
422 sptr<TimeSystemAbility> instance = TimeSystemAbility::GetInstance();
423 int64_t beforeTime = 0;
424 TimeUtils::GetWallTimeMs(beforeTime);
425 int64_t bootTime = 0;
426 TimeUtils::GetBootTimeMs(bootTime);
427 TIME_HILOGI(TIME_MODULE_SERVICE,
428 "Before Current Time: %{public}s"
429 " Set time: %{public}s"
430 " Difference: %{public}s"
431 " uid:%{public}d pid:%{public}d ",
432 std::to_string(beforeTime).c_str(), std::to_string(time).c_str(), std::to_string(time - bootTime).c_str(),
433 IPCSkeleton::GetCallingUid(), IPCSkeleton::GetCallingPid());
434 if (time < 0) {
435 TIME_HILOGE(TIME_MODULE_SERVICE, "input param error %{public}" PRId64 "", time);
436 return false;
437 }
438 int64_t currentTime = 0;
439 if (TimeUtils::GetWallTimeMs(currentTime) != ERR_OK) {
440 TIME_HILOGE(TIME_MODULE_SERVICE, "currentTime get failed");
441 return false;
442 }
443 struct timeval tv {};
444 tv.tv_sec = (time_t)(time / MILLI_TO_BASE);
445 tv.tv_usec = (suseconds_t)((time % MILLI_TO_BASE) * MILLI_TO_MICR);
446 int result = settimeofday(&tv, nullptr);
447 if (result < 0) {
448 TIME_HILOGE(TIME_MODULE_SERVICE, "settimeofday time fail: %{public}d. error: %{public}s", result,
449 strerror(errno));
450 return false;
451 }
452 auto ret = SetRtcTime(tv.tv_sec);
453 if (ret == E_TIME_SET_RTC_FAILED) {
454 TIME_HILOGE(TIME_MODULE_SERVICE, "set rtc fail: %{public}d.", ret);
455 return false;
456 }
457 TIME_HILOGD(TIME_MODULE_SERVICE, "getting currentTime to milliseconds: %{public}" PRId64 "", currentTime);
458 if (currentTime < (time - ONE_MILLI) || currentTime > (time + ONE_MILLI)) {
459 TimeServiceNotify::GetInstance().PublishTimeChangeEvents(currentTime);
460 }
461 return true;
462 }
463
SetTime(int64_t time,APIVersion apiVersion)464 int32_t TimeSystemAbility::SetTime(int64_t time, APIVersion apiVersion)
465 {
466 if (!SetRealTime(time)) {
467 return E_TIME_DEAL_FAILED;
468 }
469 return ERR_OK;
470 }
471
Dump(int fd,const std::vector<std::u16string> & args)472 int TimeSystemAbility::Dump(int fd, const std::vector<std::u16string> &args)
473 {
474 int uid = static_cast<int>(IPCSkeleton::GetCallingUid());
475 const int maxUid = 10000;
476 if (uid > maxUid) {
477 return E_TIME_DEAL_FAILED;
478 }
479
480 std::vector<std::string> argsStr;
481 for (auto &item : args) {
482 argsStr.emplace_back(Str16ToStr8(item));
483 }
484
485 TimeCmdDispatcher::GetInstance().Dispatch(fd, argsStr);
486 return ERR_OK;
487 }
488
DumpAllTimeInfo(int fd,const std::vector<std::string> & input)489 void TimeSystemAbility::DumpAllTimeInfo(int fd, const std::vector<std::string> &input)
490 {
491 dprintf(fd, "\n - dump all time info :\n");
492 struct timespec ts{};
493 struct tm timestr{};
494 char date_time[64];
495 if (GetTimeByClockId(CLOCK_BOOTTIME, ts)) {
496 auto localTime = localtime_r(&ts.tv_sec, ×tr);
497 if (localTime == nullptr) {
498 return;
499 }
500 strftime(date_time, sizeof(date_time), "%Y-%m-%d %H:%M:%S", localTime);
501 dprintf(fd, " * date time = %s\n", date_time);
502 } else {
503 dprintf(fd, " * dump date time error.\n");
504 }
505 dprintf(fd, " - dump the time Zone:\n");
506 std::string timeZone;
507 int32_t bRet = GetTimeZone(timeZone);
508 if (bRet == ERR_OK) {
509 dprintf(fd, " * time zone = %s\n", timeZone.c_str());
510 } else {
511 dprintf(fd, " * dump time zone error,is %s\n", timeZone.c_str());
512 }
513 }
514
DumpTimerInfo(int fd,const std::vector<std::string> & input)515 void TimeSystemAbility::DumpTimerInfo(int fd, const std::vector<std::string> &input)
516 {
517 dprintf(fd, "\n - dump all timer info :\n");
518 auto timerManager = TimerManager::GetInstance();
519 if (timerManager == nullptr) {
520 return;
521 }
522 timerManager->ShowTimerEntryMap(fd);
523 }
524
DumpTimerInfoById(int fd,const std::vector<std::string> & input)525 void TimeSystemAbility::DumpTimerInfoById(int fd, const std::vector<std::string> &input)
526 {
527 dprintf(fd, "\n - dump the timer info with timer id:\n");
528 int paramNumPos = 2;
529 auto timerManager = TimerManager::GetInstance();
530 if (timerManager == nullptr) {
531 return;
532 }
533 timerManager->ShowTimerEntryById(fd, std::atoi(input.at(paramNumPos).c_str()));
534 }
535
DumpTimerTriggerById(int fd,const std::vector<std::string> & input)536 void TimeSystemAbility::DumpTimerTriggerById(int fd, const std::vector<std::string> &input)
537 {
538 dprintf(fd, "\n - dump timer trigger statics with timer id:\n");
539 int paramNumPos = 2;
540 auto timerManager = TimerManager::GetInstance();
541 if (timerManager == nullptr) {
542 return;
543 }
544 timerManager->ShowTimerTriggerById(fd, std::atoi(input.at(paramNumPos).c_str()));
545 }
546
DumpIdleTimerInfo(int fd,const std::vector<std::string> & input)547 void TimeSystemAbility::DumpIdleTimerInfo(int fd, const std::vector<std::string> &input)
548 {
549 dprintf(fd, "\n - dump idle timer info :\n");
550 auto timerManager = TimerManager::GetInstance();
551 if (timerManager == nullptr) {
552 return;
553 }
554 timerManager->ShowIdleTimerInfo(fd);
555 }
556
DumpProxyTimerInfo(int fd,const std::vector<std::string> & input)557 void TimeSystemAbility::DumpProxyTimerInfo(int fd, const std::vector<std::string> &input)
558 {
559 dprintf(fd, "\n - dump proxy map:\n");
560 int64_t times;
561 TimeUtils::GetBootTimeNs(times);
562 TimerProxy::GetInstance().ShowProxyTimerInfo(fd, times);
563 }
564
DumpUidTimerMapInfo(int fd,const std::vector<std::string> & input)565 void TimeSystemAbility::DumpUidTimerMapInfo(int fd, const std::vector<std::string> &input)
566 {
567 dprintf(fd, "\n - dump uid timer map:\n");
568 int64_t times;
569 TimeUtils::GetBootTimeNs(times);
570 TimerProxy::GetInstance().ShowUidTimerMapInfo(fd, times);
571 }
572
DumpProxyDelayTime(int fd,const std::vector<std::string> & input)573 void TimeSystemAbility::DumpProxyDelayTime(int fd, const std::vector<std::string> &input)
574 {
575 dprintf(fd, "\n - dump proxy delay time:\n");
576 TimerProxy::GetInstance().ShowProxyDelayTime(fd);
577 }
578
DumpPidTimerMapInfo(int fd,const std::vector<std::string> & input)579 void TimeSystemAbility::DumpPidTimerMapInfo(int fd, const std::vector<std::string> &input)
580 {
581 dprintf(fd, "\n - dump pid timer map:\n");
582 int64_t times;
583 TimeUtils::GetBootTimeNs(times);
584 TimerProxy::GetInstance().ShowPidTimerMapInfo(fd, times);
585 }
586
DumpAdjustTime(int fd,const std::vector<std::string> & input)587 void TimeSystemAbility::DumpAdjustTime(int fd, const std::vector<std::string> &input)
588 {
589 dprintf(fd, "\n - dump adjust timer info:\n");
590 TimerProxy::GetInstance().ShowAdjustTimerInfo(fd);
591 }
592
SetRtcTime(time_t sec)593 int TimeSystemAbility::SetRtcTime(time_t sec)
594 {
595 struct rtc_time rtc {};
596 struct tm tm {};
597 struct tm *gmtime_res = nullptr;
598 int fd = -1;
599 int res;
600 if (rtcId < 0) {
601 TIME_HILOGE(TIME_MODULE_SERVICE, "invalid rtc id: %{public}s:", strerror(ENODEV));
602 return E_TIME_SET_RTC_FAILED;
603 }
604 std::stringstream strs;
605 strs << "/dev/rtc" << rtcId;
606 auto rtcDev = strs.str();
607 TIME_HILOGI(TIME_MODULE_SERVICE, "rtc_dev : %{public}s:", rtcDev.data());
608 auto rtcData = rtcDev.data();
609 fd = open(rtcData, O_RDWR);
610 if (fd < 0) {
611 TIME_HILOGE(TIME_MODULE_SERVICE, "open failed %{public}s: %{public}s", rtcDev.data(), strerror(errno));
612 return E_TIME_SET_RTC_FAILED;
613 }
614 gmtime_res = gmtime_r(&sec, &tm);
615 if (gmtime_res) {
616 rtc.tm_sec = tm.tm_sec;
617 rtc.tm_min = tm.tm_min;
618 rtc.tm_hour = tm.tm_hour;
619 rtc.tm_mday = tm.tm_mday;
620 rtc.tm_mon = tm.tm_mon;
621 rtc.tm_year = tm.tm_year;
622 rtc.tm_wday = tm.tm_wday;
623 rtc.tm_yday = tm.tm_yday;
624 rtc.tm_isdst = tm.tm_isdst;
625 res = ioctl(fd, RTC_SET_TIME, &rtc);
626 if (res < 0) {
627 TIME_HILOGE(TIME_MODULE_SERVICE, "ioctl RTC_SET_TIME failed,errno: %{public}s, res: %{public}d",
628 strerror(errno), res);
629 }
630 } else {
631 TIME_HILOGE(TIME_MODULE_SERVICE, "convert rtc time failed: %{public}s", strerror(errno));
632 res = E_TIME_SET_RTC_FAILED;
633 }
634 close(fd);
635 return res;
636 }
637
CheckRtc(const std::string & rtcPath,uint64_t rtcId)638 bool TimeSystemAbility::CheckRtc(const std::string &rtcPath, uint64_t rtcId)
639 {
640 std::stringstream strs;
641 strs << rtcPath << "/rtc" << rtcId << "/hctosys";
642 auto hctosys_path = strs.str();
643
644 std::fstream file(hctosys_path.data(), std::ios_base::in);
645 if (file.is_open()) {
646 return true;
647 } else {
648 TIME_HILOGE(TIME_MODULE_SERVICE, "failed to open %{public}s", hctosys_path.data());
649 return false;
650 }
651 }
652
GetWallClockRtcId()653 int TimeSystemAbility::GetWallClockRtcId()
654 {
655 std::string rtcPath = "/sys/class/rtc";
656
657 std::unique_ptr<DIR, int (*)(DIR *)> dir(opendir(rtcPath.c_str()), closedir);
658 if (!dir.get()) {
659 TIME_HILOGE(TIME_MODULE_SERVICE, "failed to open %{public}s: %{public}s", rtcPath.c_str(), strerror(errno));
660 return -1;
661 }
662
663 struct dirent *dirent;
664 std::string s = "rtc";
665 while (errno = 0, dirent = readdir(dir.get())) {
666 std::string name(dirent->d_name);
667 unsigned long rtcId = 0;
668 auto index = name.find(s);
669 if (index == std::string::npos) {
670 continue;
671 } else {
672 auto rtcIdStr = name.substr(index + s.length());
673 rtcId = std::stoul(rtcIdStr);
674 }
675 if (CheckRtc(rtcPath, rtcId)) {
676 TIME_HILOGD(TIME_MODULE_SERVICE, "found wall clock rtc %{public}ld", rtcId);
677 return rtcId;
678 }
679 }
680
681 if (errno == 0) {
682 TIME_HILOGE(TIME_MODULE_SERVICE, "no wall clock rtc found");
683 } else {
684 TIME_HILOGE(TIME_MODULE_SERVICE, "failed to check rtc: %{public}s", strerror(errno));
685 }
686 return -1;
687 }
688
SetTimeZone(const std::string & timeZoneId,APIVersion apiVersion)689 int32_t TimeSystemAbility::SetTimeZone(const std::string &timeZoneId, APIVersion apiVersion)
690 {
691 if (!TimeZoneInfo::GetInstance().SetTimezone(timeZoneId)) {
692 TIME_HILOGE(TIME_MODULE_SERVICE, "Set timezone failed :%{public}s", timeZoneId.c_str());
693 return E_TIME_DEAL_FAILED;
694 }
695 int64_t currentTime = 0;
696 TimeUtils::GetBootTimeMs(currentTime);
697 TimeServiceNotify::GetInstance().PublishTimeZoneChangeEvents(currentTime);
698 return ERR_OK;
699 }
700
GetTimeZone(std::string & timeZoneId)701 int32_t TimeSystemAbility::GetTimeZone(std::string &timeZoneId)
702 {
703 if (!TimeZoneInfo::GetInstance().GetTimezone(timeZoneId)) {
704 TIME_HILOGE(TIME_MODULE_SERVICE, "get timezone failed");
705 return E_TIME_DEAL_FAILED;
706 }
707 TIME_HILOGD(TIME_MODULE_SERVICE, "Current timezone : %{public}s", timeZoneId.c_str());
708 return ERR_OK;
709 }
710
GetThreadTimeMs(int64_t & time)711 int32_t TimeSystemAbility::GetThreadTimeMs(int64_t &time)
712 {
713 struct timespec tv {};
714 clockid_t cid;
715 int ret = pthread_getcpuclockid(pthread_self(), &cid);
716 if (ret != E_TIME_OK) {
717 return E_TIME_PARAMETERS_INVALID;
718 }
719 if (GetTimeByClockId(cid, tv)) {
720 time = tv.tv_sec * MILLI_TO_BASE + tv.tv_nsec / NANO_TO_MILLI;
721 return ERR_OK;
722 }
723 return E_TIME_DEAL_FAILED;
724 }
725
GetThreadTimeNs(int64_t & time)726 int32_t TimeSystemAbility::GetThreadTimeNs(int64_t &time)
727 {
728 struct timespec tv {};
729 clockid_t cid;
730 int ret = pthread_getcpuclockid(pthread_self(), &cid);
731 if (ret != E_TIME_OK) {
732 return E_TIME_PARAMETERS_INVALID;
733 }
734 if (GetTimeByClockId(cid, tv)) {
735 time = tv.tv_sec * NANO_TO_BASE + tv.tv_nsec;
736 return ERR_OK;
737 }
738 return E_TIME_DEAL_FAILED;
739 }
740
GetTimeByClockId(clockid_t clockId,struct timespec & tv)741 bool TimeSystemAbility::GetTimeByClockId(clockid_t clockId, struct timespec &tv)
742 {
743 if (clock_gettime(clockId, &tv) < 0) {
744 TIME_HILOGE(TIME_MODULE_SERVICE, "Failed clock_gettime.");
745 return false;
746 }
747 return true;
748 }
749
ProxyTimer(int32_t uid,bool isProxy,bool needRetrigger)750 bool TimeSystemAbility::ProxyTimer(int32_t uid, bool isProxy, bool needRetrigger)
751 {
752 if (!TimePermission::CheckProxyCallingPermission()) {
753 TIME_HILOGE(TIME_MODULE_SERVICE, "ProxyTimer permission check failed");
754 return E_TIME_NO_PERMISSION;
755 }
756 TIME_HILOGD(TIME_MODULE_SERVICE, "ProxyTimer service start uid: %{public}d, isProxy: %{public}d", uid, isProxy);
757 auto timerManager = TimerManager::GetInstance();
758 if (timerManager == nullptr) {
759 return false;
760 }
761 return timerManager->ProxyTimer(uid, isProxy, needRetrigger);
762 }
763
AdjustTimer(bool isAdjust,uint32_t interval)764 int32_t TimeSystemAbility::AdjustTimer(bool isAdjust, uint32_t interval)
765 {
766 auto timerManager = TimerManager::GetInstance();
767 if (timerManager == nullptr) {
768 return E_TIME_NULLPTR;
769 }
770 if (!timerManager->AdjustTimer(isAdjust, interval)) {
771 return E_TIME_NO_TIMER_ADJUST;
772 }
773 return E_TIME_OK;
774 }
775
ProxyTimer(int32_t uid,std::set<int> pidList,bool isProxy,bool needRetrigger)776 bool TimeSystemAbility::ProxyTimer(int32_t uid, std::set<int> pidList, bool isProxy, bool needRetrigger)
777 {
778 if (!TimePermission::CheckProxyCallingPermission()) {
779 TIME_HILOGE(TIME_MODULE_SERVICE, "ProxyTimer permission check failed");
780 return E_TIME_NO_PERMISSION;
781 }
782 auto timerManager = TimerManager::GetInstance();
783 if (timerManager == nullptr) {
784 return false;
785 }
786 return timerManager->ProxyTimer(uid, pidList, isProxy, needRetrigger);
787 }
788
SetTimerExemption(const std::unordered_set<std::string> & nameArr,bool isExemption)789 int32_t TimeSystemAbility::SetTimerExemption(const std::unordered_set<std::string> &nameArr, bool isExemption)
790 {
791 auto timerManager = TimerManager::GetInstance();
792 if (timerManager == nullptr) {
793 return E_TIME_NULLPTR;
794 }
795 timerManager->SetTimerExemption(nameArr, isExemption);
796 return E_TIME_OK;
797 }
798
ResetAllProxy()799 bool TimeSystemAbility::ResetAllProxy()
800 {
801 if (!TimePermission::CheckProxyCallingPermission()) {
802 TIME_HILOGE(TIME_MODULE_SERVICE, "ResetAllProxy permission check failed");
803 return E_TIME_NO_PERMISSION;
804 }
805 TIME_HILOGD(TIME_MODULE_SERVICE, "ResetAllProxy service");
806 auto timerManager = TimerManager::GetInstance();
807 if (timerManager == nullptr) {
808 return false;
809 }
810 return timerManager->ResetAllProxy();
811 }
812
GetNtpTimeMs(int64_t & time)813 int32_t TimeSystemAbility::GetNtpTimeMs(int64_t &time)
814 {
815 auto ret = NtpUpdateTime::GetInstance().GetNtpTime(time);
816 if (!ret) {
817 TIME_HILOGE(TIME_MODULE_SERVICE, "GetNtpTimeMs failed");
818 return E_TIME_NTP_UPDATE_FAILED;
819 }
820 return E_TIME_OK;
821 }
822
GetRealTimeMs(int64_t & time)823 int32_t TimeSystemAbility::GetRealTimeMs(int64_t &time)
824 {
825 auto ret = NtpUpdateTime::GetInstance().GetRealTime(time);
826 if (!ret) {
827 TIME_HILOGE(TIME_MODULE_SERVICE, "GetRealTimeMs failed");
828 return E_TIME_NTP_NOT_UPDATE;
829 }
830 return E_TIME_OK;
831 }
832
OnRemoteDied(const wptr<IRemoteObject> & object)833 void TimeSystemAbility::RSSSaDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &object)
834 {
835 auto timerManager = TimerManager::GetInstance();
836 if (timerManager == nullptr) {
837 return;
838 }
839 timerManager->HandleRSSDeath();
840 }
841
RegisterRSSDeathCallback()842 void TimeSystemAbility::RegisterRSSDeathCallback()
843 {
844 TIME_HILOGD(TIME_MODULE_SERVICE, "register rss death callback");
845 auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
846 if (systemAbilityManager == nullptr) {
847 TIME_HILOGE(TIME_MODULE_CLIENT, "Getting SystemAbilityManager failed.");
848 return;
849 }
850
851 auto systemAbility = systemAbilityManager->GetSystemAbility(DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID);
852 if (systemAbility == nullptr) {
853 TIME_HILOGE(TIME_MODULE_CLIENT, "Get SystemAbility failed.");
854 return;
855 }
856
857 if (deathRecipient_ == nullptr) {
858 deathRecipient_ = new RSSSaDeathRecipient();
859 }
860
861 systemAbility->AddDeathRecipient(deathRecipient_);
862 }
863
OnSyncShutdown()864 void TimeSystemAbility::TimePowerStateListener::OnSyncShutdown()
865 {
866 // Clears `drop_on_reboot` table.
867 TIME_HILOGI(TIME_MODULE_SERVICE, "OnSyncShutdown");
868 TimeSystemAbility::GetInstance()->SetAutoReboot();
869 TimeDatabase::GetInstance().ClearDropOnReboot();
870 }
871
RegisterPowerStateListener()872 void TimeSystemAbility::RegisterPowerStateListener()
873 {
874 TIME_HILOGI(TIME_MODULE_CLIENT, "RegisterPowerStateListener");
875 auto& powerManagerClient = OHOS::PowerMgr::ShutdownClient::GetInstance();
876 sptr<OHOS::PowerMgr::ISyncShutdownCallback> syncShutdownCallback = new TimePowerStateListener();
877 if (!syncShutdownCallback) {
878 TIME_HILOGE(TIME_MODULE_SERVICE, "Get TimePowerStateListener failed.");
879 return;
880 }
881 powerManagerClient.RegisterShutdownCallback(syncShutdownCallback, PowerMgr::ShutdownPriority::HIGH);
882 TIME_HILOGI(TIME_MODULE_CLIENT, "RegisterPowerStateListener end");
883 }
884
RecoverTimer()885 bool TimeSystemAbility::RecoverTimer()
886 {
887 auto database = TimeDatabase::GetInstance();
888 OHOS::NativeRdb::RdbPredicates holdRdbPredicates(HOLD_ON_REBOOT);
889 auto holdResultSet = database.Query(holdRdbPredicates, ALL_DATA);
890 if (holdResultSet == nullptr || holdResultSet->GoToFirstRow() != OHOS::NativeRdb::E_OK) {
891 TIME_HILOGI(TIME_MODULE_SERVICE, "hold result set is nullptr or go to first row failed");
892 } else {
893 int count;
894 holdResultSet->GetRowCount(count);
895 TIME_HILOGI(TIME_MODULE_SERVICE, "hold result rows count: %{public}d", count);
896 RecoverTimerInner(holdResultSet);
897 }
898 if (holdResultSet != nullptr) {
899 holdResultSet->Close();
900 }
901
902 OHOS::NativeRdb::RdbPredicates dropRdbPredicates(DROP_ON_REBOOT);
903 auto dropResultSet = database.Query(dropRdbPredicates, ALL_DATA);
904 if (dropResultSet == nullptr || dropResultSet->GoToFirstRow() != OHOS::NativeRdb::E_OK) {
905 TIME_HILOGI(TIME_MODULE_SERVICE, "drop result set is nullptr or go to first row failed");
906 } else {
907 int count;
908 dropResultSet->GetRowCount(count);
909 TIME_HILOGI(TIME_MODULE_SERVICE, "drop result rows count: %{public}d", count);
910 RecoverTimerInner(dropResultSet);
911 }
912 if (dropResultSet != nullptr) {
913 dropResultSet->Close();
914 }
915 return true;
916 }
917
RecoverTimerInner(std::shared_ptr<OHOS::NativeRdb::ResultSet> resultSet)918 void TimeSystemAbility::RecoverTimerInner(std::shared_ptr<OHOS::NativeRdb::ResultSet> resultSet)
919 {
920 auto timerManager = TimerManager::GetInstance();
921 if (timerManager == nullptr) {
922 return;
923 }
924 do {
925 auto timerId = static_cast<uint64_t>(GetLong(resultSet, 0));
926 auto timerInfo = std::make_shared<TimerEntry>(TimerEntry {
927 // Line 0 is 'timerId'
928 timerId,
929 // Line 1 is 'type'
930 GetInt(resultSet, 1),
931 // Line 3 is 'windowLength'
932 static_cast<uint64_t>(GetLong(resultSet, 3)),
933 // Line 4 is 'interval'
934 static_cast<uint64_t>(GetLong(resultSet, 4)),
935 // Line 2 is 'flag'
936 GetInt(resultSet, 2),
937 // Callback can't recover.
938 nullptr,
939 // Line 7 is 'wantAgent'
940 OHOS::AbilityRuntime::WantAgent::WantAgentHelper::FromString(GetString(resultSet, 7)),
941 // Line 5 is 'uid'
942 GetInt(resultSet, 5),
943 // Line 10 is 'pid'
944 GetInt(resultSet, 10),
945 // Line 6 is 'bundleName'
946 GetString(resultSet, 6)
947 });
948 if (timerInfo->wantAgent == nullptr) {
949 TIME_HILOGE(TIME_MODULE_SERVICE, "wantAgent is nullptr, uid=%{public}d, id=%{public}" PRId64 "",
950 timerInfo->uid, timerInfo->id);
951 continue;
952 }
953 timerManager->ReCreateTimer(timerId, timerInfo);
954 // Line 8 is 'state'
955 auto state = static_cast<uint8_t>(GetInt(resultSet, 8));
956 if (state == 1) {
957 // Line 9 is 'triggerTime'
958 auto triggerTime = static_cast<uint64_t>(GetLong(resultSet, 9));
959 timerManager->StartTimer(timerId, triggerTime);
960 }
961 } while (resultSet->GoToNextRow() == OHOS::NativeRdb::E_OK);
962 }
963
SetAutoReboot()964 void TimeSystemAbility::SetAutoReboot()
965 {
966 auto database = TimeDatabase::GetInstance();
967 OHOS::NativeRdb::RdbPredicates holdRdbPredicates(HOLD_ON_REBOOT);
968 holdRdbPredicates.EqualTo("state", 1)->OrderByAsc("triggerTime");
969 auto resultSet = database.Query(holdRdbPredicates, { "bundleName", "triggerTime" });
970 if (resultSet == nullptr) {
971 TIME_HILOGI(TIME_MODULE_SERVICE, "no need to set RTC");
972 return;
973 }
974 int64_t currentTime = 0;
975 TimeUtils::GetWallTimeMs(currentTime);
976 auto bundleList = TimeFileUtils::GetBundleList();
977 do {
978 auto bundleName = GetString(resultSet, 0);
979 uint64_t triggerTime = static_cast<uint64_t>(GetLong(resultSet, 1));
980 if (triggerTime < static_cast<uint64_t>(currentTime)) {
981 TIME_HILOGI(TIME_MODULE_SERVICE,
982 "triggerTime: %{public}" PRIu64" currentTime: %{public}" PRId64"", triggerTime, currentTime);
983 continue;
984 }
985 if (bundleName == (bundleList.empty() ? "" : bundleList[0])) {
986 int tmfd = timerfd_create(CLOCK_POWEROFF_ALARM, TFD_NONBLOCK);
987 if (tmfd < 0) {
988 TIME_HILOGE(TIME_MODULE_SERVICE, "timerfd_create error: %{public}s", strerror(errno));
989 resultSet->Close();
990 return;
991 }
992 if (static_cast<uint64_t>(currentTime) + TWO_MINUTES_TO_MILLI > triggerTime) {
993 TIME_HILOGI(TIME_MODULE_SERVICE, "interval less than 2min");
994 triggerTime = static_cast<uint64_t>(currentTime) + TWO_MINUTES_TO_MILLI;
995 }
996 struct itimerspec new_value;
997 std::chrono::nanoseconds nsec(triggerTime * MILLISECOND_TO_NANO);
998 auto second = std::chrono::duration_cast<std::chrono::seconds>(nsec);
999 new_value.it_value.tv_sec = second.count();
1000 new_value.it_value.tv_nsec = (nsec - second).count();
1001 TIME_HILOGI(TIME_MODULE_SERVICE, "currentTime:%{public}" PRId64 ", second:%{public}" PRId64 ","
1002 "nanosecond:%{public}" PRId64"", currentTime, static_cast<int64_t>(new_value.it_value.tv_sec),
1003 static_cast<int64_t>(new_value.it_value.tv_nsec));
1004 int ret = timerfd_settime(tmfd, TFD_TIMER_ABSTIME, &new_value, nullptr);
1005 if (ret < 0) {
1006 TIME_HILOGE(TIME_MODULE_SERVICE, "timerfd_settime error: %{public}s", strerror(errno));
1007 close(tmfd);
1008 }
1009 resultSet->Close();
1010 return;
1011 }
1012 } while (resultSet->GoToNextRow() == OHOS::NativeRdb::E_OK);
1013 resultSet->Close();
1014 }
1015 } // namespace MiscServices
1016 } // namespace OHOS