xref: /kvmtool/builtin-balloon.c (revision 790142ec29168bf50beee617d40bc08b28d2b824)
1 #include <stdio.h>
2 #include <string.h>
3 #include <signal.h>
4 
5 #include <kvm/util.h>
6 #include <kvm/kvm-cmd.h>
7 #include <kvm/builtin-balloon.h>
8 #include <kvm/parse-options.h>
9 #include <kvm/kvm.h>
10 
11 static u64 instance_pid;
12 static const char *instance_name;
13 static u64 inflate;
14 static u64 deflate;
15 
16 static const char * const balloon_usage[] = {
17 	"kvm balloon {inflate|deflate} <size in MiB> <instance name>",
18 	NULL
19 };
20 
21 static const char * const debug_usage[] = {
22 	"kvm balloon [-n name] [-p pid] [-i amount] [-d amount]",
23 	NULL
24 };
25 
26 static const struct option balloon_options[] = {
27 	OPT_GROUP("Instance options:"),
28 	OPT_STRING('n', "name", &instance_name, "name", "Instance name"),
29 	OPT_U64('p', "pid", &instance_pid, "Instance pid"),
30 	OPT_GROUP("Balloon options:"),
31 	OPT_U64('i', "inflate", &inflate, "Amount to inflate"),
32 	OPT_U64('d', "deflate", &deflate, "Amount to deflate"),
33 	OPT_END(),
34 };
35 
36 void kvm_balloon_help(void)
37 {
38 	usage_with_options(balloon_usage, balloon_options);
39 }
40 
41 static void parse_balloon_options(int argc, const char **argv)
42 {
43 	while (argc != 0) {
44 		argc = parse_options(argc, argv, balloon_options, balloon_usage,
45 				PARSE_OPT_STOP_AT_NON_OPTION);
46 		if (argc != 0)
47 			kvm_balloon_help();
48 	}
49 }
50 
51 int kvm_cmd_balloon(int argc, const char **argv, const char *prefix)
52 {
53 	u64 i;
54 
55 	parse_balloon_options(argc, argv);
56 
57 	if (inflate == 0 && deflate == 0)
58 		kvm_balloon_help();
59 
60 	if (instance_name == NULL &&
61 	    instance_pid == 0)
62 		kvm_balloon_help();
63 
64 	if (instance_name)
65 		instance_pid = kvm__get_pid_by_instance(argv[0]);
66 
67 	if (instance_pid <= 0)
68 		die("Failed locating instance");
69 
70 	if (inflate)
71 		for (i = 0; i < inflate; i++)
72 			kill(instance_pid, SIGKVMADDMEM);
73 	else if (deflate)
74 		for (i = 0; i < deflate; i++)
75 			kill(instance_pid, SIGKVMDELMEM);
76 	else
77 		kvm_balloon_help();
78 
79 	return 0;
80 }
81