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