lapic.c 72.9 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0-only
Eddie Dong's avatar
Eddie Dong committed
2
3
4
5
6
7
8

/*
 * Local APIC virtualization
 *
 * Copyright (C) 2006 Qumranet, Inc.
 * Copyright (C) 2007 Novell
 * Copyright (C) 2007 Intel
9
 * Copyright 2009 Red Hat, Inc. and/or its affiliates.
Eddie Dong's avatar
Eddie Dong committed
10
11
12
13
14
15
16
17
18
 *
 * Authors:
 *   Dor Laor <dor.laor@qumranet.com>
 *   Gregory Haskins <ghaskins@novell.com>
 *   Yaozu (Eddie) Dong <eddie.dong@intel.com>
 *
 * Based on Xen 3.1 code, Copyright (c) 2004, Intel Corporation.
 */

19
#include <linux/kvm_host.h>
Eddie Dong's avatar
Eddie Dong committed
20
21
22
23
24
25
#include <linux/kvm.h>
#include <linux/mm.h>
#include <linux/highmem.h>
#include <linux/smp.h>
#include <linux/hrtimer.h>
#include <linux/io.h>
26
#include <linux/export.h>
Roman Zippel's avatar
Roman Zippel committed
27
#include <linux/math64.h>
28
#include <linux/slab.h>
Eddie Dong's avatar
Eddie Dong committed
29
30
31
32
33
#include <asm/processor.h>
#include <asm/msr.h>
#include <asm/page.h>
#include <asm/current.h>
#include <asm/apicdef.h>
34
#include <asm/delay.h>
Arun Sharma's avatar
Arun Sharma committed
35
#include <linux/atomic.h>
36
#include <linux/jump_label.h>
37
#include "kvm_cache_regs.h"
Eddie Dong's avatar
Eddie Dong committed
38
#include "irq.h"
39
#include "ioapic.h"
40
#include "trace.h"
41
#include "x86.h"
Avi Kivity's avatar
Avi Kivity committed
42
#include "cpuid.h"
43
#include "hyperv.h"
Eddie Dong's avatar
Eddie Dong committed
44

45
46
47
48
49
50
#ifndef CONFIG_X86_64
#define mod_64(x, y) ((x) - (y) * div64_u64(x, y))
#else
#define mod_64(x, y) ((x) % (y))
#endif

Eddie Dong's avatar
Eddie Dong committed
51
52
53
54
55
56
#define PRId64 "d"
#define PRIx64 "llx"
#define PRIu64 "u"
#define PRIo64 "o"

/* 14 is the version for Xeon and Pentium 8.4.8*/
57
#define APIC_VERSION			(0x14UL | ((KVM_APIC_LVT_NUM - 1) << 16))
Eddie Dong's avatar
Eddie Dong committed
58
59
60
#define LAPIC_MMIO_LENGTH		(1 << 12)
/* followed define is not in apicdef.h */
#define MAX_APIC_VECTOR			256
61
#define APIC_VECTORS_PER_REG		32
Eddie Dong's avatar
Eddie Dong committed
62

63
static bool lapic_timer_advance_dynamic __read_mostly;
64
65
66
67
#define LAPIC_TIMER_ADVANCE_ADJUST_MIN	100	/* clock cycles */
#define LAPIC_TIMER_ADVANCE_ADJUST_MAX	10000	/* clock cycles */
#define LAPIC_TIMER_ADVANCE_NS_INIT	1000
#define LAPIC_TIMER_ADVANCE_NS_MAX     5000
68
69
70
/* step-by-step approximation to mitigate fluctuation */
#define LAPIC_TIMER_ADVANCE_ADJUST_STEP 8

71
72
73
74
75
static inline int apic_test_vector(int vec, void *bitmap)
{
	return test_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
}

76
77
78
79
80
81
82
83
bool kvm_apic_pending_eoi(struct kvm_vcpu *vcpu, int vector)
{
	struct kvm_lapic *apic = vcpu->arch.apic;

	return apic_test_vector(vector, apic->regs + APIC_ISR) ||
		apic_test_vector(vector, apic->regs + APIC_IRR);
}

Michael S. Tsirkin's avatar
Michael S. Tsirkin committed
84
85
86
87
88
89
90
91
92
93
static inline int __apic_test_and_set_vector(int vec, void *bitmap)
{
	return __test_and_set_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
}

static inline int __apic_test_and_clear_vector(int vec, void *bitmap)
{
	return __test_and_clear_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
}

94
struct static_key_deferred apic_hw_disabled __read_mostly;
95
96
struct static_key_deferred apic_sw_disabled __read_mostly;

Eddie Dong's avatar
Eddie Dong committed
97
98
static inline int apic_enabled(struct kvm_lapic *apic)
{
99
	return kvm_apic_sw_enabled(apic) &&	kvm_apic_hw_enabled(apic);
100
101
}

Eddie Dong's avatar
Eddie Dong committed
102
103
104
105
106
107
108
#define LVT_MASK	\
	(APIC_LVT_MASKED | APIC_SEND_PENDING | APIC_VECTOR_MASK)

#define LINT_MASK	\
	(LVT_MASK | APIC_MODE_MASK | APIC_INPUT_POLARITY | \
	 APIC_LVT_REMOTE_IRR | APIC_LVT_LEVEL_TRIGGER)

109
110
111
112
113
static inline u32 kvm_x2apic_id(struct kvm_lapic *apic)
{
	return apic->vcpu->vcpu_id;
}

114
static bool kvm_can_post_timer_interrupt(struct kvm_vcpu *vcpu)
115
116
117
{
	return pi_inject_timer && kvm_vcpu_apicv_active(vcpu);
}
118
119
120
121
122
123
124
125

