xref: /kvmtool/builtin-balloon.c (revision a4670ad1d0c02c1033c69255cbe3d5918e3bb22f)
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 #include <kvm/kvm-ipc.h>
11 
12 static const char *instance_name;
13 static u64 inflate;
14 static u64 deflate;
15 
16 struct balloon_cmd {
17 	u32 type;
18 	u32 len;
19 	int amount;
20 };
21 
22 static const char * const balloon_usage[] = {
23 	"lkvm balloon [-n name] [-p pid] [-i amount] [-d amount]",
24 	NULL
25 };
26 
27 static const struct option balloon_options[] = {
28 	OPT_GROUP("Instance options:"),
29 	OPT_STRING('n', "name", &instance_name, "name", "Instance name"),
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 	struct balloon_cmd cmd;
54 	int instance;
55 	int r;
56 
57 	parse_balloon_options(argc, argv);
58 
59 	if (inflate == 0 && deflate == 0)
60 		kvm_balloon_help();
61 
62 	if (instance_name == NULL)
63 		kvm_balloon_help();
64 
65 	instance = kvm__get_sock_by_instance(instance_name);
66 
67 	if (instance <= 0)
68 		die("Failed locating instance");
69 
70 	cmd.type = KVM_IPC_BALLOON;
71 	cmd.len = sizeof(cmd.amount);
72 
73 	if (inflate)
74 		cmd.amount = inflate;
75 	else if (deflate)
76 		cmd.amount = -deflate;
77 	else
78 		kvm_balloon_help();
79 
80 	r = write(instance, &cmd, sizeof(cmd));
81 
82 	close(instance);
83 
84 	if (r < 0)
85 		return -1;
86 
87 	return 0;
88 }
89