xref: /openbmc/linux/drivers/gpu/vga/vga_switcheroo.c (revision 828ff2ad)
1 /*
2  * vga_switcheroo.c - Support for laptop with dual GPU using one set of outputs
3  *
4  * Copyright (c) 2010 Red Hat Inc.
5  * Author : Dave Airlie <airlied@redhat.com>
6  *
7  * Copyright (c) 2015 Lukas Wunner <lukas@wunner.de>
8  *
9  * Permission is hereby granted, free of charge, to any person obtaining a
10  * copy of this software and associated documentation files (the "Software"),
11  * to deal in the Software without restriction, including without limitation
12  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
13  * and/or sell copies of the Software, and to permit persons to whom the
14  * Software is furnished to do so, subject to the following conditions:
15  *
16  * The above copyright notice and this permission notice (including the next
17  * paragraph) shall be included in all copies or substantial portions of the
18  * Software.
19  *
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
23  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
25  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
26  * DEALINGS
27  * IN THE SOFTWARE.
28  *
29  */
30 
31 #define pr_fmt(fmt) "vga_switcheroo: " fmt
32 
33 #include <linux/apple-gmux.h>
34 #include <linux/console.h>
35 #include <linux/debugfs.h>
36 #include <linux/fb.h>
37 #include <linux/fs.h>
38 #include <linux/module.h>
39 #include <linux/pci.h>
40 #include <linux/pm_domain.h>
41 #include <linux/pm_runtime.h>
42 #include <linux/seq_file.h>
43 #include <linux/uaccess.h>
44 #include <linux/vgaarb.h>
45 #include <linux/vga_switcheroo.h>
46 
47 /**
48  * DOC: Overview
49  *
50  * vga_switcheroo is the Linux subsystem for laptop hybrid graphics.
51  * These come in two flavors:
52  *
53  * * muxed: Dual GPUs with a multiplexer chip to switch outputs between GPUs.
54  * * muxless: Dual GPUs but only one of them is connected to outputs.
55  *   The other one is merely used to offload rendering, its results
56  *   are copied over PCIe into the framebuffer. On Linux this is
57  *   supported with DRI PRIME.
58  *
59  * Hybrid graphics started to appear in the late Naughties and were initially
60  * all muxed. Newer laptops moved to a muxless architecture for cost reasons.
61  * A notable exception is the MacBook Pro which continues to use a mux.
62  * Muxes come with varying capabilities: Some switch only the panel, others
63  * can also switch external displays. Some switch all display pins at once
64  * while others can switch just the DDC lines. (To allow EDID probing
65  * for the inactive GPU.) Also, muxes are often used to cut power to the
66  * discrete GPU while it is not used.
67  *
68  * DRM drivers register GPUs with vga_switcheroo, these are henceforth called
69  * clients. The mux is called the handler. Muxless machines also register a
70  * handler to control the power state of the discrete GPU, its ->switchto
71  * callback is a no-op for obvious reasons. The discrete GPU is often equipped
72  * with an HDA controller for the HDMI/DP audio signal, this will also
73  * register as a client so that vga_switcheroo can take care of the correct
74  * suspend/resume order when changing the discrete GPU's power state. In total
75  * there can thus be up to three clients: Two vga clients (GPUs) and one audio
76  * client (on the discrete GPU). The code is mostly prepared to support
77  * machines with more than two GPUs should they become available.
78  *
79  * The GPU to which the outputs are currently switched is called the
80  * active client in vga_switcheroo parlance. The GPU not in use is the
81  * inactive client. When the inactive client's DRM driver is loaded,
82  * it will be unable to probe the panel's EDID and hence depends on
83  * VBIOS to provide its display modes. If the VBIOS modes are bogus or
84  * if there is no VBIOS at all (which is common on the MacBook Pro),
85  * a client may alternatively request that the DDC lines are temporarily
86  * switched to it, provided that the handler supports this. Switching
87  * only the DDC lines and not the entire output avoids unnecessary
88  * flickering.
89  */
90 
91 /**
92  * struct vga_switcheroo_client - registered client
93  * @pdev: client pci device
94  * @fb_info: framebuffer to which console is remapped on switching
95  * @pwr_state: current power state if manual power control is used.
96  *	For driver power control, call vga_switcheroo_pwr_state().
97  * @ops: client callbacks
98  * @id: client identifier. Determining the id requires the handler,
99  *	so gpus are initially assigned VGA_SWITCHEROO_UNKNOWN_ID
100  *	and later given their true id in vga_switcheroo_enable()
101  * @active: whether the outputs are currently switched to this client
102  * @driver_power_control: whether power state is controlled by the driver's
103  *	runtime pm. If true, writing ON and OFF to the vga_switcheroo debugfs
104  *	interface is a no-op so as not to interfere with runtime pm
105  * @list: client list
106  * @vga_dev: pci device, indicate which GPU is bound to current audio client
107  *
108  * Registered client. A client can be either a GPU or an audio device on a GPU.
109  * For audio clients, the @fb_info and @active members are bogus. For GPU
110  * clients, the @vga_dev is bogus.
111  */
112 struct vga_switcheroo_client {
113 	struct pci_dev *pdev;
114 	struct fb_info *fb_info;
115 	enum vga_switcheroo_state pwr_state;
116 	const struct vga_switcheroo_client_ops *ops;
117 	enum vga_switcheroo_client_id id;
118 	bool active;
119 	bool driver_power_control;
120 	struct list_head list;
121 	struct pci_dev *vga_dev;
122 };
123 
124 /*
125  * protects access to struct vgasr_priv
126  */
127 static DEFINE_MUTEX(vgasr_mutex);
128 
129 /**
130  * struct vgasr_priv - vga_switcheroo private data
131  * @active: whether vga_switcheroo is enabled.
132  *	Prerequisite is the registration of two GPUs and a handler
133  * @delayed_switch_active: whether a delayed switch is pending
134  * @delayed_client_id: client to which a delayed switch is pending
135  * @debugfs_root: directory for vga_switcheroo debugfs interface
136  * @switch_file: file for vga_switcheroo debugfs interface
137  * @registered_clients: number of registered GPUs
138  *	(counting only vga clients, not audio clients)
139  * @clients: list of registered clients
140  * @handler: registered handler
141  * @handler_flags: flags of registered handler
142  * @mux_hw_lock: protects mux state
143  *	(in particular while DDC lines are temporarily switched)
144  * @old_ddc_owner: client to which DDC lines will be switched back on unlock
145  *
146  * vga_switcheroo private data. Currently only one vga_switcheroo instance
147  * per system is supported.
148  */
149 struct vgasr_priv {
150 	bool active;
151 	bool delayed_switch_active;
152 	enum vga_switcheroo_client_id delayed_client_id;
153 
154 	struct dentry *debugfs_root;
155 	struct dentry *switch_file;
156 
157 	int registered_clients;
158 	struct list_head clients;
159 
160 	const struct vga_switcheroo_handler *handler;
161 	enum vga_switcheroo_handler_flags_t handler_flags;
162 	struct mutex mux_hw_lock;
163 	int old_ddc_owner;
164 };
165 
166 #define ID_BIT_AUDIO		0x100
167 #define client_is_audio(c)		((c)->id & ID_BIT_AUDIO)
168 #define client_is_vga(c)		(!client_is_audio(c))
169 #define client_id(c)		((c)->id & ~ID_BIT_AUDIO)
170 
171 static int vga_switcheroo_debugfs_init(struct vgasr_priv *priv);
172 static void vga_switcheroo_debugfs_fini(struct vgasr_priv *priv);
173 
174 /* only one switcheroo per system */
175 static struct vgasr_priv vgasr_priv = {
176 	.clients = LIST_HEAD_INIT(vgasr_priv.clients),
177 	.mux_hw_lock = __MUTEX_INITIALIZER(vgasr_priv.mux_hw_lock),
178 };
179 
180 static bool vga_switcheroo_ready(void)
181 {
182 	/* we're ready if we get two clients + handler */
183 	return !vgasr_priv.active &&
184 	       vgasr_priv.registered_clients == 2 && vgasr_priv.handler;
185 }
186 
187 static void vga_switcheroo_enable(void)
188 {
189 	int ret;
190 	struct vga_switcheroo_client *client;
191 
192 	/* call the handler to init */
193 	if (vgasr_priv.handler->init)
194 		vgasr_priv.handler->init();
195 
196 	list_for_each_entry(client, &vgasr_priv.clients, list) {
197 		if (!client_is_vga(client) ||
198 		     client_id(client) != VGA_SWITCHEROO_UNKNOWN_ID)
199 			continue;
200 
201 		ret = vgasr_priv.handler->get_client_id(client->pdev);
202 		if (ret < 0)
203 			return;
204 
205 		client->id = ret;
206 	}
207 
208 	list_for_each_entry(client, &vgasr_priv.clients, list) {
209 		if (!client_is_audio(client) ||
210 		     client_id(client) != VGA_SWITCHEROO_UNKNOWN_ID)
211 			continue;
212 
213 		ret = vgasr_priv.handler->get_client_id(client->vga_dev);
214 		if (ret < 0)
215 			return;
216 
217 		client->id = ret | ID_BIT_AUDIO;
218 		if (client->ops->gpu_bound)
219 			client->ops->gpu_bound(client->pdev, ret);
220 	}
221 
222 	vga_switcheroo_debugfs_init(&vgasr_priv);
223 	vgasr_priv.active = true;
224 }
225 
226 /**
227  * vga_switcheroo_register_handler() - register handler
228  * @handler: handler callbacks
229  * @handler_flags: handler flags
230  *
231  * Register handler. Enable vga_switcheroo if two vga clients have already
232  * registered.
233  *
234  * Return: 0 on success, -EINVAL if a handler was already registered.
235  */
236 int vga_switcheroo_register_handler(
237 			  const struct vga_switcheroo_handler *handler,
238 			  enum vga_switcheroo_handler_flags_t handler_flags)
239 {
240 	mutex_lock(&vgasr_mutex);
241 	if (vgasr_priv.handler) {
242 		mutex_unlock(&vgasr_mutex);
243 		return -EINVAL;
244 	}
245 
246 	vgasr_priv.handler = handler;
247 	vgasr_priv.handler_flags = handler_flags;
248 	if (vga_switcheroo_ready()) {
249 		pr_info("enabled\n");
250 		vga_switcheroo_enable();
251 	}
252 	mutex_unlock(&vgasr_mutex);
253 	return 0;
254 }
255 EXPORT_SYMBOL(vga_switcheroo_register_handler);
256 
257 /**
258  * vga_switcheroo_unregister_handler() - unregister handler
259  *
260  * Unregister handler. Disable vga_switcheroo.
261  */
262 void vga_switcheroo_unregister_handler(void)
263 {
264 	mutex_lock(&vgasr_mutex);
265 	mutex_lock(&vgasr_priv.mux_hw_lock);
266 	vgasr_priv.handler_flags = 0;
267 	vgasr_priv.handler = NULL;
268 	if (vgasr_priv.active) {
269 		pr_info("disabled\n");
270 		vga_switcheroo_debugfs_fini(&vgasr_priv);
271 		vgasr_priv.active = false;
272 	}
273 	mutex_unlock(&vgasr_priv.mux_hw_lock);
274 	mutex_unlock(&vgasr_mutex);
275 }
276 EXPORT_SYMBOL(vga_switcheroo_unregister_handler);
277 
278 /**
279  * vga_switcheroo_handler_flags() - obtain handler flags
280  *
281  * Helper for clients to obtain the handler flags bitmask.
282  *
283  * Return: Handler flags. A value of 0 means that no handler is registered
284  * or that the handler has no special capabilities.
285  */
286 enum vga_switcheroo_handler_flags_t vga_switcheroo_handler_flags(void)
287 {
288 	return vgasr_priv.handler_flags;
289 }
290 EXPORT_SYMBOL(vga_switcheroo_handler_flags);
291 
292 static int register_client(struct pci_dev *pdev,
293 			   const struct vga_switcheroo_client_ops *ops,
294 			   enum vga_switcheroo_client_id id,
295 			   struct pci_dev *vga_dev,
296 			   bool active,
297 			   bool driver_power_control)
298 {
299 	struct vga_switcheroo_client *client;
300 
301 	client = kzalloc(sizeof(*client), GFP_KERNEL);
302 	if (!client)
303 		return -ENOMEM;
304 
305 	client->pwr_state = VGA_SWITCHEROO_ON;
306 	client->pdev = pdev;
307 	client->ops = ops;
308 	client->id = id;
309 	client->active = active;
310 	client->driver_power_control = driver_power_control;
311 	client->vga_dev = vga_dev;
312 
313 	mutex_lock(&vgasr_mutex);
314 	list_add_tail(&client->list, &vgasr_priv.clients);
315 	if (client_is_vga(client))
316 		vgasr_priv.registered_clients++;
317 
318 	if (vga_switcheroo_ready()) {
319 		pr_info("enabled\n");
320 		vga_switcheroo_enable();
321 	}
322 	mutex_unlock(&vgasr_mutex);
323 	return 0;
324 }
325 
326 /**
327  * vga_switcheroo_register_client - register vga client
328  * @pdev: client pci device
329  * @ops: client callbacks
330  * @driver_power_control: whether power state is controlled by the driver's
331  *	runtime pm
332  *
333  * Register vga client (GPU). Enable vga_switcheroo if another GPU and a
334  * handler have already registered. The power state of the client is assumed
335  * to be ON. Beforehand, vga_switcheroo_client_probe_defer() shall be called
336  * to ensure that all prerequisites are met.
337  *
338  * Return: 0 on success, -ENOMEM on memory allocation error.
339  */
340 int vga_switcheroo_register_client(struct pci_dev *pdev,
341 				   const struct vga_switcheroo_client_ops *ops,
342 				   bool driver_power_control)
343 {
344 	return register_client(pdev, ops, VGA_SWITCHEROO_UNKNOWN_ID, NULL,
345 			       pdev == vga_default_device(),
346 			       driver_power_control);
347 }
348 EXPORT_SYMBOL(vga_switcheroo_register_client);
349 
350 /**
351  * vga_switcheroo_register_audio_client - register audio client
352  * @pdev: client pci device
353  * @ops: client callbacks
354  * @vga_dev:  pci device which is bound to current audio client
355  *
356  * Register audio client (audio device on a GPU). The client is assumed
357  * to use runtime PM. Beforehand, vga_switcheroo_client_probe_defer()
358  * shall be called to ensure that all prerequisites are met.
359  *
360  * Return: 0 on success, -ENOMEM on memory allocation error, -EINVAL on getting
361  * client id error.
362  */
363 int vga_switcheroo_register_audio_client(struct pci_dev *pdev,
364 			const struct vga_switcheroo_client_ops *ops,
365 			struct pci_dev *vga_dev)
366 {
367 	enum vga_switcheroo_client_id id = VGA_SWITCHEROO_UNKNOWN_ID;
368 
369 	/*
370 	 * if vga_switcheroo has enabled, that mean two GPU clients and also
371 	 * handler are registered. Get audio client id from bound GPU client
372 	 * id directly, otherwise, set it as VGA_SWITCHEROO_UNKNOWN_ID,
373 	 * it will set to correct id in later when vga_switcheroo_enable()
374 	 * is called.
375 	 */
376 	mutex_lock(&vgasr_mutex);
377 	if (vgasr_priv.active) {
378 		id = vgasr_priv.handler->get_client_id(vga_dev);
379 		if (id < 0) {
380 			mutex_unlock(&vgasr_mutex);
381 			return -EINVAL;
382 		}
383 		/* notify if GPU has been already bound */
384 		if (ops->gpu_bound)
385 			ops->gpu_bound(pdev, id);
386 	}
387 	mutex_unlock(&vgasr_mutex);
388 
389 	return register_client(pdev, ops, id | ID_BIT_AUDIO, vga_dev,
390 			       false, true);
391 }
392 EXPORT_SYMBOL(vga_switcheroo_register_audio_client);
393 
394 static struct vga_switcheroo_client *
395 find_client_from_pci(struct list_head *head, struct pci_dev *pdev)
396 {
397 	struct vga_switcheroo_client *client;
398 
399 	list_for_each_entry(client, head, list)
400 		if (client->pdev == pdev)
401 			return client;
402 	return NULL;
403 }
404 
405 static struct vga_switcheroo_client *
406 find_client_from_id(struct list_head *head,
407 		    enum vga_switcheroo_client_id client_id)
408 {
409 	struct vga_switcheroo_client *client;
410 
411 	list_for_each_entry(client, head, list)
412 		if (client->id == client_id)
413 			return client;
414 	return NULL;
415 }
416 
417 static struct vga_switcheroo_client *
418 find_active_client(struct list_head *head)
419 {
420 	struct vga_switcheroo_client *client;
421 
422 	list_for_each_entry(client, head, list)
423 		if (client->active)
424 			return client;
425 	return NULL;
426 }
427 
428 /**
429  * vga_switcheroo_client_probe_defer() - whether to defer probing a given client
430  * @pdev: client pci device
431  *
432  * Determine whether any prerequisites are not fulfilled to probe a given
433  * client. Drivers shall invoke this early on in their ->probe callback
434  * and return %-EPROBE_DEFER if it evaluates to %true. Thou shalt not
435  * register the client ere thou hast called this.
436  *
437  * Return: %true if probing should be deferred, otherwise %false.
438  */
439 bool vga_switcheroo_client_probe_defer(struct pci_dev *pdev)
440 {
441 	if ((pdev->class >> 16) == PCI_BASE_CLASS_DISPLAY) {
442 		/*
443 		 * apple-gmux is needed on pre-retina MacBook Pro
444 		 * to probe the panel if pdev is the inactive GPU.
445 		 */
446 		if (apple_gmux_present() && pdev != vga_default_device() &&
447 		    !vgasr_priv.handler_flags)
448 			return true;
449 	}
450 
451 	return false;
452 }
453 EXPORT_SYMBOL(vga_switcheroo_client_probe_defer);
454 
455 static enum vga_switcheroo_state
456 vga_switcheroo_pwr_state(struct vga_switcheroo_client *client)
457 {
458 	if (client->driver_power_control)
459 		if (pm_runtime_enabled(&client->pdev->dev) &&
460 		    pm_runtime_active(&client->pdev->dev))
461 			return VGA_SWITCHEROO_ON;
462 		else
463 			return VGA_SWITCHEROO_OFF;
464 	else
465 		return client->pwr_state;
466 }
467 
468 /**
469  * vga_switcheroo_get_client_state() - obtain power state of a given client
470  * @pdev: client pci device
471  *
472  * Obtain power state of a given client as seen from vga_switcheroo.
473  * The function is only called from hda_intel.c.
474  *
475  * Return: Power state.
476  */
477 enum vga_switcheroo_state vga_switcheroo_get_client_state(struct pci_dev *pdev)
478 {
479 	struct vga_switcheroo_client *client;
480 	enum vga_switcheroo_state ret;
481 
482 	mutex_lock(&vgasr_mutex);
483 	client = find_client_from_pci(&vgasr_priv.clients, pdev);
484 	if (!client)
485 		ret = VGA_SWITCHEROO_NOT_FOUND;
486 	else
487 		ret = vga_switcheroo_pwr_state(client);
488 	mutex_unlock(&vgasr_mutex);
489 	return ret;
490 }
491 EXPORT_SYMBOL(vga_switcheroo_get_client_state);
492 
493 /**
494  * vga_switcheroo_unregister_client() - unregister client
495  * @pdev: client pci device
496  *
497  * Unregister client. Disable vga_switcheroo if this is a vga client (GPU).
498  */
499 void vga_switcheroo_unregister_client(struct pci_dev *pdev)
500 {
501 	struct vga_switcheroo_client *client;
502 
503 	mutex_lock(&vgasr_mutex);
504 	client = find_client_from_pci(&vgasr_priv.clients, pdev);
505 	if (client) {
506 		if (client_is_vga(client))
507 			vgasr_priv.registered_clients--;
508 		list_del(&client->list);
509 		kfree(client);
510 	}
511 	if (vgasr_priv.active && vgasr_priv.registered_clients < 2) {
512 		pr_info("disabled\n");
513 		vga_switcheroo_debugfs_fini(&vgasr_priv);
514 		vgasr_priv.active = false;
515 	}
516 	mutex_unlock(&vgasr_mutex);
517 }
518 EXPORT_SYMBOL(vga_switcheroo_unregister_client);
519 
520 /**
521  * vga_switcheroo_client_fb_set() - set framebuffer of a given client
522  * @pdev: client pci device
523  * @info: framebuffer
524  *
525  * Set framebuffer of a given client. The console will be remapped to this
526  * on switching.
527  */
528 void vga_switcheroo_client_fb_set(struct pci_dev *pdev,
529 				 struct fb_info *info)
530 {
531 	struct vga_switcheroo_client *client;
532 
533 	mutex_lock(&vgasr_mutex);
534 	client = find_client_from_pci(&vgasr_priv.clients, pdev);
535 	if (client)
536 		client->fb_info = info;
537 	mutex_unlock(&vgasr_mutex);
538 }
539 EXPORT_SYMBOL(vga_switcheroo_client_fb_set);
540 
541 /**
542  * vga_switcheroo_lock_ddc() - temporarily switch DDC lines to a given client
543  * @pdev: client pci device
544  *
545  * Temporarily switch DDC lines to the client identified by @pdev
546  * (but leave the outputs otherwise switched to where they are).
547  * This allows the inactive client to probe EDID. The DDC lines must
548  * afterwards be switched back by calling vga_switcheroo_unlock_ddc(),
549  * even if this function returns an error.
550  *
551  * Return: Previous DDC owner on success or a negative int on error.
552  * Specifically, %-ENODEV if no handler has registered or if the handler
553  * does not support switching the DDC lines. Also, a negative value
554  * returned by the handler is propagated back to the caller.
555  * The return value has merely an informational purpose for any caller
556  * which might be interested in it. It is acceptable to ignore the return
557  * value and simply rely on the result of the subsequent EDID probe,
558  * which will be %NULL if DDC switching failed.
559  */
560 int vga_switcheroo_lock_ddc(struct pci_dev *pdev)
561 {
562 	enum vga_switcheroo_client_id id;
563 
564 	mutex_lock(&vgasr_priv.mux_hw_lock);
565 	if (!vgasr_priv.handler || !vgasr_priv.handler->switch_ddc) {
566 		vgasr_priv.old_ddc_owner = -ENODEV;
567 		return -ENODEV;
568 	}
569 
570 	id = vgasr_priv.handler->get_client_id(pdev);
571 	vgasr_priv.old_ddc_owner = vgasr_priv.handler->switch_ddc(id);
572 	return vgasr_priv.old_ddc_owner;
573 }
574 EXPORT_SYMBOL(vga_switcheroo_lock_ddc);
575 
576 /**
577  * vga_switcheroo_unlock_ddc() - switch DDC lines back to previous owner
578  * @pdev: client pci device
579  *
580  * Switch DDC lines back to the previous owner after calling
581  * vga_switcheroo_lock_ddc(). This must be called even if
582  * vga_switcheroo_lock_ddc() returned an error.
583  *
584  * Return: Previous DDC owner on success (i.e. the client identifier of @pdev)
585  * or a negative int on error.
586  * Specifically, %-ENODEV if no handler has registered or if the handler
587  * does not support switching the DDC lines. Also, a negative value
588  * returned by the handler is propagated back to the caller.
589  * Finally, invoking this function without calling vga_switcheroo_lock_ddc()
590  * first is not allowed and will result in %-EINVAL.
591  */
592 int vga_switcheroo_unlock_ddc(struct pci_dev *pdev)
593 {
594 	enum vga_switcheroo_client_id id;
595 	int ret = vgasr_priv.old_ddc_owner;
596 
597 	if (WARN_ON_ONCE(!mutex_is_locked(&vgasr_priv.mux_hw_lock)))
598 		return -EINVAL;
599 
600 	if (vgasr_priv.old_ddc_owner >= 0) {
601 		id = vgasr_priv.handler->get_client_id(pdev);
602 		if (vgasr_priv.old_ddc_owner != id)
603 			ret = vgasr_priv.handler->switch_ddc(
604 						     vgasr_priv.old_ddc_owner);
605 	}
606 	mutex_unlock(&vgasr_priv.mux_hw_lock);
607 	return ret;
608 }
609 EXPORT_SYMBOL(vga_switcheroo_unlock_ddc);
610 
611 /**
612  * DOC: Manual switching and manual power control
613  *
614  * In this mode of use, the file /sys/kernel/debug/vgaswitcheroo/switch
615  * can be read to retrieve the current vga_switcheroo state and commands
616  * can be written to it to change the state. The file appears as soon as
617  * two GPU drivers and one handler have registered with vga_switcheroo.
618  * The following commands are understood:
619  *
620  * * OFF: Power off the device not in use.
621  * * ON: Power on the device not in use.
622  * * IGD: Switch to the integrated graphics device.
623  *   Power on the integrated GPU if necessary, power off the discrete GPU.
624  *   Prerequisite is that no user space processes (e.g. Xorg, alsactl)
625  *   have opened device files of the GPUs or the audio client. If the
626  *   switch fails, the user may invoke lsof(8) or fuser(1) on /dev/dri/
627  *   and /dev/snd/controlC1 to identify processes blocking the switch.
628  * * DIS: Switch to the discrete graphics device.
629  * * DIGD: Delayed switch to the integrated graphics device.
630  *   This will perform the switch once the last user space process has
631  *   closed the device files of the GPUs and the audio client.
632  * * DDIS: Delayed switch to the discrete graphics device.
633  * * MIGD: Mux-only switch to the integrated graphics device.
634  *   Does not remap console or change the power state of either gpu.
635  *   If the integrated GPU is currently off, the screen will turn black.
636  *   If it is on, the screen will show whatever happens to be in VRAM.
637  *   Either way, the user has to blindly enter the command to switch back.
638  * * MDIS: Mux-only switch to the discrete graphics device.
639  *
640  * For GPUs whose power state is controlled by the driver's runtime pm,
641  * the ON and OFF commands are a no-op (see next section).
642  *
643  * For muxless machines, the IGD/DIS, DIGD/DDIS and MIGD/MDIS commands
644  * should not be used.
645  */
646 
647 static int vga_switcheroo_show(struct seq_file *m, void *v)
648 {
649 	struct vga_switcheroo_client *client;
650 	int i = 0;
651 
652 	mutex_lock(&vgasr_mutex);
653 	list_for_each_entry(client, &vgasr_priv.clients, list) {
654 		seq_printf(m, "%d:%s%s:%c:%s%s:%s\n", i,
655 			   client_id(client) == VGA_SWITCHEROO_DIS ? "DIS" :
656 								     "IGD",
657 			   client_is_vga(client) ? "" : "-Audio",
658 			   client->active ? '+' : ' ',
659 			   client->driver_power_control ? "Dyn" : "",
660 			   vga_switcheroo_pwr_state(client) ? "Pwr" : "Off",
661 			   pci_name(client->pdev));
662 		i++;
663 	}
664 	mutex_unlock(&vgasr_mutex);
665 	return 0;
666 }
667 
668 static int vga_switcheroo_debugfs_open(struct inode *inode, struct file *file)
669 {
670 	return single_open(file, vga_switcheroo_show, NULL);
671 }
672 
673 static int vga_switchon(struct vga_switcheroo_client *client)
674 {
675 	if (client->driver_power_control)
676 		return 0;
677 	if (vgasr_priv.handler->power_state)
678 		vgasr_priv.handler->power_state(client->id, VGA_SWITCHEROO_ON);
679 	/* call the driver callback to turn on device */
680 	client->ops->set_gpu_state(client->pdev, VGA_SWITCHEROO_ON);
681 	client->pwr_state = VGA_SWITCHEROO_ON;
682 	return 0;
683 }
684 
685 static int vga_switchoff(struct vga_switcheroo_client *client)
686 {
687 	if (client->driver_power_control)
688 		return 0;
689 	/* call the driver callback to turn off device */
690 	client->ops->set_gpu_state(client->pdev, VGA_SWITCHEROO_OFF);
691 	if (vgasr_priv.handler->power_state)
692 		vgasr_priv.handler->power_state(client->id, VGA_SWITCHEROO_OFF);
693 	client->pwr_state = VGA_SWITCHEROO_OFF;
694 	return 0;
695 }
696 
697 static void set_audio_state(enum vga_switcheroo_client_id id,
698 			    enum vga_switcheroo_state state)
699 {
700 	struct vga_switcheroo_client *client;
701 
702 	client = find_client_from_id(&vgasr_priv.clients, id | ID_BIT_AUDIO);
703 	if (client)
704 		client->ops->set_gpu_state(client->pdev, state);
705 }
706 
707 /* stage one happens before delay */
708 static int vga_switchto_stage1(struct vga_switcheroo_client *new_client)
709 {
710 	struct vga_switcheroo_client *active;
711 
712 	active = find_active_client(&vgasr_priv.clients);
713 	if (!active)
714 		return 0;
715 
716 	if (vga_switcheroo_pwr_state(new_client) == VGA_SWITCHEROO_OFF)
717 		vga_switchon(new_client);
718 
719 	vga_set_default_device(new_client->pdev);
720 	return 0;
721 }
722 
723 /* post delay */
724 static int vga_switchto_stage2(struct vga_switcheroo_client *new_client)
725 {
726 	int ret;
727 	struct vga_switcheroo_client *active;
728 
729 	active = find_active_client(&vgasr_priv.clients);
730 	if (!active)
731 		return 0;
732 
733 	active->active = false;
734 
735 	/* let HDA controller autosuspend if GPU uses driver power control */
736 	if (!active->driver_power_control)
737 		set_audio_state(active->id, VGA_SWITCHEROO_OFF);
738 
739 	if (new_client->fb_info) {
740 		struct fb_event event;
741 
742 		console_lock();
743 		event.info = new_client->fb_info;
744 		fb_notifier_call_chain(FB_EVENT_REMAP_ALL_CONSOLE, &event);
745 		console_unlock();
746 	}
747 
748 	mutex_lock(&vgasr_priv.mux_hw_lock);
749 	ret = vgasr_priv.handler->switchto(new_client->id);
750 	mutex_unlock(&vgasr_priv.mux_hw_lock);
751 	if (ret)
752 		return ret;
753 
754 	if (new_client->ops->reprobe)
755 		new_client->ops->reprobe(new_client->pdev);
756 
757 	if (vga_switcheroo_pwr_state(active) == VGA_SWITCHEROO_ON)
758 		vga_switchoff(active);
759 
760 	/* let HDA controller autoresume if GPU uses driver power control */
761 	if (!new_client->driver_power_control)
762 		set_audio_state(new_client->id, VGA_SWITCHEROO_ON);
763 
764 	new_client->active = true;
765 	return 0;
766 }
767 
768 static bool check_can_switch(void)
769 {
770 	struct vga_switcheroo_client *client;
771 
772 	list_for_each_entry(client, &vgasr_priv.clients, list) {
773 		if (!client->ops->can_switch(client->pdev)) {
774 			pr_err("client %x refused switch\n", client->id);
775 			return false;
776 		}
777 	}
778 	return true;
779 }
780 
781 static ssize_t
782 vga_switcheroo_debugfs_write(struct file *filp, const char __user *ubuf,
783 			     size_t cnt, loff_t *ppos)
784 {
785 	char usercmd[64];
786 	int ret;
787 	bool delay = false, can_switch;
788 	bool just_mux = false;
789 	enum vga_switcheroo_client_id client_id = VGA_SWITCHEROO_UNKNOWN_ID;
790 	struct vga_switcheroo_client *client = NULL;
791 
792 	if (cnt > 63)
793 		cnt = 63;
794 
795 	if (copy_from_user(usercmd, ubuf, cnt))
796 		return -EFAULT;
797 
798 	mutex_lock(&vgasr_mutex);
799 
800 	if (!vgasr_priv.active) {
801 		cnt = -EINVAL;
802 		goto out;
803 	}
804 
805 	/* pwr off the device not in use */
806 	if (strncmp(usercmd, "OFF", 3) == 0) {
807 		list_for_each_entry(client, &vgasr_priv.clients, list) {
808 			if (client->active || client_is_audio(client))
809 				continue;
810 			if (client->driver_power_control)
811 				continue;
812 			set_audio_state(client->id, VGA_SWITCHEROO_OFF);
813 			if (client->pwr_state == VGA_SWITCHEROO_ON)
814 				vga_switchoff(client);
815 		}
816 		goto out;
817 	}
818 	/* pwr on the device not in use */
819 	if (strncmp(usercmd, "ON", 2) == 0) {
820 		list_for_each_entry(client, &vgasr_priv.clients, list) {
821 			if (client->active || client_is_audio(client))
822 				continue;
823 			if (client->driver_power_control)
824 				continue;
825 			if (client->pwr_state == VGA_SWITCHEROO_OFF)
826 				vga_switchon(client);
827 			set_audio_state(client->id, VGA_SWITCHEROO_ON);
828 		}
829 		goto out;
830 	}
831 
832 	/* request a delayed switch - test can we switch now */
833 	if (strncmp(usercmd, "DIGD", 4) == 0) {
834 		client_id = VGA_SWITCHEROO_IGD;
835 		delay = true;
836 	}
837 
838 	if (strncmp(usercmd, "DDIS", 4) == 0) {
839 		client_id = VGA_SWITCHEROO_DIS;
840 		delay = true;
841 	}
842 
843 	if (strncmp(usercmd, "IGD", 3) == 0)
844 		client_id = VGA_SWITCHEROO_IGD;
845 
846 	if (strncmp(usercmd, "DIS", 3) == 0)
847 		client_id = VGA_SWITCHEROO_DIS;
848 
849 	if (strncmp(usercmd, "MIGD", 4) == 0) {
850 		just_mux = true;
851 		client_id = VGA_SWITCHEROO_IGD;
852 	}
853 	if (strncmp(usercmd, "MDIS", 4) == 0) {
854 		just_mux = true;
855 		client_id = VGA_SWITCHEROO_DIS;
856 	}
857 
858 	if (client_id == VGA_SWITCHEROO_UNKNOWN_ID)
859 		goto out;
860 	client = find_client_from_id(&vgasr_priv.clients, client_id);
861 	if (!client)
862 		goto out;
863 
864 	vgasr_priv.delayed_switch_active = false;
865 
866 	if (just_mux) {
867 		mutex_lock(&vgasr_priv.mux_hw_lock);
868 		ret = vgasr_priv.handler->switchto(client_id);
869 		mutex_unlock(&vgasr_priv.mux_hw_lock);
870 		goto out;
871 	}
872 
873 	if (client->active)
874 		goto out;
875 
876 	/* okay we want a switch - test if devices are willing to switch */
877 	can_switch = check_can_switch();
878 
879 	if (can_switch == false && delay == false)
880 		goto out;
881 
882 	if (can_switch) {
883 		ret = vga_switchto_stage1(client);
884 		if (ret)
885 			pr_err("switching failed stage 1 %d\n", ret);
886 
887 		ret = vga_switchto_stage2(client);
888 		if (ret)
889 			pr_err("switching failed stage 2 %d\n", ret);
890 
891 	} else {
892 		pr_info("setting delayed switch to client %d\n", client->id);
893 		vgasr_priv.delayed_switch_active = true;
894 		vgasr_priv.delayed_client_id = client_id;
895 
896 		ret = vga_switchto_stage1(client);
897 		if (ret)
898 			pr_err("delayed switching stage 1 failed %d\n", ret);
899 	}
900 
901 out:
902 	mutex_unlock(&vgasr_mutex);
903 	return cnt;
904 }
905 
906 static const struct file_operations vga_switcheroo_debugfs_fops = {
907 	.owner = THIS_MODULE,
908 	.open = vga_switcheroo_debugfs_open,
909 	.write = vga_switcheroo_debugfs_write,
910 	.read = seq_read,
911 	.llseek = seq_lseek,
912 	.release = single_release,
913 };
914 
915 static void vga_switcheroo_debugfs_fini(struct vgasr_priv *priv)
916 {
917 	debugfs_remove(priv->switch_file);
918 	priv->switch_file = NULL;
919 
920 	debugfs_remove(priv->debugfs_root);
921 	priv->debugfs_root = NULL;
922 }
923 
924 static int vga_switcheroo_debugfs_init(struct vgasr_priv *priv)
925 {
926 	static const char mp[] = "/sys/kernel/debug";
927 
928 	/* already initialised */
929 	if (priv->debugfs_root)
930 		return 0;
931 	priv->debugfs_root = debugfs_create_dir("vgaswitcheroo", NULL);
932 
933 	if (!priv->debugfs_root) {
934 		pr_err("Cannot create %s/vgaswitcheroo\n", mp);
935 		goto fail;
936 	}
937 
938 	priv->switch_file = debugfs_create_file("switch", 0644,
939 						priv->debugfs_root, NULL,
940 						&vga_switcheroo_debugfs_fops);
941 	if (!priv->switch_file) {
942 		pr_err("cannot create %s/vgaswitcheroo/switch\n", mp);
943 		goto fail;
944 	}
945 	return 0;
946 fail:
947 	vga_switcheroo_debugfs_fini(priv);
948 	return -1;
949 }
950 
951 /**
952  * vga_switcheroo_process_delayed_switch() - helper for delayed switching
953  *
954  * Process a delayed switch if one is pending. DRM drivers should call this
955  * from their ->lastclose callback.
956  *
957  * Return: 0 on success. -EINVAL if no delayed switch is pending, if the client
958  * has unregistered in the meantime or if there are other clients blocking the
959  * switch. If the actual switch fails, an error is reported and 0 is returned.
960  */
961 int vga_switcheroo_process_delayed_switch(void)
962 {
963 	struct vga_switcheroo_client *client;
964 	int ret;
965 	int err = -EINVAL;
966 
967 	mutex_lock(&vgasr_mutex);
968 	if (!vgasr_priv.delayed_switch_active)
969 		goto err;
970 
971 	pr_info("processing delayed switch to %d\n",
972 		vgasr_priv.delayed_client_id);
973 
974 	client = find_client_from_id(&vgasr_priv.clients,
975 				     vgasr_priv.delayed_client_id);
976 	if (!client || !check_can_switch())
977 		goto err;
978 
979 	ret = vga_switchto_stage2(client);
980 	if (ret)
981 		pr_err("delayed switching failed stage 2 %d\n", ret);
982 
983 	vgasr_priv.delayed_switch_active = false;
984 	err = 0;
985 err:
986 	mutex_unlock(&vgasr_mutex);
987 	return err;
988 }
989 EXPORT_SYMBOL(vga_switcheroo_process_delayed_switch);
990 
991 /**
992  * DOC: Driver power control
993  *
994  * In this mode of use, the discrete GPU automatically powers up and down at
995  * the discretion of the driver's runtime pm. On muxed machines, the user may
996  * still influence the muxer state by way of the debugfs interface, however
997  * the ON and OFF commands become a no-op for the discrete GPU.
998  *
999  * This mode is the default on Nvidia HybridPower/Optimus and ATI PowerXpress.
1000  * Specifying nouveau.runpm=0, radeon.runpm=0 or amdgpu.runpm=0 on the kernel
1001  * command line disables it.
1002  *
1003  * After the GPU has been suspended, the handler needs to be called to cut
1004  * power to the GPU. Likewise it needs to reinstate power before the GPU
1005  * can resume. This is achieved by vga_switcheroo_init_domain_pm_ops(),
1006  * which augments the GPU's suspend/resume functions by the requisite
1007  * calls to the handler.
1008  *
1009  * When the audio device resumes, the GPU needs to be woken. This is achieved
1010  * by a PCI quirk which calls device_link_add() to declare a dependency on the
1011  * GPU. That way, the GPU is kept awake whenever and as long as the audio
1012  * device is in use.
1013  *
1014  * On muxed machines, if the mux is initially switched to the discrete GPU,
1015  * the user ends up with a black screen when the GPU powers down after boot.
1016  * As a workaround, the mux is forced to the integrated GPU on runtime suspend,
1017  * cf. https://bugs.freedesktop.org/show_bug.cgi?id=75917
1018  */
1019 
1020 static void vga_switcheroo_power_switch(struct pci_dev *pdev,
1021 					enum vga_switcheroo_state state)
1022 {
1023 	struct vga_switcheroo_client *client;
1024 
1025 	if (!vgasr_priv.handler->power_state)
1026 		return;
1027 
1028 	client = find_client_from_pci(&vgasr_priv.clients, pdev);
1029 	if (!client)
1030 		return;
1031 
1032 	if (!client->driver_power_control)
1033 		return;
1034 
1035 	vgasr_priv.handler->power_state(client->id, state);
1036 }
1037 
1038 /* switcheroo power domain */
1039 static int vga_switcheroo_runtime_suspend(struct device *dev)
1040 {
1041 	struct pci_dev *pdev = to_pci_dev(dev);
1042 	int ret;
1043 
1044 	ret = dev->bus->pm->runtime_suspend(dev);
1045 	if (ret)
1046 		return ret;
1047 	mutex_lock(&vgasr_mutex);
1048 	if (vgasr_priv.handler->switchto) {
1049 		mutex_lock(&vgasr_priv.mux_hw_lock);
1050 		vgasr_priv.handler->switchto(VGA_SWITCHEROO_IGD);
1051 		mutex_unlock(&vgasr_priv.mux_hw_lock);
1052 	}
1053 	pci_bus_set_current_state(pdev->bus, PCI_D3cold);
1054 	vga_switcheroo_power_switch(pdev, VGA_SWITCHEROO_OFF);
1055 	mutex_unlock(&vgasr_mutex);
1056 	return 0;
1057 }
1058 
1059 static int vga_switcheroo_runtime_resume(struct device *dev)
1060 {
1061 	struct pci_dev *pdev = to_pci_dev(dev);
1062 	int ret;
1063 
1064 	mutex_lock(&vgasr_mutex);
1065 	vga_switcheroo_power_switch(pdev, VGA_SWITCHEROO_ON);
1066 	mutex_unlock(&vgasr_mutex);
1067 	pci_wakeup_bus(pdev->bus);
1068 	ret = dev->bus->pm->runtime_resume(dev);
1069 	if (ret)
1070 		return ret;
1071 
1072 	return 0;
1073 }
1074 
1075 /**
1076  * vga_switcheroo_init_domain_pm_ops() - helper for driver power control
1077  * @dev: vga client device
1078  * @domain: power domain
1079  *
1080  * Helper for GPUs whose power state is controlled by the driver's runtime pm.
1081  * After the GPU has been suspended, the handler needs to be called to cut
1082  * power to the GPU. Likewise it needs to reinstate power before the GPU
1083  * can resume. To this end, this helper augments the suspend/resume functions
1084  * by the requisite calls to the handler. It needs only be called on platforms
1085  * where the power switch is separate to the device being powered down.
1086  */
1087 int vga_switcheroo_init_domain_pm_ops(struct device *dev,
1088 				      struct dev_pm_domain *domain)
1089 {
1090 	/* copy over all the bus versions */
1091 	if (dev->bus && dev->bus->pm) {
1092 		domain->ops = *dev->bus->pm;
1093 		domain->ops.runtime_suspend = vga_switcheroo_runtime_suspend;
1094 		domain->ops.runtime_resume = vga_switcheroo_runtime_resume;
1095 
1096 		dev_pm_domain_set(dev, domain);
1097 		return 0;
1098 	}
1099 	dev_pm_domain_set(dev, NULL);
1100 	return -EINVAL;
1101 }
1102 EXPORT_SYMBOL(vga_switcheroo_init_domain_pm_ops);
1103 
1104 void vga_switcheroo_fini_domain_pm_ops(struct device *dev)
1105 {
1106 	dev_pm_domain_set(dev, NULL);
1107 }
1108 EXPORT_SYMBOL(vga_switcheroo_fini_domain_pm_ops);
1109