Blame SOURCES/ksmctl.c

4a2fec
/* Start/stop KSM, for systemd.
4a2fec
 * Copyright (C) 2009, 2011 Red Hat, Inc.
4a2fec
 * Written by Paolo Bonzini <pbonzini@redhat.com>.
4a2fec
 * Based on the original sysvinit script by Dan Kenigsberg <danken@redhat.com>
4a2fec
 * This file is distributed under the GNU General Public License, version 2
4a2fec
 * or later.  */
4a2fec
4a2fec
#include <unistd.h>
4a2fec
#include <stdio.h>
4a2fec
#include <limits.h>
4a2fec
#include <stdint.h>
4a2fec
#include <stdlib.h>
4a2fec
#include <string.h>
4a2fec
4a2fec
#define KSM_MAX_KERNEL_PAGES_FILE "/sys/kernel/mm/ksm/max_kernel_pages"
4a2fec
#define KSM_RUN_FILE		  "/sys/kernel/mm/ksm/run"
4a2fec
4a2fec
char *program_name;
4a2fec
4a2fec
int usage(void)
4a2fec
{
4a2fec
	fprintf(stderr, "Usage: %s {start|stop}\n", program_name);
4a2fec
	return 1;
4a2fec
}
4a2fec
4a2fec
int write_value(uint64_t value, char *filename)
4a2fec
{
4a2fec
	FILE *fp;
4a2fec
	if (!(fp = fopen(filename, "w")) ||
4a2fec
	    fprintf(fp, "%llu\n", (unsigned long long) value) == EOF ||
4a2fec
	    fflush(fp) == EOF ||
4a2fec
	    fclose(fp) == EOF)
4a2fec
		return 1;
4a2fec
4a2fec
	return 0;
4a2fec
}
4a2fec
4a2fec
uint64_t ksm_max_kernel_pages()
4a2fec
{
4a2fec
	char *var = getenv("KSM_MAX_KERNEL_PAGES");
4a2fec
	char *endptr;
4a2fec
	uint64_t value;
4a2fec
	if (var && *var) {
4a2fec
		value = strtoll(var, &endptr, 0);
4a2fec
		if (value < LLONG_MAX && !*endptr)
4a2fec
			return value;
4a2fec
	}
4a2fec
	/* Unless KSM_MAX_KERNEL_PAGES is set, let KSM munch up to half of
4a2fec
	 * total memory.  */
4a2fec
	return sysconf(_SC_PHYS_PAGES) / 2;
4a2fec
}
4a2fec
4a2fec
int start(void)
4a2fec
{
4a2fec
	if (access(KSM_MAX_KERNEL_PAGES_FILE, R_OK) >= 0)
4a2fec
		write_value(ksm_max_kernel_pages(), KSM_MAX_KERNEL_PAGES_FILE);
4a2fec
	return write_value(1, KSM_RUN_FILE);
4a2fec
}
4a2fec
4a2fec
int stop(void)
4a2fec
{
4a2fec
	return write_value(0, KSM_RUN_FILE);
4a2fec
}
4a2fec
4a2fec
int main(int argc, char **argv)
4a2fec
{
4a2fec
	program_name = argv[0];
4a2fec
	if (argc < 2) {
4a2fec
		return usage();
4a2fec
	} else if (!strcmp(argv[1], "start")) {
4a2fec
		return start();
4a2fec
	} else if (!strcmp(argv[1], "stop")) {
4a2fec
		return stop();
4a2fec
	} else {
4a2fec
		return usage();
4a2fec
	}
4a2fec
}