bool kvm_can_use_hv_timer(struct kvm_vcpu *vcpu)
{
	return kvm_x86_ops.set_hv_timer
	       && !(kvm_mwait_in_guest(vcpu->kvm) ||
		    kvm_can_post_timer_interrupt(vcpu));
}
EXPORT_SYMBOL_GPL(kvm_can_use_hv_timer);
126
127
128
129
130
131

static bool kvm_use_posted_timer_interrupt(struct kvm_vcpu *vcpu)
{
	return kvm_can_post_timer_interrupt(vcpu) && vcpu->mode == IN_GUEST_MODE;
}

132
133
134
135
136
static inline bool kvm_apic_map_get_logical_dest(struct kvm_apic_map *map,
		u32 dest_id, struct kvm_lapic ***cluster, u16 *mask) {
	switch (map->mode) {
	case KVM_APIC_MODE_X2APIC: {
		u32 offset = (dest_id >> 16) * 16;
137
		u32 max_apic_id = map->max_apic_id;
138
139
140
141

		if (offset <= max_apic_id) {
			u8 cluster_size = min(max_apic_id - offset + 1, 16U);

Paolo Bonzini's avatar
Paolo Bonzini committed
142
			offset = array_index_nospec(offset, map->max_apic_id + 1);
143
144
145
146
147
			*cluster = &map->phys_map[offset];
			*mask = dest_id & (0xffff >> (16 - cluster_size));
		} else {
			*mask = 0;
		}
148

149
150
151
152
153
154
155
		return true;
		}
	case KVM_APIC_MODE_XAPIC_FLAT:
		*cluster = map->xapic_flat_map;
		*mask = dest_id & 0xff;
		return true;
	case KVM_APIC_MODE_XAPIC_CLUSTER:
156
		*cluster = map->xapic_cluster_map[(dest_id >> 4) & 0xf];
157
158
159
160
161
162
		*mask = dest_id & 0xf;
		return true;
	default:
		/* Not optimized. */
		return false;
	}
163
164
}

165
static void kvm_apic_map_free(struct rcu_head *rcu)
166
{
167
	struct kvm_apic_map *map = container_of(rcu, struct kvm_apic_map, rcu);
168

169
	kvfree(map);
170
171
}

172
173
174
175
176
177
178
179
180
181
182
183
/*
 * CLEAN -> DIRTY and UPDATE_IN_PROGRESS -> DIRTY changes happen without a lock.
 *
 * DIRTY -> UPDATE_IN_PROGRESS and UPDATE_IN_PROGRESS -> CLEAN happen with
 * apic_map_lock_held.
 */
enum {
	CLEAN,
	UPDATE_IN_PROGRESS,
	DIRTY
};

184
void kvm_recalculate_apic_map(struct kvm *kvm)
185
186
187
188
{
	struct kvm_apic_map *new, *old = NULL;
	struct kvm_vcpu *vcpu;
	int i;
189
	u32 max_id = 255; /* enough space for any xAPIC ID */
190

191
192
	/* Read kvm->arch.apic_map_dirty before kvm->arch.apic_map.  */
	if (atomic_read_acquire(&kvm->arch.apic_map_dirty) == CLEAN)
193
194
		return;

195
	mutex_lock(&kvm->arch.apic_map_lock);
196
197
198
199
200
201
	/*
	 * Read kvm->arch.apic_map_dirty before kvm->arch.apic_map
	 * (if clean) or the APIC registers (if dirty).
	 */
	if (atomic_cmpxchg_acquire(&kvm->arch.apic_map_dirty,
				   DIRTY, UPDATE_IN_PROGRESS) == CLEAN) {
202
203
204
205
		/* Someone else has updated the map. */
		mutex_unlock(&kvm->arch.apic_map_lock);
		return;
	}
206

207
208
	kvm_for_each_vcpu(i, vcpu, kvm)
		if (kvm_apic_present(vcpu))
209
			max_id = max(max_id, kvm_x2apic_id(vcpu->arch.apic));
210

211
	new = kvzalloc(sizeof(struct kvm_apic_map) +
212
213
	                   sizeof(struct kvm_lapic *) * ((u64)max_id + 1),
			   GFP_KERNEL_ACCOUNT);
214

215
216
217
	if (!new)
		goto out;

218
219
	new->max_apic_id = max_id;

220
221
	kvm_for_each_vcpu(i, vcpu, kvm) {
		struct kvm_lapic *apic = vcpu->arch.apic;
222
223
		struct kvm_lapic **cluster;
		u16 mask;
224
225
226
		u32 ldr;
		u8 xapic_id;
		u32 x2apic_id;
227

228
229
230
		if (!kvm_apic_present(vcpu))
			continue;

231
232
233
234
235
236
237
238
239
240
241
242
243
		xapic_id = kvm_xapic_id(apic);
		x2apic_id = kvm_x2apic_id(apic);

		/* Hotplug hack: see kvm_apic_match_physical_addr(), ... */
		if ((apic_x2apic_mode(apic) || x2apic_id > 0xff) &&
				x2apic_id <= new->max_apic_id)
			new->phys_map[x2apic_id] = apic;
		/*
		 * ... xAPIC ID of VCPUs with APIC ID > 0xff will wrap-around,
		 * prevent them from masking VCPUs with APIC ID <= 0xff.
		 */
		if (!apic_x2apic_mode(apic) && !new->phys_map[xapic_id])
			new->phys_map[xapic_id] = apic;
244

245
246
247
		if (!kvm_apic_sw_enabled(apic))
			continue;

248
249
		ldr = kvm_lapic_get_reg(apic, APIC_LDR);

250
251
252
253
		if (apic_x2apic_mode(apic)) {
			new->mode |= KVM_APIC_MODE_X2APIC;
		} else if (ldr) {
			ldr = GET_APIC_LOGICAL_ID(ldr);
254
			if (kvm_lapic_get_reg(apic, APIC_DFR) == APIC_DFR_FLAT)
255
256
257
258
259
				new->mode |= KVM_APIC_MODE_XAPIC_FLAT;
			else
				new->mode |= KVM_APIC_MODE_XAPIC_CLUSTER;
		}

260
		if (!kvm_apic_map_get_logical_dest(new, ldr, &cluster, &mask))
261
262
			continue;

263
264
		if (mask)
			cluster[ffs(mask) - 1] = apic;
265
266
267
268
269
	}
out:
	old = rcu_dereference_protected(kvm->arch.apic_map,
			lockdep_is_held(&kvm->arch.apic_map_lock));
	rcu_assign_pointer(kvm->arch.apic_map, new);
270
	/*
271
272
	 * Write kvm->arch.apic_map before clearing apic->apic_map_dirty.
	 * If another update has come in, leave it DIRTY.
273
	 */
274
275
	atomic_cmpxchg_release(&kvm->arch.apic_map_dirty,
			       UPDATE_IN_PROGRESS, CLEAN);
276
277
278
	mutex_unlock(&kvm->arch.apic_map_lock);

	if (old)
279
		call_rcu(&old->rcu, kvm_apic_map_free);
280

281
	kvm_make_scan_ioapic_request(kvm);
282
283
}

