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/workqueue.h>
26 #include <linux/delay.h>
27 #include <linux/slab.h>
28 #include <linux/module.h>
29 #include <linux/balloon_compaction.h>
30 #include <linux/wait.h>
31 #include <linux/mm.h>
32 #include <linux/mount.h>
33 #include <linux/magic.h>
34 
35 /*
36  * Balloon device works in 4K page units.  So each page is pointed to by
37  * multiple balloon pages.  All memory counters in this driver are in balloon
38  * page units.
39  */
40 #define VIRTIO_BALLOON_PAGES_PER_PAGE (unsigned)(PAGE_SIZE >> VIRTIO_BALLOON_PFN_SHIFT)
41 #define VIRTIO_BALLOON_ARRAY_PFNS_MAX 256
42 #define VIRTBALLOON_OOM_NOTIFY_PRIORITY 80
43 
44 #ifdef CONFIG_BALLOON_COMPACTION
45 static struct vfsmount *balloon_mnt;
46 #endif
47 
48 struct virtio_balloon {
49 	struct virtio_device *vdev;
50 	struct virtqueue *inflate_vq, *deflate_vq, *stats_vq;
51 
52 	/* The balloon servicing is delegated to a freezable workqueue. */
53 	struct work_struct update_balloon_stats_work;
54 	struct work_struct update_balloon_size_work;
55 
56 	/* Prevent updating balloon when it is being canceled. */
57 	spinlock_t stop_update_lock;
58 	bool stop_update;
59 
60 	/* Waiting for host to ack the pages we released. */
61 	wait_queue_head_t acked;
62 
63 	/* Number of balloon pages we've told the Host we're not using. */
64 	unsigned int num_pages;
65 	/*
66 	 * The pages we've told the Host we're not using are enqueued
67 	 * at vb_dev_info->pages list.
68 	 * Each page on this list adds VIRTIO_BALLOON_PAGES_PER_PAGE
69 	 * to num_pages above.
70 	 */
71 	struct balloon_dev_info vb_dev_info;
72 
73 	/* Synchronize access/update to this struct virtio_balloon elements */
74 	struct mutex balloon_lock;
75 
76 	/* The array of pfns we tell the Host about. */
77 	unsigned int num_pfns;
78 	__virtio32 pfns[VIRTIO_BALLOON_ARRAY_PFNS_MAX];
79 
80 	/* Memory statistics */
81 	struct virtio_balloon_stat stats[VIRTIO_BALLOON_S_NR];
82 
83 	/* To register a shrinker to shrink memory upon memory pressure */
84 	struct shrinker shrinker;
85 };
86 
87 static struct virtio_device_id id_table[] = {
88 	{ VIRTIO_ID_BALLOON, VIRTIO_DEV_ANY_ID },
89 	{ 0 },
90 };
91 
page_to_balloon_pfn(struct page * page)92 static u32 page_to_balloon_pfn(struct page *page)
93 {
94 	unsigned long pfn = page_to_pfn(page);
95 
96 	BUILD_BUG_ON(PAGE_SHIFT < VIRTIO_BALLOON_PFN_SHIFT);
97 	/* Convert pfn from Linux page size to balloon page size. */
98 	return pfn * VIRTIO_BALLOON_PAGES_PER_PAGE;
99 }
100 
balloon_ack(struct virtqueue * vq)101 static void balloon_ack(struct virtqueue *vq)
102 {
103 	struct virtio_balloon *vb = vq->vdev->priv;
104 
105 	wake_up(&vb->acked);
106 }
107 
tell_host(struct virtio_balloon * vb,struct virtqueue * vq)108 static void tell_host(struct virtio_balloon *vb, struct virtqueue *vq)
109 {
110 	struct scatterlist sg;
111 	unsigned int len;
112 
113 	sg_init_one(&sg, vb->pfns, sizeof(vb->pfns[0]) * vb->num_pfns);
114 
115 	/* We should always be able to add one buffer to an empty queue. */
116 	virtqueue_add_outbuf(vq, &sg, 1, vb, GFP_KERNEL);
117 	virtqueue_kick(vq);
118 
119 	/* When host has read buffer, this completes via balloon_ack */
120 	wait_event(vb->acked, virtqueue_get_buf(vq, &len));
121 
122 }
123 
set_page_pfns(struct virtio_balloon * vb,__virtio32 pfns[],struct page * page)124 static void set_page_pfns(struct virtio_balloon *vb,
125 			  __virtio32 pfns[], struct page *page)
126 {
127 	unsigned int i;
128 
129 	BUILD_BUG_ON(VIRTIO_BALLOON_PAGES_PER_PAGE > VIRTIO_BALLOON_ARRAY_PFNS_MAX);
130 
131 	/*
132 	 * Set balloon pfns pointing at this page.
133 	 * Note that the first pfn points at start of the page.
134 	 */
135 	for (i = 0; i < VIRTIO_BALLOON_PAGES_PER_PAGE; i++)
136 		pfns[i] = cpu_to_virtio32(vb->vdev,
137 					  page_to_balloon_pfn(page) + i);
138 }
139 
fill_balloon(struct virtio_balloon * vb,size_t num)140 static unsigned fill_balloon(struct virtio_balloon *vb, size_t num)
141 {
142 	unsigned num_allocated_pages;
143 	unsigned num_pfns;
144 	struct page *page;
145 	LIST_HEAD(pages);
146 
147 	/* We can only do one array worth at a time. */
148 	num = min(num, ARRAY_SIZE(vb->pfns));
149 
150 	for (num_pfns = 0; num_pfns < num;
151 	     num_pfns += VIRTIO_BALLOON_PAGES_PER_PAGE) {
152 		struct page *page = balloon_page_alloc();
153 
154 		if (!page) {
155 			dev_info_ratelimited(&vb->vdev->dev,
156 					     "Out of puff! Can't get %u pages\n",
157 					     VIRTIO_BALLOON_PAGES_PER_PAGE);
158 			/* Sleep for at least 1/5 of a second before retry. */
159 			msleep(200);
160 			break;
161 		}
162 
163 		balloon_page_push(&pages, page);
164 	}
165 
166 	mutex_lock(&vb->balloon_lock);
167 
168 	vb->num_pfns = 0;
169 
170 	while ((page = balloon_page_pop(&pages))) {
171 		balloon_page_enqueue(&vb->vb_dev_info, page);
172 
173 		set_page_pfns(vb, vb->pfns + vb->num_pfns, page);
174 		vb->num_pages += VIRTIO_BALLOON_PAGES_PER_PAGE;
175 		if (!virtio_has_feature(vb->vdev,
176 					VIRTIO_BALLOON_F_DEFLATE_ON_OOM))
177 			adjust_managed_page_count(page, -1);
178 		vb->num_pfns += VIRTIO_BALLOON_PAGES_PER_PAGE;
179 	}
180 
181 	num_allocated_pages = vb->num_pfns;
182 	/* Did we get any? */
183 	if (vb->num_pfns != 0)
184 		tell_host(vb, vb->inflate_vq);
185 	mutex_unlock(&vb->balloon_lock);
186 
187 	return num_allocated_pages;
188 }
189 
release_pages_balloon(struct virtio_balloon * vb,struct list_head * pages)190 static void release_pages_balloon(struct virtio_balloon *vb,
191 				 struct list_head *pages)
192 {
193 	struct page *page, *next;
194 
195 	list_for_each_entry_safe(page, next, pages, lru) {
196 		if (!virtio_has_feature(vb->vdev,
197 					VIRTIO_BALLOON_F_DEFLATE_ON_OOM))
198 			adjust_managed_page_count(page, 1);
199 		list_del(&page->lru);
200 		put_page(page); /* balloon reference */
201 	}
202 }
203 
leak_balloon(struct virtio_balloon * vb,size_t num)204 static unsigned leak_balloon(struct virtio_balloon *vb, size_t num)
205 {
206 	unsigned num_freed_pages;
207 	struct page *page;
208 	struct balloon_dev_info *vb_dev_info = &vb->vb_dev_info;
209 	LIST_HEAD(pages);
210 
211 	/* We can only do one array worth at a time. */
212 	num = min(num, ARRAY_SIZE(vb->pfns));
213 
214 	mutex_lock(&vb->balloon_lock);
215 	/* We can't release more pages than taken */
216 	num = min(num, (size_t)vb->num_pages);
217 	for (vb->num_pfns = 0; vb->num_pfns < num;
218 	     vb->num_pfns += VIRTIO_BALLOON_PAGES_PER_PAGE) {
219 		page = balloon_page_dequeue(vb_dev_info);
220 		if (!page)
221 			break;
222 		set_page_pfns(vb, vb->pfns + vb->num_pfns, page);
223 		list_add(&page->lru, &pages);
224 		vb->num_pages -= VIRTIO_BALLOON_PAGES_PER_PAGE;
225 	}
226 
227 	num_freed_pages = vb->num_pfns;
228 	/*
229 	 * Note that if
230 	 * virtio_has_feature(vdev, VIRTIO_BALLOON_F_MUST_TELL_HOST);
231 	 * is true, we *have* to do it in this order
232 	 */
233 	if (vb->num_pfns != 0)
234 		tell_host(vb, vb->deflate_vq);
235 	release_pages_balloon(vb, &pages);
236 	mutex_unlock(&vb->balloon_lock);
237 	return num_freed_pages;
238 }
239 
update_stat(struct virtio_balloon * vb,int idx,u16 tag,u64 val)240 static inline void update_stat(struct virtio_balloon *vb, int idx,
241 			       u16 tag, u64 val)
242 {
243 	BUG_ON(idx >= VIRTIO_BALLOON_S_NR);
244 	vb->stats[idx].tag = cpu_to_virtio16(vb->vdev, tag);
245 	vb->stats[idx].val = cpu_to_virtio64(vb->vdev, val);
246 }
247 
248 #define pages_to_bytes(x) ((u64)(x) << PAGE_SHIFT)
249 
update_balloon_stats(struct virtio_balloon * vb)250 static unsigned int update_balloon_stats(struct virtio_balloon *vb)
251 {
252 	unsigned long events[NR_VM_EVENT_ITEMS];
253 	struct sysinfo i;
254 	unsigned int idx = 0;
255 	long available;
256 	unsigned long caches;
257 
258 	all_vm_events(events);
259 	si_meminfo(&i);
260 
261 	available = si_mem_available();
262 	caches = global_node_page_state(NR_FILE_PAGES);
263 
264 #ifdef CONFIG_VM_EVENT_COUNTERS
265 	update_stat(vb, idx++, VIRTIO_BALLOON_S_SWAP_IN,
266 				pages_to_bytes(events[PSWPIN]));
267 	update_stat(vb, idx++, VIRTIO_BALLOON_S_SWAP_OUT,
268 				pages_to_bytes(events[PSWPOUT]));
269 	update_stat(vb, idx++, VIRTIO_BALLOON_S_MAJFLT, events[PGMAJFAULT]);
270 	update_stat(vb, idx++, VIRTIO_BALLOON_S_MINFLT, events[PGFAULT]);
271 #ifdef CONFIG_HUGETLB_PAGE
272 	update_stat(vb, idx++, VIRTIO_BALLOON_S_HTLB_PGALLOC,
273 		    events[HTLB_BUDDY_PGALLOC]);
274 	update_stat(vb, idx++, VIRTIO_BALLOON_S_HTLB_PGFAIL,
275 		    events[HTLB_BUDDY_PGALLOC_FAIL]);
276 #endif
277 #endif
278 	update_stat(vb, idx++, VIRTIO_BALLOON_S_MEMFREE,
279 				pages_to_bytes(i.freeram));
280 	update_stat(vb, idx++, VIRTIO_BALLOON_S_MEMTOT,
281 				pages_to_bytes(i.totalram));
282 	update_stat(vb, idx++, VIRTIO_BALLOON_S_AVAIL,
283 				pages_to_bytes(available));
284 	update_stat(vb, idx++, VIRTIO_BALLOON_S_CACHES,
285 				pages_to_bytes(caches));
286 
287 	return idx;
288 }
289 
290 /*
291  * While most virtqueues communicate guest-initiated requests to the hypervisor,
292  * the stats queue operates in reverse.  The driver initializes the virtqueue
293  * with a single buffer.  From that point forward, all conversations consist of
294  * a hypervisor request (a call to this function) which directs us to refill
295  * the virtqueue with a fresh stats buffer.  Since stats collection can sleep,
296  * we delegate the job to a freezable workqueue that will do the actual work via
297  * stats_handle_request().
298  */
stats_request(struct virtqueue * vq)299 static void stats_request(struct virtqueue *vq)
300 {
301 	struct virtio_balloon *vb = vq->vdev->priv;
302 
303 	spin_lock(&vb->stop_update_lock);
304 	if (!vb->stop_update)
305 		queue_work(system_freezable_wq, &vb->update_balloon_stats_work);
306 	spin_unlock(&vb->stop_update_lock);
307 }
308 
stats_handle_request(struct virtio_balloon * vb)309 static void stats_handle_request(struct virtio_balloon *vb)
310 {
311 	struct virtqueue *vq;
312 	struct scatterlist sg;
313 	unsigned int len, num_stats;
314 
315 	num_stats = update_balloon_stats(vb);
316 
317 	vq = vb->stats_vq;
318 	if (!virtqueue_get_buf(vq, &len))
319 		return;
320 	sg_init_one(&sg, vb->stats, sizeof(vb->stats[0]) * num_stats);
321 	virtqueue_add_outbuf(vq, &sg, 1, vb, GFP_KERNEL);
322 	virtqueue_kick(vq);
323 }
324 
virtballoon_changed(struct virtio_device * vdev)325 static void virtballoon_changed(struct virtio_device *vdev)
326 {
327 	struct virtio_balloon *vb = vdev->priv;
328 	unsigned long flags;
329 
330 	spin_lock_irqsave(&vb->stop_update_lock, flags);
331 	if (!vb->stop_update)
332 		queue_work(system_freezable_wq, &vb->update_balloon_size_work);
333 	spin_unlock_irqrestore(&vb->stop_update_lock, flags);
334 }
335 
towards_target(struct virtio_balloon * vb)336 static inline s64 towards_target(struct virtio_balloon *vb)
337 {
338 	s64 target;
339 	u32 num_pages;
340 
341 	virtio_cread(vb->vdev, struct virtio_balloon_config, num_pages,
342 		     &num_pages);
343 
344 	/* Legacy balloon config space is LE, unlike all other devices. */
345 	if (!virtio_has_feature(vb->vdev, VIRTIO_F_VERSION_1))
346 		num_pages = le32_to_cpu((__force __le32)num_pages);
347 
348 	target = num_pages;
349 	return target - vb->num_pages;
350 }
351 
update_balloon_size(struct virtio_balloon * vb)352 static void update_balloon_size(struct virtio_balloon *vb)
353 {
354 	u32 actual = vb->num_pages;
355 
356 	/* Legacy balloon config space is LE, unlike all other devices. */
357 	if (!virtio_has_feature(vb->vdev, VIRTIO_F_VERSION_1))
358 		actual = (__force u32)cpu_to_le32(actual);
359 
360 	virtio_cwrite(vb->vdev, struct virtio_balloon_config, actual,
361 		      &actual);
362 }
363 
update_balloon_stats_func(struct work_struct * work)364 static void update_balloon_stats_func(struct work_struct *work)
365 {
366 	struct virtio_balloon *vb;
367 
368 	vb = container_of(work, struct virtio_balloon,
369 			  update_balloon_stats_work);
370 	stats_handle_request(vb);
371 }
372 
update_balloon_size_func(struct work_struct * work)373 static void update_balloon_size_func(struct work_struct *work)
374 {
375 	struct virtio_balloon *vb;
376 	s64 diff;
377 
378 	vb = container_of(work, struct virtio_balloon,
379 			  update_balloon_size_work);
380 	diff = towards_target(vb);
381 
382 	if (diff > 0)
383 		diff -= fill_balloon(vb, diff);
384 	else if (diff < 0)
385 		diff += leak_balloon(vb, -diff);
386 	update_balloon_size(vb);
387 
388 	if (diff)
389 		queue_work(system_freezable_wq, work);
390 }
391 
init_vqs(struct virtio_balloon * vb)392 static int init_vqs(struct virtio_balloon *vb)
393 {
394 	struct virtqueue *vqs[3];
395 	vq_callback_t *callbacks[] = { balloon_ack, balloon_ack, stats_request };
396 	static const char * const names[] = { "inflate", "deflate", "stats" };
397 	int err, nvqs;
398 
399 	/*
400 	 * We expect two virtqueues: inflate and deflate, and
401 	 * optionally stat.
402 	 */
403 	nvqs = virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_STATS_VQ) ? 3 : 2;
404 	err = virtio_find_vqs(vb->vdev, nvqs, vqs, callbacks, names, NULL);
405 	if (err)
406 		return err;
407 
408 	vb->inflate_vq = vqs[0];
409 	vb->deflate_vq = vqs[1];
410 	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_STATS_VQ)) {
411 		struct scatterlist sg;
412 		unsigned int num_stats;
413 		vb->stats_vq = vqs[2];
414 
415 		/*
416 		 * Prime this virtqueue with one buffer so the hypervisor can
417 		 * use it to signal us later (it can't be broken yet!).
418 		 */
419 		num_stats = update_balloon_stats(vb);
420 
421 		sg_init_one(&sg, vb->stats, sizeof(vb->stats[0]) * num_stats);
422 		err = virtqueue_add_outbuf(vb->stats_vq, &sg, 1, vb,
423 					   GFP_KERNEL);
424 		if (err) {
425 			dev_warn(&vb->vdev->dev, "%s: add stat_vq failed\n",
426 				 __func__);
427 			return err;
428 		}
429 		virtqueue_kick(vb->stats_vq);
430 	}
431 	return 0;
432 }
433 
434 #ifdef CONFIG_BALLOON_COMPACTION
435 /*
436  * virtballoon_migratepage - perform the balloon page migration on behalf of
437  *			     a compation thread.     (called under page lock)
438  * @vb_dev_info: the balloon device
439  * @newpage: page that will replace the isolated page after migration finishes.
440  * @page   : the isolated (old) page that is about to be migrated to newpage.
441  * @mode   : compaction mode -- not used for balloon page migration.
442  *
443  * After a ballooned page gets isolated by compaction procedures, this is the
444  * function that performs the page migration on behalf of a compaction thread
445  * The page migration for virtio balloon is done in a simple swap fashion which
446  * follows these two macro steps:
447  *  1) insert newpage into vb->pages list and update the host about it;
448  *  2) update the host about the old page removed from vb->pages list;
449  *
450  * This function preforms the balloon page migration task.
451  * Called through balloon_mapping->a_ops->migratepage
452  */
virtballoon_migratepage(struct balloon_dev_info * vb_dev_info,struct page * newpage,struct page * page,enum migrate_mode mode)453 static int virtballoon_migratepage(struct balloon_dev_info *vb_dev_info,
454 		struct page *newpage, struct page *page, enum migrate_mode mode)
455 {
456 	struct virtio_balloon *vb = container_of(vb_dev_info,
457 			struct virtio_balloon, vb_dev_info);
458 	unsigned long flags;
459 
460 	/*
461 	 * In order to avoid lock contention while migrating pages concurrently
462 	 * to leak_balloon() or fill_balloon() we just give up the balloon_lock
463 	 * this turn, as it is easier to retry the page migration later.
464 	 * This also prevents fill_balloon() getting stuck into a mutex
465 	 * recursion in the case it ends up triggering memory compaction
466 	 * while it is attempting to inflate the ballon.
467 	 */
468 	if (!mutex_trylock(&vb->balloon_lock))
469 		return -EAGAIN;
470 
471 	get_page(newpage); /* balloon reference */
472 
473 	/*
474 	  * When we migrate a page to a different zone and adjusted the
475 	  * managed page count when inflating, we have to fixup the count of
476 	  * both involved zones.
477 	  */
478 	if (!virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_DEFLATE_ON_OOM) &&
479 	    page_zone(page) != page_zone(newpage)) {
480 		adjust_managed_page_count(page, 1);
481 		adjust_managed_page_count(newpage, -1);
482 	}
483 
484 	/* balloon's page migration 1st step  -- inflate "newpage" */
485 	spin_lock_irqsave(&vb_dev_info->pages_lock, flags);
486 	balloon_page_insert(vb_dev_info, newpage);
487 	vb_dev_info->isolated_pages--;
488 	__count_vm_event(BALLOON_MIGRATE);
489 	spin_unlock_irqrestore(&vb_dev_info->pages_lock, flags);
490 	vb->num_pfns = VIRTIO_BALLOON_PAGES_PER_PAGE;
491 	set_page_pfns(vb, vb->pfns, newpage);
492 	tell_host(vb, vb->inflate_vq);
493 
494 	/* balloon's page migration 2nd step -- deflate "page" */
495 	spin_lock_irqsave(&vb_dev_info->pages_lock, flags);
496 	balloon_page_delete(page);
497 	spin_unlock_irqrestore(&vb_dev_info->pages_lock, flags);
498 	vb->num_pfns = VIRTIO_BALLOON_PAGES_PER_PAGE;
499 	set_page_pfns(vb, vb->pfns, page);
500 	tell_host(vb, vb->deflate_vq);
501 
502 	mutex_unlock(&vb->balloon_lock);
503 
504 	put_page(page); /* balloon reference */
505 
506 	return MIGRATEPAGE_SUCCESS;
507 }
508 
balloon_mount(struct file_system_type * fs_type,int flags,const char * dev_name,void * data)509 static struct dentry *balloon_mount(struct file_system_type *fs_type,
510 		int flags, const char *dev_name, void *data)
511 {
512 	static const struct dentry_operations ops = {
513 		.d_dname = simple_dname,
514 	};
515 
516 	return mount_pseudo(fs_type, "balloon-kvm:", NULL, &ops,
517 				BALLOON_KVM_MAGIC);
518 }
519 
520 static struct file_system_type balloon_fs = {
521 	.name           = "balloon-kvm",
522 	.mount          = balloon_mount,
523 	.kill_sb        = kill_anon_super,
524 };
525 
526 #endif /* CONFIG_BALLOON_COMPACTION */
527 
virtio_balloon_shrinker_scan(struct shrinker * shrinker,struct shrink_control * sc)528 static unsigned long virtio_balloon_shrinker_scan(struct shrinker *shrinker,
529 						  struct shrink_control *sc)
530 {
531 	unsigned long pages_to_free, pages_freed = 0;
532 	struct virtio_balloon *vb = container_of(shrinker,
533 					struct virtio_balloon, shrinker);
534 
535 	pages_to_free = sc->nr_to_scan * VIRTIO_BALLOON_PAGES_PER_PAGE;
536 
537 	/*
538 	 * One invocation of leak_balloon can deflate at most
539 	 * VIRTIO_BALLOON_ARRAY_PFNS_MAX balloon pages, so we call it
540 	 * multiple times to deflate pages till reaching pages_to_free.
541 	 */
542 	while (vb->num_pages && pages_to_free) {
543 		pages_to_free -= pages_freed;
544 		pages_freed += leak_balloon(vb, pages_to_free);
545 	}
546 	update_balloon_size(vb);
547 
548 	return pages_freed / VIRTIO_BALLOON_PAGES_PER_PAGE;
549 }
550 
virtio_balloon_shrinker_count(struct shrinker * shrinker,struct shrink_control * sc)551 static unsigned long virtio_balloon_shrinker_count(struct shrinker *shrinker,
552 						   struct shrink_control *sc)
553 {
554 	struct virtio_balloon *vb = container_of(shrinker,
555 					struct virtio_balloon, shrinker);
556 
557 	return vb->num_pages / VIRTIO_BALLOON_PAGES_PER_PAGE;
558 }
559 
virtio_balloon_unregister_shrinker(struct virtio_balloon * vb)560 static void virtio_balloon_unregister_shrinker(struct virtio_balloon *vb)
561 {
562 	unregister_shrinker(&vb->shrinker);
563 }
564 
virtio_balloon_register_shrinker(struct virtio_balloon * vb)565 static int virtio_balloon_register_shrinker(struct virtio_balloon *vb)
566 {
567 	vb->shrinker.scan_objects = virtio_balloon_shrinker_scan;
568 	vb->shrinker.count_objects = virtio_balloon_shrinker_count;
569 	vb->shrinker.seeks = DEFAULT_SEEKS;
570 
571 	return register_shrinker(&vb->shrinker);
572 }
573 
virtballoon_probe(struct virtio_device * vdev)574 static int virtballoon_probe(struct virtio_device *vdev)
575 {
576 	struct virtio_balloon *vb;
577 	int err;
578 
579 	if (!vdev->config->get) {
580 		dev_err(&vdev->dev, "%s failure: config access disabled\n",
581 			__func__);
582 		return -EINVAL;
583 	}
584 
585 	vdev->priv = vb = kzalloc(sizeof(*vb), GFP_KERNEL);
586 	if (!vb) {
587 		err = -ENOMEM;
588 		goto out;
589 	}
590 
591 	INIT_WORK(&vb->update_balloon_stats_work, update_balloon_stats_func);
592 	INIT_WORK(&vb->update_balloon_size_work, update_balloon_size_func);
593 	spin_lock_init(&vb->stop_update_lock);
594 	mutex_init(&vb->balloon_lock);
595 	init_waitqueue_head(&vb->acked);
596 	vb->vdev = vdev;
597 
598 	balloon_devinfo_init(&vb->vb_dev_info);
599 
600 	err = init_vqs(vb);
601 	if (err)
602 		goto out_free_vb;
603 
604 #ifdef CONFIG_BALLOON_COMPACTION
605 	balloon_mnt = kern_mount(&balloon_fs);
606 	if (IS_ERR(balloon_mnt)) {
607 		err = PTR_ERR(balloon_mnt);
608 		goto out_del_vqs;
609 	}
610 
611 	vb->vb_dev_info.migratepage = virtballoon_migratepage;
612 	vb->vb_dev_info.inode = alloc_anon_inode(balloon_mnt->mnt_sb);
613 	if (IS_ERR(vb->vb_dev_info.inode)) {
614 		err = PTR_ERR(vb->vb_dev_info.inode);
615 		kern_unmount(balloon_mnt);
616 		goto out_del_vqs;
617 	}
618 	vb->vb_dev_info.inode->i_mapping->a_ops = &balloon_aops;
619 #endif
620 	/*
621 	 * We continue to use VIRTIO_BALLOON_F_DEFLATE_ON_OOM to decide if a
622 	 * shrinker needs to be registered to relieve memory pressure.
623 	 */
624 	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_DEFLATE_ON_OOM)) {
625 		err = virtio_balloon_register_shrinker(vb);
626 		if (err)
627 			goto out_del_vqs;
628 	}
629 	virtio_device_ready(vdev);
630 
631 	if (towards_target(vb))
632 		virtballoon_changed(vdev);
633 	return 0;
634 
635 out_del_vqs:
636 	vdev->config->del_vqs(vdev);
637 out_free_vb:
638 	kfree(vb);
639 out:
640 	return err;
641 }
642 
remove_common(struct virtio_balloon * vb)643 static void remove_common(struct virtio_balloon *vb)
644 {
645 	/* There might be pages left in the balloon: free them. */
646 	while (vb->num_pages)
647 		leak_balloon(vb, vb->num_pages);
648 	update_balloon_size(vb);
649 
650 	/* Now we reset the device so we can clean up the queues. */
651 	vb->vdev->config->reset(vb->vdev);
652 
653 	vb->vdev->config->del_vqs(vb->vdev);
654 }
655 
virtballoon_remove(struct virtio_device * vdev)656 static void virtballoon_remove(struct virtio_device *vdev)
657 {
658 	struct virtio_balloon *vb = vdev->priv;
659 
660 	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_DEFLATE_ON_OOM))
661 		virtio_balloon_unregister_shrinker(vb);
662 	spin_lock_irq(&vb->stop_update_lock);
663 	vb->stop_update = true;
664 	spin_unlock_irq(&vb->stop_update_lock);
665 	cancel_work_sync(&vb->update_balloon_size_work);
666 	cancel_work_sync(&vb->update_balloon_stats_work);
667 
668 	remove_common(vb);
669 #ifdef CONFIG_BALLOON_COMPACTION
670 	if (vb->vb_dev_info.inode)
671 		iput(vb->vb_dev_info.inode);
672 
673 	kern_unmount(balloon_mnt);
674 #endif
675 	kfree(vb);
676 }
677 
678 #ifdef CONFIG_PM_SLEEP
virtballoon_freeze(struct virtio_device * vdev)679 static int virtballoon_freeze(struct virtio_device *vdev)
680 {
681 	struct virtio_balloon *vb = vdev->priv;
682 
683 	/*
684 	 * The workqueue is already frozen by the PM core before this
685 	 * function is called.
686 	 */
687 	remove_common(vb);
688 	return 0;
689 }
690 
virtballoon_restore(struct virtio_device * vdev)691 static int virtballoon_restore(struct virtio_device *vdev)
692 {
693 	struct virtio_balloon *vb = vdev->priv;
694 	int ret;
695 
696 	ret = init_vqs(vdev->priv);
697 	if (ret)
698 		return ret;
699 
700 	virtio_device_ready(vdev);
701 
702 	if (towards_target(vb))
703 		virtballoon_changed(vdev);
704 	update_balloon_size(vb);
705 	return 0;
706 }
707 #endif
708 
virtballoon_validate(struct virtio_device * vdev)709 static int virtballoon_validate(struct virtio_device *vdev)
710 {
711 	__virtio_clear_bit(vdev, VIRTIO_F_IOMMU_PLATFORM);
712 	return 0;
713 }
714 
715 static unsigned int features[] = {
716 	VIRTIO_BALLOON_F_MUST_TELL_HOST,
717 	VIRTIO_BALLOON_F_STATS_VQ,
718 	VIRTIO_BALLOON_F_DEFLATE_ON_OOM,
719 };
720 
721 static struct virtio_driver virtio_balloon_driver = {
722 	.feature_table = features,
723 	.feature_table_size = ARRAY_SIZE(features),
724 	.driver.name =	KBUILD_MODNAME,
725 	.driver.owner =	THIS_MODULE,
726 	.id_table =	id_table,
727 	.validate =	virtballoon_validate,
728 	.probe =	virtballoon_probe,
729 	.remove =	virtballoon_remove,
730 	.config_changed = virtballoon_changed,
731 #ifdef CONFIG_PM_SLEEP
732 	.freeze	=	virtballoon_freeze,
733 	.restore =	virtballoon_restore,
734 #endif
735 };
736 
737 module_virtio_driver(virtio_balloon_driver);
738 MODULE_DEVICE_TABLE(virtio, id_table);
739 MODULE_DESCRIPTION("Virtio balloon driver");
740 MODULE_LICENSE("GPL");
741