]> git.ipfire.org Git - thirdparty/util-linux.git/blob - sys-utils/swapon.c
libmount: don't use sscanf() for swaps parsing
[thirdparty/util-linux.git] / sys-utils / swapon.c
1 #include <assert.h>
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include <getopt.h>
5 #include <string.h>
6 #include <errno.h>
7 #include <sys/stat.h>
8 #include <unistd.h>
9 #include <sys/types.h>
10 #include <sys/wait.h>
11 #include <fcntl.h>
12 #include <stdint.h>
13 #include <ctype.h>
14
15 #include <libsmartcols.h>
16
17 #include "c.h"
18 #include "nls.h"
19 #include "bitops.h"
20 #include "blkdev.h"
21 #include "pathnames.h"
22 #include "xalloc.h"
23 #include "strutils.h"
24 #include "optutils.h"
25 #include "closestream.h"
26
27 #include "swapheader.h"
28 #include "swapprober.h"
29 #include "swapon-common.h"
30
31 #ifdef HAVE_SYS_SWAP_H
32 # include <sys/swap.h>
33 #endif
34
35 #ifndef SWAP_FLAG_DISCARD
36 # define SWAP_FLAG_DISCARD 0x10000 /* enable discard for swap */
37 #endif
38
39 #ifndef SWAP_FLAG_DISCARD_ONCE
40 # define SWAP_FLAG_DISCARD_ONCE 0x20000 /* discard swap area at swapon-time */
41 #endif
42
43 #ifndef SWAP_FLAG_DISCARD_PAGES
44 # define SWAP_FLAG_DISCARD_PAGES 0x40000 /* discard page-clusters after use */
45 #endif
46
47 #define SWAP_FLAGS_DISCARD_VALID (SWAP_FLAG_DISCARD | SWAP_FLAG_DISCARD_ONCE | \
48 SWAP_FLAG_DISCARD_PAGES)
49
50 #ifndef SWAP_FLAG_PREFER
51 # define SWAP_FLAG_PREFER 0x8000 /* set if swap priority specified */
52 #endif
53
54 #ifndef SWAP_FLAG_PRIO_MASK
55 # define SWAP_FLAG_PRIO_MASK 0x7fff
56 #endif
57
58 #ifndef SWAP_FLAG_PRIO_SHIFT
59 # define SWAP_FLAG_PRIO_SHIFT 0
60 #endif
61
62 #if !defined(HAVE_SWAPON) && defined(SYS_swapon)
63 # include <sys/syscall.h>
64 # define swapon(path, flags) syscall(SYS_swapon, path, flags)
65 #endif
66
67 #define MAX_PAGESIZE (64 * 1024)
68
69 #ifndef UUID_STR_LEN
70 # define UUID_STR_LEN 37
71 #endif
72
73 enum {
74 SIG_SWAPSPACE = 1,
75 SIG_SWSUSPEND
76 };
77
78 /* column names */
79 struct colinfo {
80 const char *name; /* header */
81 double whint; /* width hint (N < 1 is in percent of termwidth) */
82 int flags; /* SCOLS_FL_* */
83 const char *help;
84 };
85
86 enum {
87 COL_PATH,
88 COL_TYPE,
89 COL_SIZE,
90 COL_USED,
91 COL_PRIO,
92 COL_UUID,
93 COL_LABEL
94 };
95 static struct colinfo infos[] = {
96 [COL_PATH] = { "NAME", 0.20, 0, N_("device file or partition path") },
97 [COL_TYPE] = { "TYPE", 0.20, SCOLS_FL_TRUNC, N_("type of the device")},
98 [COL_SIZE] = { "SIZE", 0.20, SCOLS_FL_RIGHT, N_("size of the swap area")},
99 [COL_USED] = { "USED", 0.20, SCOLS_FL_RIGHT, N_("bytes in use")},
100 [COL_PRIO] = { "PRIO", 0.20, SCOLS_FL_RIGHT, N_("swap priority")},
101 [COL_UUID] = { "UUID", 0.20, 0, N_("swap uuid")},
102 [COL_LABEL] = { "LABEL", 0.20, 0, N_("swap label")},
103 };
104
105
106 /* swap area properties */
107 struct swap_prop {
108 int discard; /* discard policy */
109 int priority; /* non-prioritized swap by default */
110 int no_fail; /* skip device if not exist */
111 };
112
113 /* device description */
114 struct swap_device {
115 const char *path; /* device or file to be turned on */
116 const char *label; /* swap label */
117 const char *uuid; /* unique identifier */
118 unsigned int pagesize;
119 };
120
121 /* control struct */
122 struct swapon_ctl {
123 int columns[ARRAY_SIZE(infos) * 2]; /* --show columns */
124 int ncolumns; /* number of columns */
125
126 struct swap_prop props; /* global settings for all devices */
127
128 unsigned int
129 all:1, /* turn on all swap devices */
130 bytes:1, /* display --show in bytes */
131 fix_page_size:1, /* reinitialize page size */
132 no_heading:1, /* toggle --show headers */
133 raw:1, /* toggle --show alignment */
134 show:1, /* display --show information */
135 verbose:1; /* be chatty */
136 };
137
138 static int column_name_to_id(const char *name, size_t namesz)
139 {
140 size_t i;
141
142 assert(name);
143
144 for (i = 0; i < ARRAY_SIZE(infos); i++) {
145 const char *cn = infos[i].name;
146
147 if (!strncasecmp(name, cn, namesz) && !*(cn + namesz))
148 return i;
149 }
150 warnx(_("unknown column: %s"), name);
151 return -1;
152 }
153
154 static inline int get_column_id(const struct swapon_ctl *ctl, int num)
155 {
156 assert(num < ctl->ncolumns);
157 assert(ctl->columns[num] < (int) ARRAY_SIZE(infos));
158
159 return ctl->columns[num];
160 }
161
162 static inline struct colinfo *get_column_info(const struct swapon_ctl *ctl, unsigned num)
163 {
164 return &infos[get_column_id(ctl, num)];
165 }
166
167 static void add_scols_line(const struct swapon_ctl *ctl, struct libscols_table *table, struct libmnt_fs *fs)
168 {
169 int i;
170 struct libscols_line *line;
171 blkid_probe pr = NULL;
172 const char *data;
173
174 assert(table);
175 assert(fs);
176
177 line = scols_table_new_line(table, NULL);
178 if (!line)
179 err(EXIT_FAILURE, _("failed to allocate output line"));
180
181 data = mnt_fs_get_source(fs);
182 if (access(data, R_OK) == 0)
183 pr = get_swap_prober(data);
184 for (i = 0; i < ctl->ncolumns; i++) {
185 char *str = NULL;
186 off_t size;
187
188 switch (get_column_id(ctl, i)) {
189 case COL_PATH:
190 xasprintf(&str, "%s", mnt_fs_get_source(fs));
191 break;
192 case COL_TYPE:
193 xasprintf(&str, "%s", mnt_fs_get_swaptype(fs));
194 break;
195 case COL_SIZE:
196 size = mnt_fs_get_size(fs);
197 size *= 1024; /* convert to bytes */
198 if (ctl->bytes)
199 xasprintf(&str, "%jd", size);
200 else
201 str = size_to_human_string(SIZE_SUFFIX_1LETTER, size);
202 break;
203 case COL_USED:
204 size = mnt_fs_get_usedsize(fs);
205 size *= 1024; /* convert to bytes */
206 if (ctl->bytes)
207 xasprintf(&str, "%jd", size);
208 else
209 str = size_to_human_string(SIZE_SUFFIX_1LETTER, size);
210 break;
211 case COL_PRIO:
212 xasprintf(&str, "%d", mnt_fs_get_priority(fs));
213 break;
214 case COL_UUID:
215 if (pr && !blkid_probe_lookup_value(pr, "UUID", &data, NULL))
216 xasprintf(&str, "%s", data);
217 break;
218 case COL_LABEL:
219 if (pr && !blkid_probe_lookup_value(pr, "LABEL", &data, NULL))
220 xasprintf(&str, "%s", data);
221 break;
222 default:
223 break;
224 }
225
226 if (str && scols_line_refer_data(line, i, str))
227 err(EXIT_FAILURE, _("failed to add output data"));
228 }
229 if (pr)
230 blkid_free_probe(pr);
231 return;
232 }
233
234 static int display_summary(void)
235 {
236 struct libmnt_table *st = get_swaps();
237 struct libmnt_iter *itr;
238 struct libmnt_fs *fs;
239
240 if (!st)
241 return -1;
242
243 if (mnt_table_is_empty(st))
244 return 0;
245
246 itr = mnt_new_iter(MNT_ITER_FORWARD);
247 if (!itr)
248 err(EXIT_FAILURE, _("failed to initialize libmount iterator"));
249
250 printf(_("%s\t\t\t\tType\t\tSize\tUsed\tPriority\n"), _("Filename"));
251
252 while (mnt_table_next_fs(st, itr, &fs) == 0) {
253 printf("%-39s\t%-8s\t%jd\t%jd\t%d\n",
254 mnt_fs_get_source(fs),
255 mnt_fs_get_swaptype(fs),
256 mnt_fs_get_size(fs),
257 mnt_fs_get_usedsize(fs),
258 mnt_fs_get_priority(fs));
259 }
260
261 mnt_free_iter(itr);
262 return 0;
263 }
264
265 static int show_table(struct swapon_ctl *ctl)
266 {
267 struct libmnt_table *st = get_swaps();
268 struct libmnt_iter *itr = NULL;
269 struct libmnt_fs *fs;
270 int i;
271 struct libscols_table *table = NULL;
272
273 if (!st)
274 return -1;
275
276 itr = mnt_new_iter(MNT_ITER_FORWARD);
277 if (!itr)
278 err(EXIT_FAILURE, _("failed to initialize libmount iterator"));
279
280 scols_init_debug(0);
281
282 table = scols_new_table();
283 if (!table)
284 err(EXIT_FAILURE, _("failed to allocate output table"));
285
286 scols_table_enable_raw(table, ctl->raw);
287 scols_table_enable_noheadings(table, ctl->no_heading);
288
289 for (i = 0; i < ctl->ncolumns; i++) {
290 struct colinfo *col = get_column_info(ctl, i);
291
292 if (!scols_table_new_column(table, col->name, col->whint, col->flags))
293 err(EXIT_FAILURE, _("failed to allocate output column"));
294 }
295
296 while (mnt_table_next_fs(st, itr, &fs) == 0)
297 add_scols_line(ctl, table, fs);
298
299 scols_print_table(table);
300 scols_unref_table(table);
301 mnt_free_iter(itr);
302 return 0;
303 }
304
305 /* calls mkswap */
306 static int swap_reinitialize(struct swap_device *dev)
307 {
308 pid_t pid;
309 int status, ret;
310 char const *cmd[7];
311 int idx=0;
312
313 assert(dev);
314 assert(dev->path);
315
316 warnx(_("%s: reinitializing the swap."), dev->path);
317
318 switch ((pid=fork())) {
319 case -1: /* fork error */
320 warn(_("fork failed"));
321 return -1;
322
323 case 0: /* child */
324 if (geteuid() != getuid()) {
325 /* in case someone uses swapon as setuid binary */
326 if (setgid(getgid()) < 0)
327 exit(EXIT_FAILURE);
328 if (setuid(getuid()) < 0)
329 exit(EXIT_FAILURE);
330 }
331
332 cmd[idx++] = "mkswap";
333 if (dev->label) {
334 cmd[idx++] = "-L";
335 cmd[idx++] = dev->label;
336 }
337 if (dev->uuid) {
338 cmd[idx++] = "-U";
339 cmd[idx++] = dev->uuid;
340 }
341 cmd[idx++] = dev->path;
342 cmd[idx++] = NULL;
343 execvp(cmd[0], (char * const *) cmd);
344 errexec(cmd[0]);
345
346 default: /* parent */
347 do {
348 ret = waitpid(pid, &status, 0);
349 } while (ret == -1 && errno == EINTR);
350
351 if (ret < 0) {
352 warn(_("waitpid failed"));
353 return -1;
354 }
355
356 /* mkswap returns: 0=suss, >0 error */
357 if (WIFEXITED(status) && WEXITSTATUS(status)==0)
358 return 0; /* ok */
359 break;
360 }
361 return -1; /* error */
362 }
363
364 /* Replaces unwanted SWSUSPEND signature with swap signature */
365 static int swap_rewrite_signature(const struct swap_device *dev)
366 {
367 int fd, rc = -1;
368
369 assert(dev);
370 assert(dev->path);
371 assert(dev->pagesize);
372
373 fd = open(dev->path, O_WRONLY);
374 if (fd == -1) {
375 warn(_("cannot open %s"), dev->path);
376 return -1;
377 }
378
379 if (lseek(fd, dev->pagesize - SWAP_SIGNATURE_SZ, SEEK_SET) < 0) {
380 warn(_("%s: lseek failed"), dev->path);
381 goto err;
382 }
383
384 if (write(fd, (void *) SWAP_SIGNATURE,
385 SWAP_SIGNATURE_SZ) != SWAP_SIGNATURE_SZ) {
386 warn(_("%s: write signature failed"), dev->path);
387 goto err;
388 }
389
390 rc = 0;
391 err:
392 if (close_fd(fd) != 0) {
393 warn(_("write failed: %s"), dev->path);
394 rc = -1;
395 }
396 return rc;
397 }
398
399 static int swap_detect_signature(const char *buf, int *sig)
400 {
401 assert(buf);
402 assert(sig);
403
404 if (memcmp(buf, SWAP_SIGNATURE, SWAP_SIGNATURE_SZ) == 0)
405 *sig = SIG_SWAPSPACE;
406
407 else if (memcmp(buf, "S1SUSPEND", 9) == 0 ||
408 memcmp(buf, "S2SUSPEND", 9) == 0 ||
409 memcmp(buf, "ULSUSPEND", 9) == 0 ||
410 memcmp(buf, "\xed\xc3\x02\xe9\x98\x56\xe5\x0c", 8) == 0 ||
411 memcmp(buf, "LINHIB0001", 10) == 0)
412 *sig = SIG_SWSUSPEND;
413 else
414 return 0;
415
416 return 1;
417 }
418
419 static char *swap_get_header(int fd, int *sig, unsigned int *pagesize)
420 {
421 char *buf;
422 ssize_t datasz;
423 unsigned int page;
424
425 assert(sig);
426 assert(pagesize);
427
428 *pagesize = 0;
429 *sig = 0;
430
431 buf = xmalloc(MAX_PAGESIZE);
432
433 datasz = read(fd, buf, MAX_PAGESIZE);
434 if (datasz == (ssize_t) -1)
435 goto err;
436
437 for (page = 0x1000; page <= MAX_PAGESIZE; page <<= 1) {
438 /* skip 32k pagesize since this does not seem to
439 * be supported */
440 if (page == 0x8000)
441 continue;
442 /* the smallest swap area is PAGE_SIZE*10, it means
443 * 40k, that's less than MAX_PAGESIZE */
444 if (datasz < 0 || (size_t) datasz < (page - SWAP_SIGNATURE_SZ))
445 break;
446 if (swap_detect_signature(buf + page - SWAP_SIGNATURE_SZ, sig)) {
447 *pagesize = page;
448 break;
449 }
450 }
451
452 if (*pagesize)
453 return buf;
454 err:
455 free(buf);
456 return NULL;
457 }
458
459 /* returns real size of swap space */
460 static unsigned long long swap_get_size(const struct swap_device *dev,
461 const char *hdr)
462 {
463 unsigned int last_page = 0;
464 const unsigned int swap_version = SWAP_VERSION;
465 const struct swap_header_v1_2 *s;
466
467 assert(dev);
468 assert(dev->pagesize > 0);
469
470 s = (const struct swap_header_v1_2 *) hdr;
471
472 if (s->version == swap_version)
473 last_page = s->last_page;
474 else if (swab32(s->version) == swap_version)
475 last_page = swab32(s->last_page);
476
477 return ((unsigned long long) last_page + 1) * dev->pagesize;
478 }
479
480 static void swap_get_info(struct swap_device *dev, const char *hdr)
481 {
482 const struct swap_header_v1_2 *s = (const struct swap_header_v1_2 *) hdr;
483
484 assert(dev);
485
486 if (s && *s->volume_name)
487 dev->label = xstrdup(s->volume_name);
488
489 if (s && *s->uuid) {
490 const unsigned char *u = s->uuid;
491 char str[UUID_STR_LEN];
492
493 snprintf(str, sizeof(str),
494 "%02x%02x%02x%02x-"
495 "%02x%02x-%02x%02x-"
496 "%02x%02x-%02x%02x%02x%02x%02x%02x",
497 u[0], u[1], u[2], u[3],
498 u[4], u[5], u[6], u[7],
499 u[8], u[9], u[10], u[11], u[12], u[13], u[14], u[15]);
500 dev->uuid = xstrdup(str);
501 }
502 }
503
504 static int swapon_checks(const struct swapon_ctl *ctl, struct swap_device *dev)
505 {
506 struct stat st;
507 int fd, sig;
508 char *hdr = NULL;
509 unsigned long long devsize = 0;
510 int permMask;
511
512 assert(ctl);
513 assert(dev);
514 assert(dev->path);
515
516 fd = open(dev->path, O_RDONLY);
517 if (fd == -1) {
518 warn(_("cannot open %s"), dev->path);
519 goto err;
520 }
521
522 if (fstat(fd, &st) < 0) {
523 warn(_("stat of %s failed"), dev->path);
524 goto err;
525 }
526
527 permMask = S_ISBLK(st.st_mode) ? 07007 : 07077;
528 if ((st.st_mode & permMask) != 0)
529 warnx(_("%s: insecure permissions %04o, %04o suggested."),
530 dev->path, st.st_mode & 07777,
531 ~permMask & 0666);
532
533 if (S_ISREG(st.st_mode) && st.st_uid != 0)
534 warnx(_("%s: insecure file owner %d, 0 (root) suggested."),
535 dev->path, st.st_uid);
536
537 /* test for holes by LBT */
538 if (S_ISREG(st.st_mode)) {
539 if (st.st_blocks * 512 < st.st_size) {
540 warnx(_("%s: skipping - it appears to have holes."),
541 dev->path);
542 goto err;
543 }
544 devsize = st.st_size;
545 }
546
547 if (S_ISBLK(st.st_mode) && blkdev_get_size(fd, &devsize)) {
548 warnx(_("%s: get size failed"), dev->path);
549 goto err;
550 }
551
552 hdr = swap_get_header(fd, &sig, &dev->pagesize);
553 if (!hdr) {
554 warnx(_("%s: read swap header failed"), dev->path);
555 goto err;
556 }
557
558 if (ctl->verbose)
559 warnx(_("%s: found signature [pagesize=%d, signature=%s]"),
560 dev->path,
561 dev->pagesize,
562 sig == SIG_SWAPSPACE ? "swap" :
563 sig == SIG_SWSUSPEND ? "suspend" : "unknown");
564
565 if (sig == SIG_SWAPSPACE && dev->pagesize) {
566 unsigned long long swapsize = swap_get_size(dev, hdr);
567 int syspg = getpagesize();
568
569 if (ctl->verbose)
570 warnx(_("%s: pagesize=%d, swapsize=%llu, devsize=%llu"),
571 dev->path, dev->pagesize, swapsize, devsize);
572
573 if (swapsize > devsize) {
574 if (ctl->verbose)
575 warnx(_("%s: last_page 0x%08llx is larger"
576 " than actual size of swapspace"),
577 dev->path, swapsize);
578
579 } else if (syspg < 0 || (unsigned int) syspg != dev->pagesize) {
580 if (ctl->fix_page_size) {
581 int rc;
582
583 swap_get_info(dev, hdr);
584
585 warnx(_("%s: swap format pagesize does not match."),
586 dev->path);
587 rc = swap_reinitialize(dev);
588 if (rc < 0)
589 goto err;
590 } else
591 warnx(_("%s: swap format pagesize does not match. "
592 "(Use --fixpgsz to reinitialize it.)"),
593 dev->path);
594 }
595 } else if (sig == SIG_SWSUSPEND) {
596 /* We have to reinitialize swap with old (=useless) software suspend
597 * data. The problem is that if we don't do it, then we get data
598 * corruption the next time an attempt at unsuspending is made.
599 */
600 warnx(_("%s: software suspend data detected. "
601 "Rewriting the swap signature."),
602 dev->path);
603 if (swap_rewrite_signature(dev) < 0)
604 goto err;
605 }
606
607 free(hdr);
608 close(fd);
609 return 0;
610 err:
611 if (fd != -1)
612 close(fd);
613 free(hdr);
614 return -1;
615 }
616
617 static int do_swapon(const struct swapon_ctl *ctl,
618 const struct swap_prop *prop,
619 const char *spec,
620 int canonic)
621 {
622 struct swap_device dev = { .path = NULL };
623 int status;
624 int flags = 0;
625 int priority;
626
627 assert(ctl);
628 assert(prop);
629
630 if (!canonic) {
631 dev.path = mnt_resolve_spec(spec, mntcache);
632 if (!dev.path)
633 return cannot_find(spec);
634 } else
635 dev.path = spec;
636
637 priority = prop->priority;
638
639 if (swapon_checks(ctl, &dev))
640 return -1;
641
642 #ifdef SWAP_FLAG_PREFER
643 if (priority >= 0) {
644 if (priority > SWAP_FLAG_PRIO_MASK)
645 priority = SWAP_FLAG_PRIO_MASK;
646
647 flags = SWAP_FLAG_PREFER
648 | ((priority & SWAP_FLAG_PRIO_MASK)
649 << SWAP_FLAG_PRIO_SHIFT);
650 }
651 #endif
652 /*
653 * Validate the discard flags passed and set them
654 * accordingly before calling sys_swapon.
655 */
656 if (prop->discard && !(prop->discard & ~SWAP_FLAGS_DISCARD_VALID)) {
657 /*
658 * If we get here with both discard policy flags set,
659 * we just need to tell the kernel to enable discards
660 * and it will do correctly, just as we expect.
661 */
662 if ((prop->discard & SWAP_FLAG_DISCARD_ONCE) &&
663 (prop->discard & SWAP_FLAG_DISCARD_PAGES))
664 flags |= SWAP_FLAG_DISCARD;
665 else
666 flags |= prop->discard;
667 }
668
669 if (ctl->verbose)
670 printf(_("swapon %s\n"), dev.path);
671
672 status = swapon(dev.path, flags);
673 if (status < 0)
674 warn(_("%s: swapon failed"), dev.path);
675
676 return status;
677 }
678
679 static int swapon_by_label(struct swapon_ctl *ctl, const char *label)
680 {
681 char *device = mnt_resolve_tag("LABEL", label, mntcache);
682 return device ? do_swapon(ctl, &ctl->props, device, TRUE) : cannot_find(label);
683 }
684
685 static int swapon_by_uuid(struct swapon_ctl *ctl, const char *uuid)
686 {
687 char *device = mnt_resolve_tag("UUID", uuid, mntcache);
688 return device ? do_swapon(ctl, &ctl->props, device, TRUE) : cannot_find(uuid);
689 }
690
691 /* -o <options> or fstab */
692 static int parse_options(struct swap_prop *props, const char *options)
693 {
694 char *arg = NULL;
695 size_t argsz = 0;
696
697 assert(props);
698 assert(options);
699
700 if (mnt_optstr_get_option(options, "nofail", NULL, NULL) == 0)
701 props->no_fail = 1;
702
703 if (mnt_optstr_get_option(options, "discard", &arg, &argsz) == 0) {
704 props->discard |= SWAP_FLAG_DISCARD;
705
706 if (arg) {
707 /* only single-time discards are wanted */
708 if (strncmp(arg, "once", argsz) == 0)
709 props->discard |= SWAP_FLAG_DISCARD_ONCE;
710
711 /* do discard for every released swap page */
712 if (strncmp(arg, "pages", argsz) == 0)
713 props->discard |= SWAP_FLAG_DISCARD_PAGES;
714 }
715 }
716
717 arg = NULL;
718 if (mnt_optstr_get_option(options, "pri", &arg, NULL) == 0 && arg)
719 props->priority = atoi(arg);
720
721 return 0;
722 }
723
724
725 static int swapon_all(struct swapon_ctl *ctl)
726 {
727 struct libmnt_table *tb = get_fstab();
728 struct libmnt_iter *itr;
729 struct libmnt_fs *fs;
730 int status = 0;
731
732 if (!tb)
733 err(EXIT_FAILURE, _("failed to parse %s"), mnt_get_fstab_path());
734
735 itr = mnt_new_iter(MNT_ITER_FORWARD);
736 if (!itr)
737 err(EXIT_FAILURE, _("failed to initialize libmount iterator"));
738
739 while (mnt_table_find_next_fs(tb, itr, match_swap, NULL, &fs) == 0) {
740 /* defaults */
741 const char *opts;
742 const char *device;
743 struct swap_prop prop; /* per device setting */
744
745 if (mnt_fs_get_option(fs, "noauto", NULL, NULL) == 0) {
746 if (ctl->verbose)
747 warnx(_("%s: noauto option -- ignored"), mnt_fs_get_source(fs));
748 continue;
749 }
750
751 /* default setting */
752 prop = ctl->props;
753
754 /* overwrite default by setting from fstab */
755 opts = mnt_fs_get_options(fs);
756 if (opts)
757 parse_options(&prop, opts);
758
759 /* convert LABEL=, UUID= etc. from fstab to device name */
760 device = mnt_resolve_spec(mnt_fs_get_source(fs), mntcache);
761 if (!device) {
762 if (!prop.no_fail)
763 status |= cannot_find(mnt_fs_get_source(fs));
764 continue;
765 }
766
767 if (is_active_swap(device)) {
768 if (ctl->verbose)
769 warnx(_("%s: already active -- ignored"), device);
770 continue;
771 }
772
773 if (prop.no_fail && access(device, R_OK) != 0) {
774 if (ctl->verbose)
775 warnx(_("%s: inaccessible -- ignored"), device);
776 continue;
777 }
778
779 /* swapon */
780 status |= do_swapon(ctl, &prop, device, TRUE);
781 }
782
783 mnt_free_iter(itr);
784 return status;
785 }
786
787
788 static void __attribute__((__noreturn__)) usage(void)
789 {
790 FILE *out = stdout;
791 size_t i;
792
793 fputs(USAGE_HEADER, out);
794 fprintf(out, _(" %s [options] [<spec>]\n"), program_invocation_short_name);
795
796 fputs(USAGE_SEPARATOR, out);
797 fputs(_("Enable devices and files for paging and swapping.\n"), out);
798
799 fputs(USAGE_OPTIONS, out);
800 fputs(_(" -a, --all enable all swaps from /etc/fstab\n"), out);
801 fputs(_(" -d, --discard[=<policy>] enable swap discards, if supported by device\n"), out);
802 fputs(_(" -e, --ifexists silently skip devices that do not exist\n"), out);
803 fputs(_(" -f, --fixpgsz reinitialize the swap space if necessary\n"), out);
804 fputs(_(" -o, --options <list> comma-separated list of swap options\n"), out);
805 fputs(_(" -p, --priority <prio> specify the priority of the swap device\n"), out);
806 fputs(_(" -s, --summary display summary about used swap devices (DEPRECATED)\n"), out);
807 fputs(_(" --show[=<columns>] display summary in definable table\n"), out);
808 fputs(_(" --noheadings don't print table heading (with --show)\n"), out);
809 fputs(_(" --raw use the raw output format (with --show)\n"), out);
810 fputs(_(" --bytes display swap size in bytes in --show output\n"), out);
811 fputs(_(" -v, --verbose verbose mode\n"), out);
812
813 fputs(USAGE_SEPARATOR, out);
814 printf(USAGE_HELP_OPTIONS(26));
815
816 fputs(_("\nThe <spec> parameter:\n" \
817 " -L <label> synonym for LABEL=<label>\n"
818 " -U <uuid> synonym for UUID=<uuid>\n"
819 " LABEL=<label> specifies device by swap area label\n"
820 " UUID=<uuid> specifies device by swap area UUID\n"
821 " PARTLABEL=<label> specifies device by partition label\n"
822 " PARTUUID=<uuid> specifies device by partition UUID\n"
823 " <device> name of device to be used\n"
824 " <file> name of file to be used\n"), out);
825
826 fputs(_("\nAvailable discard policy types (for --discard):\n"
827 " once : only single-time area discards are issued\n"
828 " pages : freed pages are discarded before they are reused\n"
829 "If no policy is selected, both discard types are enabled (default).\n"), out);
830
831 fputs(USAGE_COLUMNS, out);
832 for (i = 0; i < ARRAY_SIZE(infos); i++)
833 fprintf(out, " %-5s %s\n", infos[i].name, _(infos[i].help));
834
835 printf(USAGE_MAN_TAIL("swapon(8)"));
836 exit(EXIT_SUCCESS);
837 }
838
839 int main(int argc, char *argv[])
840 {
841 int status = 0, c;
842 size_t i;
843 char *options = NULL;
844
845 enum {
846 BYTES_OPTION = CHAR_MAX + 1,
847 NOHEADINGS_OPTION,
848 RAW_OPTION,
849 SHOW_OPTION,
850 OPT_LIST_TYPES
851 };
852
853 static const struct option long_opts[] = {
854 { "priority", required_argument, NULL, 'p' },
855 { "discard", optional_argument, NULL, 'd' },
856 { "ifexists", no_argument, NULL, 'e' },
857 { "options", optional_argument, NULL, 'o' },
858 { "summary", no_argument, NULL, 's' },
859 { "fixpgsz", no_argument, NULL, 'f' },
860 { "all", no_argument, NULL, 'a' },
861 { "help", no_argument, NULL, 'h' },
862 { "verbose", no_argument, NULL, 'v' },
863 { "version", no_argument, NULL, 'V' },
864 { "show", optional_argument, NULL, SHOW_OPTION },
865 { "output-all", no_argument, NULL, OPT_LIST_TYPES },
866 { "noheadings", no_argument, NULL, NOHEADINGS_OPTION },
867 { "raw", no_argument, NULL, RAW_OPTION },
868 { "bytes", no_argument, NULL, BYTES_OPTION },
869 { NULL, 0, NULL, 0 }
870 };
871
872 static const ul_excl_t excl[] = { /* rows and cols in ASCII order */
873 { 'a','o','s', SHOW_OPTION },
874 { 'a','o', BYTES_OPTION },
875 { 'a','o', NOHEADINGS_OPTION },
876 { 'a','o', RAW_OPTION },
877 { 0 }
878 };
879 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
880
881 struct swapon_ctl ctl;
882
883 setlocale(LC_ALL, "");
884 bindtextdomain(PACKAGE, LOCALEDIR);
885 textdomain(PACKAGE);
886 atexit(close_stdout);
887
888 memset(&ctl, 0, sizeof(struct swapon_ctl));
889 ctl.props.priority = -1;
890
891 mnt_init_debug(0);
892 mntcache = mnt_new_cache();
893
894 while ((c = getopt_long(argc, argv, "ahd::efo:p:svVL:U:",
895 long_opts, NULL)) != -1) {
896
897 err_exclusive_options(c, long_opts, excl, excl_st);
898
899 switch (c) {
900 case 'a': /* all */
901 ctl.all = 1;
902 break;
903 case 'h': /* help */
904 usage();
905 break;
906 case 'o':
907 options = optarg;
908 break;
909 case 'p': /* priority */
910 ctl.props.priority = strtos16_or_err(optarg,
911 _("failed to parse priority"));
912 break;
913 case 'L':
914 add_label(optarg);
915 break;
916 case 'U':
917 add_uuid(optarg);
918 break;
919 case 'd':
920 ctl.props.discard |= SWAP_FLAG_DISCARD;
921 if (optarg) {
922 if (*optarg == '=')
923 optarg++;
924
925 if (strcmp(optarg, "once") == 0)
926 ctl.props.discard |= SWAP_FLAG_DISCARD_ONCE;
927 else if (strcmp(optarg, "pages") == 0)
928 ctl.props.discard |= SWAP_FLAG_DISCARD_PAGES;
929 else
930 errx(EXIT_FAILURE, _("unsupported discard policy: %s"), optarg);
931 }
932 break;
933 case 'e': /* ifexists */
934 ctl.props.no_fail = 1;
935 break;
936 case 'f':
937 ctl.fix_page_size = 1;
938 break;
939 case 's': /* status report */
940 status = display_summary();
941 return status;
942 case 'v': /* be chatty */
943 ctl.verbose = 1;
944 break;
945 case SHOW_OPTION:
946 if (optarg) {
947 ctl.ncolumns = string_to_idarray(optarg,
948 ctl.columns,
949 ARRAY_SIZE(ctl.columns),
950 column_name_to_id);
951 if (ctl.ncolumns < 0)
952 return EXIT_FAILURE;
953 }
954 ctl.show = 1;
955 break;
956 case OPT_LIST_TYPES:
957 for (ctl.ncolumns = 0; (size_t)ctl.ncolumns < ARRAY_SIZE(infos); ctl.ncolumns++)
958 ctl.columns[ctl.ncolumns] = ctl.ncolumns;
959 break;
960 case NOHEADINGS_OPTION:
961 ctl.no_heading = 1;
962 break;
963 case RAW_OPTION:
964 ctl.raw = 1;
965 break;
966 case BYTES_OPTION:
967 ctl.bytes = 1;
968 break;
969 case 'V': /* version */
970 printf(UTIL_LINUX_VERSION);
971 return EXIT_SUCCESS;
972 case 0:
973 break;
974 default:
975 errtryhelp(EXIT_FAILURE);
976 }
977 }
978 argv += optind;
979
980 if (ctl.show || (!ctl.all && !numof_labels() && !numof_uuids() && *argv == NULL)) {
981 if (!ctl.ncolumns) {
982 /* default columns */
983 ctl.columns[ctl.ncolumns++] = COL_PATH;
984 ctl.columns[ctl.ncolumns++] = COL_TYPE;
985 ctl.columns[ctl.ncolumns++] = COL_SIZE;
986 ctl.columns[ctl.ncolumns++] = COL_USED;
987 ctl.columns[ctl.ncolumns++] = COL_PRIO;
988 }
989 status = show_table(&ctl);
990 return status;
991 }
992
993 if (ctl.props.no_fail && !ctl.all) {
994 warnx(_("bad usage"));
995 errtryhelp(EXIT_FAILURE);
996 }
997
998 if (ctl.all)
999 status |= swapon_all(&ctl);
1000
1001 if (options)
1002 parse_options(&ctl.props, options);
1003
1004 for (i = 0; i < numof_labels(); i++)
1005 status |= swapon_by_label(&ctl, get_label(i));
1006
1007 for (i = 0; i < numof_uuids(); i++)
1008 status |= swapon_by_uuid(&ctl, get_uuid(i));
1009
1010 while (*argv != NULL)
1011 status |= do_swapon(&ctl, &ctl.props, *argv++, FALSE);
1012
1013 free_tables();
1014 mnt_unref_cache(mntcache);
1015
1016 return status;
1017 }