284
285
static inline void apic_set_spiv(struct kvm_lapic *apic, u32 val)
{
286
	bool enabled = val & APIC_SPIV_APIC_ENABLED;
287

288
	kvm_lapic_set_reg(apic, APIC_SPIV, val);
289
290
291

	if (enabled != apic->sw_enabled) {
		apic->sw_enabled = enabled;
292
		if (enabled)
293
			static_key_slow_dec_deferred(&apic_sw_disabled);
294
		else
295
			static_key_slow_inc(&apic_sw_disabled.key);
296

297
		atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
298
299
300
	}
}

301
static inline void kvm_apic_set_xapic_id(struct kvm_lapic *apic, u8 id)
302
{
303
	kvm_lapic_set_reg(apic, APIC_ID, id << 24);
304
	atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
305
306
307
308
}

static inline void kvm_apic_set_ldr(struct kvm_lapic *apic, u32 id)
{
309
	kvm_lapic_set_reg(apic, APIC_LDR, id);
310
	atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
311
312
}

313
314
315
316
317
static inline u32 kvm_apic_calc_x2apic_ldr(u32 id)
{
	return ((id >> 4) << 16) | (1 << (id & 0xf));
}

318
static inline void kvm_apic_set_x2apic_id(struct kvm_lapic *apic, u32 id)
319
{
320
	u32 ldr = kvm_apic_calc_x2apic_ldr(id);
321

322
323
	WARN_ON_ONCE(id != apic->vcpu->vcpu_id);

324
	kvm_lapic_set_reg(apic, APIC_ID, id);
325
	kvm_lapic_set_reg(apic, APIC_LDR, ldr);
326
	atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
327
328
}

Eddie Dong's avatar
Eddie Dong committed
329
330
static inline int apic_lvt_enabled(struct kvm_lapic *apic, int lvt_type)
{
331
	return !(kvm_lapic_get_reg(apic, lvt_type) & APIC_LVT_MASKED);
Eddie Dong's avatar
Eddie Dong committed
332
333
}

334
335
static inline int apic_lvtt_oneshot(struct kvm_lapic *apic)
{
336
	return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_ONESHOT;
337
338
}

Eddie Dong's avatar
Eddie Dong committed
339
340
static inline int apic_lvtt_period(struct kvm_lapic *apic)
{
341
	return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_PERIODIC;
342
343
344
345
}

static inline int apic_lvtt_tscdeadline(struct kvm_lapic *apic)
{
346
	return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_TSCDEADLINE;
Eddie Dong's avatar
Eddie Dong committed
347
348
}

349
350
351
352
353
static inline int apic_lvt_nmi_mode(u32 lvt_val)
{
	return (lvt_val & (APIC_MODE_MASK | APIC_LVT_MASKED)) == APIC_DM_NMI;
}

354
355
356
357
358
359
void kvm_apic_set_version(struct kvm_vcpu *vcpu)
{
	struct kvm_lapic *apic = vcpu->arch.apic;
	struct kvm_cpuid_entry2 *feat;
	u32 v = APIC_VERSION;

360
	if (!lapic_in_kernel(vcpu))
361
362
		return;

363
364
365
366
367
368
369
	/*
	 * KVM emulates 82093AA datasheet (with in-kernel IOAPIC implementation)
	 * which doesn't have EOI register; Some buggy OSes (e.g. Windows with
	 * Hyper-V role) disable EOI broadcast in lapic not checking for IOAPIC
	 * version first and level-triggered interrupts never get EOIed in
	 * IOAPIC.
	 */
370
	feat = kvm_find_cpuid_entry(apic->vcpu, 0x1, 0);
371
372
	if (feat && (feat->ecx & (1 << (X86_FEATURE_X2APIC & 31))) &&
	    !ioapic_in_kernel(vcpu->kvm))
373
		v |= APIC_LVR_DIRECTED_EOI;
374
	kvm_lapic_set_reg(apic, APIC_LVR, v);
375
376
}

377
static const unsigned int apic_lvt_mask[KVM_APIC_LVT_NUM] = {
378
	LVT_MASK ,      /* part LVTT mask, timer mode mask added at runtime */
Eddie Dong's avatar
Eddie Dong committed
379
380
381
382
383
384
385
386
	LVT_MASK | APIC_MODE_MASK,	/* LVTTHMR */
	LVT_MASK | APIC_MODE_MASK,	/* LVTPC */
	LINT_MASK, LINT_MASK,	/* LVT0-1 */
	LVT_MASK		/* LVTERR */
};

