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