Merge tag 'drm-intel-next-2019-05-24' of git://anongit.freedesktop.org/drm/drm-intel...
[linux-2.6-microblaze.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/drm_atomic_helper.h>
45 #include <drm/drm_ioctl.h>
46 #include <drm/drm_irq.h>
47 #include <drm/drm_probe_helper.h>
48 #include <drm/i915_drm.h>
49
50 #include "gt/intel_gt_pm.h"
51 #include "gt/intel_reset.h"
52 #include "gt/intel_workarounds.h"
53
54 #include "i915_debugfs.h"
55 #include "i915_drv.h"
56 #include "i915_irq.h"
57 #include "i915_pmu.h"
58 #include "i915_query.h"
59 #include "i915_trace.h"
60 #include "i915_vgpu.h"
61 #include "intel_acpi.h"
62 #include "intel_audio.h"
63 #include "intel_cdclk.h"
64 #include "intel_csr.h"
65 #include "intel_dp.h"
66 #include "intel_drv.h"
67 #include "intel_fbdev.h"
68 #include "intel_gmbus.h"
69 #include "intel_hotplug.h"
70 #include "intel_overlay.h"
71 #include "intel_pipe_crc.h"
72 #include "intel_pm.h"
73 #include "intel_sprite.h"
74 #include "intel_uc.h"
75
76 static struct drm_driver driver;
77
78 #if IS_ENABLED(CONFIG_DRM_I915_DEBUG)
79 static unsigned int i915_load_fail_count;
80
81 bool __i915_inject_load_failure(const char *func, int line)
82 {
83         if (i915_load_fail_count >= i915_modparams.inject_load_failure)
84                 return false;
85
86         if (++i915_load_fail_count == i915_modparams.inject_load_failure) {
87                 DRM_INFO("Injecting failure at checkpoint %u [%s:%d]\n",
88                          i915_modparams.inject_load_failure, func, line);
89                 i915_modparams.inject_load_failure = 0;
90                 return true;
91         }
92
93         return false;
94 }
95
96 bool i915_error_injected(void)
97 {
98         return i915_load_fail_count && !i915_modparams.inject_load_failure;
99 }
100
101 #endif
102
103 #define FDO_BUG_URL "https://bugs.freedesktop.org/enter_bug.cgi?product=DRI"
104 #define FDO_BUG_MSG "Please file a bug at " FDO_BUG_URL " against DRM/Intel " \
105                     "providing the dmesg log by booting with drm.debug=0xf"
106
107 void
108 __i915_printk(struct drm_i915_private *dev_priv, const char *level,
109               const char *fmt, ...)
110 {
111         static bool shown_bug_once;
112         struct device *kdev = dev_priv->drm.dev;
113         bool is_error = level[1] <= KERN_ERR[1];
114         bool is_debug = level[1] == KERN_DEBUG[1];
115         struct va_format vaf;
116         va_list args;
117
118         if (is_debug && !(drm_debug & DRM_UT_DRIVER))
119                 return;
120
121         va_start(args, fmt);
122
123         vaf.fmt = fmt;
124         vaf.va = &args;
125
126         if (is_error)
127                 dev_printk(level, kdev, "%pV", &vaf);
128         else
129                 dev_printk(level, kdev, "[" DRM_NAME ":%ps] %pV",
130                            __builtin_return_address(0), &vaf);
131
132         va_end(args);
133
134         if (is_error && !shown_bug_once) {
135                 /*
136                  * Ask the user to file a bug report for the error, except
137                  * if they may have caused the bug by fiddling with unsafe
138                  * module parameters.
139                  */
140                 if (!test_taint(TAINT_USER))
141                         dev_notice(kdev, "%s", FDO_BUG_MSG);
142                 shown_bug_once = true;
143         }
144 }
145
146 /* Map PCH device id to PCH type, or PCH_NONE if unknown. */
147 static enum intel_pch
148 intel_pch_type(const struct drm_i915_private *dev_priv, unsigned short id)
149 {
150         switch (id) {
151         case INTEL_PCH_IBX_DEVICE_ID_TYPE:
152                 DRM_DEBUG_KMS("Found Ibex Peak PCH\n");
153                 WARN_ON(!IS_GEN(dev_priv, 5));
154                 return PCH_IBX;
155         case INTEL_PCH_CPT_DEVICE_ID_TYPE:
156                 DRM_DEBUG_KMS("Found CougarPoint PCH\n");
157                 WARN_ON(!IS_GEN(dev_priv, 6) && !IS_IVYBRIDGE(dev_priv));
158                 return PCH_CPT;
159         case INTEL_PCH_PPT_DEVICE_ID_TYPE:
160                 DRM_DEBUG_KMS("Found PantherPoint PCH\n");
161                 WARN_ON(!IS_GEN(dev_priv, 6) && !IS_IVYBRIDGE(dev_priv));
162                 /* PantherPoint is CPT compatible */
163                 return PCH_CPT;
164         case INTEL_PCH_LPT_DEVICE_ID_TYPE:
165                 DRM_DEBUG_KMS("Found LynxPoint PCH\n");
166                 WARN_ON(!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv));
167                 WARN_ON(IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv));
168                 return PCH_LPT;
169         case INTEL_PCH_LPT_LP_DEVICE_ID_TYPE:
170                 DRM_DEBUG_KMS("Found LynxPoint LP PCH\n");
171                 WARN_ON(!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv));
172                 WARN_ON(!IS_HSW_ULT(dev_priv) && !IS_BDW_ULT(dev_priv));
173                 return PCH_LPT;
174         case INTEL_PCH_WPT_DEVICE_ID_TYPE:
175                 DRM_DEBUG_KMS("Found WildcatPoint PCH\n");
176                 WARN_ON(!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv));
177                 WARN_ON(IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv));
178                 /* WildcatPoint is LPT compatible */
179                 return PCH_LPT;
180         case INTEL_PCH_WPT_LP_DEVICE_ID_TYPE:
181                 DRM_DEBUG_KMS("Found WildcatPoint LP PCH\n");
182                 WARN_ON(!IS_HASWELL(dev_priv) && !IS_BROADWELL(dev_priv));
183                 WARN_ON(!IS_HSW_ULT(dev_priv) && !IS_BDW_ULT(dev_priv));
184                 /* WildcatPoint is LPT compatible */
185                 return PCH_LPT;
186         case INTEL_PCH_SPT_DEVICE_ID_TYPE:
187                 DRM_DEBUG_KMS("Found SunrisePoint PCH\n");
188                 WARN_ON(!IS_SKYLAKE(dev_priv) && !IS_KABYLAKE(dev_priv));
189                 return PCH_SPT;
190         case INTEL_PCH_SPT_LP_DEVICE_ID_TYPE:
191                 DRM_DEBUG_KMS("Found SunrisePoint LP PCH\n");
192                 WARN_ON(!IS_SKYLAKE(dev_priv) && !IS_KABYLAKE(dev_priv));
193                 return PCH_SPT;
194         case INTEL_PCH_KBP_DEVICE_ID_TYPE:
195                 DRM_DEBUG_KMS("Found Kaby Lake PCH (KBP)\n");
196                 WARN_ON(!IS_SKYLAKE(dev_priv) && !IS_KABYLAKE(dev_priv) &&
197                         !IS_COFFEELAKE(dev_priv));
198                 /* KBP is SPT compatible */
199                 return PCH_SPT;
200         case INTEL_PCH_CNP_DEVICE_ID_TYPE:
201                 DRM_DEBUG_KMS("Found Cannon Lake PCH (CNP)\n");
202                 WARN_ON(!IS_CANNONLAKE(dev_priv) && !IS_COFFEELAKE(dev_priv));
203                 return PCH_CNP;
204         case INTEL_PCH_CNP_LP_DEVICE_ID_TYPE:
205                 DRM_DEBUG_KMS("Found Cannon Lake LP PCH (CNP-LP)\n");
206                 WARN_ON(!IS_CANNONLAKE(dev_priv) && !IS_COFFEELAKE(dev_priv));
207                 return PCH_CNP;
208         case INTEL_PCH_CMP_DEVICE_ID_TYPE:
209                 DRM_DEBUG_KMS("Found Comet Lake PCH (CMP)\n");
210                 WARN_ON(!IS_COFFEELAKE(dev_priv));
211                 /* CometPoint is CNP Compatible */
212                 return PCH_CNP;
213         case INTEL_PCH_ICP_DEVICE_ID_TYPE:
214                 DRM_DEBUG_KMS("Found Ice Lake PCH\n");
215                 WARN_ON(!IS_ICELAKE(dev_priv));
216                 return PCH_ICP;
217         default:
218                 return PCH_NONE;
219         }
220 }
221
222 static bool intel_is_virt_pch(unsigned short id,
223                               unsigned short svendor, unsigned short sdevice)
224 {
225         return (id == INTEL_PCH_P2X_DEVICE_ID_TYPE ||
226                 id == INTEL_PCH_P3X_DEVICE_ID_TYPE ||
227                 (id == INTEL_PCH_QEMU_DEVICE_ID_TYPE &&
228                  svendor == PCI_SUBVENDOR_ID_REDHAT_QUMRANET &&
229                  sdevice == PCI_SUBDEVICE_ID_QEMU));
230 }
231
232 static unsigned short
233 intel_virt_detect_pch(const struct drm_i915_private *dev_priv)
234 {
235         unsigned short id = 0;
236
237         /*
238          * In a virtualized passthrough environment we can be in a
239          * setup where the ISA bridge is not able to be passed through.
240          * In this case, a south bridge can be emulated and we have to
241          * make an educated guess as to which PCH is really there.
242          */
243
244         if (IS_ICELAKE(dev_priv))
245                 id = INTEL_PCH_ICP_DEVICE_ID_TYPE;
246         else if (IS_CANNONLAKE(dev_priv) || IS_COFFEELAKE(dev_priv))
247                 id = INTEL_PCH_CNP_DEVICE_ID_TYPE;
248         else if (IS_KABYLAKE(dev_priv) || IS_SKYLAKE(dev_priv))
249                 id = INTEL_PCH_SPT_DEVICE_ID_TYPE;
250         else if (IS_HSW_ULT(dev_priv) || IS_BDW_ULT(dev_priv))
251                 id = INTEL_PCH_LPT_LP_DEVICE_ID_TYPE;
252         else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
253                 id = INTEL_PCH_LPT_DEVICE_ID_TYPE;
254         else if (IS_GEN(dev_priv, 6) || IS_IVYBRIDGE(dev_priv))
255                 id = INTEL_PCH_CPT_DEVICE_ID_TYPE;
256         else if (IS_GEN(dev_priv, 5))
257                 id = INTEL_PCH_IBX_DEVICE_ID_TYPE;
258
259         if (id)
260                 DRM_DEBUG_KMS("Assuming PCH ID %04x\n", id);
261         else
262                 DRM_DEBUG_KMS("Assuming no PCH\n");
263
264         return id;
265 }
266
267 static void intel_detect_pch(struct drm_i915_private *dev_priv)
268 {
269         struct pci_dev *pch = NULL;
270
271         /*
272          * The reason to probe ISA bridge instead of Dev31:Fun0 is to
273          * make graphics device passthrough work easy for VMM, that only
274          * need to expose ISA bridge to let driver know the real hardware
275          * underneath. This is a requirement from virtualization team.
276          *
277          * In some virtualized environments (e.g. XEN), there is irrelevant
278          * ISA bridge in the system. To work reliably, we should scan trhough
279          * all the ISA bridge devices and check for the first match, instead
280          * of only checking the first one.
281          */
282         while ((pch = pci_get_class(PCI_CLASS_BRIDGE_ISA << 8, pch))) {
283                 unsigned short id;
284                 enum intel_pch pch_type;
285
286                 if (pch->vendor != PCI_VENDOR_ID_INTEL)
287                         continue;
288
289                 id = pch->device & INTEL_PCH_DEVICE_ID_MASK;
290
291                 pch_type = intel_pch_type(dev_priv, id);
292                 if (pch_type != PCH_NONE) {
293                         dev_priv->pch_type = pch_type;
294                         dev_priv->pch_id = id;
295                         break;
296                 } else if (intel_is_virt_pch(id, pch->subsystem_vendor,
297                                          pch->subsystem_device)) {
298                         id = intel_virt_detect_pch(dev_priv);
299                         pch_type = intel_pch_type(dev_priv, id);
300
301                         /* Sanity check virtual PCH id */
302                         if (WARN_ON(id && pch_type == PCH_NONE))
303                                 id = 0;
304
305                         dev_priv->pch_type = pch_type;
306                         dev_priv->pch_id = id;
307                         break;
308                 }
309         }
310
311         /*
312          * Use PCH_NOP (PCH but no South Display) for PCH platforms without
313          * display.
314          */
315         if (pch && !HAS_DISPLAY(dev_priv)) {
316                 DRM_DEBUG_KMS("Display disabled, reverting to NOP PCH\n");
317                 dev_priv->pch_type = PCH_NOP;
318                 dev_priv->pch_id = 0;
319         }
320
321         if (!pch)
322                 DRM_DEBUG_KMS("No PCH found.\n");
323
324         pci_dev_put(pch);
325 }
326
327 static int i915_getparam_ioctl(struct drm_device *dev, void *data,
328                                struct drm_file *file_priv)
329 {
330         struct drm_i915_private *dev_priv = to_i915(dev);
331         struct pci_dev *pdev = dev_priv->drm.pdev;
332         drm_i915_getparam_t *param = data;
333         int value;
334
335         switch (param->param) {
336         case I915_PARAM_IRQ_ACTIVE:
337         case I915_PARAM_ALLOW_BATCHBUFFER:
338         case I915_PARAM_LAST_DISPATCH:
339         case I915_PARAM_HAS_EXEC_CONSTANTS:
340                 /* Reject all old ums/dri params. */
341                 return -ENODEV;
342         case I915_PARAM_CHIPSET_ID:
343                 value = pdev->device;
344                 break;
345         case I915_PARAM_REVISION:
346                 value = pdev->revision;
347                 break;
348         case I915_PARAM_NUM_FENCES_AVAIL:
349                 value = dev_priv->num_fence_regs;
350                 break;
351         case I915_PARAM_HAS_OVERLAY:
352                 value = dev_priv->overlay ? 1 : 0;
353                 break;
354         case I915_PARAM_HAS_BSD:
355                 value = !!dev_priv->engine[VCS0];
356                 break;
357         case I915_PARAM_HAS_BLT:
358                 value = !!dev_priv->engine[BCS0];
359                 break;
360         case I915_PARAM_HAS_VEBOX:
361                 value = !!dev_priv->engine[VECS0];
362                 break;
363         case I915_PARAM_HAS_BSD2:
364                 value = !!dev_priv->engine[VCS1];
365                 break;
366         case I915_PARAM_HAS_LLC:
367                 value = HAS_LLC(dev_priv);
368                 break;
369         case I915_PARAM_HAS_WT:
370                 value = HAS_WT(dev_priv);
371                 break;
372         case I915_PARAM_HAS_ALIASING_PPGTT:
373                 value = INTEL_PPGTT(dev_priv);
374                 break;
375         case I915_PARAM_HAS_SEMAPHORES:
376                 value = !!(dev_priv->caps.scheduler & I915_SCHEDULER_CAP_SEMAPHORES);
377                 break;
378         case I915_PARAM_HAS_SECURE_BATCHES:
379                 value = capable(CAP_SYS_ADMIN);
380                 break;
381         case I915_PARAM_CMD_PARSER_VERSION:
382                 value = i915_cmd_parser_get_version(dev_priv);
383                 break;
384         case I915_PARAM_SUBSLICE_TOTAL:
385                 value = sseu_subslice_total(&RUNTIME_INFO(dev_priv)->sseu);
386                 if (!value)
387                         return -ENODEV;
388                 break;
389         case I915_PARAM_EU_TOTAL:
390                 value = RUNTIME_INFO(dev_priv)->sseu.eu_total;
391                 if (!value)
392                         return -ENODEV;
393                 break;
394         case I915_PARAM_HAS_GPU_RESET:
395                 value = i915_modparams.enable_hangcheck &&
396                         intel_has_gpu_reset(dev_priv);
397                 if (value && intel_has_reset_engine(dev_priv))
398                         value = 2;
399                 break;
400         case I915_PARAM_HAS_RESOURCE_STREAMER:
401                 value = 0;
402                 break;
403         case I915_PARAM_HAS_POOLED_EU:
404                 value = HAS_POOLED_EU(dev_priv);
405                 break;
406         case I915_PARAM_MIN_EU_IN_POOL:
407                 value = RUNTIME_INFO(dev_priv)->sseu.min_eu_in_pool;
408                 break;
409         case I915_PARAM_HUC_STATUS:
410                 value = intel_huc_check_status(&dev_priv->huc);
411                 if (value < 0)
412                         return value;
413                 break;
414         case I915_PARAM_MMAP_GTT_VERSION:
415                 /* Though we've started our numbering from 1, and so class all
416                  * earlier versions as 0, in effect their value is undefined as
417                  * the ioctl will report EINVAL for the unknown param!
418                  */
419                 value = i915_gem_mmap_gtt_version();
420                 break;
421         case I915_PARAM_HAS_SCHEDULER:
422                 value = dev_priv->caps.scheduler;
423                 break;
424
425         case I915_PARAM_MMAP_VERSION:
426                 /* Remember to bump this if the version changes! */
427         case I915_PARAM_HAS_GEM:
428         case I915_PARAM_HAS_PAGEFLIPPING:
429         case I915_PARAM_HAS_EXECBUF2: /* depends on GEM */
430         case I915_PARAM_HAS_RELAXED_FENCING:
431         case I915_PARAM_HAS_COHERENT_RINGS:
432         case I915_PARAM_HAS_RELAXED_DELTA:
433         case I915_PARAM_HAS_GEN7_SOL_RESET:
434         case I915_PARAM_HAS_WAIT_TIMEOUT:
435         case I915_PARAM_HAS_PRIME_VMAP_FLUSH:
436         case I915_PARAM_HAS_PINNED_BATCHES:
437         case I915_PARAM_HAS_EXEC_NO_RELOC:
438         case I915_PARAM_HAS_EXEC_HANDLE_LUT:
439         case I915_PARAM_HAS_COHERENT_PHYS_GTT:
440         case I915_PARAM_HAS_EXEC_SOFTPIN:
441         case I915_PARAM_HAS_EXEC_ASYNC:
442         case I915_PARAM_HAS_EXEC_FENCE:
443         case I915_PARAM_HAS_EXEC_CAPTURE:
444         case I915_PARAM_HAS_EXEC_BATCH_FIRST:
445         case I915_PARAM_HAS_EXEC_FENCE_ARRAY:
446         case I915_PARAM_HAS_EXEC_SUBMIT_FENCE:
447                 /* For the time being all of these are always true;
448                  * if some supported hardware does not have one of these
449                  * features this value needs to be provided from
450                  * INTEL_INFO(), a feature macro, or similar.
451                  */
452                 value = 1;
453                 break;
454         case I915_PARAM_HAS_CONTEXT_ISOLATION:
455                 value = intel_engines_has_context_isolation(dev_priv);
456                 break;
457         case I915_PARAM_SLICE_MASK:
458                 value = RUNTIME_INFO(dev_priv)->sseu.slice_mask;
459                 if (!value)
460                         return -ENODEV;
461                 break;
462         case I915_PARAM_SUBSLICE_MASK:
463                 value = RUNTIME_INFO(dev_priv)->sseu.subslice_mask[0];
464                 if (!value)
465                         return -ENODEV;
466                 break;
467         case I915_PARAM_CS_TIMESTAMP_FREQUENCY:
468                 value = 1000 * RUNTIME_INFO(dev_priv)->cs_timestamp_frequency_khz;
469                 break;
470         case I915_PARAM_MMAP_GTT_COHERENT:
471                 value = INTEL_INFO(dev_priv)->has_coherent_ggtt;
472                 break;
473         default:
474                 DRM_DEBUG("Unknown parameter %d\n", param->param);
475                 return -EINVAL;
476         }
477
478         if (put_user(value, param->value))
479                 return -EFAULT;
480
481         return 0;
482 }
483
484 static int i915_get_bridge_dev(struct drm_i915_private *dev_priv)
485 {
486         int domain = pci_domain_nr(dev_priv->drm.pdev->bus);
487
488         dev_priv->bridge_dev =
489                 pci_get_domain_bus_and_slot(domain, 0, PCI_DEVFN(0, 0));
490         if (!dev_priv->bridge_dev) {
491                 DRM_ERROR("bridge device not found\n");
492                 return -1;
493         }
494         return 0;
495 }
496
497 /* Allocate space for the MCH regs if needed, return nonzero on error */
498 static int
499 intel_alloc_mchbar_resource(struct drm_i915_private *dev_priv)
500 {
501         int reg = INTEL_GEN(dev_priv) >= 4 ? MCHBAR_I965 : MCHBAR_I915;
502         u32 temp_lo, temp_hi = 0;
503         u64 mchbar_addr;
504         int ret;
505
506         if (INTEL_GEN(dev_priv) >= 4)
507                 pci_read_config_dword(dev_priv->bridge_dev, reg + 4, &temp_hi);
508         pci_read_config_dword(dev_priv->bridge_dev, reg, &temp_lo);
509         mchbar_addr = ((u64)temp_hi << 32) | temp_lo;
510
511         /* If ACPI doesn't have it, assume we need to allocate it ourselves */
512 #ifdef CONFIG_PNP
513         if (mchbar_addr &&
514             pnp_range_reserved(mchbar_addr, mchbar_addr + MCHBAR_SIZE))
515                 return 0;
516 #endif
517
518         /* Get some space for it */
519         dev_priv->mch_res.name = "i915 MCHBAR";
520         dev_priv->mch_res.flags = IORESOURCE_MEM;
521         ret = pci_bus_alloc_resource(dev_priv->bridge_dev->bus,
522                                      &dev_priv->mch_res,
523                                      MCHBAR_SIZE, MCHBAR_SIZE,
524                                      PCIBIOS_MIN_MEM,
525                                      0, pcibios_align_resource,
526                                      dev_priv->bridge_dev);
527         if (ret) {
528                 DRM_DEBUG_DRIVER("failed bus alloc: %d\n", ret);
529                 dev_priv->mch_res.start = 0;
530                 return ret;
531         }
532
533         if (INTEL_GEN(dev_priv) >= 4)
534                 pci_write_config_dword(dev_priv->bridge_dev, reg + 4,
535                                        upper_32_bits(dev_priv->mch_res.start));
536
537         pci_write_config_dword(dev_priv->bridge_dev, reg,
538                                lower_32_bits(dev_priv->mch_res.start));
539         return 0;
540 }
541
542 /* Setup MCHBAR if possible, return true if we should disable it again */
543 static void
544 intel_setup_mchbar(struct drm_i915_private *dev_priv)
545 {
546         int mchbar_reg = INTEL_GEN(dev_priv) >= 4 ? MCHBAR_I965 : MCHBAR_I915;
547         u32 temp;
548         bool enabled;
549
550         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
551                 return;
552
553         dev_priv->mchbar_need_disable = false;
554
555         if (IS_I915G(dev_priv) || IS_I915GM(dev_priv)) {
556                 pci_read_config_dword(dev_priv->bridge_dev, DEVEN, &temp);
557                 enabled = !!(temp & DEVEN_MCHBAR_EN);
558         } else {
559                 pci_read_config_dword(dev_priv->bridge_dev, mchbar_reg, &temp);
560                 enabled = temp & 1;
561         }
562
563         /* If it's already enabled, don't have to do anything */
564         if (enabled)
565                 return;
566
567         if (intel_alloc_mchbar_resource(dev_priv))
568                 return;
569
570         dev_priv->mchbar_need_disable = true;
571
572         /* Space is allocated or reserved, so enable it. */
573         if (IS_I915G(dev_priv) || IS_I915GM(dev_priv)) {
574                 pci_write_config_dword(dev_priv->bridge_dev, DEVEN,
575                                        temp | DEVEN_MCHBAR_EN);
576         } else {
577                 pci_read_config_dword(dev_priv->bridge_dev, mchbar_reg, &temp);
578                 pci_write_config_dword(dev_priv->bridge_dev, mchbar_reg, temp | 1);
579         }
580 }
581
582 static void
583 intel_teardown_mchbar(struct drm_i915_private *dev_priv)
584 {
585         int mchbar_reg = INTEL_GEN(dev_priv) >= 4 ? MCHBAR_I965 : MCHBAR_I915;
586
587         if (dev_priv->mchbar_need_disable) {
588                 if (IS_I915G(dev_priv) || IS_I915GM(dev_priv)) {
589                         u32 deven_val;
590
591                         pci_read_config_dword(dev_priv->bridge_dev, DEVEN,
592                                               &deven_val);
593                         deven_val &= ~DEVEN_MCHBAR_EN;
594                         pci_write_config_dword(dev_priv->bridge_dev, DEVEN,
595                                                deven_val);
596                 } else {
597                         u32 mchbar_val;
598
599                         pci_read_config_dword(dev_priv->bridge_dev, mchbar_reg,
600                                               &mchbar_val);
601                         mchbar_val &= ~1;
602                         pci_write_config_dword(dev_priv->bridge_dev, mchbar_reg,
603                                                mchbar_val);
604                 }
605         }
606
607         if (dev_priv->mch_res.start)
608                 release_resource(&dev_priv->mch_res);
609 }
610
611 /* true = enable decode, false = disable decoder */
612 static unsigned int i915_vga_set_decode(void *cookie, bool state)
613 {
614         struct drm_i915_private *dev_priv = cookie;
615
616         intel_modeset_vga_set_state(dev_priv, state);
617         if (state)
618                 return VGA_RSRC_LEGACY_IO | VGA_RSRC_LEGACY_MEM |
619                        VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM;
620         else
621                 return VGA_RSRC_NORMAL_IO | VGA_RSRC_NORMAL_MEM;
622 }
623
624 static int i915_resume_switcheroo(struct drm_device *dev);
625 static int i915_suspend_switcheroo(struct drm_device *dev, pm_message_t state);
626
627 static void i915_switcheroo_set_state(struct pci_dev *pdev, enum vga_switcheroo_state state)
628 {
629         struct drm_device *dev = pci_get_drvdata(pdev);
630         pm_message_t pmm = { .event = PM_EVENT_SUSPEND };
631
632         if (state == VGA_SWITCHEROO_ON) {
633                 pr_info("switched on\n");
634                 dev->switch_power_state = DRM_SWITCH_POWER_CHANGING;
635                 /* i915 resume handler doesn't set to D0 */
636                 pci_set_power_state(pdev, PCI_D0);
637                 i915_resume_switcheroo(dev);
638                 dev->switch_power_state = DRM_SWITCH_POWER_ON;
639         } else {
640                 pr_info("switched off\n");
641                 dev->switch_power_state = DRM_SWITCH_POWER_CHANGING;
642                 i915_suspend_switcheroo(dev, pmm);
643                 dev->switch_power_state = DRM_SWITCH_POWER_OFF;
644         }
645 }
646
647 static bool i915_switcheroo_can_switch(struct pci_dev *pdev)
648 {
649         struct drm_device *dev = pci_get_drvdata(pdev);
650
651         /*
652          * FIXME: open_count is protected by drm_global_mutex but that would lead to
653          * locking inversion with the driver load path. And the access here is
654          * completely racy anyway. So don't bother with locking for now.
655          */
656         return dev->open_count == 0;
657 }
658
659 static const struct vga_switcheroo_client_ops i915_switcheroo_ops = {
660         .set_gpu_state = i915_switcheroo_set_state,
661         .reprobe = NULL,
662         .can_switch = i915_switcheroo_can_switch,
663 };
664
665 static int i915_load_modeset_init(struct drm_device *dev)
666 {
667         struct drm_i915_private *dev_priv = to_i915(dev);
668         struct pci_dev *pdev = dev_priv->drm.pdev;
669         int ret;
670
671         if (i915_inject_load_failure())
672                 return -ENODEV;
673
674         if (HAS_DISPLAY(dev_priv)) {
675                 ret = drm_vblank_init(&dev_priv->drm,
676                                       INTEL_INFO(dev_priv)->num_pipes);
677                 if (ret)
678                         goto out;
679         }
680
681         intel_bios_init(dev_priv);
682
683         /* If we have > 1 VGA cards, then we need to arbitrate access
684          * to the common VGA resources.
685          *
686          * If we are a secondary display controller (!PCI_DISPLAY_CLASS_VGA),
687          * then we do not take part in VGA arbitration and the
688          * vga_client_register() fails with -ENODEV.
689          */
690         ret = vga_client_register(pdev, dev_priv, NULL, i915_vga_set_decode);
691         if (ret && ret != -ENODEV)
692                 goto out;
693
694         intel_register_dsm_handler();
695
696         ret = vga_switcheroo_register_client(pdev, &i915_switcheroo_ops, false);
697         if (ret)
698                 goto cleanup_vga_client;
699
700         /* must happen before intel_power_domains_init_hw() on VLV/CHV */
701         intel_update_rawclk(dev_priv);
702
703         intel_power_domains_init_hw(dev_priv, false);
704
705         intel_csr_ucode_init(dev_priv);
706
707         ret = intel_irq_install(dev_priv);
708         if (ret)
709                 goto cleanup_csr;
710
711         intel_gmbus_setup(dev_priv);
712
713         /* Important: The output setup functions called by modeset_init need
714          * working irqs for e.g. gmbus and dp aux transfers. */
715         ret = intel_modeset_init(dev);
716         if (ret)
717                 goto cleanup_irq;
718
719         ret = i915_gem_init(dev_priv);
720         if (ret)
721                 goto cleanup_modeset;
722
723         intel_overlay_setup(dev_priv);
724
725         if (!HAS_DISPLAY(dev_priv))
726                 return 0;
727
728         ret = intel_fbdev_init(dev);
729         if (ret)
730                 goto cleanup_gem;
731
732         /* Only enable hotplug handling once the fbdev is fully set up. */
733         intel_hpd_init(dev_priv);
734
735         intel_init_ipc(dev_priv);
736
737         return 0;
738
739 cleanup_gem:
740         i915_gem_suspend(dev_priv);
741         i915_gem_fini(dev_priv);
742 cleanup_modeset:
743         intel_modeset_cleanup(dev);
744 cleanup_irq:
745         drm_irq_uninstall(dev);
746         intel_gmbus_teardown(dev_priv);
747 cleanup_csr:
748         intel_csr_ucode_fini(dev_priv);
749         intel_power_domains_fini_hw(dev_priv);
750         vga_switcheroo_unregister_client(pdev);
751 cleanup_vga_client:
752         vga_client_register(pdev, NULL, NULL, NULL);
753 out:
754         return ret;
755 }
756
757 static int i915_kick_out_firmware_fb(struct drm_i915_private *dev_priv)
758 {
759         struct apertures_struct *ap;
760         struct pci_dev *pdev = dev_priv->drm.pdev;
761         struct i915_ggtt *ggtt = &dev_priv->ggtt;
762         bool primary;
763         int ret;
764
765         ap = alloc_apertures(1);
766         if (!ap)
767                 return -ENOMEM;
768
769         ap->ranges[0].base = ggtt->gmadr.start;
770         ap->ranges[0].size = ggtt->mappable_end;
771
772         primary =
773                 pdev->resource[PCI_ROM_RESOURCE].flags & IORESOURCE_ROM_SHADOW;
774
775         ret = drm_fb_helper_remove_conflicting_framebuffers(ap, "inteldrmfb", primary);
776
777         kfree(ap);
778
779         return ret;
780 }
781
782 static void intel_init_dpio(struct drm_i915_private *dev_priv)
783 {
784         /*
785          * IOSF_PORT_DPIO is used for VLV x2 PHY (DP/HDMI B and C),
786          * CHV x1 PHY (DP/HDMI D)
787          * IOSF_PORT_DPIO_2 is used for CHV x2 PHY (DP/HDMI B and C)
788          */
789         if (IS_CHERRYVIEW(dev_priv)) {
790                 DPIO_PHY_IOSF_PORT(DPIO_PHY0) = IOSF_PORT_DPIO_2;
791                 DPIO_PHY_IOSF_PORT(DPIO_PHY1) = IOSF_PORT_DPIO;
792         } else if (IS_VALLEYVIEW(dev_priv)) {
793                 DPIO_PHY_IOSF_PORT(DPIO_PHY0) = IOSF_PORT_DPIO;
794         }
795 }
796
797 static int i915_workqueues_init(struct drm_i915_private *dev_priv)
798 {
799         /*
800          * The i915 workqueue is primarily used for batched retirement of
801          * requests (and thus managing bo) once the task has been completed
802          * by the GPU. i915_retire_requests() is called directly when we
803          * need high-priority retirement, such as waiting for an explicit
804          * bo.
805          *
806          * It is also used for periodic low-priority events, such as
807          * idle-timers and recording error state.
808          *
809          * All tasks on the workqueue are expected to acquire the dev mutex
810          * so there is no point in running more than one instance of the
811          * workqueue at any time.  Use an ordered one.
812          */
813         dev_priv->wq = alloc_ordered_workqueue("i915", 0);
814         if (dev_priv->wq == NULL)
815                 goto out_err;
816
817         dev_priv->hotplug.dp_wq = alloc_ordered_workqueue("i915-dp", 0);
818         if (dev_priv->hotplug.dp_wq == NULL)
819                 goto out_free_wq;
820
821         return 0;
822
823 out_free_wq:
824         destroy_workqueue(dev_priv->wq);
825 out_err:
826         DRM_ERROR("Failed to allocate workqueues.\n");
827
828         return -ENOMEM;
829 }
830
831 static void i915_engines_cleanup(struct drm_i915_private *i915)
832 {
833         struct intel_engine_cs *engine;
834         enum intel_engine_id id;
835
836         for_each_engine(engine, i915, id)
837                 kfree(engine);
838 }
839
840 static void i915_workqueues_cleanup(struct drm_i915_private *dev_priv)
841 {
842         destroy_workqueue(dev_priv->hotplug.dp_wq);
843         destroy_workqueue(dev_priv->wq);
844 }
845
846 /*
847  * We don't keep the workarounds for pre-production hardware, so we expect our
848  * driver to fail on these machines in one way or another. A little warning on
849  * dmesg may help both the user and the bug triagers.
850  *
851  * Our policy for removing pre-production workarounds is to keep the
852  * current gen workarounds as a guide to the bring-up of the next gen
853  * (workarounds have a habit of persisting!). Anything older than that
854  * should be removed along with the complications they introduce.
855  */
856 static void intel_detect_preproduction_hw(struct drm_i915_private *dev_priv)
857 {
858         bool pre = false;
859
860         pre |= IS_HSW_EARLY_SDV(dev_priv);
861         pre |= IS_SKL_REVID(dev_priv, 0, SKL_REVID_F0);
862         pre |= IS_BXT_REVID(dev_priv, 0, BXT_REVID_B_LAST);
863         pre |= IS_KBL_REVID(dev_priv, 0, KBL_REVID_A0);
864
865         if (pre) {
866                 DRM_ERROR("This is a pre-production stepping. "
867                           "It may not be fully functional.\n");
868                 add_taint(TAINT_MACHINE_CHECK, LOCKDEP_STILL_OK);
869         }
870 }
871
872 /**
873  * i915_driver_init_early - setup state not requiring device access
874  * @dev_priv: device private
875  *
876  * Initialize everything that is a "SW-only" state, that is state not
877  * requiring accessing the device or exposing the driver via kernel internal
878  * or userspace interfaces. Example steps belonging here: lock initialization,
879  * system memory allocation, setting up device specific attributes and
880  * function hooks not requiring accessing the device.
881  */
882 static int i915_driver_init_early(struct drm_i915_private *dev_priv)
883 {
884         int ret = 0;
885
886         if (i915_inject_load_failure())
887                 return -ENODEV;
888
889         intel_device_info_subplatform_init(dev_priv);
890
891         intel_uncore_init_early(&dev_priv->uncore);
892
893         spin_lock_init(&dev_priv->irq_lock);
894         spin_lock_init(&dev_priv->gpu_error.lock);
895         mutex_init(&dev_priv->backlight_lock);
896
897         mutex_init(&dev_priv->sb_lock);
898         pm_qos_add_request(&dev_priv->sb_qos,
899                            PM_QOS_CPU_DMA_LATENCY, PM_QOS_DEFAULT_VALUE);
900
901         mutex_init(&dev_priv->av_mutex);
902         mutex_init(&dev_priv->wm.wm_mutex);
903         mutex_init(&dev_priv->pps_mutex);
904         mutex_init(&dev_priv->hdcp_comp_mutex);
905
906         i915_memcpy_init_early(dev_priv);
907         intel_runtime_pm_init_early(dev_priv);
908
909         ret = i915_workqueues_init(dev_priv);
910         if (ret < 0)
911                 goto err_engines;
912
913         ret = i915_gem_init_early(dev_priv);
914         if (ret < 0)
915                 goto err_workqueues;
916
917         /* This must be called before any calls to HAS_PCH_* */
918         intel_detect_pch(dev_priv);
919
920         intel_wopcm_init_early(&dev_priv->wopcm);
921         intel_uc_init_early(dev_priv);
922         intel_pm_setup(dev_priv);
923         intel_init_dpio(dev_priv);
924         ret = intel_power_domains_init(dev_priv);
925         if (ret < 0)
926                 goto err_uc;
927         intel_irq_init(dev_priv);
928         intel_hangcheck_init(dev_priv);
929         intel_init_display_hooks(dev_priv);
930         intel_init_clock_gating_hooks(dev_priv);
931         intel_init_audio_hooks(dev_priv);
932         intel_display_crc_init(dev_priv);
933
934         intel_detect_preproduction_hw(dev_priv);
935
936         return 0;
937
938 err_uc:
939         intel_uc_cleanup_early(dev_priv);
940         i915_gem_cleanup_early(dev_priv);
941 err_workqueues:
942         i915_workqueues_cleanup(dev_priv);
943 err_engines:
944         i915_engines_cleanup(dev_priv);
945         return ret;
946 }
947
948 /**
949  * i915_driver_cleanup_early - cleanup the setup done in i915_driver_init_early()
950  * @dev_priv: device private
951  */
952 static void i915_driver_cleanup_early(struct drm_i915_private *dev_priv)
953 {
954         intel_irq_fini(dev_priv);
955         intel_power_domains_cleanup(dev_priv);
956         intel_uc_cleanup_early(dev_priv);
957         i915_gem_cleanup_early(dev_priv);
958         i915_workqueues_cleanup(dev_priv);
959         i915_engines_cleanup(dev_priv);
960
961         pm_qos_remove_request(&dev_priv->sb_qos);
962         mutex_destroy(&dev_priv->sb_lock);
963 }
964
965 /**
966  * i915_driver_init_mmio - setup device MMIO
967  * @dev_priv: device private
968  *
969  * Setup minimal device state necessary for MMIO accesses later in the
970  * initialization sequence. The setup here should avoid any other device-wide
971  * side effects or exposing the driver via kernel internal or user space
972  * interfaces.
973  */
974 static int i915_driver_init_mmio(struct drm_i915_private *dev_priv)
975 {
976         int ret;
977
978         if (i915_inject_load_failure())
979                 return -ENODEV;
980
981         if (i915_get_bridge_dev(dev_priv))
982                 return -EIO;
983
984         ret = intel_uncore_init_mmio(&dev_priv->uncore);
985         if (ret < 0)
986                 goto err_bridge;
987
988         /* Try to make sure MCHBAR is enabled before poking at it */
989         intel_setup_mchbar(dev_priv);
990
991         intel_device_info_init_mmio(dev_priv);
992
993         intel_uncore_prune_mmio_domains(&dev_priv->uncore);
994
995         intel_uc_init_mmio(dev_priv);
996
997         ret = intel_engines_init_mmio(dev_priv);
998         if (ret)
999                 goto err_uncore;
1000
1001         i915_gem_init_mmio(dev_priv);
1002
1003         return 0;
1004
1005 err_uncore:
1006         intel_teardown_mchbar(dev_priv);
1007         intel_uncore_fini_mmio(&dev_priv->uncore);
1008 err_bridge:
1009         pci_dev_put(dev_priv->bridge_dev);
1010
1011         return ret;
1012 }
1013
1014 /**
1015  * i915_driver_cleanup_mmio - cleanup the setup done in i915_driver_init_mmio()
1016  * @dev_priv: device private
1017  */
1018 static void i915_driver_cleanup_mmio(struct drm_i915_private *dev_priv)
1019 {
1020         intel_teardown_mchbar(dev_priv);
1021         intel_uncore_fini_mmio(&dev_priv->uncore);
1022         pci_dev_put(dev_priv->bridge_dev);
1023 }
1024
1025 static void intel_sanitize_options(struct drm_i915_private *dev_priv)
1026 {
1027         intel_gvt_sanitize_options(dev_priv);
1028 }
1029
1030 #define DRAM_TYPE_STR(type) [INTEL_DRAM_ ## type] = #type
1031
1032 static const char *intel_dram_type_str(enum intel_dram_type type)
1033 {
1034         static const char * const str[] = {
1035                 DRAM_TYPE_STR(UNKNOWN),
1036                 DRAM_TYPE_STR(DDR3),
1037                 DRAM_TYPE_STR(DDR4),
1038                 DRAM_TYPE_STR(LPDDR3),
1039                 DRAM_TYPE_STR(LPDDR4),
1040         };
1041
1042         if (type >= ARRAY_SIZE(str))
1043                 type = INTEL_DRAM_UNKNOWN;
1044
1045         return str[type];
1046 }
1047
1048 #undef DRAM_TYPE_STR
1049
1050 static int intel_dimm_num_devices(const struct dram_dimm_info *dimm)
1051 {
1052         return dimm->ranks * 64 / (dimm->width ?: 1);
1053 }
1054
1055 /* Returns total GB for the whole DIMM */
1056 static int skl_get_dimm_size(u16 val)
1057 {
1058         return val & SKL_DRAM_SIZE_MASK;
1059 }
1060
1061 static int skl_get_dimm_width(u16 val)
1062 {
1063         if (skl_get_dimm_size(val) == 0)
1064                 return 0;
1065
1066         switch (val & SKL_DRAM_WIDTH_MASK) {
1067         case SKL_DRAM_WIDTH_X8:
1068         case SKL_DRAM_WIDTH_X16:
1069         case SKL_DRAM_WIDTH_X32:
1070                 val = (val & SKL_DRAM_WIDTH_MASK) >> SKL_DRAM_WIDTH_SHIFT;
1071                 return 8 << val;
1072         default:
1073                 MISSING_CASE(val);
1074                 return 0;
1075         }
1076 }
1077
1078 static int skl_get_dimm_ranks(u16 val)
1079 {
1080         if (skl_get_dimm_size(val) == 0)
1081                 return 0;
1082
1083         val = (val & SKL_DRAM_RANK_MASK) >> SKL_DRAM_RANK_SHIFT;
1084
1085         return val + 1;
1086 }
1087
1088 /* Returns total GB for the whole DIMM */
1089 static int cnl_get_dimm_size(u16 val)
1090 {
1091         return (val & CNL_DRAM_SIZE_MASK) / 2;
1092 }
1093
1094 static int cnl_get_dimm_width(u16 val)
1095 {
1096         if (cnl_get_dimm_size(val) == 0)
1097                 return 0;
1098
1099         switch (val & CNL_DRAM_WIDTH_MASK) {
1100         case CNL_DRAM_WIDTH_X8:
1101         case CNL_DRAM_WIDTH_X16:
1102         case CNL_DRAM_WIDTH_X32:
1103                 val = (val & CNL_DRAM_WIDTH_MASK) >> CNL_DRAM_WIDTH_SHIFT;
1104                 return 8 << val;
1105         default:
1106                 MISSING_CASE(val);
1107                 return 0;
1108         }
1109 }
1110
1111 static int cnl_get_dimm_ranks(u16 val)
1112 {
1113         if (cnl_get_dimm_size(val) == 0)
1114                 return 0;
1115
1116         val = (val & CNL_DRAM_RANK_MASK) >> CNL_DRAM_RANK_SHIFT;
1117
1118         return val + 1;
1119 }
1120
1121 static bool
1122 skl_is_16gb_dimm(const struct dram_dimm_info *dimm)
1123 {
1124         /* Convert total GB to Gb per DRAM device */
1125         return 8 * dimm->size / (intel_dimm_num_devices(dimm) ?: 1) == 16;
1126 }
1127
1128 static void
1129 skl_dram_get_dimm_info(struct drm_i915_private *dev_priv,
1130                        struct dram_dimm_info *dimm,
1131                        int channel, char dimm_name, u16 val)
1132 {
1133         if (INTEL_GEN(dev_priv) >= 10) {
1134                 dimm->size = cnl_get_dimm_size(val);
1135                 dimm->width = cnl_get_dimm_width(val);
1136                 dimm->ranks = cnl_get_dimm_ranks(val);
1137         } else {
1138                 dimm->size = skl_get_dimm_size(val);
1139                 dimm->width = skl_get_dimm_width(val);
1140                 dimm->ranks = skl_get_dimm_ranks(val);
1141         }
1142
1143         DRM_DEBUG_KMS("CH%u DIMM %c size: %u GB, width: X%u, ranks: %u, 16Gb DIMMs: %s\n",
1144                       channel, dimm_name, dimm->size, dimm->width, dimm->ranks,
1145                       yesno(skl_is_16gb_dimm(dimm)));
1146 }
1147
1148 static int
1149 skl_dram_get_channel_info(struct drm_i915_private *dev_priv,
1150                           struct dram_channel_info *ch,
1151                           int channel, u32 val)
1152 {
1153         skl_dram_get_dimm_info(dev_priv, &ch->dimm_l,
1154                                channel, 'L', val & 0xffff);
1155         skl_dram_get_dimm_info(dev_priv, &ch->dimm_s,
1156                                channel, 'S', val >> 16);
1157
1158         if (ch->dimm_l.size == 0 && ch->dimm_s.size == 0) {
1159                 DRM_DEBUG_KMS("CH%u not populated\n", channel);
1160                 return -EINVAL;
1161         }
1162
1163         if (ch->dimm_l.ranks == 2 || ch->dimm_s.ranks == 2)
1164                 ch->ranks = 2;
1165         else if (ch->dimm_l.ranks == 1 && ch->dimm_s.ranks == 1)
1166                 ch->ranks = 2;
1167         else
1168                 ch->ranks = 1;
1169
1170         ch->is_16gb_dimm =
1171                 skl_is_16gb_dimm(&ch->dimm_l) ||
1172                 skl_is_16gb_dimm(&ch->dimm_s);
1173
1174         DRM_DEBUG_KMS("CH%u ranks: %u, 16Gb DIMMs: %s\n",
1175                       channel, ch->ranks, yesno(ch->is_16gb_dimm));
1176
1177         return 0;
1178 }
1179
1180 static bool
1181 intel_is_dram_symmetric(const struct dram_channel_info *ch0,
1182                         const struct dram_channel_info *ch1)
1183 {
1184         return !memcmp(ch0, ch1, sizeof(*ch0)) &&
1185                 (ch0->dimm_s.size == 0 ||
1186                  !memcmp(&ch0->dimm_l, &ch0->dimm_s, sizeof(ch0->dimm_l)));
1187 }
1188
1189 static int
1190 skl_dram_get_channels_info(struct drm_i915_private *dev_priv)
1191 {
1192         struct dram_info *dram_info = &dev_priv->dram_info;
1193         struct dram_channel_info ch0 = {}, ch1 = {};
1194         u32 val;
1195         int ret;
1196
1197         val = I915_READ(SKL_MAD_DIMM_CH0_0_0_0_MCHBAR_MCMAIN);
1198         ret = skl_dram_get_channel_info(dev_priv, &ch0, 0, val);
1199         if (ret == 0)
1200                 dram_info->num_channels++;
1201
1202         val = I915_READ(SKL_MAD_DIMM_CH1_0_0_0_MCHBAR_MCMAIN);
1203         ret = skl_dram_get_channel_info(dev_priv, &ch1, 1, val);
1204         if (ret == 0)
1205                 dram_info->num_channels++;
1206
1207         if (dram_info->num_channels == 0) {
1208                 DRM_INFO("Number of memory channels is zero\n");
1209                 return -EINVAL;
1210         }
1211
1212         /*
1213          * If any of the channel is single rank channel, worst case output
1214          * will be same as if single rank memory, so consider single rank
1215          * memory.
1216          */
1217         if (ch0.ranks == 1 || ch1.ranks == 1)
1218                 dram_info->ranks = 1;
1219         else
1220                 dram_info->ranks = max(ch0.ranks, ch1.ranks);
1221
1222         if (dram_info->ranks == 0) {
1223                 DRM_INFO("couldn't get memory rank information\n");
1224                 return -EINVAL;
1225         }
1226
1227         dram_info->is_16gb_dimm = ch0.is_16gb_dimm || ch1.is_16gb_dimm;
1228
1229         dram_info->symmetric_memory = intel_is_dram_symmetric(&ch0, &ch1);
1230
1231         DRM_DEBUG_KMS("Memory configuration is symmetric? %s\n",
1232                       yesno(dram_info->symmetric_memory));
1233         return 0;
1234 }
1235
1236 static enum intel_dram_type
1237 skl_get_dram_type(struct drm_i915_private *dev_priv)
1238 {
1239         u32 val;
1240
1241         val = I915_READ(SKL_MAD_INTER_CHANNEL_0_0_0_MCHBAR_MCMAIN);
1242
1243         switch (val & SKL_DRAM_DDR_TYPE_MASK) {
1244         case SKL_DRAM_DDR_TYPE_DDR3:
1245                 return INTEL_DRAM_DDR3;
1246         case SKL_DRAM_DDR_TYPE_DDR4:
1247                 return INTEL_DRAM_DDR4;
1248         case SKL_DRAM_DDR_TYPE_LPDDR3:
1249                 return INTEL_DRAM_LPDDR3;
1250         case SKL_DRAM_DDR_TYPE_LPDDR4:
1251                 return INTEL_DRAM_LPDDR4;
1252         default:
1253                 MISSING_CASE(val);
1254                 return INTEL_DRAM_UNKNOWN;
1255         }
1256 }
1257
1258 static int
1259 skl_get_dram_info(struct drm_i915_private *dev_priv)
1260 {
1261         struct dram_info *dram_info = &dev_priv->dram_info;
1262         u32 mem_freq_khz, val;
1263         int ret;
1264
1265         dram_info->type = skl_get_dram_type(dev_priv);
1266         DRM_DEBUG_KMS("DRAM type: %s\n", intel_dram_type_str(dram_info->type));
1267
1268         ret = skl_dram_get_channels_info(dev_priv);
1269         if (ret)
1270                 return ret;
1271
1272         val = I915_READ(SKL_MC_BIOS_DATA_0_0_0_MCHBAR_PCU);
1273         mem_freq_khz = DIV_ROUND_UP((val & SKL_REQ_DATA_MASK) *
1274                                     SKL_MEMORY_FREQ_MULTIPLIER_HZ, 1000);
1275
1276         dram_info->bandwidth_kbps = dram_info->num_channels *
1277                                                         mem_freq_khz * 8;
1278
1279         if (dram_info->bandwidth_kbps == 0) {
1280                 DRM_INFO("Couldn't get system memory bandwidth\n");
1281                 return -EINVAL;
1282         }
1283
1284         dram_info->valid = true;
1285         return 0;
1286 }
1287
1288 /* Returns Gb per DRAM device */
1289 static int bxt_get_dimm_size(u32 val)
1290 {
1291         switch (val & BXT_DRAM_SIZE_MASK) {
1292         case BXT_DRAM_SIZE_4GBIT:
1293                 return 4;
1294         case BXT_DRAM_SIZE_6GBIT:
1295                 return 6;
1296         case BXT_DRAM_SIZE_8GBIT:
1297                 return 8;
1298         case BXT_DRAM_SIZE_12GBIT:
1299                 return 12;
1300         case BXT_DRAM_SIZE_16GBIT:
1301                 return 16;
1302         default:
1303                 MISSING_CASE(val);
1304                 return 0;
1305         }
1306 }
1307
1308 static int bxt_get_dimm_width(u32 val)
1309 {
1310         if (!bxt_get_dimm_size(val))
1311                 return 0;
1312
1313         val = (val & BXT_DRAM_WIDTH_MASK) >> BXT_DRAM_WIDTH_SHIFT;
1314
1315         return 8 << val;
1316 }
1317
1318 static int bxt_get_dimm_ranks(u32 val)
1319 {
1320         if (!bxt_get_dimm_size(val))
1321                 return 0;
1322
1323         switch (val & BXT_DRAM_RANK_MASK) {
1324         case BXT_DRAM_RANK_SINGLE:
1325                 return 1;
1326         case BXT_DRAM_RANK_DUAL:
1327                 return 2;
1328         default:
1329                 MISSING_CASE(val);
1330                 return 0;
1331         }
1332 }
1333
1334 static enum intel_dram_type bxt_get_dimm_type(u32 val)
1335 {
1336         if (!bxt_get_dimm_size(val))
1337                 return INTEL_DRAM_UNKNOWN;
1338
1339         switch (val & BXT_DRAM_TYPE_MASK) {
1340         case BXT_DRAM_TYPE_DDR3:
1341                 return INTEL_DRAM_DDR3;
1342         case BXT_DRAM_TYPE_LPDDR3:
1343                 return INTEL_DRAM_LPDDR3;
1344         case BXT_DRAM_TYPE_DDR4:
1345                 return INTEL_DRAM_DDR4;
1346         case BXT_DRAM_TYPE_LPDDR4:
1347                 return INTEL_DRAM_LPDDR4;
1348         default:
1349                 MISSING_CASE(val);
1350                 return INTEL_DRAM_UNKNOWN;
1351         }
1352 }
1353
1354 static void bxt_get_dimm_info(struct dram_dimm_info *dimm,
1355                               u32 val)
1356 {
1357         dimm->width = bxt_get_dimm_width(val);
1358         dimm->ranks = bxt_get_dimm_ranks(val);
1359
1360         /*
1361          * Size in register is Gb per DRAM device. Convert to total
1362          * GB to match the way we report this for non-LP platforms.
1363          */
1364         dimm->size = bxt_get_dimm_size(val) * intel_dimm_num_devices(dimm) / 8;
1365 }
1366
1367 static int
1368 bxt_get_dram_info(struct drm_i915_private *dev_priv)
1369 {
1370         struct dram_info *dram_info = &dev_priv->dram_info;
1371         u32 dram_channels;
1372         u32 mem_freq_khz, val;
1373         u8 num_active_channels;
1374         int i;
1375
1376         val = I915_READ(BXT_P_CR_MC_BIOS_REQ_0_0_0);
1377         mem_freq_khz = DIV_ROUND_UP((val & BXT_REQ_DATA_MASK) *
1378                                     BXT_MEMORY_FREQ_MULTIPLIER_HZ, 1000);
1379
1380         dram_channels = val & BXT_DRAM_CHANNEL_ACTIVE_MASK;
1381         num_active_channels = hweight32(dram_channels);
1382
1383         /* Each active bit represents 4-byte channel */
1384         dram_info->bandwidth_kbps = (mem_freq_khz * num_active_channels * 4);
1385
1386         if (dram_info->bandwidth_kbps == 0) {
1387                 DRM_INFO("Couldn't get system memory bandwidth\n");
1388                 return -EINVAL;
1389         }
1390
1391         /*
1392          * Now read each DUNIT8/9/10/11 to check the rank of each dimms.
1393          */
1394         for (i = BXT_D_CR_DRP0_DUNIT_START; i <= BXT_D_CR_DRP0_DUNIT_END; i++) {
1395                 struct dram_dimm_info dimm;
1396                 enum intel_dram_type type;
1397
1398                 val = I915_READ(BXT_D_CR_DRP0_DUNIT(i));
1399                 if (val == 0xFFFFFFFF)
1400                         continue;
1401
1402                 dram_info->num_channels++;
1403
1404                 bxt_get_dimm_info(&dimm, val);
1405                 type = bxt_get_dimm_type(val);
1406
1407                 WARN_ON(type != INTEL_DRAM_UNKNOWN &&
1408                         dram_info->type != INTEL_DRAM_UNKNOWN &&
1409                         dram_info->type != type);
1410
1411                 DRM_DEBUG_KMS("CH%u DIMM size: %u GB, width: X%u, ranks: %u, type: %s\n",
1412                               i - BXT_D_CR_DRP0_DUNIT_START,
1413                               dimm.size, dimm.width, dimm.ranks,
1414                               intel_dram_type_str(type));
1415
1416                 /*
1417                  * If any of the channel is single rank channel,
1418                  * worst case output will be same as if single rank
1419                  * memory, so consider single rank memory.
1420                  */
1421                 if (dram_info->ranks == 0)
1422                         dram_info->ranks = dimm.ranks;
1423                 else if (dimm.ranks == 1)
1424                         dram_info->ranks = 1;
1425
1426                 if (type != INTEL_DRAM_UNKNOWN)
1427                         dram_info->type = type;
1428         }
1429
1430         if (dram_info->type == INTEL_DRAM_UNKNOWN ||
1431             dram_info->ranks == 0) {
1432                 DRM_INFO("couldn't get memory information\n");
1433                 return -EINVAL;
1434         }
1435
1436         dram_info->valid = true;
1437         return 0;
1438 }
1439
1440 static void
1441 intel_get_dram_info(struct drm_i915_private *dev_priv)
1442 {
1443         struct dram_info *dram_info = &dev_priv->dram_info;
1444         int ret;
1445
1446         /*
1447          * Assume 16Gb DIMMs are present until proven otherwise.
1448          * This is only used for the level 0 watermark latency
1449          * w/a which does not apply to bxt/glk.
1450          */
1451         dram_info->is_16gb_dimm = !IS_GEN9_LP(dev_priv);
1452
1453         if (INTEL_GEN(dev_priv) < 9)
1454                 return;
1455
1456         if (IS_GEN9_LP(dev_priv))
1457                 ret = bxt_get_dram_info(dev_priv);
1458         else
1459                 ret = skl_get_dram_info(dev_priv);
1460         if (ret)
1461                 return;
1462
1463         DRM_DEBUG_KMS("DRAM bandwidth: %u kBps, channels: %u\n",
1464                       dram_info->bandwidth_kbps,
1465                       dram_info->num_channels);
1466
1467         DRM_DEBUG_KMS("DRAM ranks: %u, 16Gb DIMMs: %s\n",
1468                       dram_info->ranks, yesno(dram_info->is_16gb_dimm));
1469 }
1470
1471 static u32 gen9_edram_size_mb(struct drm_i915_private *dev_priv, u32 cap)
1472 {
1473         const unsigned int ways[8] = { 4, 8, 12, 16, 16, 16, 16, 16 };
1474         const unsigned int sets[4] = { 1, 1, 2, 2 };
1475
1476         return EDRAM_NUM_BANKS(cap) *
1477                 ways[EDRAM_WAYS_IDX(cap)] *
1478                 sets[EDRAM_SETS_IDX(cap)];
1479 }
1480
1481 static void edram_detect(struct drm_i915_private *dev_priv)
1482 {
1483         u32 edram_cap = 0;
1484
1485         if (!(IS_HASWELL(dev_priv) ||
1486               IS_BROADWELL(dev_priv) ||
1487               INTEL_GEN(dev_priv) >= 9))
1488                 return;
1489
1490         edram_cap = __raw_uncore_read32(&dev_priv->uncore, HSW_EDRAM_CAP);
1491
1492         /* NB: We can't write IDICR yet because we don't have gt funcs set up */
1493
1494         if (!(edram_cap & EDRAM_ENABLED))
1495                 return;
1496
1497         /*
1498          * The needed capability bits for size calculation are not there with
1499          * pre gen9 so return 128MB always.
1500          */
1501         if (INTEL_GEN(dev_priv) < 9)
1502                 dev_priv->edram_size_mb = 128;
1503         else
1504                 dev_priv->edram_size_mb =
1505                         gen9_edram_size_mb(dev_priv, edram_cap);
1506
1507         DRM_INFO("Found %uMB of eDRAM\n", dev_priv->edram_size_mb);
1508 }
1509
1510 /**
1511  * i915_driver_init_hw - setup state requiring device access
1512  * @dev_priv: device private
1513  *
1514  * Setup state that requires accessing the device, but doesn't require
1515  * exposing the driver via kernel internal or userspace interfaces.
1516  */
1517 static int i915_driver_init_hw(struct drm_i915_private *dev_priv)
1518 {
1519         struct pci_dev *pdev = dev_priv->drm.pdev;
1520         int ret;
1521
1522         if (i915_inject_load_failure())
1523                 return -ENODEV;
1524
1525         intel_device_info_runtime_init(dev_priv);
1526
1527         if (HAS_PPGTT(dev_priv)) {
1528                 if (intel_vgpu_active(dev_priv) &&
1529                     !intel_vgpu_has_full_ppgtt(dev_priv)) {
1530                         i915_report_error(dev_priv,
1531                                           "incompatible vGPU found, support for isolated ppGTT required\n");
1532                         return -ENXIO;
1533                 }
1534         }
1535
1536         if (HAS_EXECLISTS(dev_priv)) {
1537                 /*
1538                  * Older GVT emulation depends upon intercepting CSB mmio,
1539                  * which we no longer use, preferring to use the HWSP cache
1540                  * instead.
1541                  */
1542                 if (intel_vgpu_active(dev_priv) &&
1543                     !intel_vgpu_has_hwsp_emulation(dev_priv)) {
1544                         i915_report_error(dev_priv,
1545                                           "old vGPU host found, support for HWSP emulation required\n");
1546                         return -ENXIO;
1547                 }
1548         }
1549
1550         intel_sanitize_options(dev_priv);
1551
1552         /* needs to be done before ggtt probe */
1553         edram_detect(dev_priv);
1554
1555         i915_perf_init(dev_priv);
1556
1557         ret = i915_ggtt_probe_hw(dev_priv);
1558         if (ret)
1559                 goto err_perf;
1560
1561         /*
1562          * WARNING: Apparently we must kick fbdev drivers before vgacon,
1563          * otherwise the vga fbdev driver falls over.
1564          */
1565         ret = i915_kick_out_firmware_fb(dev_priv);
1566         if (ret) {
1567                 DRM_ERROR("failed to remove conflicting framebuffer drivers\n");
1568                 goto err_ggtt;
1569         }
1570
1571         ret = vga_remove_vgacon(pdev);
1572         if (ret) {
1573                 DRM_ERROR("failed to remove conflicting VGA console\n");
1574                 goto err_ggtt;
1575         }
1576
1577         ret = i915_ggtt_init_hw(dev_priv);
1578         if (ret)
1579                 goto err_ggtt;
1580
1581         ret = i915_ggtt_enable_hw(dev_priv);
1582         if (ret) {
1583                 DRM_ERROR("failed to enable GGTT\n");
1584                 goto err_ggtt;
1585         }
1586
1587         pci_set_master(pdev);
1588
1589         /* overlay on gen2 is broken and can't address above 1G */
1590         if (IS_GEN(dev_priv, 2)) {
1591                 ret = dma_set_coherent_mask(&pdev->dev, DMA_BIT_MASK(30));
1592                 if (ret) {
1593                         DRM_ERROR("failed to set DMA mask\n");
1594
1595                         goto err_ggtt;
1596                 }
1597         }
1598
1599         /* 965GM sometimes incorrectly writes to hardware status page (HWS)
1600          * using 32bit addressing, overwriting memory if HWS is located
1601          * above 4GB.
1602          *
1603          * The documentation also mentions an issue with undefined
1604          * behaviour if any general state is accessed within a page above 4GB,
1605          * which also needs to be handled carefully.
1606          */
1607         if (IS_I965G(dev_priv) || IS_I965GM(dev_priv)) {
1608                 ret = dma_set_coherent_mask(&pdev->dev, DMA_BIT_MASK(32));
1609
1610                 if (ret) {
1611                         DRM_ERROR("failed to set DMA mask\n");
1612
1613                         goto err_ggtt;
1614                 }
1615         }
1616
1617         pm_qos_add_request(&dev_priv->pm_qos, PM_QOS_CPU_DMA_LATENCY,
1618                            PM_QOS_DEFAULT_VALUE);
1619
1620         intel_uncore_sanitize(dev_priv);
1621
1622         intel_gt_init_workarounds(dev_priv);
1623         i915_gem_load_init_fences(dev_priv);
1624
1625         /* On the 945G/GM, the chipset reports the MSI capability on the
1626          * integrated graphics even though the support isn't actually there
1627          * according to the published specs.  It doesn't appear to function
1628          * correctly in testing on 945G.
1629          * This may be a side effect of MSI having been made available for PEG
1630          * and the registers being closely associated.
1631          *
1632          * According to chipset errata, on the 965GM, MSI interrupts may
1633          * be lost or delayed, and was defeatured. MSI interrupts seem to
1634          * get lost on g4x as well, and interrupt delivery seems to stay
1635          * properly dead afterwards. So we'll just disable them for all
1636          * pre-gen5 chipsets.
1637          *
1638          * dp aux and gmbus irq on gen4 seems to be able to generate legacy
1639          * interrupts even when in MSI mode. This results in spurious
1640          * interrupt warnings if the legacy irq no. is shared with another
1641          * device. The kernel then disables that interrupt source and so
1642          * prevents the other device from working properly.
1643          */
1644         if (INTEL_GEN(dev_priv) >= 5) {
1645                 if (pci_enable_msi(pdev) < 0)
1646                         DRM_DEBUG_DRIVER("can't enable MSI");
1647         }
1648
1649         ret = intel_gvt_init(dev_priv);
1650         if (ret)
1651                 goto err_msi;
1652
1653         intel_opregion_setup(dev_priv);
1654         /*
1655          * Fill the dram structure to get the system raw bandwidth and
1656          * dram info. This will be used for memory latency calculation.
1657          */
1658         intel_get_dram_info(dev_priv);
1659
1660
1661         return 0;
1662
1663 err_msi:
1664         if (pdev->msi_enabled)
1665                 pci_disable_msi(pdev);
1666         pm_qos_remove_request(&dev_priv->pm_qos);
1667 err_ggtt:
1668         i915_ggtt_cleanup_hw(dev_priv);
1669 err_perf:
1670         i915_perf_fini(dev_priv);
1671         return ret;
1672 }
1673
1674 /**
1675  * i915_driver_cleanup_hw - cleanup the setup done in i915_driver_init_hw()
1676  * @dev_priv: device private
1677  */
1678 static void i915_driver_cleanup_hw(struct drm_i915_private *dev_priv)
1679 {
1680         struct pci_dev *pdev = dev_priv->drm.pdev;
1681
1682         i915_perf_fini(dev_priv);
1683
1684         if (pdev->msi_enabled)
1685                 pci_disable_msi(pdev);
1686
1687         pm_qos_remove_request(&dev_priv->pm_qos);
1688         i915_ggtt_cleanup_hw(dev_priv);
1689 }
1690
1691 /**
1692  * i915_driver_register - register the driver with the rest of the system
1693  * @dev_priv: device private
1694  *
1695  * Perform any steps necessary to make the driver available via kernel
1696  * internal or userspace interfaces.
1697  */
1698 static void i915_driver_register(struct drm_i915_private *dev_priv)
1699 {
1700         struct drm_device *dev = &dev_priv->drm;
1701
1702         i915_gem_shrinker_register(dev_priv);
1703         i915_pmu_register(dev_priv);
1704
1705         /*
1706          * Notify a valid surface after modesetting,
1707          * when running inside a VM.
1708          */
1709         if (intel_vgpu_active(dev_priv))
1710                 I915_WRITE(vgtif_reg(display_ready), VGT_DRV_DISPLAY_READY);
1711
1712         /* Reveal our presence to userspace */
1713         if (drm_dev_register(dev, 0) == 0) {
1714                 i915_debugfs_register(dev_priv);
1715                 i915_setup_sysfs(dev_priv);
1716
1717                 /* Depends on sysfs having been initialized */
1718                 i915_perf_register(dev_priv);
1719         } else
1720                 DRM_ERROR("Failed to register driver for userspace access!\n");
1721
1722         if (HAS_DISPLAY(dev_priv)) {
1723                 /* Must be done after probing outputs */
1724                 intel_opregion_register(dev_priv);
1725                 acpi_video_register();
1726         }
1727
1728         if (IS_GEN(dev_priv, 5))
1729                 intel_gpu_ips_init(dev_priv);
1730
1731         intel_audio_init(dev_priv);
1732
1733         /*
1734          * Some ports require correctly set-up hpd registers for detection to
1735          * work properly (leading to ghost connected connector status), e.g. VGA
1736          * on gm45.  Hence we can only set up the initial fbdev config after hpd
1737          * irqs are fully enabled. We do it last so that the async config
1738          * cannot run before the connectors are registered.
1739          */
1740         intel_fbdev_initial_config_async(dev);
1741
1742         /*
1743          * We need to coordinate the hotplugs with the asynchronous fbdev
1744          * configuration, for which we use the fbdev->async_cookie.
1745          */
1746         if (HAS_DISPLAY(dev_priv))
1747                 drm_kms_helper_poll_init(dev);
1748
1749         intel_power_domains_enable(dev_priv);
1750         intel_runtime_pm_enable(dev_priv);
1751 }
1752
1753 /**
1754  * i915_driver_unregister - cleanup the registration done in i915_driver_regiser()
1755  * @dev_priv: device private
1756  */
1757 static void i915_driver_unregister(struct drm_i915_private *dev_priv)
1758 {
1759         intel_runtime_pm_disable(dev_priv);
1760         intel_power_domains_disable(dev_priv);
1761
1762         intel_fbdev_unregister(dev_priv);
1763         intel_audio_deinit(dev_priv);
1764
1765         /*
1766          * After flushing the fbdev (incl. a late async config which will
1767          * have delayed queuing of a hotplug event), then flush the hotplug
1768          * events.
1769          */
1770         drm_kms_helper_poll_fini(&dev_priv->drm);
1771
1772         intel_gpu_ips_teardown();
1773         acpi_video_unregister();
1774         intel_opregion_unregister(dev_priv);
1775
1776         i915_perf_unregister(dev_priv);
1777         i915_pmu_unregister(dev_priv);
1778
1779         i915_teardown_sysfs(dev_priv);
1780         drm_dev_unplug(&dev_priv->drm);
1781
1782         i915_gem_shrinker_unregister(dev_priv);
1783 }
1784
1785 static void i915_welcome_messages(struct drm_i915_private *dev_priv)
1786 {
1787         if (drm_debug & DRM_UT_DRIVER) {
1788                 struct drm_printer p = drm_debug_printer("i915 device info:");
1789
1790                 drm_printf(&p, "pciid=0x%04x rev=0x%02x platform=%s (subplatform=0x%x) gen=%i\n",
1791                            INTEL_DEVID(dev_priv),
1792                            INTEL_REVID(dev_priv),
1793                            intel_platform_name(INTEL_INFO(dev_priv)->platform),
1794                            intel_subplatform(RUNTIME_INFO(dev_priv),
1795                                              INTEL_INFO(dev_priv)->platform),
1796                            INTEL_GEN(dev_priv));
1797
1798                 intel_device_info_dump_flags(INTEL_INFO(dev_priv), &p);
1799                 intel_device_info_dump_runtime(RUNTIME_INFO(dev_priv), &p);
1800         }
1801
1802         if (IS_ENABLED(CONFIG_DRM_I915_DEBUG))
1803                 DRM_INFO("DRM_I915_DEBUG enabled\n");
1804         if (IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM))
1805                 DRM_INFO("DRM_I915_DEBUG_GEM enabled\n");
1806         if (IS_ENABLED(CONFIG_DRM_I915_DEBUG_RUNTIME_PM))
1807                 DRM_INFO("DRM_I915_DEBUG_RUNTIME_PM enabled\n");
1808 }
1809
1810 static struct drm_i915_private *
1811 i915_driver_create(struct pci_dev *pdev, const struct pci_device_id *ent)
1812 {
1813         const struct intel_device_info *match_info =
1814                 (struct intel_device_info *)ent->driver_data;
1815         struct intel_device_info *device_info;
1816         struct drm_i915_private *i915;
1817         int err;
1818
1819         i915 = kzalloc(sizeof(*i915), GFP_KERNEL);
1820         if (!i915)
1821                 return ERR_PTR(-ENOMEM);
1822
1823         err = drm_dev_init(&i915->drm, &driver, &pdev->dev);
1824         if (err) {
1825                 kfree(i915);
1826                 return ERR_PTR(err);
1827         }
1828
1829         i915->drm.pdev = pdev;
1830         i915->drm.dev_private = i915;
1831         pci_set_drvdata(pdev, &i915->drm);
1832
1833         /* Setup the write-once "constant" device info */
1834         device_info = mkwrite_device_info(i915);
1835         memcpy(device_info, match_info, sizeof(*device_info));
1836         RUNTIME_INFO(i915)->device_id = pdev->device;
1837
1838         BUG_ON(device_info->gen > BITS_PER_TYPE(device_info->gen_mask));
1839
1840         return i915;
1841 }
1842
1843 static void i915_driver_destroy(struct drm_i915_private *i915)
1844 {
1845         struct pci_dev *pdev = i915->drm.pdev;
1846
1847         drm_dev_fini(&i915->drm);
1848         kfree(i915);
1849
1850         /* And make sure we never chase our dangling pointer from pci_dev */
1851         pci_set_drvdata(pdev, NULL);
1852 }
1853
1854 /**
1855  * i915_driver_load - setup chip and create an initial config
1856  * @pdev: PCI device
1857  * @ent: matching PCI ID entry
1858  *
1859  * The driver load routine has to do several things:
1860  *   - drive output discovery via intel_modeset_init()
1861  *   - initialize the memory manager
1862  *   - allocate initial config memory
1863  *   - setup the DRM framebuffer with the allocated memory
1864  */
1865 int i915_driver_load(struct pci_dev *pdev, const struct pci_device_id *ent)
1866 {
1867         const struct intel_device_info *match_info =
1868                 (struct intel_device_info *)ent->driver_data;
1869         struct drm_i915_private *dev_priv;
1870         int ret;
1871
1872         dev_priv = i915_driver_create(pdev, ent);
1873         if (IS_ERR(dev_priv))
1874                 return PTR_ERR(dev_priv);
1875
1876         /* Disable nuclear pageflip by default on pre-ILK */
1877         if (!i915_modparams.nuclear_pageflip && match_info->gen < 5)
1878                 dev_priv->drm.driver_features &= ~DRIVER_ATOMIC;
1879
1880         ret = pci_enable_device(pdev);
1881         if (ret)
1882                 goto out_fini;
1883
1884         ret = i915_driver_init_early(dev_priv);
1885         if (ret < 0)
1886                 goto out_pci_disable;
1887
1888         disable_rpm_wakeref_asserts(dev_priv);
1889
1890         ret = i915_driver_init_mmio(dev_priv);
1891         if (ret < 0)
1892                 goto out_runtime_pm_put;
1893
1894         ret = i915_driver_init_hw(dev_priv);
1895         if (ret < 0)
1896                 goto out_cleanup_mmio;
1897
1898         ret = i915_load_modeset_init(&dev_priv->drm);
1899         if (ret < 0)
1900                 goto out_cleanup_hw;
1901
1902         i915_driver_register(dev_priv);
1903
1904         enable_rpm_wakeref_asserts(dev_priv);
1905
1906         i915_welcome_messages(dev_priv);
1907
1908         return 0;
1909
1910 out_cleanup_hw:
1911         i915_driver_cleanup_hw(dev_priv);
1912 out_cleanup_mmio:
1913         i915_driver_cleanup_mmio(dev_priv);
1914 out_runtime_pm_put:
1915         enable_rpm_wakeref_asserts(dev_priv);
1916         i915_driver_cleanup_early(dev_priv);
1917 out_pci_disable:
1918         pci_disable_device(pdev);
1919 out_fini:
1920         i915_load_error(dev_priv, "Device initialization failed (%d)\n", ret);
1921         i915_driver_destroy(dev_priv);
1922         return ret;
1923 }
1924
1925 void i915_driver_unload(struct drm_device *dev)
1926 {
1927         struct drm_i915_private *dev_priv = to_i915(dev);
1928         struct pci_dev *pdev = dev_priv->drm.pdev;
1929
1930         disable_rpm_wakeref_asserts(dev_priv);
1931
1932         i915_driver_unregister(dev_priv);
1933
1934         /*
1935          * After unregistering the device to prevent any new users, cancel
1936          * all in-flight requests so that we can quickly unbind the active
1937          * resources.
1938          */
1939         i915_gem_set_wedged(dev_priv);
1940
1941         /* Flush any external code that still may be under the RCU lock */
1942         synchronize_rcu();
1943
1944         i915_gem_suspend(dev_priv);
1945
1946         drm_atomic_helper_shutdown(dev);
1947
1948         intel_gvt_cleanup(dev_priv);
1949
1950         intel_modeset_cleanup(dev);
1951
1952         intel_bios_cleanup(dev_priv);
1953
1954         vga_switcheroo_unregister_client(pdev);
1955         vga_client_register(pdev, NULL, NULL, NULL);
1956
1957         intel_csr_ucode_fini(dev_priv);
1958
1959         /* Free error state after interrupts are fully disabled. */
1960         cancel_delayed_work_sync(&dev_priv->gpu_error.hangcheck_work);
1961         i915_reset_error_state(dev_priv);
1962
1963         i915_gem_fini(dev_priv);
1964
1965         intel_power_domains_fini_hw(dev_priv);
1966
1967         i915_driver_cleanup_hw(dev_priv);
1968         i915_driver_cleanup_mmio(dev_priv);
1969
1970         enable_rpm_wakeref_asserts(dev_priv);
1971         intel_runtime_pm_cleanup(dev_priv);
1972 }
1973
1974 static void i915_driver_release(struct drm_device *dev)
1975 {
1976         struct drm_i915_private *dev_priv = to_i915(dev);
1977
1978         i915_driver_cleanup_early(dev_priv);
1979         i915_driver_destroy(dev_priv);
1980 }
1981
1982 static int i915_driver_open(struct drm_device *dev, struct drm_file *file)
1983 {
1984         struct drm_i915_private *i915 = to_i915(dev);
1985         int ret;
1986
1987         ret = i915_gem_open(i915, file);
1988         if (ret)
1989                 return ret;
1990
1991         return 0;
1992 }
1993
1994 /**
1995  * i915_driver_lastclose - clean up after all DRM clients have exited
1996  * @dev: DRM device
1997  *
1998  * Take care of cleaning up after all DRM clients have exited.  In the
1999  * mode setting case, we want to restore the kernel's initial mode (just
2000  * in case the last client left us in a bad state).
2001  *
2002  * Additionally, in the non-mode setting case, we'll tear down the GTT
2003  * and DMA structures, since the kernel won't be using them, and clea
2004  * up any GEM state.
2005  */
2006 static void i915_driver_lastclose(struct drm_device *dev)
2007 {
2008         intel_fbdev_restore_mode(dev);
2009         vga_switcheroo_process_delayed_switch();
2010 }
2011
2012 static void i915_driver_postclose(struct drm_device *dev, struct drm_file *file)
2013 {
2014         struct drm_i915_file_private *file_priv = file->driver_priv;
2015
2016         mutex_lock(&dev->struct_mutex);
2017         i915_gem_context_close(file);
2018         i915_gem_release(dev, file);
2019         mutex_unlock(&dev->struct_mutex);
2020
2021         kfree(file_priv);
2022 }
2023
2024 static void intel_suspend_encoders(struct drm_i915_private *dev_priv)
2025 {
2026         struct drm_device *dev = &dev_priv->drm;
2027         struct intel_encoder *encoder;
2028
2029         drm_modeset_lock_all(dev);
2030         for_each_intel_encoder(dev, encoder)
2031                 if (encoder->suspend)
2032                         encoder->suspend(encoder);
2033         drm_modeset_unlock_all(dev);
2034 }
2035
2036 static int vlv_resume_prepare(struct drm_i915_private *dev_priv,
2037                               bool rpm_resume);
2038 static int vlv_suspend_complete(struct drm_i915_private *dev_priv);
2039
2040 static bool suspend_to_idle(struct drm_i915_private *dev_priv)
2041 {
2042 #if IS_ENABLED(CONFIG_ACPI_SLEEP)
2043         if (acpi_target_system_state() < ACPI_STATE_S3)
2044                 return true;
2045 #endif
2046         return false;
2047 }
2048
2049 static int i915_drm_prepare(struct drm_device *dev)
2050 {
2051         struct drm_i915_private *i915 = to_i915(dev);
2052
2053         /*
2054          * NB intel_display_suspend() may issue new requests after we've
2055          * ostensibly marked the GPU as ready-to-sleep here. We need to
2056          * split out that work and pull it forward so that after point,
2057          * the GPU is not woken again.
2058          */
2059         i915_gem_suspend(i915);
2060
2061         return 0;
2062 }
2063
2064 static int i915_drm_suspend(struct drm_device *dev)
2065 {
2066         struct drm_i915_private *dev_priv = to_i915(dev);
2067         struct pci_dev *pdev = dev_priv->drm.pdev;
2068         pci_power_t opregion_target_state;
2069
2070         disable_rpm_wakeref_asserts(dev_priv);
2071
2072         /* We do a lot of poking in a lot of registers, make sure they work
2073          * properly. */
2074         intel_power_domains_disable(dev_priv);
2075
2076         drm_kms_helper_poll_disable(dev);
2077
2078         pci_save_state(pdev);
2079
2080         intel_display_suspend(dev);
2081
2082         intel_dp_mst_suspend(dev_priv);
2083
2084         intel_runtime_pm_disable_interrupts(dev_priv);
2085         intel_hpd_cancel_work(dev_priv);
2086
2087         intel_suspend_encoders(dev_priv);
2088
2089         intel_suspend_hw(dev_priv);
2090
2091         i915_gem_suspend_gtt_mappings(dev_priv);
2092
2093         i915_save_state(dev_priv);
2094
2095         opregion_target_state = suspend_to_idle(dev_priv) ? PCI_D1 : PCI_D3cold;
2096         intel_opregion_suspend(dev_priv, opregion_target_state);
2097
2098         intel_fbdev_set_suspend(dev, FBINFO_STATE_SUSPENDED, true);
2099
2100         dev_priv->suspend_count++;
2101
2102         intel_csr_ucode_suspend(dev_priv);
2103
2104         enable_rpm_wakeref_asserts(dev_priv);
2105
2106         return 0;
2107 }
2108
2109 static enum i915_drm_suspend_mode
2110 get_suspend_mode(struct drm_i915_private *dev_priv, bool hibernate)
2111 {
2112         if (hibernate)
2113                 return I915_DRM_SUSPEND_HIBERNATE;
2114
2115         if (suspend_to_idle(dev_priv))
2116                 return I915_DRM_SUSPEND_IDLE;
2117
2118         return I915_DRM_SUSPEND_MEM;
2119 }
2120
2121 static int i915_drm_suspend_late(struct drm_device *dev, bool hibernation)
2122 {
2123         struct drm_i915_private *dev_priv = to_i915(dev);
2124         struct pci_dev *pdev = dev_priv->drm.pdev;
2125         int ret;
2126
2127         disable_rpm_wakeref_asserts(dev_priv);
2128
2129         i915_gem_suspend_late(dev_priv);
2130
2131         intel_uncore_suspend(&dev_priv->uncore);
2132
2133         intel_power_domains_suspend(dev_priv,
2134                                     get_suspend_mode(dev_priv, hibernation));
2135
2136         ret = 0;
2137         if (INTEL_GEN(dev_priv) >= 11 || IS_GEN9_LP(dev_priv))
2138                 bxt_enable_dc9(dev_priv);
2139         else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv))
2140                 hsw_enable_pc8(dev_priv);
2141         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2142                 ret = vlv_suspend_complete(dev_priv);
2143
2144         if (ret) {
2145                 DRM_ERROR("Suspend complete failed: %d\n", ret);
2146                 intel_power_domains_resume(dev_priv);
2147
2148                 goto out;
2149         }
2150
2151         pci_disable_device(pdev);
2152         /*
2153          * During hibernation on some platforms the BIOS may try to access
2154          * the device even though it's already in D3 and hang the machine. So
2155          * leave the device in D0 on those platforms and hope the BIOS will
2156          * power down the device properly. The issue was seen on multiple old
2157          * GENs with different BIOS vendors, so having an explicit blacklist
2158          * is inpractical; apply the workaround on everything pre GEN6. The
2159          * platforms where the issue was seen:
2160          * Lenovo Thinkpad X301, X61s, X60, T60, X41
2161          * Fujitsu FSC S7110
2162          * Acer Aspire 1830T
2163          */
2164         if (!(hibernation && INTEL_GEN(dev_priv) < 6))
2165                 pci_set_power_state(pdev, PCI_D3hot);
2166
2167 out:
2168         enable_rpm_wakeref_asserts(dev_priv);
2169         if (!dev_priv->uncore.user_forcewake.count)
2170                 intel_runtime_pm_cleanup(dev_priv);
2171
2172         return ret;
2173 }
2174
2175 static int i915_suspend_switcheroo(struct drm_device *dev, pm_message_t state)
2176 {
2177         int error;
2178
2179         if (!dev) {
2180                 DRM_ERROR("dev: %p\n", dev);
2181                 DRM_ERROR("DRM not initialized, aborting suspend.\n");
2182                 return -ENODEV;
2183         }
2184
2185         if (WARN_ON_ONCE(state.event != PM_EVENT_SUSPEND &&
2186                          state.event != PM_EVENT_FREEZE))
2187                 return -EINVAL;
2188
2189         if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
2190                 return 0;
2191
2192         error = i915_drm_suspend(dev);
2193         if (error)
2194                 return error;
2195
2196         return i915_drm_suspend_late(dev, false);
2197 }
2198
2199 static int i915_drm_resume(struct drm_device *dev)
2200 {
2201         struct drm_i915_private *dev_priv = to_i915(dev);
2202         int ret;
2203
2204         disable_rpm_wakeref_asserts(dev_priv);
2205         intel_sanitize_gt_powersave(dev_priv);
2206
2207         i915_gem_sanitize(dev_priv);
2208
2209         ret = i915_ggtt_enable_hw(dev_priv);
2210         if (ret)
2211                 DRM_ERROR("failed to re-enable GGTT\n");
2212
2213         intel_csr_ucode_resume(dev_priv);
2214
2215         i915_restore_state(dev_priv);
2216         intel_pps_unlock_regs_wa(dev_priv);
2217
2218         intel_init_pch_refclk(dev_priv);
2219
2220         /*
2221          * Interrupts have to be enabled before any batches are run. If not the
2222          * GPU will hang. i915_gem_init_hw() will initiate batches to
2223          * update/restore the context.
2224          *
2225          * drm_mode_config_reset() needs AUX interrupts.
2226          *
2227          * Modeset enabling in intel_modeset_init_hw() also needs working
2228          * interrupts.
2229          */
2230         intel_runtime_pm_enable_interrupts(dev_priv);
2231
2232         drm_mode_config_reset(dev);
2233
2234         i915_gem_resume(dev_priv);
2235
2236         intel_modeset_init_hw(dev);
2237         intel_init_clock_gating(dev_priv);
2238
2239         spin_lock_irq(&dev_priv->irq_lock);
2240         if (dev_priv->display.hpd_irq_setup)
2241                 dev_priv->display.hpd_irq_setup(dev_priv);
2242         spin_unlock_irq(&dev_priv->irq_lock);
2243
2244         intel_dp_mst_resume(dev_priv);
2245
2246         intel_display_resume(dev);
2247
2248         drm_kms_helper_poll_enable(dev);
2249
2250         /*
2251          * ... but also need to make sure that hotplug processing
2252          * doesn't cause havoc. Like in the driver load code we don't
2253          * bother with the tiny race here where we might lose hotplug
2254          * notifications.
2255          * */
2256         intel_hpd_init(dev_priv);
2257
2258         intel_opregion_resume(dev_priv);
2259
2260         intel_fbdev_set_suspend(dev, FBINFO_STATE_RUNNING, false);
2261
2262         intel_power_domains_enable(dev_priv);
2263
2264         enable_rpm_wakeref_asserts(dev_priv);
2265
2266         return 0;
2267 }
2268
2269 static int i915_drm_resume_early(struct drm_device *dev)
2270 {
2271         struct drm_i915_private *dev_priv = to_i915(dev);
2272         struct pci_dev *pdev = dev_priv->drm.pdev;
2273         int ret;
2274
2275         /*
2276          * We have a resume ordering issue with the snd-hda driver also
2277          * requiring our device to be power up. Due to the lack of a
2278          * parent/child relationship we currently solve this with an early
2279          * resume hook.
2280          *
2281          * FIXME: This should be solved with a special hdmi sink device or
2282          * similar so that power domains can be employed.
2283          */
2284
2285         /*
2286          * Note that we need to set the power state explicitly, since we
2287          * powered off the device during freeze and the PCI core won't power
2288          * it back up for us during thaw. Powering off the device during
2289          * freeze is not a hard requirement though, and during the
2290          * suspend/resume phases the PCI core makes sure we get here with the
2291          * device powered on. So in case we change our freeze logic and keep
2292          * the device powered we can also remove the following set power state
2293          * call.
2294          */
2295         ret = pci_set_power_state(pdev, PCI_D0);
2296         if (ret) {
2297                 DRM_ERROR("failed to set PCI D0 power state (%d)\n", ret);
2298                 return ret;
2299         }
2300
2301         /*
2302          * Note that pci_enable_device() first enables any parent bridge
2303          * device and only then sets the power state for this device. The
2304          * bridge enabling is a nop though, since bridge devices are resumed
2305          * first. The order of enabling power and enabling the device is
2306          * imposed by the PCI core as described above, so here we preserve the
2307          * same order for the freeze/thaw phases.
2308          *
2309          * TODO: eventually we should remove pci_disable_device() /
2310          * pci_enable_enable_device() from suspend/resume. Due to how they
2311          * depend on the device enable refcount we can't anyway depend on them
2312          * disabling/enabling the device.
2313          */
2314         if (pci_enable_device(pdev))
2315                 return -EIO;
2316
2317         pci_set_master(pdev);
2318
2319         disable_rpm_wakeref_asserts(dev_priv);
2320
2321         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
2322                 ret = vlv_resume_prepare(dev_priv, false);
2323         if (ret)
2324                 DRM_ERROR("Resume prepare failed: %d, continuing anyway\n",
2325                           ret);
2326
2327         intel_uncore_resume_early(&dev_priv->uncore);
2328
2329         i915_check_and_clear_faults(dev_priv);
2330
2331         if (INTEL_GEN(dev_priv) >= 11 || IS_GEN9_LP(dev_priv)) {
2332                 gen9_sanitize_dc_state(dev_priv);
2333                 bxt_disable_dc9(dev_priv);
2334         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
2335                 hsw_disable_pc8(dev_priv);
2336         }
2337
2338         intel_uncore_sanitize(dev_priv);
2339
2340         intel_power_domains_resume(dev_priv);
2341
2342         intel_gt_sanitize(dev_priv, true);
2343
2344         enable_rpm_wakeref_asserts(dev_priv);
2345
2346         return ret;
2347 }
2348
2349 static int i915_resume_switcheroo(struct drm_device *dev)
2350 {
2351         int ret;
2352
2353         if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
2354                 return 0;
2355
2356         ret = i915_drm_resume_early(dev);
2357         if (ret)
2358                 return ret;
2359
2360         return i915_drm_resume(dev);
2361 }
2362
2363 static int i915_pm_prepare(struct device *kdev)
2364 {
2365         struct pci_dev *pdev = to_pci_dev(kdev);
2366         struct drm_device *dev = pci_get_drvdata(pdev);
2367
2368         if (!dev) {
2369                 dev_err(kdev, "DRM not initialized, aborting suspend.\n");
2370                 return -ENODEV;
2371         }
2372
2373         if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
2374                 return 0;
2375
2376         return i915_drm_prepare(dev);
2377 }
2378
2379 static int i915_pm_suspend(struct device *kdev)
2380 {
2381         struct pci_dev *pdev = to_pci_dev(kdev);
2382         struct drm_device *dev = pci_get_drvdata(pdev);
2383
2384         if (!dev) {
2385                 dev_err(kdev, "DRM not initialized, aborting suspend.\n");
2386                 return -ENODEV;
2387         }
2388
2389         if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
2390                 return 0;
2391
2392         return i915_drm_suspend(dev);
2393 }
2394
2395 static int i915_pm_suspend_late(struct device *kdev)
2396 {
2397         struct drm_device *dev = &kdev_to_i915(kdev)->drm;
2398
2399         /*
2400          * We have a suspend ordering issue with the snd-hda driver also
2401          * requiring our device to be power up. Due to the lack of a
2402          * parent/child relationship we currently solve this with an late
2403          * suspend hook.
2404          *
2405          * FIXME: This should be solved with a special hdmi sink device or
2406          * similar so that power domains can be employed.
2407          */
2408         if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
2409                 return 0;
2410
2411         return i915_drm_suspend_late(dev, false);
2412 }
2413
2414 static int i915_pm_poweroff_late(struct device *kdev)
2415 {
2416         struct drm_device *dev = &kdev_to_i915(kdev)->drm;
2417
2418         if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
2419                 return 0;
2420
2421         return i915_drm_suspend_late(dev, true);
2422 }
2423
2424 static int i915_pm_resume_early(struct device *kdev)
2425 {
2426         struct drm_device *dev = &kdev_to_i915(kdev)->drm;
2427
2428         if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
2429                 return 0;
2430
2431         return i915_drm_resume_early(dev);
2432 }
2433
2434 static int i915_pm_resume(struct device *kdev)
2435 {
2436         struct drm_device *dev = &kdev_to_i915(kdev)->drm;
2437
2438         if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
2439                 return 0;
2440
2441         return i915_drm_resume(dev);
2442 }
2443
2444 /* freeze: before creating the hibernation_image */
2445 static int i915_pm_freeze(struct device *kdev)
2446 {
2447         struct drm_device *dev = &kdev_to_i915(kdev)->drm;
2448         int ret;
2449
2450         if (dev->switch_power_state != DRM_SWITCH_POWER_OFF) {
2451                 ret = i915_drm_suspend(dev);
2452                 if (ret)
2453                         return ret;
2454         }
2455
2456         ret = i915_gem_freeze(kdev_to_i915(kdev));
2457         if (ret)
2458                 return ret;
2459
2460         return 0;
2461 }
2462
2463 static int i915_pm_freeze_late(struct device *kdev)
2464 {
2465         struct drm_device *dev = &kdev_to_i915(kdev)->drm;
2466         int ret;
2467
2468         if (dev->switch_power_state != DRM_SWITCH_POWER_OFF) {
2469                 ret = i915_drm_suspend_late(dev, true);
2470                 if (ret)
2471                         return ret;
2472         }
2473
2474         ret = i915_gem_freeze_late(kdev_to_i915(kdev));
2475         if (ret)
2476                 return ret;
2477
2478         return 0;
2479 }
2480
2481 /* thaw: called after creating the hibernation image, but before turning off. */
2482 static int i915_pm_thaw_early(struct device *kdev)
2483 {
2484         return i915_pm_resume_early(kdev);
2485 }
2486
2487 static int i915_pm_thaw(struct device *kdev)
2488 {
2489         return i915_pm_resume(kdev);
2490 }
2491
2492 /* restore: called after loading the hibernation image. */
2493 static int i915_pm_restore_early(struct device *kdev)
2494 {
2495         return i915_pm_resume_early(kdev);
2496 }
2497
2498 static int i915_pm_restore(struct device *kdev)
2499 {
2500         return i915_pm_resume(kdev);
2501 }
2502
2503 /*
2504  * Save all Gunit registers that may be lost after a D3 and a subsequent
2505  * S0i[R123] transition. The list of registers needing a save/restore is
2506  * defined in the VLV2_S0IXRegs document. This documents marks all Gunit
2507  * registers in the following way:
2508  * - Driver: saved/restored by the driver
2509  * - Punit : saved/restored by the Punit firmware
2510  * - No, w/o marking: no need to save/restore, since the register is R/O or
2511  *                    used internally by the HW in a way that doesn't depend
2512  *                    keeping the content across a suspend/resume.
2513  * - Debug : used for debugging
2514  *
2515  * We save/restore all registers marked with 'Driver', with the following
2516  * exceptions:
2517  * - Registers out of use, including also registers marked with 'Debug'.
2518  *   These have no effect on the driver's operation, so we don't save/restore
2519  *   them to reduce the overhead.
2520  * - Registers that are fully setup by an initialization function called from
2521  *   the resume path. For example many clock gating and RPS/RC6 registers.
2522  * - Registers that provide the right functionality with their reset defaults.
2523  *
2524  * TODO: Except for registers that based on the above 3 criteria can be safely
2525  * ignored, we save/restore all others, practically treating the HW context as
2526  * a black-box for the driver. Further investigation is needed to reduce the
2527  * saved/restored registers even further, by following the same 3 criteria.
2528  */
2529 static void vlv_save_gunit_s0ix_state(struct drm_i915_private *dev_priv)
2530 {
2531         struct vlv_s0ix_state *s = &dev_priv->vlv_s0ix_state;
2532         int i;
2533
2534         /* GAM 0x4000-0x4770 */
2535         s->wr_watermark         = I915_READ(GEN7_WR_WATERMARK);
2536         s->gfx_prio_ctrl        = I915_READ(GEN7_GFX_PRIO_CTRL);
2537         s->arb_mode             = I915_READ(ARB_MODE);
2538         s->gfx_pend_tlb0        = I915_READ(GEN7_GFX_PEND_TLB0);
2539         s->gfx_pend_tlb1        = I915_READ(GEN7_GFX_PEND_TLB1);
2540
2541         for (i = 0; i < ARRAY_SIZE(s->lra_limits); i++)
2542                 s->lra_limits[i] = I915_READ(GEN7_LRA_LIMITS(i));
2543
2544         s->media_max_req_count  = I915_READ(GEN7_MEDIA_MAX_REQ_COUNT);
2545         s->gfx_max_req_count    = I915_READ(GEN7_GFX_MAX_REQ_COUNT);
2546
2547         s->render_hwsp          = I915_READ(RENDER_HWS_PGA_GEN7);
2548         s->ecochk               = I915_READ(GAM_ECOCHK);
2549         s->bsd_hwsp             = I915_READ(BSD_HWS_PGA_GEN7);
2550         s->blt_hwsp             = I915_READ(BLT_HWS_PGA_GEN7);
2551
2552         s->tlb_rd_addr          = I915_READ(GEN7_TLB_RD_ADDR);
2553
2554         /* MBC 0x9024-0x91D0, 0x8500 */
2555         s->g3dctl               = I915_READ(VLV_G3DCTL);
2556         s->gsckgctl             = I915_READ(VLV_GSCKGCTL);
2557         s->mbctl                = I915_READ(GEN6_MBCTL);
2558
2559         /* GCP 0x9400-0x9424, 0x8100-0x810C */
2560         s->ucgctl1              = I915_READ(GEN6_UCGCTL1);
2561         s->ucgctl3              = I915_READ(GEN6_UCGCTL3);
2562         s->rcgctl1              = I915_READ(GEN6_RCGCTL1);
2563         s->rcgctl2              = I915_READ(GEN6_RCGCTL2);
2564         s->rstctl               = I915_READ(GEN6_RSTCTL);
2565         s->misccpctl            = I915_READ(GEN7_MISCCPCTL);
2566
2567         /* GPM 0xA000-0xAA84, 0x8000-0x80FC */
2568         s->gfxpause             = I915_READ(GEN6_GFXPAUSE);
2569         s->rpdeuhwtc            = I915_READ(GEN6_RPDEUHWTC);
2570         s->rpdeuc               = I915_READ(GEN6_RPDEUC);
2571         s->ecobus               = I915_READ(ECOBUS);
2572         s->pwrdwnupctl          = I915_READ(VLV_PWRDWNUPCTL);
2573         s->rp_down_timeout      = I915_READ(GEN6_RP_DOWN_TIMEOUT);
2574         s->rp_deucsw            = I915_READ(GEN6_RPDEUCSW);
2575         s->rcubmabdtmr          = I915_READ(GEN6_RCUBMABDTMR);
2576         s->rcedata              = I915_READ(VLV_RCEDATA);
2577         s->spare2gh             = I915_READ(VLV_SPAREG2H);
2578
2579         /* Display CZ domain, 0x4400C-0x4402C, 0x4F000-0x4F11F */
2580         s->gt_imr               = I915_READ(GTIMR);
2581         s->gt_ier               = I915_READ(GTIER);
2582         s->pm_imr               = I915_READ(GEN6_PMIMR);
2583         s->pm_ier               = I915_READ(GEN6_PMIER);
2584
2585         for (i = 0; i < ARRAY_SIZE(s->gt_scratch); i++)
2586                 s->gt_scratch[i] = I915_READ(GEN7_GT_SCRATCH(i));
2587
2588         /* GT SA CZ domain, 0x100000-0x138124 */
2589         s->tilectl              = I915_READ(TILECTL);
2590         s->gt_fifoctl           = I915_READ(GTFIFOCTL);
2591         s->gtlc_wake_ctrl       = I915_READ(VLV_GTLC_WAKE_CTRL);
2592         s->gtlc_survive         = I915_READ(VLV_GTLC_SURVIVABILITY_REG);
2593         s->pmwgicz              = I915_READ(VLV_PMWGICZ);
2594
2595         /* Gunit-Display CZ domain, 0x182028-0x1821CF */
2596         s->gu_ctl0              = I915_READ(VLV_GU_CTL0);
2597         s->gu_ctl1              = I915_READ(VLV_GU_CTL1);
2598         s->pcbr                 = I915_READ(VLV_PCBR);
2599         s->clock_gate_dis2      = I915_READ(VLV_GUNIT_CLOCK_GATE2);
2600
2601         /*
2602          * Not saving any of:
2603          * DFT,         0x9800-0x9EC0
2604          * SARB,        0xB000-0xB1FC
2605          * GAC,         0x5208-0x524C, 0x14000-0x14C000
2606          * PCI CFG
2607          */
2608 }
2609
2610 static void vlv_restore_gunit_s0ix_state(struct drm_i915_private *dev_priv)
2611 {
2612         struct vlv_s0ix_state *s = &dev_priv->vlv_s0ix_state;
2613         u32 val;
2614         int i;
2615
2616         /* GAM 0x4000-0x4770 */
2617         I915_WRITE(GEN7_WR_WATERMARK,   s->wr_watermark);
2618         I915_WRITE(GEN7_GFX_PRIO_CTRL,  s->gfx_prio_ctrl);
2619         I915_WRITE(ARB_MODE,            s->arb_mode | (0xffff << 16));
2620         I915_WRITE(GEN7_GFX_PEND_TLB0,  s->gfx_pend_tlb0);
2621         I915_WRITE(GEN7_GFX_PEND_TLB1,  s->gfx_pend_tlb1);
2622
2623         for (i = 0; i < ARRAY_SIZE(s->lra_limits); i++)
2624                 I915_WRITE(GEN7_LRA_LIMITS(i), s->lra_limits[i]);
2625
2626         I915_WRITE(GEN7_MEDIA_MAX_REQ_COUNT, s->media_max_req_count);
2627         I915_WRITE(GEN7_GFX_MAX_REQ_COUNT, s->gfx_max_req_count);
2628
2629         I915_WRITE(RENDER_HWS_PGA_GEN7, s->render_hwsp);
2630         I915_WRITE(GAM_ECOCHK,          s->ecochk);
2631         I915_WRITE(BSD_HWS_PGA_GEN7,    s->bsd_hwsp);
2632         I915_WRITE(BLT_HWS_PGA_GEN7,    s->blt_hwsp);
2633
2634         I915_WRITE(GEN7_TLB_RD_ADDR,    s->tlb_rd_addr);
2635
2636         /* MBC 0x9024-0x91D0, 0x8500 */
2637         I915_WRITE(VLV_G3DCTL,          s->g3dctl);
2638         I915_WRITE(VLV_GSCKGCTL,        s->gsckgctl);
2639         I915_WRITE(GEN6_MBCTL,          s->mbctl);
2640
2641         /* GCP 0x9400-0x9424, 0x8100-0x810C */
2642         I915_WRITE(GEN6_UCGCTL1,        s->ucgctl1);
2643         I915_WRITE(GEN6_UCGCTL3,        s->ucgctl3);
2644         I915_WRITE(GEN6_RCGCTL1,        s->rcgctl1);
2645         I915_WRITE(GEN6_RCGCTL2,        s->rcgctl2);
2646         I915_WRITE(GEN6_RSTCTL,         s->rstctl);
2647         I915_WRITE(GEN7_MISCCPCTL,      s->misccpctl);
2648
2649         /* GPM 0xA000-0xAA84, 0x8000-0x80FC */
2650         I915_WRITE(GEN6_GFXPAUSE,       s->gfxpause);
2651         I915_WRITE(GEN6_RPDEUHWTC,      s->rpdeuhwtc);
2652         I915_WRITE(GEN6_RPDEUC,         s->rpdeuc);
2653         I915_WRITE(ECOBUS,              s->ecobus);
2654         I915_WRITE(VLV_PWRDWNUPCTL,     s->pwrdwnupctl);
2655         I915_WRITE(GEN6_RP_DOWN_TIMEOUT,s->rp_down_timeout);
2656         I915_WRITE(GEN6_RPDEUCSW,       s->rp_deucsw);
2657         I915_WRITE(GEN6_RCUBMABDTMR,    s->rcubmabdtmr);
2658         I915_WRITE(VLV_RCEDATA,         s->rcedata);
2659         I915_WRITE(VLV_SPAREG2H,        s->spare2gh);
2660
2661         /* Display CZ domain, 0x4400C-0x4402C, 0x4F000-0x4F11F */
2662         I915_WRITE(GTIMR,               s->gt_imr);
2663         I915_WRITE(GTIER,               s->gt_ier);
2664         I915_WRITE(GEN6_PMIMR,          s->pm_imr);
2665         I915_WRITE(GEN6_PMIER,          s->pm_ier);
2666
2667         for (i = 0; i < ARRAY_SIZE(s->gt_scratch); i++)
2668                 I915_WRITE(GEN7_GT_SCRATCH(i), s->gt_scratch[i]);
2669
2670         /* GT SA CZ domain, 0x100000-0x138124 */
2671         I915_WRITE(TILECTL,                     s->tilectl);
2672         I915_WRITE(GTFIFOCTL,                   s->gt_fifoctl);
2673         /*
2674          * Preserve the GT allow wake and GFX force clock bit, they are not
2675          * be restored, as they are used to control the s0ix suspend/resume
2676          * sequence by the caller.
2677          */
2678         val = I915_READ(VLV_GTLC_WAKE_CTRL);
2679         val &= VLV_GTLC_ALLOWWAKEREQ;
2680         val |= s->gtlc_wake_ctrl & ~VLV_GTLC_ALLOWWAKEREQ;
2681         I915_WRITE(VLV_GTLC_WAKE_CTRL, val);
2682
2683         val = I915_READ(VLV_GTLC_SURVIVABILITY_REG);
2684         val &= VLV_GFX_CLK_FORCE_ON_BIT;
2685         val |= s->gtlc_survive & ~VLV_GFX_CLK_FORCE_ON_BIT;
2686         I915_WRITE(VLV_GTLC_SURVIVABILITY_REG, val);
2687
2688         I915_WRITE(VLV_PMWGICZ,                 s->pmwgicz);
2689
2690         /* Gunit-Display CZ domain, 0x182028-0x1821CF */
2691         I915_WRITE(VLV_GU_CTL0,                 s->gu_ctl0);
2692         I915_WRITE(VLV_GU_CTL1,                 s->gu_ctl1);
2693         I915_WRITE(VLV_PCBR,                    s->pcbr);
2694         I915_WRITE(VLV_GUNIT_CLOCK_GATE2,       s->clock_gate_dis2);
2695 }
2696
2697 static int vlv_wait_for_pw_status(struct drm_i915_private *dev_priv,
2698                                   u32 mask, u32 val)
2699 {
2700         i915_reg_t reg = VLV_GTLC_PW_STATUS;
2701         u32 reg_value;
2702         int ret;
2703
2704         /* The HW does not like us polling for PW_STATUS frequently, so
2705          * use the sleeping loop rather than risk the busy spin within
2706          * intel_wait_for_register().
2707          *
2708          * Transitioning between RC6 states should be at most 2ms (see
2709          * valleyview_enable_rps) so use a 3ms timeout.
2710          */
2711         ret = wait_for(((reg_value = I915_READ_NOTRACE(reg)) & mask) == val, 3);
2712
2713         /* just trace the final value */
2714         trace_i915_reg_rw(false, reg, reg_value, sizeof(reg_value), true);
2715
2716         return ret;
2717 }
2718
2719 int vlv_force_gfx_clock(struct drm_i915_private *dev_priv, bool force_on)
2720 {
2721         u32 val;
2722         int err;
2723
2724         val = I915_READ(VLV_GTLC_SURVIVABILITY_REG);
2725         val &= ~VLV_GFX_CLK_FORCE_ON_BIT;
2726         if (force_on)
2727                 val |= VLV_GFX_CLK_FORCE_ON_BIT;
2728         I915_WRITE(VLV_GTLC_SURVIVABILITY_REG, val);
2729
2730         if (!force_on)
2731                 return 0;
2732
2733         err = intel_wait_for_register(&dev_priv->uncore,
2734                                       VLV_GTLC_SURVIVABILITY_REG,
2735                                       VLV_GFX_CLK_STATUS_BIT,
2736                                       VLV_GFX_CLK_STATUS_BIT,
2737                                       20);
2738         if (err)
2739                 DRM_ERROR("timeout waiting for GFX clock force-on (%08x)\n",
2740                           I915_READ(VLV_GTLC_SURVIVABILITY_REG));
2741
2742         return err;
2743 }
2744
2745 static int vlv_allow_gt_wake(struct drm_i915_private *dev_priv, bool allow)
2746 {
2747         u32 mask;
2748         u32 val;
2749         int err;
2750
2751         val = I915_READ(VLV_GTLC_WAKE_CTRL);
2752         val &= ~VLV_GTLC_ALLOWWAKEREQ;
2753         if (allow)
2754                 val |= VLV_GTLC_ALLOWWAKEREQ;
2755         I915_WRITE(VLV_GTLC_WAKE_CTRL, val);
2756         POSTING_READ(VLV_GTLC_WAKE_CTRL);
2757
2758         mask = VLV_GTLC_ALLOWWAKEACK;
2759         val = allow ? mask : 0;
2760
2761         err = vlv_wait_for_pw_status(dev_priv, mask, val);
2762         if (err)
2763                 DRM_ERROR("timeout disabling GT waking\n");
2764
2765         return err;
2766 }
2767
2768 static void vlv_wait_for_gt_wells(struct drm_i915_private *dev_priv,
2769                                   bool wait_for_on)
2770 {
2771         u32 mask;
2772         u32 val;
2773
2774         mask = VLV_GTLC_PW_MEDIA_STATUS_MASK | VLV_GTLC_PW_RENDER_STATUS_MASK;
2775         val = wait_for_on ? mask : 0;
2776
2777         /*
2778          * RC6 transitioning can be delayed up to 2 msec (see
2779          * valleyview_enable_rps), use 3 msec for safety.
2780          *
2781          * This can fail to turn off the rc6 if the GPU is stuck after a failed
2782          * reset and we are trying to force the machine to sleep.
2783          */
2784         if (vlv_wait_for_pw_status(dev_priv, mask, val))
2785                 DRM_DEBUG_DRIVER("timeout waiting for GT wells to go %s\n",
2786                                  onoff(wait_for_on));
2787 }
2788
2789 static void vlv_check_no_gt_access(struct drm_i915_private *dev_priv)
2790 {
2791         if (!(I915_READ(VLV_GTLC_PW_STATUS) & VLV_GTLC_ALLOWWAKEERR))
2792                 return;
2793
2794         DRM_DEBUG_DRIVER("GT register access while GT waking disabled\n");
2795         I915_WRITE(VLV_GTLC_PW_STATUS, VLV_GTLC_ALLOWWAKEERR);
2796 }
2797
2798 static int vlv_suspend_complete(struct drm_i915_private *dev_priv)
2799 {
2800         u32 mask;
2801         int err;
2802
2803         /*
2804          * Bspec defines the following GT well on flags as debug only, so
2805          * don't treat them as hard failures.
2806          */
2807         vlv_wait_for_gt_wells(dev_priv, false);
2808
2809         mask = VLV_GTLC_RENDER_CTX_EXISTS | VLV_GTLC_MEDIA_CTX_EXISTS;
2810         WARN_ON((I915_READ(VLV_GTLC_WAKE_CTRL) & mask) != mask);
2811
2812         vlv_check_no_gt_access(dev_priv);
2813
2814         err = vlv_force_gfx_clock(dev_priv, true);
2815         if (err)
2816                 goto err1;
2817
2818         err = vlv_allow_gt_wake(dev_priv, false);
2819         if (err)
2820                 goto err2;
2821
2822         if (!IS_CHERRYVIEW(dev_priv))
2823                 vlv_save_gunit_s0ix_state(dev_priv);
2824
2825         err = vlv_force_gfx_clock(dev_priv, false);
2826         if (err)
2827                 goto err2;
2828
2829         return 0;
2830
2831 err2:
2832         /* For safety always re-enable waking and disable gfx clock forcing */
2833         vlv_allow_gt_wake(dev_priv, true);
2834 err1:
2835         vlv_force_gfx_clock(dev_priv, false);
2836
2837         return err;
2838 }
2839
2840 static int vlv_resume_prepare(struct drm_i915_private *dev_priv,
2841                                 bool rpm_resume)
2842 {
2843         int err;
2844         int ret;
2845
2846         /*
2847          * If any of the steps fail just try to continue, that's the best we
2848          * can do at this point. Return the first error code (which will also
2849          * leave RPM permanently disabled).
2850          */
2851         ret = vlv_force_gfx_clock(dev_priv, true);
2852
2853         if (!IS_CHERRYVIEW(dev_priv))
2854                 vlv_restore_gunit_s0ix_state(dev_priv);
2855
2856         err = vlv_allow_gt_wake(dev_priv, true);
2857         if (!ret)
2858                 ret = err;
2859
2860         err = vlv_force_gfx_clock(dev_priv, false);
2861         if (!ret)
2862                 ret = err;
2863
2864         vlv_check_no_gt_access(dev_priv);
2865
2866         if (rpm_resume)
2867                 intel_init_clock_gating(dev_priv);
2868
2869         return ret;
2870 }
2871
2872 static int intel_runtime_suspend(struct device *kdev)
2873 {
2874         struct pci_dev *pdev = to_pci_dev(kdev);
2875         struct drm_device *dev = pci_get_drvdata(pdev);
2876         struct drm_i915_private *dev_priv = to_i915(dev);
2877         int ret;
2878
2879         if (WARN_ON_ONCE(!(dev_priv->gt_pm.rc6.enabled && HAS_RC6(dev_priv))))
2880                 return -ENODEV;
2881
2882         if (WARN_ON_ONCE(!HAS_RUNTIME_PM(dev_priv)))
2883                 return -ENODEV;
2884
2885         DRM_DEBUG_KMS("Suspending device\n");
2886
2887         disable_rpm_wakeref_asserts(dev_priv);
2888
2889         /*
2890          * We are safe here against re-faults, since the fault handler takes
2891          * an RPM reference.
2892          */
2893         i915_gem_runtime_suspend(dev_priv);
2894
2895         intel_uc_runtime_suspend(dev_priv);
2896
2897         intel_runtime_pm_disable_interrupts(dev_priv);
2898
2899         intel_uncore_suspend(&dev_priv->uncore);
2900
2901         ret = 0;
2902         if (INTEL_GEN(dev_priv) >= 11) {
2903                 icl_display_core_uninit(dev_priv);
2904                 bxt_enable_dc9(dev_priv);
2905         } else if (IS_GEN9_LP(dev_priv)) {
2906                 bxt_display_core_uninit(dev_priv);
2907                 bxt_enable_dc9(dev_priv);
2908         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
2909                 hsw_enable_pc8(dev_priv);
2910         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
2911                 ret = vlv_suspend_complete(dev_priv);
2912         }
2913
2914         if (ret) {
2915                 DRM_ERROR("Runtime suspend failed, disabling it (%d)\n", ret);
2916                 intel_uncore_runtime_resume(&dev_priv->uncore);
2917
2918                 intel_runtime_pm_enable_interrupts(dev_priv);
2919
2920                 intel_uc_resume(dev_priv);
2921
2922                 i915_gem_init_swizzling(dev_priv);
2923                 i915_gem_restore_fences(dev_priv);
2924
2925                 enable_rpm_wakeref_asserts(dev_priv);
2926
2927                 return ret;
2928         }
2929
2930         enable_rpm_wakeref_asserts(dev_priv);
2931         intel_runtime_pm_cleanup(dev_priv);
2932
2933         if (intel_uncore_arm_unclaimed_mmio_detection(&dev_priv->uncore))
2934                 DRM_ERROR("Unclaimed access detected prior to suspending\n");
2935
2936         dev_priv->runtime_pm.suspended = true;
2937
2938         /*
2939          * FIXME: We really should find a document that references the arguments
2940          * used below!
2941          */
2942         if (IS_BROADWELL(dev_priv)) {
2943                 /*
2944                  * On Broadwell, if we use PCI_D1 the PCH DDI ports will stop
2945                  * being detected, and the call we do at intel_runtime_resume()
2946                  * won't be able to restore them. Since PCI_D3hot matches the
2947                  * actual specification and appears to be working, use it.
2948                  */
2949                 intel_opregion_notify_adapter(dev_priv, PCI_D3hot);
2950         } else {
2951                 /*
2952                  * current versions of firmware which depend on this opregion
2953                  * notification have repurposed the D1 definition to mean
2954                  * "runtime suspended" vs. what you would normally expect (D3)
2955                  * to distinguish it from notifications that might be sent via
2956                  * the suspend path.
2957                  */
2958                 intel_opregion_notify_adapter(dev_priv, PCI_D1);
2959         }
2960
2961         assert_forcewakes_inactive(&dev_priv->uncore);
2962
2963         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv))
2964                 intel_hpd_poll_init(dev_priv);
2965
2966         DRM_DEBUG_KMS("Device suspended\n");
2967         return 0;
2968 }
2969
2970 static int intel_runtime_resume(struct device *kdev)
2971 {
2972         struct pci_dev *pdev = to_pci_dev(kdev);
2973         struct drm_device *dev = pci_get_drvdata(pdev);
2974         struct drm_i915_private *dev_priv = to_i915(dev);
2975         int ret = 0;
2976
2977         if (WARN_ON_ONCE(!HAS_RUNTIME_PM(dev_priv)))
2978                 return -ENODEV;
2979
2980         DRM_DEBUG_KMS("Resuming device\n");
2981
2982         WARN_ON_ONCE(atomic_read(&dev_priv->runtime_pm.wakeref_count));
2983         disable_rpm_wakeref_asserts(dev_priv);
2984
2985         intel_opregion_notify_adapter(dev_priv, PCI_D0);
2986         dev_priv->runtime_pm.suspended = false;
2987         if (intel_uncore_unclaimed_mmio(&dev_priv->uncore))
2988                 DRM_DEBUG_DRIVER("Unclaimed access during suspend, bios?\n");
2989
2990         if (INTEL_GEN(dev_priv) >= 11) {
2991                 bxt_disable_dc9(dev_priv);
2992                 icl_display_core_init(dev_priv, true);
2993                 if (dev_priv->csr.dmc_payload) {
2994                         if (dev_priv->csr.allowed_dc_mask &
2995                             DC_STATE_EN_UPTO_DC6)
2996                                 skl_enable_dc6(dev_priv);
2997                         else if (dev_priv->csr.allowed_dc_mask &
2998                                  DC_STATE_EN_UPTO_DC5)
2999                                 gen9_enable_dc5(dev_priv);
3000                 }
3001         } else if (IS_GEN9_LP(dev_priv)) {
3002                 bxt_disable_dc9(dev_priv);
3003                 bxt_display_core_init(dev_priv, true);
3004                 if (dev_priv->csr.dmc_payload &&
3005                     (dev_priv->csr.allowed_dc_mask & DC_STATE_EN_UPTO_DC5))
3006                         gen9_enable_dc5(dev_priv);
3007         } else if (IS_HASWELL(dev_priv) || IS_BROADWELL(dev_priv)) {
3008                 hsw_disable_pc8(dev_priv);
3009         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
3010                 ret = vlv_resume_prepare(dev_priv, true);
3011         }
3012
3013         intel_uncore_runtime_resume(&dev_priv->uncore);
3014
3015         intel_runtime_pm_enable_interrupts(dev_priv);
3016
3017         intel_uc_resume(dev_priv);
3018
3019         /*
3020          * No point of rolling back things in case of an error, as the best
3021          * we can do is to hope that things will still work (and disable RPM).
3022          */
3023         i915_gem_init_swizzling(dev_priv);
3024         i915_gem_restore_fences(dev_priv);
3025
3026         /*
3027          * On VLV/CHV display interrupts are part of the display
3028          * power well, so hpd is reinitialized from there. For
3029          * everyone else do it here.
3030          */
3031         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv))
3032                 intel_hpd_init(dev_priv);
3033
3034         intel_enable_ipc(dev_priv);
3035
3036         enable_rpm_wakeref_asserts(dev_priv);
3037
3038         if (ret)
3039                 DRM_ERROR("Runtime resume failed, disabling it (%d)\n", ret);
3040         else
3041                 DRM_DEBUG_KMS("Device resumed\n");
3042
3043         return ret;
3044 }
3045
3046 const struct dev_pm_ops i915_pm_ops = {
3047         /*
3048          * S0ix (via system suspend) and S3 event handlers [PMSG_SUSPEND,
3049          * PMSG_RESUME]
3050          */
3051         .prepare = i915_pm_prepare,
3052         .suspend = i915_pm_suspend,
3053         .suspend_late = i915_pm_suspend_late,
3054         .resume_early = i915_pm_resume_early,
3055         .resume = i915_pm_resume,
3056
3057         /*
3058          * S4 event handlers
3059          * @freeze, @freeze_late    : called (1) before creating the
3060          *                            hibernation image [PMSG_FREEZE] and
3061          *                            (2) after rebooting, before restoring
3062          *                            the image [PMSG_QUIESCE]
3063          * @thaw, @thaw_early       : called (1) after creating the hibernation
3064          *                            image, before writing it [PMSG_THAW]
3065          *                            and (2) after failing to create or
3066          *                            restore the image [PMSG_RECOVER]
3067          * @poweroff, @poweroff_late: called after writing the hibernation
3068          *                            image, before rebooting [PMSG_HIBERNATE]
3069          * @restore, @restore_early : called after rebooting and restoring the
3070          *                            hibernation image [PMSG_RESTORE]
3071          */
3072         .freeze = i915_pm_freeze,
3073         .freeze_late = i915_pm_freeze_late,
3074         .thaw_early = i915_pm_thaw_early,
3075         .thaw = i915_pm_thaw,
3076         .poweroff = i915_pm_suspend,
3077         .poweroff_late = i915_pm_poweroff_late,
3078         .restore_early = i915_pm_restore_early,
3079         .restore = i915_pm_restore,
3080
3081         /* S0ix (via runtime suspend) event handlers */
3082         .runtime_suspend = intel_runtime_suspend,
3083         .runtime_resume = intel_runtime_resume,
3084 };
3085
3086 static const struct vm_operations_struct i915_gem_vm_ops = {
3087         .fault = i915_gem_fault,
3088         .open = drm_gem_vm_open,
3089         .close = drm_gem_vm_close,
3090 };
3091
3092 static const struct file_operations i915_driver_fops = {
3093         .owner = THIS_MODULE,
3094         .open = drm_open,
3095         .release = drm_release,
3096         .unlocked_ioctl = drm_ioctl,
3097         .mmap = drm_gem_mmap,
3098         .poll = drm_poll,
3099         .read = drm_read,
3100         .compat_ioctl = i915_compat_ioctl,
3101         .llseek = noop_llseek,
3102 };
3103
3104 static int
3105 i915_gem_reject_pin_ioctl(struct drm_device *dev, void *data,
3106                           struct drm_file *file)
3107 {
3108         return -ENODEV;
3109 }
3110
3111 static const struct drm_ioctl_desc i915_ioctls[] = {
3112         DRM_IOCTL_DEF_DRV(I915_INIT, drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
3113         DRM_IOCTL_DEF_DRV(I915_FLUSH, drm_noop, DRM_AUTH),
3114         DRM_IOCTL_DEF_DRV(I915_FLIP, drm_noop, DRM_AUTH),
3115         DRM_IOCTL_DEF_DRV(I915_BATCHBUFFER, drm_noop, DRM_AUTH),
3116         DRM_IOCTL_DEF_DRV(I915_IRQ_EMIT, drm_noop, DRM_AUTH),
3117         DRM_IOCTL_DEF_DRV(I915_IRQ_WAIT, drm_noop, DRM_AUTH),
3118         DRM_IOCTL_DEF_DRV(I915_GETPARAM, i915_getparam_ioctl, DRM_RENDER_ALLOW),
3119         DRM_IOCTL_DEF_DRV(I915_SETPARAM, drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
3120         DRM_IOCTL_DEF_DRV(I915_ALLOC, drm_noop, DRM_AUTH),
3121         DRM_IOCTL_DEF_DRV(I915_FREE, drm_noop, DRM_AUTH),
3122         DRM_IOCTL_DEF_DRV(I915_INIT_HEAP, drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
3123         DRM_IOCTL_DEF_DRV(I915_CMDBUFFER, drm_noop, DRM_AUTH),
3124         DRM_IOCTL_DEF_DRV(I915_DESTROY_HEAP,  drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
3125         DRM_IOCTL_DEF_DRV(I915_SET_VBLANK_PIPE,  drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
3126         DRM_IOCTL_DEF_DRV(I915_GET_VBLANK_PIPE,  drm_noop, DRM_AUTH),
3127         DRM_IOCTL_DEF_DRV(I915_VBLANK_SWAP, drm_noop, DRM_AUTH),
3128         DRM_IOCTL_DEF_DRV(I915_HWS_ADDR, drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
3129         DRM_IOCTL_DEF_DRV(I915_GEM_INIT, drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
3130         DRM_IOCTL_DEF_DRV(I915_GEM_EXECBUFFER, i915_gem_execbuffer_ioctl, DRM_AUTH),
3131         DRM_IOCTL_DEF_DRV(I915_GEM_EXECBUFFER2_WR, i915_gem_execbuffer2_ioctl, DRM_RENDER_ALLOW),
3132         DRM_IOCTL_DEF_DRV(I915_GEM_PIN, i915_gem_reject_pin_ioctl, DRM_AUTH|DRM_ROOT_ONLY),
3133         DRM_IOCTL_DEF_DRV(I915_GEM_UNPIN, i915_gem_reject_pin_ioctl, DRM_AUTH|DRM_ROOT_ONLY),
3134         DRM_IOCTL_DEF_DRV(I915_GEM_BUSY, i915_gem_busy_ioctl, DRM_RENDER_ALLOW),
3135         DRM_IOCTL_DEF_DRV(I915_GEM_SET_CACHING, i915_gem_set_caching_ioctl, DRM_RENDER_ALLOW),
3136         DRM_IOCTL_DEF_DRV(I915_GEM_GET_CACHING, i915_gem_get_caching_ioctl, DRM_RENDER_ALLOW),
3137         DRM_IOCTL_DEF_DRV(I915_GEM_THROTTLE, i915_gem_throttle_ioctl, DRM_RENDER_ALLOW),
3138         DRM_IOCTL_DEF_DRV(I915_GEM_ENTERVT, drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
3139         DRM_IOCTL_DEF_DRV(I915_GEM_LEAVEVT, drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
3140         DRM_IOCTL_DEF_DRV(I915_GEM_CREATE, i915_gem_create_ioctl, DRM_RENDER_ALLOW),
3141         DRM_IOCTL_DEF_DRV(I915_GEM_PREAD, i915_gem_pread_ioctl, DRM_RENDER_ALLOW),
3142         DRM_IOCTL_DEF_DRV(I915_GEM_PWRITE, i915_gem_pwrite_ioctl, DRM_RENDER_ALLOW),
3143         DRM_IOCTL_DEF_DRV(I915_GEM_MMAP, i915_gem_mmap_ioctl, DRM_RENDER_ALLOW),
3144         DRM_IOCTL_DEF_DRV(I915_GEM_MMAP_GTT, i915_gem_mmap_gtt_ioctl, DRM_RENDER_ALLOW),
3145         DRM_IOCTL_DEF_DRV(I915_GEM_SET_DOMAIN, i915_gem_set_domain_ioctl, DRM_RENDER_ALLOW),
3146         DRM_IOCTL_DEF_DRV(I915_GEM_SW_FINISH, i915_gem_sw_finish_ioctl, DRM_RENDER_ALLOW),
3147         DRM_IOCTL_DEF_DRV(I915_GEM_SET_TILING, i915_gem_set_tiling_ioctl, DRM_RENDER_ALLOW),
3148         DRM_IOCTL_DEF_DRV(I915_GEM_GET_TILING, i915_gem_get_tiling_ioctl, DRM_RENDER_ALLOW),
3149         DRM_IOCTL_DEF_DRV(I915_GEM_GET_APERTURE, i915_gem_get_aperture_ioctl, DRM_RENDER_ALLOW),
3150         DRM_IOCTL_DEF_DRV(I915_GET_PIPE_FROM_CRTC_ID, intel_get_pipe_from_crtc_id_ioctl, 0),
3151         DRM_IOCTL_DEF_DRV(I915_GEM_MADVISE, i915_gem_madvise_ioctl, DRM_RENDER_ALLOW),
3152         DRM_IOCTL_DEF_DRV(I915_OVERLAY_PUT_IMAGE, intel_overlay_put_image_ioctl, DRM_MASTER),
3153         DRM_IOCTL_DEF_DRV(I915_OVERLAY_ATTRS, intel_overlay_attrs_ioctl, DRM_MASTER),
3154         DRM_IOCTL_DEF_DRV(I915_SET_SPRITE_COLORKEY, intel_sprite_set_colorkey_ioctl, DRM_MASTER),
3155         DRM_IOCTL_DEF_DRV(I915_GET_SPRITE_COLORKEY, drm_noop, DRM_MASTER),
3156         DRM_IOCTL_DEF_DRV(I915_GEM_WAIT, i915_gem_wait_ioctl, DRM_RENDER_ALLOW),
3157         DRM_IOCTL_DEF_DRV(I915_GEM_CONTEXT_CREATE_EXT, i915_gem_context_create_ioctl, DRM_RENDER_ALLOW),
3158         DRM_IOCTL_DEF_DRV(I915_GEM_CONTEXT_DESTROY, i915_gem_context_destroy_ioctl, DRM_RENDER_ALLOW),
3159         DRM_IOCTL_DEF_DRV(I915_REG_READ, i915_reg_read_ioctl, DRM_RENDER_ALLOW),
3160         DRM_IOCTL_DEF_DRV(I915_GET_RESET_STATS, i915_gem_context_reset_stats_ioctl, DRM_RENDER_ALLOW),
3161         DRM_IOCTL_DEF_DRV(I915_GEM_USERPTR, i915_gem_userptr_ioctl, DRM_RENDER_ALLOW),
3162         DRM_IOCTL_DEF_DRV(I915_GEM_CONTEXT_GETPARAM, i915_gem_context_getparam_ioctl, DRM_RENDER_ALLOW),
3163         DRM_IOCTL_DEF_DRV(I915_GEM_CONTEXT_SETPARAM, i915_gem_context_setparam_ioctl, DRM_RENDER_ALLOW),
3164         DRM_IOCTL_DEF_DRV(I915_PERF_OPEN, i915_perf_open_ioctl, DRM_RENDER_ALLOW),
3165         DRM_IOCTL_DEF_DRV(I915_PERF_ADD_CONFIG, i915_perf_add_config_ioctl, DRM_UNLOCKED|DRM_RENDER_ALLOW),
3166         DRM_IOCTL_DEF_DRV(I915_PERF_REMOVE_CONFIG, i915_perf_remove_config_ioctl, DRM_UNLOCKED|DRM_RENDER_ALLOW),
3167         DRM_IOCTL_DEF_DRV(I915_QUERY, i915_query_ioctl, DRM_UNLOCKED|DRM_RENDER_ALLOW),
3168         DRM_IOCTL_DEF_DRV(I915_GEM_VM_CREATE, i915_gem_vm_create_ioctl, DRM_RENDER_ALLOW),
3169         DRM_IOCTL_DEF_DRV(I915_GEM_VM_DESTROY, i915_gem_vm_destroy_ioctl, DRM_RENDER_ALLOW),
3170 };
3171
3172 static struct drm_driver driver = {
3173         /* Don't use MTRRs here; the Xserver or userspace app should
3174          * deal with them for Intel hardware.
3175          */
3176         .driver_features =
3177             DRIVER_GEM | DRIVER_PRIME |
3178             DRIVER_RENDER | DRIVER_MODESET | DRIVER_ATOMIC | DRIVER_SYNCOBJ,
3179         .release = i915_driver_release,
3180         .open = i915_driver_open,
3181         .lastclose = i915_driver_lastclose,
3182         .postclose = i915_driver_postclose,
3183
3184         .gem_close_object = i915_gem_close_object,
3185         .gem_free_object_unlocked = i915_gem_free_object,
3186         .gem_vm_ops = &i915_gem_vm_ops,
3187
3188         .prime_handle_to_fd = drm_gem_prime_handle_to_fd,
3189         .prime_fd_to_handle = drm_gem_prime_fd_to_handle,
3190         .gem_prime_export = i915_gem_prime_export,
3191         .gem_prime_import = i915_gem_prime_import,
3192
3193         .dumb_create = i915_gem_dumb_create,
3194         .dumb_map_offset = i915_gem_mmap_gtt,
3195         .ioctls = i915_ioctls,
3196         .num_ioctls = ARRAY_SIZE(i915_ioctls),
3197         .fops = &i915_driver_fops,
3198         .name = DRIVER_NAME,
3199         .desc = DRIVER_DESC,
3200         .date = DRIVER_DATE,
3201         .major = DRIVER_MAJOR,
3202         .minor = DRIVER_MINOR,
3203         .patchlevel = DRIVER_PATCHLEVEL,
3204 };
3205
3206 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
3207 #include "selftests/mock_drm.c"
3208 #endif