vmw_balloon.c 29.7 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0
D
Dmitry Torokhov 已提交
2 3 4
/*
 * VMware Balloon driver.
 *
5
 * Copyright (C) 2000-2018, VMware, Inc. All Rights Reserved.
D
Dmitry Torokhov 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * This is VMware physical memory management driver for Linux. The driver
 * acts like a "balloon" that can be inflated to reclaim physical pages by
 * reserving them in the guest and invalidating them in the monitor,
 * freeing up the underlying machine pages so they can be allocated to
 * other guests.  The balloon can also be deflated to allow the guest to
 * use more physical memory. Higher level policies can control the sizes
 * of balloons in VMs in order to manage physical memory resources.
 */

//#define DEBUG
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt

#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/mm.h>
22
#include <linux/vmalloc.h>
D
Dmitry Torokhov 已提交
23 24 25 26 27
#include <linux/sched.h>
#include <linux/module.h>
#include <linux/workqueue.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
28 29
#include <linux/vmw_vmci_defs.h>
#include <linux/vmw_vmci_api.h>
30
#include <asm/hypervisor.h>
D
Dmitry Torokhov 已提交
31 32 33

MODULE_AUTHOR("VMware, Inc.");
MODULE_DESCRIPTION("VMware Memory Control (Balloon) Driver");
34
MODULE_VERSION("1.5.0.0-k");
D
Dmitry Torokhov 已提交
35 36 37 38 39
MODULE_ALIAS("dmi:*:svnVMware*:*");
MODULE_ALIAS("vmware_vmmemctl");
MODULE_LICENSE("GPL");

/*
40 41 42
 * Use __GFP_HIGHMEM to allow pages from HIGHMEM zone. We don't allow wait
 * (__GFP_RECLAIM) for huge page allocations. Use __GFP_NOWARN, to suppress page
 * allocation failure warnings. Disallow access to emergency low-memory pools.
D
Dmitry Torokhov 已提交
43
 */
44 45
#define VMW_HUGE_PAGE_ALLOC_FLAGS	(__GFP_HIGHMEM|__GFP_NOWARN|	\
					 __GFP_NOMEMALLOC)
D
Dmitry Torokhov 已提交
46 47

/*
48 49 50
 * Use __GFP_HIGHMEM to allow pages from HIGHMEM zone. We allow lightweight
 * reclamation (__GFP_NORETRY). Use __GFP_NOWARN, to suppress page allocation
 * failure warnings. Disallow access to emergency low-memory pools.
D
Dmitry Torokhov 已提交
51
 */
52 53
#define VMW_PAGE_ALLOC_FLAGS		(__GFP_HIGHMEM|__GFP_NOWARN|	\
					 __GFP_NOMEMALLOC|__GFP_NORETRY)
D
Dmitry Torokhov 已提交
54

55 56
/* Maximum number of refused pages we accumulate during inflation cycle */
#define VMW_BALLOON_MAX_REFUSED		16
D
Dmitry Torokhov 已提交
57 58 59 60 61 62 63 64

/*
 * Hypervisor communication port definitions.
 */
#define VMW_BALLOON_HV_PORT		0x5670
#define VMW_BALLOON_HV_MAGIC		0x456c6d6f
#define VMW_BALLOON_GUEST_ID		1	/* Linux */

65 66 67 68
enum vmwballoon_capabilities {
	/*
	 * Bit 0 is reserved and not associated to any capability.
	 */
69 70 71 72
	VMW_BALLOON_BASIC_CMDS			= (1 << 1),
	VMW_BALLOON_BATCHED_CMDS		= (1 << 2),
	VMW_BALLOON_BATCHED_2M_CMDS		= (1 << 3),
	VMW_BALLOON_SIGNALLED_WAKEUP_CMD	= (1 << 4),
73 74
};

75
#define VMW_BALLOON_CAPABILITIES	(VMW_BALLOON_BASIC_CMDS \
76
					| VMW_BALLOON_BATCHED_CMDS \
77 78
					| VMW_BALLOON_BATCHED_2M_CMDS \
					| VMW_BALLOON_SIGNALLED_WAKEUP_CMD)
79

80
#define VMW_BALLOON_2M_ORDER		(PMD_SHIFT - PAGE_SHIFT)
81
#define VMW_BALLOON_NUM_PAGE_SIZES	(2)
82

83 84 85 86 87 88 89 90 91
/*
 * Backdoor commands availability:
 *
 * START, GET_TARGET and GUEST_ID are always available,
 *
 * VMW_BALLOON_BASIC_CMDS:
 *	LOCK and UNLOCK commands,
 * VMW_BALLOON_BATCHED_CMDS:
 *	BATCHED_LOCK and BATCHED_UNLOCK commands.
92
 * VMW BALLOON_BATCHED_2M_CMDS:
93 94 95
 *	BATCHED_2M_LOCK and BATCHED_2M_UNLOCK commands,
 * VMW VMW_BALLOON_SIGNALLED_WAKEUP_CMD:
 *	VMW_BALLOON_CMD_VMCI_DOORBELL_SET command.
96
 */
97 98 99 100 101 102 103 104 105
#define VMW_BALLOON_CMD_START			0
#define VMW_BALLOON_CMD_GET_TARGET		1
#define VMW_BALLOON_CMD_LOCK			2
#define VMW_BALLOON_CMD_UNLOCK			3
#define VMW_BALLOON_CMD_GUEST_ID		4
#define VMW_BALLOON_CMD_BATCHED_LOCK		6
#define VMW_BALLOON_CMD_BATCHED_UNLOCK		7
#define VMW_BALLOON_CMD_BATCHED_2M_LOCK		8
#define VMW_BALLOON_CMD_BATCHED_2M_UNLOCK	9
106
#define VMW_BALLOON_CMD_VMCI_DOORBELL_SET	10
107

