thebeanogamer / rpms / qemu-kvm

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