2 * vgaarb.c: Implements the VGA arbitration. For details refer to
3 * Documentation/gpu/vgaarbiter.rst
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:
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
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
32 #define pr_fmt(fmt) "vgaarb: " fmt
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)
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>
52 #include <linux/console.h>
53 #include <linux/acpi.h>
55 #include <linux/uaccess.h>
57 #include <linux/vgaarb.h>
59 static void vga_arbiter_notify_clients(void);
61 * We keep a list of all vga devices in the system to speed
62 * up the various operations of the arbiter
65 struct list_head list;
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);
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);
85 static const char *vga_iostate_to_str(unsigned int iostate)
87 /* Ignore VGA_RSRC_IO and VGA_RSRC_MEM */
88 iostate &= VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
90 case VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM:
92 case VGA_RSRC_LEGACY_IO:
94 case VGA_RSRC_LEGACY_MEM:
100 static int vga_str_to_iostate(char *buf, int str_size, int *io_state)
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;
109 /* XXX We're not chekcing the str_size! */
110 if (strncmp(buf, "io+mem", 6) == 0)
112 else if (strncmp(buf, "io", 2) == 0)
114 else if (strncmp(buf, "mem", 3) == 0)
118 *io_state = VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
122 /* this is only used a cookie - it should not be dereferenced */
123 static struct pci_dev *vga_default;
125 static void vga_arb_device_card_gone(struct pci_dev *pdev);
127 /* Find somebody in our list */
128 static struct vga_device *vgadev_find(struct pci_dev *pdev)
130 struct vga_device *vgadev;
132 list_for_each_entry(vgadev, &vga_list, list)
133 if (pdev == vgadev->pdev)
139 * vga_default_device - return the default VGA device, for vgacon
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.
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
156 struct pci_dev *vga_default_device(void)
160 EXPORT_SYMBOL_GPL(vga_default_device);
162 void vga_set_default_device(struct pci_dev *pdev)
164 if (vga_default == pdev)
167 pci_dev_put(vga_default);
168 vga_default = pci_dev_get(pdev);
172 * vga_remove_vgacon - deactivete vga console
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
181 #if !defined(CONFIG_VGA_CONSOLE)
182 int vga_remove_vgacon(struct pci_dev *pdev)
186 #elif !defined(CONFIG_DUMMY_CONSOLE)
187 int vga_remove_vgacon(struct pci_dev *pdev)
192 int vga_remove_vgacon(struct pci_dev *pdev)
196 if (pdev != vga_default)
198 vgaarb_info(&pdev->dev, "deactivate vga console\n");
201 if (con_is_bound(&vga_con))
202 ret = do_take_over_console(&dummy_con, 0,
203 MAX_NR_CONSOLES - 1, 1);
205 ret = do_unregister_con_driver(&vga_con);
207 /* Ignore "already unregistered". */
216 EXPORT_SYMBOL(vga_remove_vgacon);
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)
223 /* we should inform all GPUs in the system that
224 * VGA arb has occurred and to try and disable resources
226 if (!vga_arbiter_used) {
227 vga_arbiter_used = true;
228 vga_arbiter_notify_clients();
232 static struct vga_device *__vga_tryget(struct vga_device *vgadev,
235 struct device *dev = &vgadev->pdev->dev;
236 unsigned int wants, legacy_wants, match;
237 struct vga_device *conflict;
238 unsigned int pci_bits;
241 /* Account for "normal" resources to lock. If we decode the legacy,
242 * counterpart, we need to request it as well
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;
251 vgaarb_dbg(dev, "%s: %d\n", __func__, rsrc);
252 vgaarb_dbg(dev, "%s: owns: %d\n", __func__, vgadev->owns);
254 /* Check what resources we need to acquire */
255 wants = rsrc & ~vgadev->owns;
257 /* We already own everything, just mark locked & bye bye */
261 /* We don't need to request a legacy resource, we just enable
262 * appropriate decoding and go
264 legacy_wants = wants & VGA_RSRC_LEGACY_MASK;
265 if (legacy_wants == 0)
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;
273 /* Don't conflict with myself */
274 if (vgadev == conflict)
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
283 if (vgadev->pdev->bus != conflict->pdev->bus) {
285 lwants = VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
288 /* Check if the guy has a lock on the resource. If he does,
289 * return the conflicting entry
291 if (conflict->locks & lwants)
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.
298 match = lwants & conflict->owns;
302 /* looks like he doesn't have a lock, we can steal
309 /* If we can't control legacy resources via the bridge, we
310 * also need to disable normal decoding.
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;
319 flags |= PCI_VGA_STATE_CHANGE_DECODES;
323 flags |= PCI_VGA_STATE_CHANGE_BRIDGE;
325 pci_set_vga_state(conflict->pdev, false, pci_bits, flags);
326 conflict->owns &= ~match;
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;
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".
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;
351 if (wants & VGA_RSRC_LEGACY_MASK)
352 flags |= PCI_VGA_STATE_CHANGE_BRIDGE;
354 pci_set_vga_state(vgadev->pdev, true, pci_bits, flags);
356 vgadev->owns |= wants;
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++;
371 static void __vga_put(struct vga_device *vgadev, unsigned int rsrc)
373 struct device *dev = &vgadev->pdev->dev;
374 unsigned int old_locks = vgadev->locks;
376 vgaarb_dbg(dev, "%s\n", __func__);
378 /* Update our counters, and account for equivalent legacy resources
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;
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;
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--;
396 /* Just clear lock bits, we do lazy operations so we don't really
397 * have to bother about anything else at this point
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;
404 /* Kick the wait queue in case somebody was waiting if we actually
407 if (old_locks != vgadev->locks)
408 wake_up_all(&vga_wait_queue);
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 ?
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.
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).
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
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)
439 * On success, release the VGA resource again with vga_put().
443 * 0 on success, negative error code on failure.
445 int vga_get(struct pci_dev *pdev, unsigned int rsrc, int interruptible)
447 struct vga_device *vgadev, *conflict;
449 wait_queue_entry_t wait;
452 vga_check_first_use();
453 /* The one who calls us should check for this, but lets be sure... */
455 pdev = vga_default_device();
460 spin_lock_irqsave(&vga_lock, flags);
461 vgadev = vgadev_find(pdev);
462 if (vgadev == NULL) {
463 spin_unlock_irqrestore(&vga_lock, flags);
467 conflict = __vga_tryget(vgadev, rsrc);
468 spin_unlock_irqrestore(&vga_lock, flags);
469 if (conflict == NULL)
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
479 init_waitqueue_entry(&wait, current);
480 add_wait_queue(&vga_wait_queue, &wait);
481 set_current_state(interruptible ?
483 TASK_UNINTERRUPTIBLE);
484 if (interruptible && signal_pending(current)) {
485 __set_current_state(TASK_RUNNING);
486 remove_wait_queue(&vga_wait_queue, &wait);
491 remove_wait_queue(&vga_wait_queue, &wait);
495 EXPORT_SYMBOL(vga_get);
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
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
506 * On success, release the VGA resource again with vga_put().
510 * 0 on success, negative error code on failure.
512 static int vga_tryget(struct pci_dev *pdev, unsigned int rsrc)
514 struct vga_device *vgadev;
518 vga_check_first_use();
520 /* The one who calls us should check for this, but lets be sure... */
522 pdev = vga_default_device();
525 spin_lock_irqsave(&vga_lock, flags);
526 vgadev = vgadev_find(pdev);
527 if (vgadev == NULL) {
531 if (__vga_tryget(vgadev, rsrc))
534 spin_unlock_irqrestore(&vga_lock, flags);
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
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.
548 void vga_put(struct pci_dev *pdev, unsigned int rsrc)
550 struct vga_device *vgadev;
553 /* The one who calls us should check for this, but lets be sure... */
555 pdev = vga_default_device();
558 spin_lock_irqsave(&vga_lock, flags);
559 vgadev = vgadev_find(pdev);
562 __vga_put(vgadev, rsrc);
564 spin_unlock_irqrestore(&vga_lock, flags);
566 EXPORT_SYMBOL(vga_put);
569 * Rules for using a bridge to control a VGA descendant decoding: if a bridge
570 * has only one VGA descendant then it can be used to control the VGA routing
571 * for that device. It should always use the bridge closest to the device to
572 * control it. If a bridge has a direct VGA descendant, but also have a sub-
573 * bridge VGA descendant then we cannot use that bridge to control the direct
574 * VGA descendant. So for every device we register, we need to iterate all
575 * its parent bridges so we can invalidate any devices using them properly.
577 static void vga_arbiter_check_bridge_sharing(struct vga_device *vgadev)
579 struct vga_device *same_bridge_vgadev;
580 struct pci_bus *new_bus, *bus;
581 struct pci_dev *new_bridge, *bridge;
583 vgadev->bridge_has_one_vga = true;
585 if (list_empty(&vga_list))
588 /* okay iterate the new devices bridge hierarachy */
589 new_bus = vgadev->pdev->bus;
591 new_bridge = new_bus->self;
593 /* go through list of devices already registered */
594 list_for_each_entry(same_bridge_vgadev, &vga_list, list) {
595 bus = same_bridge_vgadev->pdev->bus;
598 /* see if the share a bridge with this device */
599 if (new_bridge == bridge) {
601 * If their direct parent bridge is the same
602 * as any bridge of this device then it can't
603 * be used for that device.
605 same_bridge_vgadev->bridge_has_one_vga = false;
609 * Now iterate the previous devices bridge hierarchy.
610 * If the new devices parent bridge is in the other
611 * devices hierarchy then we can't use it to control
617 if (bridge && bridge == vgadev->pdev->bus->self)
618 vgadev->bridge_has_one_vga = false;
623 new_bus = new_bus->parent;
628 * Currently, we assume that the "initial" setup of the system is
629 * not sane, that is we come up with conflicting devices and let
630 * the arbiter's client decides if devices decodes or not legacy
633 static bool vga_arbiter_add_pci_device(struct pci_dev *pdev)
635 struct vga_device *vgadev;
638 struct pci_dev *bridge;
641 /* Only deal with VGA class devices */
642 if ((pdev->class >> 8) != PCI_CLASS_DISPLAY_VGA)
645 /* Allocate structure */
646 vgadev = kzalloc(sizeof(struct vga_device), GFP_KERNEL);
647 if (vgadev == NULL) {
648 vgaarb_err(&pdev->dev, "failed to allocate VGA arbiter data\n");
650 * What to do on allocation failure ? For now, let's just do
651 * nothing, I'm not sure there is anything saner to be done.
656 /* Take lock & check for duplicates */
657 spin_lock_irqsave(&vga_lock, flags);
658 if (vgadev_find(pdev) != NULL) {
664 /* By default, assume we decode everything */
665 vgadev->decodes = VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM |
666 VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM;
668 /* by default mark it as decoding */
670 /* Mark that we "own" resources based on our enables, we will
671 * clear that below if the bridge isn't forwarding
673 pci_read_config_word(pdev, PCI_COMMAND, &cmd);
674 if (cmd & PCI_COMMAND_IO)
675 vgadev->owns |= VGA_RSRC_LEGACY_IO;
676 if (cmd & PCI_COMMAND_MEMORY)
677 vgadev->owns |= VGA_RSRC_LEGACY_MEM;
679 /* Check if VGA cycles can get down to us */
686 pci_read_config_word(bridge, PCI_BRIDGE_CONTROL, &l);
687 if (!(l & PCI_BRIDGE_CTL_VGA)) {
695 /* Deal with VGA default device. Use first enabled one
696 * by default if arch doesn't have it's own hook
698 if (vga_default == NULL &&
699 ((vgadev->owns & VGA_RSRC_LEGACY_MASK) == VGA_RSRC_LEGACY_MASK)) {
700 vgaarb_info(&pdev->dev, "setting as boot VGA device\n");
701 vga_set_default_device(pdev);
704 vga_arbiter_check_bridge_sharing(vgadev);
706 /* Add to the list */
707 list_add_tail(&vgadev->list, &vga_list);
709 vgaarb_info(&pdev->dev, "VGA device added: decodes=%s,owns=%s,locks=%s\n",
710 vga_iostate_to_str(vgadev->decodes),
711 vga_iostate_to_str(vgadev->owns),
712 vga_iostate_to_str(vgadev->locks));
714 spin_unlock_irqrestore(&vga_lock, flags);
717 spin_unlock_irqrestore(&vga_lock, flags);
722 static bool vga_arbiter_del_pci_device(struct pci_dev *pdev)
724 struct vga_device *vgadev;
728 spin_lock_irqsave(&vga_lock, flags);
729 vgadev = vgadev_find(pdev);
730 if (vgadev == NULL) {
735 if (vga_default == pdev)
736 vga_set_default_device(NULL);
738 if (vgadev->decodes & (VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM))
741 /* Remove entry from list */
742 list_del(&vgadev->list);
744 /* Notify userland driver that the device is gone so it discards
745 * it's copies of the pci_dev pointer
747 vga_arb_device_card_gone(pdev);
749 /* Wake up all possible waiters */
750 wake_up_all(&vga_wait_queue);
752 spin_unlock_irqrestore(&vga_lock, flags);
757 /* this is called with the lock */
758 static inline void vga_update_device_decodes(struct vga_device *vgadev,
761 struct device *dev = &vgadev->pdev->dev;
762 int old_decodes, decodes_removed, decodes_unlocked;
764 old_decodes = vgadev->decodes;
765 decodes_removed = ~new_decodes & old_decodes;
766 decodes_unlocked = vgadev->locks & decodes_removed;
767 vgadev->decodes = new_decodes;
769 vgaarb_info(dev, "changed VGA decodes: olddecodes=%s,decodes=%s:owns=%s\n",
770 vga_iostate_to_str(old_decodes),
771 vga_iostate_to_str(vgadev->decodes),
772 vga_iostate_to_str(vgadev->owns));
774 /* if we removed locked decodes, lock count goes to zero, and release */
775 if (decodes_unlocked) {
776 if (decodes_unlocked & VGA_RSRC_LEGACY_IO)
777 vgadev->io_lock_cnt = 0;
778 if (decodes_unlocked & VGA_RSRC_LEGACY_MEM)
779 vgadev->mem_lock_cnt = 0;
780 __vga_put(vgadev, decodes_unlocked);
783 /* change decodes counter */
784 if (old_decodes & VGA_RSRC_LEGACY_MASK &&
785 !(new_decodes & VGA_RSRC_LEGACY_MASK))
787 if (!(old_decodes & VGA_RSRC_LEGACY_MASK) &&
788 new_decodes & VGA_RSRC_LEGACY_MASK)
790 vgaarb_dbg(dev, "decoding count now is: %d\n", vga_decode_count);
793 static void __vga_set_legacy_decoding(struct pci_dev *pdev,
794 unsigned int decodes,
797 struct vga_device *vgadev;
800 decodes &= VGA_RSRC_LEGACY_MASK;
802 spin_lock_irqsave(&vga_lock, flags);
803 vgadev = vgadev_find(pdev);
807 /* don't let userspace futz with kernel driver decodes */
808 if (userspace && vgadev->set_decode)
811 /* update the device decodes + counter */
812 vga_update_device_decodes(vgadev, decodes);
814 /* XXX if somebody is going from "doesn't decode" to "decodes" state
815 * here, additional care must be taken as we may have pending owner
816 * ship of non-legacy region ...
819 spin_unlock_irqrestore(&vga_lock, flags);
823 * vga_set_legacy_decoding
824 * @pdev: pci device of the VGA card
825 * @decodes: bit mask of what legacy regions the card decodes
827 * Indicates to the arbiter if the card decodes legacy VGA IOs, legacy VGA
828 * Memory, both, or none. All cards default to both, the card driver (fbdev for
829 * example) should tell the arbiter if it has disabled legacy decoding, so the
830 * card can be left out of the arbitration process (and can be safe to take
831 * interrupts at any time.
833 void vga_set_legacy_decoding(struct pci_dev *pdev, unsigned int decodes)
835 __vga_set_legacy_decoding(pdev, decodes, false);
837 EXPORT_SYMBOL(vga_set_legacy_decoding);
840 * vga_client_register - register or unregister a VGA arbitration client
841 * @pdev: pci device of the VGA client
842 * @set_decode: vga decode change callback
844 * Clients have two callback mechanisms they can use.
846 * @set_decode callback: If a client can disable its GPU VGA resource, it
847 * will get a callback from this to set the encode/decode state.
849 * Rationale: we cannot disable VGA decode resources unconditionally some single
850 * GPU laptops seem to require ACPI or BIOS access to the VGA registers to
851 * control things like backlights etc. Hopefully newer multi-GPU laptops do
852 * something saner, and desktops won't have any special ACPI for this. The
853 * driver will get a callback when VGA arbitration is first used by userspace
854 * since some older X servers have issues.
856 * This function does not check whether a client for @pdev has been registered
859 * To unregister just call vga_client_unregister().
861 * Returns: 0 on success, -1 on failure
863 int vga_client_register(struct pci_dev *pdev,
864 unsigned int (*set_decode)(struct pci_dev *pdev, bool decode))
867 struct vga_device *vgadev;
870 spin_lock_irqsave(&vga_lock, flags);
871 vgadev = vgadev_find(pdev);
875 vgadev->set_decode = set_decode;
879 spin_unlock_irqrestore(&vga_lock, flags);
883 EXPORT_SYMBOL(vga_client_register);
886 * Char driver implementation
890 * open : open user instance of the arbitrer. by default, it's
891 * attached to the default VGA device of the system.
893 * close : close user instance, release locks
895 * read : return a string indicating the status of the target.
896 * an IO state string is of the form {io,mem,io+mem,none},
897 * mc and ic are respectively mem and io lock counts (for
898 * debugging/diagnostic only). "decodes" indicate what the
899 * card currently decodes, "owns" indicates what is currently
900 * enabled on it, and "locks" indicates what is locked by this
901 * card. If the card is unplugged, we get "invalid" then for
902 * card_ID and an -ENODEV error is returned for any command
903 * until a new card is targeted
905 * "<card_ID>,decodes=<io_state>,owns=<io_state>,locks=<io_state> (ic,mc)"
907 * write : write a command to the arbiter. List of commands is:
909 * target <card_ID> : switch target to card <card_ID> (see below)
910 * lock <io_state> : acquires locks on target ("none" is invalid io_state)
911 * trylock <io_state> : non-blocking acquire locks on target
912 * unlock <io_state> : release locks on target
913 * unlock all : release all locks on target held by this user
914 * decodes <io_state> : set the legacy decoding attributes for the card
916 * poll : event if something change on any card (not just the target)
918 * card_ID is of the form "PCI:domain:bus:dev.fn". It can be set to "default"
919 * to go back to the system default card (TODO: not implemented yet).
920 * Currently, only PCI is supported as a prefix, but the userland API may
921 * support other bus types in the future, even if the current kernel
922 * implementation doesn't.
926 * The driver keeps track of which user has what locks on which card. It
927 * supports stacking, like the kernel one. This complexifies the implementation
928 * a bit, but makes the arbiter more tolerant to userspace problems and able
929 * to properly cleanup in all cases when a process dies.
930 * Currently, a max of 16 cards simultaneously can have locks issued from
931 * userspace for a given user (file descriptor instance) of the arbiter.
933 * If the device is hot-unplugged, there is a hook inside the module to notify
934 * they being added/removed in the system and automatically added/removed in
938 #define MAX_USER_CARDS CONFIG_VGA_ARB_MAX_GPUS
939 #define PCI_INVALID_CARD ((struct pci_dev *)-1UL)
942 * Each user has an array of these, tracking which cards have locks
944 struct vga_arb_user_card {
945 struct pci_dev *pdev;
946 unsigned int mem_cnt;
950 struct vga_arb_private {
951 struct list_head list;
952 struct pci_dev *target;
953 struct vga_arb_user_card cards[MAX_USER_CARDS];
957 static LIST_HEAD(vga_user_list);
958 static DEFINE_SPINLOCK(vga_user_lock);
962 * This function gets a string in the format: "PCI:domain:bus:dev.fn" and
963 * returns the respective values. If the string is not in this format,
966 static int vga_pci_str_to_vars(char *buf, int count, unsigned int *domain,
967 unsigned int *bus, unsigned int *devfn)
970 unsigned int slot, func;
973 n = sscanf(buf, "PCI:%x:%x:%x.%x", domain, bus, &slot, &func);
977 *devfn = PCI_DEVFN(slot, func);
982 static ssize_t vga_arb_read(struct file *file, char __user *buf,
983 size_t count, loff_t *ppos)
985 struct vga_arb_private *priv = file->private_data;
986 struct vga_device *vgadev;
987 struct pci_dev *pdev;
993 lbuf = kmalloc(1024, GFP_KERNEL);
997 /* Shields against vga_arb_device_card_gone (pci_dev going
998 * away), and allows access to vga list
1000 spin_lock_irqsave(&vga_lock, flags);
1002 /* If we are targeting the default, use it */
1003 pdev = priv->target;
1004 if (pdev == NULL || pdev == PCI_INVALID_CARD) {
1005 spin_unlock_irqrestore(&vga_lock, flags);
1006 len = sprintf(lbuf, "invalid");
1010 /* Find card vgadev structure */
1011 vgadev = vgadev_find(pdev);
1012 if (vgadev == NULL) {
1013 /* Wow, it's not in the list, that shouldn't happen,
1014 * let's fix us up and return invalid card
1016 if (pdev == priv->target)
1017 vga_arb_device_card_gone(pdev);
1018 spin_unlock_irqrestore(&vga_lock, flags);
1019 len = sprintf(lbuf, "invalid");
1023 /* Fill the buffer with infos */
1024 len = snprintf(lbuf, 1024,
1025 "count:%d,PCI:%s,decodes=%s,owns=%s,locks=%s(%d:%d)\n",
1026 vga_decode_count, pci_name(pdev),
1027 vga_iostate_to_str(vgadev->decodes),
1028 vga_iostate_to_str(vgadev->owns),
1029 vga_iostate_to_str(vgadev->locks),
1030 vgadev->io_lock_cnt, vgadev->mem_lock_cnt);
1032 spin_unlock_irqrestore(&vga_lock, flags);
1035 /* Copy that to user */
1038 rc = copy_to_user(buf, lbuf, len);
1046 * TODO: To avoid parsing inside kernel and to improve the speed we may
1047 * consider use ioctl here
1049 static ssize_t vga_arb_write(struct file *file, const char __user *buf,
1050 size_t count, loff_t *ppos)
1052 struct vga_arb_private *priv = file->private_data;
1053 struct vga_arb_user_card *uc = NULL;
1054 struct pci_dev *pdev;
1056 unsigned int io_state;
1058 char kbuf[64], *curr_pos;
1059 size_t remaining = count;
1064 if (count >= sizeof(kbuf))
1066 if (copy_from_user(kbuf, buf, count))
1069 kbuf[count] = '\0'; /* Just to make sure... */
1071 if (strncmp(curr_pos, "lock ", 5) == 0) {
1075 pr_debug("client 0x%p called 'lock'\n", priv);
1077 if (!vga_str_to_iostate(curr_pos, remaining, &io_state)) {
1081 if (io_state == VGA_RSRC_NONE) {
1086 pdev = priv->target;
1087 if (priv->target == NULL) {
1092 vga_get_uninterruptible(pdev, io_state);
1094 /* Update the client's locks lists... */
1095 for (i = 0; i < MAX_USER_CARDS; i++) {
1096 if (priv->cards[i].pdev == pdev) {
1097 if (io_state & VGA_RSRC_LEGACY_IO)
1098 priv->cards[i].io_cnt++;
1099 if (io_state & VGA_RSRC_LEGACY_MEM)
1100 priv->cards[i].mem_cnt++;
1107 } else if (strncmp(curr_pos, "unlock ", 7) == 0) {
1111 pr_debug("client 0x%p called 'unlock'\n", priv);
1113 if (strncmp(curr_pos, "all", 3) == 0)
1114 io_state = VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM;
1116 if (!vga_str_to_iostate
1117 (curr_pos, remaining, &io_state)) {
1122 if (io_state == VGA_RSRC_NONE) {
1129 pdev = priv->target;
1130 if (priv->target == NULL) {
1134 for (i = 0; i < MAX_USER_CARDS; i++) {
1135 if (priv->cards[i].pdev == pdev)
1136 uc = &priv->cards[i];
1144 if (io_state & VGA_RSRC_LEGACY_IO && uc->io_cnt == 0) {
1149 if (io_state & VGA_RSRC_LEGACY_MEM && uc->mem_cnt == 0) {
1154 vga_put(pdev, io_state);
1156 if (io_state & VGA_RSRC_LEGACY_IO)
1158 if (io_state & VGA_RSRC_LEGACY_MEM)
1163 } else if (strncmp(curr_pos, "trylock ", 8) == 0) {
1167 pr_debug("client 0x%p called 'trylock'\n", priv);
1169 if (!vga_str_to_iostate(curr_pos, remaining, &io_state)) {
1174 if (io_state == VGA_RSRC_NONE) {
1180 pdev = priv->target;
1181 if (priv->target == NULL) {
1186 if (vga_tryget(pdev, io_state)) {
1187 /* Update the client's locks lists... */
1188 for (i = 0; i < MAX_USER_CARDS; i++) {
1189 if (priv->cards[i].pdev == pdev) {
1190 if (io_state & VGA_RSRC_LEGACY_IO)
1191 priv->cards[i].io_cnt++;
1192 if (io_state & VGA_RSRC_LEGACY_MEM)
1193 priv->cards[i].mem_cnt++;
1204 } else if (strncmp(curr_pos, "target ", 7) == 0) {
1205 unsigned int domain, bus, devfn;
1206 struct vga_device *vgadev;
1210 pr_debug("client 0x%p called 'target'\n", priv);
1211 /* if target is default */
1212 if (!strncmp(curr_pos, "default", 7))
1213 pdev = pci_dev_get(vga_default_device());
1215 if (!vga_pci_str_to_vars(curr_pos, remaining,
1216 &domain, &bus, &devfn)) {
1220 pdev = pci_get_domain_bus_and_slot(domain, bus, devfn);
1222 pr_debug("invalid PCI address %04x:%02x:%02x.%x\n",
1223 domain, bus, PCI_SLOT(devfn),
1229 pr_debug("%s ==> %04x:%02x:%02x.%x pdev %p\n", curr_pos,
1230 domain, bus, PCI_SLOT(devfn), PCI_FUNC(devfn),
1234 vgadev = vgadev_find(pdev);
1235 pr_debug("vgadev %p\n", vgadev);
1236 if (vgadev == NULL) {
1238 vgaarb_dbg(&pdev->dev, "not a VGA device\n");
1246 priv->target = pdev;
1247 for (i = 0; i < MAX_USER_CARDS; i++) {
1248 if (priv->cards[i].pdev == pdev)
1250 if (priv->cards[i].pdev == NULL) {
1251 priv->cards[i].pdev = pdev;
1252 priv->cards[i].io_cnt = 0;
1253 priv->cards[i].mem_cnt = 0;
1257 if (i == MAX_USER_CARDS) {
1258 vgaarb_dbg(&pdev->dev, "maximum user cards (%d) number reached, ignoring this one!\n",
1261 /* XXX: which value to return? */
1271 } else if (strncmp(curr_pos, "decodes ", 8) == 0) {
1274 pr_debug("client 0x%p called 'decodes'\n", priv);
1276 if (!vga_str_to_iostate(curr_pos, remaining, &io_state)) {
1280 pdev = priv->target;
1281 if (priv->target == NULL) {
1286 __vga_set_legacy_decoding(pdev, io_state, true);
1290 /* If we got here, the message written is not part of the protocol! */
1297 static __poll_t vga_arb_fpoll(struct file *file, poll_table *wait)
1299 pr_debug("%s\n", __func__);
1301 poll_wait(file, &vga_wait_queue, wait);
1305 static int vga_arb_open(struct inode *inode, struct file *file)
1307 struct vga_arb_private *priv;
1308 unsigned long flags;
1310 pr_debug("%s\n", __func__);
1312 priv = kzalloc(sizeof(*priv), GFP_KERNEL);
1315 spin_lock_init(&priv->lock);
1316 file->private_data = priv;
1318 spin_lock_irqsave(&vga_user_lock, flags);
1319 list_add(&priv->list, &vga_user_list);
1320 spin_unlock_irqrestore(&vga_user_lock, flags);
1322 /* Set the client' lists of locks */
1323 priv->target = vga_default_device(); /* Maybe this is still null! */
1324 priv->cards[0].pdev = priv->target;
1325 priv->cards[0].io_cnt = 0;
1326 priv->cards[0].mem_cnt = 0;
1332 static int vga_arb_release(struct inode *inode, struct file *file)
1334 struct vga_arb_private *priv = file->private_data;
1335 struct vga_arb_user_card *uc;
1336 unsigned long flags;
1339 pr_debug("%s\n", __func__);
1341 spin_lock_irqsave(&vga_user_lock, flags);
1342 list_del(&priv->list);
1343 for (i = 0; i < MAX_USER_CARDS; i++) {
1344 uc = &priv->cards[i];
1345 if (uc->pdev == NULL)
1347 vgaarb_dbg(&uc->pdev->dev, "uc->io_cnt == %d, uc->mem_cnt == %d\n",
1348 uc->io_cnt, uc->mem_cnt);
1349 while (uc->io_cnt--)
1350 vga_put(uc->pdev, VGA_RSRC_LEGACY_IO);
1351 while (uc->mem_cnt--)
1352 vga_put(uc->pdev, VGA_RSRC_LEGACY_MEM);
1354 spin_unlock_irqrestore(&vga_user_lock, flags);
1361 static void vga_arb_device_card_gone(struct pci_dev *pdev)
1366 * callback any registered clients to let them know we have a
1367 * change in VGA cards
1369 static void vga_arbiter_notify_clients(void)
1371 struct vga_device *vgadev;
1372 unsigned long flags;
1373 uint32_t new_decodes;
1376 if (!vga_arbiter_used)
1379 spin_lock_irqsave(&vga_lock, flags);
1380 list_for_each_entry(vgadev, &vga_list, list) {
1385 if (vgadev->set_decode) {
1386 new_decodes = vgadev->set_decode(vgadev->pdev,
1388 vga_update_device_decodes(vgadev, new_decodes);
1391 spin_unlock_irqrestore(&vga_lock, flags);
1394 static int pci_notify(struct notifier_block *nb, unsigned long action,
1397 struct device *dev = data;
1398 struct pci_dev *pdev = to_pci_dev(dev);
1399 bool notify = false;
1401 vgaarb_dbg(dev, "%s\n", __func__);
1403 /* For now we're only intereted in devices added and removed. I didn't
1404 * test this thing here, so someone needs to double check for the
1405 * cases of hotplugable vga cards. */
1406 if (action == BUS_NOTIFY_ADD_DEVICE)
1407 notify = vga_arbiter_add_pci_device(pdev);
1408 else if (action == BUS_NOTIFY_DEL_DEVICE)
1409 notify = vga_arbiter_del_pci_device(pdev);
1412 vga_arbiter_notify_clients();
1416 static struct notifier_block pci_notifier = {
1417 .notifier_call = pci_notify,
1420 static const struct file_operations vga_arb_device_fops = {
1421 .read = vga_arb_read,
1422 .write = vga_arb_write,
1423 .poll = vga_arb_fpoll,
1424 .open = vga_arb_open,
1425 .release = vga_arb_release,
1426 .llseek = noop_llseek,
1429 static struct miscdevice vga_arb_device = {
1430 MISC_DYNAMIC_MINOR, "vga_arbiter", &vga_arb_device_fops
1433 #if defined(CONFIG_ACPI)
1434 static bool vga_arb_integrated_gpu(struct device *dev)
1436 struct acpi_device *adev = ACPI_COMPANION(dev);
1438 return adev && !strcmp(acpi_device_hid(adev), ACPI_VIDEO_HID);
1441 static bool vga_arb_integrated_gpu(struct device *dev)
1447 static void __init vga_arb_select_default_device(void)
1449 struct pci_dev *pdev, *found = NULL;
1450 struct vga_device *vgadev;
1452 #if defined(CONFIG_X86) || defined(CONFIG_IA64)
1453 u64 base = screen_info.lfb_base;
1454 u64 size = screen_info.lfb_size;
1456 resource_size_t start, end;
1457 unsigned long flags;
1460 if (screen_info.capabilities & VIDEO_CAPABILITY_64BIT_BASE)
1461 base |= (u64)screen_info.ext_lfb_base << 32;
1463 limit = base + size;
1465 list_for_each_entry(vgadev, &vga_list, list) {
1466 struct device *dev = &vgadev->pdev->dev;
1468 * Override vga_arbiter_add_pci_device()'s I/O based detection
1469 * as it may take the wrong device (e.g. on Apple system under
1472 * Select the device owning the boot framebuffer if there is
1476 /* Does firmware framebuffer belong to us? */
1477 for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
1478 flags = pci_resource_flags(vgadev->pdev, i);
1480 if ((flags & IORESOURCE_MEM) == 0)
1483 start = pci_resource_start(vgadev->pdev, i);
1484 end = pci_resource_end(vgadev->pdev, i);
1489 if (base < start || limit >= end)
1492 if (!vga_default_device())
1493 vgaarb_info(dev, "setting as boot device\n");
1494 else if (vgadev->pdev != vga_default_device())
1495 vgaarb_info(dev, "overriding boot device\n");
1496 vga_set_default_device(vgadev->pdev);
1501 if (!vga_default_device()) {
1502 list_for_each_entry_reverse(vgadev, &vga_list, list) {
1503 struct device *dev = &vgadev->pdev->dev;
1506 pdev = vgadev->pdev;
1507 pci_read_config_word(pdev, PCI_COMMAND, &cmd);
1508 if (cmd & (PCI_COMMAND_IO | PCI_COMMAND_MEMORY)) {
1510 if (vga_arb_integrated_gpu(dev))
1517 vgaarb_info(&found->dev, "setting as boot device (VGA legacy resources not available)\n");
1518 vga_set_default_device(found);
1522 if (!vga_default_device()) {
1523 vgadev = list_first_entry_or_null(&vga_list,
1524 struct vga_device, list);
1526 struct device *dev = &vgadev->pdev->dev;
1527 vgaarb_info(dev, "setting as boot device (VGA legacy resources not available)\n");
1528 vga_set_default_device(vgadev->pdev);
1533 static int __init vga_arb_device_init(void)
1536 struct pci_dev *pdev;
1537 struct vga_device *vgadev;
1539 rc = misc_register(&vga_arb_device);
1541 pr_err("error %d registering device\n", rc);
1543 bus_register_notifier(&pci_bus_type, &pci_notifier);
1545 /* We add all PCI devices satisfying VGA class in the arbiter by
1549 pci_get_subsys(PCI_ANY_ID, PCI_ANY_ID, PCI_ANY_ID,
1550 PCI_ANY_ID, pdev)) != NULL)
1551 vga_arbiter_add_pci_device(pdev);
1553 list_for_each_entry(vgadev, &vga_list, list) {
1554 struct device *dev = &vgadev->pdev->dev;
1556 if (vgadev->bridge_has_one_vga)
1557 vgaarb_info(dev, "bridge control possible\n");
1559 vgaarb_info(dev, "no bridge control possible\n");
1562 vga_arb_select_default_device();
1564 pr_info("loaded\n");
1567 subsys_initcall(vga_arb_device_init);