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