1 /*
2  * Virtio balloon implementation, inspired by Dor Laor and Marcelo
3  * Tosatti's implementations.
4  *
5  *  Copyright 2008 Rusty Russell IBM Corporation
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 2 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, write to the Free Software
19  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21 
22 #include <linux/virtio.h>
23 #include <linux/virtio_balloon.h>
24 #include <linux/swap.h>
25 #include <linux/kthread.h>
26 #include <linux/freezer.h>
27 #include <linux/delay.h>
28 #include <linux/slab.h>
29 #include <linux/module.h>
30 #include <linux/balloon_compaction.h>
31 
32 /*
33  * Balloon device works in 4K page units.  So each page is pointed to by
34  * multiple balloon pages.  All memory counters in this driver are in balloon
35  * page units.
36  */
37 #define VIRTIO_BALLOON_PAGES_PER_PAGE (unsigned)(PAGE_SIZE >> VIRTIO_BALLOON_PFN_SHIFT)
38 #define VIRTIO_BALLOON_ARRAY_PFNS_MAX 256
39 
40 struct virtio_balloon
41 {
42 	struct virtio_device *vdev;
43 	struct virtqueue *inflate_vq, *deflate_vq, *stats_vq;
44 
45 	/* Where the ballooning thread waits for config to change. */
46 	wait_queue_head_t config_change;
47 
48 	/* The thread servicing the balloon. */
49 	struct task_struct *thread;
50 
51 	/* Waiting for host to ack the pages we released. */
52 	wait_queue_head_t acked;
53 
54 	/* Number of balloon pages we've told the Host we're not using. */
55 	unsigned int num_pages;
56 	/*
57 	 * The pages we've told the Host we're not using are enqueued
58 	 * at vb_dev_info->pages list.
59 	 * Each page on this list adds VIRTIO_BALLOON_PAGES_PER_PAGE
60 	 * to num_pages above.
61 	 */
62 	struct balloon_dev_info *vb_dev_info;
63 
64 	/* Synchronize access/update to this struct virtio_balloon elements */
65 	struct mutex balloon_lock;
66 
67 	/* The array of pfns we tell the Host about. */
68 	unsigned int num_pfns;
69 	u32 pfns[VIRTIO_BALLOON_ARRAY_PFNS_MAX];
70 
71 	/* Memory statistics */
72 	int need_stats_update;
73 	struct virtio_balloon_stat stats[VIRTIO_BALLOON_S_NR];
74 };
75 
76 static struct virtio_device_id id_table[] = {
77 	{ VIRTIO_ID_BALLOON, VIRTIO_DEV_ANY_ID },
78 	{ 0 },
79 };
80 
81 static u32 page_to_balloon_pfn(struct page *page)
82 {
83 	unsigned long pfn = page_to_pfn(page);
84 
85 	BUILD_BUG_ON(PAGE_SHIFT < VIRTIO_BALLOON_PFN_SHIFT);
86 	/* Convert pfn from Linux page size to balloon page size. */
87 	return pfn * VIRTIO_BALLOON_PAGES_PER_PAGE;
88 }
89 
90 static struct page *balloon_pfn_to_page(u32 pfn)
91 {
92 	BUG_ON(pfn % VIRTIO_BALLOON_PAGES_PER_PAGE);
93 	return pfn_to_page(pfn / VIRTIO_BALLOON_PAGES_PER_PAGE);
94 }
95 
96 static void balloon_ack(struct virtqueue *vq)
97 {
98 	struct virtio_balloon *vb = vq->vdev->priv;
99 
100 	wake_up(&vb->acked);
101 }
102 
103 static void tell_host(struct virtio_balloon *vb, struct virtqueue *vq)
104 {
105 	struct scatterlist sg;
106 	unsigned int len;
107 
108 	sg_init_one(&sg, vb->pfns, sizeof(vb->pfns[0]) * vb->num_pfns);
109 
110 	/* We should always be able to add one buffer to an empty queue. */
111 	virtqueue_add_outbuf(vq, &sg, 1, vb, GFP_KERNEL);
112 	virtqueue_kick(vq);
113 
114 	/* When host has read buffer, this completes via balloon_ack */
115 	wait_event(vb->acked, virtqueue_get_buf(vq, &len));
116 }
117 
118 static void set_page_pfns(u32 pfns[], struct page *page)
119 {
120 	unsigned int i;
121 
122 	/* Set balloon pfns pointing at this page.
123 	 * Note that the first pfn points at start of the page. */
124 	for (i = 0; i < VIRTIO_BALLOON_PAGES_PER_PAGE; i++)
125 		pfns[i] = page_to_balloon_pfn(page) + i;
126 }
127 
128 static void fill_balloon(struct virtio_balloon *vb, size_t num)
129 {
130 	struct balloon_dev_info *vb_dev_info = vb->vb_dev_info;
131 
132 	/* We can only do one array worth at a time. */
133 	num = min(num, ARRAY_SIZE(vb->pfns));
134 
135 	mutex_lock(&vb->balloon_lock);
136 	for (vb->num_pfns = 0; vb->num_pfns < num;
137 	     vb->num_pfns += VIRTIO_BALLOON_PAGES_PER_PAGE) {
138 		struct page *page = balloon_page_enqueue(vb_dev_info);
139 
140 		if (!page) {
141 			dev_info_ratelimited(&vb->vdev->dev,
142 					     "Out of puff! Can't get %u pages\n",
143 					     VIRTIO_BALLOON_PAGES_PER_PAGE);
144 			/* Sleep for at least 1/5 of a second before retry. */
145 			msleep(200);
146 			break;
147 		}
148 		set_page_pfns(vb->pfns + vb->num_pfns, page);
149 		vb->num_pages += VIRTIO_BALLOON_PAGES_PER_PAGE;
150 		adjust_managed_page_count(page, -1);
151 	}
152 
153 	/* Did we get any? */
154 	if (vb->num_pfns != 0)
155 		tell_host(vb, vb->inflate_vq);
156 	mutex_unlock(&vb->balloon_lock);
157 }
158 
159 static void release_pages_by_pfn(const u32 pfns[], unsigned int num)
160 {
161 	unsigned int i;
162 
163 	/* Find pfns pointing at start of each page, get pages and free them. */
164 	for (i = 0; i < num; i += VIRTIO_BALLOON_PAGES_PER_PAGE) {
165 		struct page *page = balloon_pfn_to_page(pfns[i]);
166 		balloon_page_free(page);
167 		adjust_managed_page_count(page, 1);
168 	}
169 }
170 
171 static void leak_balloon(struct virtio_balloon *vb, size_t num)
172 {
173 	struct page *page;
174 	struct balloon_dev_info *vb_dev_info = vb->vb_dev_info;
175 
176 	/* We can only do one array worth at a time. */
177 	num = min(num, ARRAY_SIZE(vb->pfns));
178 
179 	mutex_lock(&vb->balloon_lock);
180 	for (vb->num_pfns = 0; vb->num_pfns < num;
181 	     vb->num_pfns += VIRTIO_BALLOON_PAGES_PER_PAGE) {
182 		page = balloon_page_dequeue(vb_dev_info);
183 		if (!page)
184 			break;
185 		set_page_pfns(vb->pfns + vb->num_pfns, page);
186 		vb->num_pages -= VIRTIO_BALLOON_PAGES_PER_PAGE;
187 	}
188 
189 	/*
190 	 * Note that if
191 	 * virtio_has_feature(vdev, VIRTIO_BALLOON_F_MUST_TELL_HOST);
192 	 * is true, we *have* to do it in this order
193 	 */
194 	if (vb->num_pfns != 0)
195 		tell_host(vb, vb->deflate_vq);
196 	mutex_unlock(&vb->balloon_lock);
197 	release_pages_by_pfn(vb->pfns, vb->num_pfns);
198 }
199 
200 static inline void update_stat(struct virtio_balloon *vb, int idx,
201 			       u16 tag, u64 val)
202 {
203 	BUG_ON(idx >= VIRTIO_BALLOON_S_NR);
204 	vb->stats[idx].tag = tag;
205 	vb->stats[idx].val = val;
206 }
207 
208 #define pages_to_bytes(x) ((u64)(x) << PAGE_SHIFT)
209 
210 static void update_balloon_stats(struct virtio_balloon *vb)
211 {
212 	unsigned long events[NR_VM_EVENT_ITEMS];
213 	struct sysinfo i;
214 	int idx = 0;
215 
216 	all_vm_events(events);
217 	si_meminfo(&i);
218 
219 	update_stat(vb, idx++, VIRTIO_BALLOON_S_SWAP_IN,
220 				pages_to_bytes(events[PSWPIN]));
221 	update_stat(vb, idx++, VIRTIO_BALLOON_S_SWAP_OUT,
222 				pages_to_bytes(events[PSWPOUT]));
223 	update_stat(vb, idx++, VIRTIO_BALLOON_S_MAJFLT, events[PGMAJFAULT]);
224 	update_stat(vb, idx++, VIRTIO_BALLOON_S_MINFLT, events[PGFAULT]);
225 	update_stat(vb, idx++, VIRTIO_BALLOON_S_MEMFREE,
226 				pages_to_bytes(i.freeram));
227 	update_stat(vb, idx++, VIRTIO_BALLOON_S_MEMTOT,
228 				pages_to_bytes(i.totalram));
229 }
230 
231 /*
232  * While most virtqueues communicate guest-initiated requests to the hypervisor,
233  * the stats queue operates in reverse.  The driver initializes the virtqueue
234  * with a single buffer.  From that point forward, all conversations consist of
235  * a hypervisor request (a call to this function) which directs us to refill
236  * the virtqueue with a fresh stats buffer.  Since stats collection can sleep,
237  * we notify our kthread which does the actual work via stats_handle_request().
238  */
239 static void stats_request(struct virtqueue *vq)
240 {
241 	struct virtio_balloon *vb = vq->vdev->priv;
242 
243 	vb->need_stats_update = 1;
244 	wake_up(&vb->config_change);
245 }
246 
247 static void stats_handle_request(struct virtio_balloon *vb)
248 {
249 	struct virtqueue *vq;
250 	struct scatterlist sg;
251 	unsigned int len;
252 
253 	vb->need_stats_update = 0;
254 	update_balloon_stats(vb);
255 
256 	vq = vb->stats_vq;
257 	if (!virtqueue_get_buf(vq, &len))
258 		return;
259 	sg_init_one(&sg, vb->stats, sizeof(vb->stats));
260 	virtqueue_add_outbuf(vq, &sg, 1, vb, GFP_KERNEL);
261 	virtqueue_kick(vq);
262 }
263 
264 static void virtballoon_changed(struct virtio_device *vdev)
265 {
266 	struct virtio_balloon *vb = vdev->priv;
267 
268 	wake_up(&vb->config_change);
269 }
270 
271 static inline s64 towards_target(struct virtio_balloon *vb)
272 {
273 	__le32 v;
274 	s64 target;
275 
276 	virtio_cread(vb->vdev, struct virtio_balloon_config, num_pages, &v);
277 
278 	target = le32_to_cpu(v);
279 	return target - vb->num_pages;
280 }
281 
282 static void update_balloon_size(struct virtio_balloon *vb)
283 {
284 	__le32 actual = cpu_to_le32(vb->num_pages);
285 
286 	virtio_cwrite(vb->vdev, struct virtio_balloon_config, actual,
287 		      &actual);
288 }
289 
290 static int balloon(void *_vballoon)
291 {
292 	struct virtio_balloon *vb = _vballoon;
293 
294 	set_freezable();
295 	while (!kthread_should_stop()) {
296 		s64 diff;
297 
298 		try_to_freeze();
299 		wait_event_interruptible(vb->config_change,
300 					 (diff = towards_target(vb)) != 0
301 					 || vb->need_stats_update
302 					 || kthread_should_stop()
303 					 || freezing(current));
304 		if (vb->need_stats_update)
305 			stats_handle_request(vb);
306 		if (diff > 0)
307 			fill_balloon(vb, diff);
308 		else if (diff < 0)
309 			leak_balloon(vb, -diff);
310 		update_balloon_size(vb);
311 
312 		/*
313 		 * For large balloon changes, we could spend a lot of time
314 		 * and always have work to do.  Be nice if preempt disabled.
315 		 */
316 		cond_resched();
317 	}
318 	return 0;
319 }
320 
321 static int init_vqs(struct virtio_balloon *vb)
322 {
323 	struct virtqueue *vqs[3];
324 	vq_callback_t *callbacks[] = { balloon_ack, balloon_ack, stats_request };
325 	const char *names[] = { "inflate", "deflate", "stats" };
326 	int err, nvqs;
327 
328 	/*
329 	 * We expect two virtqueues: inflate and deflate, and
330 	 * optionally stat.
331 	 */
332 	nvqs = virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_STATS_VQ) ? 3 : 2;
333 	err = vb->vdev->config->find_vqs(vb->vdev, nvqs, vqs, callbacks, names);
334 	if (err)
335 		return err;
336 
337 	vb->inflate_vq = vqs[0];
338 	vb->deflate_vq = vqs[1];
339 	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_STATS_VQ)) {
340 		struct scatterlist sg;
341 		vb->stats_vq = vqs[2];
342 
343 		/*
344 		 * Prime this virtqueue with one buffer so the hypervisor can
345 		 * use it to signal us later (it can't be broken yet!).
346 		 */
347 		sg_init_one(&sg, vb->stats, sizeof vb->stats);
348 		if (virtqueue_add_outbuf(vb->stats_vq, &sg, 1, vb, GFP_KERNEL)
349 		    < 0)
350 			BUG();
351 		virtqueue_kick(vb->stats_vq);
352 	}
353 	return 0;
354 }
355 
356 static const struct address_space_operations virtio_balloon_aops;
357 #ifdef CONFIG_BALLOON_COMPACTION
358 /*
359  * virtballoon_migratepage - perform the balloon page migration on behalf of
360  *			     a compation thread.     (called under page lock)
361  * @mapping: the page->mapping which will be assigned to the new migrated page.
362  * @newpage: page that will replace the isolated page after migration finishes.
363  * @page   : the isolated (old) page that is about to be migrated to newpage.
364  * @mode   : compaction mode -- not used for balloon page migration.
365  *
366  * After a ballooned page gets isolated by compaction procedures, this is the
367  * function that performs the page migration on behalf of a compaction thread
368  * The page migration for virtio balloon is done in a simple swap fashion which
369  * follows these two macro steps:
370  *  1) insert newpage into vb->pages list and update the host about it;
371  *  2) update the host about the old page removed from vb->pages list;
372  *
373  * This function preforms the balloon page migration task.
374  * Called through balloon_mapping->a_ops->migratepage
375  */
376 static int virtballoon_migratepage(struct address_space *mapping,
377 		struct page *newpage, struct page *page, enum migrate_mode mode)
378 {
379 	struct balloon_dev_info *vb_dev_info = balloon_page_device(page);
380 	struct virtio_balloon *vb;
381 	unsigned long flags;
382 
383 	BUG_ON(!vb_dev_info);
384 
385 	vb = vb_dev_info->balloon_device;
386 
387 	/*
388 	 * In order to avoid lock contention while migrating pages concurrently
389 	 * to leak_balloon() or fill_balloon() we just give up the balloon_lock
390 	 * this turn, as it is easier to retry the page migration later.
391 	 * This also prevents fill_balloon() getting stuck into a mutex
392 	 * recursion in the case it ends up triggering memory compaction
393 	 * while it is attempting to inflate the ballon.
394 	 */
395 	if (!mutex_trylock(&vb->balloon_lock))
396 		return -EAGAIN;
397 
398 	/* balloon's page migration 1st step  -- inflate "newpage" */
399 	spin_lock_irqsave(&vb_dev_info->pages_lock, flags);
400 	balloon_page_insert(newpage, mapping, &vb_dev_info->pages);
401 	vb_dev_info->isolated_pages--;
402 	spin_unlock_irqrestore(&vb_dev_info->pages_lock, flags);
403 	vb->num_pfns = VIRTIO_BALLOON_PAGES_PER_PAGE;
404 	set_page_pfns(vb->pfns, newpage);
405 	tell_host(vb, vb->inflate_vq);
406 
407 	/*
408 	 * balloon's page migration 2nd step -- deflate "page"
409 	 *
410 	 * It's safe to delete page->lru here because this page is at
411 	 * an isolated migration list, and this step is expected to happen here
412 	 */
413 	balloon_page_delete(page);
414 	vb->num_pfns = VIRTIO_BALLOON_PAGES_PER_PAGE;
415 	set_page_pfns(vb->pfns, page);
416 	tell_host(vb, vb->deflate_vq);
417 
418 	mutex_unlock(&vb->balloon_lock);
419 
420 	return MIGRATEPAGE_BALLOON_SUCCESS;
421 }
422 
423 /* define the balloon_mapping->a_ops callback to allow balloon page migration */
424 static const struct address_space_operations virtio_balloon_aops = {
425 			.migratepage = virtballoon_migratepage,
426 };
427 #endif /* CONFIG_BALLOON_COMPACTION */
428 
429 static int virtballoon_probe(struct virtio_device *vdev)
430 {
431 	struct virtio_balloon *vb;
432 	struct address_space *vb_mapping;
433 	struct balloon_dev_info *vb_devinfo;
434 	int err;
435 
436 	vdev->priv = vb = kmalloc(sizeof(*vb), GFP_KERNEL);
437 	if (!vb) {
438 		err = -ENOMEM;
439 		goto out;
440 	}
441 
442 	vb->num_pages = 0;
443 	mutex_init(&vb->balloon_lock);
444 	init_waitqueue_head(&vb->config_change);
445 	init_waitqueue_head(&vb->acked);
446 	vb->vdev = vdev;
447 	vb->need_stats_update = 0;
448 
449 	vb_devinfo = balloon_devinfo_alloc(vb);
450 	if (IS_ERR(vb_devinfo)) {
451 		err = PTR_ERR(vb_devinfo);
452 		goto out_free_vb;
453 	}
454 
455 	vb_mapping = balloon_mapping_alloc(vb_devinfo,
456 					   (balloon_compaction_check()) ?
457 					   &virtio_balloon_aops : NULL);
458 	if (IS_ERR(vb_mapping)) {
459 		/*
460 		 * IS_ERR(vb_mapping) && PTR_ERR(vb_mapping) == -EOPNOTSUPP
461 		 * This means !CONFIG_BALLOON_COMPACTION, otherwise we get off.
462 		 */
463 		err = PTR_ERR(vb_mapping);
464 		if (err != -EOPNOTSUPP)
465 			goto out_free_vb_devinfo;
466 	}
467 
468 	vb->vb_dev_info = vb_devinfo;
469 
470 	err = init_vqs(vb);
471 	if (err)
472 		goto out_free_vb_mapping;
473 
474 	vb->thread = kthread_run(balloon, vb, "vballoon");
475 	if (IS_ERR(vb->thread)) {
476 		err = PTR_ERR(vb->thread);
477 		goto out_del_vqs;
478 	}
479 
480 	return 0;
481 
482 out_del_vqs:
483 	vdev->config->del_vqs(vdev);
484 out_free_vb_mapping:
485 	balloon_mapping_free(vb_mapping);
486 out_free_vb_devinfo:
487 	balloon_devinfo_free(vb_devinfo);
488 out_free_vb:
489 	kfree(vb);
490 out:
491 	return err;
492 }
493 
494 static void remove_common(struct virtio_balloon *vb)
495 {
496 	/* There might be pages left in the balloon: free them. */
497 	while (vb->num_pages)
498 		leak_balloon(vb, vb->num_pages);
499 	update_balloon_size(vb);
500 
501 	/* Now we reset the device so we can clean up the queues. */
502 	vb->vdev->config->reset(vb->vdev);
503 
504 	vb->vdev->config->del_vqs(vb->vdev);
505 }
506 
507 static void virtballoon_remove(struct virtio_device *vdev)
508 {
509 	struct virtio_balloon *vb = vdev->priv;
510 
511 	kthread_stop(vb->thread);
512 	remove_common(vb);
513 	balloon_mapping_free(vb->vb_dev_info->mapping);
514 	balloon_devinfo_free(vb->vb_dev_info);
515 	kfree(vb);
516 }
517 
518 #ifdef CONFIG_PM_SLEEP
519 static int virtballoon_freeze(struct virtio_device *vdev)
520 {
521 	struct virtio_balloon *vb = vdev->priv;
522 
523 	/*
524 	 * The kthread is already frozen by the PM core before this
525 	 * function is called.
526 	 */
527 
528 	remove_common(vb);
529 	return 0;
530 }
531 
532 static int virtballoon_restore(struct virtio_device *vdev)
533 {
534 	struct virtio_balloon *vb = vdev->priv;
535 	int ret;
536 
537 	ret = init_vqs(vdev->priv);
538 	if (ret)
539 		return ret;
540 
541 	fill_balloon(vb, towards_target(vb));
542 	update_balloon_size(vb);
543 	return 0;
544 }
545 #endif
546 
547 static unsigned int features[] = {
548 	VIRTIO_BALLOON_F_MUST_TELL_HOST,
549 	VIRTIO_BALLOON_F_STATS_VQ,
550 };
551 
552 static struct virtio_driver virtio_balloon_driver = {
553 	.feature_table = features,
554 	.feature_table_size = ARRAY_SIZE(features),
555 	.driver.name =	KBUILD_MODNAME,
556 	.driver.owner =	THIS_MODULE,
557 	.id_table =	id_table,
558 	.probe =	virtballoon_probe,
559 	.remove =	virtballoon_remove,
560 	.config_changed = virtballoon_changed,
561 #ifdef CONFIG_PM_SLEEP
562 	.freeze	=	virtballoon_freeze,
563 	.restore =	virtballoon_restore,
564 #endif
565 };
566 
567 module_virtio_driver(virtio_balloon_driver);
568 MODULE_DEVICE_TABLE(virtio, id_table);
569 MODULE_DESCRIPTION("Virtio balloon driver");
570 MODULE_LICENSE("GPL");
571