static int find_highest_vector(void *bitmap)
{
387
388
	int vec;
	u32 *reg;
Eddie Dong's avatar
Eddie Dong committed
389

390
391
392
393
	for (vec = MAX_APIC_VECTOR - APIC_VECTORS_PER_REG;
	     vec >= 0; vec -= APIC_VECTORS_PER_REG) {
		reg = bitmap + REG_POS(vec);
		if (*reg)
394
			return __fls(*reg) + vec;
395
	}
Eddie Dong's avatar
Eddie Dong committed
396

397
	return -1;
Eddie Dong's avatar
Eddie Dong committed
398
399
}

Michael S. Tsirkin's avatar
Michael S. Tsirkin committed
400
401
static u8 count_vectors(void *bitmap)
{
402
403
	int vec;
	u32 *reg;
Michael S. Tsirkin's avatar
Michael S. Tsirkin committed
404
	u8 count = 0;
405
406
407
408
409
410

	for (vec = 0; vec < MAX_APIC_VECTOR; vec += APIC_VECTORS_PER_REG) {
		reg = bitmap + REG_POS(vec);
		count += hweight32(*reg);
	}

Michael S. Tsirkin's avatar
Michael S. Tsirkin committed
411
412
413
	return count;
}

414
bool __kvm_apic_update_irr(u32 *pir, void *regs, int *max_irr)
415
{
416
	u32 i, vec;
417
418
419
420
421
	u32 pir_val, irr_val, prev_irr_val;
	int max_updated_irr;

	max_updated_irr = -1;
	*max_irr = -1;
422

423
	for (i = vec = 0; i <= 7; i++, vec += 32) {
424
		pir_val = READ_ONCE(pir[i]);
425
		irr_val = *((u32 *)(regs + APIC_IRR + i * 0x10));
426
		if (pir_val) {
427
			prev_irr_val = irr_val;
428
429
			irr_val |= xchg(&pir[i], 0);
			*((u32 *)(regs + APIC_IRR + i * 0x10)) = irr_val;
430
431
432
433
			if (prev_irr_val != irr_val) {
				max_updated_irr =
					__fls(irr_val ^ prev_irr_val) + vec;
			}
434
		}
435
		if (irr_val)
436
			*max_irr = __fls(irr_val) + vec;
437
	}
438

439
440
	return ((max_updated_irr != -1) &&
		(max_updated_irr == *max_irr));
441
}
442
443
EXPORT_SYMBOL_GPL(__kvm_apic_update_irr);

444
bool kvm_apic_update_irr(struct kvm_vcpu *vcpu, u32 *pir, int *max_irr)
445
446
447
{
	struct kvm_lapic *apic = vcpu->arch.apic;

448
	return __kvm_apic_update_irr(pir, apic->regs, max_irr);
449
}
450
451
EXPORT_SYMBOL_GPL(kvm_apic_update_irr);

452
static inline int apic_search_irr(struct kvm_lapic *apic)
Eddie Dong's avatar
Eddie Dong committed
453
{
454
	return find_highest_vector(apic->regs + APIC_IRR);
Eddie Dong's avatar
Eddie Dong committed
455
456
457
458
459
460
}

static inline int apic_find_highest_irr(struct kvm_lapic *apic)
{
	int result;

461
462
463
464
	/*
	 * Note that irr_pending is just a hint. It will be always
	 * true with virtual interrupt delivery enabled.
	 */
465
466
467
468
	if (!apic->irr_pending)
		return -1;

	result = apic_search_irr(apic);
Eddie Dong's avatar
Eddie Dong committed
469
470
471
472
473
	ASSERT(result == -1 || result >= 16);

	return result;
}

474
475
static inline void apic_clear_irr(int vec, struct kvm_lapic *apic)
{
476
477
478
479
	struct kvm_vcpu *vcpu;

	vcpu = apic->vcpu;

480
	if (unlikely(vcpu->arch.apicv_active)) {
481
		/* need to update RVI */
482
		kvm_lapic_clear_vector(vec, apic->regs + APIC_IRR);
483
		kvm_x86_ops.hwapic_irr_update(vcpu,
484
				apic_find_highest_irr(apic));
485
486
	} else {
		apic->irr_pending = false;
487
		kvm_lapic_clear_vector(vec, apic->regs + APIC_IRR);
488
489
		if (apic_search_irr(apic) != -1)
			apic->irr_pending = true;
490
	}
491
492
}

Michael S. Tsirkin's avatar
Michael S. Tsirkin committed
493
494
static inline void apic_set_isr(int vec, struct kvm_lapic *apic)
{
495
496
497
498
499
500
	struct kvm_vcpu *vcpu;

	if (__apic_test_and_set_vector(vec, apic->regs + APIC_ISR))
		return;

	vcpu = apic->vcpu;
501

Michael S. Tsirkin's avatar
Michael S. Tsirkin committed
502
	/*
503
504
505
	 * With APIC virtualization enabled, all caching is disabled
	 * because the processor can modify ISR under the hood.  Instead
	 * just set SVI.
Michael S. Tsirkin's avatar
Michael S. Tsirkin committed
506
	 */
507
	if (unlikely(vcpu->arch.apicv_active))
508
		kvm_x86_ops.hwapic_isr_update(vcpu, vec);
509
510
511
512
513
514
515
516
517
518
	else {
		++apic->isr_count;
		BUG_ON(apic->isr_count > MAX_APIC_VECTOR);
		/*
		 * ISR (in service register) bit is set when injecting an interrupt.
		 * The highest vector is injected. Thus the latest bit set matches
		 * the highest bit in ISR.
		 */
		apic->highest_isr_cache = vec;
	}
Michael S. Tsirkin's avatar
Michael S. Tsirkin committed
519
520
}

