Home | History | Annotate | Download | only in init
      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 #include "log.h"
     27 
     28 #ifdef _INIT_INIT_H
     29 #error "Do not include init.h in files used by ueventd or watchdogd; it will expose init's globals"
     30 #endif
     31 
     32 #define DEV_NAME "/dev/watchdog"
     33 
     34 namespace android {
     35 namespace init {
     36 
     37 int watchdogd_main(int argc, char **argv) {
     38     InitKernelLogging(argv);
     39 
     40     int interval = 10;
     41     if (argc >= 2) interval = atoi(argv[1]);
     42 
     43     int margin = 10;
     44     if (argc >= 3) margin = atoi(argv[2]);
     45 
     46     LOG(INFO) << "watchdogd started (interval " << interval << ", margin " << margin << ")!";
     47 
     48     int fd = open(DEV_NAME, O_RDWR|O_CLOEXEC);
     49     if (fd == -1) {
     50         PLOG(ERROR) << "Failed to open " << DEV_NAME;
     51         return 1;
     52     }
     53 
     54     int timeout = interval + margin;
     55     int ret = ioctl(fd, WDIOC_SETTIMEOUT, &timeout);
     56     if (ret) {
     57         PLOG(ERROR) << "Failed to set timeout to " << timeout;
     58         ret = ioctl(fd, WDIOC_GETTIMEOUT, &timeout);
     59         if (ret) {
     60             PLOG(ERROR) << "Failed to get timeout";
     61         } else {
     62             if (timeout > margin) {
     63                 interval = timeout - margin;
     64             } else {
     65                 interval = 1;
     66             }
     67             LOG(WARNING) << "Adjusted interval to timeout returned by driver: "
     68                          << "timeout " << timeout
     69                          << ", interval " << interval
     70                          << ", margin " << margin;
     71         }
     72     }
     73 
     74     while (true) {
     75         write(fd, "", 1);
     76         sleep(interval);
     77     }
     78 }
     79 
     80 }  // namespace init
     81 }  // namespace android
     82