108
#define VMW_BALLOON_CMD_NUM			11
D
Dmitry Torokhov 已提交
109 110

/* error codes */
111 112 113 114 115 116 117 118 119 120 121 122 123
#define VMW_BALLOON_SUCCESS		        0
#define VMW_BALLOON_FAILURE		        -1
#define VMW_BALLOON_ERROR_CMD_INVALID	        1
#define VMW_BALLOON_ERROR_PPN_INVALID	        2
#define VMW_BALLOON_ERROR_PPN_LOCKED	        3
#define VMW_BALLOON_ERROR_PPN_UNLOCKED	        4
#define VMW_BALLOON_ERROR_PPN_PINNED	        5
#define VMW_BALLOON_ERROR_PPN_NOTNEEDED	        6
#define VMW_BALLOON_ERROR_RESET		        7
#define VMW_BALLOON_ERROR_BUSY		        8

#define VMW_BALLOON_SUCCESS_WITH_CAPABILITIES	(0x03000000)

124 125 126 127 128 129 130 131 132
#define VMW_BALLOON_CMD_WITH_TARGET_MASK			\
	((1UL << VMW_BALLOON_CMD_GET_TARGET)		|	\
	 (1UL << VMW_BALLOON_CMD_LOCK)			|	\
	 (1UL << VMW_BALLOON_CMD_UNLOCK)		|	\
	 (1UL << VMW_BALLOON_CMD_BATCHED_LOCK)		|	\
	 (1UL << VMW_BALLOON_CMD_BATCHED_UNLOCK)	|	\
	 (1UL << VMW_BALLOON_CMD_BATCHED_2M_LOCK)	|	\
	 (1UL << VMW_BALLOON_CMD_BATCHED_2M_UNLOCK))

133 134 135 136 137 138 139 140 141 142 143 144 145
static const char * const vmballoon_cmd_names[] = {
	[VMW_BALLOON_CMD_START]			= "start",
	[VMW_BALLOON_CMD_GET_TARGET]		= "target",
	[VMW_BALLOON_CMD_LOCK]			= "lock",
	[VMW_BALLOON_CMD_UNLOCK]		= "unlock",
	[VMW_BALLOON_CMD_GUEST_ID]		= "guestType",
	[VMW_BALLOON_CMD_BATCHED_LOCK]		= "batchLock",
	[VMW_BALLOON_CMD_BATCHED_UNLOCK]	= "batchUnlock",
	[VMW_BALLOON_CMD_BATCHED_2M_LOCK]	= "2m-lock",
	[VMW_BALLOON_CMD_BATCHED_2M_UNLOCK]	= "2m-unlock",
	[VMW_BALLOON_CMD_VMCI_DOORBELL_SET]	= "doorbellSet"
};

D
Dmitry Torokhov 已提交
146 147 148
#ifdef CONFIG_DEBUG_FS
struct vmballoon_stats {
	unsigned int timer;
149
	unsigned int doorbell;
D
Dmitry Torokhov 已提交
150

151
	/* allocation statistics */
152 153 154 155 156
	unsigned int alloc[VMW_BALLOON_NUM_PAGE_SIZES];
	unsigned int alloc_fail[VMW_BALLOON_NUM_PAGE_SIZES];
	unsigned int refused_alloc[VMW_BALLOON_NUM_PAGE_SIZES];
	unsigned int refused_free[VMW_BALLOON_NUM_PAGE_SIZES];
	unsigned int free[VMW_BALLOON_NUM_PAGE_SIZES];
D
Dmitry Torokhov 已提交
157

158 159 160
	/* Monitor operations.  */
	unsigned long ops[VMW_BALLOON_CMD_NUM];
	unsigned long ops_fail[VMW_BALLOON_CMD_NUM];
D
Dmitry Torokhov 已提交
161 162 163 164 165 166 167
};

#define STATS_INC(stat) (stat)++
#else
#define STATS_INC(stat)
#endif

168
static DEFINE_STATIC_KEY_TRUE(vmw_balloon_batching);
169

170
struct vmballoon_page_size {
D
Dmitry Torokhov 已提交
171 172 173 174 175
	/* list of reserved physical pages */
	struct list_head pages;

	/* transient list of non-balloonable pages */
	struct list_head refused_pages;
176
	unsigned int n_refused_pages;
177 178
};

179 180 181 182 183 184 185 186 187 188 189 190 191
/**
 * struct vmballoon_batch_entry - a batch entry for lock or unlock.
 *
 * @status: the status of the operation, which is written by the hypervisor.
 * @reserved: reserved for future use. Must be set to zero.
 * @pfn: the physical frame number of the page to be locked or unlocked.
 */
struct vmballoon_batch_entry {
	u64 status : 5;
	u64 reserved : PAGE_SHIFT - 5;
	u64 pfn : 52;
} __packed;

192 193 194 195 196
struct vmballoon {
	struct vmballoon_page_size page_sizes[VMW_BALLOON_NUM_PAGE_SIZES];

	/* supported page sizes. 1 == 4k pages only, 2 == 4k and 2m pages */
	unsigned supported_page_sizes;
D
Dmitry Torokhov 已提交
197 198 199 200 201 202 203 204

	/* balloon size in pages */
	unsigned int size;
	unsigned int target;

	/* reset flag */
	bool reset_required;

205 206
	unsigned long capabilities;

207 208 209 210 211 212 213 214
	/**
	 * @batch_page: pointer to communication batch page.
	 *
	 * When batching is used, batch_page points to a page, which holds up to
	 * %VMW_BALLOON_BATCH_MAX_PAGES entries for locking or unlocking.
	 */
	struct vmballoon_batch_entry *batch_page;

215 216 217
	unsigned int batch_max_pages;
	struct page *page;

D
Dmitry Torokhov 已提交
218 219 220 221 222 223 224 225 226
#ifdef CONFIG_DEBUG_FS
	/* statistics */
	struct vmballoon_stats stats;