521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
static inline int apic_find_highest_isr(struct kvm_lapic *apic)
{
	int result;

	/*
	 * Note that isr_count is always 1, and highest_isr_cache
	 * is always -1, with APIC virtualization enabled.
	 */
	if (!apic->isr_count)
		return -1;
	if (likely(apic->highest_isr_cache != -1))
		return apic->highest_isr_cache;

	result = find_highest_vector(apic->regs + APIC_ISR);
	ASSERT(result == -1 || result >= 16);

	return result;
}

Michael S. Tsirkin's avatar
Michael S. Tsirkin committed
540
541
static inline void apic_clear_isr(int vec, struct kvm_lapic *apic)
{
542
543
544
545
546
547
548
549
550
551
552
553
554
	struct kvm_vcpu *vcpu;
	if (!__apic_test_and_clear_vector(vec, apic->regs + APIC_ISR))
		return;

	vcpu = apic->vcpu;

	/*
	 * We do get here for APIC virtualization enabled if the guest
	 * uses the Hyper-V APIC enlightenment.  In this case we may need
	 * to trigger a new interrupt delivery by writing the SVI field;
	 * on the other hand isr_count and highest_isr_cache are unused
	 * and must be left alone.
	 */
555
	if (unlikely(vcpu->arch.apicv_active))
556
		kvm_x86_ops.hwapic_isr_update(vcpu,
557
558
					       apic_find_highest_isr(apic));
	else {
Michael S. Tsirkin's avatar
Michael S. Tsirkin committed
559
		--apic->isr_count;
560
561
562
		BUG_ON(apic->isr_count < 0);
		apic->highest_isr_cache = -1;
	}
Michael S. Tsirkin's avatar
Michael S. Tsirkin committed
563
564
}

565
566
int kvm_lapic_find_highest_irr(struct kvm_vcpu *vcpu)
{
567
568
569
570
571
	/* This may race with setting of irr in __apic_accept_irq() and
	 * value returned may be wrong, but kvm_vcpu_kick() in __apic_accept_irq
	 * will cause vmexit immediately and the value will be recalculated
	 * on the next vmentry.
	 */
572
	return apic_find_highest_irr(vcpu->arch.apic);
573
}
574
EXPORT_SYMBOL_GPL(kvm_lapic_find_highest_irr);
575

576
static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
577
			     int vector, int level, int trig_mode,
578
			     struct dest_map *dest_map);
579

580
int kvm_apic_set_irq(struct kvm_vcpu *vcpu, struct kvm_lapic_irq *irq,
581
		     struct dest_map *dest_map)
Eddie Dong's avatar
Eddie Dong committed
582
{
583
	struct kvm_lapic *apic = vcpu->arch.apic;
584

585
	return __apic_accept_irq(apic, irq->delivery_mode, irq->vector,
586
			irq->level, irq->trig_mode, dest_map);
Eddie Dong's avatar
Eddie Dong committed
587
588
}

589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
static int __pv_send_ipi(unsigned long *ipi_bitmap, struct kvm_apic_map *map,
			 struct kvm_lapic_irq *irq, u32 min)
{
	int i, count = 0;
	struct kvm_vcpu *vcpu;

	if (min > map->max_apic_id)
		return 0;

	for_each_set_bit(i, ipi_bitmap,
		min((u32)BITS_PER_LONG, (map->max_apic_id - min + 1))) {
		if (map->phys_map[min + i]) {
			vcpu = map->phys_map[min + i]->vcpu;
			count += kvm_apic_set_irq(vcpu, irq, NULL);
		}
	}

	return count;
}

609
int kvm_pv_send_ipi(struct kvm *kvm, unsigned long ipi_bitmap_low,
610
		    unsigned long ipi_bitmap_high, u32 min,
611
612
613
614
615
		    unsigned long icr, int op_64_bit)
{
	struct kvm_apic_map *map;
	struct kvm_lapic_irq irq = {0};
	int cluster_size = op_64_bit ? 64 : 32;
616
617
618
619
	int count;

	if (icr & (APIC_DEST_MASK | APIC_SHORT_MASK))
		return -KVM_EINVAL;
620
621
622
623
624
625
626
627
628

	irq.vector = icr & APIC_VECTOR_MASK;
	irq.delivery_mode = icr & APIC_MODE_MASK;
	irq.level = (icr & APIC_INT_ASSERT) != 0;
	irq.trig_mode = icr & APIC_INT_LEVELTRIG;

	rcu_read_lock();
	map = rcu_dereference(kvm->arch.apic_map);

629
630
631
632
633
	count = -EOPNOTSUPP;
	if (likely(map)) {
		count = __pv_send_ipi(&ipi_bitmap_low, map, &irq, min);
		min += cluster_size;
		count += __pv_send_ipi(&ipi_bitmap_high, map, &irq, min);
634
635
636
637
638
639
	}

	rcu_read_unlock();
	return count;
}

640
641
static int pv_eoi_put_user(struct kvm_vcpu *vcpu, u8 val)
{
642
643
644

	return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, &val,
				      sizeof(val));
645
646
647
648
}

static int pv_eoi_get_user(struct kvm_vcpu *vcpu, u8 *val)
{
649
650
651

	return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, val,
				      sizeof(*val));
652
653
654
655
656
657
658
659
660
661
}

static inline bool pv_eoi_enabled(struct kvm_vcpu *vcpu)
{
	return vcpu->arch.pv_eoi.msr_val & KVM_MSR_ENABLED;
}

