mkswap.c - ubase - suckless linux base utils
(HTM) git clone git://git.suckless.org/ubase
(DIR) Log
(DIR) Files
(DIR) Refs
(DIR) README
(DIR) LICENSE
---
mkswap.c (1739B)
---
1 /* See LICENSE file for copyright and license details. */
2 #include <sys/stat.h>
3
4 #include <fcntl.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <unistd.h>
9
10 #include "util.h"
11
12 #define SWAP_UUID_LENGTH 16
13 #define SWAP_LABEL_LENGTH 16
14 #define SWAP_MIN_PAGES 10
15
16 struct swap_hdr {
17 char bootbits[1024];
18 unsigned int version;
19 unsigned int last_page;
20 unsigned int nr_badpages;
21 unsigned char uuid[SWAP_UUID_LENGTH];
22 char volume_name[SWAP_LABEL_LENGTH];
23 unsigned int padding[117];
24 unsigned int badpages[1];
25 };
26
27 static void
28 usage(void)
29 {
30 eprintf("usage: %s device\n", argv0);
31 }
32
33 int
34 main(int argc, char *argv[])
35 {
36 int fd;
37 unsigned int pages;
38 long pagesize;
39 struct stat sb;
40 char *buf;
41 struct swap_hdr *hdr;
42
43 ARGBEGIN {
44 default:
45 usage();
46 } ARGEND;
47
48 if (argc < 1)
49 usage();
50
51 pagesize = sysconf(_SC_PAGESIZE);
52 if (pagesize <= 0) {
53 pagesize = sysconf(_SC_PAGE_SIZE);
54 if (pagesize <= 0)
55 eprintf("can't determine pagesize\n");
56 }
57
58 fd = open(argv[0], O_RDWR);
59 if (fd < 0)
60 eprintf("open %s:", argv[0]);
61 if (fstat(fd, &sb) < 0)
62 eprintf("stat %s:", argv[0]);
63
64 buf = ecalloc(1, pagesize);
65
66 pages = sb.st_size / pagesize;
67 if (pages < SWAP_MIN_PAGES)
68 eprintf("swap space needs to be at least %ldKiB\n",
69 SWAP_MIN_PAGES * pagesize / 1024);
70
71 /* Fill up the swap header */
72 hdr = (struct swap_hdr *)buf;
73 hdr->version = 1;
74 hdr->last_page = pages - 1;
75 strncpy(buf + pagesize - 10, "SWAPSPACE2", 10);
76
77 printf("Setting up swapspace version 1, size = %luKiB\n",
78 (pages - 1) * pagesize / 1024);
79
80 /* Write out the signature page */
81 if (write(fd, buf, pagesize) != pagesize)
82 eprintf("unable to write signature page\n");
83
84 fsync(fd);
85 close(fd);
86 free(buf);
87
88 return 0;
89 }