	/* debugfs file exporting statistics */
	struct dentry *dbg_entry;
#endif

	struct delayed_work dwork;
227 228

	struct vmci_handle vmci_doorbell;
D
Dmitry Torokhov 已提交
229 230 231 232
};

static struct vmballoon balloon;

233 234 235 236 237 238
static inline unsigned long
__vmballoon_cmd(struct vmballoon *b, unsigned long cmd, unsigned long arg1,
		unsigned long arg2, unsigned long *result)
{
	unsigned long status, dummy1, dummy2, dummy3, local_result;

239 240
	STATS_INC(b->stats.ops[cmd]);

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
	asm volatile ("inl %%dx" :
		"=a"(status),
		"=c"(dummy1),
		"=d"(dummy2),
		"=b"(local_result),
		"=S"(dummy3) :
		"0"(VMW_BALLOON_HV_MAGIC),
		"1"(cmd),
		"2"(VMW_BALLOON_HV_PORT),
		"3"(arg1),
		"4"(arg2) :
		"memory");

	/* update the result if needed */
	if (result)
		*result = (cmd == VMW_BALLOON_CMD_START) ? dummy1 :
							   local_result;

	/* update target when applicable */
	if (status == VMW_BALLOON_SUCCESS &&
	    ((1ul << cmd) & VMW_BALLOON_CMD_WITH_TARGET_MASK))
		b->target = local_result;

264 265 266 267 268 269 270 271
	if (status != VMW_BALLOON_SUCCESS &&
	    status != VMW_BALLOON_SUCCESS_WITH_CAPABILITIES) {
		STATS_INC(b->stats.ops_fail[cmd]);
		pr_debug("%s: %s [0x%lx,0x%lx) failed, returned %ld\n",
			 __func__, vmballoon_cmd_names[cmd], arg1, arg2,
			 status);
	}

272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
	/* mark reset required accordingly */
	if (status == VMW_BALLOON_ERROR_RESET)
		b->reset_required = true;

	return status;
}

static __always_inline unsigned long
vmballoon_cmd(struct vmballoon *b, unsigned long cmd, unsigned long arg1,
	      unsigned long arg2)
{
	unsigned long dummy;

	return __vmballoon_cmd(b, cmd, arg1, arg2, &dummy);
}

D
Dmitry Torokhov 已提交
288 289 290 291
/*
 * Send "start" command to the host, communicating supported version
 * of the protocol.
 */
292
static bool vmballoon_send_start(struct vmballoon *b, unsigned long req_caps)
D
Dmitry Torokhov 已提交
293
{
294
	unsigned long status, capabilities;
295
	bool success;
D
Dmitry Torokhov 已提交
296

297 298
	status = __vmballoon_cmd(b, VMW_BALLOON_CMD_START, req_caps, 0,
				 &capabilities);
299 300 301 302

	switch (status) {
	case VMW_BALLOON_SUCCESS_WITH_CAPABILITIES:
		b->capabilities = capabilities;
303 304
		success = true;
		break;
305 306
	case VMW_BALLOON_SUCCESS:
		b->capabilities = VMW_BALLOON_BASIC_CMDS;
307 308 309 310
		success = true;
		break;
	default:
		success = false;
311
	}
D
Dmitry Torokhov 已提交
312

313 314 315 316 317 318 319
	/*
	 * 2MB pages are only supported with batching. If batching is for some
	 * reason disabled, do not use 2MB pages, since otherwise the legacy
	 * mechanism is used with 2MB pages, causing a failure.
	 */
	if ((b->capabilities & VMW_BALLOON_BATCHED_2M_CMDS) &&
	    (b->capabilities & VMW_BALLOON_BATCHED_CMDS))
320 321 322 323 324
		b->supported_page_sizes = 2;
	else
		b->supported_page_sizes = 1;

	return success;
D
Dmitry Torokhov 已提交
325 326 327 328 329 330 331 332 333 334
}

/*
 * Communicate guest type to the host so that it can adjust ballooning
 * algorithm to the one most appropriate for the guest. This command
 * is normally issued after sending "start" command and is part of
 * standard reset sequence.
 */
static bool vmballoon_send_guest_id(struct vmballoon *b)
{
335
	unsigned long status;
D
Dmitry Torokhov 已提交
336

337 338
	status = vmballoon_cmd(b, VMW_BALLOON_CMD_GUEST_ID,
			       VMW_BALLOON_GUEST_ID, 0);
D
Dmitry Torokhov 已提交
339

340
	if (status == VMW_BALLOON_SUCCESS)
D
Dmitry Torokhov 已提交
341 342 343 344 345
		return true;

	return false;
}

346 347 348
static u16 vmballoon_page_size(bool is_2m_page)
{
	if (is_2m_page)
349
		return 1 << VMW_BALLOON_2M_ORDER;
350 351 352 353

	return 1;
}

354 355 356 357 358 359 360 361
/**
 * vmballoon_send_get_target() - Retrieve desired balloon size from the host.
 *
 * @b: pointer to the balloon.
 *
 * Return: zero on success, EINVAL if limit does not fit in 32-bit, as required
 * by the host-guest protocol and EIO if an error occurred in communicating with
 * the host.
D
Dmitry Torokhov 已提交
362
 */
363
static int vmballoon_send_get_target(struct vmballoon *b)
D
Dmitry Torokhov 已提交
364 365 366 367
{
	unsigned long status;
	unsigned long limit;

368
	limit = totalram_pages;
D
Dmitry Torokhov 已提交
369 370

	/* Ensure limit fits in 32-bits */
371 372
	if (limit != (u32)limit)
		return -EINVAL;
D
Dmitry Torokhov 已提交
373

374 375
	status = vmballoon_cmd(b, VMW_BALLOON_CMD_GET_TARGET, limit, 0);

376
	return status == VMW_BALLOON_SUCCESS ? 0 : -EIO;
D
Dmitry Torokhov 已提交
377 378
}

