xref: /openbmc/linux/drivers/gpu/vga/vga_switcheroo.c (revision a06c488d)
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/console.h>
34 #include <linux/debugfs.h>
35 #include <linux/fb.h>
36 #include <linux/fs.h>
37 #include <linux/module.h>
38 #include <linux/pci.h>
39 #include <linux/pm_domain.h>
40 #include <linux/pm_runtime.h>
41 #include <linux/seq_file.h>
42 #include <linux/uaccess.h>
43 #include <linux/vgaarb.h>
44 #include <linux/vga_switcheroo.h>
45 
46 /**
47  * DOC: Overview
48  *
49  * vga_switcheroo is the Linux subsystem for laptop hybrid graphics.
50  * These come in two flavors:
51  *
52  * * muxed: Dual GPUs with a multiplexer chip to switch outputs between GPUs.
53  * * muxless: Dual GPUs but only one of them is connected to outputs.
54  * 	The other one is merely used to offload rendering, its results
55  * 	are copied over PCIe into the framebuffer. On Linux this is
56  * 	supported with DRI PRIME.
57  *
58  * Hybrid graphics started to appear in the late Naughties and were initially
59  * all muxed. Newer laptops moved to a muxless architecture for cost reasons.
60  * A notable exception is the MacBook Pro which continues to use a mux.
61  * Muxes come with varying capabilities: Some switch only the panel, others
62  * can also switch external displays. Some switch all display pins at once
63  * while others can switch just the DDC lines. (To allow EDID probing
64  * for the inactive GPU.) Also, muxes are often used to cut power to the
65  * discrete GPU while it is not used.
66  *
67  * DRM drivers register GPUs with vga_switcheroo, these are henceforth called
68  * clients. The mux is called the handler. Muxless machines also register a
69  * handler to control the power state of the discrete GPU, its ->switchto
70  * callback is a no-op for obvious reasons. The discrete GPU is often equipped
71  * with an HDA controller for the HDMI/DP audio signal, this will also
72  * register as a client so that vga_switcheroo can take care of the correct
73  * suspend/resume order when changing the discrete GPU's power state. In total
74  * there can thus be up to three clients: Two vga clients (GPUs) and one audio
75  * client (on the discrete GPU). The code is mostly prepared to support
76  * machines with more than two GPUs should they become available.
77  * The GPU to which the outputs are currently switched is called the
78  * active client in vga_switcheroo parlance. The GPU not in use is the
79  * inactive client.
80  */
81 
82 /**
83  * struct vga_switcheroo_client - registered client
84  * @pdev: client pci device
85  * @fb_info: framebuffer to which console is remapped on switching
86  * @pwr_state: current power state
87  * @ops: client callbacks
88  * @id: client identifier. Determining the id requires the handler,
89  * 	so gpus are initially assigned VGA_SWITCHEROO_UNKNOWN_ID
90  * 	and later given their true id in vga_switcheroo_enable()
91  * @active: whether the outputs are currently switched to this client
92  * @driver_power_control: whether power state is controlled by the driver's
93  * 	runtime pm. If true, writing ON and OFF to the vga_switcheroo debugfs
94  * 	interface is a no-op so as not to interfere with runtime pm
95  * @list: client list
96  *
97  * Registered client. A client can be either a GPU or an audio device on a GPU.
98  * For audio clients, the @fb_info, @active and @driver_power_control members
99  * are bogus.
100  */
101 struct vga_switcheroo_client {
102 	struct pci_dev *pdev;
103 	struct fb_info *fb_info;
104 	enum vga_switcheroo_state pwr_state;
105 	const struct vga_switcheroo_client_ops *ops;
106 	enum vga_switcheroo_client_id id;
107 	bool active;
108 	bool driver_power_control;
109 	struct list_head list;
110 };
111 
112 /*
113  * protects access to struct vgasr_priv
114  */
115 static DEFINE_MUTEX(vgasr_mutex);
116 
117 /**
118  * struct vgasr_priv - vga_switcheroo private data
119  * @active: whether vga_switcheroo is enabled.
120  * 	Prerequisite is the registration of two GPUs and a handler
121  * @delayed_switch_active: whether a delayed switch is pending
122  * @delayed_client_id: client to which a delayed switch is pending
123  * @debugfs_root: directory for vga_switcheroo debugfs interface
124  * @switch_file: file for vga_switcheroo debugfs interface
125  * @registered_clients: number of registered GPUs
126  * 	(counting only vga clients, not audio clients)
127  * @clients: list of registered clients
128  * @handler: registered handler
129  *
130  * vga_switcheroo private data. Currently only one vga_switcheroo instance
131  * per system is supported.
132  */
133 struct vgasr_priv {
134 	bool active;
135 	bool delayed_switch_active;
136 	enum vga_switcheroo_client_id delayed_client_id;
137 
138 	struct dentry *debugfs_root;
139 	struct dentry *switch_file;
140 
141 	int registered_clients;
142 	struct list_head clients;
143 
144 	const struct vga_switcheroo_handler *handler;
145 };
146 
147 #define ID_BIT_AUDIO		0x100
148 #define client_is_audio(c)	((c)->id & ID_BIT_AUDIO)
149 #define client_is_vga(c)	((c)->id == VGA_SWITCHEROO_UNKNOWN_ID || \
150 				 !client_is_audio(c))
151 #define client_id(c)		((c)->id & ~ID_BIT_AUDIO)
152 
153 static int vga_switcheroo_debugfs_init(struct vgasr_priv *priv);
154 static void vga_switcheroo_debugfs_fini(struct vgasr_priv *priv);
155 
156 /* only one switcheroo per system */
157 static struct vgasr_priv vgasr_priv = {
158 	.clients = LIST_HEAD_INIT(vgasr_priv.clients),
159 };
160 
161 static bool vga_switcheroo_ready(void)
162 {
163 	/* we're ready if we get two clients + handler */
164 	return !vgasr_priv.active &&
165 	       vgasr_priv.registered_clients == 2 && vgasr_priv.handler;
166 }
167 
168 static void vga_switcheroo_enable(void)
169 {
170 	int ret;
171 	struct vga_switcheroo_client *client;
172 
173 	/* call the handler to init */
174 	if (vgasr_priv.handler->init)
175 		vgasr_priv.handler->init();
176 
177 	list_for_each_entry(client, &vgasr_priv.clients, list) {
178 		if (client->id != VGA_SWITCHEROO_UNKNOWN_ID)
179 			continue;
180 		ret = vgasr_priv.handler->get_client_id(client->pdev);
181 		if (ret < 0)
182 			return;
183 
184 		client->id = ret;
185 	}
186 	vga_switcheroo_debugfs_init(&vgasr_priv);
187 	vgasr_priv.active = true;
188 }
189 
190 /**
191  * vga_switcheroo_register_handler() - register handler
192  * @handler: handler callbacks
193  *
194  * Register handler. Enable vga_switcheroo if two vga clients have already
195  * registered.
196  *
197  * Return: 0 on success, -EINVAL if a handler was already registered.
198  */
199 int vga_switcheroo_register_handler(const struct vga_switcheroo_handler *handler)
200 {
201 	mutex_lock(&vgasr_mutex);
202 	if (vgasr_priv.handler) {
203 		mutex_unlock(&vgasr_mutex);
204 		return -EINVAL;
205 	}
206 
207 	vgasr_priv.handler = handler;
208 	if (vga_switcheroo_ready()) {
209 		pr_info("enabled\n");
210 		vga_switcheroo_enable();
211 	}
212 	mutex_unlock(&vgasr_mutex);
213 	return 0;
214 }
215 EXPORT_SYMBOL(vga_switcheroo_register_handler);
216 
217 /**
218  * vga_switcheroo_unregister_handler() - unregister handler
219  *
220  * Unregister handler. Disable vga_switcheroo.
221  */
222 void vga_switcheroo_unregister_handler(void)
223 {
224 	mutex_lock(&vgasr_mutex);
225 	vgasr_priv.handler = NULL;
226 	if (vgasr_priv.active) {
227 		pr_info("disabled\n");
228 		vga_switcheroo_debugfs_fini(&vgasr_priv);
229 		vgasr_priv.active = false;
230 	}
231 	mutex_unlock(&vgasr_mutex);
232 }
233 EXPORT_SYMBOL(vga_switcheroo_unregister_handler);
234 
235 static int register_client(struct pci_dev *pdev,
236 			   const struct vga_switcheroo_client_ops *ops,
237 			   enum vga_switcheroo_client_id id, bool active,
238 			   bool driver_power_control)
239 {
240 	struct vga_switcheroo_client *client;
241 
242 	client = kzalloc(sizeof(*client), GFP_KERNEL);
243 	if (!client)
244 		return -ENOMEM;
245 
246 	client->pwr_state = VGA_SWITCHEROO_ON;
247 	client->pdev = pdev;
248 	client->ops = ops;
249 	client->id = id;
250 	client->active = active;
251 	client->driver_power_control = driver_power_control;
252 
253 	mutex_lock(&vgasr_mutex);
254 	list_add_tail(&client->list, &vgasr_priv.clients);
255 	if (client_is_vga(client))
256 		vgasr_priv.registered_clients++;
257 
258 	if (vga_switcheroo_ready()) {
259 		pr_info("enabled\n");
260 		vga_switcheroo_enable();
261 	}
262 	mutex_unlock(&vgasr_mutex);
263 	return 0;
264 }
265 
266 /**
267  * vga_switcheroo_register_client - register vga client
268  * @pdev: client pci device
269  * @ops: client callbacks
270  * @driver_power_control: whether power state is controlled by the driver's
271  * 	runtime pm
272  *
273  * Register vga client (GPU). Enable vga_switcheroo if another GPU and a
274  * handler have already registered. The power state of the client is assumed
275  * to be ON.
276  *
277  * Return: 0 on success, -ENOMEM on memory allocation error.
278  */
279 int vga_switcheroo_register_client(struct pci_dev *pdev,
280 				   const struct vga_switcheroo_client_ops *ops,
281 				   bool driver_power_control)
282 {
283 	return register_client(pdev, ops, VGA_SWITCHEROO_UNKNOWN_ID,
284 			       pdev == vga_default_device(),
285 			       driver_power_control);
286 }
287 EXPORT_SYMBOL(vga_switcheroo_register_client);
288 
289 /**
290  * vga_switcheroo_register_audio_client - register audio client
291  * @pdev: client pci device
292  * @ops: client callbacks
293  * @id: client identifier
294  *
295  * Register audio client (audio device on a GPU). The power state of the
296  * client is assumed to be ON.
297  *
298  * Return: 0 on success, -ENOMEM on memory allocation error.
299  */
300 int vga_switcheroo_register_audio_client(struct pci_dev *pdev,
301 					 const struct vga_switcheroo_client_ops *ops,
302 					 enum vga_switcheroo_client_id id)
303 {
304 	return register_client(pdev, ops, id | ID_BIT_AUDIO, false, false);
305 }
306 EXPORT_SYMBOL(vga_switcheroo_register_audio_client);
307 
308 static struct vga_switcheroo_client *
309 find_client_from_pci(struct list_head *head, struct pci_dev *pdev)
310 {
311 	struct vga_switcheroo_client *client;
312 
313 	list_for_each_entry(client, head, list)
314 		if (client->pdev == pdev)
315 			return client;
316 	return NULL;
317 }
318 
319 static struct vga_switcheroo_client *
320 find_client_from_id(struct list_head *head,
321 		    enum vga_switcheroo_client_id client_id)
322 {
323 	struct vga_switcheroo_client *client;
324 
325 	list_for_each_entry(client, head, list)
326 		if (client->id == client_id)
327 			return client;
328 	return NULL;
329 }
330 
331 static struct vga_switcheroo_client *
332 find_active_client(struct list_head *head)
333 {
334 	struct vga_switcheroo_client *client;
335 
336 	list_for_each_entry(client, head, list)
337 		if (client->active)
338 			return client;
339 	return NULL;
340 }
341 
342 /**
343  * vga_switcheroo_get_client_state() - obtain power state of a given client
344  * @pdev: client pci device
345  *
346  * Obtain power state of a given client as seen from vga_switcheroo.
347  * The function is only called from hda_intel.c.
348  *
349  * Return: Power state.
350  */
351 enum vga_switcheroo_state vga_switcheroo_get_client_state(struct pci_dev *pdev)
352 {
353 	struct vga_switcheroo_client *client;
354 	enum vga_switcheroo_state ret;
355 
356 	mutex_lock(&vgasr_mutex);
357 	client = find_client_from_pci(&vgasr_priv.clients, pdev);
358 	if (!client)
359 		ret = VGA_SWITCHEROO_NOT_FOUND;
360 	else
361 		ret = client->pwr_state;
362 	mutex_unlock(&vgasr_mutex);
363 	return ret;
364 }
365 EXPORT_SYMBOL(vga_switcheroo_get_client_state);
366 
367 /**
368  * vga_switcheroo_unregister_client() - unregister client
369  * @pdev: client pci device
370  *
371  * Unregister client. Disable vga_switcheroo if this is a vga client (GPU).
372  */
373 void vga_switcheroo_unregister_client(struct pci_dev *pdev)
374 {
375 	struct vga_switcheroo_client *client;
376 
377 	mutex_lock(&vgasr_mutex);
378 	client = find_client_from_pci(&vgasr_priv.clients, pdev);
379 	if (client) {
380 		if (client_is_vga(client))
381 			vgasr_priv.registered_clients--;
382 		list_del(&client->list);
383 		kfree(client);
384 	}
385 	if (vgasr_priv.active && vgasr_priv.registered_clients < 2) {
386 		pr_info("disabled\n");
387 		vga_switcheroo_debugfs_fini(&vgasr_priv);
388 		vgasr_priv.active = false;
389 	}
390 	mutex_unlock(&vgasr_mutex);
391 }
392 EXPORT_SYMBOL(vga_switcheroo_unregister_client);
393 
394 /**
395  * vga_switcheroo_client_fb_set() - set framebuffer of a given client
396  * @pdev: client pci device
397  * @info: framebuffer
398  *
399  * Set framebuffer of a given client. The console will be remapped to this
400  * on switching.
401  */
402 void vga_switcheroo_client_fb_set(struct pci_dev *pdev,
403 				 struct fb_info *info)
404 {
405 	struct vga_switcheroo_client *client;
406 
407 	mutex_lock(&vgasr_mutex);
408 	client = find_client_from_pci(&vgasr_priv.clients, pdev);
409 	if (client)
410 		client->fb_info = info;
411 	mutex_unlock(&vgasr_mutex);
412 }
413 EXPORT_SYMBOL(vga_switcheroo_client_fb_set);
414 
415 /**
416  * DOC: Manual switching and manual power control
417  *
418  * In this mode of use, the file /sys/kernel/debug/vgaswitcheroo/switch
419  * can be read to retrieve the current vga_switcheroo state and commands
420  * can be written to it to change the state. The file appears as soon as
421  * two GPU drivers and one handler have registered with vga_switcheroo.
422  * The following commands are understood:
423  *
424  * * OFF: Power off the device not in use.
425  * * ON: Power on the device not in use.
426  * * IGD: Switch to the integrated graphics device.
427  * 	Power on the integrated GPU if necessary, power off the discrete GPU.
428  * 	Prerequisite is that no user space processes (e.g. Xorg, alsactl)
429  * 	have opened device files of the GPUs or the audio client. If the
430  * 	switch fails, the user may invoke lsof(8) or fuser(1) on /dev/dri/
431  * 	and /dev/snd/controlC1 to identify processes blocking the switch.
432  * * DIS: Switch to the discrete graphics device.
433  * * DIGD: Delayed switch to the integrated graphics device.
434  * 	This will perform the switch once the last user space process has
435  * 	closed the device files of the GPUs and the audio client.
436  * * DDIS: Delayed switch to the discrete graphics device.
437  * * MIGD: Mux-only switch to the integrated graphics device.
438  * 	Does not remap console or change the power state of either gpu.
439  * 	If the integrated GPU is currently off, the screen will turn black.
440  * 	If it is on, the screen will show whatever happens to be in VRAM.
441  * 	Either way, the user has to blindly enter the command to switch back.
442  * * MDIS: Mux-only switch to the discrete graphics device.
443  *
444  * For GPUs whose power state is controlled by the driver's runtime pm,
445  * the ON and OFF commands are a no-op (see next section).
446  *
447  * For muxless machines, the IGD/DIS, DIGD/DDIS and MIGD/MDIS commands
448  * should not be used.
449  */
450 
451 static int vga_switcheroo_show(struct seq_file *m, void *v)
452 {
453 	struct vga_switcheroo_client *client;
454 	int i = 0;
455 
456 	mutex_lock(&vgasr_mutex);
457 	list_for_each_entry(client, &vgasr_priv.clients, list) {
458 		seq_printf(m, "%d:%s%s:%c:%s%s:%s\n", i,
459 			   client_id(client) == VGA_SWITCHEROO_DIS ? "DIS" :
460 								     "IGD",
461 			   client_is_vga(client) ? "" : "-Audio",
462 			   client->active ? '+' : ' ',
463 			   client->driver_power_control ? "Dyn" : "",
464 			   client->pwr_state ? "Pwr" : "Off",
465 			   pci_name(client->pdev));
466 		i++;
467 	}
468 	mutex_unlock(&vgasr_mutex);
469 	return 0;
470 }
471 
472 static int vga_switcheroo_debugfs_open(struct inode *inode, struct file *file)
473 {
474 	return single_open(file, vga_switcheroo_show, NULL);
475 }
476 
477 static int vga_switchon(struct vga_switcheroo_client *client)
478 {
479 	if (client->driver_power_control)
480 		return 0;
481 	if (vgasr_priv.handler->power_state)
482 		vgasr_priv.handler->power_state(client->id, VGA_SWITCHEROO_ON);
483 	/* call the driver callback to turn on device */
484 	client->ops->set_gpu_state(client->pdev, VGA_SWITCHEROO_ON);
485 	client->pwr_state = VGA_SWITCHEROO_ON;
486 	return 0;
487 }
488 
489 static int vga_switchoff(struct vga_switcheroo_client *client)
490 {
491 	if (client->driver_power_control)
492 		return 0;
493 	/* call the driver callback to turn off device */
494 	client->ops->set_gpu_state(client->pdev, VGA_SWITCHEROO_OFF);
495 	if (vgasr_priv.handler->power_state)
496 		vgasr_priv.handler->power_state(client->id, VGA_SWITCHEROO_OFF);
497 	client->pwr_state = VGA_SWITCHEROO_OFF;
498 	return 0;
499 }
500 
501 static void set_audio_state(enum vga_switcheroo_client_id id,
502 			    enum vga_switcheroo_state state)
503 {
504 	struct vga_switcheroo_client *client;
505 
506 	client = find_client_from_id(&vgasr_priv.clients, id | ID_BIT_AUDIO);
507 	if (client && client->pwr_state != state) {
508 		client->ops->set_gpu_state(client->pdev, state);
509 		client->pwr_state = state;
510 	}
511 }
512 
513 /* stage one happens before delay */
514 static int vga_switchto_stage1(struct vga_switcheroo_client *new_client)
515 {
516 	struct vga_switcheroo_client *active;
517 
518 	active = find_active_client(&vgasr_priv.clients);
519 	if (!active)
520 		return 0;
521 
522 	if (new_client->pwr_state == VGA_SWITCHEROO_OFF)
523 		vga_switchon(new_client);
524 
525 	vga_set_default_device(new_client->pdev);
526 	return 0;
527 }
528 
529 /* post delay */
530 static int vga_switchto_stage2(struct vga_switcheroo_client *new_client)
531 {
532 	int ret;
533 	struct vga_switcheroo_client *active;
534 
535 	active = find_active_client(&vgasr_priv.clients);
536 	if (!active)
537 		return 0;
538 
539 	active->active = false;
540 
541 	set_audio_state(active->id, VGA_SWITCHEROO_OFF);
542 
543 	if (new_client->fb_info) {
544 		struct fb_event event;
545 
546 		console_lock();
547 		event.info = new_client->fb_info;
548 		fb_notifier_call_chain(FB_EVENT_REMAP_ALL_CONSOLE, &event);
549 		console_unlock();
550 	}
551 
552 	ret = vgasr_priv.handler->switchto(new_client->id);
553 	if (ret)
554 		return ret;
555 
556 	if (new_client->ops->reprobe)
557 		new_client->ops->reprobe(new_client->pdev);
558 
559 	if (active->pwr_state == VGA_SWITCHEROO_ON)
560 		vga_switchoff(active);
561 
562 	set_audio_state(new_client->id, VGA_SWITCHEROO_ON);
563 
564 	new_client->active = true;
565 	return 0;
566 }
567 
568 static bool check_can_switch(void)
569 {
570 	struct vga_switcheroo_client *client;
571 
572 	list_for_each_entry(client, &vgasr_priv.clients, list) {
573 		if (!client->ops->can_switch(client->pdev)) {
574 			pr_err("client %x refused switch\n", client->id);
575 			return false;
576 		}
577 	}
578 	return true;
579 }
580 
581 static ssize_t
582 vga_switcheroo_debugfs_write(struct file *filp, const char __user *ubuf,
583 			     size_t cnt, loff_t *ppos)
584 {
585 	char usercmd[64];
586 	int ret;
587 	bool delay = false, can_switch;
588 	bool just_mux = false;
589 	enum vga_switcheroo_client_id client_id = VGA_SWITCHEROO_UNKNOWN_ID;
590 	struct vga_switcheroo_client *client = NULL;
591 
592 	if (cnt > 63)
593 		cnt = 63;
594 
595 	if (copy_from_user(usercmd, ubuf, cnt))
596 		return -EFAULT;
597 
598 	mutex_lock(&vgasr_mutex);
599 
600 	if (!vgasr_priv.active) {
601 		cnt = -EINVAL;
602 		goto out;
603 	}
604 
605 	/* pwr off the device not in use */
606 	if (strncmp(usercmd, "OFF", 3) == 0) {
607 		list_for_each_entry(client, &vgasr_priv.clients, list) {
608 			if (client->active || client_is_audio(client))
609 				continue;
610 			if (client->driver_power_control)
611 				continue;
612 			set_audio_state(client->id, VGA_SWITCHEROO_OFF);
613 			if (client->pwr_state == VGA_SWITCHEROO_ON)
614 				vga_switchoff(client);
615 		}
616 		goto out;
617 	}
618 	/* pwr on the device not in use */
619 	if (strncmp(usercmd, "ON", 2) == 0) {
620 		list_for_each_entry(client, &vgasr_priv.clients, list) {
621 			if (client->active || client_is_audio(client))
622 				continue;
623 			if (client->driver_power_control)
624 				continue;
625 			if (client->pwr_state == VGA_SWITCHEROO_OFF)
626 				vga_switchon(client);
627 			set_audio_state(client->id, VGA_SWITCHEROO_ON);
628 		}
629 		goto out;
630 	}
631 
632 	/* request a delayed switch - test can we switch now */
633 	if (strncmp(usercmd, "DIGD", 4) == 0) {
634 		client_id = VGA_SWITCHEROO_IGD;
635 		delay = true;
636 	}
637 
638 	if (strncmp(usercmd, "DDIS", 4) == 0) {
639 		client_id = VGA_SWITCHEROO_DIS;
640 		delay = true;
641 	}
642 
643 	if (strncmp(usercmd, "IGD", 3) == 0)
644 		client_id = VGA_SWITCHEROO_IGD;
645 
646 	if (strncmp(usercmd, "DIS", 3) == 0)
647 		client_id = VGA_SWITCHEROO_DIS;
648 
649 	if (strncmp(usercmd, "MIGD", 4) == 0) {
650 		just_mux = true;
651 		client_id = VGA_SWITCHEROO_IGD;
652 	}
653 	if (strncmp(usercmd, "MDIS", 4) == 0) {
654 		just_mux = true;
655 		client_id = VGA_SWITCHEROO_DIS;
656 	}
657 
658 	if (client_id == VGA_SWITCHEROO_UNKNOWN_ID)
659 		goto out;
660 	client = find_client_from_id(&vgasr_priv.clients, client_id);
661 	if (!client)
662 		goto out;
663 
664 	vgasr_priv.delayed_switch_active = false;
665 
666 	if (just_mux) {
667 		ret = vgasr_priv.handler->switchto(client_id);
668 		goto out;
669 	}
670 
671 	if (client->active)
672 		goto out;
673 
674 	/* okay we want a switch - test if devices are willing to switch */
675 	can_switch = check_can_switch();
676 
677 	if (can_switch == false && delay == false)
678 		goto out;
679 
680 	if (can_switch) {
681 		ret = vga_switchto_stage1(client);
682 		if (ret)
683 			pr_err("switching failed stage 1 %d\n", ret);
684 
685 		ret = vga_switchto_stage2(client);
686 		if (ret)
687 			pr_err("switching failed stage 2 %d\n", ret);
688 
689 	} else {
690 		pr_info("setting delayed switch to client %d\n", client->id);
691 		vgasr_priv.delayed_switch_active = true;
692 		vgasr_priv.delayed_client_id = client_id;
693 
694 		ret = vga_switchto_stage1(client);
695 		if (ret)
696 			pr_err("delayed switching stage 1 failed %d\n", ret);
697 	}
698 
699 out:
700 	mutex_unlock(&vgasr_mutex);
701 	return cnt;
702 }
703 
704 static const struct file_operations vga_switcheroo_debugfs_fops = {
705 	.owner = THIS_MODULE,
706 	.open = vga_switcheroo_debugfs_open,
707 	.write = vga_switcheroo_debugfs_write,
708 	.read = seq_read,
709 	.llseek = seq_lseek,
710 	.release = single_release,
711 };
712 
713 static void vga_switcheroo_debugfs_fini(struct vgasr_priv *priv)
714 {
715 	debugfs_remove(priv->switch_file);
716 	priv->switch_file = NULL;
717 
718 	debugfs_remove(priv->debugfs_root);
719 	priv->debugfs_root = NULL;
720 }
721 
722 static int vga_switcheroo_debugfs_init(struct vgasr_priv *priv)
723 {
724 	static const char mp[] = "/sys/kernel/debug";
725 
726 	/* already initialised */
727 	if (priv->debugfs_root)
728 		return 0;
729 	priv->debugfs_root = debugfs_create_dir("vgaswitcheroo", NULL);
730 
731 	if (!priv->debugfs_root) {
732 		pr_err("Cannot create %s/vgaswitcheroo\n", mp);
733 		goto fail;
734 	}
735 
736 	priv->switch_file = debugfs_create_file("switch", 0644,
737 						priv->debugfs_root, NULL,
738 						&vga_switcheroo_debugfs_fops);
739 	if (!priv->switch_file) {
740 		pr_err("cannot create %s/vgaswitcheroo/switch\n", mp);
741 		goto fail;
742 	}
743 	return 0;
744 fail:
745 	vga_switcheroo_debugfs_fini(priv);
746 	return -1;
747 }
748 
749 /**
750  * vga_switcheroo_process_delayed_switch() - helper for delayed switching
751  *
752  * Process a delayed switch if one is pending. DRM drivers should call this
753  * from their ->lastclose callback.
754  *
755  * Return: 0 on success. -EINVAL if no delayed switch is pending, if the client
756  * has unregistered in the meantime or if there are other clients blocking the
757  * switch. If the actual switch fails, an error is reported and 0 is returned.
758  */
759 int vga_switcheroo_process_delayed_switch(void)
760 {
761 	struct vga_switcheroo_client *client;
762 	int ret;
763 	int err = -EINVAL;
764 
765 	mutex_lock(&vgasr_mutex);
766 	if (!vgasr_priv.delayed_switch_active)
767 		goto err;
768 
769 	pr_info("processing delayed switch to %d\n",
770 		vgasr_priv.delayed_client_id);
771 
772 	client = find_client_from_id(&vgasr_priv.clients,
773 				     vgasr_priv.delayed_client_id);
774 	if (!client || !check_can_switch())
775 		goto err;
776 
777 	ret = vga_switchto_stage2(client);
778 	if (ret)
779 		pr_err("delayed switching failed stage 2 %d\n", ret);
780 
781 	vgasr_priv.delayed_switch_active = false;
782 	err = 0;
783 err:
784 	mutex_unlock(&vgasr_mutex);
785 	return err;
786 }
787 EXPORT_SYMBOL(vga_switcheroo_process_delayed_switch);
788 
789 /**
790  * DOC: Driver power control
791  *
792  * In this mode of use, the discrete GPU automatically powers up and down at
793  * the discretion of the driver's runtime pm. On muxed machines, the user may
794  * still influence the muxer state by way of the debugfs interface, however
795  * the ON and OFF commands become a no-op for the discrete GPU.
796  *
797  * This mode is the default on Nvidia HybridPower/Optimus and ATI PowerXpress.
798  * Specifying nouveau.runpm=0, radeon.runpm=0 or amdgpu.runpm=0 on the kernel
799  * command line disables it.
800  *
801  * When the driver decides to power up or down, it notifies vga_switcheroo
802  * thereof so that it can (a) power the audio device on the GPU up or down,
803  * and (b) update its internal power state representation for the device.
804  * This is achieved by vga_switcheroo_set_dynamic_switch().
805  *
806  * After the GPU has been suspended, the handler needs to be called to cut
807  * power to the GPU. Likewise it needs to reinstate power before the GPU
808  * can resume. This is achieved by vga_switcheroo_init_domain_pm_ops(),
809  * which augments the GPU's suspend/resume functions by the requisite
810  * calls to the handler.
811  *
812  * When the audio device resumes, the GPU needs to be woken. This is achieved
813  * by vga_switcheroo_init_domain_pm_optimus_hdmi_audio(), which augments the
814  * audio device's resume function.
815  *
816  * On muxed machines, if the mux is initially switched to the discrete GPU,
817  * the user ends up with a black screen when the GPU powers down after boot.
818  * As a workaround, the mux is forced to the integrated GPU on runtime suspend,
819  * cf. https://bugs.freedesktop.org/show_bug.cgi?id=75917
820  */
821 
822 static void vga_switcheroo_power_switch(struct pci_dev *pdev,
823 					enum vga_switcheroo_state state)
824 {
825 	struct vga_switcheroo_client *client;
826 
827 	if (!vgasr_priv.handler->power_state)
828 		return;
829 
830 	client = find_client_from_pci(&vgasr_priv.clients, pdev);
831 	if (!client)
832 		return;
833 
834 	if (!client->driver_power_control)
835 		return;
836 
837 	vgasr_priv.handler->power_state(client->id, state);
838 }
839 
840 /**
841  * vga_switcheroo_set_dynamic_switch() - helper for driver power control
842  * @pdev: client pci device
843  * @dynamic: new power state
844  *
845  * Helper for GPUs whose power state is controlled by the driver's runtime pm.
846  * When the driver decides to power up or down, it notifies vga_switcheroo
847  * thereof using this helper so that it can (a) power the audio device on
848  * the GPU up or down, and (b) update its internal power state representation
849  * for the device.
850  */
851 void vga_switcheroo_set_dynamic_switch(struct pci_dev *pdev,
852 				       enum vga_switcheroo_state dynamic)
853 {
854 	struct vga_switcheroo_client *client;
855 
856 	mutex_lock(&vgasr_mutex);
857 	client = find_client_from_pci(&vgasr_priv.clients, pdev);
858 	if (!client || !client->driver_power_control) {
859 		mutex_unlock(&vgasr_mutex);
860 		return;
861 	}
862 
863 	client->pwr_state = dynamic;
864 	set_audio_state(client->id, dynamic);
865 	mutex_unlock(&vgasr_mutex);
866 }
867 EXPORT_SYMBOL(vga_switcheroo_set_dynamic_switch);
868 
869 /* switcheroo power domain */
870 static int vga_switcheroo_runtime_suspend(struct device *dev)
871 {
872 	struct pci_dev *pdev = to_pci_dev(dev);
873 	int ret;
874 
875 	ret = dev->bus->pm->runtime_suspend(dev);
876 	if (ret)
877 		return ret;
878 	mutex_lock(&vgasr_mutex);
879 	if (vgasr_priv.handler->switchto)
880 		vgasr_priv.handler->switchto(VGA_SWITCHEROO_IGD);
881 	vga_switcheroo_power_switch(pdev, VGA_SWITCHEROO_OFF);
882 	mutex_unlock(&vgasr_mutex);
883 	return 0;
884 }
885 
886 static int vga_switcheroo_runtime_resume(struct device *dev)
887 {
888 	struct pci_dev *pdev = to_pci_dev(dev);
889 	int ret;
890 
891 	mutex_lock(&vgasr_mutex);
892 	vga_switcheroo_power_switch(pdev, VGA_SWITCHEROO_ON);
893 	mutex_unlock(&vgasr_mutex);
894 	ret = dev->bus->pm->runtime_resume(dev);
895 	if (ret)
896 		return ret;
897 
898 	return 0;
899 }
900 
901 /**
902  * vga_switcheroo_init_domain_pm_ops() - helper for driver power control
903  * @dev: vga client device
904  * @domain: power domain
905  *
906  * Helper for GPUs whose power state is controlled by the driver's runtime pm.
907  * After the GPU has been suspended, the handler needs to be called to cut
908  * power to the GPU. Likewise it needs to reinstate power before the GPU
909  * can resume. To this end, this helper augments the suspend/resume functions
910  * by the requisite calls to the handler. It needs only be called on platforms
911  * where the power switch is separate to the device being powered down.
912  */
913 int vga_switcheroo_init_domain_pm_ops(struct device *dev,
914 				      struct dev_pm_domain *domain)
915 {
916 	/* copy over all the bus versions */
917 	if (dev->bus && dev->bus->pm) {
918 		domain->ops = *dev->bus->pm;
919 		domain->ops.runtime_suspend = vga_switcheroo_runtime_suspend;
920 		domain->ops.runtime_resume = vga_switcheroo_runtime_resume;
921 
922 		dev_pm_domain_set(dev, domain);
923 		return 0;
924 	}
925 	dev_pm_domain_set(dev, NULL);
926 	return -EINVAL;
927 }
928 EXPORT_SYMBOL(vga_switcheroo_init_domain_pm_ops);
929 
930 void vga_switcheroo_fini_domain_pm_ops(struct device *dev)
931 {
932 	dev_pm_domain_set(dev, NULL);
933 }
934 EXPORT_SYMBOL(vga_switcheroo_fini_domain_pm_ops);
935 
936 static int vga_switcheroo_runtime_resume_hdmi_audio(struct device *dev)
937 {
938 	struct pci_dev *pdev = to_pci_dev(dev);
939 	struct vga_switcheroo_client *client;
940 	struct device *video_dev = NULL;
941 	int ret;
942 
943 	/* we need to check if we have to switch back on the video
944 	   device so the audio device can come back */
945 	mutex_lock(&vgasr_mutex);
946 	list_for_each_entry(client, &vgasr_priv.clients, list) {
947 		if (PCI_SLOT(client->pdev->devfn) == PCI_SLOT(pdev->devfn) &&
948 		    client_is_vga(client)) {
949 			video_dev = &client->pdev->dev;
950 			break;
951 		}
952 	}
953 	mutex_unlock(&vgasr_mutex);
954 
955 	if (video_dev) {
956 		ret = pm_runtime_get_sync(video_dev);
957 		if (ret && ret != 1)
958 			return ret;
959 	}
960 	ret = dev->bus->pm->runtime_resume(dev);
961 
962 	/* put the reference for the gpu */
963 	if (video_dev) {
964 		pm_runtime_mark_last_busy(video_dev);
965 		pm_runtime_put_autosuspend(video_dev);
966 	}
967 	return ret;
968 }
969 
970 /**
971  * vga_switcheroo_init_domain_pm_optimus_hdmi_audio() - helper for driver
972  * 	power control
973  * @dev: audio client device
974  * @domain: power domain
975  *
976  * Helper for GPUs whose power state is controlled by the driver's runtime pm.
977  * When the audio device resumes, the GPU needs to be woken. This helper
978  * augments the audio device's resume function to do that.
979  *
980  * Return: 0 on success, -EINVAL if no power management operations are
981  * defined for this device.
982  */
983 int
984 vga_switcheroo_init_domain_pm_optimus_hdmi_audio(struct device *dev,
985 						 struct dev_pm_domain *domain)
986 {
987 	/* copy over all the bus versions */
988 	if (dev->bus && dev->bus->pm) {
989 		domain->ops = *dev->bus->pm;
990 		domain->ops.runtime_resume =
991 			vga_switcheroo_runtime_resume_hdmi_audio;
992 
993 		dev_pm_domain_set(dev, domain);
994 		return 0;
995 	}
996 	dev_pm_domain_set(dev, NULL);
997 	return -EINVAL;
998 }
999 EXPORT_SYMBOL(vga_switcheroo_init_domain_pm_optimus_hdmi_audio);
1000