cryptospore / rpms / qemu-kvm

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