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