xref: /linux/drivers/virtio/virtio_balloon.c (revision 7f063b2f17eaba2a35e251aa53627f2a70d536e2)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Virtio balloon implementation, inspired by Dor Laor and Marcelo
4  * Tosatti's implementations.
5  *
6  *  Copyright 2008 Rusty Russell IBM Corporation
7  */
8 
9 #include <linux/virtio.h>
10 #include <uapi/linux/virtio_ring.h>
11 #include <linux/virtio_balloon.h>
12 #include <linux/swap.h>
13 #include <linux/workqueue.h>
14 #include <linux/delay.h>
15 #include <linux/slab.h>
16 #include <linux/module.h>
17 #include <linux/balloon.h>
18 #include <linux/oom.h>
19 #include <linux/wait.h>
20 #include <linux/mm.h>
21 #include <linux/page_reporting.h>
22 
23 /*
24  * Balloon device works in 4K page units.  So each page is pointed to by
25  * multiple balloon pages.  All memory counters in this driver are in balloon
26  * page units.
27  */
28 #define VIRTIO_BALLOON_PAGES_PER_PAGE (unsigned int)(PAGE_SIZE >> VIRTIO_BALLOON_PFN_SHIFT)
29 #define VIRTIO_BALLOON_ARRAY_PFNS_MAX 256
30 /* Maximum number of (4k) pages to deflate on OOM notifications. */
31 #define VIRTIO_BALLOON_OOM_NR_PAGES 256
32 #define VIRTIO_BALLOON_OOM_NOTIFY_PRIORITY 80
33 
34 #define VIRTIO_BALLOON_FREE_PAGE_ALLOC_FLAG (__GFP_NORETRY | __GFP_NOWARN | \
35 					     __GFP_NOMEMALLOC)
36 /* The order of free page blocks to report to host */
37 #define VIRTIO_BALLOON_HINT_BLOCK_ORDER MAX_PAGE_ORDER
38 /* The size of a free page block in bytes */
39 #define VIRTIO_BALLOON_HINT_BLOCK_BYTES \
40 	(1 << (VIRTIO_BALLOON_HINT_BLOCK_ORDER + PAGE_SHIFT))
41 #define VIRTIO_BALLOON_HINT_BLOCK_PAGES (1 << VIRTIO_BALLOON_HINT_BLOCK_ORDER)
42 
43 enum virtio_balloon_vq {
44 	VIRTIO_BALLOON_VQ_INFLATE,
45 	VIRTIO_BALLOON_VQ_DEFLATE,
46 	VIRTIO_BALLOON_VQ_STATS,
47 	VIRTIO_BALLOON_VQ_FREE_PAGE,
48 	VIRTIO_BALLOON_VQ_REPORTING,
49 	VIRTIO_BALLOON_VQ_MAX
50 };
51 
52 enum virtio_balloon_config_read {
53 	VIRTIO_BALLOON_CONFIG_READ_CMD_ID = 0,
54 };
55 
56 struct virtio_balloon {
57 	struct virtio_device *vdev;
58 	struct virtqueue *inflate_vq, *deflate_vq, *stats_vq, *free_page_vq;
59 
60 	/* Balloon's own wq for cpu-intensive work items */
61 	struct workqueue_struct *balloon_wq;
62 	/* The free page reporting work item submitted to the balloon wq */
63 	struct work_struct report_free_page_work;
64 
65 	/* The balloon servicing is delegated to a freezable workqueue. */
66 	struct work_struct update_balloon_stats_work;
67 	struct work_struct update_balloon_size_work;
68 
69 	/* Prevent updating balloon when it is being canceled. */
70 	spinlock_t stop_update_lock;
71 	bool stop_update;
72 	/* Bitmap to indicate if reading the related config fields are needed */
73 	unsigned long config_read_bitmap;
74 
75 	/* The list of allocated free pages, waiting to be given back to mm */
76 	struct list_head free_page_list;
77 	spinlock_t free_page_list_lock;
78 	/* The number of free page blocks on the above list */
79 	unsigned long num_free_page_blocks;
80 	/*
81 	 * The cmd id received from host.
82 	 * Read it via virtio_balloon_cmd_id_received to get the latest value
83 	 * sent from host.
84 	 */
85 	u32 cmd_id_received_cache;
86 	/* The cmd id that is actively in use */
87 	__virtio32 cmd_id_active;
88 	/* Buffer to store the stop sign */
89 	__virtio32 cmd_id_stop;
90 
91 	/* Waiting for host to ack the pages we released. */
92 	wait_queue_head_t acked;
93 
94 	/* Number of balloon pages we've told the Host we're not using. */
95 	unsigned int num_pages;
96 	/*
97 	 * The pages we've told the Host we're not using are enqueued
98 	 * at vb_dev_info->pages list.
99 	 * Each page on this list adds VIRTIO_BALLOON_PAGES_PER_PAGE
100 	 * to num_pages above.
101 	 */
102 	struct balloon_dev_info vb_dev_info;
103 
104 	/* Synchronize access/update to this struct virtio_balloon elements */
105 	struct mutex balloon_lock;
106 
107 	/* The array of pfns we tell the Host about. */
108 	unsigned int num_pfns;
109 	__virtio32 pfns[VIRTIO_BALLOON_ARRAY_PFNS_MAX];
110 
111 	/* Memory statistics */
112 	struct virtio_balloon_stat stats[VIRTIO_BALLOON_S_NR];
113 
114 	/* Shrinker to return free pages - VIRTIO_BALLOON_F_FREE_PAGE_HINT */
115 	struct shrinker *shrinker;
116 
117 	/* OOM notifier to deflate on OOM - VIRTIO_BALLOON_F_DEFLATE_ON_OOM */
118 	struct notifier_block oom_nb;
119 
120 	/* Free page reporting device */
121 	struct virtqueue *reporting_vq;
122 	struct page_reporting_dev_info pr_dev_info;
123 
124 	/* State for keeping the wakeup_source active while adjusting the balloon */
125 	spinlock_t wakeup_lock;
126 	bool processing_wakeup_event;
127 	u32 wakeup_signal_mask;
128 };
129 
130 #define VIRTIO_BALLOON_WAKEUP_SIGNAL_ADJUST (1 << 0)
131 #define VIRTIO_BALLOON_WAKEUP_SIGNAL_STATS (1 << 1)
132 
133 static const struct virtio_device_id id_table[] = {
134 	{ VIRTIO_ID_BALLOON, VIRTIO_DEV_ANY_ID },
135 	{ 0 },
136 };
137 
page_to_balloon_pfn(struct page * page)138 static u32 page_to_balloon_pfn(struct page *page)
139 {
140 	unsigned long pfn = page_to_pfn(page);
141 
142 	BUILD_BUG_ON(PAGE_SHIFT < VIRTIO_BALLOON_PFN_SHIFT);
143 	/* Convert pfn from Linux page size to balloon page size. */
144 	return pfn * VIRTIO_BALLOON_PAGES_PER_PAGE;
145 }
146 
start_wakeup_event(struct virtio_balloon * vb,u32 mask)147 static void start_wakeup_event(struct virtio_balloon *vb, u32 mask)
148 {
149 	unsigned long flags;
150 
151 	spin_lock_irqsave(&vb->wakeup_lock, flags);
152 	vb->wakeup_signal_mask |= mask;
153 	if (!vb->processing_wakeup_event) {
154 		vb->processing_wakeup_event = true;
155 		pm_stay_awake(&vb->vdev->dev);
156 	}
157 	spin_unlock_irqrestore(&vb->wakeup_lock, flags);
158 }
159 
process_wakeup_event(struct virtio_balloon * vb,u32 mask)160 static void process_wakeup_event(struct virtio_balloon *vb, u32 mask)
161 {
162 	spin_lock_irq(&vb->wakeup_lock);
163 	vb->wakeup_signal_mask &= ~mask;
164 	spin_unlock_irq(&vb->wakeup_lock);
165 }
166 
finish_wakeup_event(struct virtio_balloon * vb)167 static void finish_wakeup_event(struct virtio_balloon *vb)
168 {
169 	spin_lock_irq(&vb->wakeup_lock);
170 	if (!vb->wakeup_signal_mask && vb->processing_wakeup_event) {
171 		vb->processing_wakeup_event = false;
172 		pm_relax(&vb->vdev->dev);
173 	}
174 	spin_unlock_irq(&vb->wakeup_lock);
175 }
176 
balloon_ack(struct virtqueue * vq)177 static void balloon_ack(struct virtqueue *vq)
178 {
179 	struct virtio_balloon *vb = vq->vdev->priv;
180 
181 	wake_up(&vb->acked);
182 }
183 
tell_host(struct virtio_balloon * vb,struct virtqueue * vq)184 static void tell_host(struct virtio_balloon *vb, struct virtqueue *vq)
185 {
186 	struct scatterlist sg;
187 	unsigned int len;
188 	int err;
189 
190 	sg_init_one(&sg, vb->pfns, sizeof(vb->pfns[0]) * vb->num_pfns);
191 
192 	/* We should always be able to add one buffer to an empty queue. */
193 	err = virtqueue_add_outbuf(vq, &sg, 1, vb, GFP_KERNEL);
194 	if (WARN_ON_ONCE(err))
195 		return;
196 	virtqueue_kick(vq);
197 
198 	/* When host has read buffer, this completes via balloon_ack */
199 	wait_event(vb->acked, virtqueue_get_buf(vq, &len));
200 }
201 
virtballoon_free_page_report(struct page_reporting_dev_info * pr_dev_info,struct scatterlist * sg,unsigned int nents)202 static int virtballoon_free_page_report(struct page_reporting_dev_info *pr_dev_info,
203 				   struct scatterlist *sg, unsigned int nents)
204 {
205 	struct virtio_balloon *vb =
206 		container_of(pr_dev_info, struct virtio_balloon, pr_dev_info);
207 	struct virtqueue *vq = vb->reporting_vq;
208 	unsigned int unused, err;
209 
210 	/* We should always be able to add these buffers to an empty queue. */
211 	err = virtqueue_add_inbuf(vq, sg, nents, vb, GFP_NOWAIT);
212 
213 	/*
214 	 * In the extremely unlikely case that something has occurred and we
215 	 * are able to trigger an error we will simply display a warning
216 	 * and exit without actually processing the pages.
217 	 */
218 	if (WARN_ON_ONCE(err))
219 		return err;
220 
221 	virtqueue_kick(vq);
222 
223 	/* When host has read buffer, this completes via balloon_ack */
224 	wait_event(vb->acked, virtqueue_get_buf(vq, &unused));
225 
226 	return 0;
227 }
228 
set_page_pfns(struct virtio_balloon * vb,__virtio32 pfns[],struct page * page)229 static void set_page_pfns(struct virtio_balloon *vb,
230 			  __virtio32 pfns[], struct page *page)
231 {
232 	unsigned int i;
233 
234 	BUILD_BUG_ON(VIRTIO_BALLOON_PAGES_PER_PAGE > VIRTIO_BALLOON_ARRAY_PFNS_MAX);
235 
236 	/*
237 	 * Set balloon pfns pointing at this page.
238 	 * Note that the first pfn points at start of the page.
239 	 */
240 	for (i = 0; i < VIRTIO_BALLOON_PAGES_PER_PAGE; i++)
241 		pfns[i] = cpu_to_virtio32(vb->vdev,
242 					  page_to_balloon_pfn(page) + i);
243 }
244 
fill_balloon(struct virtio_balloon * vb,size_t num)245 static unsigned int fill_balloon(struct virtio_balloon *vb, size_t num)
246 {
247 	unsigned int num_allocated_pages;
248 	struct page *page, *next;
249 	unsigned int num_pfns;
250 	LIST_HEAD(pages);
251 
252 	/* We can only do one array worth at a time. */
253 	num = min(num, ARRAY_SIZE(vb->pfns));
254 
255 	for (num_pfns = 0; num_pfns < num;
256 	     num_pfns += VIRTIO_BALLOON_PAGES_PER_PAGE) {
257 		page = balloon_page_alloc();
258 
259 		if (!page) {
260 			dev_info_ratelimited(&vb->vdev->dev,
261 					     "Out of puff! Can't get %u pages\n",
262 					     VIRTIO_BALLOON_PAGES_PER_PAGE);
263 			/* Sleep for at least 1/5 of a second before retry. */
264 			msleep(200);
265 			break;
266 		}
267 
268 		list_add(&page->lru, &pages);
269 	}
270 
271 	mutex_lock(&vb->balloon_lock);
272 
273 	vb->num_pfns = 0;
274 
275 	list_for_each_entry_safe(page, next, &pages, lru) {
276 		list_del(&page->lru);
277 		balloon_page_enqueue(&vb->vb_dev_info, page);
278 
279 		set_page_pfns(vb, vb->pfns + vb->num_pfns, page);
280 		vb->num_pages += VIRTIO_BALLOON_PAGES_PER_PAGE;
281 		vb->num_pfns += VIRTIO_BALLOON_PAGES_PER_PAGE;
282 	}
283 
284 	num_allocated_pages = vb->num_pfns;
285 	/* Did we get any? */
286 	if (vb->num_pfns != 0)
287 		tell_host(vb, vb->inflate_vq);
288 	mutex_unlock(&vb->balloon_lock);
289 
290 	return num_allocated_pages;
291 }
292 
release_pages_balloon(struct virtio_balloon * vb,struct list_head * pages)293 static void release_pages_balloon(struct virtio_balloon *vb,
294 				 struct list_head *pages)
295 {
296 	struct page *page, *next;
297 
298 	list_for_each_entry_safe(page, next, pages, lru) {
299 		list_del(&page->lru);
300 		put_page(page); /* balloon reference */
301 	}
302 }
303 
leak_balloon(struct virtio_balloon * vb,size_t num)304 static unsigned int leak_balloon(struct virtio_balloon *vb, size_t num)
305 {
306 	unsigned int num_freed_pages;
307 	struct page *page;
308 	struct balloon_dev_info *vb_dev_info = &vb->vb_dev_info;
309 	LIST_HEAD(pages);
310 
311 	/* We can only do one array worth at a time. */
312 	num = min(num, ARRAY_SIZE(vb->pfns));
313 
314 	mutex_lock(&vb->balloon_lock);
315 	/* We can't release more pages than taken */
316 	num = min(num, (size_t)vb->num_pages);
317 	for (vb->num_pfns = 0; vb->num_pfns < num;
318 	     vb->num_pfns += VIRTIO_BALLOON_PAGES_PER_PAGE) {
319 		page = balloon_page_dequeue(vb_dev_info);
320 		if (!page)
321 			break;
322 		set_page_pfns(vb, vb->pfns + vb->num_pfns, page);
323 		list_add(&page->lru, &pages);
324 		vb->num_pages -= VIRTIO_BALLOON_PAGES_PER_PAGE;
325 	}
326 
327 	num_freed_pages = vb->num_pfns;
328 	/*
329 	 * Note that if
330 	 * virtio_has_feature(vdev, VIRTIO_BALLOON_F_MUST_TELL_HOST);
331 	 * is true, we *have* to do it in this order
332 	 */
333 	if (vb->num_pfns != 0)
334 		tell_host(vb, vb->deflate_vq);
335 	release_pages_balloon(vb, &pages);
336 	mutex_unlock(&vb->balloon_lock);
337 	return num_freed_pages;
338 }
339 
update_stat(struct virtio_balloon * vb,int idx,u16 tag,u64 val)340 static inline void update_stat(struct virtio_balloon *vb, int idx,
341 			       u16 tag, u64 val)
342 {
343 	BUG_ON(idx >= VIRTIO_BALLOON_S_NR);
344 	vb->stats[idx].tag = cpu_to_virtio16(vb->vdev, tag);
345 	vb->stats[idx].val = cpu_to_virtio64(vb->vdev, val);
346 }
347 
348 #define pages_to_bytes(x) ((u64)(x) << PAGE_SHIFT)
349 
350 #ifdef CONFIG_VM_EVENT_COUNTERS
351 /* Return the number of entries filled by vm events */
update_balloon_vm_stats(struct virtio_balloon * vb)352 static inline unsigned int update_balloon_vm_stats(struct virtio_balloon *vb)
353 {
354 	unsigned long events[NR_VM_EVENT_ITEMS];
355 	unsigned int idx = 0;
356 	unsigned int zid;
357 	unsigned long stall = 0;
358 
359 	all_vm_events(events);
360 	update_stat(vb, idx++, VIRTIO_BALLOON_S_SWAP_IN,
361 		    pages_to_bytes(events[PSWPIN]));
362 	update_stat(vb, idx++, VIRTIO_BALLOON_S_SWAP_OUT,
363 		    pages_to_bytes(events[PSWPOUT]));
364 	update_stat(vb, idx++, VIRTIO_BALLOON_S_MAJFLT, events[PGMAJFAULT]);
365 	update_stat(vb, idx++, VIRTIO_BALLOON_S_MINFLT, events[PGFAULT]);
366 	update_stat(vb, idx++, VIRTIO_BALLOON_S_OOM_KILL, events[OOM_KILL]);
367 
368 	/* sum all the stall events */
369 	for (zid = 0; zid < MAX_NR_ZONES; zid++)
370 		stall += events[ALLOCSTALL_NORMAL - ZONE_NORMAL + zid];
371 
372 	update_stat(vb, idx++, VIRTIO_BALLOON_S_ALLOC_STALL, stall);
373 
374 	update_stat(vb, idx++, VIRTIO_BALLOON_S_ASYNC_SCAN,
375 		    pages_to_bytes(global_node_page_state(PGSCAN_KSWAPD)));
376 	update_stat(vb, idx++, VIRTIO_BALLOON_S_DIRECT_SCAN,
377 		    pages_to_bytes(global_node_page_state(PGSCAN_DIRECT)));
378 	update_stat(vb, idx++, VIRTIO_BALLOON_S_ASYNC_RECLAIM,
379 		    pages_to_bytes(global_node_page_state(PGSTEAL_KSWAPD)));
380 	update_stat(vb, idx++, VIRTIO_BALLOON_S_DIRECT_RECLAIM,
381 		    pages_to_bytes(global_node_page_state(PGSTEAL_DIRECT)));
382 
383 #ifdef CONFIG_HUGETLB_PAGE
384 	update_stat(vb, idx++, VIRTIO_BALLOON_S_HTLB_PGALLOC,
385 		    events[HTLB_BUDDY_PGALLOC]);
386 	update_stat(vb, idx++, VIRTIO_BALLOON_S_HTLB_PGFAIL,
387 		    events[HTLB_BUDDY_PGALLOC_FAIL]);
388 #endif /* CONFIG_HUGETLB_PAGE */
389 
390 	return idx;
391 }
392 #else /* CONFIG_VM_EVENT_COUNTERS */
update_balloon_vm_stats(struct virtio_balloon * vb)393 static inline unsigned int update_balloon_vm_stats(struct virtio_balloon *vb)
394 {
395 	return 0;
396 }
397 #endif /* CONFIG_VM_EVENT_COUNTERS */
398 
update_balloon_stats(struct virtio_balloon * vb)399 static unsigned int update_balloon_stats(struct virtio_balloon *vb)
400 {
401 	struct sysinfo i;
402 	unsigned int idx;
403 	long available;
404 	unsigned long caches;
405 
406 	idx = update_balloon_vm_stats(vb);
407 
408 	si_meminfo(&i);
409 	available = si_mem_available();
410 	caches = global_node_page_state(NR_FILE_PAGES);
411 	update_stat(vb, idx++, VIRTIO_BALLOON_S_MEMFREE,
412 				pages_to_bytes(i.freeram));
413 	update_stat(vb, idx++, VIRTIO_BALLOON_S_MEMTOT,
414 				pages_to_bytes(i.totalram));
415 	update_stat(vb, idx++, VIRTIO_BALLOON_S_AVAIL,
416 				pages_to_bytes(available));
417 	update_stat(vb, idx++, VIRTIO_BALLOON_S_CACHES,
418 				pages_to_bytes(caches));
419 
420 	return idx;
421 }
422 
423 /*
424  * While most virtqueues communicate guest-initiated requests to the hypervisor,
425  * the stats queue operates in reverse.  The driver initializes the virtqueue
426  * with a single buffer.  From that point forward, all conversations consist of
427  * a hypervisor request (a call to this function) which directs us to refill
428  * the virtqueue with a fresh stats buffer.  Since stats collection can sleep,
429  * we delegate the job to a freezable workqueue that will do the actual work via
430  * stats_handle_request().
431  */
stats_request(struct virtqueue * vq)432 static void stats_request(struct virtqueue *vq)
433 {
434 	struct virtio_balloon *vb = vq->vdev->priv;
435 
436 	spin_lock(&vb->stop_update_lock);
437 	if (!vb->stop_update) {
438 		start_wakeup_event(vb, VIRTIO_BALLOON_WAKEUP_SIGNAL_STATS);
439 		queue_work(system_freezable_wq, &vb->update_balloon_stats_work);
440 	}
441 	spin_unlock(&vb->stop_update_lock);
442 }
443 
stats_handle_request(struct virtio_balloon * vb)444 static void stats_handle_request(struct virtio_balloon *vb)
445 {
446 	struct virtqueue *vq;
447 	struct scatterlist sg;
448 	unsigned int len, num_stats;
449 	int err;
450 
451 	num_stats = update_balloon_stats(vb);
452 
453 	vq = vb->stats_vq;
454 	if (!virtqueue_get_buf(vq, &len))
455 		return;
456 	sg_init_one(&sg, vb->stats, sizeof(vb->stats[0]) * num_stats);
457 	err = virtqueue_add_outbuf(vq, &sg, 1, vb, GFP_KERNEL);
458 	if (WARN_ON_ONCE(err))
459 		return;
460 	virtqueue_kick(vq);
461 }
462 
towards_target(struct virtio_balloon * vb)463 static inline s64 towards_target(struct virtio_balloon *vb)
464 {
465 	s64 target;
466 	u32 num_pages;
467 
468 	/* Legacy balloon config space is LE, unlike all other devices. */
469 	virtio_cread_le(vb->vdev, struct virtio_balloon_config, num_pages,
470 			&num_pages);
471 
472 	/*
473 	 * Aligned up to guest page size to avoid inflating and deflating
474 	 * balloon endlessly.
475 	 */
476 	target = ALIGN(num_pages, VIRTIO_BALLOON_PAGES_PER_PAGE);
477 	return target - vb->num_pages;
478 }
479 
480 /* Gives back @num_to_return blocks of free pages to mm. */
return_free_pages_to_mm(struct virtio_balloon * vb,unsigned long num_to_return)481 static unsigned long return_free_pages_to_mm(struct virtio_balloon *vb,
482 					     unsigned long num_to_return)
483 {
484 	unsigned long num_returned = 0;
485 	struct page *page, *next;
486 
487 	if (unlikely(!num_to_return))
488 		return 0;
489 
490 	spin_lock_irq(&vb->free_page_list_lock);
491 
492 	list_for_each_entry_safe(page, next, &vb->free_page_list, lru) {
493 		list_del(&page->lru);
494 		__free_pages(page, VIRTIO_BALLOON_HINT_BLOCK_ORDER);
495 		if (++num_returned == num_to_return)
496 			break;
497 	}
498 	vb->num_free_page_blocks -= num_returned;
499 	spin_unlock_irq(&vb->free_page_list_lock);
500 
501 	return num_returned;
502 }
503 
virtio_balloon_queue_free_page_work(struct virtio_balloon * vb)504 static void virtio_balloon_queue_free_page_work(struct virtio_balloon *vb)
505 {
506 	if (!virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT))
507 		return;
508 
509 	/* No need to queue the work if the bit was already set. */
510 	if (test_and_set_bit(VIRTIO_BALLOON_CONFIG_READ_CMD_ID,
511 			     &vb->config_read_bitmap))
512 		return;
513 
514 	queue_work(vb->balloon_wq, &vb->report_free_page_work);
515 }
516 
start_update_balloon_size(struct virtio_balloon * vb)517 static void start_update_balloon_size(struct virtio_balloon *vb)
518 {
519 	start_wakeup_event(vb, VIRTIO_BALLOON_WAKEUP_SIGNAL_ADJUST);
520 	queue_work(system_freezable_wq, &vb->update_balloon_size_work);
521 }
522 
virtballoon_changed(struct virtio_device * vdev)523 static void virtballoon_changed(struct virtio_device *vdev)
524 {
525 	struct virtio_balloon *vb = vdev->priv;
526 	unsigned long flags;
527 
528 	spin_lock_irqsave(&vb->stop_update_lock, flags);
529 	if (!vb->stop_update) {
530 		start_update_balloon_size(vb);
531 		virtio_balloon_queue_free_page_work(vb);
532 	}
533 	spin_unlock_irqrestore(&vb->stop_update_lock, flags);
534 }
535 
update_balloon_size(struct virtio_balloon * vb)536 static void update_balloon_size(struct virtio_balloon *vb)
537 {
538 	u32 actual = vb->num_pages;
539 
540 	/* Legacy balloon config space is LE, unlike all other devices. */
541 	virtio_cwrite_le(vb->vdev, struct virtio_balloon_config, actual,
542 			 &actual);
543 }
544 
update_balloon_stats_func(struct work_struct * work)545 static void update_balloon_stats_func(struct work_struct *work)
546 {
547 	struct virtio_balloon *vb;
548 
549 	vb = container_of(work, struct virtio_balloon,
550 			  update_balloon_stats_work);
551 
552 	process_wakeup_event(vb, VIRTIO_BALLOON_WAKEUP_SIGNAL_STATS);
553 	stats_handle_request(vb);
554 	finish_wakeup_event(vb);
555 }
556 
update_balloon_size_func(struct work_struct * work)557 static void update_balloon_size_func(struct work_struct *work)
558 {
559 	struct virtio_balloon *vb;
560 	s64 diff;
561 
562 	vb = container_of(work, struct virtio_balloon,
563 			  update_balloon_size_work);
564 
565 	process_wakeup_event(vb, VIRTIO_BALLOON_WAKEUP_SIGNAL_ADJUST);
566 
567 	diff = towards_target(vb);
568 
569 	if (diff) {
570 		if (diff > 0)
571 			diff -= fill_balloon(vb, diff);
572 		else
573 			diff += leak_balloon(vb, -diff);
574 		update_balloon_size(vb);
575 	}
576 
577 	if (diff)
578 		queue_work(system_freezable_wq, work);
579 	else
580 		finish_wakeup_event(vb);
581 }
582 
init_vqs(struct virtio_balloon * vb)583 static int init_vqs(struct virtio_balloon *vb)
584 {
585 	struct virtqueue_info vqs_info[VIRTIO_BALLOON_VQ_MAX] = {};
586 	struct virtqueue *vqs[VIRTIO_BALLOON_VQ_MAX];
587 	int err;
588 
589 	/*
590 	 * Inflateq and deflateq are used unconditionally. The names[]
591 	 * will be NULL if the related feature is not enabled, which will
592 	 * cause no allocation for the corresponding virtqueue in find_vqs.
593 	 */
594 	vqs_info[VIRTIO_BALLOON_VQ_INFLATE].callback = balloon_ack;
595 	vqs_info[VIRTIO_BALLOON_VQ_INFLATE].name = "inflate";
596 	vqs_info[VIRTIO_BALLOON_VQ_DEFLATE].callback = balloon_ack;
597 	vqs_info[VIRTIO_BALLOON_VQ_DEFLATE].name = "deflate";
598 
599 	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_STATS_VQ)) {
600 		vqs_info[VIRTIO_BALLOON_VQ_STATS].name = "stats";
601 		vqs_info[VIRTIO_BALLOON_VQ_STATS].callback = stats_request;
602 	}
603 
604 	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT))
605 		vqs_info[VIRTIO_BALLOON_VQ_FREE_PAGE].name = "free_page_vq";
606 
607 	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_REPORTING)) {
608 		vqs_info[VIRTIO_BALLOON_VQ_REPORTING].name = "reporting_vq";
609 		vqs_info[VIRTIO_BALLOON_VQ_REPORTING].callback = balloon_ack;
610 	}
611 
612 	err = virtio_find_vqs(vb->vdev, VIRTIO_BALLOON_VQ_MAX, vqs,
613 			      vqs_info, NULL);
614 	if (err)
615 		return err;
616 
617 	vb->inflate_vq = vqs[VIRTIO_BALLOON_VQ_INFLATE];
618 	vb->deflate_vq = vqs[VIRTIO_BALLOON_VQ_DEFLATE];
619 	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_STATS_VQ)) {
620 		struct scatterlist sg;
621 		unsigned int num_stats;
622 		vb->stats_vq = vqs[VIRTIO_BALLOON_VQ_STATS];
623 
624 		/*
625 		 * Prime this virtqueue with one buffer so the hypervisor can
626 		 * use it to signal us later (it can't be broken yet!).
627 		 */
628 		num_stats = update_balloon_stats(vb);
629 
630 		sg_init_one(&sg, vb->stats, sizeof(vb->stats[0]) * num_stats);
631 		err = virtqueue_add_outbuf(vb->stats_vq, &sg, 1, vb,
632 					   GFP_KERNEL);
633 		if (err) {
634 			dev_warn(&vb->vdev->dev, "%s: add stat_vq failed\n",
635 				 __func__);
636 			return err;
637 		}
638 		virtqueue_kick(vb->stats_vq);
639 	}
640 
641 	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT))
642 		vb->free_page_vq = vqs[VIRTIO_BALLOON_VQ_FREE_PAGE];
643 
644 	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_REPORTING))
645 		vb->reporting_vq = vqs[VIRTIO_BALLOON_VQ_REPORTING];
646 
647 	return 0;
648 }
649 
virtio_balloon_cmd_id_received(struct virtio_balloon * vb)650 static u32 virtio_balloon_cmd_id_received(struct virtio_balloon *vb)
651 {
652 	if (test_and_clear_bit(VIRTIO_BALLOON_CONFIG_READ_CMD_ID,
653 			       &vb->config_read_bitmap)) {
654 		/* Legacy balloon config space is LE, unlike all other devices. */
655 		virtio_cread_le(vb->vdev, struct virtio_balloon_config,
656 				free_page_hint_cmd_id,
657 				&vb->cmd_id_received_cache);
658 	}
659 
660 	return vb->cmd_id_received_cache;
661 }
662 
send_cmd_id_start(struct virtio_balloon * vb)663 static int send_cmd_id_start(struct virtio_balloon *vb)
664 {
665 	struct scatterlist sg;
666 	struct virtqueue *vq = vb->free_page_vq;
667 	int err, unused;
668 
669 	/* Detach all the used buffers from the vq */
670 	while (virtqueue_get_buf(vq, &unused))
671 		;
672 
673 	vb->cmd_id_active = cpu_to_virtio32(vb->vdev,
674 					virtio_balloon_cmd_id_received(vb));
675 	sg_init_one(&sg, &vb->cmd_id_active, sizeof(vb->cmd_id_active));
676 	err = virtqueue_add_outbuf(vq, &sg, 1, &vb->cmd_id_active, GFP_KERNEL);
677 	if (!err)
678 		virtqueue_kick(vq);
679 	return err;
680 }
681 
send_cmd_id_stop(struct virtio_balloon * vb)682 static int send_cmd_id_stop(struct virtio_balloon *vb)
683 {
684 	struct scatterlist sg;
685 	struct virtqueue *vq = vb->free_page_vq;
686 	int err, unused;
687 
688 	/* Detach all the used buffers from the vq */
689 	while (virtqueue_get_buf(vq, &unused))
690 		;
691 
692 	sg_init_one(&sg, &vb->cmd_id_stop, sizeof(vb->cmd_id_stop));
693 	err = virtqueue_add_outbuf(vq, &sg, 1, &vb->cmd_id_stop, GFP_KERNEL);
694 	if (!err)
695 		virtqueue_kick(vq);
696 	return err;
697 }
698 
get_free_page_and_send(struct virtio_balloon * vb)699 static int get_free_page_and_send(struct virtio_balloon *vb)
700 {
701 	struct virtqueue *vq = vb->free_page_vq;
702 	struct page *page;
703 	struct scatterlist sg;
704 	int err, unused;
705 	void *p;
706 
707 	/* Detach all the used buffers from the vq */
708 	while (virtqueue_get_buf(vq, &unused))
709 		;
710 
711 	page = alloc_pages(VIRTIO_BALLOON_FREE_PAGE_ALLOC_FLAG,
712 			   VIRTIO_BALLOON_HINT_BLOCK_ORDER);
713 	/*
714 	 * When the allocation returns NULL, it indicates that we have got all
715 	 * the possible free pages, so return -EINTR to stop.
716 	 */
717 	if (!page)
718 		return -EINTR;
719 
720 	p = page_address(page);
721 	sg_init_one(&sg, p, VIRTIO_BALLOON_HINT_BLOCK_BYTES);
722 	/* There is always 1 entry reserved for the cmd id to use. */
723 	if (vq->num_free > 1) {
724 		err = virtqueue_add_inbuf(vq, &sg, 1, p, GFP_KERNEL);
725 		if (unlikely(err)) {
726 			__free_pages(page, VIRTIO_BALLOON_HINT_BLOCK_ORDER);
727 			return err;
728 		}
729 		virtqueue_kick(vq);
730 		spin_lock_irq(&vb->free_page_list_lock);
731 		list_add(&page->lru, &vb->free_page_list);
732 		vb->num_free_page_blocks++;
733 		spin_unlock_irq(&vb->free_page_list_lock);
734 	} else {
735 		/*
736 		 * The vq has no available entry to add this page block, so
737 		 * just free it.
738 		 */
739 		__free_pages(page, VIRTIO_BALLOON_HINT_BLOCK_ORDER);
740 	}
741 
742 	return 0;
743 }
744 
send_free_pages(struct virtio_balloon * vb)745 static int send_free_pages(struct virtio_balloon *vb)
746 {
747 	int err;
748 	u32 cmd_id_active;
749 
750 	while (1) {
751 		/*
752 		 * If a stop id or a new cmd id was just received from host,
753 		 * stop the reporting.
754 		 */
755 		cmd_id_active = virtio32_to_cpu(vb->vdev, vb->cmd_id_active);
756 		if (unlikely(cmd_id_active !=
757 			     virtio_balloon_cmd_id_received(vb)))
758 			break;
759 
760 		/*
761 		 * The free page blocks are allocated and sent to host one by
762 		 * one.
763 		 */
764 		err = get_free_page_and_send(vb);
765 		if (err == -EINTR)
766 			break;
767 		else if (unlikely(err))
768 			return err;
769 	}
770 
771 	return 0;
772 }
773 
virtio_balloon_report_free_page(struct virtio_balloon * vb)774 static void virtio_balloon_report_free_page(struct virtio_balloon *vb)
775 {
776 	int err;
777 	struct device *dev = &vb->vdev->dev;
778 
779 	/* Start by sending the received cmd id to host with an outbuf. */
780 	err = send_cmd_id_start(vb);
781 	if (unlikely(err))
782 		dev_err(dev, "Failed to send a start id, err = %d\n", err);
783 
784 	err = send_free_pages(vb);
785 	if (unlikely(err))
786 		dev_err(dev, "Failed to send a free page, err = %d\n", err);
787 
788 	/* End by sending a stop id to host with an outbuf. */
789 	err = send_cmd_id_stop(vb);
790 	if (unlikely(err))
791 		dev_err(dev, "Failed to send a stop id, err = %d\n", err);
792 }
793 
report_free_page_func(struct work_struct * work)794 static void report_free_page_func(struct work_struct *work)
795 {
796 	struct virtio_balloon *vb = container_of(work, struct virtio_balloon,
797 						 report_free_page_work);
798 	u32 cmd_id_received;
799 
800 	cmd_id_received = virtio_balloon_cmd_id_received(vb);
801 	if (cmd_id_received == VIRTIO_BALLOON_CMD_ID_DONE) {
802 		/* Pass ULONG_MAX to give back all the free pages */
803 		return_free_pages_to_mm(vb, ULONG_MAX);
804 	} else if (cmd_id_received != VIRTIO_BALLOON_CMD_ID_STOP &&
805 		   cmd_id_received !=
806 		   virtio32_to_cpu(vb->vdev, vb->cmd_id_active)) {
807 		virtio_balloon_report_free_page(vb);
808 	}
809 }
810 
811 #ifdef CONFIG_BALLOON_MIGRATION
812 /*
813  * virtballoon_migratepage - perform the balloon page migration on behalf of
814  *			     a compaction thread.     (called under page lock)
815  * @vb_dev_info: the balloon device
816  * @newpage: page that will replace the isolated page after migration finishes.
817  * @page   : the isolated (old) page that is about to be migrated to newpage.
818  * @mode   : compaction mode -- not used for balloon page migration.
819  *
820  * After a ballooned page gets isolated by compaction procedures, this is the
821  * function that performs the page migration on behalf of a compaction thread
822  * The page migration for virtio balloon is done in a simple swap fashion which
823  * follows these two macro steps:
824  *  1) insert newpage into vb->pages list and update the host about it;
825  *  2) update the host about the old page removed from vb->pages list;
826  *
827  * This function preforms the balloon page migration task.
828  * Called through movable_operations->migrate_page
829  */
virtballoon_migratepage(struct balloon_dev_info * vb_dev_info,struct page * newpage,struct page * page,enum migrate_mode mode)830 static int virtballoon_migratepage(struct balloon_dev_info *vb_dev_info,
831 		struct page *newpage, struct page *page, enum migrate_mode mode)
832 {
833 	struct virtio_balloon *vb = container_of(vb_dev_info,
834 			struct virtio_balloon, vb_dev_info);
835 
836 	/*
837 	 * In order to avoid lock contention while migrating pages concurrently
838 	 * to leak_balloon() or fill_balloon() we just give up the balloon_lock
839 	 * this turn, as it is easier to retry the page migration later.
840 	 * This also prevents fill_balloon() getting stuck into a mutex
841 	 * recursion in the case it ends up triggering memory compaction
842 	 * while it is attempting to inflate the ballon.
843 	 */
844 	if (!mutex_trylock(&vb->balloon_lock))
845 		return -EAGAIN;
846 
847 	/* balloon's page migration 1st step  -- inflate "newpage" */
848 	vb->num_pfns = VIRTIO_BALLOON_PAGES_PER_PAGE;
849 	set_page_pfns(vb, vb->pfns, newpage);
850 	tell_host(vb, vb->inflate_vq);
851 
852 	/* balloon's page migration 2nd step -- deflate "page" */
853 	vb->num_pfns = VIRTIO_BALLOON_PAGES_PER_PAGE;
854 	set_page_pfns(vb, vb->pfns, page);
855 	tell_host(vb, vb->deflate_vq);
856 
857 	mutex_unlock(&vb->balloon_lock);
858 	return 0;
859 }
860 #endif /* CONFIG_BALLOON_MIGRATION */
861 
shrink_free_pages(struct virtio_balloon * vb,unsigned long pages_to_free)862 static unsigned long shrink_free_pages(struct virtio_balloon *vb,
863 				       unsigned long pages_to_free)
864 {
865 	unsigned long blocks_to_free, blocks_freed;
866 
867 	pages_to_free = round_up(pages_to_free,
868 				 VIRTIO_BALLOON_HINT_BLOCK_PAGES);
869 	blocks_to_free = pages_to_free / VIRTIO_BALLOON_HINT_BLOCK_PAGES;
870 	blocks_freed = return_free_pages_to_mm(vb, blocks_to_free);
871 
872 	return blocks_freed * VIRTIO_BALLOON_HINT_BLOCK_PAGES;
873 }
874 
virtio_balloon_shrinker_scan(struct shrinker * shrinker,struct shrink_control * sc)875 static unsigned long virtio_balloon_shrinker_scan(struct shrinker *shrinker,
876 						  struct shrink_control *sc)
877 {
878 	struct virtio_balloon *vb = shrinker->private_data;
879 
880 	return shrink_free_pages(vb, sc->nr_to_scan);
881 }
882 
virtio_balloon_shrinker_count(struct shrinker * shrinker,struct shrink_control * sc)883 static unsigned long virtio_balloon_shrinker_count(struct shrinker *shrinker,
884 						   struct shrink_control *sc)
885 {
886 	struct virtio_balloon *vb = shrinker->private_data;
887 
888 	return vb->num_free_page_blocks * VIRTIO_BALLOON_HINT_BLOCK_PAGES;
889 }
890 
virtio_balloon_oom_notify(struct notifier_block * nb,unsigned long dummy,void * parm)891 static int virtio_balloon_oom_notify(struct notifier_block *nb,
892 				     unsigned long dummy, void *parm)
893 {
894 	struct virtio_balloon *vb = container_of(nb,
895 						 struct virtio_balloon, oom_nb);
896 	unsigned long *freed = parm;
897 
898 	*freed += leak_balloon(vb, VIRTIO_BALLOON_OOM_NR_PAGES) /
899 		  VIRTIO_BALLOON_PAGES_PER_PAGE;
900 	update_balloon_size(vb);
901 
902 	return NOTIFY_OK;
903 }
904 
virtio_balloon_unregister_shrinker(struct virtio_balloon * vb)905 static void virtio_balloon_unregister_shrinker(struct virtio_balloon *vb)
906 {
907 	shrinker_free(vb->shrinker);
908 }
909 
virtio_balloon_register_shrinker(struct virtio_balloon * vb)910 static int virtio_balloon_register_shrinker(struct virtio_balloon *vb)
911 {
912 	vb->shrinker = shrinker_alloc(0, "virtio-balloon");
913 	if (!vb->shrinker)
914 		return -ENOMEM;
915 
916 	vb->shrinker->scan_objects = virtio_balloon_shrinker_scan;
917 	vb->shrinker->count_objects = virtio_balloon_shrinker_count;
918 	vb->shrinker->private_data = vb;
919 
920 	shrinker_register(vb->shrinker);
921 
922 	return 0;
923 }
924 
virtballoon_probe(struct virtio_device * vdev)925 static int virtballoon_probe(struct virtio_device *vdev)
926 {
927 	struct virtio_balloon *vb;
928 	int err;
929 
930 	if (!vdev->config->get) {
931 		dev_err(&vdev->dev, "%s failure: config access disabled\n",
932 			__func__);
933 		return -EINVAL;
934 	}
935 
936 	vdev->priv = vb = kzalloc_obj(*vb);
937 	if (!vb) {
938 		err = -ENOMEM;
939 		goto out;
940 	}
941 
942 	INIT_WORK(&vb->update_balloon_stats_work, update_balloon_stats_func);
943 	INIT_WORK(&vb->update_balloon_size_work, update_balloon_size_func);
944 	spin_lock_init(&vb->stop_update_lock);
945 	mutex_init(&vb->balloon_lock);
946 	init_waitqueue_head(&vb->acked);
947 	vb->vdev = vdev;
948 
949 	balloon_devinfo_init(&vb->vb_dev_info);
950 
951 	err = init_vqs(vb);
952 	if (err)
953 		goto out_free_vb;
954 
955 	if (!virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_DEFLATE_ON_OOM))
956 		vb->vb_dev_info.adjust_managed_page_count = true;
957 #ifdef CONFIG_BALLOON_MIGRATION
958 	vb->vb_dev_info.migratepage = virtballoon_migratepage;
959 #endif
960 	if (virtio_has_feature(vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT)) {
961 		/*
962 		 * There is always one entry reserved for cmd id, so the ring
963 		 * size needs to be at least two to report free page hints.
964 		 */
965 		if (virtqueue_get_vring_size(vb->free_page_vq) < 2) {
966 			err = -ENOSPC;
967 			goto out_del_vqs;
968 		}
969 		vb->balloon_wq = alloc_workqueue("balloon-wq",
970 					WQ_FREEZABLE | WQ_CPU_INTENSIVE | WQ_PERCPU,
971 					0);
972 		if (!vb->balloon_wq) {
973 			err = -ENOMEM;
974 			goto out_del_vqs;
975 		}
976 		INIT_WORK(&vb->report_free_page_work, report_free_page_func);
977 		vb->cmd_id_received_cache = VIRTIO_BALLOON_CMD_ID_STOP;
978 		vb->cmd_id_active = cpu_to_virtio32(vb->vdev,
979 						  VIRTIO_BALLOON_CMD_ID_STOP);
980 		vb->cmd_id_stop = cpu_to_virtio32(vb->vdev,
981 						  VIRTIO_BALLOON_CMD_ID_STOP);
982 		spin_lock_init(&vb->free_page_list_lock);
983 		INIT_LIST_HEAD(&vb->free_page_list);
984 		/*
985 		 * We're allowed to reuse any free pages, even if they are
986 		 * still to be processed by the host.
987 		 */
988 		err = virtio_balloon_register_shrinker(vb);
989 		if (err)
990 			goto out_del_balloon_wq;
991 	}
992 
993 	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_DEFLATE_ON_OOM)) {
994 		vb->oom_nb.notifier_call = virtio_balloon_oom_notify;
995 		vb->oom_nb.priority = VIRTIO_BALLOON_OOM_NOTIFY_PRIORITY;
996 		err = register_oom_notifier(&vb->oom_nb);
997 		if (err < 0)
998 			goto out_unregister_shrinker;
999 	}
1000 
1001 	if (virtio_has_feature(vdev, VIRTIO_BALLOON_F_PAGE_POISON)) {
1002 		/* Start with poison val of 0 representing general init */
1003 		__u32 poison_val = 0;
1004 
1005 		/*
1006 		 * Let the hypervisor know that we are expecting a
1007 		 * specific value to be written back in balloon pages.
1008 		 *
1009 		 * If the PAGE_POISON value was larger than a byte we would
1010 		 * need to byte swap poison_val here to guarantee it is
1011 		 * little-endian. However for now it is a single byte so we
1012 		 * can pass it as-is.
1013 		 */
1014 		if (!want_init_on_free())
1015 			memset(&poison_val, PAGE_POISON, sizeof(poison_val));
1016 
1017 		virtio_cwrite_le(vb->vdev, struct virtio_balloon_config,
1018 				 poison_val, &poison_val);
1019 	}
1020 
1021 	vb->pr_dev_info.report = virtballoon_free_page_report;
1022 	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_REPORTING)) {
1023 		unsigned int capacity;
1024 
1025 		capacity = virtqueue_get_vring_size(vb->reporting_vq);
1026 
1027 		vb->pr_dev_info.order = PAGE_REPORTING_ORDER_UNSPECIFIED;
1028 
1029 		/*
1030 		 * The default page reporting order is @pageblock_order, which
1031 		 * corresponds to 512MB in size on ARM64 when 64KB base page
1032 		 * size is used. The page reporting won't be triggered if the
1033 		 * freeing page can't come up with a free area like that huge.
1034 		 * So we specify the page reporting order to 5, corresponding
1035 		 * to 2MB. It helps to avoid THP splitting if 4KB base page
1036 		 * size is used by host.
1037 		 *
1038 		 * Ideally, the page reporting order is selected based on the
1039 		 * host's base page size. However, it needs more work to report
1040 		 * that value. The hard-coded order would be fine currently.
1041 		 */
1042 #if defined(CONFIG_ARM64) && defined(CONFIG_ARM64_64K_PAGES)
1043 		vb->pr_dev_info.order = 5;
1044 #endif
1045 
1046 		vb->pr_dev_info.capacity = capacity;
1047 		err = page_reporting_register(&vb->pr_dev_info);
1048 		if (err)
1049 			goto out_unregister_oom;
1050 	}
1051 
1052 	spin_lock_init(&vb->wakeup_lock);
1053 
1054 	/*
1055 	 * The virtio balloon itself can't wake up the device, but it is
1056 	 * responsible for processing wakeup events passed up from the transport
1057 	 * layer. Wakeup sources don't support nesting/chaining calls, so we use
1058 	 * our own wakeup source to ensure wakeup events are properly handled
1059 	 * without trampling on the transport layer's wakeup source.
1060 	 */
1061 	device_set_wakeup_capable(&vb->vdev->dev, true);
1062 
1063 	virtio_device_ready(vdev);
1064 
1065 	if (towards_target(vb))
1066 		virtballoon_changed(vdev);
1067 	return 0;
1068 
1069 out_unregister_oom:
1070 	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_DEFLATE_ON_OOM))
1071 		unregister_oom_notifier(&vb->oom_nb);
1072 out_unregister_shrinker:
1073 	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT))
1074 		virtio_balloon_unregister_shrinker(vb);
1075 out_del_balloon_wq:
1076 	if (virtio_has_feature(vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT))
1077 		destroy_workqueue(vb->balloon_wq);
1078 out_del_vqs:
1079 	vdev->config->del_vqs(vdev);
1080 out_free_vb:
1081 	mutex_destroy(&vb->balloon_lock);
1082 	kfree(vb);
1083 out:
1084 	return err;
1085 }
1086 
remove_common(struct virtio_balloon * vb)1087 static void remove_common(struct virtio_balloon *vb)
1088 {
1089 	/* There might be pages left in the balloon: free them. */
1090 	while (vb->num_pages)
1091 		leak_balloon(vb, vb->num_pages);
1092 	update_balloon_size(vb);
1093 
1094 	/* There might be free pages that are being reported: release them. */
1095 	if (virtio_has_feature(vb->vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT))
1096 		return_free_pages_to_mm(vb, ULONG_MAX);
1097 
1098 	/* Now we reset the device so we can clean up the queues. */
1099 	virtio_reset_device(vb->vdev);
1100 
1101 	vb->vdev->config->del_vqs(vb->vdev);
1102 }
1103 
1104 /*
1105  * Stop all asynchronous balloon work. The device must still be alive so that
1106  * in-flight requests can drain via the host before it is reset or freed.
1107  */
virtballoon_quiesce(struct virtio_balloon * vb)1108 static void virtballoon_quiesce(struct virtio_balloon *vb)
1109 {
1110 	struct virtio_device *vdev = vb->vdev;
1111 
1112 	if (virtio_has_feature(vdev, VIRTIO_BALLOON_F_REPORTING))
1113 		page_reporting_unregister(&vb->pr_dev_info);
1114 	if (virtio_has_feature(vdev, VIRTIO_BALLOON_F_DEFLATE_ON_OOM))
1115 		unregister_oom_notifier(&vb->oom_nb);
1116 	if (virtio_has_feature(vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT))
1117 		virtio_balloon_unregister_shrinker(vb);
1118 
1119 	spin_lock_irq(&vb->stop_update_lock);
1120 	vb->stop_update = true;
1121 	spin_unlock_irq(&vb->stop_update_lock);
1122 	cancel_work_sync(&vb->update_balloon_size_work);
1123 	cancel_work_sync(&vb->update_balloon_stats_work);
1124 
1125 	if (virtio_has_feature(vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT))
1126 		cancel_work_sync(&vb->report_free_page_work);
1127 }
1128 
virtballoon_remove(struct virtio_device * vdev)1129 static void virtballoon_remove(struct virtio_device *vdev)
1130 {
1131 	struct virtio_balloon *vb = vdev->priv;
1132 
1133 	virtballoon_quiesce(vb);
1134 
1135 	if (virtio_has_feature(vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT))
1136 		destroy_workqueue(vb->balloon_wq);
1137 
1138 	remove_common(vb);
1139 	mutex_destroy(&vb->balloon_lock);
1140 	kfree(vb);
1141 }
1142 
virtballoon_shutdown(struct virtio_device * vdev)1143 static void virtballoon_shutdown(struct virtio_device *vdev)
1144 {
1145 	virtballoon_quiesce(vdev->priv);
1146 	virtio_device_shutdown(vdev);
1147 }
1148 
1149 #ifdef CONFIG_PM_SLEEP
virtballoon_freeze(struct virtio_device * vdev)1150 static int virtballoon_freeze(struct virtio_device *vdev)
1151 {
1152 	struct virtio_balloon *vb = vdev->priv;
1153 
1154 	/*
1155 	 * The workqueue is already frozen by the PM core before this
1156 	 * function is called.
1157 	 */
1158 	remove_common(vb);
1159 	return 0;
1160 }
1161 
virtballoon_restore(struct virtio_device * vdev)1162 static int virtballoon_restore(struct virtio_device *vdev)
1163 {
1164 	struct virtio_balloon *vb = vdev->priv;
1165 	int ret;
1166 
1167 	ret = init_vqs(vdev->priv);
1168 	if (ret)
1169 		return ret;
1170 
1171 	virtio_device_ready(vdev);
1172 
1173 	if (towards_target(vb))
1174 		virtballoon_changed(vdev);
1175 	update_balloon_size(vb);
1176 	return 0;
1177 }
1178 #endif
1179 
virtballoon_validate(struct virtio_device * vdev)1180 static int virtballoon_validate(struct virtio_device *vdev)
1181 {
1182 	/*
1183 	 * Inform the hypervisor that our pages are poisoned or
1184 	 * initialized. If we cannot do that then we should disable
1185 	 * page reporting as it could potentially change the contents
1186 	 * of our free pages.
1187 	 */
1188 	if (!want_init_on_free() && !page_poisoning_enabled_static())
1189 		__virtio_clear_bit(vdev, VIRTIO_BALLOON_F_PAGE_POISON);
1190 	else if (!virtio_has_feature(vdev, VIRTIO_BALLOON_F_PAGE_POISON))
1191 		__virtio_clear_bit(vdev, VIRTIO_BALLOON_F_REPORTING);
1192 
1193 	/*
1194 	 * Disable indirect descriptors to avoid memory allocation in
1195 	 * virtqueue_add during page reporting.
1196 	 */
1197 	__virtio_clear_bit(vdev, VIRTIO_RING_F_INDIRECT_DESC);
1198 	__virtio_clear_bit(vdev, VIRTIO_F_ACCESS_PLATFORM);
1199 	return 0;
1200 }
1201 
1202 static unsigned int features[] = {
1203 	VIRTIO_BALLOON_F_MUST_TELL_HOST,
1204 	VIRTIO_BALLOON_F_STATS_VQ,
1205 	VIRTIO_BALLOON_F_DEFLATE_ON_OOM,
1206 	VIRTIO_BALLOON_F_FREE_PAGE_HINT,
1207 	VIRTIO_BALLOON_F_PAGE_POISON,
1208 	VIRTIO_BALLOON_F_REPORTING,
1209 };
1210 
1211 static struct virtio_driver virtio_balloon_driver = {
1212 	.feature_table = features,
1213 	.feature_table_size = ARRAY_SIZE(features),
1214 	.driver.name =	KBUILD_MODNAME,
1215 	.id_table =	id_table,
1216 	.validate =	virtballoon_validate,
1217 	.probe =	virtballoon_probe,
1218 	.remove =	virtballoon_remove,
1219 	.shutdown =	virtballoon_shutdown,
1220 	.config_changed = virtballoon_changed,
1221 #ifdef CONFIG_PM_SLEEP
1222 	.freeze	=	virtballoon_freeze,
1223 	.restore =	virtballoon_restore,
1224 #endif
1225 };
1226 
1227 module_virtio_driver(virtio_balloon_driver);
1228 MODULE_DEVICE_TABLE(virtio, id_table);
1229 MODULE_DESCRIPTION("Virtio balloon driver");
1230 MODULE_LICENSE("GPL");
1231