-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathhibernation-setup-tool.c
1799 lines (1432 loc) · 55.9 KB
/
hibernation-setup-tool.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Hibernation Setup Tool
// Sets up a swap area suitable to hibernate a Linux system.
//
// Copyright (c) 2021 Microsoft Corp.
// Licensed under the terms of the MIT license.
#define _GNU_SOURCE
/* sys/mount.h has to be included before linux/fs.h
* https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=898743
*/
#include <sys/mount.h>
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <ftw.h>
#include <linux/falloc.h>
#include <linux/fs.h>
#include <linux/ioctl.h>
#include <linux/magic.h>
#include <linux/suspend_ioctls.h>
#include <mntent.h>
#include <netdb.h>
#include <netinet/in.h>
#include <spawn.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/auxv.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/statfs.h>
#include <sys/swap.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include <sys/vfs.h>
#include <sys/wait.h>
#include <syscall.h>
#include <syslog.h>
#include <sys/socket.h>
#include <unistd.h>
#define MEGA_BYTES (1ul << 20)
#define GIGA_BYTES (1ul << 30)
#ifndef SEEK_HOLE
#define SEEK_HOLE 4
#endif
#ifndef IOPRIO_WHO_PROCESS
#define IOPRIO_WHO_PROCESS 1
#endif
#ifndef IOPRIO_CLASS_IDLE
#define IOPRIO_CLASS_IDLE 3
#endif
#ifndef IOPRIO_PRIO_VALUE
#define IOPRIO_PRIO_VALUE(klass, data) (((klass) << 13) | (data))
#endif
#ifndef XFS_SUPER_MAGIC
#define XFS_SUPER_MAGIC ('X' << 24 | 'F' << 16 | 'S' << 8 | 'B')
#endif
static const char swap_file_name[] = "/hibfile.sys";
/* Prefixes are needed when running services. This makes it easier to grep for
* code run via hibernate, resume hooks and hibernation tool. */
static bool log_needs_tool_prefix = false;
static bool log_needs_pre_hook_prefix = false;
static bool log_needs_post_hook_prefix = false;
/* We don't always want to spam syslog: spamming stdout is fine as this tool
* and its hooks are supposed to be executed as daemons in systemd and their
* output will be stored in their journal files. */
static bool log_needs_syslog = false;
/* This is a link pointing to a file in a tmpfs filesystem and is mostly used to detect
* if we got a cold boot or not. */
static const char hibernate_lock_file_name[] = "/etc/hibernation-setup-tool.last_hibernation";
enum host_vm_notification {
HOST_VM_NOTIFY_COLD_BOOT, /* Sent every time system cold boots */
HOST_VM_NOTIFY_HIBERNATING, /* Sent right before hibernation */
HOST_VM_NOTIFY_RESUMED_FROM_HIBERNATION, /* Sent right after hibernation */
HOST_VM_NOTIFY_PRE_HIBERNATION_FAILED, /* Sent on errors when hibernating or resuming */
};
struct swap_file {
size_t capacity;
char path[];
};
static int ioprio_set(int which, int who, int ioprio) { return (int)syscall(SYS_ioprio_set, which, who, ioprio); }
static void log_impl(int log_level, const char *fmt, va_list ap)
{
if (log_needs_syslog) {
va_list ap_cpy;
va_copy(ap_cpy, ap);
vsyslog(log_level, fmt, ap_cpy);
va_end(ap_cpy);
}
flockfile(stdout);
if (log_needs_tool_prefix)
printf("hibernation-setup-tool: ");
else if (log_needs_pre_hook_prefix)
printf("hibernate-hook: ");
else if (log_needs_post_hook_prefix)
printf("resume-hook: ");
if (log_level == LOG_INFO)
printf("INFO: ");
else if (log_level == LOG_ERR)
printf("ERROR: ");
else if (log_level == LOG_NOTICE)
printf("NOTICE: ");
vprintf(fmt, ap);
printf("\n");
funlockfile(stdout);
}
__attribute__((format(printf, 1, 2))) static void log_info(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
log_impl(LOG_INFO, fmt, ap);
va_end(ap);
}
__attribute__((format(printf, 1, 2))) static void log_notice(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
log_impl(LOG_NOTICE, fmt, ap);
va_end(ap);
}
__attribute__((format(printf, 1, 2))) __attribute__((noreturn)) static void log_fatal(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
log_impl(LOG_ERR, fmt, ap);
va_end(ap);
exit(1);
__builtin_unreachable();
}
static char *next_field(char *current)
{
if (!current)
return NULL;
if (*current == '\0')
return NULL;
while (!isspace(*current))
current++;
*current = '\0'; /* 0-terminate the previous call to next_field() */
current++; /* skip the NUL terminator */
while (isspace(*current))
current++;
return current;
}
static size_t parse_size_or_die(const char *ptr, const char expected_end, char **endptr)
{
size_t parsed;
errno = 0;
if (sizeof(size_t) == sizeof(unsigned long long)) {
parsed = strtoull(ptr, endptr, 10);
} else if (sizeof(size_t) == sizeof(unsigned long)) {
parsed = strtoul(ptr, endptr, 10);
} else {
log_fatal("Invalid size of size_t: %zu", sizeof(size_t));
}
if (errno || (endptr && **endptr != expected_end))
log_fatal("Could not parse size: %s", strerror(errno));
return parsed;
}
static const char *find_executable_in_path(const char *name, const char *path_env, char path_buf[static PATH_MAX])
{
if (!path_env)
path_env = "/bin:/sbin:/usr/bin:/usr/sbin";
while (*path_env) {
const char *p = strchr(path_env, ':');
int ret;
if (!p) {
/* Last segment of $PATH */
ret = snprintf(path_buf, PATH_MAX, "%s/%s", path_env, name);
path_env = "";
} else if (p - path_env) {
/* Middle segments */
ret = snprintf(path_buf, PATH_MAX, "%.*s/%s", (int)(p - path_env), path_env, name);
path_env = p + 1;
} else {
/* Empty segment or non-root directory? Skip. */
path_env = p + 1;
continue;
}
if (ret < 0 || ret >= PATH_MAX)
log_fatal("Building path to determine if %s exists would overflow buffer", name);
if (path_buf[0] != '/')
continue;
if (!access(path_buf, X_OK))
return path_buf;
}
return NULL;
}
static bool is_exec_in_path(const char *name)
{
char path_buf[PATH_MAX];
return find_executable_in_path(name, getenv("PATH"), path_buf) != NULL;
}
static struct swap_file *new_swap_file(const char *path, size_t capacity)
{
struct swap_file *out;
out = malloc(sizeof(*out) + strlen(path) + 1);
if (!out)
log_fatal("Could not allocate memory for swap file information");
out->capacity = capacity;
memcpy(out->path, path, strlen(path) + 1);
return out;
}
static struct swap_file *find_swap_file(size_t needed_size)
{
char buffer[1024];
FILE *swaps;
struct swap_file *out = NULL;
swaps = fopen("/proc/swaps", "re");
if (!swaps)
log_fatal("Could not open /proc/swaps: is /proc mounted?");
/* Skip first line (header) */
if (!fgets(buffer, sizeof(buffer), swaps))
log_fatal("Could not skip first line from /proc/swaps");
while (fgets(buffer, sizeof(buffer), swaps)) {
char *filename = buffer;
char *type = next_field(filename);
if (!type) {
log_info("Couldn't get the second field while parsing /proc/swaps");
break;
}
if (!strcmp(type, "file")) {
char *size = next_field(type);
if (!size)
log_fatal("Malformed line in /proc/swaps: can't find size column");
size_t size_as_int = parse_size_or_die(size, ' ', NULL);
if (size_as_int < needed_size)
continue;
out = new_swap_file(filename, size_as_int);
break;
}
}
fclose(swaps);
if (!out) {
struct stat st;
if (stat(swap_file_name, &st) < 0)
return NULL;
if (!S_ISREG(st.st_mode))
return NULL;
return new_swap_file(swap_file_name, st.st_size);
}
return out;
}
static size_t physical_memory(void)
{
FILE *meminfo;
char buffer[256];
size_t total = 0;
meminfo = fopen("/proc/meminfo", "re");
if (!meminfo)
log_fatal("Could not determine physical memory size. Is /proc mounted?");
while (fgets(buffer, sizeof(buffer), meminfo)) {
static const size_t mem_total_len = sizeof("MemTotal: ") - 1;
if (!strncmp(buffer, "MemTotal: ", mem_total_len)) {
char *endptr;
total = parse_size_or_die(buffer + mem_total_len, ' ', &endptr);
if (!strcmp(endptr, " kB\n"))
total *= 1024;
else if (!strcmp(endptr, " MB\n"))
total *= MEGA_BYTES;
else if (!strcmp(endptr, " GB\n"))
total *= 1024 * MEGA_BYTES;
else if (!strcmp(endptr, " TB\n"))
total *= (size_t)MEGA_BYTES * (size_t)MEGA_BYTES;
else
log_fatal("Could not determine unit for physical memory information");
break;
}
}
fclose(meminfo);
return total;
}
static size_t swap_needed_size(size_t phys_mem)
{
/* This is using the recommendation from the Fedora project documentation. */
if (phys_mem <= 2 * GIGA_BYTES)
return 3 * phys_mem;
if (phys_mem <= 8 * GIGA_BYTES)
return 2 * phys_mem;
if (phys_mem <= 64 * GIGA_BYTES)
return (3 * phys_mem) / 2;
/* Note: Fedora documentation doesn't recommend hibernation for machines over 64GB of RAM,
* but we're extending this for a bit. */
if (phys_mem <= 256 * GIGA_BYTES)
return (5 * phys_mem) / 4;
log_fatal("Hibernation not recommended for a machine with more than 256GB of RAM");
}
static size_t free_device_space()
{
struct statfs buffer;
size_t block_size;
size_t free_bytes;
if (statfs("/", &buffer) < 0)
log_fatal("Could not determine free device space: %s", strerror(errno));
block_size = buffer.f_bsize;
free_bytes = block_size * buffer.f_bfree;
return free_bytes;
}
static char *get_uuid_for_dev_path(const char *path)
{
struct stat dev_st;
struct dirent *ent;
char *uuid = NULL;
DIR *uuid_dir;
if (stat(path, &dev_st) < 0) {
log_info("Could not stat(%s): %s", path, strerror(errno));
return NULL;
}
uuid_dir = opendir("/dev/disk/by-uuid/");
if (!uuid_dir) {
log_info("Could not open directory /dev/disk/by-uuid/: %s", strerror(errno));
return NULL;
}
while ((ent = readdir(uuid_dir))) {
struct stat ent_st;
if (fstatat(dirfd(uuid_dir), ent->d_name, &ent_st, 0) < 0)
continue;
/* Shouldn't happen, but just in case */
if ((ent_st.st_mode & S_IFMT) != S_IFBLK)
continue;
if (ent_st.st_rdev == dev_st.st_rdev) {
uuid = strdup(ent->d_name);
break;
}
}
closedir(uuid_dir);
if (uuid)
log_info("UUID for device %s is %s", path, uuid);
return uuid;
}
static char *get_disk_uuid_for_file_path(const char *path)
{
FILE *mounts = setmntent("/proc/mounts", "re");
struct mntent *ent;
struct stat st;
if (!mounts)
return NULL;
if (stat(path, &st) < 0)
log_fatal("Could not stat(%s): %s", path, strerror(errno));
while ((ent = getmntent(mounts))) {
struct stat ent_st;
if (stat(ent->mnt_dir, &ent_st) < 0)
continue;
if (ent_st.st_dev == st.st_dev)
break;
}
endmntent(mounts);
if (!ent) {
log_info("Could not determine device for file in path %s", path);
return NULL;
}
return get_uuid_for_dev_path(ent->mnt_fsname);
}
static long determine_block_size_for_root_fs(void)
{
FILE *mtab = setmntent("/proc/mounts", "re");
struct mntent *mntent;
long sector_size = 0;
if (!mtab)
log_fatal("Could not determine mounted partitions. Is /proc mounted?");
while ((mntent = getmntent(mtab))) {
if (!strcmp(mntent->mnt_dir, "/")) {
int fd = open(mntent->mnt_fsname, O_RDONLY | O_CLOEXEC);
if (fd < 0) {
log_fatal("Could not open %s to determine block size: %s", mntent->mnt_fsname, strerror(errno));
}
if (ioctl(fd, BLKSSZGET, §or_size) < 0)
sector_size = 0;
close(fd);
break;
}
}
endmntent(mtab);
if (sector_size) {
struct statfs sfs;
if (statfs("/", &sfs) < 0)
log_fatal("Could not determine optimal block size for root filesystem: %s", strerror(errno));
return sfs.f_bsize > sector_size ? sfs.f_bsize : sector_size;
}
log_fatal("Could not obtain sector size for root partition: %s", strerror(errno));
}
static char *read_first_line_from_file(const char *path, char buffer[static 1024])
{
FILE *f = fopen(path, "re");
if (!f)
return NULL;
bool did_read = fgets(buffer, 1024, f) != NULL;
fclose(f);
if (!did_read)
return NULL;
char *lf = strchr(buffer, '\n');
if (lf)
*lf = '\0';
return buffer;
}
static bool is_hyperv(void) { return !access("/sys/bus/vmbus", F_OK); }
static bool is_running_in_container(void)
{
FILE *cgroup;
char buffer[1024];
bool ret = false;
cgroup = fopen("/proc/1/cgroup", "re");
if (!cgroup)
log_fatal("Could not read /proc/1/cgroup to determine if we're running in a container");
while (fgets(buffer, sizeof(buffer), cgroup)) {
const char *first_colon = strchr(buffer, ':');
if (!first_colon)
continue;
/* When running in a container, PID 1 will have a line in
* /proc/1/cgroup with "0::/" as a content; whereas, when running in
* the host, it might have something like "0::/init.slice".
*
* Things might be different with anything other than systemd, but
* since we're supporting systemd-only distros at this point, it's
* safer to use this method rather than rely on things like the
* presence of /.dockerenv or something like that as the container
* runtime not be docker. */
if (!strcmp(first_colon, "::/\n")) {
ret = true;
break;
}
}
fclose(cgroup);
return ret;
}
static bool is_hibernation_enabled_for_vm(void)
{
char buffer[1024];
char *entry;
if (is_running_in_container()) {
log_info("We're running in a container; this isn't supported.");
return false;
}
if (access("/dev/snapshot", F_OK) != 0) {
log_info("Kernel does not support hibernation or /dev/snapshot has not been found.");
return false;
}
/* First, check if the kernel can hibernate. Don't even bother if the
* interface to hibernate it isn't available. */
entry = read_first_line_from_file("/sys/power/disk", buffer);
if (!entry) {
log_info("Kernel does not support hibernation (/sys/power/disk does not exist or can't be read).");
return false;
}
if (strstr(entry, "platform")) {
log_info("VM supports hibernation with platform-supported events.");
return true;
}
if (strstr(entry, "shutdown")) {
log_info("VM supports hibernation only with the shutdown method. This is not ideal.");
} else if (strstr(entry, "suspend")) {
log_info("VM supports hibernation only with the suspend method. This is not ideal.");
} else {
log_info("Unknown VM hibernation support mode found: %s", entry);
return false;
}
if (is_hyperv()) {
log_info("This is a Hyper-V VM, checking if hibernation is enabled through VMBus events.");
entry = read_first_line_from_file("/sys/bus/vmbus/hibernation", buffer);
if (entry) {
if (!strcmp(entry, "1")) {
log_info("Hibernation is enabled according to VMBus. This is ideal.");
return true;
}
log_info("Hibernation is disabled according to VMBus.");
}
}
log_info("Even though VM is capable of hibernation, it seems to be disabled.");
return false;
}
static int open_and_get_socket(const char *host, int portno)
{
struct hostent *server;
struct sockaddr_in serv_addr;
int sockfd;
/* create the socket */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
log_info("Error opening socket: %s", strerror(errno));
return -1;
}
struct timeval timeout;
timeout.tv_sec = 10;
timeout.tv_usec = 0;
if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof timeout) < 0 ||
setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof timeout) < 0)
{
log_info("Unable to set timeouts for socket: %s", strerror(errno));
close(sockfd);
return -1;
}
/* lookup the ip address */
server = gethostbyname(host);
if (server == NULL)
{
log_info("Unable to fetch host info %s: %s", host, strerror(h_errno));
close(sockfd);
return -1;
}
/* fill in the structure */
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memcpy(&serv_addr.sin_addr.s_addr, server->h_addr, server->h_length);
/* connect the socket */
if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
log_info("Unable to connect to host %s: %s", host, strerror(errno));
close(sockfd);
return -1;
}
return sockfd;
}
static bool is_hibernation_allowed_for_vm(void)
{
int portno = 80;
char response[4096];
int sockfd, read_bytes;
const char *imds_host = "169.254.169.254";
const char *imds_req = "GET /metadata/instance/compute/additionalCapabilities/hibernationEnabled?api-version=2021-11-01&format=text HTTP/1.1\r\nHost: %s\r\nMetadata:true\r\n\r\n";
size_t req_size = strlen(imds_req) + strlen(imds_host) + 1;
char request[req_size];
snprintf(request, req_size, imds_req, imds_host);
sockfd = open_and_get_socket(imds_host, portno);
if(sockfd < 0)
return false;
log_info("IMDS Request:\n%s\n", request);
/*
Sample request -
GET /metadata/instance/compute/additionalCapabilities/hibernationEnabled?api-version=2021-11-01&format=text HTTP/1.1
Host: 169.254.169.254
Metadata:true
*/
if (write(sockfd, request, strlen(request)) < 0)
{
log_info("Failed to write to socket: %s", strerror(errno));
close(sockfd);
return false;
}
/*
Sample response -
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Server: IMDS/150.870.65.597
Date: Tue, 22 Mar 2022 00:34:37 GMT
Content-Length: 4
true (or false)
*/
read_bytes = read(sockfd, response, sizeof(response) - 1);
if (read_bytes < 0)
{
log_info("Failed to read from socket: %s", strerror(errno));
close(sockfd);
return false;
}
else if (read_bytes == 0)
{
log_info("IMDS connection closed prematurely without returning any response");
close(sockfd);
return false;
}
response[read_bytes] = '\0';
/* close the socket */
close(sockfd);
/* process response */
log_info("IMDS Response:\n%s\n", response);
if(strstr(response, "true"))
{
log_info("Hibernation is allowed for this VM");
return true;
}
return false;
}
static uint32_t get_swap_file_offset(int fd)
{
uint32_t blksize;
if (ioctl(fd, FIGETBSZ, &blksize) < 0)
log_fatal("Could not get file block size: %s", strerror(errno));
uint32_t last = 0, first = 0, num_contiguous_blocks = 0;
uint32_t blocks_per_page = sysconf(_SC_PAGE_SIZE) / blksize;
uint32_t first_blknum = ~0;
for (uint32_t i = 0; i < blocks_per_page; i++) {
uint32_t blknum = i;
if (ioctl(fd, FIBMAP, &blknum) < 0)
log_fatal("Could not get filesystem block number for block #%d: %s", i, strerror(errno));
if (i == 0)
first_blknum = blknum;
if (last && blknum - last != 1) {
/* If we find a block that's not contiguous, bail out. We
* check below if we have enough contiguous blocks for hibernation
* to work. */
break;
}
if (!first)
first = blknum;
last = blknum;
num_contiguous_blocks++;
}
log_info("First %d blocks of %d bytes are contiguous", num_contiguous_blocks, blksize);
if (num_contiguous_blocks * blksize >= sysconf(_SC_PAGE_SIZE))
return first_blknum;
return ~0;
}
static bool try_zero_out_with_write(const char *path, off_t needed_size)
{
int fd = open(path, O_WRONLY | O_CLOEXEC);
int ret = true;
if (fd < 0) {
log_info("Could not open %s: %s", path, strerror(errno));
return false;
}
long block_size = determine_block_size_for_root_fs();
const uint32_t pattern = 'T' << 24 | 'F' << 16 | 'S' << 8 | 'M';
for (off_t offset = 0; offset < needed_size; offset += block_size) {
ssize_t written = pwrite(fd, &pattern, sizeof(pattern), offset);
if (written < 0) {
log_info("Could not write pattern to %s: %s", path, strerror(errno));
ret = false;
goto out;
}
}
fdatasync(fd);
out:
close(fd);
return ret;
}
static bool fs_set_flags(int fd, int flags_to_set, int flags_to_reset)
{
int current_flags;
if (ioctl(fd, FS_IOC_GETFLAGS, ¤t_flags) < 0)
return false;
current_flags |= flags_to_set;
current_flags &= ~flags_to_reset;
if (ioctl(fd, FS_IOC_SETFLAGS, ¤t_flags) < 0)
return false;
return true;
}
static bool is_file_on_fs(const char *path, __fsword_t magic)
{
struct statfs stfs;
if (!statfs(path, &stfs))
return stfs.f_type == magic;
return false;
}
static bool create_swap_file_with_size(const char *path, off_t size)
{
int fd = open(path, O_CLOEXEC | O_WRONLY | O_CREAT, 0600);
int rc;
if (fd < 0)
return false;
/* Disabling CoW is necessary on btrfs filesystems, but issue the
* ioctl regardless of the filesystem just in case.
* More information: https://wiki.archlinux.org/index.php/btrfs#Swap_file
*/
if (!fs_set_flags(fd, FS_NOCOW_FL, 0)) {
/* Some filesystems don't support CoW (EXT4 for instance), so don't bother
* giving an error message in those cases. */
if (errno != EOPNOTSUPP)
log_info("Could not disable CoW for %s: %s. Will try setting up swap anyway.", path, strerror(errno));
}
/* Disable compression, too. */
if (!fs_set_flags(fd, FS_NOCOMP_FL, FS_COMPR_FL)) {
/* Compression is optional, too, so don't bother giving an error message in
* case the filesystem doesn't support it. */
if (errno != EOPNOTSUPP)
log_info("Could not disable compression for %s: %s. Will try setting up swap anyway.", path, strerror(errno));
}
if (is_file_on_fs(path, XFS_SUPER_MAGIC)) {
rc = 0;
} else {
rc = ftruncate(fd, size);
if (rc < 0) {
if (errno == EPERM) {
log_info("Not enough disk space to create %s with %zu MB.", path, size / MEGA_BYTES);
} else {
log_info("Could not resize %s to %ld MB: %s", path, size / MEGA_BYTES, strerror(errno));
}
}
}
close(fd);
return rc == 0;
}
static bool try_zeroing_out_with_fallocate(const char *path, off_t size)
{
int fd = open(path, O_CLOEXEC | O_WRONLY);
if (fd < 0) {
log_info("Could not open %s for writing: %s", path, strerror(errno));
return false;
}
if (fallocate(fd, 0, 0, size) < 0) {
int fallocate_errno = errno;
if (unlink(path) < 0)
log_info("Couldn't remove incomplete hibernation file %s: %s", path, strerror(errno));
if (fallocate_errno == ENOSPC) {
log_fatal("System ran out of disk space while allocating hibernation file. It needs %zd MiB", size / MEGA_BYTES);
} else {
log_fatal("Could not allocate %s: %s", path, strerror(fallocate_errno));
}
}
close(fd);
return true;
}
static bool try_vspawn_and_wait(const char *program, int n_args, va_list ap)
{
pid_t pid;
int rc;
char **argv;
argv = calloc(n_args + 2, sizeof(char *));
if (!argv) {
log_info("Couldn't allocate memory for argument array");
return false;
}
argv[0] = (char *)program;
for (int i = 1; i <= n_args; i++)
argv[i] = va_arg(ap, char *);
rc = posix_spawnp(&pid, program, NULL, NULL, argv, NULL);
free(argv);
if (rc != 0) {
log_info("Could not spawn %s: %s", program, strerror(rc));
return false;
}
log_info("Waiting for %s (pid %d) to finish.", program, pid);
int wstatus;
if (waitpid(pid, &wstatus, 0) != pid) {
log_info("Couldn't wait for %s: %s", program, strerror(errno));
return false;
}
if (!WIFEXITED(wstatus)) {
log_info("%s ended abnormally: %s", program, strerror(errno));
return false;
}
if (WEXITSTATUS(wstatus) == 127) {
log_info("Failed to spawn %s", program);
return false;
}
if (WEXITSTATUS(wstatus) != 0) {
log_info("%s ended with unexpected exit code %d", program, WEXITSTATUS(wstatus));
return false;
}
log_info("%s finished successfully.", program);
return true;
}
static bool try_spawn_and_wait(const char *program, int n_args, ...)
{
va_list ap;
bool spawned;
va_start(ap, n_args);
spawned = try_vspawn_and_wait(program, n_args, ap);
va_end(ap);
return spawned;
}
static void spawn_and_wait(const char *program, int n_args, ...)
{
va_list ap;
bool spawned;
va_start(ap, n_args);
spawned = try_vspawn_and_wait(program, n_args, ap);
va_end(ap);
if (!spawned)
log_fatal("Aborting program due to error condition when spawning %s", program);
}
static void perform_fs_specific_checks(const char *path)
{
/* Not performing defragmentation for xfs file systems as xfs_fsr process is taking time for SKUs with larger RAM.
While it is good to have optimization, not ideal to have performance hit on the tool */
if (is_file_on_fs(path, EXT4_SUPER_MAGIC) && is_exec_in_path("e4defrag")) {
try_spawn_and_wait("e4defrag", 1, path);
return;
}
if (is_file_on_fs(path, BTRFS_SUPER_MAGIC)) {
struct utsname utsbuf;
if (uname(&utsbuf) < 0)
log_fatal("Could not determine Linux kernel version: %s", strerror(errno));
if (utsbuf.release[1] != '.')
log_fatal("Could not parse Linux kernel version");
if (utsbuf.release[0] < '5')
log_fatal("Swap files are not supported on Btrfs running on kernel %s", utsbuf.release);
if (is_exec_in_path("btrfs"))
try_spawn_and_wait("btrfs", 3, "filesystem", "defragment", path);
return;
}
}
bool is_kernel_version_at_least(const char *version)
{
struct utsname my_uname;
if (uname(&my_uname) == -1) {
log_info("uname call failed.");
return true;
}
unsigned sys_major_version = 0, sys_minor_version = 0;
unsigned req_major_version = 0, req_minor_version = 0;
sscanf(my_uname.release, "%u.%u", &sys_major_version, &sys_minor_version);
sscanf(version, "%u.%u", &req_major_version, &req_minor_version);
uint64_t sys_version = sys_major_version * 10000 + sys_minor_version;
uint64_t req_version = req_major_version * 10000 + req_minor_version;
return sys_version >= req_version;