static bool pv_eoi_get_pending(struct kvm_vcpu *vcpu)
{
	u8 val;
662
	if (pv_eoi_get_user(vcpu, &val) < 0) {
663
		printk(KERN_WARNING "Can't read EOI MSR value: 0x%llx\n",
664
			   (unsigned long long)vcpu->arch.pv_eoi.msr_val);
665
666
		return false;
	}
667
668
669
670
671
672
	return val & 0x1;
}

static void pv_eoi_set_pending(struct kvm_vcpu *vcpu)
{
	if (pv_eoi_put_user(vcpu, KVM_PV_EOI_ENABLED) < 0) {
673
		printk(KERN_WARNING "Can't set EOI MSR value: 0x%llx\n",
674
			   (unsigned long long)vcpu->arch.pv_eoi.msr_val);
675
676
677
678
679
680
681
682
		return;
	}
	__set_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
}

static void pv_eoi_clr_pending(struct kvm_vcpu *vcpu)
{
	if (pv_eoi_put_user(vcpu, KVM_PV_EOI_DISABLED) < 0) {
683
		printk(KERN_WARNING "Can't clear EOI MSR value: 0x%llx\n",
684
			   (unsigned long long)vcpu->arch.pv_eoi.msr_val);
685
686
687
688
689
		return;
	}
	__clear_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
}

690
691
static int apic_has_interrupt_for_ppr(struct kvm_lapic *apic, u32 ppr)
{
692
	int highest_irr;
693
	if (apic->vcpu->arch.apicv_active)
694
		highest_irr = kvm_x86_ops.sync_pir_to_irr(apic->vcpu);
695
696
	else
		highest_irr = apic_find_highest_irr(apic);
697
698
699
700
701
702
	if (highest_irr == -1 || (highest_irr & 0xF0) <= ppr)
		return -1;
	return highest_irr;
}

static bool __apic_update_ppr(struct kvm_lapic *apic, u32 *new_ppr)
Eddie Dong's avatar
Eddie Dong committed
703
{
704
	u32 tpr, isrv, ppr, old_ppr;
Eddie Dong's avatar
Eddie Dong committed
705
706
	int isr;

707
708
	old_ppr = kvm_lapic_get_reg(apic, APIC_PROCPRI);
	tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI);
Eddie Dong's avatar
Eddie Dong committed
709
710
711
712
713
714
715
716
	isr = apic_find_highest_isr(apic);
	isrv = (isr != -1) ? isr : 0;

	if ((tpr & 0xf0) >= (isrv & 0xf0))
		ppr = tpr & 0xff;
	else
		ppr = isrv & 0xf0;

717
718
	*new_ppr = ppr;
	if (old_ppr != ppr)
719
		kvm_lapic_set_reg(apic, APIC_PROCPRI, ppr);
720
721
722
723
724
725
726
727

	return ppr < old_ppr;
}

static void apic_update_ppr(struct kvm_lapic *apic)
{
	u32 ppr;

728
729
	if (__apic_update_ppr(apic, &ppr) &&
	    apic_has_interrupt_for_ppr(apic, ppr) != -1)
730
		kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
Eddie Dong's avatar
Eddie Dong committed
731
732
}

733
734
735
736
737
738
void kvm_apic_update_ppr(struct kvm_vcpu *vcpu)
{
	apic_update_ppr(vcpu->arch.apic);
}
EXPORT_SYMBOL_GPL(kvm_apic_update_ppr);

Eddie Dong's avatar
Eddie Dong committed
739
740
static void apic_set_tpr(struct kvm_lapic *apic, u32 tpr)
{
741
	kvm_lapic_set_reg(apic, APIC_TASKPRI, tpr);
Eddie Dong's avatar
Eddie Dong committed
742
743
744
	apic_update_ppr(apic);
}

745
static bool kvm_apic_broadcast(struct kvm_lapic *apic, u32 mda)
746
{
747
748
	return mda == (apic_x2apic_mode(apic) ?
			X2APIC_BROADCAST : APIC_BROADCAST);
749
750
}

751
static bool kvm_apic_match_physical_addr(struct kvm_lapic *apic, u32 mda)
Eddie Dong's avatar
Eddie Dong committed
752
{
753
754
755
756
	if (kvm_apic_broadcast(apic, mda))
		return true;

	if (apic_x2apic_mode(apic))
757
		return mda == kvm_x2apic_id(apic);
758

759
760
761
762
763
764
765
766
767
	/*
	 * Hotplug hack: Make LAPIC in xAPIC mode also accept interrupts as if
	 * it were in x2APIC mode.  Hotplugged VCPUs start in xAPIC mode and
	 * this allows unique addressing of VCPUs with APIC ID over 0xff.
	 * The 0xff condition is needed because writeable xAPIC ID.
	 */
	if (kvm_x2apic_id(apic) > 0xff && mda == kvm_x2apic_id(apic))
		return true;

768
	return mda == kvm_xapic_id(apic);
Eddie Dong's avatar
Eddie Dong committed
769
770
}

771
static bool kvm_apic_match_logical_addr(struct kvm_lapic *apic, u32 mda)
Eddie Dong's avatar
Eddie Dong committed
772
{
Gleb Natapov's avatar
Gleb Natapov committed
773
774
	u32 logical_id;

775
	if (kvm_apic_broadcast(apic, mda))
776
		return true;
777

778
	logical_id = kvm_lapic_get_reg(apic, APIC_LDR);
Eddie Dong's avatar
Eddie Dong committed
779

780
	if (apic_x2apic_mode(apic))
781
782
		return ((logical_id >> 16) == (mda >> 16))
		       && (logical_id & mda & 0xffff) != 0;
Eddie Dong's avatar
Eddie Dong committed
783

784
	logical_id = GET_APIC_LOGICAL_ID(logical_id);
Eddie Dong's avatar
Eddie Dong committed
785

786
	switch (kvm_lapic_get_reg(apic, APIC_DFR)) {
Eddie Dong's avatar
Eddie Dong committed
787
	case APIC_DFR_FLAT:
788
		return (logical_id & mda) != 0;
Eddie Dong's avatar
Eddie Dong committed
789
	case APIC_DFR_CLUSTER:
790
791
		return ((logical_id >> 4) == (mda >> 4))
		       && (logical_id & mda & 0xf) != 0;
Eddie Dong's avatar
Eddie Dong committed
792
	default:
793
		return false;
Eddie Dong's avatar
Eddie Dong committed
794
795
796
	}
}

