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