379
static struct page *vmballoon_alloc_page(bool is_2m_page)
380 381
{
	if (is_2m_page)
382
		return alloc_pages(VMW_HUGE_PAGE_ALLOC_FLAGS,
383
				   VMW_BALLOON_2M_ORDER);
384

385
	return alloc_page(VMW_PAGE_ALLOC_FLAGS);
386 387 388 389 390
}

static void vmballoon_free_page(struct page *page, bool is_2m_page)
{
	if (is_2m_page)
391
		__free_pages(page, VMW_BALLOON_2M_ORDER);
392 393 394 395
	else
		__free_page(page);
}

D
Dmitry Torokhov 已提交
396 397 398 399 400 401 402 403 404
/*
 * Quickly release all pages allocated for the balloon. This function is
 * called when host decides to "reset" balloon for one reason or another.
 * Unlike normal "deflate" we do not (shall not) notify host of the pages
 * being released.
 */
static void vmballoon_pop(struct vmballoon *b)
{
	struct page *page, *next;
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
	unsigned is_2m_pages;

	for (is_2m_pages = 0; is_2m_pages < VMW_BALLOON_NUM_PAGE_SIZES;
			is_2m_pages++) {
		struct vmballoon_page_size *page_size =
				&b->page_sizes[is_2m_pages];
		u16 size_per_page = vmballoon_page_size(is_2m_pages);

		list_for_each_entry_safe(page, next, &page_size->pages, lru) {
			list_del(&page->lru);
			vmballoon_free_page(page, is_2m_pages);
			STATS_INC(b->stats.free[is_2m_pages]);
			b->size -= size_per_page;
			cond_resched();
		}
D
Dmitry Torokhov 已提交
420 421
	}

422 423 424
	/* Clearing the batch_page unconditionally has no adverse effect */
	free_page((unsigned long)b->batch_page);
	b->batch_page = NULL;
D
Dmitry Torokhov 已提交
425 426
}

427 428 429 430 431 432 433 434 435 436 437 438
/**
 * vmballoon_status_page - returns the status of (un)lock operation
 *
 * @b: pointer to the balloon.
 * @idx: index for the page for which the operation is performed.
 * @p: pointer to where the page struct is returned.
 *
 * Following a lock or unlock operation, returns the status of the operation for
 * an individual page. Provides the page that the operation was performed on on
 * the @page argument.
 *
 * Returns: The status of a lock or unlock operation for an individual page.
D
Dmitry Torokhov 已提交
439
 */
440 441
static unsigned long vmballoon_status_page(struct vmballoon *b, int idx,
					   struct page **p)
D
Dmitry Torokhov 已提交
442
{
443 444 445 446 447
	if (static_branch_likely(&vmw_balloon_batching)) {
		/* batching mode */
		*p = pfn_to_page(b->batch_page[idx].pfn);
		return b->batch_page[idx].status;
	}
448

449 450
	/* non-batching mode */
	*p = b->page;
D
Dmitry Torokhov 已提交
451

452 453 454 455 456 457 458 459
	/*
	 * If a failure occurs, the indication will be provided in the status
	 * of the entire operation, which is considered before the individual
	 * page status. So for non-batching mode, the indication is always of
	 * success.
	 */
	return VMW_BALLOON_SUCCESS;
}
D
Dmitry Torokhov 已提交
460

461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
/**
 * vmballoon_lock_op - notifies the host about inflated/deflated pages.
 * @b: pointer to the balloon.
 * @num_pages: number of inflated/deflated pages.
 * @is_2m_pages: whether the page(s) are 2M (or 4k).
 * @lock: whether the operation is lock (or unlock).
 *
 * Notify the host about page(s) that were ballooned (or removed from the
 * balloon) so that host can use it without fear that guest will need it (or
 * stop using them since the VM does). Host may reject some pages, we need to
 * check the return value and maybe submit a different page. The pages that are
 * inflated/deflated are pointed by @b->page.
 *
 * Return: result as provided by the hypervisor.
 */
static unsigned long vmballoon_lock_op(struct vmballoon *b,
				       unsigned int num_pages,
				       bool is_2m_pages, bool lock)
{
	unsigned long cmd, pfn;

	if (static_branch_likely(&vmw_balloon_batching)) {
		if (lock)
			cmd = is_2m_pages ? VMW_BALLOON_CMD_BATCHED_2M_LOCK :
					    VMW_BALLOON_CMD_BATCHED_LOCK;
		else
			cmd = is_2m_pages ? VMW_BALLOON_CMD_BATCHED_2M_UNLOCK :
					    VMW_BALLOON_CMD_BATCHED_UNLOCK;

		pfn = PHYS_PFN(virt_to_phys(b->batch_page));
	} else {
		cmd = lock ? VMW_BALLOON_CMD_LOCK : VMW_BALLOON_CMD_UNLOCK;
		pfn = page_to_pfn(b->page);

		/* In non-batching mode, PFNs must fit in 32-bit */
		if (unlikely(pfn != (u32)pfn))
			return VMW_BALLOON_ERROR_PPN_INVALID;
498
	}
D
Dmitry Torokhov 已提交
499

500
	return vmballoon_cmd(b, cmd, pfn, num_pages);
D
Dmitry Torokhov 已提交
501 502
}

503 504
static int vmballoon_lock(struct vmballoon *b, unsigned int num_pages,
			  bool is_2m_pages)
