1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Disk protection for HP/DELL machines.
4 * Copyright 2008 Eric Piel
5 * Copyright 2009 Pavel Machek <pavel@ucw.cz>
6 * Copyright 2012 Sonal Santan
7 * Copyright 2014 Pali Rohár <pali.rohar@gmail.com>
15 #include <sys/types.h>
25 static char unload_heads_path
[64];
26 static char device_path
[32];
27 static const char app_name
[] = "FREE FALL";
29 static int set_unload_heads_path(char *device
)
31 if (strlen(device
) <= 5 || strncmp(device
, "/dev/", 5) != 0)
33 strncpy(device_path
, device
, sizeof(device_path
) - 1);
35 snprintf(unload_heads_path
, sizeof(unload_heads_path
) - 1,
36 "/sys/block/%s/device/unload_heads", device
+5);
40 static int valid_disk(void)
42 int fd
= open(unload_heads_path
, O_RDONLY
);
45 perror(unload_heads_path
);
53 static void write_int(char *path
, int i
)
56 int fd
= open(path
, O_RDWR
);
63 sprintf(buf
, "%d", i
);
65 if (write(fd
, buf
, strlen(buf
)) != strlen(buf
)) {
73 static void set_led(int on
)
77 write_int("/sys/class/leds/hp::hddprotect/brightness", on
);
80 static void protect(int seconds
)
82 const char *str
= (seconds
== 0) ? "Unparked" : "Parked";
84 write_int(unload_heads_path
, seconds
*1000);
85 syslog(LOG_INFO
, "%s %s disk head\n", str
, device_path
);
88 static int on_ac(void)
90 /* /sys/class/power_supply/AC0/online */
94 static int lid_open(void)
96 /* /proc/acpi/button/lid/LID/state */
100 static void ignore_me(int signum
)
106 int main(int argc
, char **argv
)
110 struct sched_param param
;
113 ret
= set_unload_heads_path("/dev/sda");
115 ret
= set_unload_heads_path(argv
[1]);
119 if (ret
|| !valid_disk()) {
120 fprintf(stderr
, "usage: %s <device> (default: /dev/sda)\n",
125 fd
= open("/dev/freefall", O_RDONLY
);
127 perror("/dev/freefall");
131 if (stat("/sys/class/leds/hp::hddprotect/brightness", &st
))
134 if (daemon(0, 0) != 0) {
139 openlog(app_name
, LOG_CONS
| LOG_PID
| LOG_NDELAY
, LOG_LOCAL1
);
141 param
.sched_priority
= sched_get_priority_max(SCHED_FIFO
);
142 sched_setscheduler(0, SCHED_FIFO
, ¶m
);
143 mlockall(MCL_CURRENT
|MCL_FUTURE
);
145 signal(SIGALRM
, ignore_me
);
150 ret
= read(fd
, &count
, sizeof(count
));
152 if ((ret
== -1) && (errno
== EINTR
)) {
153 /* Alarm expired, time to unpark the heads */
157 if (ret
!= sizeof(count
)) {
164 if (1 || on_ac() || lid_open())