2 * zramctl - control compressed block devices in RAM
4 * Copyright (c) 2014 Timofey Titovets <Nefelim4ag@gmail.com>
5 * Copyright (C) 2014 Karel Zak <kzak@redhat.com>
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License as
9 * published by the Free Software Foundation.
11 * This program is distributed in the hope that it would be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 #include <sys/types.h>
29 #include <libsmartcols.h>
33 #include "closestream.h"
38 #include "ismounted.h"
41 #include "pathnames.h"
43 /*#define CONFIG_ZRAM_DEBUG*/
45 #ifdef CONFIG_ZRAM_DEBUG
46 # define DBG(x) do { fputs("zram: ", stderr); x; fputc('\n', stderr); } while(0)
51 /* status output columns */
74 static const struct colinfo infos
[] = {
75 [COL_NAME
] = { "NAME", 0.25, 0, N_("zram device name") },
76 [COL_DISKSIZE
] = { "DISKSIZE", 5, SCOLS_FL_RIGHT
, N_("limit on the uncompressed amount of data") },
77 [COL_ORIG_SIZE
] = { "DATA", 5, SCOLS_FL_RIGHT
, N_("uncompressed size of stored data") },
78 [COL_COMP_SIZE
] = { "COMPR", 5, SCOLS_FL_RIGHT
, N_("compressed size of stored data") },
79 [COL_ALGORITHM
] = { "ALGORITHM", 3, 0, N_("the selected compression algorithm") },
80 [COL_STREAMS
] = { "STREAMS", 3, SCOLS_FL_RIGHT
, N_("number of concurrent compress operations") },
81 [COL_ZEROPAGES
] = { "ZERO-PAGES", 3, SCOLS_FL_RIGHT
, N_("empty pages with no allocated memory") },
82 [COL_MEMTOTAL
] = { "TOTAL", 5, SCOLS_FL_RIGHT
, N_("all memory including allocator fragmentation and metadata overhead") },
83 [COL_MEMLIMIT
] = { "MEM-LIMIT", 5, SCOLS_FL_RIGHT
, N_("memory limit used to store compressed data") },
84 [COL_MEMUSED
] = { "MEM-USED", 5, SCOLS_FL_RIGHT
, N_("memory zram have been consumed to store compressed data") },
85 [COL_MIGRATED
] = { "MIGRATED", 5, SCOLS_FL_RIGHT
, N_("number of objects migrated by compaction") },
86 [COL_MOUNTPOINT
]= { "MOUNTPOINT",0.10, SCOLS_FL_TRUNC
, N_("where the device is mounted") },
89 static int columns
[ARRAY_SIZE(infos
) * 2] = {-1};
93 MM_ORIG_DATA_SIZE
= 0,
102 static const char *mm_stat_names
[] = {
103 [MM_ORIG_DATA_SIZE
] = "orig_data_size",
104 [MM_COMPR_DATA_SIZE
] = "compr_data_size",
105 [MM_MEM_USED_TOTAL
] = "mem_used_total",
106 [MM_MEM_LIMIT
] = "mem_limit",
107 [MM_MEM_USED_MAX
] = "mem_used_max",
108 [MM_ZERO_PAGES
] = "zero_pages",
109 [MM_NUM_MIGRATED
] = "num_migrated"
114 struct sysfs_cxt sysfs
;
117 unsigned int mm_stat_probed
: 1,
119 has_control
: 1; /* has /sys/class/zram-control/ */
122 static unsigned int raw
, no_headings
, inbytes
;
124 static int get_column_id(int num
)
126 assert(num
< ncolumns
);
127 assert(columns
[num
] < (int) ARRAY_SIZE(infos
));
131 static const struct colinfo
*get_column_info(int num
)
133 return &infos
[ get_column_id(num
) ];
136 static int column_name_to_id(const char *name
, size_t namesz
)
140 for (i
= 0; i
< ARRAY_SIZE(infos
); i
++) {
141 const char *cn
= infos
[i
].name
;
143 if (!strncasecmp(name
, cn
, namesz
) && !*(cn
+ namesz
))
146 warnx(_("unknown column: %s"), name
);
150 static void zram_reset_stat(struct zram
*z
)
153 strv_free(z
->mm_stat
);
155 z
->mm_stat_probed
= 0;
159 static void zram_set_devname(struct zram
*z
, const char *devname
, size_t n
)
164 snprintf(z
->devname
, sizeof(z
->devname
), "/dev/zram%zu", n
);
166 strncpy(z
->devname
, devname
, sizeof(z
->devname
));
167 z
->devname
[sizeof(z
->devname
) - 1] = '\0';
170 DBG(fprintf(stderr
, "set devname: %s", z
->devname
));
171 sysfs_deinit(&z
->sysfs
);
175 static int zram_get_devnum(struct zram
*z
)
181 if (sscanf(z
->devname
, "/dev/zram%d", &n
) == 1)
186 static struct zram
*new_zram(const char *devname
)
188 struct zram
*z
= xcalloc(1, sizeof(struct zram
));
190 DBG(fprintf(stderr
, "new: %p", z
));
192 zram_set_devname(z
, devname
, 0);
196 static void free_zram(struct zram
*z
)
200 DBG(fprintf(stderr
, "free: %p", z
));
201 sysfs_deinit(&z
->sysfs
);
206 static struct sysfs_cxt
*zram_get_sysfs(struct zram
*z
)
210 if (!z
->sysfs
.devno
) {
211 dev_t devno
= sysfs_devname_to_devno(z
->devname
, NULL
);
214 if (sysfs_init(&z
->sysfs
, devno
, NULL
))
216 if (*z
->devname
!= '/') {
217 /* canonicalize the device name according to /sys */
219 if (sysfs_get_devname(&z
->sysfs
, name
, sizeof(name
)))
220 snprintf(z
->devname
, sizeof(z
->devname
), "/dev/%s", name
);
227 static inline int zram_exist(struct zram
*z
)
232 if (zram_get_sysfs(z
) == NULL
) {
237 DBG(fprintf(stderr
, "%s exists", z
->devname
));
241 static int zram_set_u64parm(struct zram
*z
, const char *attr
, uint64_t num
)
243 struct sysfs_cxt
*sysfs
= zram_get_sysfs(z
);
246 DBG(fprintf(stderr
, "%s writing %ju to %s", z
->devname
, num
, attr
));
247 return sysfs_write_u64(sysfs
, attr
, num
);
250 static int zram_set_strparm(struct zram
*z
, const char *attr
, const char *str
)
252 struct sysfs_cxt
*sysfs
= zram_get_sysfs(z
);
255 DBG(fprintf(stderr
, "%s writing %s to %s", z
->devname
, str
, attr
));
256 return sysfs_write_string(sysfs
, attr
, str
);
260 static int zram_used(struct zram
*z
)
263 struct sysfs_cxt
*sysfs
= zram_get_sysfs(z
);
266 sysfs_read_u64(sysfs
, "disksize", &size
) == 0 &&
269 DBG(fprintf(stderr
, "%s used", z
->devname
));
272 DBG(fprintf(stderr
, "%s unused", z
->devname
));
276 static int zram_has_control(struct zram
*z
)
278 if (!z
->control_probed
) {
279 z
->has_control
= access(_PATH_SYS_CLASS
"/zram-control/", F_OK
) == 0 ? 1 : 0;
280 z
->control_probed
= 1;
281 DBG(fprintf(stderr
, "zram-control: %s", z
->has_control
? "yes" : "no"));
284 return z
->has_control
;
287 static int zram_control_add(struct zram
*z
)
291 if (!zram_has_control(z
))
294 n
= path_read_s32(_PATH_SYS_CLASS
"/zram-control/hot_add");
298 DBG(fprintf(stderr
, "hot-add: %d", n
));
299 zram_set_devname(z
, NULL
, n
);
303 static int zram_control_remove(struct zram
*z
)
305 char str
[sizeof stringify_value(INT_MAX
)];
308 if (!zram_has_control(z
))
311 n
= zram_get_devnum(z
);
315 DBG(fprintf(stderr
, "hot-remove: %d", n
));
316 snprintf(str
, sizeof(str
), "%d", n
);
317 return path_write_str(str
, _PATH_SYS_CLASS
"/zram-control/hot_remove");
320 static struct zram
*find_free_zram(void)
322 struct zram
*z
= new_zram(NULL
);
326 for (i
= 0; isfree
== 0; i
++) {
327 DBG(fprintf(stderr
, "find free: checking zram%zu", i
));
328 zram_set_devname(z
, NULL
, i
);
329 if (!zram_exist(z
) && zram_control_add(z
) != 0)
331 isfree
= !zram_used(z
);
340 static char *get_mm_stat(struct zram
*z
, size_t idx
, int bytes
)
342 struct sysfs_cxt
*sysfs
;
346 assert(idx
< ARRAY_SIZE(mm_stat_names
));
349 sysfs
= zram_get_sysfs(z
);
353 /* Linux >= 4.1 uses /sys/block/zram<id>/mm_stat */
354 if (!z
->mm_stat
&& !z
->mm_stat_probed
) {
357 str
= sysfs_strdup(sysfs
, "mm_stat");
359 z
->mm_stat
= strv_split(str
, " ");
361 /* make sure kernel provides mm_stat as expected */
362 if (strv_length(z
->mm_stat
) < ARRAY_SIZE(mm_stat_names
)) {
363 strv_free(z
->mm_stat
);
367 z
->mm_stat_probed
= 1;
374 return xstrdup(z
->mm_stat
[idx
]);
376 num
= strtou64_or_err(z
->mm_stat
[idx
], _("Failed to parse mm_stat"));
377 return size_to_human_string(SIZE_SUFFIX_1LETTER
, num
);
380 /* Linux < 4.1 uses /sys/block/zram<id>/<attrname> */
381 name
= mm_stat_names
[idx
];
383 return sysfs_strdup(sysfs
, name
);
384 else if (sysfs_read_u64(sysfs
, name
, &num
) == 0)
385 return size_to_human_string(SIZE_SUFFIX_1LETTER
, num
);
389 static void fill_table_row(struct libscols_table
*tb
, struct zram
*z
)
391 static struct libscols_line
*ln
;
392 struct sysfs_cxt
*sysfs
;
399 DBG(fprintf(stderr
, "%s: filling status table", z
->devname
));
401 sysfs
= zram_get_sysfs(z
);
405 ln
= scols_table_new_line(tb
, NULL
);
407 err(EXIT_FAILURE
, _("failed to allocate output line"));
409 for (i
= 0; i
< (size_t) ncolumns
; i
++) {
412 switch (get_column_id(i
)) {
414 str
= xstrdup(z
->devname
);
418 str
= sysfs_strdup(sysfs
, "disksize");
419 else if (sysfs_read_u64(sysfs
, "disksize", &num
) == 0)
420 str
= size_to_human_string(SIZE_SUFFIX_1LETTER
, num
);
424 char *alg
= sysfs_strdup(sysfs
, "comp_algorithm");
427 char* lbr
= strrchr(alg
, '[');
428 char* rbr
= strrchr(alg
, ']');
430 if (lbr
!= NULL
&& rbr
!= NULL
&& rbr
- lbr
> 1)
431 str
= xstrndup(lbr
+ 1, rbr
- lbr
- 1);
438 char path
[PATH_MAX
] = { '\0' };
441 check_mount_point(z
->devname
, &fl
, path
, sizeof(path
));
447 str
= sysfs_strdup(sysfs
, "max_comp_streams");
450 str
= get_mm_stat(z
, MM_ZERO_PAGES
, 1);
453 str
= get_mm_stat(z
, MM_ORIG_DATA_SIZE
, inbytes
);
456 str
= get_mm_stat(z
, MM_COMPR_DATA_SIZE
, inbytes
);
459 str
= get_mm_stat(z
, MM_MEM_USED_TOTAL
, inbytes
);
462 str
= get_mm_stat(z
, MM_MEM_LIMIT
, inbytes
);
465 str
= get_mm_stat(z
, MM_MEM_USED_MAX
, inbytes
);
468 str
= get_mm_stat(z
, MM_NUM_MIGRATED
, inbytes
);
471 if (str
&& scols_line_refer_data(ln
, i
, str
))
472 err(EXIT_FAILURE
, _("failed to add output data"));
476 static void status(struct zram
*z
)
478 struct libscols_table
*tb
;
485 tb
= scols_new_table();
487 err(EXIT_FAILURE
, _("failed to allocate output table"));
489 scols_table_enable_raw(tb
, raw
);
490 scols_table_enable_noheadings(tb
, no_headings
);
492 for (i
= 0; i
< (size_t) ncolumns
; i
++) {
493 const struct colinfo
*col
= get_column_info(i
);
495 if (!scols_table_new_column(tb
, col
->name
, col
->whint
, col
->flags
))
496 err(EXIT_FAILURE
, _("failed to initialize output column"));
500 /* just one device specified */
501 fill_table_row(tb
, z
);
505 /* list all used devices */
507 if (!(dir
= opendir(_PATH_DEV
)))
508 err(EXIT_FAILURE
, _("cannot open %s"), _PATH_DEV
);
510 while ((d
= readdir(dir
))) {
512 if (sscanf(d
->d_name
, "zram%d", &n
) != 1)
514 zram_set_devname(z
, NULL
, n
);
515 if (zram_exist(z
) && zram_used(z
))
516 fill_table_row(tb
, z
);
522 scols_print_table(tb
);
523 scols_unref_table(tb
);
526 static void __attribute__((__noreturn__
)) usage(void)
531 fputs(USAGE_HEADER
, out
);
532 fprintf(out
, _( " %1$s [options] <device>\n"
533 " %1$s -r <device> [...]\n"
534 " %1$s [options] -f | <device> -s <size>\n"),
535 program_invocation_short_name
);
537 fputs(USAGE_SEPARATOR
, out
);
538 fputs(_("Set up and control zram devices.\n"), out
);
540 fputs(USAGE_OPTIONS
, out
);
541 fputs(_(" -a, --algorithm lzo|lz4|lz4hc|deflate|842 compression algorithm to use\n"), out
);
542 fputs(_(" -b, --bytes print sizes in bytes rather than in human readable format\n"), out
);
543 fputs(_(" -f, --find find a free device\n"), out
);
544 fputs(_(" -n, --noheadings don't print headings\n"), out
);
545 fputs(_(" -o, --output <list> columns to use for status output\n"), out
);
546 fputs(_(" --output-all output all columns\n"), out
);
547 fputs(_(" --raw use raw status output format\n"), out
);
548 fputs(_(" -r, --reset reset all specified devices\n"), out
);
549 fputs(_(" -s, --size <size> device size\n"), out
);
550 fputs(_(" -t, --streams <number> number of compression streams\n"), out
);
552 fputs(USAGE_SEPARATOR
, out
);
553 printf(USAGE_HELP_OPTIONS(27));
555 fputs(USAGE_COLUMNS
, out
);
556 for (i
= 0; i
< ARRAY_SIZE(infos
); i
++)
557 fprintf(out
, " %11s %s\n", infos
[i
].name
, _(infos
[i
].help
));
559 printf(USAGE_MAN_TAIL("zramctl(8)"));
572 int main(int argc
, char **argv
)
574 uintmax_t size
= 0, nstreams
= 0;
575 char *algorithm
= NULL
;
576 int rc
= 0, c
, find
= 0, act
= A_NONE
;
577 struct zram
*zram
= NULL
;
580 OPT_RAW
= CHAR_MAX
+ 1,
584 static const struct option longopts
[] = {
585 { "algorithm", required_argument
, NULL
, 'a' },
586 { "bytes", no_argument
, NULL
, 'b' },
587 { "find", no_argument
, NULL
, 'f' },
588 { "help", no_argument
, NULL
, 'h' },
589 { "output", required_argument
, NULL
, 'o' },
590 { "output-all",no_argument
, NULL
, OPT_LIST_TYPES
},
591 { "noheadings",no_argument
, NULL
, 'n' },
592 { "reset", no_argument
, NULL
, 'r' },
593 { "raw", no_argument
, NULL
, OPT_RAW
},
594 { "size", required_argument
, NULL
, 's' },
595 { "streams", required_argument
, NULL
, 't' },
596 { "version", no_argument
, NULL
, 'V' },
600 static const ul_excl_t excl
[] = {
605 int excl_st
[ARRAY_SIZE(excl
)] = UL_EXCL_STATUS_INIT
;
607 setlocale(LC_ALL
, "");
608 bindtextdomain(PACKAGE
, LOCALEDIR
);
610 atexit(close_stdout
);
612 while ((c
= getopt_long(argc
, argv
, "a:bfho:nrs:t:V", longopts
, NULL
)) != -1) {
614 err_exclusive_options(c
, longopts
, excl
, excl_st
);
627 ncolumns
= string_to_idarray(optarg
,
628 columns
, ARRAY_SIZE(columns
),
634 for (ncolumns
= 0; (size_t)ncolumns
< ARRAY_SIZE(infos
); ncolumns
++)
635 columns
[ncolumns
] = ncolumns
;
638 size
= strtosize_or_err(optarg
, _("failed to parse size"));
642 nstreams
= strtou64_or_err(optarg
, _("failed to parse streams"));
654 printf(UTIL_LINUX_VERSION
);
659 errtryhelp(EXIT_FAILURE
);
663 if (find
&& optind
< argc
)
664 errx(EXIT_FAILURE
, _("option --find is mutually exclusive "
667 act
= find
? A_FINDONLY
: A_STATUS
;
669 if (act
!= A_RESET
&& optind
+ 1 < argc
)
670 errx(EXIT_FAILURE
, _("only one <device> at a time is allowed"));
672 if ((act
== A_STATUS
|| act
== A_FINDONLY
) && (algorithm
|| nstreams
))
673 errx(EXIT_FAILURE
, _("options --algorithm and --streams "
674 "must be combined with --size"));
678 if (!ncolumns
) { /* default columns */
679 columns
[ncolumns
++] = COL_NAME
;
680 columns
[ncolumns
++] = COL_ALGORITHM
;
681 columns
[ncolumns
++] = COL_DISKSIZE
;
682 columns
[ncolumns
++] = COL_ORIG_SIZE
;
683 columns
[ncolumns
++] = COL_COMP_SIZE
;
684 columns
[ncolumns
++] = COL_MEMTOTAL
;
685 columns
[ncolumns
++] = COL_STREAMS
;
686 columns
[ncolumns
++] = COL_MOUNTPOINT
;
689 zram
= new_zram(argv
[optind
++]);
690 if (!zram_exist(zram
))
691 err(EXIT_FAILURE
, "%s", zram
->devname
);
698 errx(EXIT_FAILURE
, _("no device specified"));
699 while (optind
< argc
) {
700 zram
= new_zram(argv
[optind
]);
701 if (!zram_exist(zram
)
702 || zram_set_u64parm(zram
, "reset", 1)) {
703 warn(_("%s: failed to reset"), zram
->devname
);
706 zram_control_remove(zram
);
712 zram
= find_free_zram();
714 errx(EXIT_FAILURE
, _("no free zram device found"));
715 printf("%s\n", zram
->devname
);
720 zram
= find_free_zram();
722 errx(EXIT_FAILURE
, _("no free zram device found"));
723 } else if (optind
== argc
)
724 errx(EXIT_FAILURE
, _("no device specified"));
726 zram
= new_zram(argv
[optind
]);
727 if (!zram_exist(zram
))
728 err(EXIT_FAILURE
, "%s", zram
->devname
);
731 if (zram_set_u64parm(zram
, "reset", 1))
732 err(EXIT_FAILURE
, _("%s: failed to reset"), zram
->devname
);
735 zram_set_u64parm(zram
, "max_comp_streams", nstreams
))
736 err(EXIT_FAILURE
, _("%s: failed to set number of streams"), zram
->devname
);
739 zram_set_strparm(zram
, "comp_algorithm", algorithm
))
740 err(EXIT_FAILURE
, _("%s: failed to set algorithm"), zram
->devname
);
742 if (zram_set_u64parm(zram
, "disksize", size
))
743 err(EXIT_FAILURE
, _("%s: failed to set disksize (%ju bytes)"),
744 zram
->devname
, size
);
746 printf("%s\n", zram
->devname
);
751 return rc
? EXIT_FAILURE
: EXIT_SUCCESS
;