505
{
506 507
	unsigned long batch_status;
	int i;
508
	u16 size_per_page = vmballoon_page_size(is_2m_pages);
509

510
	batch_status = vmballoon_lock_op(b, num_pages, is_2m_pages, true);
511 512

	for (i = 0; i < num_pages; i++) {
513 514
		unsigned long status;
		struct page *p;
515 516
		struct vmballoon_page_size *page_size =
				&b->page_sizes[is_2m_pages];
517

518 519 520 521 522 523 524 525
		status = vmballoon_status_page(b, i, &p);

		/*
		 * Failure of the whole batch overrides a single operation
		 * results.
		 */
		if (batch_status != VMW_BALLOON_SUCCESS)
			status = batch_status;
526

527 528
		if (status == VMW_BALLOON_SUCCESS) {
			/* track allocated page */
529
			list_add(&p->lru, &page_size->pages);
530 531

			/* update balloon size */
532
			b->size += size_per_page;
533 534 535 536 537 538
			continue;
		}

		/* Error occurred */
		STATS_INC(b->stats.refused_alloc[is_2m_pages]);

539 540 541 542 543 544 545
		/*
		 * Place page on the list of non-balloonable pages
		 * and retry allocation, unless we already accumulated
		 * too many of them, in which case take a breather.
		 */
		list_add(&p->lru, &page_size->refused_pages);
		page_size->n_refused_pages++;
546 547
	}

548
	return batch_status == VMW_BALLOON_SUCCESS ? 0 : -EIO;
549 550
}

D
Dmitry Torokhov 已提交
551 552 553 554 555
/*
 * Release the page allocated for the balloon. Note that we first notify
 * the host so it can make sure the page will be available for the guest
 * to use, if needed.
 */
556 557
static int vmballoon_unlock(struct vmballoon *b, unsigned int num_pages,
			    bool is_2m_pages)
D
Dmitry Torokhov 已提交
558
{
559 560
	int i;
	unsigned long batch_status;
561
	u16 size_per_page = vmballoon_page_size(is_2m_pages);
562

563
	batch_status = vmballoon_lock_op(b, num_pages, is_2m_pages, false);
564 565

	for (i = 0; i < num_pages; i++) {
566 567 568 569 570 571
		struct vmballoon_page_size *page_size;
		unsigned long status;
		struct page *p;

		status = vmballoon_status_page(b, i, &p);
		page_size = &b->page_sizes[is_2m_pages];
572

573 574 575 576 577 578 579 580
		/*
		 * Failure of the whole batch overrides a single operation
		 * results.
		 */
		if (batch_status != VMW_BALLOON_SUCCESS)
			status = batch_status;

		if (status != VMW_BALLOON_SUCCESS) {
581 582 583 584 585
			/*
			 * That page wasn't successfully unlocked by the
			 * hypervisor, re-add it to the list of pages owned by
			 * the balloon driver.
			 */
586
			list_add(&p->lru, &page_size->pages);
587 588
		} else {
			/* deallocate page */
589 590
			vmballoon_free_page(p, is_2m_pages);
			STATS_INC(b->stats.free[is_2m_pages]);
591 592

			/* update balloon size */
593
			b->size -= size_per_page;
594 595 596
		}
	}

597
	return batch_status == VMW_BALLOON_SUCCESS ? 0 : -EIO;
598 599
}

D
Dmitry Torokhov 已提交
600 601 602 603
/*
 * Release pages that were allocated while attempting to inflate the
 * balloon but were refused by the host for one reason or another.
 */
604 605
static void vmballoon_release_refused_pages(struct vmballoon *b,
		bool is_2m_pages)
D
Dmitry Torokhov 已提交
606 607
{
	struct page *page, *next;
608 609
	struct vmballoon_page_size *page_size =
			&b->page_sizes[is_2m_pages];
D
Dmitry Torokhov 已提交
610

611
	list_for_each_entry_safe(page, next, &page_size->refused_pages, lru) {
D
Dmitry Torokhov 已提交
612
		list_del(&page->lru);
613 614
		vmballoon_free_page(page, is_2m_pages);
		STATS_INC(b->stats.refused_free[is_2m_pages]);
D
Dmitry Torokhov 已提交
615
	}
616

617
	page_size->n_refused_pages = 0;
D
Dmitry Torokhov 已提交
618 619
}

620 621
static void vmballoon_add_page(struct vmballoon *b, int idx, struct page *p)
{
622 623
	if (static_branch_likely(&vmw_balloon_batching))
		b->batch_page[idx] = (struct vmballoon_batch_entry)
624
					{ .pfn = page_to_pfn(p) };
625 626
	else
		b->page = p;
627 628
}

629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
/**
 * vmballoon_change - retrieve the required balloon change
 *
 * @b: pointer for the balloon.
 *
 * Return: the required change for the balloon size. A positive number
 * indicates inflation, a negative number indicates a deflation.
 */
static int64_t vmballoon_change(struct vmballoon *b)
{
	int64_t size, target;

	size = b->size;
	target = b->target;

	/*
	 * We must cast first because of int sizes
	 * Otherwise we might get huge positives instead of negatives
	 */

	if (b->reset_required)
		return 0;

	/* consider a 2MB slack on deflate, unless the balloon is emptied */
	if (target < size && size - target < vmballoon_page_size(true) &&
	    target != 0)
		return 0;

	return target - size;
}

D
Dmitry Torokhov 已提交
660 661 662 663 664 665 666
/*
 * Inflate the balloon towards its target size. Note that we try to limit
 * the rate of allocation to make sure we are not choking the rest of the
 * system.
 */