797
798
/* The KVM local APIC implementation has two quirks:
 *
799
800
801
 *  - Real hardware delivers interrupts destined to x2APIC ID > 0xff to LAPICs
 *    in xAPIC mode if the "destination & 0xff" matches its xAPIC ID.
 *    KVM doesn't do that aliasing.
802
803
804
805
806
807
808
809
810
811
 *
 *  - in-kernel IOAPIC messages have to be delivered directly to
 *    x2APIC, because the kernel does not support interrupt remapping.
 *    In order to support broadcast without interrupt remapping, x2APIC
 *    rewrites the destination of non-IPI messages from APIC_BROADCAST
 *    to X2APIC_BROADCAST.
 *
 * The broadcast quirk can be disabled with KVM_CAP_X2APIC_API.  This is
 * important when userspace wants to use x2APIC-format MSIs, because
 * APIC_BROADCAST (0xff) is a legal route for "cluster 0, CPUs 0-7".
812
 */
813
814
static u32 kvm_apic_mda(struct kvm_vcpu *vcpu, unsigned int dest_id,
		struct kvm_lapic *source, struct kvm_lapic *target)
815
816
817
{
	bool ipi = source != NULL;

818
	if (!vcpu->kvm->arch.x2apic_broadcast_quirk_disabled &&
819
	    !ipi && dest_id == APIC_BROADCAST && apic_x2apic_mode(target))
820
821
		return X2APIC_BROADCAST;

822
	return dest_id;
823
824
}

825
bool kvm_apic_match_dest(struct kvm_vcpu *vcpu, struct kvm_lapic *source,
826
			   int shorthand, unsigned int dest, int dest_mode)
Eddie Dong's avatar
Eddie Dong committed
827
{
828
	struct kvm_lapic *target = vcpu->arch.apic;
829
	u32 mda = kvm_apic_mda(vcpu, dest, source, target);
Eddie Dong's avatar
Eddie Dong committed
830

Zachary Amsden's avatar
Zachary Amsden committed
831
	ASSERT(target);
832
	switch (shorthand) {
Eddie Dong's avatar
Eddie Dong committed
833
	case APIC_DEST_NOSHORT:
834
		if (dest_mode == APIC_DEST_PHYSICAL)
835
			return kvm_apic_match_physical_addr(target, mda);
836
		else
837
			return kvm_apic_match_logical_addr(target, mda);
Eddie Dong's avatar
Eddie Dong committed
838
	case APIC_DEST_SELF:
839
		return target == source;
Eddie Dong's avatar
Eddie Dong committed
840
	case APIC_DEST_ALLINC:
841
		return true;
Eddie Dong's avatar
Eddie Dong committed
842
	case APIC_DEST_ALLBUT:
843
		return target != source;
Eddie Dong's avatar
Eddie Dong committed
844
	default:
845
		return false;
Eddie Dong's avatar
Eddie Dong committed
846
847
	}
}
848
EXPORT_SYMBOL_GPL(kvm_apic_match_dest);
Eddie Dong's avatar
Eddie Dong committed
849

850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
int kvm_vector_to_index(u32 vector, u32 dest_vcpus,
		       const unsigned long *bitmap, u32 bitmap_size)
{
	u32 mod;
	int i, idx = -1;

	mod = vector % dest_vcpus;

	for (i = 0; i <= mod; i++) {
		idx = find_next_bit(bitmap, bitmap_size, idx + 1);
		BUG_ON(idx == bitmap_size);
	}

	return idx;
}

866
867
868
869
870
871
872
873
874
static void kvm_apic_disabled_lapic_found(struct kvm *kvm)
{
	if (!kvm->arch.disabled_lapic_found) {
		kvm->arch.disabled_lapic_found = true;
		printk(KERN_INFO
		       "Disabled LAPIC found during irq injection\n");
	}
}

875
876
static bool kvm_apic_is_broadcast_dest(struct kvm *kvm, struct kvm_lapic **src,
		struct kvm_lapic_irq *irq, struct kvm_apic_map *map)
877
{
878
879
880
881
882
883
884
885
886
887
888
889
	if (kvm->arch.x2apic_broadcast_quirk_disabled) {
		if ((irq->dest_id == APIC_BROADCAST &&
				map->mode != KVM_APIC_MODE_X2APIC))
			return true;
		if (irq->dest_id == X2APIC_BROADCAST)
			return true;
	} else {
		bool x2apic_ipi = src && *src && apic_x2apic_mode(*src);
		if (irq->dest_id == (x2apic_ipi ?
		                     X2APIC_BROADCAST : APIC_BROADCAST))
			return true;
	}
890

891
892
	return false;
}
893

894
895
896
897
898
899
900
901
902
903
904
905
906
/* Return true if the interrupt can be handled by using *bitmap as index mask
 * for valid destinations in *dst array.
 * Return false if kvm_apic_map_get_dest_lapic did nothing useful.
 * Note: we may have zero kvm_lapic destinations when we return true, which
 * means that the interrupt should be dropped.  In this case, *bitmap would be
 * zero and *dst undefined.
 */
