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