1 /* Disk protection for HP/DELL machines.
3 * Copyright 2008 Eric Piel
4 * Copyright 2009 Pavel Machek <pavel@ucw.cz>
5 * Copyright 2012 Sonal Santan
6 * Copyright 2014 Pali Rohár <pali.rohar@gmail.com>
16 #include <sys/types.h>
26 static char unload_heads_path[64];
27 static char device_path[32];
28 static const char app_name[] = "FREE FALL";
30 static int set_unload_heads_path(char *device)
34 if (strlen(device) <= 5 || strncmp(device, "/dev/", 5) != 0)
36 strncpy(devname, device + 5, sizeof(devname) - 1);
37 devname[sizeof(devname) - 1] = '\0';
38 strncpy(device_path, device, sizeof(device_path) - 1);
40 snprintf(unload_heads_path, sizeof(unload_heads_path) - 1,
41 "/sys/block/%s/device/unload_heads", devname);
45 static int valid_disk(void)
47 int fd = open(unload_heads_path, O_RDONLY);
50 perror(unload_heads_path);
58 static void write_int(char *path, int i)
61 int fd = open(path, O_RDWR);
68 sprintf(buf, "%d", i);
70 if (write(fd, buf, strlen(buf)) != strlen(buf)) {
78 static void set_led(int on)
82 write_int("/sys/class/leds/hp::hddprotect/brightness", on);
85 static void protect(int seconds)
87 const char *str = (seconds == 0) ? "Unparked" : "Parked";
89 write_int(unload_heads_path, seconds*1000);
90 syslog(LOG_INFO, "%s %s disk head\n", str, device_path);
93 static int on_ac(void)
95 /* /sys/class/power_supply/AC0/online */
99 static int lid_open(void)
101 /* /proc/acpi/button/lid/LID/state */
105 static void ignore_me(int signum)
111 int main(int argc, char **argv)
115 struct sched_param param;
118 ret = set_unload_heads_path("/dev/sda");
120 ret = set_unload_heads_path(argv[1]);
124 if (ret || !valid_disk()) {
125 fprintf(stderr, "usage: %s <device> (default: /dev/sda)\n",
130 fd = open("/dev/freefall", O_RDONLY);
132 perror("/dev/freefall");
136 if (stat("/sys/class/leds/hp::hddprotect/brightness", &st))
139 if (daemon(0, 0) != 0) {
144 openlog(app_name, LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL1);
146 param.sched_priority = sched_get_priority_max(SCHED_FIFO);
147 sched_setscheduler(0, SCHED_FIFO, ¶m);
148 mlockall(MCL_CURRENT|MCL_FUTURE);
150 signal(SIGALRM, ignore_me);
155 ret = read(fd, &count, sizeof(count));
157 if ((ret == -1) && (errno == EINTR)) {
158 /* Alarm expired, time to unpark the heads */
162 if (ret != sizeof(count)) {
169 if (1 || on_ac() || lid_open())