static inline bool kvm_apic_map_get_dest_lapic(struct kvm *kvm,
		struct kvm_lapic **src, struct kvm_lapic_irq *irq,
		struct kvm_apic_map *map, struct kvm_lapic ***dst,
		unsigned long *bitmap)
{
	int i, lowest;
907

908
909
910
911
912
	if (irq->shorthand == APIC_DEST_SELF && src) {
		*dst = src;
		*bitmap = 1;
		return true;
	} else if (irq->shorthand)
913
914
		return false;

915
	if (!map || kvm_apic_is_broadcast_dest(kvm, src, irq, map))
916
917
		return false;

918
	if (irq->dest_mode == APIC_DEST_PHYSICAL) {
919
		if (irq->dest_id > map->max_apic_id) {
920
921
			*bitmap = 0;
		} else {
Paolo Bonzini's avatar
Paolo Bonzini committed
922
923
			u32 dest_id = array_index_nospec(irq->dest_id, map->max_apic_id + 1);
			*dst = &map->phys_map[dest_id];
924
925
			*bitmap = 1;
		}
926
		return true;
927
	}
928

929
930
931
	*bitmap = 0;
	if (!kvm_apic_map_get_logical_dest(map, irq->dest_id, dst,
				(u16 *)bitmap))
932
		return false;
933

934
935
	if (!kvm_lowest_prio_delivery(irq))
		return true;
936

937
938
939
940
941
942
943
944
945
946
	if (!kvm_vector_hashing_enabled()) {
		lowest = -1;
		for_each_set_bit(i, bitmap, 16) {
			if (!(*dst)[i])
				continue;
			if (lowest < 0)
				lowest = i;
			else if (kvm_apic_compare_prio((*dst)[i]->vcpu,
						(*dst)[lowest]->vcpu) < 0)
				lowest = i;
947
		}
948
949
950
	} else {
		if (!*bitmap)
			return true;
951

952
953
		lowest = kvm_vector_to_index(irq->vector, hweight16(*bitmap),
				bitmap, 16);
954

955
956
957
958
959
960
		if (!(*dst)[lowest]) {
			kvm_apic_disabled_lapic_found(kvm);
			*bitmap = 0;
			return true;
		}
	}
961

962
	*bitmap = (lowest >= 0) ? 1 << lowest : 0;
963

964
965
	return true;
}
966

967
968
969
970
971
972
973
974
bool kvm_irq_delivery_to_apic_fast(struct kvm *kvm, struct kvm_lapic *src,
		struct kvm_lapic_irq *irq, int *r, struct dest_map *dest_map)
{
	struct kvm_apic_map *map;
	unsigned long bitmap;
	struct kvm_lapic **dst = NULL;
	int i;
	bool ret;
975

976
	*r = -1;
977

978
979
980
981
	if (irq->shorthand == APIC_DEST_SELF) {
		*r = kvm_apic_set_irq(src->vcpu, irq, dest_map);
		return true;
	}
982

983
984
	rcu_read_lock();
	map = rcu_dereference(kvm->arch.apic_map);
985

986
	ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dst, &bitmap);
987
988
	if (ret) {
		*r = 0;
989
990
991
992
		for_each_set_bit(i, &bitmap, 16) {
			if (!dst[i])
				continue;
			*r += kvm_apic_set_irq(dst[i]->vcpu, irq, dest_map);
993
		}
994
	}
995
996
997
998
999

	rcu_read_unlock();
	return ret;
}

1000
/*
Miaohe Lin's avatar
Miaohe Lin committed
1001
 * This routine tries to handle interrupts in posted mode, here is how
1002
1003
1004
1005
 * it deals with different cases:
 * - For single-destination interrupts, handle it in posted mode
 * - Else if vector hashing is enabled and it is a lowest-priority
 *   interrupt, handle it in posted mode and use the following mechanism
1006
 *   to find the destination vCPU.
1007
1008
1009
1010
1011
1012
1013
 *	1. For lowest-priority interrupts, store all the possible
 *	   destination vCPUs in an array.
 *	2. Use "guest vector % max number of destination vCPUs" to find
 *	   the right destination vCPU in the array for the lowest-priority
 *	   interrupt.
 * - Otherwise, use remapped mode to inject the interrupt.
 */
1014
1015
1016
1017
bool kvm_intr_is_single_vcpu_fast(struct kvm *kvm, struct kvm_lapic_irq *irq,
			struct kvm_vcpu **dest_vcpu)
{
	struct kvm_apic_map *map;
1018
1019
	unsigned long bitmap;
	struct kvm_lapic **dst = NULL;
1020
1021
1022
1023
1024
1025
1026
1027
	bool ret = false;

	if (irq->shorthand)
		return false;

	rcu_read_lock();
	map = rcu_dereference(kvm->arch.apic_map);

1028
1029
1030
	if (kvm_apic_map_get_dest_lapic(kvm, NULL, irq, map, &dst, &bitmap) &&
			hweight16(bitmap) == 1) {
		unsigned long i = find_first_bit(&bitmap, 16);
1031

1032
1033
1034
		if (dst[i]) {
			*dest_vcpu = dst[i]->vcpu;
			ret = true;
1035
		}
1036
1037
1038
1039
1040
1041
	}

	rcu_read_unlock();
	return ret;
}

Eddie Dong's avatar
Eddie Dong committed
1042
1043
1044
1045
1046
/*
 * Add a pending IRQ into lapic.
 * Return 1 if successfully added and 0 if discarded.
 */
static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
1047
			     int vector, int level, int trig_mode,
1048
			     struct dest_map *dest_map)
Eddie Dong's avatar
Eddie Dong committed
1049
{
1050
	int result = 0;
1051
	struct kvm_vcpu *vcpu = apic->vcpu;