1 /*
2  * Copyright (C) 2012 The Android Open Source Project
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <linux/watchdog.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <unistd.h>
23 
24 #include <android-base/logging.h>
25 
26 #define DEV_NAME "/dev/watchdog"
27 
main(int argc,char ** argv)28 int main(int argc, char** argv) {
29     android::base::InitLogging(argv, &android::base::KernelLogger);
30 
31     int interval = 10;
32     if (argc >= 2) interval = atoi(argv[1]);
33 
34     int margin = 10;
35     if (argc >= 3) margin = atoi(argv[2]);
36 
37     LOG(INFO) << "watchdogd started (interval " << interval << ", margin " << margin << ")!";
38 
39     int fd = open(DEV_NAME, O_RDWR | O_CLOEXEC);
40     if (fd == -1) {
41         PLOG(ERROR) << "Failed to open " << DEV_NAME;
42         return 1;
43     }
44 
45     int timeout = interval + margin;
46     int ret = ioctl(fd, WDIOC_SETTIMEOUT, &timeout);
47     if (ret) {
48         PLOG(ERROR) << "Failed to set timeout to " << timeout;
49         ret = ioctl(fd, WDIOC_GETTIMEOUT, &timeout);
50         if (ret) {
51             PLOG(ERROR) << "Failed to get timeout";
52         } else {
53             if (timeout > margin) {
54                 interval = timeout - margin;
55             } else {
56                 interval = 1;
57             }
58             LOG(WARNING) << "Adjusted interval to timeout returned by driver: "
59                          << "timeout " << timeout << ", interval " << interval << ", margin "
60                          << margin;
61         }
62     }
63 
64     while (true) {
65         write(fd, "", 1);
66         sleep(interval);
67     }
68 }
69