xref: /openbmc/linux/drivers/pci/vgaarb.c (revision b421364a)
1 // SPDX-License-Identifier: MIT
2 /*
3  * vgaarb.c: Implements the VGA arbitration. For details refer to
4  * Documentation/gpu/vgaarbiter.rst
5  *
6  * (C) Copyright 2005 Benjamin Herrenschmidt <benh@kernel.crashing.org>
7  * (C) Copyright 2007 Paulo R. Zanoni <przanoni@gmail.com>
8  * (C) Copyright 2007, 2009 Tiago Vignatti <vignatti@freedesktop.org>
9  */
10 
11 #define pr_fmt(fmt) "vgaarb: " fmt
12 
13 #define vgaarb_dbg(dev, fmt, arg...)	dev_dbg(dev, "vgaarb: " fmt, ##arg)
14 #define vgaarb_info(dev, fmt, arg...)	dev_info(dev, "vgaarb: " fmt, ##arg)
15 #define vgaarb_err(dev, fmt, arg...)	dev_err(dev, "vgaarb: " fmt, ##arg)
16 
17 #include <linux/module.h>
18 #include <linux/kernel.h>
19 #include <linux/pci.h>
20 #include <linux/errno.h>
21 #include <linux/init.h>
22 #include <linux/list.h>
23 #include <linux/sched/signal.h>
24 #include <linux/wait.h>
25 #include <linux/spinlock.h>
26 #include <linux/poll.h>
27 #include <linux/miscdevice.h>
28 #include <linux/slab.h>
29 #include <linux/screen_info.h>
30 #include <linux/vt.h>
31 #include <linux/console.h>
32 #include <linux/acpi.h>
33 
34 #include <linux/uaccess.h>
35 
36 #include <linux/vgaarb.h>
37 
38 static void vga_arbiter_notify_clients(void);
39 /*
40  * We keep a list of all vga devices in the system to speed
41  * up the various operations of the arbiter
42  */
43 struct vga_device {
44 	struct list_head list;
45 	struct pci_dev *pdev;
46 	unsigned int decodes;	/* what does it decodes */
47 	unsigned int owns;	/* what does it owns */
48 	unsigned int locks;	/* what does it locks */
49 	unsigned int io_lock_cnt;	/* legacy IO lock count */
50 	unsigned int mem_lock_cnt;	/* legacy MEM lock count */
51 	unsigned int io_norm_cnt;	/* normal IO count */
52 	unsigned int mem_norm_cnt;	/* normal MEM count */
53 	bool bridge_has_one_vga;
54 	bool is_firmware_default;	/* device selected by firmware */
55 	unsigned int (*set_decode)(struct pci_dev *pdev, bool decode);
56 };
57 
58 static LIST_HEAD(vga_list);
59 static int vga_count, vga_decode_count;
60 static bool vga_arbiter_used;
61 static DEFINE_SPINLOCK(vga_lock);
62 static DECLARE_WAIT_QUEUE_HEAD(vga_wait_queue);
63 
64 
65 static const char *vga_iostate_to_str(unsigned int iostate)
66 {
67 	/* Ignore VGA_RSRC_IO and VGA_RSRC_MEM */
68 	iostate &= VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
69 	switch (iostate) {
70 	case VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM:
71 		return "io+mem";
72 	case VGA_RSRC_LEGACY_IO:
73 		return "io";
74 	case VGA_RSRC_LEGACY_MEM:
75 		return "mem";
76 	}
77 	return "none";
78 }
79 
80 static int vga_str_to_iostate(char *buf, int str_size, unsigned int *io_state)
81 {
82 	/* we could in theory hand out locks on IO and mem
83 	 * separately to userspace but it can cause deadlocks */
84 	if (strncmp(buf, "none", 4) == 0) {
85 		*io_state = VGA_RSRC_NONE;
86 		return 1;
87 	}
88 
89 	/* XXX We're not chekcing the str_size! */
90 	if (strncmp(buf, "io+mem", 6) == 0)
91 		goto both;
92 	else if (strncmp(buf, "io", 2) == 0)
93 		goto both;
94 	else if (strncmp(buf, "mem", 3) == 0)
95 		goto both;
96 	return 0;
97 both:
98 	*io_state = VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
99 	return 1;
100 }
101 
102 /* this is only used a cookie - it should not be dereferenced */
103 static struct pci_dev *vga_default;
104 
105 /* Find somebody in our list */
106 static struct vga_device *vgadev_find(struct pci_dev *pdev)
107 {
108 	struct vga_device *vgadev;
109 
110 	list_for_each_entry(vgadev, &vga_list, list)
111 		if (pdev == vgadev->pdev)
112 			return vgadev;
113 	return NULL;
114 }
115 
116 /**
117  * vga_default_device - return the default VGA device, for vgacon
118  *
119  * This can be defined by the platform. The default implementation
120  * is rather dumb and will probably only work properly on single
121  * vga card setups and/or x86 platforms.
122  *
123  * If your VGA default device is not PCI, you'll have to return
124  * NULL here. In this case, I assume it will not conflict with
125  * any PCI card. If this is not true, I'll have to define two archs
126  * hooks for enabling/disabling the VGA default device if that is
127  * possible. This may be a problem with real _ISA_ VGA cards, in
128  * addition to a PCI one. I don't know at this point how to deal
129  * with that card. Can theirs IOs be disabled at all ? If not, then
130  * I suppose it's a matter of having the proper arch hook telling
131  * us about it, so we basically never allow anybody to succeed a
132  * vga_get()...
133  */
134 struct pci_dev *vga_default_device(void)
135 {
136 	return vga_default;
137 }
138 EXPORT_SYMBOL_GPL(vga_default_device);
139 
140 void vga_set_default_device(struct pci_dev *pdev)
141 {
142 	if (vga_default == pdev)
143 		return;
144 
145 	pci_dev_put(vga_default);
146 	vga_default = pci_dev_get(pdev);
147 }
148 
149 /**
150  * vga_remove_vgacon - deactivete vga console
151  *
152  * Unbind and unregister vgacon in case pdev is the default vga
153  * device.  Can be called by gpu drivers on initialization to make
154  * sure vga register access done by vgacon will not disturb the
155  * device.
156  *
157  * @pdev: pci device.
158  */
159 #if !defined(CONFIG_VGA_CONSOLE)
160 int vga_remove_vgacon(struct pci_dev *pdev)
161 {
162 	return 0;
163 }
164 #elif !defined(CONFIG_DUMMY_CONSOLE)
165 int vga_remove_vgacon(struct pci_dev *pdev)
166 {
167 	return -ENODEV;
168 }
169 #else
170 int vga_remove_vgacon(struct pci_dev *pdev)
171 {
172 	int ret = 0;
173 
174 	if (pdev != vga_default)
175 		return 0;
176 	vgaarb_info(&pdev->dev, "deactivate vga console\n");
177 
178 	console_lock();
179 	if (con_is_bound(&vga_con))
180 		ret = do_take_over_console(&dummy_con, 0,
181 					   MAX_NR_CONSOLES - 1, 1);
182 	if (ret == 0) {
183 		ret = do_unregister_con_driver(&vga_con);
184 
185 		/* Ignore "already unregistered". */
186 		if (ret == -ENODEV)
187 			ret = 0;
188 	}
189 	console_unlock();
190 
191 	return ret;
192 }
193 #endif
194 EXPORT_SYMBOL(vga_remove_vgacon);
195 
196 /* If we don't ever use VGA arb we should avoid
197    turning off anything anywhere due to old X servers getting
198    confused about the boot device not being VGA */
199 static void vga_check_first_use(void)
200 {
201 	/* we should inform all GPUs in the system that
202 	 * VGA arb has occurred and to try and disable resources
203 	 * if they can */
204 	if (!vga_arbiter_used) {
205 		vga_arbiter_used = true;
206 		vga_arbiter_notify_clients();
207 	}
208 }
209 
210 static struct vga_device *__vga_tryget(struct vga_device *vgadev,
211 				       unsigned int rsrc)
212 {
213 	struct device *dev = &vgadev->pdev->dev;
214 	unsigned int wants, legacy_wants, match;
215 	struct vga_device *conflict;
216 	unsigned int pci_bits;
217 	u32 flags = 0;
218 
219 	/* Account for "normal" resources to lock. If we decode the legacy,
220 	 * counterpart, we need to request it as well
221 	 */
222 	if ((rsrc & VGA_RSRC_NORMAL_IO) &&
223 	    (vgadev->decodes & VGA_RSRC_LEGACY_IO))
224 		rsrc |= VGA_RSRC_LEGACY_IO;
225 	if ((rsrc & VGA_RSRC_NORMAL_MEM) &&
226 	    (vgadev->decodes & VGA_RSRC_LEGACY_MEM))
227 		rsrc |= VGA_RSRC_LEGACY_MEM;
228 
229 	vgaarb_dbg(dev, "%s: %d\n", __func__, rsrc);
230 	vgaarb_dbg(dev, "%s: owns: %d\n", __func__, vgadev->owns);
231 
232 	/* Check what resources we need to acquire */
233 	wants = rsrc & ~vgadev->owns;
234 
235 	/* We already own everything, just mark locked & bye bye */
236 	if (wants == 0)
237 		goto lock_them;
238 
239 	/* We don't need to request a legacy resource, we just enable
240 	 * appropriate decoding and go
241 	 */
242 	legacy_wants = wants & VGA_RSRC_LEGACY_MASK;
243 	if (legacy_wants == 0)
244 		goto enable_them;
245 
246 	/* Ok, we don't, let's find out how we need to kick off */
247 	list_for_each_entry(conflict, &vga_list, list) {
248 		unsigned int lwants = legacy_wants;
249 		unsigned int change_bridge = 0;
250 
251 		/* Don't conflict with myself */
252 		if (vgadev == conflict)
253 			continue;
254 
255 		/* We have a possible conflict. before we go further, we must
256 		 * check if we sit on the same bus as the conflicting device.
257 		 * if we don't, then we must tie both IO and MEM resources
258 		 * together since there is only a single bit controlling
259 		 * VGA forwarding on P2P bridges
260 		 */
261 		if (vgadev->pdev->bus != conflict->pdev->bus) {
262 			change_bridge = 1;
263 			lwants = VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
264 		}
265 
266 		/* Check if the guy has a lock on the resource. If he does,
267 		 * return the conflicting entry
268 		 */
269 		if (conflict->locks & lwants)
270 			return conflict;
271 
272 		/* Ok, now check if it owns the resource we want.  We can
273 		 * lock resources that are not decoded, therefore a device
274 		 * can own resources it doesn't decode.
275 		 */
276 		match = lwants & conflict->owns;
277 		if (!match)
278 			continue;
279 
280 		/* looks like he doesn't have a lock, we can steal
281 		 * them from him
282 		 */
283 
284 		flags = 0;
285 		pci_bits = 0;
286 
287 		/* If we can't control legacy resources via the bridge, we
288 		 * also need to disable normal decoding.
289 		 */
290 		if (!conflict->bridge_has_one_vga) {
291 			if ((match & conflict->decodes) & VGA_RSRC_LEGACY_MEM)
292 				pci_bits |= PCI_COMMAND_MEMORY;
293 			if ((match & conflict->decodes) & VGA_RSRC_LEGACY_IO)
294 				pci_bits |= PCI_COMMAND_IO;
295 
296 			if (pci_bits)
297 				flags |= PCI_VGA_STATE_CHANGE_DECODES;
298 		}
299 
300 		if (change_bridge)
301 			flags |= PCI_VGA_STATE_CHANGE_BRIDGE;
302 
303 		pci_set_vga_state(conflict->pdev, false, pci_bits, flags);
304 		conflict->owns &= ~match;
305 
306 		/* If we disabled normal decoding, reflect it in owns */
307 		if (pci_bits & PCI_COMMAND_MEMORY)
308 			conflict->owns &= ~VGA_RSRC_NORMAL_MEM;
309 		if (pci_bits & PCI_COMMAND_IO)
310 			conflict->owns &= ~VGA_RSRC_NORMAL_IO;
311 	}
312 
313 enable_them:
314 	/* ok dude, we got it, everybody conflicting has been disabled, let's
315 	 * enable us.  Mark any bits in "owns" regardless of whether we
316 	 * decoded them.  We can lock resources we don't decode, therefore
317 	 * we must track them via "owns".
318 	 */
319 	flags = 0;
320 	pci_bits = 0;
321 
322 	if (!vgadev->bridge_has_one_vga) {
323 		flags |= PCI_VGA_STATE_CHANGE_DECODES;
324 		if (wants & (VGA_RSRC_LEGACY_MEM|VGA_RSRC_NORMAL_MEM))
325 			pci_bits |= PCI_COMMAND_MEMORY;
326 		if (wants & (VGA_RSRC_LEGACY_IO|VGA_RSRC_NORMAL_IO))
327 			pci_bits |= PCI_COMMAND_IO;
328 	}
329 	if (wants & VGA_RSRC_LEGACY_MASK)
330 		flags |= PCI_VGA_STATE_CHANGE_BRIDGE;
331 
332 	pci_set_vga_state(vgadev->pdev, true, pci_bits, flags);
333 
334 	vgadev->owns |= wants;
335 lock_them:
336 	vgadev->locks |= (rsrc & VGA_RSRC_LEGACY_MASK);
337 	if (rsrc & VGA_RSRC_LEGACY_IO)
338 		vgadev->io_lock_cnt++;
339 	if (rsrc & VGA_RSRC_LEGACY_MEM)
340 		vgadev->mem_lock_cnt++;
341 	if (rsrc & VGA_RSRC_NORMAL_IO)
342 		vgadev->io_norm_cnt++;
343 	if (rsrc & VGA_RSRC_NORMAL_MEM)
344 		vgadev->mem_norm_cnt++;
345 
346 	return NULL;
347 }
348 
349 static void __vga_put(struct vga_device *vgadev, unsigned int rsrc)
350 {
351 	struct device *dev = &vgadev->pdev->dev;
352 	unsigned int old_locks = vgadev->locks;
353 
354 	vgaarb_dbg(dev, "%s\n", __func__);
355 
356 	/* Update our counters, and account for equivalent legacy resources
357 	 * if we decode them
358 	 */
359 	if ((rsrc & VGA_RSRC_NORMAL_IO) && vgadev->io_norm_cnt > 0) {
360 		vgadev->io_norm_cnt--;
361 		if (vgadev->decodes & VGA_RSRC_LEGACY_IO)
362 			rsrc |= VGA_RSRC_LEGACY_IO;
363 	}
364 	if ((rsrc & VGA_RSRC_NORMAL_MEM) && vgadev->mem_norm_cnt > 0) {
365 		vgadev->mem_norm_cnt--;
366 		if (vgadev->decodes & VGA_RSRC_LEGACY_MEM)
367 			rsrc |= VGA_RSRC_LEGACY_MEM;
368 	}
369 	if ((rsrc & VGA_RSRC_LEGACY_IO) && vgadev->io_lock_cnt > 0)
370 		vgadev->io_lock_cnt--;
371 	if ((rsrc & VGA_RSRC_LEGACY_MEM) && vgadev->mem_lock_cnt > 0)
372 		vgadev->mem_lock_cnt--;
373 
374 	/* Just clear lock bits, we do lazy operations so we don't really
375 	 * have to bother about anything else at this point
376 	 */
377 	if (vgadev->io_lock_cnt == 0)
378 		vgadev->locks &= ~VGA_RSRC_LEGACY_IO;
379 	if (vgadev->mem_lock_cnt == 0)
380 		vgadev->locks &= ~VGA_RSRC_LEGACY_MEM;
381 
382 	/* Kick the wait queue in case somebody was waiting if we actually
383 	 * released something
384 	 */
385 	if (old_locks != vgadev->locks)
386 		wake_up_all(&vga_wait_queue);
387 }
388 
389 /**
390  * vga_get - acquire & locks VGA resources
391  * @pdev: pci device of the VGA card or NULL for the system default
392  * @rsrc: bit mask of resources to acquire and lock
393  * @interruptible: blocking should be interruptible by signals ?
394  *
395  * This function acquires VGA resources for the given card and mark those
396  * resources locked. If the resource requested are "normal" (and not legacy)
397  * resources, the arbiter will first check whether the card is doing legacy
398  * decoding for that type of resource. If yes, the lock is "converted" into a
399  * legacy resource lock.
400  *
401  * The arbiter will first look for all VGA cards that might conflict and disable
402  * their IOs and/or Memory access, including VGA forwarding on P2P bridges if
403  * necessary, so that the requested resources can be used. Then, the card is
404  * marked as locking these resources and the IO and/or Memory accesses are
405  * enabled on the card (including VGA forwarding on parent P2P bridges if any).
406  *
407  * This function will block if some conflicting card is already locking one of
408  * the required resources (or any resource on a different bus segment, since P2P
409  * bridges don't differentiate VGA memory and IO afaik). You can indicate
410  * whether this blocking should be interruptible by a signal (for userland
411  * interface) or not.
412  *
413  * Must not be called at interrupt time or in atomic context.  If the card
414  * already owns the resources, the function succeeds.  Nested calls are
415  * supported (a per-resource counter is maintained)
416  *
417  * On success, release the VGA resource again with vga_put().
418  *
419  * Returns:
420  *
421  * 0 on success, negative error code on failure.
422  */
423 int vga_get(struct pci_dev *pdev, unsigned int rsrc, int interruptible)
424 {
425 	struct vga_device *vgadev, *conflict;
426 	unsigned long flags;
427 	wait_queue_entry_t wait;
428 	int rc = 0;
429 
430 	vga_check_first_use();
431 	/* The one who calls us should check for this, but lets be sure... */
432 	if (pdev == NULL)
433 		pdev = vga_default_device();
434 	if (pdev == NULL)
435 		return 0;
436 
437 	for (;;) {
438 		spin_lock_irqsave(&vga_lock, flags);
439 		vgadev = vgadev_find(pdev);
440 		if (vgadev == NULL) {
441 			spin_unlock_irqrestore(&vga_lock, flags);
442 			rc = -ENODEV;
443 			break;
444 		}
445 		conflict = __vga_tryget(vgadev, rsrc);
446 		spin_unlock_irqrestore(&vga_lock, flags);
447 		if (conflict == NULL)
448 			break;
449 
450 
451 		/* We have a conflict, we wait until somebody kicks the
452 		 * work queue. Currently we have one work queue that we
453 		 * kick each time some resources are released, but it would
454 		 * be fairly easy to have a per device one so that we only
455 		 * need to attach to the conflicting device
456 		 */
457 		init_waitqueue_entry(&wait, current);
458 		add_wait_queue(&vga_wait_queue, &wait);
459 		set_current_state(interruptible ?
460 				  TASK_INTERRUPTIBLE :
461 				  TASK_UNINTERRUPTIBLE);
462 		if (interruptible && signal_pending(current)) {
463 			__set_current_state(TASK_RUNNING);
464 			remove_wait_queue(&vga_wait_queue, &wait);
465 			rc = -ERESTARTSYS;
466 			break;
467 		}
468 		schedule();
469 		remove_wait_queue(&vga_wait_queue, &wait);
470 	}
471 	return rc;
472 }
473 EXPORT_SYMBOL(vga_get);
474 
475 /**
476  * vga_tryget - try to acquire & lock legacy VGA resources
477  * @pdev: pci devivce of VGA card or NULL for system default
478  * @rsrc: bit mask of resources to acquire and lock
479  *
480  * This function performs the same operation as vga_get(), but will return an
481  * error (-EBUSY) instead of blocking if the resources are already locked by
482  * another card. It can be called in any context
483  *
484  * On success, release the VGA resource again with vga_put().
485  *
486  * Returns:
487  *
488  * 0 on success, negative error code on failure.
489  */
490 static int vga_tryget(struct pci_dev *pdev, unsigned int rsrc)
491 {
492 	struct vga_device *vgadev;
493 	unsigned long flags;
494 	int rc = 0;
495 
496 	vga_check_first_use();
497 
498 	/* The one who calls us should check for this, but lets be sure... */
499 	if (pdev == NULL)
500 		pdev = vga_default_device();
501 	if (pdev == NULL)
502 		return 0;
503 	spin_lock_irqsave(&vga_lock, flags);
504 	vgadev = vgadev_find(pdev);
505 	if (vgadev == NULL) {
506 		rc = -ENODEV;
507 		goto bail;
508 	}
509 	if (__vga_tryget(vgadev, rsrc))
510 		rc = -EBUSY;
511 bail:
512 	spin_unlock_irqrestore(&vga_lock, flags);
513 	return rc;
514 }
515 
516 /**
517  * vga_put - release lock on legacy VGA resources
518  * @pdev: pci device of VGA card or NULL for system default
519  * @rsrc: but mask of resource to release
520  *
521  * This fuction releases resources previously locked by vga_get() or
522  * vga_tryget(). The resources aren't disabled right away, so that a subsequence
523  * vga_get() on the same card will succeed immediately. Resources have a
524  * counter, so locks are only released if the counter reaches 0.
525  */
526 void vga_put(struct pci_dev *pdev, unsigned int rsrc)
527 {
528 	struct vga_device *vgadev;
529 	unsigned long flags;
530 
531 	/* The one who calls us should check for this, but lets be sure... */
532 	if (pdev == NULL)
533 		pdev = vga_default_device();
534 	if (pdev == NULL)
535 		return;
536 	spin_lock_irqsave(&vga_lock, flags);
537 	vgadev = vgadev_find(pdev);
538 	if (vgadev == NULL)
539 		goto bail;
540 	__vga_put(vgadev, rsrc);
541 bail:
542 	spin_unlock_irqrestore(&vga_lock, flags);
543 }
544 EXPORT_SYMBOL(vga_put);
545 
546 static bool vga_is_firmware_default(struct pci_dev *pdev)
547 {
548 #if defined(CONFIG_X86) || defined(CONFIG_IA64)
549 	u64 base = screen_info.lfb_base;
550 	u64 size = screen_info.lfb_size;
551 	struct resource *r;
552 	u64 limit;
553 
554 	/* Select the device owning the boot framebuffer if there is one */
555 
556 	if (screen_info.capabilities & VIDEO_CAPABILITY_64BIT_BASE)
557 		base |= (u64)screen_info.ext_lfb_base << 32;
558 
559 	limit = base + size;
560 
561 	/* Does firmware framebuffer belong to us? */
562 	pci_dev_for_each_resource(pdev, r) {
563 		if (resource_type(r) != IORESOURCE_MEM)
564 			continue;
565 
566 		if (!r->start || !r->end)
567 			continue;
568 
569 		if (base < r->start || limit >= r->end)
570 			continue;
571 
572 		return true;
573 	}
574 #endif
575 	return false;
576 }
577 
578 static bool vga_arb_integrated_gpu(struct device *dev)
579 {
580 #if defined(CONFIG_ACPI)
581 	struct acpi_device *adev = ACPI_COMPANION(dev);
582 
583 	return adev && !strcmp(acpi_device_hid(adev), ACPI_VIDEO_HID);
584 #else
585 	return false;
586 #endif
587 }
588 
589 /*
590  * Return true if vgadev is a better default VGA device than the best one
591  * we've seen so far.
592  */
593 static bool vga_is_boot_device(struct vga_device *vgadev)
594 {
595 	struct vga_device *boot_vga = vgadev_find(vga_default_device());
596 	struct pci_dev *pdev = vgadev->pdev;
597 	u16 cmd, boot_cmd;
598 
599 	/*
600 	 * We select the default VGA device in this order:
601 	 *   Firmware framebuffer (see vga_arb_select_default_device())
602 	 *   Legacy VGA device (owns VGA_RSRC_LEGACY_MASK)
603 	 *   Non-legacy integrated device (see vga_arb_select_default_device())
604 	 *   Non-legacy discrete device (see vga_arb_select_default_device())
605 	 *   Other device (see vga_arb_select_default_device())
606 	 */
607 
608 	/*
609 	 * We always prefer a firmware default device, so if we've already
610 	 * found one, there's no need to consider vgadev.
611 	 */
612 	if (boot_vga && boot_vga->is_firmware_default)
613 		return false;
614 
615 	if (vga_is_firmware_default(pdev)) {
616 		vgadev->is_firmware_default = true;
617 		return true;
618 	}
619 
620 	/*
621 	 * A legacy VGA device has MEM and IO enabled and any bridges
622 	 * leading to it have PCI_BRIDGE_CTL_VGA enabled so the legacy
623 	 * resources ([mem 0xa0000-0xbffff], [io 0x3b0-0x3bb], etc) are
624 	 * routed to it.
625 	 *
626 	 * We use the first one we find, so if we've already found one,
627 	 * vgadev is no better.
628 	 */
629 	if (boot_vga &&
630 	    (boot_vga->owns & VGA_RSRC_LEGACY_MASK) == VGA_RSRC_LEGACY_MASK)
631 		return false;
632 
633 	if ((vgadev->owns & VGA_RSRC_LEGACY_MASK) == VGA_RSRC_LEGACY_MASK)
634 		return true;
635 
636 	/*
637 	 * If we haven't found a legacy VGA device, accept a non-legacy
638 	 * device.  It may have either IO or MEM enabled, and bridges may
639 	 * not have PCI_BRIDGE_CTL_VGA enabled, so it may not be able to
640 	 * use legacy VGA resources.  Prefer an integrated GPU over others.
641 	 */
642 	pci_read_config_word(pdev, PCI_COMMAND, &cmd);
643 	if (cmd & (PCI_COMMAND_IO | PCI_COMMAND_MEMORY)) {
644 
645 		/*
646 		 * An integrated GPU overrides a previous non-legacy
647 		 * device.  We expect only a single integrated GPU, but if
648 		 * there are more, we use the *last* because that was the
649 		 * previous behavior.
650 		 */
651 		if (vga_arb_integrated_gpu(&pdev->dev))
652 			return true;
653 
654 		/*
655 		 * We prefer the first non-legacy discrete device we find.
656 		 * If we already found one, vgadev is no better.
657 		 */
658 		if (boot_vga) {
659 			pci_read_config_word(boot_vga->pdev, PCI_COMMAND,
660 					     &boot_cmd);
661 			if (boot_cmd & (PCI_COMMAND_IO | PCI_COMMAND_MEMORY))
662 				return false;
663 		}
664 		return true;
665 	}
666 
667 	/*
668 	 * vgadev has neither IO nor MEM enabled.  If we haven't found any
669 	 * other VGA devices, it is the best candidate so far.
670 	 */
671 	if (!boot_vga)
672 		return true;
673 
674 	return false;
675 }
676 
677 /*
678  * Rules for using a bridge to control a VGA descendant decoding: if a bridge
679  * has only one VGA descendant then it can be used to control the VGA routing
680  * for that device. It should always use the bridge closest to the device to
681  * control it. If a bridge has a direct VGA descendant, but also have a sub-
682  * bridge VGA descendant then we cannot use that bridge to control the direct
683  * VGA descendant. So for every device we register, we need to iterate all
684  * its parent bridges so we can invalidate any devices using them properly.
685  */
686 static void vga_arbiter_check_bridge_sharing(struct vga_device *vgadev)
687 {
688 	struct vga_device *same_bridge_vgadev;
689 	struct pci_bus *new_bus, *bus;
690 	struct pci_dev *new_bridge, *bridge;
691 
692 	vgadev->bridge_has_one_vga = true;
693 
694 	if (list_empty(&vga_list)) {
695 		vgaarb_info(&vgadev->pdev->dev, "bridge control possible\n");
696 		return;
697 	}
698 
699 	/* okay iterate the new devices bridge hierarachy */
700 	new_bus = vgadev->pdev->bus;
701 	while (new_bus) {
702 		new_bridge = new_bus->self;
703 
704 		/* go through list of devices already registered */
705 		list_for_each_entry(same_bridge_vgadev, &vga_list, list) {
706 			bus = same_bridge_vgadev->pdev->bus;
707 			bridge = bus->self;
708 
709 			/* see if the share a bridge with this device */
710 			if (new_bridge == bridge) {
711 				/*
712 				 * If their direct parent bridge is the same
713 				 * as any bridge of this device then it can't
714 				 * be used for that device.
715 				 */
716 				same_bridge_vgadev->bridge_has_one_vga = false;
717 			}
718 
719 			/*
720 			 * Now iterate the previous devices bridge hierarchy.
721 			 * If the new devices parent bridge is in the other
722 			 * devices hierarchy then we can't use it to control
723 			 * this device
724 			 */
725 			while (bus) {
726 				bridge = bus->self;
727 
728 				if (bridge && bridge == vgadev->pdev->bus->self)
729 					vgadev->bridge_has_one_vga = false;
730 
731 				bus = bus->parent;
732 			}
733 		}
734 		new_bus = new_bus->parent;
735 	}
736 
737 	if (vgadev->bridge_has_one_vga)
738 		vgaarb_info(&vgadev->pdev->dev, "bridge control possible\n");
739 	else
740 		vgaarb_info(&vgadev->pdev->dev, "no bridge control possible\n");
741 }
742 
743 /*
744  * Currently, we assume that the "initial" setup of the system is
745  * not sane, that is we come up with conflicting devices and let
746  * the arbiter's client decides if devices decodes or not legacy
747  * things.
748  */
749 static bool vga_arbiter_add_pci_device(struct pci_dev *pdev)
750 {
751 	struct vga_device *vgadev;
752 	unsigned long flags;
753 	struct pci_bus *bus;
754 	struct pci_dev *bridge;
755 	u16 cmd;
756 
757 	/* Only deal with VGA class devices */
758 	if ((pdev->class >> 8) != PCI_CLASS_DISPLAY_VGA)
759 		return false;
760 
761 	/* Allocate structure */
762 	vgadev = kzalloc(sizeof(struct vga_device), GFP_KERNEL);
763 	if (vgadev == NULL) {
764 		vgaarb_err(&pdev->dev, "failed to allocate VGA arbiter data\n");
765 		/*
766 		 * What to do on allocation failure ? For now, let's just do
767 		 * nothing, I'm not sure there is anything saner to be done.
768 		 */
769 		return false;
770 	}
771 
772 	/* Take lock & check for duplicates */
773 	spin_lock_irqsave(&vga_lock, flags);
774 	if (vgadev_find(pdev) != NULL) {
775 		BUG_ON(1);
776 		goto fail;
777 	}
778 	vgadev->pdev = pdev;
779 
780 	/* By default, assume we decode everything */
781 	vgadev->decodes = VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM |
782 			  VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM;
783 
784 	/* by default mark it as decoding */
785 	vga_decode_count++;
786 	/* Mark that we "own" resources based on our enables, we will
787 	 * clear that below if the bridge isn't forwarding
788 	 */
789 	pci_read_config_word(pdev, PCI_COMMAND, &cmd);
790 	if (cmd & PCI_COMMAND_IO)
791 		vgadev->owns |= VGA_RSRC_LEGACY_IO;
792 	if (cmd & PCI_COMMAND_MEMORY)
793 		vgadev->owns |= VGA_RSRC_LEGACY_MEM;
794 
795 	/* Check if VGA cycles can get down to us */
796 	bus = pdev->bus;
797 	while (bus) {
798 		bridge = bus->self;
799 		if (bridge) {
800 			u16 l;
801 
802 			pci_read_config_word(bridge, PCI_BRIDGE_CONTROL, &l);
803 			if (!(l & PCI_BRIDGE_CTL_VGA)) {
804 				vgadev->owns = 0;
805 				break;
806 			}
807 		}
808 		bus = bus->parent;
809 	}
810 
811 	if (vga_is_boot_device(vgadev)) {
812 		vgaarb_info(&pdev->dev, "setting as boot VGA device%s\n",
813 			    vga_default_device() ?
814 			    " (overriding previous)" : "");
815 		vga_set_default_device(pdev);
816 	}
817 
818 	vga_arbiter_check_bridge_sharing(vgadev);
819 
820 	/* Add to the list */
821 	list_add_tail(&vgadev->list, &vga_list);
822 	vga_count++;
823 	vgaarb_info(&pdev->dev, "VGA device added: decodes=%s,owns=%s,locks=%s\n",
824 		vga_iostate_to_str(vgadev->decodes),
825 		vga_iostate_to_str(vgadev->owns),
826 		vga_iostate_to_str(vgadev->locks));
827 
828 	spin_unlock_irqrestore(&vga_lock, flags);
829 	return true;
830 fail:
831 	spin_unlock_irqrestore(&vga_lock, flags);
832 	kfree(vgadev);
833 	return false;
834 }
835 
836 static bool vga_arbiter_del_pci_device(struct pci_dev *pdev)
837 {
838 	struct vga_device *vgadev;
839 	unsigned long flags;
840 	bool ret = true;
841 
842 	spin_lock_irqsave(&vga_lock, flags);
843 	vgadev = vgadev_find(pdev);
844 	if (vgadev == NULL) {
845 		ret = false;
846 		goto bail;
847 	}
848 
849 	if (vga_default == pdev)
850 		vga_set_default_device(NULL);
851 
852 	if (vgadev->decodes & (VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM))
853 		vga_decode_count--;
854 
855 	/* Remove entry from list */
856 	list_del(&vgadev->list);
857 	vga_count--;
858 
859 	/* Wake up all possible waiters */
860 	wake_up_all(&vga_wait_queue);
861 bail:
862 	spin_unlock_irqrestore(&vga_lock, flags);
863 	kfree(vgadev);
864 	return ret;
865 }
866 
867 /* This is called with the lock */
868 static void vga_update_device_decodes(struct vga_device *vgadev,
869 				      unsigned int new_decodes)
870 {
871 	struct device *dev = &vgadev->pdev->dev;
872 	unsigned int old_decodes = vgadev->decodes;
873 	unsigned int decodes_removed = ~new_decodes & old_decodes;
874 	unsigned int decodes_unlocked = vgadev->locks & decodes_removed;
875 
876 	vgadev->decodes = new_decodes;
877 
878 	vgaarb_info(dev, "VGA decodes changed: olddecodes=%s,decodes=%s:owns=%s\n",
879 		    vga_iostate_to_str(old_decodes),
880 		    vga_iostate_to_str(vgadev->decodes),
881 		    vga_iostate_to_str(vgadev->owns));
882 
883 	/* If we removed locked decodes, lock count goes to zero, and release */
884 	if (decodes_unlocked) {
885 		if (decodes_unlocked & VGA_RSRC_LEGACY_IO)
886 			vgadev->io_lock_cnt = 0;
887 		if (decodes_unlocked & VGA_RSRC_LEGACY_MEM)
888 			vgadev->mem_lock_cnt = 0;
889 		__vga_put(vgadev, decodes_unlocked);
890 	}
891 
892 	/* change decodes counter */
893 	if (old_decodes & VGA_RSRC_LEGACY_MASK &&
894 	    !(new_decodes & VGA_RSRC_LEGACY_MASK))
895 		vga_decode_count--;
896 	if (!(old_decodes & VGA_RSRC_LEGACY_MASK) &&
897 	    new_decodes & VGA_RSRC_LEGACY_MASK)
898 		vga_decode_count++;
899 	vgaarb_dbg(dev, "decoding count now is: %d\n", vga_decode_count);
900 }
901 
902 static void __vga_set_legacy_decoding(struct pci_dev *pdev,
903 				      unsigned int decodes,
904 				      bool userspace)
905 {
906 	struct vga_device *vgadev;
907 	unsigned long flags;
908 
909 	decodes &= VGA_RSRC_LEGACY_MASK;
910 
911 	spin_lock_irqsave(&vga_lock, flags);
912 	vgadev = vgadev_find(pdev);
913 	if (vgadev == NULL)
914 		goto bail;
915 
916 	/* don't let userspace futz with kernel driver decodes */
917 	if (userspace && vgadev->set_decode)
918 		goto bail;
919 
920 	/* update the device decodes + counter */
921 	vga_update_device_decodes(vgadev, decodes);
922 
923 	/* XXX if somebody is going from "doesn't decode" to "decodes" state
924 	 * here, additional care must be taken as we may have pending owner
925 	 * ship of non-legacy region ...
926 	 */
927 bail:
928 	spin_unlock_irqrestore(&vga_lock, flags);
929 }
930 
931 /**
932  * vga_set_legacy_decoding
933  * @pdev: pci device of the VGA card
934  * @decodes: bit mask of what legacy regions the card decodes
935  *
936  * Indicates to the arbiter if the card decodes legacy VGA IOs, legacy VGA
937  * Memory, both, or none. All cards default to both, the card driver (fbdev for
938  * example) should tell the arbiter if it has disabled legacy decoding, so the
939  * card can be left out of the arbitration process (and can be safe to take
940  * interrupts at any time.
941  */
942 void vga_set_legacy_decoding(struct pci_dev *pdev, unsigned int decodes)
943 {
944 	__vga_set_legacy_decoding(pdev, decodes, false);
945 }
946 EXPORT_SYMBOL(vga_set_legacy_decoding);
947 
948 /**
949  * vga_client_register - register or unregister a VGA arbitration client
950  * @pdev: pci device of the VGA client
951  * @set_decode: vga decode change callback
952  *
953  * Clients have two callback mechanisms they can use.
954  *
955  * @set_decode callback: If a client can disable its GPU VGA resource, it
956  * will get a callback from this to set the encode/decode state.
957  *
958  * Rationale: we cannot disable VGA decode resources unconditionally some single
959  * GPU laptops seem to require ACPI or BIOS access to the VGA registers to
960  * control things like backlights etc.  Hopefully newer multi-GPU laptops do
961  * something saner, and desktops won't have any special ACPI for this. The
962  * driver will get a callback when VGA arbitration is first used by userspace
963  * since some older X servers have issues.
964  *
965  * This function does not check whether a client for @pdev has been registered
966  * already.
967  *
968  * To unregister just call vga_client_unregister().
969  *
970  * Returns: 0 on success, -1 on failure
971  */
972 int vga_client_register(struct pci_dev *pdev,
973 		unsigned int (*set_decode)(struct pci_dev *pdev, bool decode))
974 {
975 	int ret = -ENODEV;
976 	struct vga_device *vgadev;
977 	unsigned long flags;
978 
979 	spin_lock_irqsave(&vga_lock, flags);
980 	vgadev = vgadev_find(pdev);
981 	if (!vgadev)
982 		goto bail;
983 
984 	vgadev->set_decode = set_decode;
985 	ret = 0;
986 
987 bail:
988 	spin_unlock_irqrestore(&vga_lock, flags);
989 	return ret;
990 
991 }
992 EXPORT_SYMBOL(vga_client_register);
993 
994 /*
995  * Char driver implementation
996  *
997  * Semantics is:
998  *
999  *  open       : open user instance of the arbitrer. by default, it's
1000  *                attached to the default VGA device of the system.
1001  *
1002  *  close      : close user instance, release locks
1003  *
1004  *  read       : return a string indicating the status of the target.
1005  *                an IO state string is of the form {io,mem,io+mem,none},
1006  *                mc and ic are respectively mem and io lock counts (for
1007  *                debugging/diagnostic only). "decodes" indicate what the
1008  *                card currently decodes, "owns" indicates what is currently
1009  *                enabled on it, and "locks" indicates what is locked by this
1010  *                card. If the card is unplugged, we get "invalid" then for
1011  *                card_ID and an -ENODEV error is returned for any command
1012  *                until a new card is targeted
1013  *
1014  *   "<card_ID>,decodes=<io_state>,owns=<io_state>,locks=<io_state> (ic,mc)"
1015  *
1016  * write       : write a command to the arbiter. List of commands is:
1017  *
1018  *   target <card_ID>   : switch target to card <card_ID> (see below)
1019  *   lock <io_state>    : acquires locks on target ("none" is invalid io_state)
1020  *   trylock <io_state> : non-blocking acquire locks on target
1021  *   unlock <io_state>  : release locks on target
1022  *   unlock all         : release all locks on target held by this user
1023  *   decodes <io_state> : set the legacy decoding attributes for the card
1024  *
1025  * poll         : event if something change on any card (not just the target)
1026  *
1027  * card_ID is of the form "PCI:domain:bus:dev.fn". It can be set to "default"
1028  * to go back to the system default card (TODO: not implemented yet).
1029  * Currently, only PCI is supported as a prefix, but the userland API may
1030  * support other bus types in the future, even if the current kernel
1031  * implementation doesn't.
1032  *
1033  * Note about locks:
1034  *
1035  * The driver keeps track of which user has what locks on which card. It
1036  * supports stacking, like the kernel one. This complexifies the implementation
1037  * a bit, but makes the arbiter more tolerant to userspace problems and able
1038  * to properly cleanup in all cases when a process dies.
1039  * Currently, a max of 16 cards simultaneously can have locks issued from
1040  * userspace for a given user (file descriptor instance) of the arbiter.
1041  *
1042  * If the device is hot-unplugged, there is a hook inside the module to notify
1043  * they being added/removed in the system and automatically added/removed in
1044  * the arbiter.
1045  */
1046 
1047 #define MAX_USER_CARDS         CONFIG_VGA_ARB_MAX_GPUS
1048 #define PCI_INVALID_CARD       ((struct pci_dev *)-1UL)
1049 
1050 /*
1051  * Each user has an array of these, tracking which cards have locks
1052  */
1053 struct vga_arb_user_card {
1054 	struct pci_dev *pdev;
1055 	unsigned int mem_cnt;
1056 	unsigned int io_cnt;
1057 };
1058 
1059 struct vga_arb_private {
1060 	struct list_head list;
1061 	struct pci_dev *target;
1062 	struct vga_arb_user_card cards[MAX_USER_CARDS];
1063 	spinlock_t lock;
1064 };
1065 
1066 static LIST_HEAD(vga_user_list);
1067 static DEFINE_SPINLOCK(vga_user_lock);
1068 
1069 
1070 /*
1071  * This function gets a string in the format: "PCI:domain:bus:dev.fn" and
1072  * returns the respective values. If the string is not in this format,
1073  * it returns 0.
1074  */
1075 static int vga_pci_str_to_vars(char *buf, int count, unsigned int *domain,
1076 			       unsigned int *bus, unsigned int *devfn)
1077 {
1078 	int n;
1079 	unsigned int slot, func;
1080 
1081 
1082 	n = sscanf(buf, "PCI:%x:%x:%x.%x", domain, bus, &slot, &func);
1083 	if (n != 4)
1084 		return 0;
1085 
1086 	*devfn = PCI_DEVFN(slot, func);
1087 
1088 	return 1;
1089 }
1090 
1091 static ssize_t vga_arb_read(struct file *file, char __user *buf,
1092 			    size_t count, loff_t *ppos)
1093 {
1094 	struct vga_arb_private *priv = file->private_data;
1095 	struct vga_device *vgadev;
1096 	struct pci_dev *pdev;
1097 	unsigned long flags;
1098 	size_t len;
1099 	int rc;
1100 	char *lbuf;
1101 
1102 	lbuf = kmalloc(1024, GFP_KERNEL);
1103 	if (lbuf == NULL)
1104 		return -ENOMEM;
1105 
1106 	/* Protects vga_list */
1107 	spin_lock_irqsave(&vga_lock, flags);
1108 
1109 	/* If we are targeting the default, use it */
1110 	pdev = priv->target;
1111 	if (pdev == NULL || pdev == PCI_INVALID_CARD) {
1112 		spin_unlock_irqrestore(&vga_lock, flags);
1113 		len = sprintf(lbuf, "invalid");
1114 		goto done;
1115 	}
1116 
1117 	/* Find card vgadev structure */
1118 	vgadev = vgadev_find(pdev);
1119 	if (vgadev == NULL) {
1120 		/* Wow, it's not in the list, that shouldn't happen,
1121 		 * let's fix us up and return invalid card
1122 		 */
1123 		spin_unlock_irqrestore(&vga_lock, flags);
1124 		len = sprintf(lbuf, "invalid");
1125 		goto done;
1126 	}
1127 
1128 	/* Fill the buffer with infos */
1129 	len = snprintf(lbuf, 1024,
1130 		       "count:%d,PCI:%s,decodes=%s,owns=%s,locks=%s(%u:%u)\n",
1131 		       vga_decode_count, pci_name(pdev),
1132 		       vga_iostate_to_str(vgadev->decodes),
1133 		       vga_iostate_to_str(vgadev->owns),
1134 		       vga_iostate_to_str(vgadev->locks),
1135 		       vgadev->io_lock_cnt, vgadev->mem_lock_cnt);
1136 
1137 	spin_unlock_irqrestore(&vga_lock, flags);
1138 done:
1139 
1140 	/* Copy that to user */
1141 	if (len > count)
1142 		len = count;
1143 	rc = copy_to_user(buf, lbuf, len);
1144 	kfree(lbuf);
1145 	if (rc)
1146 		return -EFAULT;
1147 	return len;
1148 }
1149 
1150 /*
1151  * TODO: To avoid parsing inside kernel and to improve the speed we may
1152  * consider use ioctl here
1153  */
1154 static ssize_t vga_arb_write(struct file *file, const char __user *buf,
1155 			     size_t count, loff_t *ppos)
1156 {
1157 	struct vga_arb_private *priv = file->private_data;
1158 	struct vga_arb_user_card *uc = NULL;
1159 	struct pci_dev *pdev;
1160 
1161 	unsigned int io_state;
1162 
1163 	char kbuf[64], *curr_pos;
1164 	size_t remaining = count;
1165 
1166 	int ret_val;
1167 	int i;
1168 
1169 	if (count >= sizeof(kbuf))
1170 		return -EINVAL;
1171 	if (copy_from_user(kbuf, buf, count))
1172 		return -EFAULT;
1173 	curr_pos = kbuf;
1174 	kbuf[count] = '\0';	/* Just to make sure... */
1175 
1176 	if (strncmp(curr_pos, "lock ", 5) == 0) {
1177 		curr_pos += 5;
1178 		remaining -= 5;
1179 
1180 		pr_debug("client 0x%p called 'lock'\n", priv);
1181 
1182 		if (!vga_str_to_iostate(curr_pos, remaining, &io_state)) {
1183 			ret_val = -EPROTO;
1184 			goto done;
1185 		}
1186 		if (io_state == VGA_RSRC_NONE) {
1187 			ret_val = -EPROTO;
1188 			goto done;
1189 		}
1190 
1191 		pdev = priv->target;
1192 		if (priv->target == NULL) {
1193 			ret_val = -ENODEV;
1194 			goto done;
1195 		}
1196 
1197 		vga_get_uninterruptible(pdev, io_state);
1198 
1199 		/* Update the client's locks lists... */
1200 		for (i = 0; i < MAX_USER_CARDS; i++) {
1201 			if (priv->cards[i].pdev == pdev) {
1202 				if (io_state & VGA_RSRC_LEGACY_IO)
1203 					priv->cards[i].io_cnt++;
1204 				if (io_state & VGA_RSRC_LEGACY_MEM)
1205 					priv->cards[i].mem_cnt++;
1206 				break;
1207 			}
1208 		}
1209 
1210 		ret_val = count;
1211 		goto done;
1212 	} else if (strncmp(curr_pos, "unlock ", 7) == 0) {
1213 		curr_pos += 7;
1214 		remaining -= 7;
1215 
1216 		pr_debug("client 0x%p called 'unlock'\n", priv);
1217 
1218 		if (strncmp(curr_pos, "all", 3) == 0)
1219 			io_state = VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
1220 		else {
1221 			if (!vga_str_to_iostate
1222 			    (curr_pos, remaining, &io_state)) {
1223 				ret_val = -EPROTO;
1224 				goto done;
1225 			}
1226 			/* TODO: Add this?
1227 			   if (io_state == VGA_RSRC_NONE) {
1228 			   ret_val = -EPROTO;
1229 			   goto done;
1230 			   }
1231 			  */
1232 		}
1233 
1234 		pdev = priv->target;
1235 		if (priv->target == NULL) {
1236 			ret_val = -ENODEV;
1237 			goto done;
1238 		}
1239 		for (i = 0; i < MAX_USER_CARDS; i++) {
1240 			if (priv->cards[i].pdev == pdev)
1241 				uc = &priv->cards[i];
1242 		}
1243 
1244 		if (!uc) {
1245 			ret_val = -EINVAL;
1246 			goto done;
1247 		}
1248 
1249 		if (io_state & VGA_RSRC_LEGACY_IO && uc->io_cnt == 0) {
1250 			ret_val = -EINVAL;
1251 			goto done;
1252 		}
1253 
1254 		if (io_state & VGA_RSRC_LEGACY_MEM && uc->mem_cnt == 0) {
1255 			ret_val = -EINVAL;
1256 			goto done;
1257 		}
1258 
1259 		vga_put(pdev, io_state);
1260 
1261 		if (io_state & VGA_RSRC_LEGACY_IO)
1262 			uc->io_cnt--;
1263 		if (io_state & VGA_RSRC_LEGACY_MEM)
1264 			uc->mem_cnt--;
1265 
1266 		ret_val = count;
1267 		goto done;
1268 	} else if (strncmp(curr_pos, "trylock ", 8) == 0) {
1269 		curr_pos += 8;
1270 		remaining -= 8;
1271 
1272 		pr_debug("client 0x%p called 'trylock'\n", priv);
1273 
1274 		if (!vga_str_to_iostate(curr_pos, remaining, &io_state)) {
1275 			ret_val = -EPROTO;
1276 			goto done;
1277 		}
1278 		/* TODO: Add this?
1279 		   if (io_state == VGA_RSRC_NONE) {
1280 		   ret_val = -EPROTO;
1281 		   goto done;
1282 		   }
1283 		 */
1284 
1285 		pdev = priv->target;
1286 		if (priv->target == NULL) {
1287 			ret_val = -ENODEV;
1288 			goto done;
1289 		}
1290 
1291 		if (vga_tryget(pdev, io_state)) {
1292 			/* Update the client's locks lists... */
1293 			for (i = 0; i < MAX_USER_CARDS; i++) {
1294 				if (priv->cards[i].pdev == pdev) {
1295 					if (io_state & VGA_RSRC_LEGACY_IO)
1296 						priv->cards[i].io_cnt++;
1297 					if (io_state & VGA_RSRC_LEGACY_MEM)
1298 						priv->cards[i].mem_cnt++;
1299 					break;
1300 				}
1301 			}
1302 			ret_val = count;
1303 			goto done;
1304 		} else {
1305 			ret_val = -EBUSY;
1306 			goto done;
1307 		}
1308 
1309 	} else if (strncmp(curr_pos, "target ", 7) == 0) {
1310 		unsigned int domain, bus, devfn;
1311 		struct vga_device *vgadev;
1312 
1313 		curr_pos += 7;
1314 		remaining -= 7;
1315 		pr_debug("client 0x%p called 'target'\n", priv);
1316 		/* if target is default */
1317 		if (!strncmp(curr_pos, "default", 7))
1318 			pdev = pci_dev_get(vga_default_device());
1319 		else {
1320 			if (!vga_pci_str_to_vars(curr_pos, remaining,
1321 						 &domain, &bus, &devfn)) {
1322 				ret_val = -EPROTO;
1323 				goto done;
1324 			}
1325 			pdev = pci_get_domain_bus_and_slot(domain, bus, devfn);
1326 			if (!pdev) {
1327 				pr_debug("invalid PCI address %04x:%02x:%02x.%x\n",
1328 					 domain, bus, PCI_SLOT(devfn),
1329 					 PCI_FUNC(devfn));
1330 				ret_val = -ENODEV;
1331 				goto done;
1332 			}
1333 
1334 			pr_debug("%s ==> %04x:%02x:%02x.%x pdev %p\n", curr_pos,
1335 				domain, bus, PCI_SLOT(devfn), PCI_FUNC(devfn),
1336 				pdev);
1337 		}
1338 
1339 		vgadev = vgadev_find(pdev);
1340 		pr_debug("vgadev %p\n", vgadev);
1341 		if (vgadev == NULL) {
1342 			if (pdev) {
1343 				vgaarb_dbg(&pdev->dev, "not a VGA device\n");
1344 				pci_dev_put(pdev);
1345 			}
1346 
1347 			ret_val = -ENODEV;
1348 			goto done;
1349 		}
1350 
1351 		priv->target = pdev;
1352 		for (i = 0; i < MAX_USER_CARDS; i++) {
1353 			if (priv->cards[i].pdev == pdev)
1354 				break;
1355 			if (priv->cards[i].pdev == NULL) {
1356 				priv->cards[i].pdev = pdev;
1357 				priv->cards[i].io_cnt = 0;
1358 				priv->cards[i].mem_cnt = 0;
1359 				break;
1360 			}
1361 		}
1362 		if (i == MAX_USER_CARDS) {
1363 			vgaarb_dbg(&pdev->dev, "maximum user cards (%d) number reached, ignoring this one!\n",
1364 				MAX_USER_CARDS);
1365 			pci_dev_put(pdev);
1366 			/* XXX: which value to return? */
1367 			ret_val =  -ENOMEM;
1368 			goto done;
1369 		}
1370 
1371 		ret_val = count;
1372 		pci_dev_put(pdev);
1373 		goto done;
1374 
1375 
1376 	} else if (strncmp(curr_pos, "decodes ", 8) == 0) {
1377 		curr_pos += 8;
1378 		remaining -= 8;
1379 		pr_debug("client 0x%p called 'decodes'\n", priv);
1380 
1381 		if (!vga_str_to_iostate(curr_pos, remaining, &io_state)) {
1382 			ret_val = -EPROTO;
1383 			goto done;
1384 		}
1385 		pdev = priv->target;
1386 		if (priv->target == NULL) {
1387 			ret_val = -ENODEV;
1388 			goto done;
1389 		}
1390 
1391 		__vga_set_legacy_decoding(pdev, io_state, true);
1392 		ret_val = count;
1393 		goto done;
1394 	}
1395 	/* If we got here, the message written is not part of the protocol! */
1396 	return -EPROTO;
1397 
1398 done:
1399 	return ret_val;
1400 }
1401 
1402 static __poll_t vga_arb_fpoll(struct file *file, poll_table *wait)
1403 {
1404 	pr_debug("%s\n", __func__);
1405 
1406 	poll_wait(file, &vga_wait_queue, wait);
1407 	return EPOLLIN;
1408 }
1409 
1410 static int vga_arb_open(struct inode *inode, struct file *file)
1411 {
1412 	struct vga_arb_private *priv;
1413 	unsigned long flags;
1414 
1415 	pr_debug("%s\n", __func__);
1416 
1417 	priv = kzalloc(sizeof(*priv), GFP_KERNEL);
1418 	if (priv == NULL)
1419 		return -ENOMEM;
1420 	spin_lock_init(&priv->lock);
1421 	file->private_data = priv;
1422 
1423 	spin_lock_irqsave(&vga_user_lock, flags);
1424 	list_add(&priv->list, &vga_user_list);
1425 	spin_unlock_irqrestore(&vga_user_lock, flags);
1426 
1427 	/* Set the client' lists of locks */
1428 	priv->target = vga_default_device(); /* Maybe this is still null! */
1429 	priv->cards[0].pdev = priv->target;
1430 	priv->cards[0].io_cnt = 0;
1431 	priv->cards[0].mem_cnt = 0;
1432 
1433 
1434 	return 0;
1435 }
1436 
1437 static int vga_arb_release(struct inode *inode, struct file *file)
1438 {
1439 	struct vga_arb_private *priv = file->private_data;
1440 	struct vga_arb_user_card *uc;
1441 	unsigned long flags;
1442 	int i;
1443 
1444 	pr_debug("%s\n", __func__);
1445 
1446 	spin_lock_irqsave(&vga_user_lock, flags);
1447 	list_del(&priv->list);
1448 	for (i = 0; i < MAX_USER_CARDS; i++) {
1449 		uc = &priv->cards[i];
1450 		if (uc->pdev == NULL)
1451 			continue;
1452 		vgaarb_dbg(&uc->pdev->dev, "uc->io_cnt == %d, uc->mem_cnt == %d\n",
1453 			uc->io_cnt, uc->mem_cnt);
1454 		while (uc->io_cnt--)
1455 			vga_put(uc->pdev, VGA_RSRC_LEGACY_IO);
1456 		while (uc->mem_cnt--)
1457 			vga_put(uc->pdev, VGA_RSRC_LEGACY_MEM);
1458 	}
1459 	spin_unlock_irqrestore(&vga_user_lock, flags);
1460 
1461 	kfree(priv);
1462 
1463 	return 0;
1464 }
1465 
1466 /*
1467  * callback any registered clients to let them know we have a
1468  * change in VGA cards
1469  */
1470 static void vga_arbiter_notify_clients(void)
1471 {
1472 	struct vga_device *vgadev;
1473 	unsigned long flags;
1474 	unsigned int new_decodes;
1475 	bool new_state;
1476 
1477 	if (!vga_arbiter_used)
1478 		return;
1479 
1480 	new_state = (vga_count > 1) ? false : true;
1481 
1482 	spin_lock_irqsave(&vga_lock, flags);
1483 	list_for_each_entry(vgadev, &vga_list, list) {
1484 		if (vgadev->set_decode) {
1485 			new_decodes = vgadev->set_decode(vgadev->pdev,
1486 							 new_state);
1487 			vga_update_device_decodes(vgadev, new_decodes);
1488 		}
1489 	}
1490 	spin_unlock_irqrestore(&vga_lock, flags);
1491 }
1492 
1493 static int pci_notify(struct notifier_block *nb, unsigned long action,
1494 		      void *data)
1495 {
1496 	struct device *dev = data;
1497 	struct pci_dev *pdev = to_pci_dev(dev);
1498 	bool notify = false;
1499 
1500 	vgaarb_dbg(dev, "%s\n", __func__);
1501 
1502 	/* For now we're only intereted in devices added and removed. I didn't
1503 	 * test this thing here, so someone needs to double check for the
1504 	 * cases of hotplugable vga cards. */
1505 	if (action == BUS_NOTIFY_ADD_DEVICE)
1506 		notify = vga_arbiter_add_pci_device(pdev);
1507 	else if (action == BUS_NOTIFY_DEL_DEVICE)
1508 		notify = vga_arbiter_del_pci_device(pdev);
1509 
1510 	if (notify)
1511 		vga_arbiter_notify_clients();
1512 	return 0;
1513 }
1514 
1515 static struct notifier_block pci_notifier = {
1516 	.notifier_call = pci_notify,
1517 };
1518 
1519 static const struct file_operations vga_arb_device_fops = {
1520 	.read = vga_arb_read,
1521 	.write = vga_arb_write,
1522 	.poll = vga_arb_fpoll,
1523 	.open = vga_arb_open,
1524 	.release = vga_arb_release,
1525 	.llseek = noop_llseek,
1526 };
1527 
1528 static struct miscdevice vga_arb_device = {
1529 	MISC_DYNAMIC_MINOR, "vga_arbiter", &vga_arb_device_fops
1530 };
1531 
1532 static int __init vga_arb_device_init(void)
1533 {
1534 	int rc;
1535 	struct pci_dev *pdev;
1536 
1537 	rc = misc_register(&vga_arb_device);
1538 	if (rc < 0)
1539 		pr_err("error %d registering device\n", rc);
1540 
1541 	bus_register_notifier(&pci_bus_type, &pci_notifier);
1542 
1543 	/* We add all PCI devices satisfying VGA class in the arbiter by
1544 	 * default */
1545 	pdev = NULL;
1546 	while ((pdev =
1547 		pci_get_subsys(PCI_ANY_ID, PCI_ANY_ID, PCI_ANY_ID,
1548 			       PCI_ANY_ID, pdev)) != NULL)
1549 		vga_arbiter_add_pci_device(pdev);
1550 
1551 	pr_info("loaded\n");
1552 	return rc;
1553 }
1554 subsys_initcall_sync(vga_arb_device_init);
1555