Blame SOURCES/ksmctl.c

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