Blame SOURCES/ksmctl.c

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