1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright © 2019 Intel Corporation
4  */
5 
6 #include <linux/vga_switcheroo.h>
7 
8 #include "i915_drv.h"
9 #include "i915_switcheroo.h"
10 
11 static void i915_switcheroo_set_state(struct pci_dev *pdev,
12 				      enum vga_switcheroo_state state)
13 {
14 	struct drm_i915_private *i915 = pdev_to_i915(pdev);
15 	pm_message_t pmm = { .event = PM_EVENT_SUSPEND };
16 
17 	if (!i915) {
18 		dev_err(&pdev->dev, "DRM not initialized, aborting switch.\n");
19 		return;
20 	}
21 
22 	if (state == VGA_SWITCHEROO_ON) {
23 		drm_info(&i915->drm, "switched on\n");
24 		i915->drm.switch_power_state = DRM_SWITCH_POWER_CHANGING;
25 		/* i915 resume handler doesn't set to D0 */
26 		pci_set_power_state(pdev, PCI_D0);
27 		i915_resume_switcheroo(i915);
28 		i915->drm.switch_power_state = DRM_SWITCH_POWER_ON;
29 	} else {
30 		drm_info(&i915->drm, "switched off\n");
31 		i915->drm.switch_power_state = DRM_SWITCH_POWER_CHANGING;
32 		i915_suspend_switcheroo(i915, pmm);
33 		i915->drm.switch_power_state = DRM_SWITCH_POWER_OFF;
34 	}
35 }
36 
37 static bool i915_switcheroo_can_switch(struct pci_dev *pdev)
38 {
39 	struct drm_i915_private *i915 = pdev_to_i915(pdev);
40 
41 	/*
42 	 * FIXME: open_count is protected by drm_global_mutex but that would lead to
43 	 * locking inversion with the driver load path. And the access here is
44 	 * completely racy anyway. So don't bother with locking for now.
45 	 */
46 	return i915 && atomic_read(&i915->drm.open_count) == 0;
47 }
48 
49 static const struct vga_switcheroo_client_ops i915_switcheroo_ops = {
50 	.set_gpu_state = i915_switcheroo_set_state,
51 	.reprobe = NULL,
52 	.can_switch = i915_switcheroo_can_switch,
53 };
54 
55 int i915_switcheroo_register(struct drm_i915_private *i915)
56 {
57 	struct pci_dev *pdev = i915->drm.pdev;
58 
59 	return vga_switcheroo_register_client(pdev, &i915_switcheroo_ops, false);
60 }
61 
62 void i915_switcheroo_unregister(struct drm_i915_private *i915)
63 {
64 	struct pci_dev *pdev = i915->drm.pdev;
65 
66 	vga_switcheroo_unregister_client(pdev);
67 }
68