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