static void vmballoon_inflate(struct vmballoon *b)
{
667
	unsigned int num_pages = 0;
D
Dmitry Torokhov 已提交
668
	int error = 0;
669
	bool is_2m_pages;
D
Dmitry Torokhov 已提交
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689

	/*
	 * First try NOSLEEP page allocations to inflate balloon.
	 *
	 * If we do not throttle nosleep allocations, we can drain all
	 * free pages in the guest quickly (if the balloon target is high).
	 * As a side-effect, draining free pages helps to inform (force)
	 * the guest to start swapping if balloon target is not met yet,
	 * which is a desired behavior. However, balloon driver can consume
	 * all available CPU cycles if too many pages are allocated in a
	 * second. Therefore, we throttle nosleep allocations even when
	 * the guest is not under memory pressure. OTOH, if we have already
	 * predicted that the guest is under memory pressure, then we
	 * slowdown page allocations considerably.
	 */

	/*
	 * Start with no sleep allocation rate which may be higher
	 * than sleeping allocation rate.
	 */
690
	is_2m_pages = b->supported_page_sizes == VMW_BALLOON_NUM_PAGE_SIZES;
D
Dmitry Torokhov 已提交
691

692 693
	while ((int64_t)(num_pages * vmballoon_page_size(is_2m_pages)) <
	       vmballoon_change(b)) {
694
		struct page *page;
D
Dmitry Torokhov 已提交
695

696 697
		STATS_INC(b->stats.alloc[is_2m_pages]);
		page = vmballoon_alloc_page(is_2m_pages);
698
		if (!page) {
699 700
			STATS_INC(b->stats.alloc_fail[is_2m_pages]);
			if (is_2m_pages) {
701
				vmballoon_lock(b, num_pages, true);
702 703 704 705 706 707 708 709 710 711 712

				/*
				 * ignore errors from locking as we now switch
				 * to 4k pages and we might get different
				 * errors.
				 */

				num_pages = 0;
				is_2m_pages = false;
				continue;
			}
713
			break;
D
Dmitry Torokhov 已提交
714 715
		}

716
		vmballoon_add_page(b, num_pages++, page);
717
		if (num_pages == b->batch_max_pages) {
718 719 720
			struct vmballoon_page_size *page_size =
					&b->page_sizes[is_2m_pages];

721
			error = vmballoon_lock(b, num_pages, is_2m_pages);
722

723
			num_pages = 0;
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742

			/*
			 * Stop allocating this page size if we already
			 * accumulated too many pages that the hypervisor
			 * refused.
			 */
			if (page_size->n_refused_pages >=
			    VMW_BALLOON_MAX_REFUSED) {
				if (!is_2m_pages)
					break;

				/*
				 * Release the refused pages as we move to 4k
				 * pages.
				 */
				vmballoon_release_refused_pages(b, true);
				is_2m_pages = true;
			}

743 744 745
			if (error)
				break;
		}
746

747
		cond_resched();
D
Dmitry Torokhov 已提交
748 749
	}

750
	if (num_pages > 0)
751
		vmballoon_lock(b, num_pages, is_2m_pages);
752

753 754
	vmballoon_release_refused_pages(b, true);
	vmballoon_release_refused_pages(b, false);
D
Dmitry Torokhov 已提交
755 756 757 758 759 760 761
}

/*
 * Decrease the size of the balloon allowing guest to use more memory.
 */
static void vmballoon_deflate(struct vmballoon *b)
{
762
	unsigned is_2m_pages;
D
Dmitry Torokhov 已提交
763 764

	/* free pages to reach target */
765 766 767 768 769 770 771 772
	for (is_2m_pages = 0; is_2m_pages < b->supported_page_sizes;
			is_2m_pages++) {
		struct page *page, *next;
		unsigned int num_pages = 0;
		struct vmballoon_page_size *page_size =
				&b->page_sizes[is_2m_pages];

		list_for_each_entry_safe(page, next, &page_size->pages, lru) {
773 774 775
			if ((int64_t)(num_pages *
				      vmballoon_page_size(is_2m_pages)) >=
					-vmballoon_change(b))
776
				break;
777

778
			list_del(&page->lru);
779
			vmballoon_add_page(b, num_pages++, page);
780

781 782
			if (num_pages == b->batch_max_pages) {
				int error;
D
Dmitry Torokhov 已提交
783

784
				error = vmballoon_unlock(b, num_pages,
785
						       is_2m_pages);
786 787 788 789
				num_pages = 0;
				if (error)
					return;
			}
790

791 792
			cond_resched();
		}
D
Dmitry Torokhov 已提交
793

794
		if (num_pages > 0)
795
			vmballoon_unlock(b, num_pages, is_2m_pages);
796
	}
797 798
}

799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
/**
 * vmballoon_deinit_batching - disables batching mode.
 *
 * @b: pointer to &struct vmballoon.
 *
 * Disables batching, by deallocating the page for communication with the
 * hypervisor and disabling the static key to indicate that batching is off.
 */
static void vmballoon_deinit_batching(struct vmballoon *b)
{
	free_page((unsigned long)b->batch_page);
	b->batch_page = NULL;
	static_branch_disable(&vmw_balloon_batching);
	b->batch_max_pages = 1;
}
814

815 816 817 818 819 820 821 822 823 824 825
/**
 * vmballoon_init_batching - enable batching mode.
 *
 * @b: pointer to &struct vmballoon.
 *
 * Enables batching, by allocating a page for communication with the hypervisor
 * and enabling the static_key to use batching.
 *
 * Return: zero on success or an appropriate error-code.
 */
static int vmballoon_init_batching(struct vmballoon *b)
826
{
827
	struct page *page;
828

829 830
	page = alloc_page(GFP_KERNEL | __GFP_ZERO);
	if (!page)
831
		return -ENOMEM;
832

833
	b->batch_page = page_address(page);
834 835 836 837 838
	b->batch_max_pages = PAGE_SIZE / sizeof(struct vmballoon_batch_entry);

	static_branch_enable(&vmw_balloon_batching);

	return 0;
839 840
}

841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
/*
 * Receive notification and resize balloon
 */
