xref: /openbmc/linux/drivers/pci/vgaarb.c (revision 60a9bac8)
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  * Rules for using a bridge to control a VGA descendant decoding: if a bridge
633  * has only one VGA descendant then it can be used to control the VGA routing
634  * for that device. It should always use the bridge closest to the device to
635  * control it. If a bridge has a direct VGA descendant, but also have a sub-
636  * bridge VGA descendant then we cannot use that bridge to control the direct
637  * VGA descendant. So for every device we register, we need to iterate all
638  * its parent bridges so we can invalidate any devices using them properly.
639  */
640 static void vga_arbiter_check_bridge_sharing(struct vga_device *vgadev)
641 {
642 	struct vga_device *same_bridge_vgadev;
643 	struct pci_bus *new_bus, *bus;
644 	struct pci_dev *new_bridge, *bridge;
645 
646 	vgadev->bridge_has_one_vga = true;
647 
648 	if (list_empty(&vga_list))
649 		return;
650 
651 	/* okay iterate the new devices bridge hierarachy */
652 	new_bus = vgadev->pdev->bus;
653 	while (new_bus) {
654 		new_bridge = new_bus->self;
655 
656 		/* go through list of devices already registered */
657 		list_for_each_entry(same_bridge_vgadev, &vga_list, list) {
658 			bus = same_bridge_vgadev->pdev->bus;
659 			bridge = bus->self;
660 
661 			/* see if the share a bridge with this device */
662 			if (new_bridge == bridge) {
663 				/*
664 				 * If their direct parent bridge is the same
665 				 * as any bridge of this device then it can't
666 				 * be used for that device.
667 				 */
668 				same_bridge_vgadev->bridge_has_one_vga = false;
669 			}
670 
671 			/*
672 			 * Now iterate the previous devices bridge hierarchy.
673 			 * If the new devices parent bridge is in the other
674 			 * devices hierarchy then we can't use it to control
675 			 * this device
676 			 */
677 			while (bus) {
678 				bridge = bus->self;
679 
680 				if (bridge && bridge == vgadev->pdev->bus->self)
681 					vgadev->bridge_has_one_vga = false;
682 
683 				bus = bus->parent;
684 			}
685 		}
686 		new_bus = new_bus->parent;
687 	}
688 }
689 
690 /*
691  * Currently, we assume that the "initial" setup of the system is
692  * not sane, that is we come up with conflicting devices and let
693  * the arbiter's client decides if devices decodes or not legacy
694  * things.
695  */
696 static bool vga_arbiter_add_pci_device(struct pci_dev *pdev)
697 {
698 	struct vga_device *vgadev;
699 	unsigned long flags;
700 	struct pci_bus *bus;
701 	struct pci_dev *bridge;
702 	u16 cmd;
703 
704 	/* Only deal with VGA class devices */
705 	if ((pdev->class >> 8) != PCI_CLASS_DISPLAY_VGA)
706 		return false;
707 
708 	/* Allocate structure */
709 	vgadev = kzalloc(sizeof(struct vga_device), GFP_KERNEL);
710 	if (vgadev == NULL) {
711 		vgaarb_err(&pdev->dev, "failed to allocate VGA arbiter data\n");
712 		/*
713 		 * What to do on allocation failure ? For now, let's just do
714 		 * nothing, I'm not sure there is anything saner to be done.
715 		 */
716 		return false;
717 	}
718 
719 	/* Take lock & check for duplicates */
720 	spin_lock_irqsave(&vga_lock, flags);
721 	if (vgadev_find(pdev) != NULL) {
722 		BUG_ON(1);
723 		goto fail;
724 	}
725 	vgadev->pdev = pdev;
726 
727 	/* By default, assume we decode everything */
728 	vgadev->decodes = VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM |
729 			  VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM;
730 
731 	/* by default mark it as decoding */
732 	vga_decode_count++;
733 	/* Mark that we "own" resources based on our enables, we will
734 	 * clear that below if the bridge isn't forwarding
735 	 */
736 	pci_read_config_word(pdev, PCI_COMMAND, &cmd);
737 	if (cmd & PCI_COMMAND_IO)
738 		vgadev->owns |= VGA_RSRC_LEGACY_IO;
739 	if (cmd & PCI_COMMAND_MEMORY)
740 		vgadev->owns |= VGA_RSRC_LEGACY_MEM;
741 
742 	/* Check if VGA cycles can get down to us */
743 	bus = pdev->bus;
744 	while (bus) {
745 		bridge = bus->self;
746 		if (bridge) {
747 			u16 l;
748 
749 			pci_read_config_word(bridge, PCI_BRIDGE_CONTROL, &l);
750 			if (!(l & PCI_BRIDGE_CTL_VGA)) {
751 				vgadev->owns = 0;
752 				break;
753 			}
754 		}
755 		bus = bus->parent;
756 	}
757 
758 	/* Deal with VGA default device. Use first enabled one
759 	 * by default if arch doesn't have it's own hook
760 	 */
761 	if (vga_default == NULL &&
762 	    ((vgadev->owns & VGA_RSRC_LEGACY_MASK) == VGA_RSRC_LEGACY_MASK)) {
763 		vgaarb_info(&pdev->dev, "setting as boot VGA device\n");
764 		vga_set_default_device(pdev);
765 	}
766 
767 	vga_arbiter_check_bridge_sharing(vgadev);
768 
769 	/* Add to the list */
770 	list_add_tail(&vgadev->list, &vga_list);
771 	vga_count++;
772 	vgaarb_info(&pdev->dev, "VGA device added: decodes=%s,owns=%s,locks=%s\n",
773 		vga_iostate_to_str(vgadev->decodes),
774 		vga_iostate_to_str(vgadev->owns),
775 		vga_iostate_to_str(vgadev->locks));
776 
777 	spin_unlock_irqrestore(&vga_lock, flags);
778 	return true;
779 fail:
780 	spin_unlock_irqrestore(&vga_lock, flags);
781 	kfree(vgadev);
782 	return false;
783 }
784 
785 static bool vga_arbiter_del_pci_device(struct pci_dev *pdev)
786 {
787 	struct vga_device *vgadev;
788 	unsigned long flags;
789 	bool ret = true;
790 
791 	spin_lock_irqsave(&vga_lock, flags);
792 	vgadev = vgadev_find(pdev);
793 	if (vgadev == NULL) {
794 		ret = false;
795 		goto bail;
796 	}
797 
798 	if (vga_default == pdev)
799 		vga_set_default_device(NULL);
800 
801 	if (vgadev->decodes & (VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM))
802 		vga_decode_count--;
803 
804 	/* Remove entry from list */
805 	list_del(&vgadev->list);
806 	vga_count--;
807 	/* Notify userland driver that the device is gone so it discards
808 	 * it's copies of the pci_dev pointer
809 	 */
810 	vga_arb_device_card_gone(pdev);
811 
812 	/* Wake up all possible waiters */
813 	wake_up_all(&vga_wait_queue);
814 bail:
815 	spin_unlock_irqrestore(&vga_lock, flags);
816 	kfree(vgadev);
817 	return ret;
818 }
819 
820 /* this is called with the lock */
821 static inline void vga_update_device_decodes(struct vga_device *vgadev,
822 					     int new_decodes)
823 {
824 	struct device *dev = &vgadev->pdev->dev;
825 	int old_decodes, decodes_removed, decodes_unlocked;
826 
827 	old_decodes = vgadev->decodes;
828 	decodes_removed = ~new_decodes & old_decodes;
829 	decodes_unlocked = vgadev->locks & decodes_removed;
830 	vgadev->decodes = new_decodes;
831 
832 	vgaarb_info(dev, "changed VGA decodes: olddecodes=%s,decodes=%s:owns=%s\n",
833 		vga_iostate_to_str(old_decodes),
834 		vga_iostate_to_str(vgadev->decodes),
835 		vga_iostate_to_str(vgadev->owns));
836 
837 	/* if we removed locked decodes, lock count goes to zero, and release */
838 	if (decodes_unlocked) {
839 		if (decodes_unlocked & VGA_RSRC_LEGACY_IO)
840 			vgadev->io_lock_cnt = 0;
841 		if (decodes_unlocked & VGA_RSRC_LEGACY_MEM)
842 			vgadev->mem_lock_cnt = 0;
843 		__vga_put(vgadev, decodes_unlocked);
844 	}
845 
846 	/* change decodes counter */
847 	if (old_decodes & VGA_RSRC_LEGACY_MASK &&
848 	    !(new_decodes & VGA_RSRC_LEGACY_MASK))
849 		vga_decode_count--;
850 	if (!(old_decodes & VGA_RSRC_LEGACY_MASK) &&
851 	    new_decodes & VGA_RSRC_LEGACY_MASK)
852 		vga_decode_count++;
853 	vgaarb_dbg(dev, "decoding count now is: %d\n", vga_decode_count);
854 }
855 
856 static void __vga_set_legacy_decoding(struct pci_dev *pdev,
857 				      unsigned int decodes,
858 				      bool userspace)
859 {
860 	struct vga_device *vgadev;
861 	unsigned long flags;
862 
863 	decodes &= VGA_RSRC_LEGACY_MASK;
864 
865 	spin_lock_irqsave(&vga_lock, flags);
866 	vgadev = vgadev_find(pdev);
867 	if (vgadev == NULL)
868 		goto bail;
869 
870 	/* don't let userspace futz with kernel driver decodes */
871 	if (userspace && vgadev->set_decode)
872 		goto bail;
873 
874 	/* update the device decodes + counter */
875 	vga_update_device_decodes(vgadev, decodes);
876 
877 	/* XXX if somebody is going from "doesn't decode" to "decodes" state
878 	 * here, additional care must be taken as we may have pending owner
879 	 * ship of non-legacy region ...
880 	 */
881 bail:
882 	spin_unlock_irqrestore(&vga_lock, flags);
883 }
884 
885 /**
886  * vga_set_legacy_decoding
887  * @pdev: pci device of the VGA card
888  * @decodes: bit mask of what legacy regions the card decodes
889  *
890  * Indicates to the arbiter if the card decodes legacy VGA IOs, legacy VGA
891  * Memory, both, or none. All cards default to both, the card driver (fbdev for
892  * example) should tell the arbiter if it has disabled legacy decoding, so the
893  * card can be left out of the arbitration process (and can be safe to take
894  * interrupts at any time.
895  */
896 void vga_set_legacy_decoding(struct pci_dev *pdev, unsigned int decodes)
897 {
898 	__vga_set_legacy_decoding(pdev, decodes, false);
899 }
900 EXPORT_SYMBOL(vga_set_legacy_decoding);
901 
902 /**
903  * vga_client_register - register or unregister a VGA arbitration client
904  * @pdev: pci device of the VGA client
905  * @set_decode: vga decode change callback
906  *
907  * Clients have two callback mechanisms they can use.
908  *
909  * @set_decode callback: If a client can disable its GPU VGA resource, it
910  * will get a callback from this to set the encode/decode state.
911  *
912  * Rationale: we cannot disable VGA decode resources unconditionally some single
913  * GPU laptops seem to require ACPI or BIOS access to the VGA registers to
914  * control things like backlights etc.  Hopefully newer multi-GPU laptops do
915  * something saner, and desktops won't have any special ACPI for this. The
916  * driver will get a callback when VGA arbitration is first used by userspace
917  * since some older X servers have issues.
918  *
919  * This function does not check whether a client for @pdev has been registered
920  * already.
921  *
922  * To unregister just call vga_client_unregister().
923  *
924  * Returns: 0 on success, -1 on failure
925  */
926 int vga_client_register(struct pci_dev *pdev,
927 		unsigned int (*set_decode)(struct pci_dev *pdev, bool decode))
928 {
929 	int ret = -ENODEV;
930 	struct vga_device *vgadev;
931 	unsigned long flags;
932 
933 	spin_lock_irqsave(&vga_lock, flags);
934 	vgadev = vgadev_find(pdev);
935 	if (!vgadev)
936 		goto bail;
937 
938 	vgadev->set_decode = set_decode;
939 	ret = 0;
940 
941 bail:
942 	spin_unlock_irqrestore(&vga_lock, flags);
943 	return ret;
944 
945 }
946 EXPORT_SYMBOL(vga_client_register);
947 
948 /*
949  * Char driver implementation
950  *
951  * Semantics is:
952  *
953  *  open       : open user instance of the arbitrer. by default, it's
954  *                attached to the default VGA device of the system.
955  *
956  *  close      : close user instance, release locks
957  *
958  *  read       : return a string indicating the status of the target.
959  *                an IO state string is of the form {io,mem,io+mem,none},
960  *                mc and ic are respectively mem and io lock counts (for
961  *                debugging/diagnostic only). "decodes" indicate what the
962  *                card currently decodes, "owns" indicates what is currently
963  *                enabled on it, and "locks" indicates what is locked by this
964  *                card. If the card is unplugged, we get "invalid" then for
965  *                card_ID and an -ENODEV error is returned for any command
966  *                until a new card is targeted
967  *
968  *   "<card_ID>,decodes=<io_state>,owns=<io_state>,locks=<io_state> (ic,mc)"
969  *
970  * write       : write a command to the arbiter. List of commands is:
971  *
972  *   target <card_ID>   : switch target to card <card_ID> (see below)
973  *   lock <io_state>    : acquires locks on target ("none" is invalid io_state)
974  *   trylock <io_state> : non-blocking acquire locks on target
975  *   unlock <io_state>  : release locks on target
976  *   unlock all         : release all locks on target held by this user
977  *   decodes <io_state> : set the legacy decoding attributes for the card
978  *
979  * poll         : event if something change on any card (not just the target)
980  *
981  * card_ID is of the form "PCI:domain:bus:dev.fn". It can be set to "default"
982  * to go back to the system default card (TODO: not implemented yet).
983  * Currently, only PCI is supported as a prefix, but the userland API may
984  * support other bus types in the future, even if the current kernel
985  * implementation doesn't.
986  *
987  * Note about locks:
988  *
989  * The driver keeps track of which user has what locks on which card. It
990  * supports stacking, like the kernel one. This complexifies the implementation
991  * a bit, but makes the arbiter more tolerant to userspace problems and able
992  * to properly cleanup in all cases when a process dies.
993  * Currently, a max of 16 cards simultaneously can have locks issued from
994  * userspace for a given user (file descriptor instance) of the arbiter.
995  *
996  * If the device is hot-unplugged, there is a hook inside the module to notify
997  * they being added/removed in the system and automatically added/removed in
998  * the arbiter.
999  */
1000 
1001 #define MAX_USER_CARDS         CONFIG_VGA_ARB_MAX_GPUS
1002 #define PCI_INVALID_CARD       ((struct pci_dev *)-1UL)
1003 
1004 /*
1005  * Each user has an array of these, tracking which cards have locks
1006  */
1007 struct vga_arb_user_card {
1008 	struct pci_dev *pdev;
1009 	unsigned int mem_cnt;
1010 	unsigned int io_cnt;
1011 };
1012 
1013 struct vga_arb_private {
1014 	struct list_head list;
1015 	struct pci_dev *target;
1016 	struct vga_arb_user_card cards[MAX_USER_CARDS];
1017 	spinlock_t lock;
1018 };
1019 
1020 static LIST_HEAD(vga_user_list);
1021 static DEFINE_SPINLOCK(vga_user_lock);
1022 
1023 
1024 /*
1025  * This function gets a string in the format: "PCI:domain:bus:dev.fn" and
1026  * returns the respective values. If the string is not in this format,
1027  * it returns 0.
1028  */
1029 static int vga_pci_str_to_vars(char *buf, int count, unsigned int *domain,
1030 			       unsigned int *bus, unsigned int *devfn)
1031 {
1032 	int n;
1033 	unsigned int slot, func;
1034 
1035 
1036 	n = sscanf(buf, "PCI:%x:%x:%x.%x", domain, bus, &slot, &func);
1037 	if (n != 4)
1038 		return 0;
1039 
1040 	*devfn = PCI_DEVFN(slot, func);
1041 
1042 	return 1;
1043 }
1044 
1045 static ssize_t vga_arb_read(struct file *file, char __user *buf,
1046 			    size_t count, loff_t *ppos)
1047 {
1048 	struct vga_arb_private *priv = file->private_data;
1049 	struct vga_device *vgadev;
1050 	struct pci_dev *pdev;
1051 	unsigned long flags;
1052 	size_t len;
1053 	int rc;
1054 	char *lbuf;
1055 
1056 	lbuf = kmalloc(1024, GFP_KERNEL);
1057 	if (lbuf == NULL)
1058 		return -ENOMEM;
1059 
1060 	/* Shields against vga_arb_device_card_gone (pci_dev going
1061 	 * away), and allows access to vga list
1062 	 */
1063 	spin_lock_irqsave(&vga_lock, flags);
1064 
1065 	/* If we are targeting the default, use it */
1066 	pdev = priv->target;
1067 	if (pdev == NULL || pdev == PCI_INVALID_CARD) {
1068 		spin_unlock_irqrestore(&vga_lock, flags);
1069 		len = sprintf(lbuf, "invalid");
1070 		goto done;
1071 	}
1072 
1073 	/* Find card vgadev structure */
1074 	vgadev = vgadev_find(pdev);
1075 	if (vgadev == NULL) {
1076 		/* Wow, it's not in the list, that shouldn't happen,
1077 		 * let's fix us up and return invalid card
1078 		 */
1079 		if (pdev == priv->target)
1080 			vga_arb_device_card_gone(pdev);
1081 		spin_unlock_irqrestore(&vga_lock, flags);
1082 		len = sprintf(lbuf, "invalid");
1083 		goto done;
1084 	}
1085 
1086 	/* Fill the buffer with infos */
1087 	len = snprintf(lbuf, 1024,
1088 		       "count:%d,PCI:%s,decodes=%s,owns=%s,locks=%s(%d:%d)\n",
1089 		       vga_decode_count, pci_name(pdev),
1090 		       vga_iostate_to_str(vgadev->decodes),
1091 		       vga_iostate_to_str(vgadev->owns),
1092 		       vga_iostate_to_str(vgadev->locks),
1093 		       vgadev->io_lock_cnt, vgadev->mem_lock_cnt);
1094 
1095 	spin_unlock_irqrestore(&vga_lock, flags);
1096 done:
1097 
1098 	/* Copy that to user */
1099 	if (len > count)
1100 		len = count;
1101 	rc = copy_to_user(buf, lbuf, len);
1102 	kfree(lbuf);
1103 	if (rc)
1104 		return -EFAULT;
1105 	return len;
1106 }
1107 
1108 /*
1109  * TODO: To avoid parsing inside kernel and to improve the speed we may
1110  * consider use ioctl here
1111  */
1112 static ssize_t vga_arb_write(struct file *file, const char __user *buf,
1113 			     size_t count, loff_t *ppos)
1114 {
1115 	struct vga_arb_private *priv = file->private_data;
1116 	struct vga_arb_user_card *uc = NULL;
1117 	struct pci_dev *pdev;
1118 
1119 	unsigned int io_state;
1120 
1121 	char kbuf[64], *curr_pos;
1122 	size_t remaining = count;
1123 
1124 	int ret_val;
1125 	int i;
1126 
1127 	if (count >= sizeof(kbuf))
1128 		return -EINVAL;
1129 	if (copy_from_user(kbuf, buf, count))
1130 		return -EFAULT;
1131 	curr_pos = kbuf;
1132 	kbuf[count] = '\0';	/* Just to make sure... */
1133 
1134 	if (strncmp(curr_pos, "lock ", 5) == 0) {
1135 		curr_pos += 5;
1136 		remaining -= 5;
1137 
1138 		pr_debug("client 0x%p called 'lock'\n", priv);
1139 
1140 		if (!vga_str_to_iostate(curr_pos, remaining, &io_state)) {
1141 			ret_val = -EPROTO;
1142 			goto done;
1143 		}
1144 		if (io_state == VGA_RSRC_NONE) {
1145 			ret_val = -EPROTO;
1146 			goto done;
1147 		}
1148 
1149 		pdev = priv->target;
1150 		if (priv->target == NULL) {
1151 			ret_val = -ENODEV;
1152 			goto done;
1153 		}
1154 
1155 		vga_get_uninterruptible(pdev, io_state);
1156 
1157 		/* Update the client's locks lists... */
1158 		for (i = 0; i < MAX_USER_CARDS; i++) {
1159 			if (priv->cards[i].pdev == pdev) {
1160 				if (io_state & VGA_RSRC_LEGACY_IO)
1161 					priv->cards[i].io_cnt++;
1162 				if (io_state & VGA_RSRC_LEGACY_MEM)
1163 					priv->cards[i].mem_cnt++;
1164 				break;
1165 			}
1166 		}
1167 
1168 		ret_val = count;
1169 		goto done;
1170 	} else if (strncmp(curr_pos, "unlock ", 7) == 0) {
1171 		curr_pos += 7;
1172 		remaining -= 7;
1173 
1174 		pr_debug("client 0x%p called 'unlock'\n", priv);
1175 
1176 		if (strncmp(curr_pos, "all", 3) == 0)
1177 			io_state = VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
1178 		else {
1179 			if (!vga_str_to_iostate
1180 			    (curr_pos, remaining, &io_state)) {
1181 				ret_val = -EPROTO;
1182 				goto done;
1183 			}
1184 			/* TODO: Add this?
1185 			   if (io_state == VGA_RSRC_NONE) {
1186 			   ret_val = -EPROTO;
1187 			   goto done;
1188 			   }
1189 			  */
1190 		}
1191 
1192 		pdev = priv->target;
1193 		if (priv->target == NULL) {
1194 			ret_val = -ENODEV;
1195 			goto done;
1196 		}
1197 		for (i = 0; i < MAX_USER_CARDS; i++) {
1198 			if (priv->cards[i].pdev == pdev)
1199 				uc = &priv->cards[i];
1200 		}
1201 
1202 		if (!uc) {
1203 			ret_val = -EINVAL;
1204 			goto done;
1205 		}
1206 
1207 		if (io_state & VGA_RSRC_LEGACY_IO && uc->io_cnt == 0) {
1208 			ret_val = -EINVAL;
1209 			goto done;
1210 		}
1211 
1212 		if (io_state & VGA_RSRC_LEGACY_MEM && uc->mem_cnt == 0) {
1213 			ret_val = -EINVAL;
1214 			goto done;
1215 		}
1216 
1217 		vga_put(pdev, io_state);
1218 
1219 		if (io_state & VGA_RSRC_LEGACY_IO)
1220 			uc->io_cnt--;
1221 		if (io_state & VGA_RSRC_LEGACY_MEM)
1222 			uc->mem_cnt--;
1223 
1224 		ret_val = count;
1225 		goto done;
1226 	} else if (strncmp(curr_pos, "trylock ", 8) == 0) {
1227 		curr_pos += 8;
1228 		remaining -= 8;
1229 
1230 		pr_debug("client 0x%p called 'trylock'\n", priv);
1231 
1232 		if (!vga_str_to_iostate(curr_pos, remaining, &io_state)) {
1233 			ret_val = -EPROTO;
1234 			goto done;
1235 		}
1236 		/* TODO: Add this?
1237 		   if (io_state == VGA_RSRC_NONE) {
1238 		   ret_val = -EPROTO;
1239 		   goto done;
1240 		   }
1241 		 */
1242 
1243 		pdev = priv->target;
1244 		if (priv->target == NULL) {
1245 			ret_val = -ENODEV;
1246 			goto done;
1247 		}
1248 
1249 		if (vga_tryget(pdev, io_state)) {
1250 			/* Update the client's locks lists... */
1251 			for (i = 0; i < MAX_USER_CARDS; i++) {
1252 				if (priv->cards[i].pdev == pdev) {
1253 					if (io_state & VGA_RSRC_LEGACY_IO)
1254 						priv->cards[i].io_cnt++;
1255 					if (io_state & VGA_RSRC_LEGACY_MEM)
1256 						priv->cards[i].mem_cnt++;
1257 					break;
1258 				}
1259 			}
1260 			ret_val = count;
1261 			goto done;
1262 		} else {
1263 			ret_val = -EBUSY;
1264 			goto done;
1265 		}
1266 
1267 	} else if (strncmp(curr_pos, "target ", 7) == 0) {
1268 		unsigned int domain, bus, devfn;
1269 		struct vga_device *vgadev;
1270 
1271 		curr_pos += 7;
1272 		remaining -= 7;
1273 		pr_debug("client 0x%p called 'target'\n", priv);
1274 		/* if target is default */
1275 		if (!strncmp(curr_pos, "default", 7))
1276 			pdev = pci_dev_get(vga_default_device());
1277 		else {
1278 			if (!vga_pci_str_to_vars(curr_pos, remaining,
1279 						 &domain, &bus, &devfn)) {
1280 				ret_val = -EPROTO;
1281 				goto done;
1282 			}
1283 			pdev = pci_get_domain_bus_and_slot(domain, bus, devfn);
1284 			if (!pdev) {
1285 				pr_debug("invalid PCI address %04x:%02x:%02x.%x\n",
1286 					 domain, bus, PCI_SLOT(devfn),
1287 					 PCI_FUNC(devfn));
1288 				ret_val = -ENODEV;
1289 				goto done;
1290 			}
1291 
1292 			pr_debug("%s ==> %04x:%02x:%02x.%x pdev %p\n", curr_pos,
1293 				domain, bus, PCI_SLOT(devfn), PCI_FUNC(devfn),
1294 				pdev);
1295 		}
1296 
1297 		vgadev = vgadev_find(pdev);
1298 		pr_debug("vgadev %p\n", vgadev);
1299 		if (vgadev == NULL) {
1300 			if (pdev) {
1301 				vgaarb_dbg(&pdev->dev, "not a VGA device\n");
1302 				pci_dev_put(pdev);
1303 			}
1304 
1305 			ret_val = -ENODEV;
1306 			goto done;
1307 		}
1308 
1309 		priv->target = pdev;
1310 		for (i = 0; i < MAX_USER_CARDS; i++) {
1311 			if (priv->cards[i].pdev == pdev)
1312 				break;
1313 			if (priv->cards[i].pdev == NULL) {
1314 				priv->cards[i].pdev = pdev;
1315 				priv->cards[i].io_cnt = 0;
1316 				priv->cards[i].mem_cnt = 0;
1317 				break;
1318 			}
1319 		}
1320 		if (i == MAX_USER_CARDS) {
1321 			vgaarb_dbg(&pdev->dev, "maximum user cards (%d) number reached, ignoring this one!\n",
1322 				MAX_USER_CARDS);
1323 			pci_dev_put(pdev);
1324 			/* XXX: which value to return? */
1325 			ret_val =  -ENOMEM;
1326 			goto done;
1327 		}
1328 
1329 		ret_val = count;
1330 		pci_dev_put(pdev);
1331 		goto done;
1332 
1333 
1334 	} else if (strncmp(curr_pos, "decodes ", 8) == 0) {
1335 		curr_pos += 8;
1336 		remaining -= 8;
1337 		pr_debug("client 0x%p called 'decodes'\n", priv);
1338 
1339 		if (!vga_str_to_iostate(curr_pos, remaining, &io_state)) {
1340 			ret_val = -EPROTO;
1341 			goto done;
1342 		}
1343 		pdev = priv->target;
1344 		if (priv->target == NULL) {
1345 			ret_val = -ENODEV;
1346 			goto done;
1347 		}
1348 
1349 		__vga_set_legacy_decoding(pdev, io_state, true);
1350 		ret_val = count;
1351 		goto done;
1352 	}
1353 	/* If we got here, the message written is not part of the protocol! */
1354 	return -EPROTO;
1355 
1356 done:
1357 	return ret_val;
1358 }
1359 
1360 static __poll_t vga_arb_fpoll(struct file *file, poll_table *wait)
1361 {
1362 	pr_debug("%s\n", __func__);
1363 
1364 	poll_wait(file, &vga_wait_queue, wait);
1365 	return EPOLLIN;
1366 }
1367 
1368 static int vga_arb_open(struct inode *inode, struct file *file)
1369 {
1370 	struct vga_arb_private *priv;
1371 	unsigned long flags;
1372 
1373 	pr_debug("%s\n", __func__);
1374 
1375 	priv = kzalloc(sizeof(*priv), GFP_KERNEL);
1376 	if (priv == NULL)
1377 		return -ENOMEM;
1378 	spin_lock_init(&priv->lock);
1379 	file->private_data = priv;
1380 
1381 	spin_lock_irqsave(&vga_user_lock, flags);
1382 	list_add(&priv->list, &vga_user_list);
1383 	spin_unlock_irqrestore(&vga_user_lock, flags);
1384 
1385 	/* Set the client' lists of locks */
1386 	priv->target = vga_default_device(); /* Maybe this is still null! */
1387 	priv->cards[0].pdev = priv->target;
1388 	priv->cards[0].io_cnt = 0;
1389 	priv->cards[0].mem_cnt = 0;
1390 
1391 
1392 	return 0;
1393 }
1394 
1395 static int vga_arb_release(struct inode *inode, struct file *file)
1396 {
1397 	struct vga_arb_private *priv = file->private_data;
1398 	struct vga_arb_user_card *uc;
1399 	unsigned long flags;
1400 	int i;
1401 
1402 	pr_debug("%s\n", __func__);
1403 
1404 	spin_lock_irqsave(&vga_user_lock, flags);
1405 	list_del(&priv->list);
1406 	for (i = 0; i < MAX_USER_CARDS; i++) {
1407 		uc = &priv->cards[i];
1408 		if (uc->pdev == NULL)
1409 			continue;
1410 		vgaarb_dbg(&uc->pdev->dev, "uc->io_cnt == %d, uc->mem_cnt == %d\n",
1411 			uc->io_cnt, uc->mem_cnt);
1412 		while (uc->io_cnt--)
1413 			vga_put(uc->pdev, VGA_RSRC_LEGACY_IO);
1414 		while (uc->mem_cnt--)
1415 			vga_put(uc->pdev, VGA_RSRC_LEGACY_MEM);
1416 	}
1417 	spin_unlock_irqrestore(&vga_user_lock, flags);
1418 
1419 	kfree(priv);
1420 
1421 	return 0;
1422 }
1423 
1424 static void vga_arb_device_card_gone(struct pci_dev *pdev)
1425 {
1426 }
1427 
1428 /*
1429  * callback any registered clients to let them know we have a
1430  * change in VGA cards
1431  */
1432 static void vga_arbiter_notify_clients(void)
1433 {
1434 	struct vga_device *vgadev;
1435 	unsigned long flags;
1436 	uint32_t new_decodes;
1437 	bool new_state;
1438 
1439 	if (!vga_arbiter_used)
1440 		return;
1441 
1442 	spin_lock_irqsave(&vga_lock, flags);
1443 	list_for_each_entry(vgadev, &vga_list, list) {
1444 		if (vga_count > 1)
1445 			new_state = false;
1446 		else
1447 			new_state = true;
1448 		if (vgadev->set_decode) {
1449 			new_decodes = vgadev->set_decode(vgadev->pdev,
1450 							 new_state);
1451 			vga_update_device_decodes(vgadev, new_decodes);
1452 		}
1453 	}
1454 	spin_unlock_irqrestore(&vga_lock, flags);
1455 }
1456 
1457 static int pci_notify(struct notifier_block *nb, unsigned long action,
1458 		      void *data)
1459 {
1460 	struct device *dev = data;
1461 	struct pci_dev *pdev = to_pci_dev(dev);
1462 	bool notify = false;
1463 
1464 	vgaarb_dbg(dev, "%s\n", __func__);
1465 
1466 	/* For now we're only intereted in devices added and removed. I didn't
1467 	 * test this thing here, so someone needs to double check for the
1468 	 * cases of hotplugable vga cards. */
1469 	if (action == BUS_NOTIFY_ADD_DEVICE)
1470 		notify = vga_arbiter_add_pci_device(pdev);
1471 	else if (action == BUS_NOTIFY_DEL_DEVICE)
1472 		notify = vga_arbiter_del_pci_device(pdev);
1473 
1474 	if (notify)
1475 		vga_arbiter_notify_clients();
1476 	return 0;
1477 }
1478 
1479 static struct notifier_block pci_notifier = {
1480 	.notifier_call = pci_notify,
1481 };
1482 
1483 static const struct file_operations vga_arb_device_fops = {
1484 	.read = vga_arb_read,
1485 	.write = vga_arb_write,
1486 	.poll = vga_arb_fpoll,
1487 	.open = vga_arb_open,
1488 	.release = vga_arb_release,
1489 	.llseek = noop_llseek,
1490 };
1491 
1492 static struct miscdevice vga_arb_device = {
1493 	MISC_DYNAMIC_MINOR, "vga_arbiter", &vga_arb_device_fops
1494 };
1495 
1496 static void __init vga_arb_select_default_device(void)
1497 {
1498 	struct pci_dev *pdev, *found = NULL;
1499 	struct vga_device *vgadev;
1500 
1501 	list_for_each_entry(vgadev, &vga_list, list) {
1502 		vga_select_framebuffer_device(vgadev->pdev);
1503 	}
1504 
1505 	if (!vga_default_device()) {
1506 		list_for_each_entry_reverse(vgadev, &vga_list, list) {
1507 			struct device *dev = &vgadev->pdev->dev;
1508 			u16 cmd;
1509 
1510 			pdev = vgadev->pdev;
1511 			pci_read_config_word(pdev, PCI_COMMAND, &cmd);
1512 			if (cmd & (PCI_COMMAND_IO | PCI_COMMAND_MEMORY)) {
1513 				found = pdev;
1514 				if (vga_arb_integrated_gpu(dev))
1515 					break;
1516 			}
1517 		}
1518 	}
1519 
1520 	if (found) {
1521 		vgaarb_info(&found->dev, "setting as boot device (VGA legacy resources not available)\n");
1522 		vga_set_default_device(found);
1523 		return;
1524 	}
1525 
1526 	if (!vga_default_device()) {
1527 		vgadev = list_first_entry_or_null(&vga_list,
1528 						  struct vga_device, list);
1529 		if (vgadev) {
1530 			struct device *dev = &vgadev->pdev->dev;
1531 			vgaarb_info(dev, "setting as boot device (VGA legacy resources not available)\n");
1532 			vga_set_default_device(vgadev->pdev);
1533 		}
1534 	}
1535 }
1536 
1537 static int __init vga_arb_device_init(void)
1538 {
1539 	int rc;
1540 	struct pci_dev *pdev;
1541 	struct vga_device *vgadev;
1542 
1543 	rc = misc_register(&vga_arb_device);
1544 	if (rc < 0)
1545 		pr_err("error %d registering device\n", rc);
1546 
1547 	bus_register_notifier(&pci_bus_type, &pci_notifier);
1548 
1549 	/* We add all PCI devices satisfying VGA class in the arbiter by
1550 	 * default */
1551 	pdev = NULL;
1552 	while ((pdev =
1553 		pci_get_subsys(PCI_ANY_ID, PCI_ANY_ID, PCI_ANY_ID,
1554 			       PCI_ANY_ID, pdev)) != NULL)
1555 		vga_arbiter_add_pci_device(pdev);
1556 
1557 	list_for_each_entry(vgadev, &vga_list, list) {
1558 		struct device *dev = &vgadev->pdev->dev;
1559 
1560 		if (vgadev->bridge_has_one_vga)
1561 			vgaarb_info(dev, "bridge control possible\n");
1562 		else
1563 			vgaarb_info(dev, "no bridge control possible\n");
1564 	}
1565 
1566 	vga_arb_select_default_device();
1567 
1568 	pr_info("loaded\n");
1569 	return rc;
1570 }
1571 subsys_initcall_sync(vga_arb_device_init);
1572