]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/gpu/drm/i915/i915_drv.c
drm/i915/hsw: Fix GPU hang during resume from S3-devices state
[karo-tx-linux.git] / drivers / gpu / drm / i915 / i915_drv.c
1 /* i915_drv.c -- i830,i845,i855,i865,i915 driver -*- linux-c -*-
2  */
3 /*
4  *
5  * Copyright 2003 Tungsten Graphics, Inc., Cedar Park, Texas.
6  * All Rights Reserved.
7  *
8  * Permission is hereby granted, free of charge, to any person obtaining a
9  * copy of this software and associated documentation files (the
10  * "Software"), to deal in the Software without restriction, including
11  * without limitation the rights to use, copy, modify, merge, publish,
12  * distribute, sub license, and/or sell copies of the Software, and to
13  * permit persons to whom the Software is furnished to do so, subject to
14  * the following conditions:
15  *
16  * The above copyright notice and this permission notice (including the
17  * next paragraph) shall be included in all copies or substantial portions
18  * of the Software.
19  *
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
21  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
23  * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS BE LIABLE FOR
24  * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
25  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
26  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27  *
28  */
29
30 #include <linux/acpi.h>
31 #include <linux/device.h>
32 #include <linux/oom.h>
33 #include <linux/module.h>
34 #include <linux/pci.h>
35 #include <linux/pm.h>
36 #include <linux/pm_runtime.h>
37 #include <linux/pnp.h>
38 #include <linux/slab.h>
39 #include <linux/vgaarb.h>
40 #include <linux/vga_switcheroo.h>
41 #include <linux/vt.h>
42 #include <acpi/video.h>
43
44 #include <drm/drmP.h>
45 #include <drm/drm_crtc_helper.h>
46 #include <drm/i915_drm.h>
47
48 #include "i915_drv.h"
49 #include "i915_trace.h"
50 #include "i915_vgpu.h"
51 #include "intel_drv.h"
52
53 static struct drm_driver driver;
54
55 static unsigned int i915_load_fail_count;
56
57 bool __i915_inject_load_failure(const char *func, int line)
58 {
59         if (i915_load_fail_count >= i915.inject_load_failure)
60                 return false;
61
62         if (++i915_load_fail_count == i915.inject_load_failure) {
63                 DRM_INFO("Injecting failure at checkpoint %u [%s:%d]\n",
64                          i915.inject_load_failure, func, line);
65                 return true;
66         }
67
68         return false;
69 }
70
71 #define FDO_BUG_URL "https://bugs.freedesktop.org/enter_bug.cgi?product=DRI"
72 #define FDO_BUG_MSG "Please file a bug at " FDO_BUG_URL " against DRM/Intel " \
73                     "providing the dmesg log by booting with drm.debug=0xf"
74
75 void
76 __i915_printk(struct drm_i915_private *dev_priv, const char *level,
77               const char *fmt, ...)
78 {
79         static bool shown_bug_once;
80         struct device *kdev = dev_priv->drm.dev;
81         bool is_error = level[1] <= KERN_ERR[1];
82         bool is_debug = level[1] == KERN_DEBUG[1];
83         struct va_format vaf;
84         va_list args;
85
86         if (is_debug && !(drm_debug & DRM_UT_DRIVER))
87                 return;
88
89         va_start(args, fmt);
90
91         vaf.fmt = fmt;
92         vaf.va = &args;
93
94         dev_printk(level, kdev, "[" DRM_NAME ":%ps] %pV",
95                    __builtin_return_address(0), &vaf);
96
97         if (is_error && !shown_bug_once) {
98                 dev_notice(kdev, "%s", FDO_BUG_MSG);
99                 shown_bug_once = true;
100         }
101
102         va_end(args);
103 }
104
105 static bool i915_error_injected(struct drm_i915_private *dev_priv)
106 {
107         return i915.inject_load_failure &&
108                i915_load_fail_count == i915.inject_load_failure;
109 }
110
111 #define i915_load_error(dev_priv, fmt, ...)                                  \
112         __i915_printk(dev_priv,                                              \
113                       i915_error_injected(dev_priv) ? KERN_DEBUG : KERN_ERR, \
114                       fmt, ##__VA_ARGS__)
115
116
117 static enum intel_pch intel_virt_detect_pch(struct drm_device *dev)
118 {
119         enum intel_pch ret = PCH_NOP;
120
121         /*
122          * In a virtualized passthrough environment we can be in a
123          * setup where the ISA bridge is not able to be passed through.
124          * In this case, a south bridge can be emulated and we have to
125          * make an educated guess as to which PCH is really there.
126          */
127
128         if (IS_GEN5(dev)) {
129                 ret = PCH_IBX;
130                 DRM_DEBUG_KMS("Assuming Ibex Peak PCH\n");
131         } else if (IS_GEN6(dev) || IS_IVYBRIDGE(dev)) {
132                 ret = PCH_CPT;
133                 DRM_DEBUG_KMS("Assuming CouarPoint PCH\n");
134         } else if (IS_HASWELL(dev) || IS_BROADWELL(dev)) {
135                 ret = PCH_LPT;
136                 DRM_DEBUG_KMS("Assuming LynxPoint PCH\n");
137         } else if (IS_SKYLAKE(dev) || IS_KABYLAKE(dev)) {
138                 ret = PCH_SPT;
139                 DRM_DEBUG_KMS("Assuming SunrisePoint PCH\n");
140         }
141
142         return ret;
143 }
144
145 static void intel_detect_pch(struct drm_device *dev)
146 {
147         struct drm_i915_private *dev_priv = to_i915(dev);
148         struct pci_dev *pch = NULL;
149
150         /* In all current cases, num_pipes is equivalent to the PCH_NOP setting
151          * (which really amounts to a PCH but no South Display).
152          */
153         if (INTEL_INFO(dev)->num_pipes == 0) {
154                 dev_priv->pch_type = PCH_NOP;
155                 return;
156         }
157
158         /*
159          * The reason to probe ISA bridge instead of Dev31:Fun0 is to
160          * make graphics device passthrough work easy for VMM, that only
161          * need to expose ISA bridge to let driver know the real hardware
162          * underneath. This is a requirement from virtualization team.
163          *
164          * In some virtualized environments (e.g. XEN), there is irrelevant
165          * ISA bridge in the system. To work reliably, we should scan trhough
166          * all the ISA bridge devices and check for the first match, instead
167          * of only checking the first one.
168          */
169         while ((pch = pci_get_class(PCI_CLASS_BRIDGE_ISA << 8, pch))) {
170                 if (pch->vendor == PCI_VENDOR_ID_INTEL) {
171                         unsigned short id = pch->device & INTEL_PCH_DEVICE_ID_MASK;
172                         dev_priv->pch_id = id;
173
174                         if (id == INTEL_PCH_IBX_DEVICE_ID_TYPE) {
175                                 dev_priv->pch_type = PCH_IBX;
176                                 DRM_DEBUG_KMS("Found Ibex Peak PCH\n");
177                                 WARN_ON(!IS_GEN5(dev));
178                         } else if (id == INTEL_PCH_CPT_DEVICE_ID_TYPE) {
179                                 dev_priv->pch_type = PCH_CPT;
180                                 DRM_DEBUG_KMS("Found CougarPoint PCH\n");
181                                 WARN_ON(!(IS_GEN6(dev) || IS_IVYBRIDGE(dev)));
182                         } else if (id == INTEL_PCH_PPT_DEVICE_ID_TYPE) {
183                                 /* PantherPoint is CPT compatible */
184                                 dev_priv->pch_type = PCH_CPT;
185                                 DRM_DEBUG_KMS("Found PantherPoint PCH\n");
186                                 WARN_ON(!(IS_GEN6(dev) || IS_IVYBRIDGE(dev)));
187                         } else if (id == INTEL_PCH_LPT_DEVICE_ID_TYPE) {
188                                 dev_priv->pch_type = PCH_LPT;
189                                 DRM_DEBUG_KMS("Found LynxPoint PCH\n");
190                                 WARN_ON(!IS_HASWELL(dev) && !IS_BROADWELL(dev));
191                                 WARN_ON(IS_HSW_ULT(dev) || IS_BDW_ULT(dev));
192                         } else if (id == INTEL_PCH_LPT_LP_DEVICE_ID_TYPE) {
193                                 dev_priv->pch_type = PCH_LPT;
194                                 DRM_DEBUG_KMS("Found LynxPoint LP PCH\n");
195                                 WARN_ON(!IS_HASWELL(dev) && !IS_BROADWELL(dev));
196                                 WARN_ON(!IS_HSW_ULT(dev) && !IS_BDW_ULT(dev));
197                         } else if (id == INTEL_PCH_SPT_DEVICE_ID_TYPE) {
198                                 dev_priv->pch_type = PCH_SPT;
199                                 DRM_DEBUG_KMS("Found SunrisePoint PCH\n");
200                                 WARN_ON(!IS_SKYLAKE(dev) &&
201                                         !IS_KABYLAKE(dev));
202                         } else if (id == INTEL_PCH_SPT_LP_DEVICE_ID_TYPE) {
203                                 dev_priv->pch_type = PCH_SPT;
204                                 DRM_DEBUG_KMS("Found SunrisePoint LP PCH\n");
205                                 WARN_ON(!IS_SKYLAKE(dev) &&
206                                         !IS_KABYLAKE(dev));
207                         } else if (id == INTEL_PCH_KBP_DEVICE_ID_TYPE) {
208                                 dev_priv->pch_type = PCH_KBP;
209                                 DRM_DEBUG_KMS("Found KabyPoint PCH\n");
210                                 WARN_ON(!IS_KABYLAKE(dev));
211                         } else if ((id == INTEL_PCH_P2X_DEVICE_ID_TYPE) ||
212                                    (id == INTEL_PCH_P3X_DEVICE_ID_TYPE) ||
213                                    ((id == INTEL_PCH_QEMU_DEVICE_ID_TYPE) &&
214                                     pch->subsystem_vendor ==
215                                             PCI_SUBVENDOR_ID_REDHAT_QUMRANET &&
216                                     pch->subsystem_device ==
217                                             PCI_SUBDEVICE_ID_QEMU)) {
218                                 dev_priv->pch_type = intel_virt_detect_pch(dev);
219                         } else
220                                 continue;
221
222                         break;
223                 }
224         }
225         if (!pch)
226                 DRM_DEBUG_KMS("No PCH found.\n");
227
228         pci_dev_put(pch);
229 }
230
231 static int i915_getparam(struct drm_device *dev, void *data,
232                          struct drm_file *file_priv)
233 {
234         struct drm_i915_private *dev_priv = to_i915(dev);
235         struct pci_dev *pdev = dev_priv->drm.pdev;
236         drm_i915_getparam_t *param = data;
237         int value;
238
239         switch (param->param) {
240         case I915_PARAM_IRQ_ACTIVE:
241         case I915_PARAM_ALLOW_BATCHBUFFER:
242         case I915_PARAM_LAST_DISPATCH:
243                 /* Reject all old ums/dri params. */
244                 return -ENODEV;
245         case I915_PARAM_CHIPSET_ID:
246                 value = pdev->device;
247                 break;
248         case I915_PARAM_REVISION:
249                 value = pdev->revision;
250                 break;
251         case I915_PARAM_NUM_FENCES_AVAIL:
252                 value = dev_priv->num_fence_regs;
253                 break;
254         case I915_PARAM_HAS_OVERLAY:
255                 value = dev_priv->overlay ? 1 : 0;
256                 break;
257         case I915_PARAM_HAS_BSD:
258                 value = intel_engine_initialized(&dev_priv->engine[VCS]);
259                 break;
260         case I915_PARAM_HAS_BLT:
261                 value = intel_engine_initialized(&dev_priv->engine[BCS]);
262                 break;
263         case I915_PARAM_HAS_VEBOX:
264                 value = intel_engine_initialized(&dev_priv->engine[VECS]);
265                 break;
266         case I915_PARAM_HAS_BSD2:
267                 value = intel_engine_initialized(&dev_priv->engine[VCS2]);
268                 break;
269         case I915_PARAM_HAS_EXEC_CONSTANTS:
270                 value = INTEL_GEN(dev_priv) >= 4;
271                 break;
272         case I915_PARAM_HAS_LLC:
273                 value = HAS_LLC(dev_priv);
274                 break;
275         case I915_PARAM_HAS_WT:
276                 value = HAS_WT(dev_priv);
277                 break;
278         case I915_PARAM_HAS_ALIASING_PPGTT:
279                 value = USES_PPGTT(dev_priv);
280                 break;
281         case I915_PARAM_HAS_SEMAPHORES:
282                 value = i915.semaphores;
283                 break;
284         case I915_PARAM_HAS_SECURE_BATCHES:
285                 value = capable(CAP_SYS_ADMIN);
286                 break;
287         case I915_PARAM_CMD_PARSER_VERSION:
288                 value = i915_cmd_parser_get_version(dev_priv);
289                 break;
290         case I915_PARAM_SUBSLICE_TOTAL:
291                 value = sseu_subslice_total(&INTEL_INFO(dev_priv)->sseu);
292                 if (!value)
293                         return -ENODEV;
294                 break;
295         case I915_PARAM_EU_TOTAL:
296                 value = INTEL_INFO(dev_priv)->sseu.eu_total;
297                 if (!value)
298                         return -ENODEV;
299                 break;
300         case I915_PARAM_HAS_GPU_RESET:
301                 value = i915.enable_hangcheck && intel_has_gpu_reset(dev_priv);
302                 break;
303         case I915_PARAM_HAS_RESOURCE_STREAMER:
304                 value = HAS_RESOURCE_STREAMER(dev_priv);
305                 break;
306         case I915_PARAM_HAS_POOLED_EU:
307                 value = HAS_POOLED_EU(dev_priv);
308                 break;
309         case I915_PARAM_MIN_EU_IN_POOL:
310                 value = INTEL_INFO(dev_priv)->sseu.min_eu_in_pool;
311                 break;
312         case I915_PARAM_MMAP_GTT_VERSION:
313                 /* Though we've started our numbering from 1, and so class all
314                  * earlier versions as 0, in effect their value is undefined as
315                  * the ioctl will report EINVAL for the unknown param!
316                  */
317                 value = i915_gem_mmap_gtt_version();
318                 break;
319         case I915_PARAM_MMAP_VERSION:
320                 /* Remember to bump this if the version changes! */
321         case I915_PARAM_HAS_GEM:
322         case I915_PARAM_HAS_PAGEFLIPPING:
323         case I915_PARAM_HAS_EXECBUF2: /* depends on GEM */
324         case I915_PARAM_HAS_RELAXED_FENCING:
325         case I915_PARAM_HAS_COHERENT_RINGS:
326         case I915_PARAM_HAS_RELAXED_DELTA:
327         case I915_PARAM_HAS_GEN7_SOL_RESET:
328         case I915_PARAM_HAS_WAIT_TIMEOUT:
329         case I915_PARAM_HAS_PRIME_VMAP_FLUSH:
330         case I915_PARAM_HAS_PINNED_BATCHES:
331         case I915_PARAM_HAS_EXEC_NO_RELOC:
332         case I915_PARAM_HAS_EXEC_HANDLE_LUT:
333         case I915_PARAM_HAS_COHERENT_PHYS_GTT:
334         case I915_PARAM_HAS_EXEC_SOFTPIN:
335                 /* For the time being all of these are always true;
336                  * if some supported hardware does not have one of these
337                  * features this value needs to be provided from
338                  * INTEL_INFO(), a feature macro, or similar.
339                  */
340                 value = 1;
341                 break;
342         default:
343                 DRM_DEBUG("Unknown parameter %d\n", param->param);
344                 return -EINVAL;
345         }
346
347         if (put_user(value, param->value))
348                 return -EFAULT;
349
350         return 0;
351 }
352
353 static int i915_get_bridge_dev(struct drm_device *dev)
354 {
355         struct drm_i915_private *dev_priv = to_i915(dev);
356
357         dev_priv->bridge_dev = pci_get_bus_and_slot(0, PCI_DEVFN(0, 0));
358         if (!dev_priv->bridge_dev) {
359                 DRM_ERROR("bridge device not found\n");
360                 return -1;
361         }
362         return 0;
363 }
364
365 /* Allocate space for the MCH regs if needed, return nonzero on error */
366 static int
367 intel_alloc_mchbar_resource(struct drm_device *dev)
368 {
369         struct drm_i915_private *dev_priv = to_i915(dev);
370         int reg = INTEL_INFO(dev)->gen >= 4 ? MCHBAR_I965 : MCHBAR_I915;
371         u32 temp_lo, temp_hi = 0;
372         u64 mchbar_addr;
373         int ret;
374
375         if (INTEL_INFO(dev)->gen >= 4)
376                 pci_read_config_dword(dev_priv->bridge_dev, reg + 4, &temp_hi);
377         pci_read_config_dword(dev_priv->bridge_dev, reg, &temp_lo);
378         mchbar_addr = ((u64)temp_hi << 32) | temp_lo;
379
380         /* If ACPI doesn't have it, assume we need to allocate it ourselves */
381 #ifdef CONFIG_PNP
382         if (mchbar_addr &&
383             pnp_range_reserved(mchbar_addr, mchbar_addr + MCHBAR_SIZE))
384                 return 0;
385 #endif
386
387         /* Get some space for it */
388         dev_priv->mch_res.name = "i915 MCHBAR";
389         dev_priv->mch_res.flags = IORESOURCE_MEM;
390         ret = pci_bus_alloc_resource(dev_priv->bridge_dev->bus,
391                                      &dev_priv->mch_res,
392                                      MCHBAR_SIZE, MCHBAR_SIZE,
393                                      PCIBIOS_MIN_MEM,
394                                      0, pcibios_align_resource,
395                                      dev_priv->bridge_dev);
396         if (ret) {
397                 DRM_DEBUG_DRIVER("failed bus alloc: %d\n", ret);
398                 dev_priv->mch_res.start = 0;
399                 return ret;
400         }
401
402         if (INTEL_INFO(dev)->gen >= 4)
403                 pci_write_config_dword(dev_priv->bridge_dev, reg + 4,
404                                        upper_32_bits(dev_priv->mch_res.start));
405
406         pci_write_config_dword(dev_priv->bridge_dev, reg,
407                                lower_32_bits(dev_priv->mch_res.start));
408         return 0;
409 }
410
411 /* Setup MCHBAR if possible, return true if we should disable it again */
412 static void
413 intel_setup_mchbar(struct drm_device *dev)
414 {
415         struct drm_i915_private *dev_priv = to_i915(dev);
416         int mchbar_reg = INTEL_INFO(dev)->gen >= 4 ? MCHBAR_I965 : MCHBAR_I915;
417         u32 temp;
418         bool enabled;
419
420         if (IS_VALLEYVIEW(dev) || IS_CHERRYVIEW(dev))
421                 return;
422
423         dev_priv->mchbar_need_disable = false;
424
425         if (IS_I915G(dev) || IS_I915GM(dev)) {
426                 pci_read_config_dword(dev_priv->bridge_dev, DEVEN, &temp);
427                 enabled = !!(temp & DEVEN_MCHBAR_EN);
428         } else {
429                 pci_read_config_dword(dev_priv->bridge_dev, mchbar_reg, &temp);
430                 enabled = temp & 1;
431         }
432
433         /* If it's already enabled, don't have to do anything */
434         if (enabled)
435                 return;
436
437         if (intel_alloc_mchbar_resource(dev))
438                 return;
439
440         dev_priv->mchbar_need_disable = true;
441
442         /* Space is allocated or reserved, so enable it. */
443         if (IS_I915G(dev) || IS_I915GM(dev)) {
444                 pci_write_config_dword(dev_priv->bridge_dev, DEVEN,
445                                        temp | DEVEN_MCHBAR_EN);
446         } else {
447                 pci_read_config_dword(dev_priv->bridge_dev, mchbar_reg, &temp);
448                 pci_write_config_dword(dev_priv->bridge_dev, mchbar_reg, temp | 1);
449         }
450 }
451
452 static void
453 intel_teardown_mchbar(struct drm_device *dev)
454 {
455         struct drm_i915_private *dev_priv = to_i915(dev);
456         int mchbar_reg = INTEL_INFO(dev)->gen >= 4 ? MCHBAR_I965 : MCHBAR_I915;
457
458         if (dev_priv->mchbar_need_disable) {
459                 if (IS_I915G(dev) || IS_I915GM(dev)) {
460                         u32 deven_val;
461
462                         pci_read_config_dword(dev_priv->bridge_dev, DEVEN,
463                                               &deven_val);
464                         deven_val &= ~DEVEN_MCHBAR_EN;
465                         pci_write_config_dword(dev_priv->bridge_dev, DEVEN,
466                                                deven_val);
467                 } else {
468                         u32 mchbar_val;
469
470                         pci_read_config_dword(dev_priv->bridge_dev, mchbar_reg,
471                                               &mchbar_val);
472                         mchbar_val &= ~1;
473                         pci_write_config_dword(dev_priv->bridge_dev, mchbar_reg,
474                                                mchbar_val);
475                 }
476         }
477
478         if (dev_priv->mch_res.start)
479                 release_resource(&dev_priv->mch_res);
480 }
481
482 /* true = enable decode, false = disable decoder */
483 static unsigned int i915_vga_set_decode(void *cookie, bool state)
484 {
485         struct drm_device *dev = cookie;
486
487         intel_modeset_vga_set_state(dev, state);
488         if (state)
489                 return VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM |
490                        VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM;
491         else
492                 return VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM;
493 }
494
495 static void i915_switcheroo_set_state(struct pci_dev *pdev, enum vga_switcheroo_state state)
496 {
497         struct drm_device *dev = pci_get_drvdata(pdev);
498         pm_message_t pmm = { .event = PM_EVENT_SUSPEND };
499
500         if (state == VGA_SWITCHEROO_ON) {
501                 pr_info("switched on\n");
502                 dev->switch_power_state = DRM_SWITCH_POWER_CHANGING;
503                 /* i915 resume handler doesn't set to D0 */
504                 pci_set_power_state(pdev, PCI_D0);
505                 i915_resume_switcheroo(dev);
506                 dev->switch_power_state = DRM_SWITCH_POWER_ON;
507         } else {
508                 pr_info("switched off\n");
509                 dev->switch_power_state = DRM_SWITCH_POWER_CHANGING;
510                 i915_suspend_switcheroo(dev, pmm);
511                 dev->switch_power_state = DRM_SWITCH_POWER_OFF;
512         }
513 }
514
515 static bool i915_switcheroo_can_switch(struct pci_dev *pdev)
516 {
517         struct drm_device *dev = pci_get_drvdata(pdev);
518
519         /*
520          * FIXME: open_count is protected by drm_global_mutex but that would lead to
521          * locking inversion with the driver load path. And the access here is
522          * completely racy anyway. So don't bother with locking for now.
523          */
524         return dev->open_count == 0;
525 }
526
527 static const struct vga_switcheroo_client_ops i915_switcheroo_ops = {
528         .set_gpu_state = i915_switcheroo_set_state,
529         .reprobe = NULL,
530         .can_switch = i915_switcheroo_can_switch,
531 };
532
533 static void i915_gem_fini(struct drm_device *dev)
534 {
535         mutex_lock(&dev->struct_mutex);
536         i915_gem_cleanup_engines(dev);
537         i915_gem_context_fini(dev);
538         mutex_unlock(&dev->struct_mutex);
539
540         WARN_ON(!list_empty(&to_i915(dev)->context_list));
541 }
542
543 static int i915_load_modeset_init(struct drm_device *dev)
544 {
545         struct drm_i915_private *dev_priv = to_i915(dev);
546         struct pci_dev *pdev = dev_priv->drm.pdev;
547         int ret;
548
549         if (i915_inject_load_failure())
550                 return -ENODEV;
551
552         ret = intel_bios_init(dev_priv);
553         if (ret)
554                 DRM_INFO("failed to find VBIOS tables\n");
555
556         /* If we have > 1 VGA cards, then we need to arbitrate access
557          * to the common VGA resources.
558          *
559          * If we are a secondary display controller (!PCI_DISPLAY_CLASS_VGA),
560          * then we do not take part in VGA arbitration and the
561          * vga_client_register() fails with -ENODEV.
562          */
563         ret = vga_client_register(pdev, dev, NULL, i915_vga_set_decode);
564         if (ret && ret != -ENODEV)
565                 goto out;
566
567         intel_register_dsm_handler();
568
569         ret = vga_switcheroo_register_client(pdev, &i915_switcheroo_ops, false);
570         if (ret)
571                 goto cleanup_vga_client;
572
573         /* must happen before intel_power_domains_init_hw() on VLV/CHV */
574         intel_update_rawclk(dev_priv);
575
576         intel_power_domains_init_hw(dev_priv, false);
577
578         intel_csr_ucode_init(dev_priv);
579
580         ret = intel_irq_install(dev_priv);
581         if (ret)
582                 goto cleanup_csr;
583
584         intel_setup_gmbus(dev);
585
586         /* Important: The output setup functions called by modeset_init need
587          * working irqs for e.g. gmbus and dp aux transfers. */
588         intel_modeset_init(dev);
589
590         intel_guc_init(dev);
591
592         ret = i915_gem_init(dev);
593         if (ret)
594                 goto cleanup_irq;
595
596         intel_modeset_gem_init(dev);
597
598         if (INTEL_INFO(dev)->num_pipes == 0)
599                 return 0;
600
601         ret = intel_fbdev_init(dev);
602         if (ret)
603                 goto cleanup_gem;
604
605         /* Only enable hotplug handling once the fbdev is fully set up. */
606         intel_hpd_init(dev_priv);
607
608         drm_kms_helper_poll_init(dev);
609
610         return 0;
611
612 cleanup_gem:
613         if (i915_gem_suspend(dev))
614                 DRM_ERROR("failed to idle hardware; continuing to unload!\n");
615         i915_gem_fini(dev);
616 cleanup_irq:
617         intel_guc_fini(dev);
618         drm_irq_uninstall(dev);
619         intel_teardown_gmbus(dev);
620 cleanup_csr:
621         intel_csr_ucode_fini(dev_priv);
622         intel_power_domains_fini(dev_priv);
623         vga_switcheroo_unregister_client(pdev);
624 cleanup_vga_client:
625         vga_client_register(pdev, NULL, NULL, NULL);
626 out:
627         return ret;
628 }
629
630 #if IS_ENABLED(CONFIG_FB)
631 static int i915_kick_out_firmware_fb(struct drm_i915_private *dev_priv)
632 {
633         struct apertures_struct *ap;
634         struct pci_dev *pdev = dev_priv->drm.pdev;
635         struct i915_ggtt *ggtt = &dev_priv->ggtt;
636         bool primary;
637         int ret;
638
639         ap = alloc_apertures(1);
640         if (!ap)
641                 return -ENOMEM;
642
643         ap->ranges[0].base = ggtt->mappable_base;
644         ap->ranges[0].size = ggtt->mappable_end;
645
646         primary =
647                 pdev->resource[PCI_ROM_RESOURCE].flags & IORESOURCE_ROM_SHADOW;
648
649         ret = drm_fb_helper_remove_conflicting_framebuffers(ap, "inteldrmfb", primary);
650
651         kfree(ap);
652
653         return ret;
654 }
655 #else
656 static int i915_kick_out_firmware_fb(struct drm_i915_private *dev_priv)
657 {
658         return 0;
659 }
660 #endif
661
662 #if !defined(CONFIG_VGA_CONSOLE)
663 static int i915_kick_out_vgacon(struct drm_i915_private *dev_priv)
664 {
665         return 0;
666 }
667 #elif !defined(CONFIG_DUMMY_CONSOLE)
668 static int i915_kick_out_vgacon(struct drm_i915_private *dev_priv)
669 {
670         return -ENODEV;
671 }
672 #else
673 static int i915_kick_out_vgacon(struct drm_i915_private *dev_priv)
674 {
675         int ret = 0;
676
677         DRM_INFO("Replacing VGA console driver\n");
678
679         console_lock();
680         if (con_is_bound(&vga_con))
681                 ret = do_take_over_console(&dummy_con, 0, MAX_NR_CONSOLES - 1, 1);
682         if (ret == 0) {
683                 ret = do_unregister_con_driver(&vga_con);
684
685                 /* Ignore "already unregistered". */
686                 if (ret == -ENODEV)
687                         ret = 0;
688         }
689         console_unlock();
690
691         return ret;
692 }
693 #endif
694
695 static void intel_init_dpio(struct drm_i915_private *dev_priv)
696 {
697         /*
698          * IOSF_PORT_DPIO is used for VLV x2 PHY (DP/HDMI B and C),
699          * CHV x1 PHY (DP/HDMI D)
700          * IOSF_PORT_DPIO_2 is used for CHV x2 PHY (DP/HDMI B and C)
701          */
702         if (IS_CHERRYVIEW(dev_priv)) {
703                 DPIO_PHY_IOSF_PORT(DPIO_PHY0) = IOSF_PORT_DPIO_2;
704                 DPIO_PHY_IOSF_PORT(DPIO_PHY1) = IOSF_PORT_DPIO;
705         } else if (IS_VALLEYVIEW(dev_priv)) {
706                 DPIO_PHY_IOSF_PORT(DPIO_PHY0) = IOSF_PORT_DPIO;
707         }
708 }
709
710 static int i915_workqueues_init(struct drm_i915_private *dev_priv)
711 {
712         /*
713          * The i915 workqueue is primarily used for batched retirement of
714          * requests (and thus managing bo) once the task has been completed
715          * by the GPU. i915_gem_retire_requests() is called directly when we
716          * need high-priority retirement, such as waiting for an explicit
717          * bo.
718          *
719          * It is also used for periodic low-priority events, such as
720          * idle-timers and recording error state.
721          *
722          * All tasks on the workqueue are expected to acquire the dev mutex
723          * so there is no point in running more than one instance of the
724          * workqueue at any time.  Use an ordered one.
725          */
726         dev_priv->wq = alloc_ordered_workqueue("i915", 0);
727         if (dev_priv->wq == NULL)
728                 goto out_err;
729
730         dev_priv->hotplug.dp_wq = alloc_ordered_workqueue("i915-dp", 0);
731         if (dev_priv->hotplug.dp_wq == NULL)
732                 goto out_free_wq;
733
734         return 0;
735
736 out_free_wq:
737         destroy_workqueue(dev_priv->wq);
738 out_err:
739         DRM_ERROR("Failed to allocate workqueues.\n");
740
741         return -ENOMEM;
742 }
743
744 static void i915_workqueues_cleanup(struct drm_i915_private *dev_priv)
745 {
746         destroy_workqueue(dev_priv->hotplug.dp_wq);
747         destroy_workqueue(dev_priv->wq);
748 }
749
750 /*
751  * We don't keep the workarounds for pre-production hardware, so we expect our
752  * driver to fail on these machines in one way or another. A little warning on
753  * dmesg may help both the user and the bug triagers.
754  */
755 static void intel_detect_preproduction_hw(struct drm_i915_private *dev_priv)
756 {
757         if (IS_HSW_EARLY_SDV(dev_priv) ||
758             IS_SKL_REVID(dev_priv, 0, SKL_REVID_F0))
759                 DRM_ERROR("This is a pre-production stepping. "
760                           "It may not be fully functional.\n");
761 }
762
763 /**
764  * i915_driver_init_early - setup state not requiring device access
765  * @dev_priv: device private
766  *
767  * Initialize everything that is a "SW-only" state, that is state not
768  * requiring accessing the device or exposing the driver via kernel internal
769  * or userspace interfaces. Example steps belonging here: lock initialization,
770  * system memory allocation, setting up device specific attributes and
771  * function hooks not requiring accessing the device.
772  */
773 static int i915_driver_init_early(struct drm_i915_private *dev_priv,
774                                   const struct pci_device_id *ent)
775 {
776         const struct intel_device_info *match_info =
777                 (struct intel_device_info *)ent->driver_data;
778         struct intel_device_info *device_info;
779         int ret = 0;
780
781         if (i915_inject_load_failure())
782                 return -ENODEV;
783
784         /* Setup the write-once "constant" device info */
785         device_info = mkwrite_device_info(dev_priv);
786         memcpy(device_info, match_info, sizeof(*device_info));
787         device_info->device_id = dev_priv->drm.pdev->device;
788
789         BUG_ON(device_info->gen > sizeof(device_info->gen_mask) * BITS_PER_BYTE);
790         device_info->gen_mask = BIT(device_info->gen - 1);
791
792         spin_lock_init(&dev_priv->irq_lock);
793         spin_lock_init(&dev_priv->gpu_error.lock);
794         mutex_init(&dev_priv->backlight_lock);
795         spin_lock_init(&dev_priv->uncore.lock);
796         spin_lock_init(&dev_priv->mm.object_stat_lock);
797         spin_lock_init(&dev_priv->mmio_flip_lock);
798         mutex_init(&dev_priv->sb_lock);
799         mutex_init(&dev_priv->modeset_restore_lock);
800         mutex_init(&dev_priv->av_mutex);
801         mutex_init(&dev_priv->wm.wm_mutex);
802         mutex_init(&dev_priv->pps_mutex);
803
804         i915_memcpy_init_early(dev_priv);
805
806         ret = i915_workqueues_init(dev_priv);
807         if (ret < 0)
808                 return ret;
809
810         ret = intel_gvt_init(dev_priv);
811         if (ret < 0)
812                 goto err_workqueues;
813
814         /* This must be called before any calls to HAS_PCH_* */
815         intel_detect_pch(&dev_priv->drm);
816
817         intel_pm_setup(&dev_priv->drm);
818         intel_init_dpio(dev_priv);
819         intel_power_domains_init(dev_priv);
820         intel_irq_init(dev_priv);
821         intel_init_display_hooks(dev_priv);
822         intel_init_clock_gating_hooks(dev_priv);
823         intel_init_audio_hooks(dev_priv);
824         i915_gem_load_init(&dev_priv->drm);
825
826         intel_display_crc_init(dev_priv);
827
828         intel_device_info_dump(dev_priv);
829
830         intel_detect_preproduction_hw(dev_priv);
831
832         return 0;
833
834 err_workqueues:
835         i915_workqueues_cleanup(dev_priv);
836         return ret;
837 }
838
839 /**
840  * i915_driver_cleanup_early - cleanup the setup done in i915_driver_init_early()
841  * @dev_priv: device private
842  */
843 static void i915_driver_cleanup_early(struct drm_i915_private *dev_priv)
844 {
845         i915_gem_load_cleanup(&dev_priv->drm);
846         i915_workqueues_cleanup(dev_priv);
847 }
848
849 static int i915_mmio_setup(struct drm_device *dev)
850 {
851         struct drm_i915_private *dev_priv = to_i915(dev);
852         struct pci_dev *pdev = dev_priv->drm.pdev;
853         int mmio_bar;
854         int mmio_size;
855
856         mmio_bar = IS_GEN2(dev) ? 1 : 0;
857         /*
858          * Before gen4, the registers and the GTT are behind different BARs.
859          * However, from gen4 onwards, the registers and the GTT are shared
860          * in the same BAR, so we want to restrict this ioremap from
861          * clobbering the GTT which we want ioremap_wc instead. Fortunately,
862          * the register BAR remains the same size for all the earlier
863          * generations up to Ironlake.
864          */
865         if (INTEL_INFO(dev)->gen < 5)
866                 mmio_size = 512 * 1024;
867         else
868                 mmio_size = 2 * 1024 * 1024;
869         dev_priv->regs = pci_iomap(pdev, mmio_bar, mmio_size);
870         if (dev_priv->regs == NULL) {
871                 DRM_ERROR("failed to map registers\n");
872
873                 return -EIO;
874         }
875
876         /* Try to make sure MCHBAR is enabled before poking at it */
877         intel_setup_mchbar(dev);
878
879         return 0;
880 }
881
882 static void i915_mmio_cleanup(struct drm_device *dev)
883 {
884         struct drm_i915_private *dev_priv = to_i915(dev);
885         struct pci_dev *pdev = dev_priv->drm.pdev;
886
887         intel_teardown_mchbar(dev);
888         pci_iounmap(pdev, dev_priv->regs);
889 }
890
891 /**
892  * i915_driver_init_mmio - setup device MMIO
893  * @dev_priv: device private
894  *
895  * Setup minimal device state necessary for MMIO accesses later in the
896  * initialization sequence. The setup here should avoid any other device-wide
897  * side effects or exposing the driver via kernel internal or user space
898  * interfaces.
899  */
900 static int i915_driver_init_mmio(struct drm_i915_private *dev_priv)
901 {
902         struct drm_device *dev = &dev_priv->drm;
903         int ret;
904
905         if (i915_inject_load_failure())
906                 return -ENODEV;
907
908         if (i915_get_bridge_dev(dev))
909                 return -EIO;
910
911         ret = i915_mmio_setup(dev);
912         if (ret < 0)
913                 goto put_bridge;
914
915         intel_uncore_init(dev_priv);
916
917         return 0;
918
919 put_bridge:
920         pci_dev_put(dev_priv->bridge_dev);
921
922         return ret;
923 }
924
925 /**
926  * i915_driver_cleanup_mmio - cleanup the setup done in i915_driver_init_mmio()
927  * @dev_priv: device private
928  */
929 static void i915_driver_cleanup_mmio(struct drm_i915_private *dev_priv)
930 {
931         struct drm_device *dev = &dev_priv->drm;
932
933         intel_uncore_fini(dev_priv);
934         i915_mmio_cleanup(dev);
935         pci_dev_put(dev_priv->bridge_dev);
936 }
937
938 static void intel_sanitize_options(struct drm_i915_private *dev_priv)
939 {
940         i915.enable_execlists =
941                 intel_sanitize_enable_execlists(dev_priv,
942                                                 i915.enable_execlists);
943
944         /*
945          * i915.enable_ppgtt is read-only, so do an early pass to validate the
946          * user's requested state against the hardware/driver capabilities.  We
947          * do this now so that we can print out any log messages once rather
948          * than every time we check intel_enable_ppgtt().
949          */
950         i915.enable_ppgtt =
951                 intel_sanitize_enable_ppgtt(dev_priv, i915.enable_ppgtt);
952         DRM_DEBUG_DRIVER("ppgtt mode: %i\n", i915.enable_ppgtt);
953
954         i915.semaphores = intel_sanitize_semaphores(dev_priv, i915.semaphores);
955         DRM_DEBUG_DRIVER("use GPU sempahores? %s\n", yesno(i915.semaphores));
956 }
957
958 /**
959  * i915_driver_init_hw - setup state requiring device access
960  * @dev_priv: device private
961  *
962  * Setup state that requires accessing the device, but doesn't require
963  * exposing the driver via kernel internal or userspace interfaces.
964  */
965 static int i915_driver_init_hw(struct drm_i915_private *dev_priv)
966 {
967         struct pci_dev *pdev = dev_priv->drm.pdev;
968         struct drm_device *dev = &dev_priv->drm;
969         int ret;
970
971         if (i915_inject_load_failure())
972                 return -ENODEV;
973
974         intel_device_info_runtime_init(dev_priv);
975
976         intel_sanitize_options(dev_priv);
977
978         ret = i915_ggtt_probe_hw(dev_priv);
979         if (ret)
980                 return ret;
981
982         /* WARNING: Apparently we must kick fbdev drivers before vgacon,
983          * otherwise the vga fbdev driver falls over. */
984         ret = i915_kick_out_firmware_fb(dev_priv);
985         if (ret) {
986                 DRM_ERROR("failed to remove conflicting framebuffer drivers\n");
987                 goto out_ggtt;
988         }
989
990         ret = i915_kick_out_vgacon(dev_priv);
991         if (ret) {
992                 DRM_ERROR("failed to remove conflicting VGA console\n");
993                 goto out_ggtt;
994         }
995
996         ret = i915_ggtt_init_hw(dev_priv);
997         if (ret)
998                 return ret;
999
1000         ret = i915_ggtt_enable_hw(dev_priv);
1001         if (ret) {
1002                 DRM_ERROR("failed to enable GGTT\n");
1003                 goto out_ggtt;
1004         }
1005
1006         pci_set_master(pdev);
1007
1008         /* overlay on gen2 is broken and can't address above 1G */
1009         if (IS_GEN2(dev)) {
1010                 ret = dma_set_coherent_mask(&pdev->dev, DMA_BIT_MASK(30));
1011                 if (ret) {
1012                         DRM_ERROR("failed to set DMA mask\n");
1013
1014                         goto out_ggtt;
1015                 }
1016         }
1017
1018         /* 965GM sometimes incorrectly writes to hardware status page (HWS)
1019          * using 32bit addressing, overwriting memory if HWS is located
1020          * above 4GB.
1021          *
1022          * The documentation also mentions an issue with undefined
1023          * behaviour if any general state is accessed within a page above 4GB,
1024          * which also needs to be handled carefully.
1025          */
1026         if (IS_BROADWATER(dev) || IS_CRESTLINE(dev)) {
1027                 ret = dma_set_coherent_mask(&pdev->dev, DMA_BIT_MASK(32));
1028
1029                 if (ret) {
1030                         DRM_ERROR("failed to set DMA mask\n");
1031
1032                         goto out_ggtt;
1033                 }
1034         }
1035
1036         pm_qos_add_request(&dev_priv->pm_qos, PM_QOS_CPU_DMA_LATENCY,
1037                            PM_QOS_DEFAULT_VALUE);
1038
1039         intel_uncore_sanitize(dev_priv);
1040
1041         intel_opregion_setup(dev_priv);
1042
1043         i915_gem_load_init_fences(dev_priv);
1044
1045         /* On the 945G/GM, the chipset reports the MSI capability on the
1046          * integrated graphics even though the support isn't actually there
1047          * according to the published specs.  It doesn't appear to function
1048          * correctly in testing on 945G.
1049          * This may be a side effect of MSI having been made available for PEG
1050          * and the registers being closely associated.
1051          *
1052          * According to chipset errata, on the 965GM, MSI interrupts may
1053          * be lost or delayed, but we use them anyways to avoid
1054          * stuck interrupts on some machines.
1055          */
1056         if (!IS_I945G(dev) && !IS_I945GM(dev)) {
1057                 if (pci_enable_msi(pdev) < 0)
1058                         DRM_DEBUG_DRIVER("can't enable MSI");
1059         }
1060
1061         return 0;
1062
1063 out_ggtt:
1064         i915_ggtt_cleanup_hw(dev_priv);
1065
1066         return ret;
1067 }
1068
1069 /**
1070  * i915_driver_cleanup_hw - cleanup the setup done in i915_driver_init_hw()
1071  * @dev_priv: device private
1072  */
1073 static void i915_driver_cleanup_hw(struct drm_i915_private *dev_priv)
1074 {
1075         struct pci_dev *pdev = dev_priv->drm.pdev;
1076
1077         if (pdev->msi_enabled)
1078                 pci_disable_msi(pdev);
1079
1080         pm_qos_remove_request(&dev_priv->pm_qos);
1081         i915_ggtt_cleanup_hw(dev_priv);
1082 }
1083
1084 /**
1085  * i915_driver_register - register the driver with the rest of the system
1086  * @dev_priv: device private
1087  *
1088  * Perform any steps necessary to make the driver available via kernel
1089  * internal or userspace interfaces.
1090  */
1091 static void i915_driver_register(struct drm_i915_private *dev_priv)
1092 {
1093         struct drm_device *dev = &dev_priv->drm;
1094
1095         i915_gem_shrinker_init(dev_priv);
1096
1097         /*
1098          * Notify a valid surface after modesetting,
1099          * when running inside a VM.
1100          */
1101         if (intel_vgpu_active(dev_priv))
1102                 I915_WRITE(vgtif_reg(display_ready), VGT_DRV_DISPLAY_READY);
1103
1104         /* Reveal our presence to userspace */
1105         if (drm_dev_register(dev, 0) == 0) {
1106                 i915_debugfs_register(dev_priv);
1107                 i915_setup_sysfs(dev_priv);
1108         } else
1109                 DRM_ERROR("Failed to register driver for userspace access!\n");
1110
1111         if (INTEL_INFO(dev_priv)->num_pipes) {
1112                 /* Must be done after probing outputs */
1113                 intel_opregion_register(dev_priv);
1114                 acpi_video_register();
1115         }
1116
1117         if (IS_GEN5(dev_priv))
1118                 intel_gpu_ips_init(dev_priv);
1119
1120         i915_audio_component_init(dev_priv);
1121
1122         /*
1123          * Some ports require correctly set-up hpd registers for detection to
1124          * work properly (leading to ghost connected connector status), e.g. VGA
1125          * on gm45.  Hence we can only set up the initial fbdev config after hpd
1126          * irqs are fully enabled. We do it last so that the async config
1127          * cannot run before the connectors are registered.
1128          */
1129         intel_fbdev_initial_config_async(dev);
1130 }
1131
1132 /**
1133  * i915_driver_unregister - cleanup the registration done in i915_driver_regiser()
1134  * @dev_priv: device private
1135  */
1136 static void i915_driver_unregister(struct drm_i915_private *dev_priv)
1137 {
1138         i915_audio_component_cleanup(dev_priv);
1139
1140         intel_gpu_ips_teardown();
1141         acpi_video_unregister();
1142         intel_opregion_unregister(dev_priv);
1143
1144         i915_teardown_sysfs(dev_priv);
1145         i915_debugfs_unregister(dev_priv);
1146         drm_dev_unregister(&dev_priv->drm);
1147
1148         i915_gem_shrinker_cleanup(dev_priv);
1149 }
1150
1151 /**
1152  * i915_driver_load - setup chip and create an initial config
1153  * @dev: DRM device
1154  * @flags: startup flags
1155  *
1156  * The driver load routine has to do several things:
1157  *   - drive output discovery via intel_modeset_init()
1158  *   - initialize the memory manager
1159  *   - allocate initial config memory
1160  *   - setup the DRM framebuffer with the allocated memory
1161  */
1162 int i915_driver_load(struct pci_dev *pdev, const struct pci_device_id *ent)
1163 {
1164         struct drm_i915_private *dev_priv;
1165         int ret;
1166
1167         if (i915.nuclear_pageflip)
1168                 driver.driver_features |= DRIVER_ATOMIC;
1169
1170         ret = -ENOMEM;
1171         dev_priv = kzalloc(sizeof(*dev_priv), GFP_KERNEL);
1172         if (dev_priv)
1173                 ret = drm_dev_init(&dev_priv->drm, &driver, &pdev->dev);
1174         if (ret) {
1175                 dev_printk(KERN_ERR, &pdev->dev,
1176                            "[" DRM_NAME ":%s] allocation failed\n", __func__);
1177                 kfree(dev_priv);
1178                 return ret;
1179         }
1180
1181         dev_priv->drm.pdev = pdev;
1182         dev_priv->drm.dev_private = dev_priv;
1183
1184         ret = pci_enable_device(pdev);
1185         if (ret)
1186                 goto out_free_priv;
1187
1188         pci_set_drvdata(pdev, &dev_priv->drm);
1189
1190         ret = i915_driver_init_early(dev_priv, ent);
1191         if (ret < 0)
1192                 goto out_pci_disable;
1193
1194         intel_runtime_pm_get(dev_priv);
1195
1196         ret = i915_driver_init_mmio(dev_priv);
1197         if (ret < 0)
1198                 goto out_runtime_pm_put;
1199
1200         ret = i915_driver_init_hw(dev_priv);
1201         if (ret < 0)
1202                 goto out_cleanup_mmio;
1203
1204         /*
1205          * TODO: move the vblank init and parts of modeset init steps into one
1206          * of the i915_driver_init_/i915_driver_register functions according
1207          * to the role/effect of the given init step.
1208          */
1209         if (INTEL_INFO(dev_priv)->num_pipes) {
1210                 ret = drm_vblank_init(&dev_priv->drm,
1211                                       INTEL_INFO(dev_priv)->num_pipes);
1212                 if (ret)
1213                         goto out_cleanup_hw;
1214         }
1215
1216         ret = i915_load_modeset_init(&dev_priv->drm);
1217         if (ret < 0)
1218                 goto out_cleanup_vblank;
1219
1220         i915_driver_register(dev_priv);
1221
1222         intel_runtime_pm_enable(dev_priv);
1223
1224         /* Everything is in place, we can now relax! */
1225         DRM_INFO("Initialized %s %d.%d.%d %s for %s on minor %d\n",
1226                  driver.name, driver.major, driver.minor, driver.patchlevel,
1227                  driver.date, pci_name(pdev), dev_priv->drm.primary->index);
1228
1229         intel_runtime_pm_put(dev_priv);
1230
1231         return 0;
1232
1233 out_cleanup_vblank:
1234         drm_vblank_cleanup(&dev_priv->drm);
1235 out_cleanup_hw:
1236         i915_driver_cleanup_hw(dev_priv);
1237 out_cleanup_mmio:
1238         i915_driver_cleanup_mmio(dev_priv);
1239 out_runtime_pm_put:
1240         intel_runtime_pm_put(dev_priv);
1241         i915_driver_cleanup_early(dev_priv);
1242 out_pci_disable:
1243         pci_disable_device(pdev);
1244 out_free_priv:
1245         i915_load_error(dev_priv, "Device initialization failed (%d)\n", ret);
1246         drm_dev_unref(&dev_priv->drm);
1247         return ret;
1248 }
1249
1250 void i915_driver_unload(struct drm_device *dev)
1251 {
1252         struct drm_i915_private *dev_priv = to_i915(dev);
1253         struct pci_dev *pdev = dev_priv->drm.pdev;
1254
1255         intel_fbdev_fini(dev);
1256
1257         if (i915_gem_suspend(dev))
1258                 DRM_ERROR("failed to idle hardware; continuing to unload!\n");
1259
1260         intel_display_power_get(dev_priv, POWER_DOMAIN_INIT);
1261
1262         i915_driver_unregister(dev_priv);
1263
1264         drm_vblank_cleanup(dev);
1265
1266         intel_modeset_cleanup(dev);
1267
1268         /*
1269          * free the memory space allocated for the child device
1270          * config parsed from VBT
1271          */
1272         if (dev_priv->vbt.child_dev && dev_priv->vbt.child_dev_num) {
1273                 kfree(dev_priv->vbt.child_dev);
1274                 dev_priv->vbt.child_dev = NULL;
1275                 dev_priv->vbt.child_dev_num = 0;
1276         }
1277         kfree(dev_priv->vbt.sdvo_lvds_vbt_mode);
1278         dev_priv->vbt.sdvo_lvds_vbt_mode = NULL;
1279         kfree(dev_priv->vbt.lfp_lvds_vbt_mode);
1280         dev_priv->vbt.lfp_lvds_vbt_mode = NULL;
1281
1282         vga_switcheroo_unregister_client(pdev);
1283         vga_client_register(pdev, NULL, NULL, NULL);
1284
1285         intel_csr_ucode_fini(dev_priv);
1286
1287         /* Free error state after interrupts are fully disabled. */
1288         cancel_delayed_work_sync(&dev_priv->gpu_error.hangcheck_work);
1289         i915_destroy_error_state(dev);
1290
1291         /* Flush any outstanding unpin_work. */
1292         drain_workqueue(dev_priv->wq);
1293
1294         intel_guc_fini(dev);
1295         i915_gem_fini(dev);
1296         intel_fbc_cleanup_cfb(dev_priv);
1297
1298         intel_power_domains_fini(dev_priv);
1299
1300         i915_driver_cleanup_hw(dev_priv);
1301         i915_driver_cleanup_mmio(dev_priv);
1302
1303         intel_display_power_put(dev_priv, POWER_DOMAIN_INIT);
1304
1305         i915_driver_cleanup_early(dev_priv);
1306 }
1307
1308 static int i915_driver_open(struct drm_device *dev, struct drm_file *file)
1309 {
1310         int ret;
1311
1312         ret = i915_gem_open(dev, file);
1313         if (ret)
1314                 return ret;
1315
1316         return 0;
1317 }
1318
1319 /**
1320  * i915_driver_lastclose - clean up after all DRM clients have exited
1321  * @dev: DRM device
1322  *
1323  * Take care of cleaning up after all DRM clients have exited.  In the
1324  * mode setting case, we want to restore the kernel's initial mode (just
1325  * in case the last client left us in a bad state).
1326  *
1327  * Additionally, in the non-mode setting case, we'll tear down the GTT
1328  * and DMA structures, since the kernel won't be using them, and clea
1329  * up any GEM state.
1330  */
1331 static void i915_driver_lastclose(struct drm_device *dev)
1332 {
1333         intel_fbdev_restore_mode(dev);
1334         vga_switcheroo_process_delayed_switch();
1335 }
1336
1337 static void i915_driver_preclose(struct drm_device *dev, struct drm_file *file)
1338 {
1339         mutex_lock(&dev->struct_mutex);
1340         i915_gem_context_close(dev, file);
1341         i915_gem_release(dev, file);
1342         mutex_unlock(&dev->struct_mutex);
1343 }
1344
1345 static void i915_driver_postclose(struct drm_device *dev, struct drm_file *file)
1346 {
1347         struct drm_i915_file_private *file_priv = file->driver_priv;
1348
1349         kfree(file_priv);
1350 }
1351
1352 static void intel_suspend_encoders(struct drm_i915_private *dev_priv)
1353 {
1354         struct drm_device *dev = &dev_priv->drm;
1355         struct intel_encoder *encoder;
1356
1357         drm_modeset_lock_all(dev);
1358         for_each_intel_encoder(dev, encoder)
1359                 if (encoder->suspend)
1360                         encoder->suspend(encoder);
1361         drm_modeset_unlock_all(dev);
1362 }
1363
1364 static int vlv_resume_prepare(struct drm_i915_private *dev_priv,
1365                               bool rpm_resume);
1366 static int vlv_suspend_complete(struct drm_i915_private *dev_priv);
1367
1368 static bool suspend_to_idle(struct drm_i915_private *dev_priv)
1369 {
1370 #if IS_ENABLED(CONFIG_ACPI_SLEEP)
1371         if (acpi_target_system_state() < ACPI_STATE_S3)
1372                 return true;
1373 #endif
1374         return false;
1375 }
1376
1377 static int i915_drm_suspend(struct drm_device *dev)
1378 {
1379         struct drm_i915_private *dev_priv = to_i915(dev);
1380         struct pci_dev *pdev = dev_priv->drm.pdev;
1381         pci_power_t opregion_target_state;
1382         int error;
1383
1384         /* ignore lid events during suspend */
1385         mutex_lock(&dev_priv->modeset_restore_lock);
1386         dev_priv->modeset_restore = MODESET_SUSPENDED;
1387         mutex_unlock(&dev_priv->modeset_restore_lock);
1388
1389         disable_rpm_wakeref_asserts(dev_priv);
1390
1391         /* We do a lot of poking in a lot of registers, make sure they work
1392          * properly. */
1393         intel_display_set_init_power(dev_priv, true);
1394
1395         drm_kms_helper_poll_disable(dev);
1396
1397         pci_save_state(pdev);
1398
1399         error = i915_gem_suspend(dev);
1400         if (error) {
1401                 dev_err(&pdev->dev,
1402                         "GEM idle failed, resume might fail\n");
1403                 goto out;
1404         }
1405
1406         intel_guc_suspend(dev);
1407
1408         intel_display_suspend(dev);
1409
1410         intel_dp_mst_suspend(dev);
1411
1412         intel_runtime_pm_disable_interrupts(dev_priv);
1413         intel_hpd_cancel_work(dev_priv);
1414
1415         intel_suspend_encoders(dev_priv);
1416
1417         intel_suspend_hw(dev);
1418
1419         i915_gem_suspend_gtt_mappings(dev);
1420
1421         i915_save_state(dev);
1422
1423         opregion_target_state = suspend_to_idle(dev_priv) ? PCI_D1 : PCI_D3cold;
1424         intel_opregion_notify_adapter(dev_priv, opregion_target_state);
1425
1426         intel_uncore_forcewake_reset(dev_priv, false);
1427         intel_opregion_unregister(dev_priv);
1428
1429         intel_fbdev_set_suspend(dev, FBINFO_STATE_SUSPENDED, true);
1430
1431         dev_priv->suspend_count++;
1432
1433         intel_display_set_init_power(dev_priv, false);
1434
1435         intel_csr_ucode_suspend(dev_priv);
1436
1437 out:
1438         enable_rpm_wakeref_asserts(dev_priv);
1439
1440         return error;
1441 }
1442
1443 static int i915_drm_suspend_late(struct drm_device *dev, bool hibernation)
1444 {
1445         struct drm_i915_private *dev_priv = to_i915(dev);
1446         struct pci_dev *pdev = dev_priv->drm.pdev;
1447         bool fw_csr;
1448         int ret;
1449
1450         disable_rpm_wakeref_asserts(dev_priv);
1451
1452         fw_csr = !IS_BROXTON(dev_priv) &&
1453                 suspend_to_idle(dev_priv) && dev_priv->csr.dmc_payload;
1454         /*
1455          * In case of firmware assisted context save/restore don't manually
1456          * deinit the power domains. This also means the CSR/DMC firmware will
1457          * stay active, it will power down any HW resources as required and
1458          * also enable deeper system power states that would be blocked if the
1459          * firmware was inactive.
1460          */
1461         if (!fw_csr)
1462                 intel_power_domains_suspend(dev_priv);
1463
1464         ret = 0;
1465         if (IS_BROXTON(dev_priv))
1466                 bxt_enable_dc9(dev_priv);
1467         else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
1468                 hsw_enable_pc8(dev_priv);
1469         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
1470                 ret = vlv_suspend_complete(dev_priv);
1471
1472         if (ret) {
1473                 DRM_ERROR("Suspend complete failed: %d\n", ret);
1474                 if (!fw_csr)
1475                         intel_power_domains_init_hw(dev_priv, true);
1476
1477                 goto out;
1478         }
1479
1480         pci_disable_device(pdev);
1481         /*
1482          * During hibernation on some platforms the BIOS may try to access
1483          * the device even though it's already in D3 and hang the machine. So
1484          * leave the device in D0 on those platforms and hope the BIOS will
1485          * power down the device properly. The issue was seen on multiple old
1486          * GENs with different BIOS vendors, so having an explicit blacklist
1487          * is inpractical; apply the workaround on everything pre GEN6. The
1488          * platforms where the issue was seen:
1489          * Lenovo Thinkpad X301, X61s, X60, T60, X41
1490          * Fujitsu FSC S7110
1491          * Acer Aspire 1830T
1492          */
1493         if (!(hibernation && INTEL_INFO(dev_priv)->gen < 6))
1494                 pci_set_power_state(pdev, PCI_D3hot);
1495
1496         dev_priv->suspended_to_idle = suspend_to_idle(dev_priv);
1497
1498 out:
1499         enable_rpm_wakeref_asserts(dev_priv);
1500
1501         return ret;
1502 }
1503
1504 int i915_suspend_switcheroo(struct drm_device *dev, pm_message_t state)
1505 {
1506         int error;
1507
1508         if (!dev) {
1509                 DRM_ERROR("dev: %p\n", dev);
1510                 DRM_ERROR("DRM not initialized, aborting suspend.\n");
1511                 return -ENODEV;
1512         }
1513
1514         if (WARN_ON_ONCE(state.event != PM_EVENT_SUSPEND &&
1515                          state.event != PM_EVENT_FREEZE))
1516                 return -EINVAL;
1517
1518         if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
1519                 return 0;
1520
1521         error = i915_drm_suspend(dev);
1522         if (error)
1523                 return error;
1524
1525         return i915_drm_suspend_late(dev, false);
1526 }
1527
1528 static int i915_drm_resume(struct drm_device *dev)
1529 {
1530         struct drm_i915_private *dev_priv = to_i915(dev);
1531         int ret;
1532
1533         disable_rpm_wakeref_asserts(dev_priv);
1534         intel_sanitize_gt_powersave(dev_priv);
1535
1536         ret = i915_ggtt_enable_hw(dev_priv);
1537         if (ret)
1538                 DRM_ERROR("failed to re-enable GGTT\n");
1539
1540         intel_csr_ucode_resume(dev_priv);
1541
1542         i915_gem_resume(dev);
1543
1544         i915_restore_state(dev);
1545         intel_pps_unlock_regs_wa(dev_priv);
1546         intel_opregion_setup(dev_priv);
1547
1548         intel_init_pch_refclk(dev);
1549         drm_mode_config_reset(dev);
1550
1551         /*
1552          * Interrupts have to be enabled before any batches are run. If not the
1553          * GPU will hang. i915_gem_init_hw() will initiate batches to
1554          * update/restore the context.
1555          *
1556          * Modeset enabling in intel_modeset_init_hw() also needs working
1557          * interrupts.
1558          */
1559         intel_runtime_pm_enable_interrupts(dev_priv);
1560
1561         mutex_lock(&dev->struct_mutex);
1562         if (i915_gem_init_hw(dev)) {
1563                 DRM_ERROR("failed to re-initialize GPU, declaring wedged!\n");
1564                 i915_gem_set_wedged(dev_priv);
1565         }
1566         mutex_unlock(&dev->struct_mutex);
1567
1568         intel_guc_resume(dev);
1569
1570         intel_modeset_init_hw(dev);
1571
1572         spin_lock_irq(&dev_priv->irq_lock);
1573         if (dev_priv->display.hpd_irq_setup)
1574                 dev_priv->display.hpd_irq_setup(dev_priv);
1575         spin_unlock_irq(&dev_priv->irq_lock);
1576
1577         intel_dp_mst_resume(dev);
1578
1579         intel_display_resume(dev);
1580
1581         /*
1582          * ... but also need to make sure that hotplug processing
1583          * doesn't cause havoc. Like in the driver load code we don't
1584          * bother with the tiny race here where we might loose hotplug
1585          * notifications.
1586          * */
1587         intel_hpd_init(dev_priv);
1588         /* Config may have changed between suspend and resume */
1589         drm_helper_hpd_irq_event(dev);
1590
1591         intel_opregion_register(dev_priv);
1592
1593         intel_fbdev_set_suspend(dev, FBINFO_STATE_RUNNING, false);
1594
1595         mutex_lock(&dev_priv->modeset_restore_lock);
1596         dev_priv->modeset_restore = MODESET_DONE;
1597         mutex_unlock(&dev_priv->modeset_restore_lock);
1598
1599         intel_opregion_notify_adapter(dev_priv, PCI_D0);
1600
1601         intel_autoenable_gt_powersave(dev_priv);
1602         drm_kms_helper_poll_enable(dev);
1603
1604         enable_rpm_wakeref_asserts(dev_priv);
1605
1606         return 0;
1607 }
1608
1609 static int i915_drm_resume_early(struct drm_device *dev)
1610 {
1611         struct drm_i915_private *dev_priv = to_i915(dev);
1612         struct pci_dev *pdev = dev_priv->drm.pdev;
1613         int ret;
1614
1615         /*
1616          * We have a resume ordering issue with the snd-hda driver also
1617          * requiring our device to be power up. Due to the lack of a
1618          * parent/child relationship we currently solve this with an early
1619          * resume hook.
1620          *
1621          * FIXME: This should be solved with a special hdmi sink device or
1622          * similar so that power domains can be employed.
1623          */
1624
1625         /*
1626          * Note that we need to set the power state explicitly, since we
1627          * powered off the device during freeze and the PCI core won't power
1628          * it back up for us during thaw. Powering off the device during
1629          * freeze is not a hard requirement though, and during the
1630          * suspend/resume phases the PCI core makes sure we get here with the
1631          * device powered on. So in case we change our freeze logic and keep
1632          * the device powered we can also remove the following set power state
1633          * call.
1634          */
1635         ret = pci_set_power_state(pdev, PCI_D0);
1636         if (ret) {
1637                 DRM_ERROR("failed to set PCI D0 power state (%d)\n", ret);
1638                 goto out;
1639         }
1640
1641         /*
1642          * Note that pci_enable_device() first enables any parent bridge
1643          * device and only then sets the power state for this device. The
1644          * bridge enabling is a nop though, since bridge devices are resumed
1645          * first. The order of enabling power and enabling the device is
1646          * imposed by the PCI core as described above, so here we preserve the
1647          * same order for the freeze/thaw phases.
1648          *
1649          * TODO: eventually we should remove pci_disable_device() /
1650          * pci_enable_enable_device() from suspend/resume. Due to how they
1651          * depend on the device enable refcount we can't anyway depend on them
1652          * disabling/enabling the device.
1653          */
1654         if (pci_enable_device(pdev)) {
1655                 ret = -EIO;
1656                 goto out;
1657         }
1658
1659         pci_set_master(pdev);
1660
1661         disable_rpm_wakeref_asserts(dev_priv);
1662
1663         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
1664                 ret = vlv_resume_prepare(dev_priv, false);
1665         if (ret)
1666                 DRM_ERROR("Resume prepare failed: %d, continuing anyway\n",
1667                           ret);
1668
1669         intel_uncore_early_sanitize(dev_priv, true);
1670
1671         if (IS_BROXTON(dev_priv)) {
1672                 if (!dev_priv->suspended_to_idle)
1673                         gen9_sanitize_dc_state(dev_priv);
1674                 bxt_disable_dc9(dev_priv);
1675         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
1676                 hsw_disable_pc8(dev_priv);
1677         }
1678
1679         intel_uncore_sanitize(dev_priv);
1680
1681         if (IS_BROXTON(dev_priv) ||
1682             !(dev_priv->suspended_to_idle && dev_priv->csr.dmc_payload))
1683                 intel_power_domains_init_hw(dev_priv, true);
1684
1685         enable_rpm_wakeref_asserts(dev_priv);
1686
1687 out:
1688         dev_priv->suspended_to_idle = false;
1689
1690         return ret;
1691 }
1692
1693 int i915_resume_switcheroo(struct drm_device *dev)
1694 {
1695         int ret;
1696
1697         if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
1698                 return 0;
1699
1700         ret = i915_drm_resume_early(dev);
1701         if (ret)
1702                 return ret;
1703
1704         return i915_drm_resume(dev);
1705 }
1706
1707 static void disable_engines_irq(struct drm_i915_private *dev_priv)
1708 {
1709         struct intel_engine_cs *engine;
1710
1711         /* Ensure irq handler finishes, and not run again. */
1712         disable_irq(dev_priv->drm.irq);
1713         for_each_engine(engine, dev_priv)
1714                 tasklet_kill(&engine->irq_tasklet);
1715 }
1716
1717 static void enable_engines_irq(struct drm_i915_private *dev_priv)
1718 {
1719         enable_irq(dev_priv->drm.irq);
1720 }
1721
1722 /**
1723  * i915_reset - reset chip after a hang
1724  * @dev: drm device to reset
1725  *
1726  * Reset the chip.  Useful if a hang is detected. Marks the device as wedged
1727  * on failure.
1728  *
1729  * Caller must hold the struct_mutex.
1730  *
1731  * Procedure is fairly simple:
1732  *   - reset the chip using the reset reg
1733  *   - re-init context state
1734  *   - re-init hardware status page
1735  *   - re-init ring buffer
1736  *   - re-init interrupt state
1737  *   - re-init display
1738  */
1739 void i915_reset(struct drm_i915_private *dev_priv)
1740 {
1741         struct drm_device *dev = &dev_priv->drm;
1742         struct i915_gpu_error *error = &dev_priv->gpu_error;
1743         int ret;
1744
1745         lockdep_assert_held(&dev->struct_mutex);
1746
1747         if (!test_and_clear_bit(I915_RESET_IN_PROGRESS, &error->flags))
1748                 return;
1749
1750         /* Clear any previous failed attempts at recovery. Time to try again. */
1751         __clear_bit(I915_WEDGED, &error->flags);
1752         error->reset_count++;
1753
1754         pr_notice("drm/i915: Resetting chip after gpu hang\n");
1755
1756         disable_engines_irq(dev_priv);
1757         ret = intel_gpu_reset(dev_priv, ALL_ENGINES);
1758         enable_engines_irq(dev_priv);
1759
1760         if (ret) {
1761                 if (ret != -ENODEV)
1762                         DRM_ERROR("Failed to reset chip: %i\n", ret);
1763                 else
1764                         DRM_DEBUG_DRIVER("GPU reset disabled\n");
1765                 goto error;
1766         }
1767
1768         i915_gem_reset(dev_priv);
1769         intel_overlay_reset(dev_priv);
1770
1771         /* Ok, now get things going again... */
1772
1773         /*
1774          * Everything depends on having the GTT running, so we need to start
1775          * there.  Fortunately we don't need to do this unless we reset the
1776          * chip at a PCI level.
1777          *
1778          * Next we need to restore the context, but we don't use those
1779          * yet either...
1780          *
1781          * Ring buffer needs to be re-initialized in the KMS case, or if X
1782          * was running at the time of the reset (i.e. we weren't VT
1783          * switched away).
1784          */
1785         ret = i915_gem_init_hw(dev);
1786         if (ret) {
1787                 DRM_ERROR("Failed hw init on reset %d\n", ret);
1788                 goto error;
1789         }
1790
1791 wakeup:
1792         wake_up_bit(&error->flags, I915_RESET_IN_PROGRESS);
1793         return;
1794
1795 error:
1796         i915_gem_set_wedged(dev_priv);
1797         goto wakeup;
1798 }
1799
1800 static int i915_pm_suspend(struct device *kdev)
1801 {
1802         struct pci_dev *pdev = to_pci_dev(kdev);
1803         struct drm_device *dev = pci_get_drvdata(pdev);
1804
1805         if (!dev) {
1806                 dev_err(kdev, "DRM not initialized, aborting suspend.\n");
1807                 return -ENODEV;
1808         }
1809
1810         if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
1811                 return 0;
1812
1813         return i915_drm_suspend(dev);
1814 }
1815
1816 static int i915_pm_suspend_late(struct device *kdev)
1817 {
1818         struct drm_device *dev = &kdev_to_i915(kdev)->drm;
1819
1820         /*
1821          * We have a suspend ordering issue with the snd-hda driver also
1822          * requiring our device to be power up. Due to the lack of a
1823          * parent/child relationship we currently solve this with an late
1824          * suspend hook.
1825          *
1826          * FIXME: This should be solved with a special hdmi sink device or
1827          * similar so that power domains can be employed.
1828          */
1829         if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
1830                 return 0;
1831
1832         return i915_drm_suspend_late(dev, false);
1833 }
1834
1835 static int i915_pm_poweroff_late(struct device *kdev)
1836 {
1837         struct drm_device *dev = &kdev_to_i915(kdev)->drm;
1838
1839         if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
1840                 return 0;
1841
1842         return i915_drm_suspend_late(dev, true);
1843 }
1844
1845 static int i915_pm_resume_early(struct device *kdev)
1846 {
1847         struct drm_device *dev = &kdev_to_i915(kdev)->drm;
1848
1849         if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
1850                 return 0;
1851
1852         return i915_drm_resume_early(dev);
1853 }
1854
1855 static int i915_pm_resume(struct device *kdev)
1856 {
1857         struct drm_device *dev = &kdev_to_i915(kdev)->drm;
1858
1859         if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
1860                 return 0;
1861
1862         return i915_drm_resume(dev);
1863 }
1864
1865 /* freeze: before creating the hibernation_image */
1866 static int i915_pm_freeze(struct device *kdev)
1867 {
1868         int ret;
1869
1870         ret = i915_pm_suspend(kdev);
1871         if (ret)
1872                 return ret;
1873
1874         ret = i915_gem_freeze(kdev_to_i915(kdev));
1875         if (ret)
1876                 return ret;
1877
1878         return 0;
1879 }
1880
1881 static int i915_pm_freeze_late(struct device *kdev)
1882 {
1883         int ret;
1884
1885         ret = i915_pm_suspend_late(kdev);
1886         if (ret)
1887                 return ret;
1888
1889         ret = i915_gem_freeze_late(kdev_to_i915(kdev));
1890         if (ret)
1891                 return ret;
1892
1893         return 0;
1894 }
1895
1896 /* thaw: called after creating the hibernation image, but before turning off. */
1897 static int i915_pm_thaw_early(struct device *kdev)
1898 {
1899         return i915_pm_resume_early(kdev);
1900 }
1901
1902 static int i915_pm_thaw(struct device *kdev)
1903 {
1904         return i915_pm_resume(kdev);
1905 }
1906
1907 /* restore: called after loading the hibernation image. */
1908 static int i915_pm_restore_early(struct device *kdev)
1909 {
1910         return i915_pm_resume_early(kdev);
1911 }
1912
1913 static int i915_pm_restore(struct device *kdev)
1914 {
1915         return i915_pm_resume(kdev);
1916 }
1917
1918 /*
1919  * Save all Gunit registers that may be lost after a D3 and a subsequent
1920  * S0i[R123] transition. The list of registers needing a save/restore is
1921  * defined in the VLV2_S0IXRegs document. This documents marks all Gunit
1922  * registers in the following way:
1923  * - Driver: saved/restored by the driver
1924  * - Punit : saved/restored by the Punit firmware
1925  * - No, w/o marking: no need to save/restore, since the register is R/O or
1926  *                    used internally by the HW in a way that doesn't depend
1927  *                    keeping the content across a suspend/resume.
1928  * - Debug : used for debugging
1929  *
1930  * We save/restore all registers marked with 'Driver', with the following
1931  * exceptions:
1932  * - Registers out of use, including also registers marked with 'Debug'.
1933  *   These have no effect on the driver's operation, so we don't save/restore
1934  *   them to reduce the overhead.
1935  * - Registers that are fully setup by an initialization function called from
1936  *   the resume path. For example many clock gating and RPS/RC6 registers.
1937  * - Registers that provide the right functionality with their reset defaults.
1938  *
1939  * TODO: Except for registers that based on the above 3 criteria can be safely
1940  * ignored, we save/restore all others, practically treating the HW context as
1941  * a black-box for the driver. Further investigation is needed to reduce the
1942  * saved/restored registers even further, by following the same 3 criteria.
1943  */
1944 static void vlv_save_gunit_s0ix_state(struct drm_i915_private *dev_priv)
1945 {
1946         struct vlv_s0ix_state *s = &dev_priv->vlv_s0ix_state;
1947         int i;
1948
1949         /* GAM 0x4000-0x4770 */
1950         s->wr_watermark         = I915_READ(GEN7_WR_WATERMARK);
1951         s->gfx_prio_ctrl        = I915_READ(GEN7_GFX_PRIO_CTRL);
1952         s->arb_mode             = I915_READ(ARB_MODE);
1953         s->gfx_pend_tlb0        = I915_READ(GEN7_GFX_PEND_TLB0);
1954         s->gfx_pend_tlb1        = I915_READ(GEN7_GFX_PEND_TLB1);
1955
1956         for (i = 0; i < ARRAY_SIZE(s->lra_limits); i++)
1957                 s->lra_limits[i] = I915_READ(GEN7_LRA_LIMITS(i));
1958
1959         s->media_max_req_count  = I915_READ(GEN7_MEDIA_MAX_REQ_COUNT);
1960         s->gfx_max_req_count    = I915_READ(GEN7_GFX_MAX_REQ_COUNT);
1961
1962         s->render_hwsp          = I915_READ(RENDER_HWS_PGA_GEN7);
1963         s->ecochk               = I915_READ(GAM_ECOCHK);
1964         s->bsd_hwsp             = I915_READ(BSD_HWS_PGA_GEN7);
1965         s->blt_hwsp             = I915_READ(BLT_HWS_PGA_GEN7);
1966
1967         s->tlb_rd_addr          = I915_READ(GEN7_TLB_RD_ADDR);
1968
1969         /* MBC 0x9024-0x91D0, 0x8500 */
1970         s->g3dctl               = I915_READ(VLV_G3DCTL);
1971         s->gsckgctl             = I915_READ(VLV_GSCKGCTL);
1972         s->mbctl                = I915_READ(GEN6_MBCTL);
1973
1974         /* GCP 0x9400-0x9424, 0x8100-0x810C */
1975         s->ucgctl1              = I915_READ(GEN6_UCGCTL1);
1976         s->ucgctl3              = I915_READ(GEN6_UCGCTL3);
1977         s->rcgctl1              = I915_READ(GEN6_RCGCTL1);
1978         s->rcgctl2              = I915_READ(GEN6_RCGCTL2);
1979         s->rstctl               = I915_READ(GEN6_RSTCTL);
1980         s->misccpctl            = I915_READ(GEN7_MISCCPCTL);
1981
1982         /* GPM 0xA000-0xAA84, 0x8000-0x80FC */
1983         s->gfxpause             = I915_READ(GEN6_GFXPAUSE);
1984         s->rpdeuhwtc            = I915_READ(GEN6_RPDEUHWTC);
1985         s->rpdeuc               = I915_READ(GEN6_RPDEUC);
1986         s->ecobus               = I915_READ(ECOBUS);
1987         s->pwrdwnupctl          = I915_READ(VLV_PWRDWNUPCTL);
1988         s->rp_down_timeout      = I915_READ(GEN6_RP_DOWN_TIMEOUT);
1989         s->rp_deucsw            = I915_READ(GEN6_RPDEUCSW);
1990         s->rcubmabdtmr          = I915_READ(GEN6_RCUBMABDTMR);
1991         s->rcedata              = I915_READ(VLV_RCEDATA);
1992         s->spare2gh             = I915_READ(VLV_SPAREG2H);
1993
1994         /* Display CZ domain, 0x4400C-0x4402C, 0x4F000-0x4F11F */
1995         s->gt_imr               = I915_READ(GTIMR);
1996         s->gt_ier               = I915_READ(GTIER);
1997         s->pm_imr               = I915_READ(GEN6_PMIMR);
1998         s->pm_ier               = I915_READ(GEN6_PMIER);
1999
2000         for (i = 0; i < ARRAY_SIZE(s->gt_scratch); i++)
2001                 s->gt_scratch[i] = I915_READ(GEN7_GT_SCRATCH(i));
2002
2003         /* GT SA CZ domain, 0x100000-0x138124 */
2004         s->tilectl              = I915_READ(TILECTL);
2005         s->gt_fifoctl           = I915_READ(GTFIFOCTL);
2006         s->gtlc_wake_ctrl       = I915_READ(VLV_GTLC_WAKE_CTRL);
2007         s->gtlc_survive         = I915_READ(VLV_GTLC_SURVIVABILITY_REG);
2008         s->pmwgicz              = I915_READ(VLV_PMWGICZ);
2009
2010         /* Gunit-Display CZ domain, 0x182028-0x1821CF */
2011         s->gu_ctl0              = I915_READ(VLV_GU_CTL0);
2012         s->gu_ctl1              = I915_READ(VLV_GU_CTL1);
2013         s->pcbr                 = I915_READ(VLV_PCBR);
2014         s->clock_gate_dis2      = I915_READ(VLV_GUNIT_CLOCK_GATE2);
2015
2016         /*
2017          * Not saving any of:
2018          * DFT,         0x9800-0x9EC0
2019          * SARB,        0xB000-0xB1FC
2020          * GAC,         0x5208-0x524C, 0x14000-0x14C000
2021          * PCI CFG
2022          */
2023 }
2024
2025 static void vlv_restore_gunit_s0ix_state(struct drm_i915_private *dev_priv)
2026 {
2027         struct vlv_s0ix_state *s = &dev_priv->vlv_s0ix_state;
2028         u32 val;
2029         int i;
2030
2031         /* GAM 0x4000-0x4770 */
2032         I915_WRITE(GEN7_WR_WATERMARK,   s->wr_watermark);
2033         I915_WRITE(GEN7_GFX_PRIO_CTRL,  s->gfx_prio_ctrl);
2034         I915_WRITE(ARB_MODE,            s->arb_mode | (0xffff << 16));
2035         I915_WRITE(GEN7_GFX_PEND_TLB0,  s->gfx_pend_tlb0);
2036         I915_WRITE(GEN7_GFX_PEND_TLB1,  s->gfx_pend_tlb1);
2037
2038         for (i = 0; i < ARRAY_SIZE(s->lra_limits); i++)
2039                 I915_WRITE(GEN7_LRA_LIMITS(i), s->lra_limits[i]);
2040
2041         I915_WRITE(GEN7_MEDIA_MAX_REQ_COUNT, s->media_max_req_count);
2042         I915_WRITE(GEN7_GFX_MAX_REQ_COUNT, s->gfx_max_req_count);
2043
2044         I915_WRITE(RENDER_HWS_PGA_GEN7, s->render_hwsp);
2045         I915_WRITE(GAM_ECOCHK,          s->ecochk);
2046         I915_WRITE(BSD_HWS_PGA_GEN7,    s->bsd_hwsp);
2047         I915_WRITE(BLT_HWS_PGA_GEN7,    s->blt_hwsp);
2048
2049         I915_WRITE(GEN7_TLB_RD_ADDR,    s->tlb_rd_addr);
2050
2051         /* MBC 0x9024-0x91D0, 0x8500 */
2052         I915_WRITE(VLV_G3DCTL,          s->g3dctl);
2053         I915_WRITE(VLV_GSCKGCTL,        s->gsckgctl);
2054         I915_WRITE(GEN6_MBCTL,          s->mbctl);
2055
2056         /* GCP 0x9400-0x9424, 0x8100-0x810C */
2057         I915_WRITE(GEN6_UCGCTL1,        s->ucgctl1);
2058         I915_WRITE(GEN6_UCGCTL3,        s->ucgctl3);
2059         I915_WRITE(GEN6_RCGCTL1,        s->rcgctl1);
2060         I915_WRITE(GEN6_RCGCTL2,        s->rcgctl2);
2061         I915_WRITE(GEN6_RSTCTL,         s->rstctl);
2062         I915_WRITE(GEN7_MISCCPCTL,      s->misccpctl);
2063
2064         /* GPM 0xA000-0xAA84, 0x8000-0x80FC */
2065         I915_WRITE(GEN6_GFXPAUSE,       s->gfxpause);
2066         I915_WRITE(GEN6_RPDEUHWTC,      s->rpdeuhwtc);
2067         I915_WRITE(GEN6_RPDEUC,         s->rpdeuc);
2068         I915_WRITE(ECOBUS,              s->ecobus);
2069         I915_WRITE(VLV_PWRDWNUPCTL,     s->pwrdwnupctl);
2070         I915_WRITE(GEN6_RP_DOWN_TIMEOUT,s->rp_down_timeout);
2071         I915_WRITE(GEN6_RPDEUCSW,       s->rp_deucsw);
2072         I915_WRITE(GEN6_RCUBMABDTMR,    s->rcubmabdtmr);
2073         I915_WRITE(VLV_RCEDATA,         s->rcedata);
2074         I915_WRITE(VLV_SPAREG2H,        s->spare2gh);
2075
2076         /* Display CZ domain, 0x4400C-0x4402C, 0x4F000-0x4F11F */
2077         I915_WRITE(GTIMR,               s->gt_imr);
2078         I915_WRITE(GTIER,               s->gt_ier);
2079         I915_WRITE(GEN6_PMIMR,          s->pm_imr);
2080         I915_WRITE(GEN6_PMIER,          s->pm_ier);
2081
2082         for (i = 0; i < ARRAY_SIZE(s->gt_scratch); i++)
2083                 I915_WRITE(GEN7_GT_SCRATCH(i), s->gt_scratch[i]);
2084
2085         /* GT SA CZ domain, 0x100000-0x138124 */
2086         I915_WRITE(TILECTL,                     s->tilectl);
2087         I915_WRITE(GTFIFOCTL,                   s->gt_fifoctl);
2088         /*
2089          * Preserve the GT allow wake and GFX force clock bit, they are not
2090          * be restored, as they are used to control the s0ix suspend/resume
2091          * sequence by the caller.
2092          */
2093         val = I915_READ(VLV_GTLC_WAKE_CTRL);
2094         val &= VLV_GTLC_ALLOWWAKEREQ;
2095         val |= s->gtlc_wake_ctrl & ~VLV_GTLC_ALLOWWAKEREQ;
2096         I915_WRITE(VLV_GTLC_WAKE_CTRL, val);
2097
2098         val = I915_READ(VLV_GTLC_SURVIVABILITY_REG);
2099         val &= VLV_GFX_CLK_FORCE_ON_BIT;
2100         val |= s->gtlc_survive & ~VLV_GFX_CLK_FORCE_ON_BIT;
2101         I915_WRITE(VLV_GTLC_SURVIVABILITY_REG, val);
2102
2103         I915_WRITE(VLV_PMWGICZ,                 s->pmwgicz);
2104
2105         /* Gunit-Display CZ domain, 0x182028-0x1821CF */
2106         I915_WRITE(VLV_GU_CTL0,                 s->gu_ctl0);
2107         I915_WRITE(VLV_GU_CTL1,                 s->gu_ctl1);
2108         I915_WRITE(VLV_PCBR,                    s->pcbr);
2109         I915_WRITE(VLV_GUNIT_CLOCK_GATE2,       s->clock_gate_dis2);
2110 }
2111
2112 int vlv_force_gfx_clock(struct drm_i915_private *dev_priv, bool force_on)
2113 {
2114         u32 val;
2115         int err;
2116
2117         val = I915_READ(VLV_GTLC_SURVIVABILITY_REG);
2118         val &= ~VLV_GFX_CLK_FORCE_ON_BIT;
2119         if (force_on)
2120                 val |= VLV_GFX_CLK_FORCE_ON_BIT;
2121         I915_WRITE(VLV_GTLC_SURVIVABILITY_REG, val);
2122
2123         if (!force_on)
2124                 return 0;
2125
2126         err = intel_wait_for_register(dev_priv,
2127                                       VLV_GTLC_SURVIVABILITY_REG,
2128                                       VLV_GFX_CLK_STATUS_BIT,
2129                                       VLV_GFX_CLK_STATUS_BIT,
2130                                       20);
2131         if (err)
2132                 DRM_ERROR("timeout waiting for GFX clock force-on (%08x)\n",
2133                           I915_READ(VLV_GTLC_SURVIVABILITY_REG));
2134
2135         return err;
2136 }
2137
2138 static int vlv_allow_gt_wake(struct drm_i915_private *dev_priv, bool allow)
2139 {
2140         u32 val;
2141         int err = 0;
2142
2143         val = I915_READ(VLV_GTLC_WAKE_CTRL);
2144         val &= ~VLV_GTLC_ALLOWWAKEREQ;
2145         if (allow)
2146                 val |= VLV_GTLC_ALLOWWAKEREQ;
2147         I915_WRITE(VLV_GTLC_WAKE_CTRL, val);
2148         POSTING_READ(VLV_GTLC_WAKE_CTRL);
2149
2150         err = intel_wait_for_register(dev_priv,
2151                                       VLV_GTLC_PW_STATUS,
2152                                       VLV_GTLC_ALLOWWAKEACK,
2153                                       allow,
2154                                       1);
2155         if (err)
2156                 DRM_ERROR("timeout disabling GT waking\n");
2157
2158         return err;
2159 }
2160
2161 static int vlv_wait_for_gt_wells(struct drm_i915_private *dev_priv,
2162                                  bool wait_for_on)
2163 {
2164         u32 mask;
2165         u32 val;
2166         int err;
2167
2168         mask = VLV_GTLC_PW_MEDIA_STATUS_MASK | VLV_GTLC_PW_RENDER_STATUS_MASK;
2169         val = wait_for_on ? mask : 0;
2170         if ((I915_READ(VLV_GTLC_PW_STATUS) & mask) == val)
2171                 return 0;
2172
2173         DRM_DEBUG_KMS("waiting for GT wells to go %s (%08x)\n",
2174                       onoff(wait_for_on),
2175                       I915_READ(VLV_GTLC_PW_STATUS));
2176
2177         /*
2178          * RC6 transitioning can be delayed up to 2 msec (see
2179          * valleyview_enable_rps), use 3 msec for safety.
2180          */
2181         err = intel_wait_for_register(dev_priv,
2182                                       VLV_GTLC_PW_STATUS, mask, val,
2183                                       3);
2184         if (err)
2185                 DRM_ERROR("timeout waiting for GT wells to go %s\n",
2186                           onoff(wait_for_on));
2187
2188         return err;
2189 }
2190
2191 static void vlv_check_no_gt_access(struct drm_i915_private *dev_priv)
2192 {
2193         if (!(I915_READ(VLV_GTLC_PW_STATUS) & VLV_GTLC_ALLOWWAKEERR))
2194                 return;
2195
2196         DRM_DEBUG_DRIVER("GT register access while GT waking disabled\n");
2197         I915_WRITE(VLV_GTLC_PW_STATUS, VLV_GTLC_ALLOWWAKEERR);
2198 }
2199
2200 static int vlv_suspend_complete(struct drm_i915_private *dev_priv)
2201 {
2202         u32 mask;
2203         int err;
2204
2205         /*
2206          * Bspec defines the following GT well on flags as debug only, so
2207          * don't treat them as hard failures.
2208          */
2209         (void)vlv_wait_for_gt_wells(dev_priv, false);
2210
2211         mask = VLV_GTLC_RENDER_CTX_EXISTS | VLV_GTLC_MEDIA_CTX_EXISTS;
2212         WARN_ON((I915_READ(VLV_GTLC_WAKE_CTRL) & mask) != mask);
2213
2214         vlv_check_no_gt_access(dev_priv);
2215
2216         err = vlv_force_gfx_clock(dev_priv, true);
2217         if (err)
2218                 goto err1;
2219
2220         err = vlv_allow_gt_wake(dev_priv, false);
2221         if (err)
2222                 goto err2;
2223
2224         if (!IS_CHERRYVIEW(dev_priv))
2225                 vlv_save_gunit_s0ix_state(dev_priv);
2226
2227         err = vlv_force_gfx_clock(dev_priv, false);
2228         if (err)
2229                 goto err2;
2230
2231         return 0;
2232
2233 err2:
2234         /* For safety always re-enable waking and disable gfx clock forcing */
2235         vlv_allow_gt_wake(dev_priv, true);
2236 err1:
2237         vlv_force_gfx_clock(dev_priv, false);
2238
2239         return err;
2240 }
2241
2242 static int vlv_resume_prepare(struct drm_i915_private *dev_priv,
2243                                 bool rpm_resume)
2244 {
2245         struct drm_device *dev = &dev_priv->drm;
2246         int err;
2247         int ret;
2248
2249         /*
2250          * If any of the steps fail just try to continue, that's the best we
2251          * can do at this point. Return the first error code (which will also
2252          * leave RPM permanently disabled).
2253          */
2254         ret = vlv_force_gfx_clock(dev_priv, true);
2255
2256         if (!IS_CHERRYVIEW(dev_priv))
2257                 vlv_restore_gunit_s0ix_state(dev_priv);
2258
2259         err = vlv_allow_gt_wake(dev_priv, true);
2260         if (!ret)
2261                 ret = err;
2262
2263         err = vlv_force_gfx_clock(dev_priv, false);
2264         if (!ret)
2265                 ret = err;
2266
2267         vlv_check_no_gt_access(dev_priv);
2268
2269         if (rpm_resume) {
2270                 intel_init_clock_gating(dev);
2271                 i915_gem_restore_fences(dev);
2272         }
2273
2274         return ret;
2275 }
2276
2277 static int intel_runtime_suspend(struct device *kdev)
2278 {
2279         struct pci_dev *pdev = to_pci_dev(kdev);
2280         struct drm_device *dev = pci_get_drvdata(pdev);
2281         struct drm_i915_private *dev_priv = to_i915(dev);
2282         int ret;
2283
2284         if (WARN_ON_ONCE(!(dev_priv->rps.enabled && intel_enable_rc6())))
2285                 return -ENODEV;
2286
2287         if (WARN_ON_ONCE(!HAS_RUNTIME_PM(dev)))
2288                 return -ENODEV;
2289
2290         DRM_DEBUG_KMS("Suspending device\n");
2291
2292         /*
2293          * We could deadlock here in case another thread holding struct_mutex
2294          * calls RPM suspend concurrently, since the RPM suspend will wait
2295          * first for this RPM suspend to finish. In this case the concurrent
2296          * RPM resume will be followed by its RPM suspend counterpart. Still
2297          * for consistency return -EAGAIN, which will reschedule this suspend.
2298          */
2299         if (!mutex_trylock(&dev->struct_mutex)) {
2300                 DRM_DEBUG_KMS("device lock contention, deffering suspend\n");
2301                 /*
2302                  * Bump the expiration timestamp, otherwise the suspend won't
2303                  * be rescheduled.
2304                  */
2305                 pm_runtime_mark_last_busy(kdev);
2306
2307                 return -EAGAIN;
2308         }
2309
2310         disable_rpm_wakeref_asserts(dev_priv);
2311
2312         /*
2313          * We are safe here against re-faults, since the fault handler takes
2314          * an RPM reference.
2315          */
2316         i915_gem_release_all_mmaps(dev_priv);
2317         mutex_unlock(&dev->struct_mutex);
2318
2319         intel_guc_suspend(dev);
2320
2321         intel_runtime_pm_disable_interrupts(dev_priv);
2322
2323         ret = 0;
2324         if (IS_BROXTON(dev_priv)) {
2325                 bxt_display_core_uninit(dev_priv);
2326                 bxt_enable_dc9(dev_priv);
2327         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
2328                 hsw_enable_pc8(dev_priv);
2329         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
2330                 ret = vlv_suspend_complete(dev_priv);
2331         }
2332
2333         if (ret) {
2334                 DRM_ERROR("Runtime suspend failed, disabling it (%d)\n", ret);
2335                 intel_runtime_pm_enable_interrupts(dev_priv);
2336
2337                 enable_rpm_wakeref_asserts(dev_priv);
2338
2339                 return ret;
2340         }
2341
2342         intel_uncore_forcewake_reset(dev_priv, false);
2343
2344         enable_rpm_wakeref_asserts(dev_priv);
2345         WARN_ON_ONCE(atomic_read(&dev_priv->pm.wakeref_count));
2346
2347         if (intel_uncore_arm_unclaimed_mmio_detection(dev_priv))
2348                 DRM_ERROR("Unclaimed access detected prior to suspending\n");
2349
2350         dev_priv->pm.suspended = true;
2351
2352         /*
2353          * FIXME: We really should find a document that references the arguments
2354          * used below!
2355          */
2356         if (IS_BROADWELL(dev_priv)) {
2357                 /*
2358                  * On Broadwell, if we use PCI_D1 the PCH DDI ports will stop
2359                  * being detected, and the call we do at intel_runtime_resume()
2360                  * won't be able to restore them. Since PCI_D3hot matches the
2361                  * actual specification and appears to be working, use it.
2362                  */
2363                 intel_opregion_notify_adapter(dev_priv, PCI_D3hot);
2364         } else {
2365                 /*
2366                  * current versions of firmware which depend on this opregion
2367                  * notification have repurposed the D1 definition to mean
2368                  * "runtime suspended" vs. what you would normally expect (D3)
2369                  * to distinguish it from notifications that might be sent via
2370                  * the suspend path.
2371                  */
2372                 intel_opregion_notify_adapter(dev_priv, PCI_D1);
2373         }
2374
2375         assert_forcewakes_inactive(dev_priv);
2376
2377         if (!IS_VALLEYVIEW(dev_priv) || !IS_CHERRYVIEW(dev_priv))
2378                 intel_hpd_poll_init(dev_priv);
2379
2380         DRM_DEBUG_KMS("Device suspended\n");
2381         return 0;
2382 }
2383
2384 static int intel_runtime_resume(struct device *kdev)
2385 {
2386         struct pci_dev *pdev = to_pci_dev(kdev);
2387         struct drm_device *dev = pci_get_drvdata(pdev);
2388         struct drm_i915_private *dev_priv = to_i915(dev);
2389         int ret = 0;
2390
2391         if (WARN_ON_ONCE(!HAS_RUNTIME_PM(dev)))
2392                 return -ENODEV;
2393
2394         DRM_DEBUG_KMS("Resuming device\n");
2395
2396         WARN_ON_ONCE(atomic_read(&dev_priv->pm.wakeref_count));
2397         disable_rpm_wakeref_asserts(dev_priv);
2398
2399         intel_opregion_notify_adapter(dev_priv, PCI_D0);
2400         dev_priv->pm.suspended = false;
2401         if (intel_uncore_unclaimed_mmio(dev_priv))
2402                 DRM_DEBUG_DRIVER("Unclaimed access during suspend, bios?\n");
2403
2404         intel_guc_resume(dev);
2405
2406         if (IS_GEN6(dev_priv))
2407                 intel_init_pch_refclk(dev);
2408
2409         if (IS_BROXTON(dev)) {
2410                 bxt_disable_dc9(dev_priv);
2411                 bxt_display_core_init(dev_priv, true);
2412                 if (dev_priv->csr.dmc_payload &&
2413                     (dev_priv->csr.allowed_dc_mask & DC_STATE_EN_UPTO_DC5))
2414                         gen9_enable_dc5(dev_priv);
2415         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
2416                 hsw_disable_pc8(dev_priv);
2417         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
2418                 ret = vlv_resume_prepare(dev_priv, true);
2419         }
2420
2421         /*
2422          * No point of rolling back things in case of an error, as the best
2423          * we can do is to hope that things will still work (and disable RPM).
2424          */
2425         i915_gem_init_swizzling(dev);
2426
2427         intel_runtime_pm_enable_interrupts(dev_priv);
2428
2429         /*
2430          * On VLV/CHV display interrupts are part of the display
2431          * power well, so hpd is reinitialized from there. For
2432          * everyone else do it here.
2433          */
2434         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv))
2435                 intel_hpd_init(dev_priv);
2436
2437         enable_rpm_wakeref_asserts(dev_priv);
2438
2439         if (ret)
2440                 DRM_ERROR("Runtime resume failed, disabling it (%d)\n", ret);
2441         else
2442                 DRM_DEBUG_KMS("Device resumed\n");
2443
2444         return ret;
2445 }
2446
2447 const struct dev_pm_ops i915_pm_ops = {
2448         /*
2449          * S0ix (via system suspend) and S3 event handlers [PMSG_SUSPEND,
2450          * PMSG_RESUME]
2451          */
2452         .suspend = i915_pm_suspend,
2453         .suspend_late = i915_pm_suspend_late,
2454         .resume_early = i915_pm_resume_early,
2455         .resume = i915_pm_resume,
2456
2457         /*
2458          * S4 event handlers
2459          * @freeze, @freeze_late    : called (1) before creating the
2460          *                            hibernation image [PMSG_FREEZE] and
2461          *                            (2) after rebooting, before restoring
2462          *                            the image [PMSG_QUIESCE]
2463          * @thaw, @thaw_early       : called (1) after creating the hibernation
2464          *                            image, before writing it [PMSG_THAW]
2465          *                            and (2) after failing to create or
2466          *                            restore the image [PMSG_RECOVER]
2467          * @poweroff, @poweroff_late: called after writing the hibernation
2468          *                            image, before rebooting [PMSG_HIBERNATE]
2469          * @restore, @restore_early : called after rebooting and restoring the
2470          *                            hibernation image [PMSG_RESTORE]
2471          */
2472         .freeze = i915_pm_freeze,
2473         .freeze_late = i915_pm_freeze_late,
2474         .thaw_early = i915_pm_thaw_early,
2475         .thaw = i915_pm_thaw,
2476         .poweroff = i915_pm_suspend,
2477         .poweroff_late = i915_pm_poweroff_late,
2478         .restore_early = i915_pm_restore_early,
2479         .restore = i915_pm_restore,
2480
2481         /* S0ix (via runtime suspend) event handlers */
2482         .runtime_suspend = intel_runtime_suspend,
2483         .runtime_resume = intel_runtime_resume,
2484 };
2485
2486 static const struct vm_operations_struct i915_gem_vm_ops = {
2487         .fault = i915_gem_fault,
2488         .open = drm_gem_vm_open,
2489         .close = drm_gem_vm_close,
2490 };
2491
2492 static const struct file_operations i915_driver_fops = {
2493         .owner = THIS_MODULE,
2494         .open = drm_open,
2495         .release = drm_release,
2496         .unlocked_ioctl = drm_ioctl,
2497         .mmap = drm_gem_mmap,
2498         .poll = drm_poll,
2499         .read = drm_read,
2500 #ifdef CONFIG_COMPAT
2501         .compat_ioctl = i915_compat_ioctl,
2502 #endif
2503         .llseek = noop_llseek,
2504 };
2505
2506 static int
2507 i915_gem_reject_pin_ioctl(struct drm_device *dev, void *data,
2508                           struct drm_file *file)
2509 {
2510         return -ENODEV;
2511 }
2512
2513 static const struct drm_ioctl_desc i915_ioctls[] = {
2514         DRM_IOCTL_DEF_DRV(I915_INIT, drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
2515         DRM_IOCTL_DEF_DRV(I915_FLUSH, drm_noop, DRM_AUTH),
2516         DRM_IOCTL_DEF_DRV(I915_FLIP, drm_noop, DRM_AUTH),
2517         DRM_IOCTL_DEF_DRV(I915_BATCHBUFFER, drm_noop, DRM_AUTH),
2518         DRM_IOCTL_DEF_DRV(I915_IRQ_EMIT, drm_noop, DRM_AUTH),
2519         DRM_IOCTL_DEF_DRV(I915_IRQ_WAIT, drm_noop, DRM_AUTH),
2520         DRM_IOCTL_DEF_DRV(I915_GETPARAM, i915_getparam, DRM_AUTH|DRM_RENDER_ALLOW),
2521         DRM_IOCTL_DEF_DRV(I915_SETPARAM, drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
2522         DRM_IOCTL_DEF_DRV(I915_ALLOC, drm_noop, DRM_AUTH),
2523         DRM_IOCTL_DEF_DRV(I915_FREE, drm_noop, DRM_AUTH),
2524         DRM_IOCTL_DEF_DRV(I915_INIT_HEAP, drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
2525         DRM_IOCTL_DEF_DRV(I915_CMDBUFFER, drm_noop, DRM_AUTH),
2526         DRM_IOCTL_DEF_DRV(I915_DESTROY_HEAP,  drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
2527         DRM_IOCTL_DEF_DRV(I915_SET_VBLANK_PIPE,  drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
2528         DRM_IOCTL_DEF_DRV(I915_GET_VBLANK_PIPE,  drm_noop, DRM_AUTH),
2529         DRM_IOCTL_DEF_DRV(I915_VBLANK_SWAP, drm_noop, DRM_AUTH),
2530         DRM_IOCTL_DEF_DRV(I915_HWS_ADDR, drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
2531         DRM_IOCTL_DEF_DRV(I915_GEM_INIT, drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
2532         DRM_IOCTL_DEF_DRV(I915_GEM_EXECBUFFER, i915_gem_execbuffer, DRM_AUTH),
2533         DRM_IOCTL_DEF_DRV(I915_GEM_EXECBUFFER2, i915_gem_execbuffer2, DRM_AUTH|DRM_RENDER_ALLOW),
2534         DRM_IOCTL_DEF_DRV(I915_GEM_PIN, i915_gem_reject_pin_ioctl, DRM_AUTH|DRM_ROOT_ONLY),
2535         DRM_IOCTL_DEF_DRV(I915_GEM_UNPIN, i915_gem_reject_pin_ioctl, DRM_AUTH|DRM_ROOT_ONLY),
2536         DRM_IOCTL_DEF_DRV(I915_GEM_BUSY, i915_gem_busy_ioctl, DRM_AUTH|DRM_RENDER_ALLOW),
2537         DRM_IOCTL_DEF_DRV(I915_GEM_SET_CACHING, i915_gem_set_caching_ioctl, DRM_RENDER_ALLOW),
2538         DRM_IOCTL_DEF_DRV(I915_GEM_GET_CACHING, i915_gem_get_caching_ioctl, DRM_RENDER_ALLOW),
2539         DRM_IOCTL_DEF_DRV(I915_GEM_THROTTLE, i915_gem_throttle_ioctl, DRM_AUTH|DRM_RENDER_ALLOW),
2540         DRM_IOCTL_DEF_DRV(I915_GEM_ENTERVT, drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
2541         DRM_IOCTL_DEF_DRV(I915_GEM_LEAVEVT, drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
2542         DRM_IOCTL_DEF_DRV(I915_GEM_CREATE, i915_gem_create_ioctl, DRM_RENDER_ALLOW),
2543         DRM_IOCTL_DEF_DRV(I915_GEM_PREAD, i915_gem_pread_ioctl, DRM_RENDER_ALLOW),
2544         DRM_IOCTL_DEF_DRV(I915_GEM_PWRITE, i915_gem_pwrite_ioctl, DRM_RENDER_ALLOW),
2545         DRM_IOCTL_DEF_DRV(I915_GEM_MMAP, i915_gem_mmap_ioctl, DRM_RENDER_ALLOW),
2546         DRM_IOCTL_DEF_DRV(I915_GEM_MMAP_GTT, i915_gem_mmap_gtt_ioctl, DRM_RENDER_ALLOW),
2547         DRM_IOCTL_DEF_DRV(I915_GEM_SET_DOMAIN, i915_gem_set_domain_ioctl, DRM_RENDER_ALLOW),
2548         DRM_IOCTL_DEF_DRV(I915_GEM_SW_FINISH, i915_gem_sw_finish_ioctl, DRM_RENDER_ALLOW),
2549         DRM_IOCTL_DEF_DRV(I915_GEM_SET_TILING, i915_gem_set_tiling, DRM_RENDER_ALLOW),
2550         DRM_IOCTL_DEF_DRV(I915_GEM_GET_TILING, i915_gem_get_tiling, DRM_RENDER_ALLOW),
2551         DRM_IOCTL_DEF_DRV(I915_GEM_GET_APERTURE, i915_gem_get_aperture_ioctl, DRM_RENDER_ALLOW),
2552         DRM_IOCTL_DEF_DRV(I915_GET_PIPE_FROM_CRTC_ID, intel_get_pipe_from_crtc_id, 0),
2553         DRM_IOCTL_DEF_DRV(I915_GEM_MADVISE, i915_gem_madvise_ioctl, DRM_RENDER_ALLOW),
2554         DRM_IOCTL_DEF_DRV(I915_OVERLAY_PUT_IMAGE, intel_overlay_put_image_ioctl, DRM_MASTER|DRM_CONTROL_ALLOW),
2555         DRM_IOCTL_DEF_DRV(I915_OVERLAY_ATTRS, intel_overlay_attrs_ioctl, DRM_MASTER|DRM_CONTROL_ALLOW),
2556         DRM_IOCTL_DEF_DRV(I915_SET_SPRITE_COLORKEY, intel_sprite_set_colorkey, DRM_MASTER|DRM_CONTROL_ALLOW),
2557         DRM_IOCTL_DEF_DRV(I915_GET_SPRITE_COLORKEY, drm_noop, DRM_MASTER|DRM_CONTROL_ALLOW),
2558         DRM_IOCTL_DEF_DRV(I915_GEM_WAIT, i915_gem_wait_ioctl, DRM_AUTH|DRM_RENDER_ALLOW),
2559         DRM_IOCTL_DEF_DRV(I915_GEM_CONTEXT_CREATE, i915_gem_context_create_ioctl, DRM_RENDER_ALLOW),
2560         DRM_IOCTL_DEF_DRV(I915_GEM_CONTEXT_DESTROY, i915_gem_context_destroy_ioctl, DRM_RENDER_ALLOW),
2561         DRM_IOCTL_DEF_DRV(I915_REG_READ, i915_reg_read_ioctl, DRM_RENDER_ALLOW),
2562         DRM_IOCTL_DEF_DRV(I915_GET_RESET_STATS, i915_gem_context_reset_stats_ioctl, DRM_RENDER_ALLOW),
2563         DRM_IOCTL_DEF_DRV(I915_GEM_USERPTR, i915_gem_userptr_ioctl, DRM_RENDER_ALLOW),
2564         DRM_IOCTL_DEF_DRV(I915_GEM_CONTEXT_GETPARAM, i915_gem_context_getparam_ioctl, DRM_RENDER_ALLOW),
2565         DRM_IOCTL_DEF_DRV(I915_GEM_CONTEXT_SETPARAM, i915_gem_context_setparam_ioctl, DRM_RENDER_ALLOW),
2566 };
2567
2568 static struct drm_driver driver = {
2569         /* Don't use MTRRs here; the Xserver or userspace app should
2570          * deal with them for Intel hardware.
2571          */
2572         .driver_features =
2573             DRIVER_HAVE_IRQ | DRIVER_IRQ_SHARED | DRIVER_GEM | DRIVER_PRIME |
2574             DRIVER_RENDER | DRIVER_MODESET,
2575         .open = i915_driver_open,
2576         .lastclose = i915_driver_lastclose,
2577         .preclose = i915_driver_preclose,
2578         .postclose = i915_driver_postclose,
2579         .set_busid = drm_pci_set_busid,
2580
2581         .gem_close_object = i915_gem_close_object,
2582         .gem_free_object = i915_gem_free_object,
2583         .gem_vm_ops = &i915_gem_vm_ops,
2584
2585         .prime_handle_to_fd = drm_gem_prime_handle_to_fd,
2586         .prime_fd_to_handle = drm_gem_prime_fd_to_handle,
2587         .gem_prime_export = i915_gem_prime_export,
2588         .gem_prime_import = i915_gem_prime_import,
2589
2590         .dumb_create = i915_gem_dumb_create,
2591         .dumb_map_offset = i915_gem_mmap_gtt,
2592         .dumb_destroy = drm_gem_dumb_destroy,
2593         .ioctls = i915_ioctls,
2594         .num_ioctls = ARRAY_SIZE(i915_ioctls),
2595         .fops = &i915_driver_fops,
2596         .name = DRIVER_NAME,
2597         .desc = DRIVER_DESC,
2598         .date = DRIVER_DATE,
2599         .major = DRIVER_MAJOR,
2600         .minor = DRIVER_MINOR,
2601         .patchlevel = DRIVER_PATCHLEVEL,
2602 };