static void vmballoon_doorbell(void *client_data)
{
	struct vmballoon *b = client_data;

	STATS_INC(b->stats.doorbell);

	mod_delayed_work(system_freezable_wq, &b->dwork, 0);
}

/*
 * Clean up vmci doorbell
 */
static void vmballoon_vmci_cleanup(struct vmballoon *b)
{
858 859
	vmballoon_cmd(b, VMW_BALLOON_CMD_VMCI_DOORBELL_SET,
		      VMCI_INVALID_ID, VMCI_INVALID_ID);
860 861 862 863 864 865 866 867 868 869 870 871

	if (!vmci_handle_is_invalid(b->vmci_doorbell)) {
		vmci_doorbell_destroy(b->vmci_doorbell);
		b->vmci_doorbell = VMCI_INVALID_HANDLE;
	}
}

/*
 * Initialize vmci doorbell, to get notified as soon as balloon changes
 */
static int vmballoon_vmci_init(struct vmballoon *b)
{
872
	unsigned long error;
873

874 875
	if ((b->capabilities & VMW_BALLOON_SIGNALLED_WAKEUP_CMD) == 0)
		return 0;
876

877 878 879
	error = vmci_doorbell_create(&b->vmci_doorbell, VMCI_FLAG_DELAYED_CB,
				     VMCI_PRIVILEGE_FLAG_RESTRICTED,
				     vmballoon_doorbell, b);
880

881 882 883
	if (error != VMCI_SUCCESS)
		goto fail;

884 885 886
	error =	__vmballoon_cmd(b, VMW_BALLOON_CMD_VMCI_DOORBELL_SET,
				b->vmci_doorbell.context,
				b->vmci_doorbell.resource, NULL);
887 888 889

	if (error != VMW_BALLOON_SUCCESS)
		goto fail;
890 891

	return 0;
892 893 894
fail:
	vmballoon_vmci_cleanup(b);
	return -EIO;
895 896
}

897 898 899 900 901 902 903
/*
 * Perform standard reset sequence by popping the balloon (in case it
 * is not  empty) and then restarting protocol. This operation normally
 * happens when host responds with VMW_BALLOON_ERROR_RESET to a command.
 */
static void vmballoon_reset(struct vmballoon *b)
{
904 905 906 907
	int error;

	vmballoon_vmci_cleanup(b);

908 909 910 911 912 913 914
	/* free all pages, skipping monitor unlock */
	vmballoon_pop(b);

	if (!vmballoon_send_start(b, VMW_BALLOON_CAPABILITIES))
		return;

	if ((b->capabilities & VMW_BALLOON_BATCHED_CMDS) != 0) {
915
		if (vmballoon_init_batching(b)) {
916 917 918 919 920 921 922 923 924 925
			/*
			 * We failed to initialize batching, inform the monitor
			 * about it by sending a null capability.
			 *
			 * The guest will retry in one second.
			 */
			vmballoon_send_start(b, 0);
			return;
		}
	} else if ((b->capabilities & VMW_BALLOON_BASIC_CMDS) != 0) {
926
		vmballoon_deinit_batching(b);
927 928 929
	}

	b->reset_required = false;
930 931 932 933 934

	error = vmballoon_vmci_init(b);
	if (error)
		pr_err("failed to initialize vmci doorbell\n");

935 936
	if (!vmballoon_send_guest_id(b))
		pr_err("failed to send guest ID to the host\n");
D
Dmitry Torokhov 已提交
937 938
}

939 940 941 942 943 944 945
/**
 * vmballoon_work - periodic balloon worker for reset, inflation and deflation.
 *
 * @work: pointer to the &work_struct which is provided by the workqueue.
 *
 * Resets the protocol if needed, gets the new size and adjusts balloon as
 * needed. Repeat in 1 sec.
D
Dmitry Torokhov 已提交
946 947 948 949 950
 */
static void vmballoon_work(struct work_struct *work)
{
	struct delayed_work *dwork = to_delayed_work(work);
	struct vmballoon *b = container_of(dwork, struct vmballoon, dwork);
951
	int64_t change = 0;
D
Dmitry Torokhov 已提交
952 953 954 955 956 957

	STATS_INC(b->stats.timer);

	if (b->reset_required)
		vmballoon_reset(b);

958
	if (!vmballoon_send_get_target(b))
959 960 961 962 963
		change = vmballoon_change(b);

	if (change != 0) {
		pr_debug("%s - size: %u, target %u", __func__,
			 b->size, b->target);
D
Dmitry Torokhov 已提交
964

965
		if (change > 0)
D
Dmitry Torokhov 已提交
966
			vmballoon_inflate(b);
967
		else  /* (change < 0) */
D
Dmitry Torokhov 已提交
968 969 970
			vmballoon_deflate(b);
	}

971 972 973 974 975 976
	/*
	 * We are using a freezable workqueue so that balloon operations are
	 * stopped while the system transitions to/from sleep/hibernation.
	 */
	queue_delayed_work(system_freezable_wq,
			   dwork, round_jiffies_relative(HZ));
D
Dmitry Torokhov 已提交
977 978 979 980 981 982 983 984 985 986 987
}

/*
 * DEBUGFS Interface
 */
#ifdef CONFIG_DEBUG_FS

static int vmballoon_debug_show(struct seq_file *f, void *offset)
{
	struct vmballoon *b = f->private;
	struct vmballoon_stats *stats = &b->stats;
988
	int i;
D
Dmitry Torokhov 已提交
989

990 991 992
	/* format capabilities info */
	seq_printf(f,
		   "balloon capabilities:   %#4x\n"
993 994 995 996
		   "used capabilities:      %#4lx\n"
		   "is resetting:           %c\n",
		   VMW_BALLOON_CAPABILITIES, b->capabilities,
		   b->reset_required ? 'y' : 'n');
997

D
Dmitry Torokhov 已提交
998 999 1000 1001 1002 1003
	/* format size info */
	seq_printf(f,
		   "target:             %8d pages\n"
		   "current:            %8d pages\n",
		   b->target, b->size);

1004 1005 1006 1007 1008 1009 1010 1011 1012
	for (i = 0; i < VMW_BALLOON_CMD_NUM; i++) {
		if (vmballoon_cmd_names[i] == NULL)
			continue;

		seq_printf(f, "%-22s: %16lu (%lu failed)\n",
			   vmballoon_cmd_names[i], stats->ops[i],
			   stats->ops_fail[i]);
	}

D
Dmitry Torokhov 已提交
1013 1014 1015
	seq_printf(f,
		   "\n"
		   "timer:              %8u\n"
1016
		   "doorbell:           %8u\n"
1017
		   "prim2mAlloc:        %8u (%4u failed)\n"
1018
		   "prim4kAlloc:        %8u (%4u failed)\n"
1019
		   "prim2mFree:         %8u\n"
D
Dmitry Torokhov 已提交
1020
		   "primFree:           %8u\n"
1021
		   "err2mAlloc:         %8u\n"
D
Dmitry Torokhov 已提交
1022
		   "errAlloc:           %8u\n"
1023
		   "err2mFree:          %8u\n"
1024
		   "errFree:            %8u\n",
D
Dmitry Torokhov 已提交
1025
		   stats->timer,
1026
		   stats->doorbell,
1027 1028 1029 1030 1031
		   stats->alloc[true], stats->alloc_fail[true],
		   stats->alloc[false], stats->alloc_fail[false],
		   stats->free[true],
		   stats->free[false],
		   stats->refused_alloc[true], stats->refused_alloc[false],
1032
		   stats->refused_free[true], stats->refused_free[false]);
D
Dmitry Torokhov 已提交
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085

	return 0;
}

static int vmballoon_debug_open(struct inode *inode, struct file *file)
{
	return single_open(file, vmballoon_debug_show, inode->i_private);
}

static const struct file_operations vmballoon_debug_fops = {
	.owner		= THIS_MODULE,
	.open		= vmballoon_debug_open,
	.read		= seq_read,
	.llseek		= seq_lseek,
	.release	= single_release,
};

static int __init vmballoon_debugfs_init(struct vmballoon *b)
{
	int error;

	b->dbg_entry = debugfs_create_file("vmmemctl", S_IRUGO, NULL, b,
					   &vmballoon_debug_fops);
	if (IS_ERR(b->dbg_entry)) {
		error = PTR_ERR(b->dbg_entry);
		pr_err("failed to create debugfs entry, error: %d\n", error);
		return error;
	}

	return 0;
}

static void __exit vmballoon_debugfs_exit(struct vmballoon *b)
{
	debugfs_remove(b->dbg_entry);
}

#else

static inline int vmballoon_debugfs_init(struct vmballoon *b)
{
	return 0;
}

static inline void vmballoon_debugfs_exit(struct vmballoon *b)
{
}

#endif	/* CONFIG_DEBUG_FS */

static int __init vmballoon_init(void)
{
	int error;
1086
	unsigned is_2m_pages;
D
Dmitry Torokhov 已提交
1087 1088 1089 1090
	/*
	 * Check if we are running on VMware's hypervisor and bail out
	 * if we are not.
	 */
1091
	if (x86_hyper_type != X86_HYPER_VMWARE)
D
Dmitry Torokhov 已提交
1092 1093
		return -ENODEV;

1094 1095 1096 1097 1098
	for (is_2m_pages = 0; is_2m_pages < VMW_BALLOON_NUM_PAGE_SIZES;
			is_2m_pages++) {
		INIT_LIST_HEAD(&balloon.page_sizes[is_2m_pages].pages);
		INIT_LIST_HEAD(&balloon.page_sizes[is_2m_pages].refused_pages);
	}
D
Dmitry Torokhov 已提交
1099 1100 1101 1102 1103

	INIT_DELAYED_WORK(&balloon.dwork, vmballoon_work);

	error = vmballoon_debugfs_init(&balloon);
	if (error)
1104
		return error;
D
Dmitry Torokhov 已提交
1105

1106
	balloon.vmci_doorbell = VMCI_INVALID_HANDLE;
1107 1108 1109 1110
	balloon.batch_page = NULL;
	balloon.page = NULL;
	balloon.reset_required = true;

1111
	queue_delayed_work(system_freezable_wq, &balloon.dwork, 0);
D
Dmitry Torokhov 已提交
1112 1113 1114

	return 0;
}
1115 1116 1117 1118 1119 1120 1121 1122

/*
 * Using late_initcall() instead of module_init() allows the balloon to use the
 * VMCI doorbell even when the balloon is built into the kernel. Otherwise the
 * VMCI is probed only after the balloon is initialized. If the balloon is used
 * as a module, late_initcall() is equivalent to module_init().
 */
late_initcall(vmballoon_init);
D
Dmitry Torokhov 已提交
1123 1124 1125

static void __exit vmballoon_exit(void)
{
1126
	vmballoon_vmci_cleanup(&balloon);
D
Dmitry Torokhov 已提交
1127 1128 1129 1130 1131 1132 1133 1134 1135
	cancel_delayed_work_sync(&balloon.dwork);

	vmballoon_debugfs_exit(&balloon);

	/*
	 * Deallocate all reserved memory, and reset connection with monitor.
	 * Reset connection before deallocating memory to avoid potential for
	 * additional spurious resets from guest touching deallocated pages.
	 */
1136
	vmballoon_send_start(&balloon, 0);
D
Dmitry Torokhov 已提交
1137 1138 1139
	vmballoon_pop(&balloon);
}
module_exit(vmballoon_exit);