python_code
stringlengths 0
1.8M
| repo_name
stringclasses 7
values | file_path
stringlengths 5
99
|
---|---|---|
/*
* Copyright 2008 Red Hat Inc.
* Copyright 2009 Jerome Glisse.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors:
* Dave Airlie
* Jerome Glisse <[email protected]>
*/
#include <linux/pci.h>
#include <drm/drm_device.h>
#include <drm/radeon_drm.h>
#include "radeon.h"
#if IS_ENABLED(CONFIG_AGP)
struct radeon_agpmode_quirk {
u32 hostbridge_vendor;
u32 hostbridge_device;
u32 chip_vendor;
u32 chip_device;
u32 subsys_vendor;
u32 subsys_device;
u32 default_mode;
};
static struct radeon_agpmode_quirk radeon_agpmode_quirk_list[] = {
/* Intel E7505 Memory Controller Hub / RV350 AR [Radeon 9600XT] Needs AGPMode 4 (deb #515326) */
{ PCI_VENDOR_ID_INTEL, 0x2550, PCI_VENDOR_ID_ATI, 0x4152, 0x1458, 0x4038, 4},
/* Intel 82865G/PE/P DRAM Controller/Host-Hub / Mobility 9800 Needs AGPMode 4 (deb #462590) */
{ PCI_VENDOR_ID_INTEL, 0x2570, PCI_VENDOR_ID_ATI, 0x4a4e, PCI_VENDOR_ID_DELL, 0x5106, 4},
/* Intel 82865G/PE/P DRAM Controller/Host-Hub / RV280 [Radeon 9200 SE] Needs AGPMode 4 (lp #300304) */
{ PCI_VENDOR_ID_INTEL, 0x2570, PCI_VENDOR_ID_ATI, 0x5964,
0x148c, 0x2073, 4},
/* Intel 82855PM Processor to I/O Controller / Mobility M6 LY Needs AGPMode 1 (deb #467235) */
{ PCI_VENDOR_ID_INTEL, 0x3340, PCI_VENDOR_ID_ATI, 0x4c59,
PCI_VENDOR_ID_IBM, 0x052f, 1},
/* Intel 82855PM host bridge / Mobility 9600 M10 RV350 Needs AGPMode 1 (lp #195051) */
{ PCI_VENDOR_ID_INTEL, 0x3340, PCI_VENDOR_ID_ATI, 0x4e50,
PCI_VENDOR_ID_IBM, 0x0550, 1},
/* Intel 82855PM host bridge / RV250/M9 GL [Mobility FireGL 9000/Radeon 9000] needs AGPMode 1 (Thinkpad T40p) */
{ PCI_VENDOR_ID_INTEL, 0x3340, PCI_VENDOR_ID_ATI, 0x4c66,
PCI_VENDOR_ID_IBM, 0x054d, 1},
/* Intel 82855PM host bridge / Mobility M7 needs AGPMode 1 */
{ PCI_VENDOR_ID_INTEL, 0x3340, PCI_VENDOR_ID_ATI, 0x4c57,
PCI_VENDOR_ID_IBM, 0x0530, 1},
/* Intel 82855PM host bridge / FireGL Mobility T2 RV350 Needs AGPMode 2 (fdo #20647) */
{ PCI_VENDOR_ID_INTEL, 0x3340, PCI_VENDOR_ID_ATI, 0x4e54,
PCI_VENDOR_ID_IBM, 0x054f, 2},
/* Intel 82855PM host bridge / Mobility M9+ / VaioPCG-V505DX Needs AGPMode 2 (fdo #17928) */
{ PCI_VENDOR_ID_INTEL, 0x3340, PCI_VENDOR_ID_ATI, 0x5c61,
PCI_VENDOR_ID_SONY, 0x816b, 2},
/* Intel 82855PM Processor to I/O Controller / Mobility M9+ Needs AGPMode 8 (phoronix forum) */
{ PCI_VENDOR_ID_INTEL, 0x3340, PCI_VENDOR_ID_ATI, 0x5c61,
PCI_VENDOR_ID_SONY, 0x8195, 8},
/* Intel 82830 830 Chipset Host Bridge / Mobility M6 LY Needs AGPMode 2 (fdo #17360)*/
{ PCI_VENDOR_ID_INTEL, 0x3575, PCI_VENDOR_ID_ATI, 0x4c59,
PCI_VENDOR_ID_DELL, 0x00e3, 2},
/* Intel 82852/82855 host bridge / Mobility FireGL 9000 RV250 Needs AGPMode 1 (lp #296617) */
{ PCI_VENDOR_ID_INTEL, 0x3580, PCI_VENDOR_ID_ATI, 0x4c66,
PCI_VENDOR_ID_DELL, 0x0149, 1},
/* Intel 82855PM host bridge / Mobility FireGL 9000 RV250 Needs AGPMode 1 for suspend/resume */
{ PCI_VENDOR_ID_INTEL, 0x3340, PCI_VENDOR_ID_ATI, 0x4c66,
PCI_VENDOR_ID_IBM, 0x0531, 1},
/* Intel 82852/82855 host bridge / Mobility 9600 M10 RV350 Needs AGPMode 1 (deb #467460) */
{ PCI_VENDOR_ID_INTEL, 0x3580, PCI_VENDOR_ID_ATI, 0x4e50,
0x1025, 0x0061, 1},
/* Intel 82852/82855 host bridge / Mobility 9600 M10 RV350 Needs AGPMode 1 (lp #203007) */
{ PCI_VENDOR_ID_INTEL, 0x3580, PCI_VENDOR_ID_ATI, 0x4e50,
0x1025, 0x0064, 1},
/* Intel 82852/82855 host bridge / Mobility 9600 M10 RV350 Needs AGPMode 1 (lp #141551) */
{ PCI_VENDOR_ID_INTEL, 0x3580, PCI_VENDOR_ID_ATI, 0x4e50,
PCI_VENDOR_ID_ASUSTEK, 0x1942, 1},
/* Intel 82852/82855 host bridge / Mobility 9600/9700 Needs AGPMode 1 (deb #510208) */
{ PCI_VENDOR_ID_INTEL, 0x3580, PCI_VENDOR_ID_ATI, 0x4e50,
0x10cf, 0x127f, 1},
/* ASRock K7VT4A+ AGP 8x / ATI Radeon 9250 AGP Needs AGPMode 4 (lp #133192) */
{ 0x1849, 0x3189, PCI_VENDOR_ID_ATI, 0x5960,
0x1787, 0x5960, 4},
/* VIA K8M800 Host Bridge / RV280 [Radeon 9200 PRO] Needs AGPMode 4 (fdo #12544) */
{ PCI_VENDOR_ID_VIA, 0x0204, PCI_VENDOR_ID_ATI, 0x5960,
0x17af, 0x2020, 4},
/* VIA KT880 Host Bridge / RV350 [Radeon 9550] Needs AGPMode 4 (fdo #19981) */
{ PCI_VENDOR_ID_VIA, 0x0269, PCI_VENDOR_ID_ATI, 0x4153,
PCI_VENDOR_ID_ASUSTEK, 0x003c, 4},
/* VIA VT8363 Host Bridge / R200 QL [Radeon 8500] Needs AGPMode 2 (lp #141551) */
{ PCI_VENDOR_ID_VIA, 0x0305, PCI_VENDOR_ID_ATI, 0x514c,
PCI_VENDOR_ID_ATI, 0x013a, 2},
/* VIA VT82C693A Host Bridge / RV280 [Radeon 9200 PRO] Needs AGPMode 2 (deb #515512) */
{ PCI_VENDOR_ID_VIA, 0x0691, PCI_VENDOR_ID_ATI, 0x5960,
PCI_VENDOR_ID_ASUSTEK, 0x004c, 2},
/* VIA VT82C693A Host Bridge / RV280 [Radeon 9200 PRO] Needs AGPMode 2 */
{ PCI_VENDOR_ID_VIA, 0x0691, PCI_VENDOR_ID_ATI, 0x5960,
PCI_VENDOR_ID_ASUSTEK, 0x0054, 2},
/* VIA VT8377 Host Bridge / R200 QM [Radeon 9100] Needs AGPMode 4 (deb #461144) */
{ PCI_VENDOR_ID_VIA, 0x3189, PCI_VENDOR_ID_ATI, 0x514d,
0x174b, 0x7149, 4},
/* VIA VT8377 Host Bridge / RV280 [Radeon 9200 PRO] Needs AGPMode 4 (lp #312693) */
{ PCI_VENDOR_ID_VIA, 0x3189, PCI_VENDOR_ID_ATI, 0x5960,
0x1462, 0x0380, 4},
/* VIA VT8377 Host Bridge / RV280 Needs AGPMode 4 (ati ML) */
{ PCI_VENDOR_ID_VIA, 0x3189, PCI_VENDOR_ID_ATI, 0x5964,
0x148c, 0x2073, 4},
/* ATI Host Bridge / RV280 [M9+] Needs AGPMode 1 (phoronix forum) */
{ PCI_VENDOR_ID_ATI, 0xcbb2, PCI_VENDOR_ID_ATI, 0x5c61,
PCI_VENDOR_ID_SONY, 0x8175, 1},
{ 0, 0, 0, 0, 0, 0, 0 },
};
struct radeon_agp_head *radeon_agp_head_init(struct drm_device *dev)
{
struct pci_dev *pdev = to_pci_dev(dev->dev);
struct radeon_agp_head *head;
head = kzalloc(sizeof(*head), GFP_KERNEL);
if (!head)
return NULL;
head->bridge = agp_find_bridge(pdev);
if (!head->bridge) {
head->bridge = agp_backend_acquire(pdev);
if (!head->bridge) {
kfree(head);
return NULL;
}
agp_copy_info(head->bridge, &head->agp_info);
agp_backend_release(head->bridge);
} else {
agp_copy_info(head->bridge, &head->agp_info);
}
if (head->agp_info.chipset == NOT_SUPPORTED) {
kfree(head);
return NULL;
}
INIT_LIST_HEAD(&head->memory);
head->cant_use_aperture = head->agp_info.cant_use_aperture;
head->page_mask = head->agp_info.page_mask;
head->base = head->agp_info.aper_base;
return head;
}
static int radeon_agp_head_acquire(struct radeon_device *rdev)
{
struct drm_device *dev = rdev->ddev;
struct pci_dev *pdev = to_pci_dev(dev->dev);
if (!rdev->agp)
return -ENODEV;
if (rdev->agp->acquired)
return -EBUSY;
rdev->agp->bridge = agp_backend_acquire(pdev);
if (!rdev->agp->bridge)
return -ENODEV;
rdev->agp->acquired = 1;
return 0;
}
static int radeon_agp_head_release(struct radeon_device *rdev)
{
if (!rdev->agp || !rdev->agp->acquired)
return -EINVAL;
agp_backend_release(rdev->agp->bridge);
rdev->agp->acquired = 0;
return 0;
}
static int radeon_agp_head_enable(struct radeon_device *rdev, struct radeon_agp_mode mode)
{
if (!rdev->agp || !rdev->agp->acquired)
return -EINVAL;
rdev->agp->mode = mode.mode;
agp_enable(rdev->agp->bridge, mode.mode);
rdev->agp->enabled = 1;
return 0;
}
static int radeon_agp_head_info(struct radeon_device *rdev, struct radeon_agp_info *info)
{
struct agp_kern_info *kern;
if (!rdev->agp || !rdev->agp->acquired)
return -EINVAL;
kern = &rdev->agp->agp_info;
info->agp_version_major = kern->version.major;
info->agp_version_minor = kern->version.minor;
info->mode = kern->mode;
info->aperture_base = kern->aper_base;
info->aperture_size = kern->aper_size * 1024 * 1024;
info->memory_allowed = kern->max_memory << PAGE_SHIFT;
info->memory_used = kern->current_memory << PAGE_SHIFT;
info->id_vendor = kern->device->vendor;
info->id_device = kern->device->device;
return 0;
}
#endif
int radeon_agp_init(struct radeon_device *rdev)
{
#if IS_ENABLED(CONFIG_AGP)
struct radeon_agpmode_quirk *p = radeon_agpmode_quirk_list;
struct radeon_agp_mode mode;
struct radeon_agp_info info;
uint32_t agp_status;
int default_mode;
bool is_v3;
int ret;
/* Acquire AGP. */
ret = radeon_agp_head_acquire(rdev);
if (ret) {
DRM_ERROR("Unable to acquire AGP: %d\n", ret);
return ret;
}
ret = radeon_agp_head_info(rdev, &info);
if (ret) {
radeon_agp_head_release(rdev);
DRM_ERROR("Unable to get AGP info: %d\n", ret);
return ret;
}
if (rdev->agp->agp_info.aper_size < 32) {
radeon_agp_head_release(rdev);
dev_warn(rdev->dev, "AGP aperture too small (%zuM) "
"need at least 32M, disabling AGP\n",
rdev->agp->agp_info.aper_size);
return -EINVAL;
}
mode.mode = info.mode;
/* chips with the agp to pcie bridge don't have the AGP_STATUS register
* Just use the whatever mode the host sets up.
*/
if (rdev->family <= CHIP_RV350)
agp_status = (RREG32(RADEON_AGP_STATUS) | RADEON_AGPv3_MODE) & mode.mode;
else
agp_status = mode.mode;
is_v3 = !!(agp_status & RADEON_AGPv3_MODE);
if (is_v3) {
default_mode = (agp_status & RADEON_AGPv3_8X_MODE) ? 8 : 4;
} else {
if (agp_status & RADEON_AGP_4X_MODE) {
default_mode = 4;
} else if (agp_status & RADEON_AGP_2X_MODE) {
default_mode = 2;
} else {
default_mode = 1;
}
}
/* Apply AGPMode Quirks */
while (p && p->chip_device != 0) {
if (info.id_vendor == p->hostbridge_vendor &&
info.id_device == p->hostbridge_device &&
rdev->pdev->vendor == p->chip_vendor &&
rdev->pdev->device == p->chip_device &&
rdev->pdev->subsystem_vendor == p->subsys_vendor &&
rdev->pdev->subsystem_device == p->subsys_device) {
default_mode = p->default_mode;
}
++p;
}
if (radeon_agpmode > 0) {
if ((radeon_agpmode < (is_v3 ? 4 : 1)) ||
(radeon_agpmode > (is_v3 ? 8 : 4)) ||
(radeon_agpmode & (radeon_agpmode - 1))) {
DRM_ERROR("Illegal AGP Mode: %d (valid %s), leaving at %d\n",
radeon_agpmode, is_v3 ? "4, 8" : "1, 2, 4",
default_mode);
radeon_agpmode = default_mode;
} else {
DRM_INFO("AGP mode requested: %d\n", radeon_agpmode);
}
} else {
radeon_agpmode = default_mode;
}
mode.mode &= ~RADEON_AGP_MODE_MASK;
if (is_v3) {
switch (radeon_agpmode) {
case 8:
mode.mode |= RADEON_AGPv3_8X_MODE;
break;
case 4:
default:
mode.mode |= RADEON_AGPv3_4X_MODE;
break;
}
} else {
switch (radeon_agpmode) {
case 4:
mode.mode |= RADEON_AGP_4X_MODE;
break;
case 2:
mode.mode |= RADEON_AGP_2X_MODE;
break;
case 1:
default:
mode.mode |= RADEON_AGP_1X_MODE;
break;
}
}
mode.mode &= ~RADEON_AGP_FW_MODE; /* disable fw */
ret = radeon_agp_head_enable(rdev, mode);
if (ret) {
DRM_ERROR("Unable to enable AGP (mode = 0x%lx)\n", mode.mode);
radeon_agp_head_release(rdev);
return ret;
}
rdev->mc.agp_base = rdev->agp->agp_info.aper_base;
rdev->mc.gtt_size = rdev->agp->agp_info.aper_size << 20;
rdev->mc.gtt_start = rdev->mc.agp_base;
rdev->mc.gtt_end = rdev->mc.gtt_start + rdev->mc.gtt_size - 1;
dev_info(rdev->dev, "GTT: %lluM 0x%08llX - 0x%08llX\n",
rdev->mc.gtt_size >> 20, rdev->mc.gtt_start, rdev->mc.gtt_end);
/* workaround some hw issues */
if (rdev->family < CHIP_R200) {
WREG32(RADEON_AGP_CNTL, RREG32(RADEON_AGP_CNTL) | 0x000e0000);
}
return 0;
#else
return 0;
#endif
}
void radeon_agp_resume(struct radeon_device *rdev)
{
#if IS_ENABLED(CONFIG_AGP)
int r;
if (rdev->flags & RADEON_IS_AGP) {
r = radeon_agp_init(rdev);
if (r)
dev_warn(rdev->dev, "radeon AGP reinit failed\n");
}
#endif
}
void radeon_agp_fini(struct radeon_device *rdev)
{
#if IS_ENABLED(CONFIG_AGP)
if (rdev->agp && rdev->agp->acquired) {
radeon_agp_head_release(rdev);
}
#endif
}
void radeon_agp_suspend(struct radeon_device *rdev)
{
radeon_agp_fini(rdev);
}
| linux-master | drivers/gpu/drm/radeon/radeon_agp.c |
/*
* Copyright 2009 Jerome Glisse.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
*/
/*
* Authors:
* Jerome Glisse <[email protected]>
* Thomas Hellstrom <thomas-at-tungstengraphics-dot-com>
* Dave Airlie
*/
#include <linux/io.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <drm/drm_cache.h>
#include <drm/drm_prime.h>
#include <drm/radeon_drm.h>
#include "radeon.h"
#include "radeon_trace.h"
#include "radeon_ttm.h"
static void radeon_bo_clear_surface_reg(struct radeon_bo *bo);
/*
* To exclude mutual BO access we rely on bo_reserve exclusion, as all
* function are calling it.
*/
static void radeon_ttm_bo_destroy(struct ttm_buffer_object *tbo)
{
struct radeon_bo *bo;
bo = container_of(tbo, struct radeon_bo, tbo);
mutex_lock(&bo->rdev->gem.mutex);
list_del_init(&bo->list);
mutex_unlock(&bo->rdev->gem.mutex);
radeon_bo_clear_surface_reg(bo);
WARN_ON_ONCE(!list_empty(&bo->va));
if (bo->tbo.base.import_attach)
drm_prime_gem_destroy(&bo->tbo.base, bo->tbo.sg);
drm_gem_object_release(&bo->tbo.base);
kfree(bo);
}
bool radeon_ttm_bo_is_radeon_bo(struct ttm_buffer_object *bo)
{
if (bo->destroy == &radeon_ttm_bo_destroy)
return true;
return false;
}
void radeon_ttm_placement_from_domain(struct radeon_bo *rbo, u32 domain)
{
u32 c = 0, i;
rbo->placement.placement = rbo->placements;
rbo->placement.busy_placement = rbo->placements;
if (domain & RADEON_GEM_DOMAIN_VRAM) {
/* Try placing BOs which don't need CPU access outside of the
* CPU accessible part of VRAM
*/
if ((rbo->flags & RADEON_GEM_NO_CPU_ACCESS) &&
rbo->rdev->mc.visible_vram_size < rbo->rdev->mc.real_vram_size) {
rbo->placements[c].fpfn =
rbo->rdev->mc.visible_vram_size >> PAGE_SHIFT;
rbo->placements[c].mem_type = TTM_PL_VRAM;
rbo->placements[c++].flags = 0;
}
rbo->placements[c].fpfn = 0;
rbo->placements[c].mem_type = TTM_PL_VRAM;
rbo->placements[c++].flags = 0;
}
if (domain & RADEON_GEM_DOMAIN_GTT) {
rbo->placements[c].fpfn = 0;
rbo->placements[c].mem_type = TTM_PL_TT;
rbo->placements[c++].flags = 0;
}
if (domain & RADEON_GEM_DOMAIN_CPU) {
rbo->placements[c].fpfn = 0;
rbo->placements[c].mem_type = TTM_PL_SYSTEM;
rbo->placements[c++].flags = 0;
}
if (!c) {
rbo->placements[c].fpfn = 0;
rbo->placements[c].mem_type = TTM_PL_SYSTEM;
rbo->placements[c++].flags = 0;
}
rbo->placement.num_placement = c;
rbo->placement.num_busy_placement = c;
for (i = 0; i < c; ++i) {
if ((rbo->flags & RADEON_GEM_CPU_ACCESS) &&
(rbo->placements[i].mem_type == TTM_PL_VRAM) &&
!rbo->placements[i].fpfn)
rbo->placements[i].lpfn =
rbo->rdev->mc.visible_vram_size >> PAGE_SHIFT;
else
rbo->placements[i].lpfn = 0;
}
}
int radeon_bo_create(struct radeon_device *rdev,
unsigned long size, int byte_align, bool kernel,
u32 domain, u32 flags, struct sg_table *sg,
struct dma_resv *resv,
struct radeon_bo **bo_ptr)
{
struct radeon_bo *bo;
enum ttm_bo_type type;
unsigned long page_align = roundup(byte_align, PAGE_SIZE) >> PAGE_SHIFT;
int r;
size = ALIGN(size, PAGE_SIZE);
if (kernel) {
type = ttm_bo_type_kernel;
} else if (sg) {
type = ttm_bo_type_sg;
} else {
type = ttm_bo_type_device;
}
*bo_ptr = NULL;
bo = kzalloc(sizeof(struct radeon_bo), GFP_KERNEL);
if (bo == NULL)
return -ENOMEM;
drm_gem_private_object_init(rdev->ddev, &bo->tbo.base, size);
bo->rdev = rdev;
bo->surface_reg = -1;
INIT_LIST_HEAD(&bo->list);
INIT_LIST_HEAD(&bo->va);
bo->initial_domain = domain & (RADEON_GEM_DOMAIN_VRAM |
RADEON_GEM_DOMAIN_GTT |
RADEON_GEM_DOMAIN_CPU);
bo->flags = flags;
/* PCI GART is always snooped */
if (!(rdev->flags & RADEON_IS_PCIE))
bo->flags &= ~(RADEON_GEM_GTT_WC | RADEON_GEM_GTT_UC);
/* Write-combined CPU mappings of GTT cause GPU hangs with RV6xx
* See https://bugs.freedesktop.org/show_bug.cgi?id=91268
*/
if (rdev->family >= CHIP_RV610 && rdev->family <= CHIP_RV635)
bo->flags &= ~(RADEON_GEM_GTT_WC | RADEON_GEM_GTT_UC);
#ifdef CONFIG_X86_32
/* XXX: Write-combined CPU mappings of GTT seem broken on 32-bit
* See https://bugs.freedesktop.org/show_bug.cgi?id=84627
*/
bo->flags &= ~(RADEON_GEM_GTT_WC | RADEON_GEM_GTT_UC);
#elif defined(CONFIG_X86) && !defined(CONFIG_X86_PAT)
/* Don't try to enable write-combining when it can't work, or things
* may be slow
* See https://bugs.freedesktop.org/show_bug.cgi?id=88758
*/
#ifndef CONFIG_COMPILE_TEST
#warning Please enable CONFIG_MTRR and CONFIG_X86_PAT for better performance \
thanks to write-combining
#endif
if (bo->flags & RADEON_GEM_GTT_WC)
DRM_INFO_ONCE("Please enable CONFIG_MTRR and CONFIG_X86_PAT for "
"better performance thanks to write-combining\n");
bo->flags &= ~(RADEON_GEM_GTT_WC | RADEON_GEM_GTT_UC);
#else
/* For architectures that don't support WC memory,
* mask out the WC flag from the BO
*/
if (!drm_arch_can_wc_memory())
bo->flags &= ~RADEON_GEM_GTT_WC;
#endif
radeon_ttm_placement_from_domain(bo, domain);
/* Kernel allocation are uninterruptible */
down_read(&rdev->pm.mclk_lock);
r = ttm_bo_init_validate(&rdev->mman.bdev, &bo->tbo, type,
&bo->placement, page_align, !kernel, sg, resv,
&radeon_ttm_bo_destroy);
up_read(&rdev->pm.mclk_lock);
if (unlikely(r != 0)) {
return r;
}
*bo_ptr = bo;
trace_radeon_bo_create(bo);
return 0;
}
int radeon_bo_kmap(struct radeon_bo *bo, void **ptr)
{
bool is_iomem;
long r;
r = dma_resv_wait_timeout(bo->tbo.base.resv, DMA_RESV_USAGE_KERNEL,
false, MAX_SCHEDULE_TIMEOUT);
if (r < 0)
return r;
if (bo->kptr) {
if (ptr) {
*ptr = bo->kptr;
}
return 0;
}
r = ttm_bo_kmap(&bo->tbo, 0, PFN_UP(bo->tbo.base.size), &bo->kmap);
if (r) {
return r;
}
bo->kptr = ttm_kmap_obj_virtual(&bo->kmap, &is_iomem);
if (ptr) {
*ptr = bo->kptr;
}
radeon_bo_check_tiling(bo, 0, 0);
return 0;
}
void radeon_bo_kunmap(struct radeon_bo *bo)
{
if (bo->kptr == NULL)
return;
bo->kptr = NULL;
radeon_bo_check_tiling(bo, 0, 0);
ttm_bo_kunmap(&bo->kmap);
}
struct radeon_bo *radeon_bo_ref(struct radeon_bo *bo)
{
if (bo == NULL)
return NULL;
ttm_bo_get(&bo->tbo);
return bo;
}
void radeon_bo_unref(struct radeon_bo **bo)
{
struct ttm_buffer_object *tbo;
if ((*bo) == NULL)
return;
tbo = &((*bo)->tbo);
ttm_bo_put(tbo);
*bo = NULL;
}
int radeon_bo_pin_restricted(struct radeon_bo *bo, u32 domain, u64 max_offset,
u64 *gpu_addr)
{
struct ttm_operation_ctx ctx = { false, false };
int r, i;
if (radeon_ttm_tt_has_userptr(bo->rdev, bo->tbo.ttm))
return -EPERM;
if (bo->tbo.pin_count) {
ttm_bo_pin(&bo->tbo);
if (gpu_addr)
*gpu_addr = radeon_bo_gpu_offset(bo);
if (max_offset != 0) {
u64 domain_start;
if (domain == RADEON_GEM_DOMAIN_VRAM)
domain_start = bo->rdev->mc.vram_start;
else
domain_start = bo->rdev->mc.gtt_start;
WARN_ON_ONCE(max_offset <
(radeon_bo_gpu_offset(bo) - domain_start));
}
return 0;
}
if (bo->prime_shared_count && domain == RADEON_GEM_DOMAIN_VRAM) {
/* A BO shared as a dma-buf cannot be sensibly migrated to VRAM */
return -EINVAL;
}
radeon_ttm_placement_from_domain(bo, domain);
for (i = 0; i < bo->placement.num_placement; i++) {
/* force to pin into visible video ram */
if ((bo->placements[i].mem_type == TTM_PL_VRAM) &&
!(bo->flags & RADEON_GEM_NO_CPU_ACCESS) &&
(!max_offset || max_offset > bo->rdev->mc.visible_vram_size))
bo->placements[i].lpfn =
bo->rdev->mc.visible_vram_size >> PAGE_SHIFT;
else
bo->placements[i].lpfn = max_offset >> PAGE_SHIFT;
}
r = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
if (likely(r == 0)) {
ttm_bo_pin(&bo->tbo);
if (gpu_addr != NULL)
*gpu_addr = radeon_bo_gpu_offset(bo);
if (domain == RADEON_GEM_DOMAIN_VRAM)
bo->rdev->vram_pin_size += radeon_bo_size(bo);
else
bo->rdev->gart_pin_size += radeon_bo_size(bo);
} else {
dev_err(bo->rdev->dev, "%p pin failed\n", bo);
}
return r;
}
int radeon_bo_pin(struct radeon_bo *bo, u32 domain, u64 *gpu_addr)
{
return radeon_bo_pin_restricted(bo, domain, 0, gpu_addr);
}
void radeon_bo_unpin(struct radeon_bo *bo)
{
ttm_bo_unpin(&bo->tbo);
if (!bo->tbo.pin_count) {
if (bo->tbo.resource->mem_type == TTM_PL_VRAM)
bo->rdev->vram_pin_size -= radeon_bo_size(bo);
else
bo->rdev->gart_pin_size -= radeon_bo_size(bo);
}
}
int radeon_bo_evict_vram(struct radeon_device *rdev)
{
struct ttm_device *bdev = &rdev->mman.bdev;
struct ttm_resource_manager *man;
/* late 2.6.33 fix IGP hibernate - we need pm ops to do this correct */
#ifndef CONFIG_HIBERNATION
if (rdev->flags & RADEON_IS_IGP) {
if (rdev->mc.igp_sideport_enabled == false)
/* Useless to evict on IGP chips */
return 0;
}
#endif
man = ttm_manager_type(bdev, TTM_PL_VRAM);
if (!man)
return 0;
return ttm_resource_manager_evict_all(bdev, man);
}
void radeon_bo_force_delete(struct radeon_device *rdev)
{
struct radeon_bo *bo, *n;
if (list_empty(&rdev->gem.objects)) {
return;
}
dev_err(rdev->dev, "Userspace still has active objects !\n");
list_for_each_entry_safe(bo, n, &rdev->gem.objects, list) {
dev_err(rdev->dev, "%p %p %lu %lu force free\n",
&bo->tbo.base, bo, (unsigned long)bo->tbo.base.size,
*((unsigned long *)&bo->tbo.base.refcount));
mutex_lock(&bo->rdev->gem.mutex);
list_del_init(&bo->list);
mutex_unlock(&bo->rdev->gem.mutex);
/* this should unref the ttm bo */
drm_gem_object_put(&bo->tbo.base);
}
}
int radeon_bo_init(struct radeon_device *rdev)
{
/* reserve PAT memory space to WC for VRAM */
arch_io_reserve_memtype_wc(rdev->mc.aper_base,
rdev->mc.aper_size);
/* Add an MTRR for the VRAM */
if (!rdev->fastfb_working) {
rdev->mc.vram_mtrr = arch_phys_wc_add(rdev->mc.aper_base,
rdev->mc.aper_size);
}
DRM_INFO("Detected VRAM RAM=%lluM, BAR=%lluM\n",
rdev->mc.mc_vram_size >> 20,
(unsigned long long)rdev->mc.aper_size >> 20);
DRM_INFO("RAM width %dbits %cDR\n",
rdev->mc.vram_width, rdev->mc.vram_is_ddr ? 'D' : 'S');
return radeon_ttm_init(rdev);
}
void radeon_bo_fini(struct radeon_device *rdev)
{
radeon_ttm_fini(rdev);
arch_phys_wc_del(rdev->mc.vram_mtrr);
arch_io_free_memtype_wc(rdev->mc.aper_base, rdev->mc.aper_size);
}
/* Returns how many bytes TTM can move per IB.
*/
static u64 radeon_bo_get_threshold_for_moves(struct radeon_device *rdev)
{
u64 real_vram_size = rdev->mc.real_vram_size;
struct ttm_resource_manager *man =
ttm_manager_type(&rdev->mman.bdev, TTM_PL_VRAM);
u64 vram_usage = ttm_resource_manager_usage(man);
/* This function is based on the current VRAM usage.
*
* - If all of VRAM is free, allow relocating the number of bytes that
* is equal to 1/4 of the size of VRAM for this IB.
* - If more than one half of VRAM is occupied, only allow relocating
* 1 MB of data for this IB.
*
* - From 0 to one half of used VRAM, the threshold decreases
* linearly.
* __________________
* 1/4 of -|\ |
* VRAM | \ |
* | \ |
* | \ |
* | \ |
* | \ |
* | \ |
* | \________|1 MB
* |----------------|
* VRAM 0 % 100 %
* used used
*
* Note: It's a threshold, not a limit. The threshold must be crossed
* for buffer relocations to stop, so any buffer of an arbitrary size
* can be moved as long as the threshold isn't crossed before
* the relocation takes place. We don't want to disable buffer
* relocations completely.
*
* The idea is that buffers should be placed in VRAM at creation time
* and TTM should only do a minimum number of relocations during
* command submission. In practice, you need to submit at least
* a dozen IBs to move all buffers to VRAM if they are in GTT.
*
* Also, things can get pretty crazy under memory pressure and actual
* VRAM usage can change a lot, so playing safe even at 50% does
* consistently increase performance.
*/
u64 half_vram = real_vram_size >> 1;
u64 half_free_vram = vram_usage >= half_vram ? 0 : half_vram - vram_usage;
u64 bytes_moved_threshold = half_free_vram >> 1;
return max(bytes_moved_threshold, 1024*1024ull);
}
int radeon_bo_list_validate(struct radeon_device *rdev,
struct ww_acquire_ctx *ticket,
struct list_head *head, int ring)
{
struct ttm_operation_ctx ctx = { true, false };
struct radeon_bo_list *lobj;
struct list_head duplicates;
int r;
u64 bytes_moved = 0, initial_bytes_moved;
u64 bytes_moved_threshold = radeon_bo_get_threshold_for_moves(rdev);
INIT_LIST_HEAD(&duplicates);
r = ttm_eu_reserve_buffers(ticket, head, true, &duplicates);
if (unlikely(r != 0)) {
return r;
}
list_for_each_entry(lobj, head, tv.head) {
struct radeon_bo *bo = lobj->robj;
if (!bo->tbo.pin_count) {
u32 domain = lobj->preferred_domains;
u32 allowed = lobj->allowed_domains;
u32 current_domain =
radeon_mem_type_to_domain(bo->tbo.resource->mem_type);
/* Check if this buffer will be moved and don't move it
* if we have moved too many buffers for this IB already.
*
* Note that this allows moving at least one buffer of
* any size, because it doesn't take the current "bo"
* into account. We don't want to disallow buffer moves
* completely.
*/
if ((allowed & current_domain) != 0 &&
(domain & current_domain) == 0 && /* will be moved */
bytes_moved > bytes_moved_threshold) {
/* don't move it */
domain = current_domain;
}
retry:
radeon_ttm_placement_from_domain(bo, domain);
if (ring == R600_RING_TYPE_UVD_INDEX)
radeon_uvd_force_into_uvd_segment(bo, allowed);
initial_bytes_moved = atomic64_read(&rdev->num_bytes_moved);
r = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
bytes_moved += atomic64_read(&rdev->num_bytes_moved) -
initial_bytes_moved;
if (unlikely(r)) {
if (r != -ERESTARTSYS &&
domain != lobj->allowed_domains) {
domain = lobj->allowed_domains;
goto retry;
}
ttm_eu_backoff_reservation(ticket, head);
return r;
}
}
lobj->gpu_offset = radeon_bo_gpu_offset(bo);
lobj->tiling_flags = bo->tiling_flags;
}
list_for_each_entry(lobj, &duplicates, tv.head) {
lobj->gpu_offset = radeon_bo_gpu_offset(lobj->robj);
lobj->tiling_flags = lobj->robj->tiling_flags;
}
return 0;
}
int radeon_bo_get_surface_reg(struct radeon_bo *bo)
{
struct radeon_device *rdev = bo->rdev;
struct radeon_surface_reg *reg;
struct radeon_bo *old_object;
int steal;
int i;
dma_resv_assert_held(bo->tbo.base.resv);
if (!bo->tiling_flags)
return 0;
if (bo->surface_reg >= 0) {
i = bo->surface_reg;
goto out;
}
steal = -1;
for (i = 0; i < RADEON_GEM_MAX_SURFACES; i++) {
reg = &rdev->surface_regs[i];
if (!reg->bo)
break;
old_object = reg->bo;
if (old_object->tbo.pin_count == 0)
steal = i;
}
/* if we are all out */
if (i == RADEON_GEM_MAX_SURFACES) {
if (steal == -1)
return -ENOMEM;
/* find someone with a surface reg and nuke their BO */
reg = &rdev->surface_regs[steal];
old_object = reg->bo;
/* blow away the mapping */
DRM_DEBUG("stealing surface reg %d from %p\n", steal, old_object);
ttm_bo_unmap_virtual(&old_object->tbo);
old_object->surface_reg = -1;
i = steal;
}
bo->surface_reg = i;
reg->bo = bo;
out:
radeon_set_surface_reg(rdev, i, bo->tiling_flags, bo->pitch,
bo->tbo.resource->start << PAGE_SHIFT,
bo->tbo.base.size);
return 0;
}
static void radeon_bo_clear_surface_reg(struct radeon_bo *bo)
{
struct radeon_device *rdev = bo->rdev;
struct radeon_surface_reg *reg;
if (bo->surface_reg == -1)
return;
reg = &rdev->surface_regs[bo->surface_reg];
radeon_clear_surface_reg(rdev, bo->surface_reg);
reg->bo = NULL;
bo->surface_reg = -1;
}
int radeon_bo_set_tiling_flags(struct radeon_bo *bo,
uint32_t tiling_flags, uint32_t pitch)
{
struct radeon_device *rdev = bo->rdev;
int r;
if (rdev->family >= CHIP_CEDAR) {
unsigned bankw, bankh, mtaspect, tilesplit, stilesplit;
bankw = (tiling_flags >> RADEON_TILING_EG_BANKW_SHIFT) & RADEON_TILING_EG_BANKW_MASK;
bankh = (tiling_flags >> RADEON_TILING_EG_BANKH_SHIFT) & RADEON_TILING_EG_BANKH_MASK;
mtaspect = (tiling_flags >> RADEON_TILING_EG_MACRO_TILE_ASPECT_SHIFT) & RADEON_TILING_EG_MACRO_TILE_ASPECT_MASK;
tilesplit = (tiling_flags >> RADEON_TILING_EG_TILE_SPLIT_SHIFT) & RADEON_TILING_EG_TILE_SPLIT_MASK;
stilesplit = (tiling_flags >> RADEON_TILING_EG_STENCIL_TILE_SPLIT_SHIFT) & RADEON_TILING_EG_STENCIL_TILE_SPLIT_MASK;
switch (bankw) {
case 0:
case 1:
case 2:
case 4:
case 8:
break;
default:
return -EINVAL;
}
switch (bankh) {
case 0:
case 1:
case 2:
case 4:
case 8:
break;
default:
return -EINVAL;
}
switch (mtaspect) {
case 0:
case 1:
case 2:
case 4:
case 8:
break;
default:
return -EINVAL;
}
if (tilesplit > 6) {
return -EINVAL;
}
if (stilesplit > 6) {
return -EINVAL;
}
}
r = radeon_bo_reserve(bo, false);
if (unlikely(r != 0))
return r;
bo->tiling_flags = tiling_flags;
bo->pitch = pitch;
radeon_bo_unreserve(bo);
return 0;
}
void radeon_bo_get_tiling_flags(struct radeon_bo *bo,
uint32_t *tiling_flags,
uint32_t *pitch)
{
dma_resv_assert_held(bo->tbo.base.resv);
if (tiling_flags)
*tiling_flags = bo->tiling_flags;
if (pitch)
*pitch = bo->pitch;
}
int radeon_bo_check_tiling(struct radeon_bo *bo, bool has_moved,
bool force_drop)
{
if (!force_drop)
dma_resv_assert_held(bo->tbo.base.resv);
if (!(bo->tiling_flags & RADEON_TILING_SURFACE))
return 0;
if (force_drop) {
radeon_bo_clear_surface_reg(bo);
return 0;
}
if (bo->tbo.resource->mem_type != TTM_PL_VRAM) {
if (!has_moved)
return 0;
if (bo->surface_reg >= 0)
radeon_bo_clear_surface_reg(bo);
return 0;
}
if ((bo->surface_reg >= 0) && !has_moved)
return 0;
return radeon_bo_get_surface_reg(bo);
}
void radeon_bo_move_notify(struct ttm_buffer_object *bo)
{
struct radeon_bo *rbo;
if (!radeon_ttm_bo_is_radeon_bo(bo))
return;
rbo = container_of(bo, struct radeon_bo, tbo);
radeon_bo_check_tiling(rbo, 0, 1);
radeon_vm_bo_invalidate(rbo->rdev, rbo);
}
vm_fault_t radeon_bo_fault_reserve_notify(struct ttm_buffer_object *bo)
{
struct ttm_operation_ctx ctx = { false, false };
struct radeon_device *rdev;
struct radeon_bo *rbo;
unsigned long offset, size, lpfn;
int i, r;
if (!radeon_ttm_bo_is_radeon_bo(bo))
return 0;
rbo = container_of(bo, struct radeon_bo, tbo);
radeon_bo_check_tiling(rbo, 0, 0);
rdev = rbo->rdev;
if (bo->resource->mem_type != TTM_PL_VRAM)
return 0;
size = bo->resource->size;
offset = bo->resource->start << PAGE_SHIFT;
if ((offset + size) <= rdev->mc.visible_vram_size)
return 0;
/* Can't move a pinned BO to visible VRAM */
if (rbo->tbo.pin_count > 0)
return VM_FAULT_SIGBUS;
/* hurrah the memory is not visible ! */
radeon_ttm_placement_from_domain(rbo, RADEON_GEM_DOMAIN_VRAM);
lpfn = rdev->mc.visible_vram_size >> PAGE_SHIFT;
for (i = 0; i < rbo->placement.num_placement; i++) {
/* Force into visible VRAM */
if ((rbo->placements[i].mem_type == TTM_PL_VRAM) &&
(!rbo->placements[i].lpfn || rbo->placements[i].lpfn > lpfn))
rbo->placements[i].lpfn = lpfn;
}
r = ttm_bo_validate(bo, &rbo->placement, &ctx);
if (unlikely(r == -ENOMEM)) {
radeon_ttm_placement_from_domain(rbo, RADEON_GEM_DOMAIN_GTT);
r = ttm_bo_validate(bo, &rbo->placement, &ctx);
} else if (likely(!r)) {
offset = bo->resource->start << PAGE_SHIFT;
/* this should never happen */
if ((offset + size) > rdev->mc.visible_vram_size)
return VM_FAULT_SIGBUS;
}
if (unlikely(r == -EBUSY || r == -ERESTARTSYS))
return VM_FAULT_NOPAGE;
else if (unlikely(r))
return VM_FAULT_SIGBUS;
ttm_bo_move_to_lru_tail_unlocked(bo);
return 0;
}
/**
* radeon_bo_fence - add fence to buffer object
*
* @bo: buffer object in question
* @fence: fence to add
* @shared: true if fence should be added shared
*
*/
void radeon_bo_fence(struct radeon_bo *bo, struct radeon_fence *fence,
bool shared)
{
struct dma_resv *resv = bo->tbo.base.resv;
int r;
r = dma_resv_reserve_fences(resv, 1);
if (r) {
/* As last resort on OOM we block for the fence */
dma_fence_wait(&fence->base, false);
return;
}
dma_resv_add_fence(resv, &fence->base, shared ?
DMA_RESV_USAGE_READ : DMA_RESV_USAGE_WRITE);
}
| linux-master | drivers/gpu/drm/radeon/radeon_object.c |
/*
* Copyright 2008 Advanced Micro Devices, Inc.
* Copyright 2008 Red Hat Inc.
* Copyright 2009 Jerome Glisse.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Dave Airlie
* Alex Deucher
* Jerome Glisse
*/
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <drm/drm_device.h>
#include <drm/drm_file.h>
#include "radeon.h"
#include "radeon_asic.h"
#include "rs400d.h"
/* This files gather functions specifics to : rs400,rs480 */
static void rs400_debugfs_pcie_gart_info_init(struct radeon_device *rdev);
void rs400_gart_adjust_size(struct radeon_device *rdev)
{
/* Check gart size */
switch (rdev->mc.gtt_size/(1024*1024)) {
case 32:
case 64:
case 128:
case 256:
case 512:
case 1024:
case 2048:
break;
default:
DRM_ERROR("Unable to use IGP GART size %uM\n",
(unsigned)(rdev->mc.gtt_size >> 20));
DRM_ERROR("Valid GART size for IGP are 32M,64M,128M,256M,512M,1G,2G\n");
DRM_ERROR("Forcing to 32M GART size\n");
rdev->mc.gtt_size = 32 * 1024 * 1024;
return;
}
}
void rs400_gart_tlb_flush(struct radeon_device *rdev)
{
uint32_t tmp;
unsigned int timeout = rdev->usec_timeout;
WREG32_MC(RS480_GART_CACHE_CNTRL, RS480_GART_CACHE_INVALIDATE);
do {
tmp = RREG32_MC(RS480_GART_CACHE_CNTRL);
if ((tmp & RS480_GART_CACHE_INVALIDATE) == 0)
break;
udelay(1);
timeout--;
} while (timeout > 0);
WREG32_MC(RS480_GART_CACHE_CNTRL, 0);
}
int rs400_gart_init(struct radeon_device *rdev)
{
int r;
if (rdev->gart.ptr) {
WARN(1, "RS400 GART already initialized\n");
return 0;
}
/* Check gart size */
switch(rdev->mc.gtt_size / (1024 * 1024)) {
case 32:
case 64:
case 128:
case 256:
case 512:
case 1024:
case 2048:
break;
default:
return -EINVAL;
}
/* Initialize common gart structure */
r = radeon_gart_init(rdev);
if (r)
return r;
rs400_debugfs_pcie_gart_info_init(rdev);
rdev->gart.table_size = rdev->gart.num_gpu_pages * 4;
return radeon_gart_table_ram_alloc(rdev);
}
int rs400_gart_enable(struct radeon_device *rdev)
{
uint32_t size_reg;
uint32_t tmp;
tmp = RREG32_MC(RS690_AIC_CTRL_SCRATCH);
tmp |= RS690_DIS_OUT_OF_PCI_GART_ACCESS;
WREG32_MC(RS690_AIC_CTRL_SCRATCH, tmp);
/* Check gart size */
switch(rdev->mc.gtt_size / (1024 * 1024)) {
case 32:
size_reg = RS480_VA_SIZE_32MB;
break;
case 64:
size_reg = RS480_VA_SIZE_64MB;
break;
case 128:
size_reg = RS480_VA_SIZE_128MB;
break;
case 256:
size_reg = RS480_VA_SIZE_256MB;
break;
case 512:
size_reg = RS480_VA_SIZE_512MB;
break;
case 1024:
size_reg = RS480_VA_SIZE_1GB;
break;
case 2048:
size_reg = RS480_VA_SIZE_2GB;
break;
default:
return -EINVAL;
}
/* It should be fine to program it to max value */
if (rdev->family == CHIP_RS690 || (rdev->family == CHIP_RS740)) {
WREG32_MC(RS690_MCCFG_AGP_BASE, 0xFFFFFFFF);
WREG32_MC(RS690_MCCFG_AGP_BASE_2, 0);
} else {
WREG32(RADEON_AGP_BASE, 0xFFFFFFFF);
WREG32(RS480_AGP_BASE_2, 0);
}
tmp = REG_SET(RS690_MC_AGP_TOP, rdev->mc.gtt_end >> 16);
tmp |= REG_SET(RS690_MC_AGP_START, rdev->mc.gtt_start >> 16);
if ((rdev->family == CHIP_RS690) || (rdev->family == CHIP_RS740)) {
WREG32_MC(RS690_MCCFG_AGP_LOCATION, tmp);
tmp = RREG32(RADEON_BUS_CNTL) & ~RS600_BUS_MASTER_DIS;
WREG32(RADEON_BUS_CNTL, tmp);
} else {
WREG32(RADEON_MC_AGP_LOCATION, tmp);
tmp = RREG32(RADEON_BUS_CNTL) & ~RADEON_BUS_MASTER_DIS;
WREG32(RADEON_BUS_CNTL, tmp);
}
/* Table should be in 32bits address space so ignore bits above. */
tmp = (u32)rdev->gart.table_addr & 0xfffff000;
tmp |= (upper_32_bits(rdev->gart.table_addr) & 0xff) << 4;
WREG32_MC(RS480_GART_BASE, tmp);
/* TODO: more tweaking here */
WREG32_MC(RS480_GART_FEATURE_ID,
(RS480_TLB_ENABLE |
RS480_GTW_LAC_EN | RS480_1LEVEL_GART));
/* Disable snooping */
WREG32_MC(RS480_AGP_MODE_CNTL,
(1 << RS480_REQ_TYPE_SNOOP_SHIFT) | RS480_REQ_TYPE_SNOOP_DIS);
/* Disable AGP mode */
/* FIXME: according to doc we should set HIDE_MMCFG_BAR=0,
* AGPMODE30=0 & AGP30ENHANCED=0 in NB_CNTL */
if ((rdev->family == CHIP_RS690) || (rdev->family == CHIP_RS740)) {
tmp = RREG32_MC(RS480_MC_MISC_CNTL);
tmp |= RS480_GART_INDEX_REG_EN | RS690_BLOCK_GFX_D3_EN;
WREG32_MC(RS480_MC_MISC_CNTL, tmp);
} else {
tmp = RREG32_MC(RS480_MC_MISC_CNTL);
tmp |= RS480_GART_INDEX_REG_EN;
WREG32_MC(RS480_MC_MISC_CNTL, tmp);
}
/* Enable gart */
WREG32_MC(RS480_AGP_ADDRESS_SPACE_SIZE, (RS480_GART_EN | size_reg));
rs400_gart_tlb_flush(rdev);
DRM_INFO("PCIE GART of %uM enabled (table at 0x%016llX).\n",
(unsigned)(rdev->mc.gtt_size >> 20),
(unsigned long long)rdev->gart.table_addr);
rdev->gart.ready = true;
return 0;
}
void rs400_gart_disable(struct radeon_device *rdev)
{
uint32_t tmp;
tmp = RREG32_MC(RS690_AIC_CTRL_SCRATCH);
tmp |= RS690_DIS_OUT_OF_PCI_GART_ACCESS;
WREG32_MC(RS690_AIC_CTRL_SCRATCH, tmp);
WREG32_MC(RS480_AGP_ADDRESS_SPACE_SIZE, 0);
}
void rs400_gart_fini(struct radeon_device *rdev)
{
radeon_gart_fini(rdev);
rs400_gart_disable(rdev);
radeon_gart_table_ram_free(rdev);
}
#define RS400_PTE_UNSNOOPED (1 << 0)
#define RS400_PTE_WRITEABLE (1 << 2)
#define RS400_PTE_READABLE (1 << 3)
uint64_t rs400_gart_get_page_entry(uint64_t addr, uint32_t flags)
{
uint32_t entry;
entry = (lower_32_bits(addr) & PAGE_MASK) |
((upper_32_bits(addr) & 0xff) << 4);
if (flags & RADEON_GART_PAGE_READ)
entry |= RS400_PTE_READABLE;
if (flags & RADEON_GART_PAGE_WRITE)
entry |= RS400_PTE_WRITEABLE;
if (!(flags & RADEON_GART_PAGE_SNOOP))
entry |= RS400_PTE_UNSNOOPED;
return entry;
}
void rs400_gart_set_page(struct radeon_device *rdev, unsigned i,
uint64_t entry)
{
u32 *gtt = rdev->gart.ptr;
gtt[i] = cpu_to_le32(lower_32_bits(entry));
}
int rs400_mc_wait_for_idle(struct radeon_device *rdev)
{
unsigned i;
uint32_t tmp;
for (i = 0; i < rdev->usec_timeout; i++) {
/* read MC_STATUS */
tmp = RREG32(RADEON_MC_STATUS);
if (tmp & RADEON_MC_IDLE) {
return 0;
}
udelay(1);
}
return -1;
}
static void rs400_gpu_init(struct radeon_device *rdev)
{
/* FIXME: is this correct ? */
r420_pipes_init(rdev);
if (rs400_mc_wait_for_idle(rdev)) {
pr_warn("rs400: Failed to wait MC idle while programming pipes. Bad things might happen. %08x\n",
RREG32(RADEON_MC_STATUS));
}
}
static void rs400_mc_init(struct radeon_device *rdev)
{
u64 base;
rs400_gart_adjust_size(rdev);
rdev->mc.igp_sideport_enabled = radeon_combios_sideport_present(rdev);
/* DDR for all card after R300 & IGP */
rdev->mc.vram_is_ddr = true;
rdev->mc.vram_width = 128;
r100_vram_init_sizes(rdev);
base = (RREG32(RADEON_NB_TOM) & 0xffff) << 16;
radeon_vram_location(rdev, &rdev->mc, base);
rdev->mc.gtt_base_align = rdev->mc.gtt_size - 1;
radeon_gtt_location(rdev, &rdev->mc);
radeon_update_bandwidth_info(rdev);
}
uint32_t rs400_mc_rreg(struct radeon_device *rdev, uint32_t reg)
{
unsigned long flags;
uint32_t r;
spin_lock_irqsave(&rdev->mc_idx_lock, flags);
WREG32(RS480_NB_MC_INDEX, reg & 0xff);
r = RREG32(RS480_NB_MC_DATA);
WREG32(RS480_NB_MC_INDEX, 0xff);
spin_unlock_irqrestore(&rdev->mc_idx_lock, flags);
return r;
}
void rs400_mc_wreg(struct radeon_device *rdev, uint32_t reg, uint32_t v)
{
unsigned long flags;
spin_lock_irqsave(&rdev->mc_idx_lock, flags);
WREG32(RS480_NB_MC_INDEX, ((reg) & 0xff) | RS480_NB_MC_IND_WR_EN);
WREG32(RS480_NB_MC_DATA, (v));
WREG32(RS480_NB_MC_INDEX, 0xff);
spin_unlock_irqrestore(&rdev->mc_idx_lock, flags);
}
#if defined(CONFIG_DEBUG_FS)
static int rs400_debugfs_gart_info_show(struct seq_file *m, void *unused)
{
struct radeon_device *rdev = m->private;
uint32_t tmp;
tmp = RREG32(RADEON_HOST_PATH_CNTL);
seq_printf(m, "HOST_PATH_CNTL 0x%08x\n", tmp);
tmp = RREG32(RADEON_BUS_CNTL);
seq_printf(m, "BUS_CNTL 0x%08x\n", tmp);
tmp = RREG32_MC(RS690_AIC_CTRL_SCRATCH);
seq_printf(m, "AIC_CTRL_SCRATCH 0x%08x\n", tmp);
if (rdev->family == CHIP_RS690 || (rdev->family == CHIP_RS740)) {
tmp = RREG32_MC(RS690_MCCFG_AGP_BASE);
seq_printf(m, "MCCFG_AGP_BASE 0x%08x\n", tmp);
tmp = RREG32_MC(RS690_MCCFG_AGP_BASE_2);
seq_printf(m, "MCCFG_AGP_BASE_2 0x%08x\n", tmp);
tmp = RREG32_MC(RS690_MCCFG_AGP_LOCATION);
seq_printf(m, "MCCFG_AGP_LOCATION 0x%08x\n", tmp);
tmp = RREG32_MC(RS690_MCCFG_FB_LOCATION);
seq_printf(m, "MCCFG_FB_LOCATION 0x%08x\n", tmp);
tmp = RREG32(RS690_HDP_FB_LOCATION);
seq_printf(m, "HDP_FB_LOCATION 0x%08x\n", tmp);
} else {
tmp = RREG32(RADEON_AGP_BASE);
seq_printf(m, "AGP_BASE 0x%08x\n", tmp);
tmp = RREG32(RS480_AGP_BASE_2);
seq_printf(m, "AGP_BASE_2 0x%08x\n", tmp);
tmp = RREG32(RADEON_MC_AGP_LOCATION);
seq_printf(m, "MC_AGP_LOCATION 0x%08x\n", tmp);
}
tmp = RREG32_MC(RS480_GART_BASE);
seq_printf(m, "GART_BASE 0x%08x\n", tmp);
tmp = RREG32_MC(RS480_GART_FEATURE_ID);
seq_printf(m, "GART_FEATURE_ID 0x%08x\n", tmp);
tmp = RREG32_MC(RS480_AGP_MODE_CNTL);
seq_printf(m, "AGP_MODE_CONTROL 0x%08x\n", tmp);
tmp = RREG32_MC(RS480_MC_MISC_CNTL);
seq_printf(m, "MC_MISC_CNTL 0x%08x\n", tmp);
tmp = RREG32_MC(0x5F);
seq_printf(m, "MC_MISC_UMA_CNTL 0x%08x\n", tmp);
tmp = RREG32_MC(RS480_AGP_ADDRESS_SPACE_SIZE);
seq_printf(m, "AGP_ADDRESS_SPACE_SIZE 0x%08x\n", tmp);
tmp = RREG32_MC(RS480_GART_CACHE_CNTRL);
seq_printf(m, "GART_CACHE_CNTRL 0x%08x\n", tmp);
tmp = RREG32_MC(0x3B);
seq_printf(m, "MC_GART_ERROR_ADDRESS 0x%08x\n", tmp);
tmp = RREG32_MC(0x3C);
seq_printf(m, "MC_GART_ERROR_ADDRESS_HI 0x%08x\n", tmp);
tmp = RREG32_MC(0x30);
seq_printf(m, "GART_ERROR_0 0x%08x\n", tmp);
tmp = RREG32_MC(0x31);
seq_printf(m, "GART_ERROR_1 0x%08x\n", tmp);
tmp = RREG32_MC(0x32);
seq_printf(m, "GART_ERROR_2 0x%08x\n", tmp);
tmp = RREG32_MC(0x33);
seq_printf(m, "GART_ERROR_3 0x%08x\n", tmp);
tmp = RREG32_MC(0x34);
seq_printf(m, "GART_ERROR_4 0x%08x\n", tmp);
tmp = RREG32_MC(0x35);
seq_printf(m, "GART_ERROR_5 0x%08x\n", tmp);
tmp = RREG32_MC(0x36);
seq_printf(m, "GART_ERROR_6 0x%08x\n", tmp);
tmp = RREG32_MC(0x37);
seq_printf(m, "GART_ERROR_7 0x%08x\n", tmp);
return 0;
}
DEFINE_SHOW_ATTRIBUTE(rs400_debugfs_gart_info);
#endif
static void rs400_debugfs_pcie_gart_info_init(struct radeon_device *rdev)
{
#if defined(CONFIG_DEBUG_FS)
struct dentry *root = rdev->ddev->primary->debugfs_root;
debugfs_create_file("rs400_gart_info", 0444, root, rdev,
&rs400_debugfs_gart_info_fops);
#endif
}
static void rs400_mc_program(struct radeon_device *rdev)
{
struct r100_mc_save save;
/* Stops all mc clients */
r100_mc_stop(rdev, &save);
/* Wait for mc idle */
if (rs400_mc_wait_for_idle(rdev))
dev_warn(rdev->dev, "rs400: Wait MC idle timeout before updating MC.\n");
WREG32(R_000148_MC_FB_LOCATION,
S_000148_MC_FB_START(rdev->mc.vram_start >> 16) |
S_000148_MC_FB_TOP(rdev->mc.vram_end >> 16));
r100_mc_resume(rdev, &save);
}
static int rs400_startup(struct radeon_device *rdev)
{
int r;
r100_set_common_regs(rdev);
rs400_mc_program(rdev);
/* Resume clock */
r300_clock_startup(rdev);
/* Initialize GPU configuration (# pipes, ...) */
rs400_gpu_init(rdev);
r100_enable_bm(rdev);
/* Initialize GART (initialize after TTM so we can allocate
* memory through TTM but finalize after TTM) */
r = rs400_gart_enable(rdev);
if (r)
return r;
/* allocate wb buffer */
r = radeon_wb_init(rdev);
if (r)
return r;
r = radeon_fence_driver_start_ring(rdev, RADEON_RING_TYPE_GFX_INDEX);
if (r) {
dev_err(rdev->dev, "failed initializing CP fences (%d).\n", r);
return r;
}
/* Enable IRQ */
if (!rdev->irq.installed) {
r = radeon_irq_kms_init(rdev);
if (r)
return r;
}
r100_irq_set(rdev);
rdev->config.r300.hdp_cntl = RREG32(RADEON_HOST_PATH_CNTL);
/* 1M ring buffer */
r = r100_cp_init(rdev, 1024 * 1024);
if (r) {
dev_err(rdev->dev, "failed initializing CP (%d).\n", r);
return r;
}
r = radeon_ib_pool_init(rdev);
if (r) {
dev_err(rdev->dev, "IB initialization failed (%d).\n", r);
return r;
}
return 0;
}
int rs400_resume(struct radeon_device *rdev)
{
int r;
/* Make sur GART are not working */
rs400_gart_disable(rdev);
/* Resume clock before doing reset */
r300_clock_startup(rdev);
/* setup MC before calling post tables */
rs400_mc_program(rdev);
/* Reset gpu before posting otherwise ATOM will enter infinite loop */
if (radeon_asic_reset(rdev)) {
dev_warn(rdev->dev, "GPU reset failed ! (0xE40=0x%08X, 0x7C0=0x%08X)\n",
RREG32(R_000E40_RBBM_STATUS),
RREG32(R_0007C0_CP_STAT));
}
/* post */
radeon_combios_asic_init(rdev->ddev);
/* Resume clock after posting */
r300_clock_startup(rdev);
/* Initialize surface registers */
radeon_surface_init(rdev);
rdev->accel_working = true;
r = rs400_startup(rdev);
if (r) {
rdev->accel_working = false;
}
return r;
}
int rs400_suspend(struct radeon_device *rdev)
{
radeon_pm_suspend(rdev);
r100_cp_disable(rdev);
radeon_wb_disable(rdev);
r100_irq_disable(rdev);
rs400_gart_disable(rdev);
return 0;
}
void rs400_fini(struct radeon_device *rdev)
{
radeon_pm_fini(rdev);
r100_cp_fini(rdev);
radeon_wb_fini(rdev);
radeon_ib_pool_fini(rdev);
radeon_gem_fini(rdev);
rs400_gart_fini(rdev);
radeon_irq_kms_fini(rdev);
radeon_fence_driver_fini(rdev);
radeon_bo_fini(rdev);
radeon_atombios_fini(rdev);
kfree(rdev->bios);
rdev->bios = NULL;
}
int rs400_init(struct radeon_device *rdev)
{
int r;
/* Disable VGA */
r100_vga_render_disable(rdev);
/* Initialize scratch registers */
radeon_scratch_init(rdev);
/* Initialize surface registers */
radeon_surface_init(rdev);
/* TODO: disable VGA need to use VGA request */
/* restore some register to sane defaults */
r100_restore_sanity(rdev);
/* BIOS*/
if (!radeon_get_bios(rdev)) {
if (ASIC_IS_AVIVO(rdev))
return -EINVAL;
}
if (rdev->is_atom_bios) {
dev_err(rdev->dev, "Expecting combios for RS400/RS480 GPU\n");
return -EINVAL;
} else {
r = radeon_combios_init(rdev);
if (r)
return r;
}
/* Reset gpu before posting otherwise ATOM will enter infinite loop */
if (radeon_asic_reset(rdev)) {
dev_warn(rdev->dev,
"GPU reset failed ! (0xE40=0x%08X, 0x7C0=0x%08X)\n",
RREG32(R_000E40_RBBM_STATUS),
RREG32(R_0007C0_CP_STAT));
}
/* check if cards are posted or not */
if (radeon_boot_test_post_card(rdev) == false)
return -EINVAL;
/* Initialize clocks */
radeon_get_clock_info(rdev->ddev);
/* initialize memory controller */
rs400_mc_init(rdev);
/* Fence driver */
radeon_fence_driver_init(rdev);
/* Memory manager */
r = radeon_bo_init(rdev);
if (r)
return r;
r = rs400_gart_init(rdev);
if (r)
return r;
r300_set_reg_safe(rdev);
/* Initialize power management */
radeon_pm_init(rdev);
rdev->accel_working = true;
r = rs400_startup(rdev);
if (r) {
/* Somethings want wront with the accel init stop accel */
dev_err(rdev->dev, "Disabling GPU acceleration\n");
r100_cp_fini(rdev);
radeon_wb_fini(rdev);
radeon_ib_pool_fini(rdev);
rs400_gart_fini(rdev);
radeon_irq_kms_fini(rdev);
rdev->accel_working = false;
}
return 0;
}
| linux-master | drivers/gpu/drm/radeon/rs400.c |
/*
* Copyright 2014 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Slava Grigorev <[email protected]>
*/
#include <linux/gcd.h>
#include <linux/component.h>
#include <drm/drm_crtc.h>
#include "dce6_afmt.h"
#include "evergreen_hdmi.h"
#include "radeon.h"
#include "atom.h"
#include "r600.h"
#include "radeon_audio.h"
void dce6_audio_enable(struct radeon_device *rdev, struct r600_audio_pin *pin,
u8 enable_mask);
struct r600_audio_pin* r600_audio_get_pin(struct radeon_device *rdev);
struct r600_audio_pin* dce6_audio_get_pin(struct radeon_device *rdev);
static void radeon_audio_hdmi_mode_set(struct drm_encoder *encoder,
struct drm_display_mode *mode);
static void radeon_audio_dp_mode_set(struct drm_encoder *encoder,
struct drm_display_mode *mode);
static const u32 pin_offsets[7] =
{
(0x5e00 - 0x5e00),
(0x5e18 - 0x5e00),
(0x5e30 - 0x5e00),
(0x5e48 - 0x5e00),
(0x5e60 - 0x5e00),
(0x5e78 - 0x5e00),
(0x5e90 - 0x5e00),
};
static u32 radeon_audio_rreg(struct radeon_device *rdev, u32 offset, u32 reg)
{
return RREG32(reg);
}
static void radeon_audio_wreg(struct radeon_device *rdev, u32 offset,
u32 reg, u32 v)
{
WREG32(reg, v);
}
static struct radeon_audio_basic_funcs r600_funcs = {
.endpoint_rreg = radeon_audio_rreg,
.endpoint_wreg = radeon_audio_wreg,
.enable = r600_audio_enable,
};
static struct radeon_audio_basic_funcs dce32_funcs = {
.endpoint_rreg = radeon_audio_rreg,
.endpoint_wreg = radeon_audio_wreg,
.enable = r600_audio_enable,
};
static struct radeon_audio_basic_funcs dce4_funcs = {
.endpoint_rreg = radeon_audio_rreg,
.endpoint_wreg = radeon_audio_wreg,
.enable = dce4_audio_enable,
};
static struct radeon_audio_basic_funcs dce6_funcs = {
.endpoint_rreg = dce6_endpoint_rreg,
.endpoint_wreg = dce6_endpoint_wreg,
.enable = dce6_audio_enable,
};
static struct radeon_audio_funcs r600_hdmi_funcs = {
.get_pin = r600_audio_get_pin,
.set_dto = r600_hdmi_audio_set_dto,
.update_acr = r600_hdmi_update_acr,
.set_vbi_packet = r600_set_vbi_packet,
.set_avi_packet = r600_set_avi_packet,
.set_audio_packet = r600_set_audio_packet,
.set_mute = r600_set_mute,
.mode_set = radeon_audio_hdmi_mode_set,
.dpms = r600_hdmi_enable,
};
static struct radeon_audio_funcs dce32_hdmi_funcs = {
.get_pin = r600_audio_get_pin,
.write_sad_regs = dce3_2_afmt_write_sad_regs,
.write_speaker_allocation = dce3_2_afmt_hdmi_write_speaker_allocation,
.set_dto = dce3_2_audio_set_dto,
.update_acr = dce3_2_hdmi_update_acr,
.set_vbi_packet = r600_set_vbi_packet,
.set_avi_packet = r600_set_avi_packet,
.set_audio_packet = dce3_2_set_audio_packet,
.set_mute = dce3_2_set_mute,
.mode_set = radeon_audio_hdmi_mode_set,
.dpms = r600_hdmi_enable,
};
static struct radeon_audio_funcs dce32_dp_funcs = {
.get_pin = r600_audio_get_pin,
.write_sad_regs = dce3_2_afmt_write_sad_regs,
.write_speaker_allocation = dce3_2_afmt_dp_write_speaker_allocation,
.set_dto = dce3_2_audio_set_dto,
.set_avi_packet = r600_set_avi_packet,
.set_audio_packet = dce3_2_set_audio_packet,
};
static struct radeon_audio_funcs dce4_hdmi_funcs = {
.get_pin = r600_audio_get_pin,
.write_sad_regs = evergreen_hdmi_write_sad_regs,
.write_speaker_allocation = dce4_afmt_hdmi_write_speaker_allocation,
.write_latency_fields = dce4_afmt_write_latency_fields,
.set_dto = dce4_hdmi_audio_set_dto,
.update_acr = evergreen_hdmi_update_acr,
.set_vbi_packet = dce4_set_vbi_packet,
.set_color_depth = dce4_hdmi_set_color_depth,
.set_avi_packet = evergreen_set_avi_packet,
.set_audio_packet = dce4_set_audio_packet,
.set_mute = dce4_set_mute,
.mode_set = radeon_audio_hdmi_mode_set,
.dpms = evergreen_hdmi_enable,
};
static struct radeon_audio_funcs dce4_dp_funcs = {
.get_pin = r600_audio_get_pin,
.write_sad_regs = evergreen_hdmi_write_sad_regs,
.write_speaker_allocation = dce4_afmt_dp_write_speaker_allocation,
.write_latency_fields = dce4_afmt_write_latency_fields,
.set_dto = dce4_dp_audio_set_dto,
.set_avi_packet = evergreen_set_avi_packet,
.set_audio_packet = dce4_set_audio_packet,
.mode_set = radeon_audio_dp_mode_set,
.dpms = evergreen_dp_enable,
};
static struct radeon_audio_funcs dce6_hdmi_funcs = {
.select_pin = dce6_afmt_select_pin,
.get_pin = dce6_audio_get_pin,
.write_sad_regs = dce6_afmt_write_sad_regs,
.write_speaker_allocation = dce6_afmt_hdmi_write_speaker_allocation,
.write_latency_fields = dce6_afmt_write_latency_fields,
.set_dto = dce6_hdmi_audio_set_dto,
.update_acr = evergreen_hdmi_update_acr,
.set_vbi_packet = dce4_set_vbi_packet,
.set_color_depth = dce4_hdmi_set_color_depth,
.set_avi_packet = evergreen_set_avi_packet,
.set_audio_packet = dce4_set_audio_packet,
.set_mute = dce4_set_mute,
.mode_set = radeon_audio_hdmi_mode_set,
.dpms = evergreen_hdmi_enable,
};
static struct radeon_audio_funcs dce6_dp_funcs = {
.select_pin = dce6_afmt_select_pin,
.get_pin = dce6_audio_get_pin,
.write_sad_regs = dce6_afmt_write_sad_regs,
.write_speaker_allocation = dce6_afmt_dp_write_speaker_allocation,
.write_latency_fields = dce6_afmt_write_latency_fields,
.set_dto = dce6_dp_audio_set_dto,
.set_avi_packet = evergreen_set_avi_packet,
.set_audio_packet = dce4_set_audio_packet,
.mode_set = radeon_audio_dp_mode_set,
.dpms = evergreen_dp_enable,
};
static void radeon_audio_component_notify(struct radeon_device *rdev, int port);
static void radeon_audio_enable(struct radeon_device *rdev,
struct r600_audio_pin *pin, u8 enable_mask)
{
struct drm_encoder *encoder;
struct radeon_encoder *radeon_encoder;
struct radeon_encoder_atom_dig *dig;
int pin_count = 0;
if (!pin)
return;
if (rdev->mode_info.mode_config_initialized) {
list_for_each_entry(encoder, &rdev->ddev->mode_config.encoder_list, head) {
if (radeon_encoder_is_digital(encoder)) {
radeon_encoder = to_radeon_encoder(encoder);
dig = radeon_encoder->enc_priv;
if (dig->pin == pin)
pin_count++;
}
}
if ((pin_count > 1) && (enable_mask == 0))
return;
}
if (rdev->audio.funcs->enable)
rdev->audio.funcs->enable(rdev, pin, enable_mask);
radeon_audio_component_notify(rdev, pin->id);
}
static void radeon_audio_interface_init(struct radeon_device *rdev)
{
if (ASIC_IS_DCE6(rdev)) {
rdev->audio.funcs = &dce6_funcs;
rdev->audio.hdmi_funcs = &dce6_hdmi_funcs;
rdev->audio.dp_funcs = &dce6_dp_funcs;
} else if (ASIC_IS_DCE4(rdev)) {
rdev->audio.funcs = &dce4_funcs;
rdev->audio.hdmi_funcs = &dce4_hdmi_funcs;
rdev->audio.dp_funcs = &dce4_dp_funcs;
} else if (ASIC_IS_DCE32(rdev)) {
rdev->audio.funcs = &dce32_funcs;
rdev->audio.hdmi_funcs = &dce32_hdmi_funcs;
rdev->audio.dp_funcs = &dce32_dp_funcs;
} else {
rdev->audio.funcs = &r600_funcs;
rdev->audio.hdmi_funcs = &r600_hdmi_funcs;
rdev->audio.dp_funcs = NULL;
}
}
static int radeon_audio_chipset_supported(struct radeon_device *rdev)
{
return ASIC_IS_DCE2(rdev) && !ASIC_IS_NODCE(rdev);
}
int radeon_audio_init(struct radeon_device *rdev)
{
int i;
if (!radeon_audio || !radeon_audio_chipset_supported(rdev))
return 0;
rdev->audio.enabled = true;
if (ASIC_IS_DCE83(rdev)) /* KB: 2 streams, 3 endpoints */
rdev->audio.num_pins = 3;
else if (ASIC_IS_DCE81(rdev)) /* KV: 4 streams, 7 endpoints */
rdev->audio.num_pins = 7;
else if (ASIC_IS_DCE8(rdev)) /* BN/HW: 6 streams, 7 endpoints */
rdev->audio.num_pins = 7;
else if (ASIC_IS_DCE64(rdev)) /* OL: 2 streams, 2 endpoints */
rdev->audio.num_pins = 2;
else if (ASIC_IS_DCE61(rdev)) /* TN: 4 streams, 6 endpoints */
rdev->audio.num_pins = 6;
else if (ASIC_IS_DCE6(rdev)) /* SI: 6 streams, 6 endpoints */
rdev->audio.num_pins = 6;
else
rdev->audio.num_pins = 1;
for (i = 0; i < rdev->audio.num_pins; i++) {
rdev->audio.pin[i].channels = -1;
rdev->audio.pin[i].rate = -1;
rdev->audio.pin[i].bits_per_sample = -1;
rdev->audio.pin[i].status_bits = 0;
rdev->audio.pin[i].category_code = 0;
rdev->audio.pin[i].connected = false;
rdev->audio.pin[i].offset = pin_offsets[i];
rdev->audio.pin[i].id = i;
}
radeon_audio_interface_init(rdev);
/* disable audio. it will be set up later */
for (i = 0; i < rdev->audio.num_pins; i++)
radeon_audio_enable(rdev, &rdev->audio.pin[i], 0);
return 0;
}
u32 radeon_audio_endpoint_rreg(struct radeon_device *rdev, u32 offset, u32 reg)
{
if (rdev->audio.funcs->endpoint_rreg)
return rdev->audio.funcs->endpoint_rreg(rdev, offset, reg);
return 0;
}
void radeon_audio_endpoint_wreg(struct radeon_device *rdev, u32 offset,
u32 reg, u32 v)
{
if (rdev->audio.funcs->endpoint_wreg)
rdev->audio.funcs->endpoint_wreg(rdev, offset, reg, v);
}
static void radeon_audio_write_sad_regs(struct drm_encoder *encoder)
{
struct drm_connector *connector = radeon_get_connector_for_encoder(encoder);
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct cea_sad *sads;
int sad_count;
if (!connector)
return;
sad_count = drm_edid_to_sad(radeon_connector_edid(connector), &sads);
if (sad_count < 0)
DRM_ERROR("Couldn't read SADs: %d\n", sad_count);
if (sad_count <= 0)
return;
BUG_ON(!sads);
if (radeon_encoder->audio && radeon_encoder->audio->write_sad_regs)
radeon_encoder->audio->write_sad_regs(encoder, sads, sad_count);
kfree(sads);
}
static void radeon_audio_write_speaker_allocation(struct drm_encoder *encoder)
{
struct drm_connector *connector = radeon_get_connector_for_encoder(encoder);
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
u8 *sadb = NULL;
int sad_count;
if (!connector)
return;
sad_count = drm_edid_to_speaker_allocation(radeon_connector_edid(connector),
&sadb);
if (sad_count < 0) {
DRM_DEBUG("Couldn't read Speaker Allocation Data Block: %d\n",
sad_count);
sad_count = 0;
}
if (radeon_encoder->audio && radeon_encoder->audio->write_speaker_allocation)
radeon_encoder->audio->write_speaker_allocation(encoder, sadb, sad_count);
kfree(sadb);
}
static void radeon_audio_write_latency_fields(struct drm_encoder *encoder,
struct drm_display_mode *mode)
{
struct drm_connector *connector = radeon_get_connector_for_encoder(encoder);
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
if (!connector)
return;
if (radeon_encoder->audio && radeon_encoder->audio->write_latency_fields)
radeon_encoder->audio->write_latency_fields(encoder, connector, mode);
}
struct r600_audio_pin* radeon_audio_get_pin(struct drm_encoder *encoder)
{
struct radeon_device *rdev = encoder->dev->dev_private;
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
if (radeon_encoder->audio && radeon_encoder->audio->get_pin)
return radeon_encoder->audio->get_pin(rdev);
return NULL;
}
static void radeon_audio_select_pin(struct drm_encoder *encoder)
{
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
if (radeon_encoder->audio && radeon_encoder->audio->select_pin)
radeon_encoder->audio->select_pin(encoder);
}
void radeon_audio_detect(struct drm_connector *connector,
struct drm_encoder *encoder,
enum drm_connector_status status)
{
struct drm_device *dev = connector->dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct radeon_encoder_atom_dig *dig;
if (!radeon_audio_chipset_supported(rdev))
return;
if (!radeon_encoder_is_digital(encoder))
return;
dig = radeon_encoder->enc_priv;
if (status == connector_status_connected) {
if (connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
struct radeon_connector *radeon_connector = to_radeon_connector(connector);
if (radeon_dp_getsinktype(radeon_connector) ==
CONNECTOR_OBJECT_ID_DISPLAYPORT)
radeon_encoder->audio = rdev->audio.dp_funcs;
else
radeon_encoder->audio = rdev->audio.hdmi_funcs;
} else {
radeon_encoder->audio = rdev->audio.hdmi_funcs;
}
if (drm_detect_monitor_audio(radeon_connector_edid(connector))) {
if (!dig->pin)
dig->pin = radeon_audio_get_pin(encoder);
radeon_audio_enable(rdev, dig->pin, 0xf);
} else {
radeon_audio_enable(rdev, dig->pin, 0);
dig->pin = NULL;
}
} else {
radeon_audio_enable(rdev, dig->pin, 0);
dig->pin = NULL;
}
}
void radeon_audio_fini(struct radeon_device *rdev)
{
int i;
if (!rdev->audio.enabled)
return;
for (i = 0; i < rdev->audio.num_pins; i++)
radeon_audio_enable(rdev, &rdev->audio.pin[i], 0);
rdev->audio.enabled = false;
}
static void radeon_audio_set_dto(struct drm_encoder *encoder, unsigned int clock)
{
struct radeon_device *rdev = encoder->dev->dev_private;
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct radeon_crtc *crtc = to_radeon_crtc(encoder->crtc);
if (radeon_encoder->audio && radeon_encoder->audio->set_dto)
radeon_encoder->audio->set_dto(rdev, crtc, clock);
}
static int radeon_audio_set_avi_packet(struct drm_encoder *encoder,
struct drm_display_mode *mode)
{
struct radeon_device *rdev = encoder->dev->dev_private;
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct radeon_encoder_atom_dig *dig = radeon_encoder->enc_priv;
struct drm_connector *connector = radeon_get_connector_for_encoder(encoder);
u8 buffer[HDMI_INFOFRAME_HEADER_SIZE + HDMI_AVI_INFOFRAME_SIZE];
struct hdmi_avi_infoframe frame;
int err;
if (!connector)
return -EINVAL;
err = drm_hdmi_avi_infoframe_from_display_mode(&frame, connector, mode);
if (err < 0) {
DRM_ERROR("failed to setup AVI infoframe: %d\n", err);
return err;
}
if (radeon_encoder->output_csc != RADEON_OUTPUT_CSC_BYPASS) {
drm_hdmi_avi_infoframe_quant_range(&frame, connector, mode,
radeon_encoder->output_csc == RADEON_OUTPUT_CSC_TVRGB ?
HDMI_QUANTIZATION_RANGE_LIMITED :
HDMI_QUANTIZATION_RANGE_FULL);
}
err = hdmi_avi_infoframe_pack(&frame, buffer, sizeof(buffer));
if (err < 0) {
DRM_ERROR("failed to pack AVI infoframe: %d\n", err);
return err;
}
if (dig && dig->afmt && radeon_encoder->audio &&
radeon_encoder->audio->set_avi_packet)
radeon_encoder->audio->set_avi_packet(rdev, dig->afmt->offset,
buffer, sizeof(buffer));
return 0;
}
/*
* calculate CTS and N values if they are not found in the table
*/
static void radeon_audio_calc_cts(unsigned int clock, int *CTS, int *N, int freq)
{
int n, cts;
unsigned long div, mul;
/* Safe, but overly large values */
n = 128 * freq;
cts = clock * 1000;
/* Smallest valid fraction */
div = gcd(n, cts);
n /= div;
cts /= div;
/*
* The optimal N is 128*freq/1000. Calculate the closest larger
* value that doesn't truncate any bits.
*/
mul = ((128*freq/1000) + (n-1))/n;
n *= mul;
cts *= mul;
/* Check that we are in spec (not always possible) */
if (n < (128*freq/1500))
pr_warn("Calculated ACR N value is too small. You may experience audio problems.\n");
if (n > (128*freq/300))
pr_warn("Calculated ACR N value is too large. You may experience audio problems.\n");
*N = n;
*CTS = cts;
DRM_DEBUG("Calculated ACR timing N=%d CTS=%d for frequency %d\n",
*N, *CTS, freq);
}
static const struct radeon_hdmi_acr* radeon_audio_acr(unsigned int clock)
{
static struct radeon_hdmi_acr res;
u8 i;
static const struct radeon_hdmi_acr hdmi_predefined_acr[] = {
/* 32kHz 44.1kHz 48kHz */
/* Clock N CTS N CTS N CTS */
{ 25175, 4096, 25175, 28224, 125875, 6144, 25175 }, /* 25,20/1.001 MHz */
{ 25200, 4096, 25200, 6272, 28000, 6144, 25200 }, /* 25.20 MHz */
{ 27000, 4096, 27000, 6272, 30000, 6144, 27000 }, /* 27.00 MHz */
{ 27027, 4096, 27027, 6272, 30030, 6144, 27027 }, /* 27.00*1.001 MHz */
{ 54000, 4096, 54000, 6272, 60000, 6144, 54000 }, /* 54.00 MHz */
{ 54054, 4096, 54054, 6272, 60060, 6144, 54054 }, /* 54.00*1.001 MHz */
{ 74176, 4096, 74176, 5733, 75335, 6144, 74176 }, /* 74.25/1.001 MHz */
{ 74250, 4096, 74250, 6272, 82500, 6144, 74250 }, /* 74.25 MHz */
{ 148352, 4096, 148352, 5733, 150670, 6144, 148352 }, /* 148.50/1.001 MHz */
{ 148500, 4096, 148500, 6272, 165000, 6144, 148500 }, /* 148.50 MHz */
};
/* Precalculated values for common clocks */
for (i = 0; i < ARRAY_SIZE(hdmi_predefined_acr); i++)
if (hdmi_predefined_acr[i].clock == clock)
return &hdmi_predefined_acr[i];
/* And odd clocks get manually calculated */
radeon_audio_calc_cts(clock, &res.cts_32khz, &res.n_32khz, 32000);
radeon_audio_calc_cts(clock, &res.cts_44_1khz, &res.n_44_1khz, 44100);
radeon_audio_calc_cts(clock, &res.cts_48khz, &res.n_48khz, 48000);
return &res;
}
/*
* update the N and CTS parameters for a given pixel clock rate
*/
static void radeon_audio_update_acr(struct drm_encoder *encoder, unsigned int clock)
{
const struct radeon_hdmi_acr *acr = radeon_audio_acr(clock);
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct radeon_encoder_atom_dig *dig = radeon_encoder->enc_priv;
if (!dig || !dig->afmt)
return;
if (radeon_encoder->audio && radeon_encoder->audio->update_acr)
radeon_encoder->audio->update_acr(encoder, dig->afmt->offset, acr);
}
static void radeon_audio_set_vbi_packet(struct drm_encoder *encoder)
{
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct radeon_encoder_atom_dig *dig = radeon_encoder->enc_priv;
if (!dig || !dig->afmt)
return;
if (radeon_encoder->audio && radeon_encoder->audio->set_vbi_packet)
radeon_encoder->audio->set_vbi_packet(encoder, dig->afmt->offset);
}
static void radeon_hdmi_set_color_depth(struct drm_encoder *encoder)
{
int bpc = 8;
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct radeon_encoder_atom_dig *dig = radeon_encoder->enc_priv;
if (!dig || !dig->afmt)
return;
if (encoder->crtc) {
struct radeon_crtc *radeon_crtc = to_radeon_crtc(encoder->crtc);
bpc = radeon_crtc->bpc;
}
if (radeon_encoder->audio && radeon_encoder->audio->set_color_depth)
radeon_encoder->audio->set_color_depth(encoder, dig->afmt->offset, bpc);
}
static void radeon_audio_set_audio_packet(struct drm_encoder *encoder)
{
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct radeon_encoder_atom_dig *dig = radeon_encoder->enc_priv;
if (!dig || !dig->afmt)
return;
if (radeon_encoder->audio && radeon_encoder->audio->set_audio_packet)
radeon_encoder->audio->set_audio_packet(encoder, dig->afmt->offset);
}
static void radeon_audio_set_mute(struct drm_encoder *encoder, bool mute)
{
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct radeon_encoder_atom_dig *dig = radeon_encoder->enc_priv;
if (!dig || !dig->afmt)
return;
if (radeon_encoder->audio && radeon_encoder->audio->set_mute)
radeon_encoder->audio->set_mute(encoder, dig->afmt->offset, mute);
}
/*
* update the info frames with the data from the current display mode
*/
static void radeon_audio_hdmi_mode_set(struct drm_encoder *encoder,
struct drm_display_mode *mode)
{
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct radeon_encoder_atom_dig *dig = radeon_encoder->enc_priv;
struct drm_connector *connector = radeon_get_connector_for_encoder(encoder);
if (!dig || !dig->afmt)
return;
if (!connector)
return;
if (drm_detect_monitor_audio(radeon_connector_edid(connector))) {
radeon_audio_set_mute(encoder, true);
radeon_audio_write_speaker_allocation(encoder);
radeon_audio_write_sad_regs(encoder);
radeon_audio_write_latency_fields(encoder, mode);
radeon_audio_set_dto(encoder, mode->clock);
radeon_audio_set_vbi_packet(encoder);
radeon_hdmi_set_color_depth(encoder);
radeon_audio_update_acr(encoder, mode->clock);
radeon_audio_set_audio_packet(encoder);
radeon_audio_select_pin(encoder);
if (radeon_audio_set_avi_packet(encoder, mode) < 0)
return;
radeon_audio_set_mute(encoder, false);
} else {
radeon_hdmi_set_color_depth(encoder);
if (radeon_audio_set_avi_packet(encoder, mode) < 0)
return;
}
}
static void radeon_audio_dp_mode_set(struct drm_encoder *encoder,
struct drm_display_mode *mode)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct radeon_encoder_atom_dig *dig = radeon_encoder->enc_priv;
struct drm_connector *connector = radeon_get_connector_for_encoder(encoder);
if (!dig || !dig->afmt)
return;
if (!connector)
return;
if (drm_detect_monitor_audio(radeon_connector_edid(connector))) {
radeon_audio_write_speaker_allocation(encoder);
radeon_audio_write_sad_regs(encoder);
radeon_audio_write_latency_fields(encoder, mode);
radeon_audio_set_dto(encoder, rdev->clock.vco_freq * 10);
radeon_audio_set_audio_packet(encoder);
radeon_audio_select_pin(encoder);
if (radeon_audio_set_avi_packet(encoder, mode) < 0)
return;
}
}
void radeon_audio_mode_set(struct drm_encoder *encoder,
struct drm_display_mode *mode)
{
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
if (radeon_encoder->audio && radeon_encoder->audio->mode_set)
radeon_encoder->audio->mode_set(encoder, mode);
}
void radeon_audio_dpms(struct drm_encoder *encoder, int mode)
{
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
if (radeon_encoder->audio && radeon_encoder->audio->dpms)
radeon_encoder->audio->dpms(encoder, mode == DRM_MODE_DPMS_ON);
}
unsigned int radeon_audio_decode_dfs_div(unsigned int div)
{
if (div >= 8 && div < 64)
return (div - 8) * 25 + 200;
else if (div >= 64 && div < 96)
return (div - 64) * 50 + 1600;
else if (div >= 96 && div < 128)
return (div - 96) * 100 + 3200;
else
return 0;
}
/*
* Audio component support
*/
static void radeon_audio_component_notify(struct radeon_device *rdev, int port)
{
struct drm_audio_component *acomp;
mutex_lock(&rdev->audio.component_mutex);
acomp = rdev->audio.component;
if (acomp && acomp->audio_ops && acomp->audio_ops->pin_eld_notify)
acomp->audio_ops->pin_eld_notify(acomp->audio_ops->audio_ptr,
port, -1);
mutex_unlock(&rdev->audio.component_mutex);
}
static int radeon_audio_component_get_eld(struct device *kdev, int port,
int pipe, bool *enabled,
unsigned char *buf, int max_bytes)
{
struct drm_device *dev = dev_get_drvdata(kdev);
struct radeon_device *rdev = dev->dev_private;
struct drm_encoder *encoder;
struct radeon_encoder *radeon_encoder;
struct radeon_encoder_atom_dig *dig;
struct drm_connector *connector;
int ret = 0;
*enabled = false;
if (!rdev->audio.enabled || !rdev->mode_info.mode_config_initialized)
return 0;
list_for_each_entry(encoder, &rdev->ddev->mode_config.encoder_list, head) {
if (!radeon_encoder_is_digital(encoder))
continue;
radeon_encoder = to_radeon_encoder(encoder);
dig = radeon_encoder->enc_priv;
if (!dig->pin || dig->pin->id != port)
continue;
connector = radeon_get_connector_for_encoder(encoder);
if (!connector)
continue;
*enabled = true;
ret = drm_eld_size(connector->eld);
memcpy(buf, connector->eld, min(max_bytes, ret));
break;
}
return ret;
}
static const struct drm_audio_component_ops radeon_audio_component_ops = {
.get_eld = radeon_audio_component_get_eld,
};
static int radeon_audio_component_bind(struct device *kdev,
struct device *hda_kdev, void *data)
{
struct drm_device *dev = dev_get_drvdata(kdev);
struct radeon_device *rdev = dev->dev_private;
struct drm_audio_component *acomp = data;
if (WARN_ON(!device_link_add(hda_kdev, kdev, DL_FLAG_STATELESS)))
return -ENOMEM;
mutex_lock(&rdev->audio.component_mutex);
acomp->ops = &radeon_audio_component_ops;
acomp->dev = kdev;
rdev->audio.component = acomp;
mutex_unlock(&rdev->audio.component_mutex);
return 0;
}
static void radeon_audio_component_unbind(struct device *kdev,
struct device *hda_kdev, void *data)
{
struct drm_device *dev = dev_get_drvdata(kdev);
struct radeon_device *rdev = dev->dev_private;
struct drm_audio_component *acomp = data;
device_link_remove(hda_kdev, kdev);
mutex_lock(&rdev->audio.component_mutex);
rdev->audio.component = NULL;
acomp->ops = NULL;
acomp->dev = NULL;
mutex_unlock(&rdev->audio.component_mutex);
}
static const struct component_ops radeon_audio_component_bind_ops = {
.bind = radeon_audio_component_bind,
.unbind = radeon_audio_component_unbind,
};
void radeon_audio_component_init(struct radeon_device *rdev)
{
if (rdev->audio.component_registered ||
!radeon_audio || !radeon_audio_chipset_supported(rdev))
return;
if (!component_add(rdev->dev, &radeon_audio_component_bind_ops))
rdev->audio.component_registered = true;
}
void radeon_audio_component_fini(struct radeon_device *rdev)
{
if (rdev->audio.component_registered) {
component_del(rdev->dev, &radeon_audio_component_bind_ops);
rdev->audio.component_registered = false;
}
}
| linux-master | drivers/gpu/drm/radeon/radeon_audio.c |
/*
* SPDX-License-Identifier: MIT
*
* (C) Copyright 2016 Intel Corporation
*/
#include <linux/slab.h>
#include <linux/dma-fence.h>
#include <linux/irq_work.h>
#include <linux/dma-resv.h>
#include "i915_sw_fence.h"
#include "i915_selftest.h"
#if IS_ENABLED(CONFIG_DRM_I915_DEBUG)
#define I915_SW_FENCE_BUG_ON(expr) BUG_ON(expr)
#else
#define I915_SW_FENCE_BUG_ON(expr) BUILD_BUG_ON_INVALID(expr)
#endif
#ifdef CONFIG_DRM_I915_SW_FENCE_CHECK_DAG
static DEFINE_SPINLOCK(i915_sw_fence_lock);
#endif
#define WQ_FLAG_BITS \
BITS_PER_TYPE(typeof_member(struct wait_queue_entry, flags))
/* after WQ_FLAG_* for safety */
#define I915_SW_FENCE_FLAG_FENCE BIT(WQ_FLAG_BITS - 1)
#define I915_SW_FENCE_FLAG_ALLOC BIT(WQ_FLAG_BITS - 2)
enum {
DEBUG_FENCE_IDLE = 0,
DEBUG_FENCE_NOTIFY,
};
static void *i915_sw_fence_debug_hint(void *addr)
{
return (void *)(((struct i915_sw_fence *)addr)->fn);
}
#ifdef CONFIG_DRM_I915_SW_FENCE_DEBUG_OBJECTS
static const struct debug_obj_descr i915_sw_fence_debug_descr = {
.name = "i915_sw_fence",
.debug_hint = i915_sw_fence_debug_hint,
};
static inline void debug_fence_init(struct i915_sw_fence *fence)
{
debug_object_init(fence, &i915_sw_fence_debug_descr);
}
static inline void debug_fence_init_onstack(struct i915_sw_fence *fence)
{
debug_object_init_on_stack(fence, &i915_sw_fence_debug_descr);
}
static inline void debug_fence_activate(struct i915_sw_fence *fence)
{
debug_object_activate(fence, &i915_sw_fence_debug_descr);
}
static inline void debug_fence_set_state(struct i915_sw_fence *fence,
int old, int new)
{
debug_object_active_state(fence, &i915_sw_fence_debug_descr, old, new);
}
static inline void debug_fence_deactivate(struct i915_sw_fence *fence)
{
debug_object_deactivate(fence, &i915_sw_fence_debug_descr);
}
static inline void debug_fence_destroy(struct i915_sw_fence *fence)
{
debug_object_destroy(fence, &i915_sw_fence_debug_descr);
}
static inline void debug_fence_free(struct i915_sw_fence *fence)
{
debug_object_free(fence, &i915_sw_fence_debug_descr);
smp_wmb(); /* flush the change in state before reallocation */
}
static inline void debug_fence_assert(struct i915_sw_fence *fence)
{
debug_object_assert_init(fence, &i915_sw_fence_debug_descr);
}
#else
static inline void debug_fence_init(struct i915_sw_fence *fence)
{
}
static inline void debug_fence_init_onstack(struct i915_sw_fence *fence)
{
}
static inline void debug_fence_activate(struct i915_sw_fence *fence)
{
}
static inline void debug_fence_set_state(struct i915_sw_fence *fence,
int old, int new)
{
}
static inline void debug_fence_deactivate(struct i915_sw_fence *fence)
{
}
static inline void debug_fence_destroy(struct i915_sw_fence *fence)
{
}
static inline void debug_fence_free(struct i915_sw_fence *fence)
{
}
static inline void debug_fence_assert(struct i915_sw_fence *fence)
{
}
#endif
static int __i915_sw_fence_notify(struct i915_sw_fence *fence,
enum i915_sw_fence_notify state)
{
return fence->fn(fence, state);
}
#ifdef CONFIG_DRM_I915_SW_FENCE_DEBUG_OBJECTS
void i915_sw_fence_fini(struct i915_sw_fence *fence)
{
debug_fence_free(fence);
}
#endif
static void __i915_sw_fence_wake_up_all(struct i915_sw_fence *fence,
struct list_head *continuation)
{
wait_queue_head_t *x = &fence->wait;
wait_queue_entry_t *pos, *next;
unsigned long flags;
debug_fence_deactivate(fence);
atomic_set_release(&fence->pending, -1); /* 0 -> -1 [done] */
/*
* To prevent unbounded recursion as we traverse the graph of
* i915_sw_fences, we move the entry list from this, the next ready
* fence, to the tail of the original fence's entry list
* (and so added to the list to be woken).
*/
spin_lock_irqsave_nested(&x->lock, flags, 1 + !!continuation);
if (continuation) {
list_for_each_entry_safe(pos, next, &x->head, entry) {
if (pos->flags & I915_SW_FENCE_FLAG_FENCE)
list_move_tail(&pos->entry, continuation);
else
pos->func(pos, TASK_NORMAL, 0, continuation);
}
} else {
LIST_HEAD(extra);
do {
list_for_each_entry_safe(pos, next, &x->head, entry) {
int wake_flags;
wake_flags = 0;
if (pos->flags & I915_SW_FENCE_FLAG_FENCE)
wake_flags = fence->error;
pos->func(pos, TASK_NORMAL, wake_flags, &extra);
}
if (list_empty(&extra))
break;
list_splice_tail_init(&extra, &x->head);
} while (1);
}
spin_unlock_irqrestore(&x->lock, flags);
debug_fence_assert(fence);
}
static void __i915_sw_fence_complete(struct i915_sw_fence *fence,
struct list_head *continuation)
{
debug_fence_assert(fence);
if (!atomic_dec_and_test(&fence->pending))
return;
debug_fence_set_state(fence, DEBUG_FENCE_IDLE, DEBUG_FENCE_NOTIFY);
if (__i915_sw_fence_notify(fence, FENCE_COMPLETE) != NOTIFY_DONE)
return;
debug_fence_set_state(fence, DEBUG_FENCE_NOTIFY, DEBUG_FENCE_IDLE);
__i915_sw_fence_wake_up_all(fence, continuation);
debug_fence_destroy(fence);
__i915_sw_fence_notify(fence, FENCE_FREE);
}
void i915_sw_fence_complete(struct i915_sw_fence *fence)
{
debug_fence_assert(fence);
if (WARN_ON(i915_sw_fence_done(fence)))
return;
__i915_sw_fence_complete(fence, NULL);
}
bool i915_sw_fence_await(struct i915_sw_fence *fence)
{
int pending;
/*
* It is only safe to add a new await to the fence while it has
* not yet been signaled (i.e. there are still existing signalers).
*/
pending = atomic_read(&fence->pending);
do {
if (pending < 1)
return false;
} while (!atomic_try_cmpxchg(&fence->pending, &pending, pending + 1));
return true;
}
void __i915_sw_fence_init(struct i915_sw_fence *fence,
i915_sw_fence_notify_t fn,
const char *name,
struct lock_class_key *key)
{
__init_waitqueue_head(&fence->wait, name, key);
fence->fn = fn;
#ifdef CONFIG_DRM_I915_SW_FENCE_CHECK_DAG
fence->flags = 0;
#endif
i915_sw_fence_reinit(fence);
}
void i915_sw_fence_reinit(struct i915_sw_fence *fence)
{
debug_fence_init(fence);
atomic_set(&fence->pending, 1);
fence->error = 0;
I915_SW_FENCE_BUG_ON(!list_empty(&fence->wait.head));
}
void i915_sw_fence_commit(struct i915_sw_fence *fence)
{
debug_fence_activate(fence);
i915_sw_fence_complete(fence);
}
static int i915_sw_fence_wake(wait_queue_entry_t *wq, unsigned mode, int flags, void *key)
{
i915_sw_fence_set_error_once(wq->private, flags);
list_del(&wq->entry);
__i915_sw_fence_complete(wq->private, key);
if (wq->flags & I915_SW_FENCE_FLAG_ALLOC)
kfree(wq);
return 0;
}
#ifdef CONFIG_DRM_I915_SW_FENCE_CHECK_DAG
static bool __i915_sw_fence_check_if_after(struct i915_sw_fence *fence,
const struct i915_sw_fence * const signaler)
{
wait_queue_entry_t *wq;
if (__test_and_set_bit(I915_SW_FENCE_CHECKED_BIT, &fence->flags))
return false;
if (fence == signaler)
return true;
list_for_each_entry(wq, &fence->wait.head, entry) {
if (wq->func != i915_sw_fence_wake)
continue;
if (__i915_sw_fence_check_if_after(wq->private, signaler))
return true;
}
return false;
}
static void __i915_sw_fence_clear_checked_bit(struct i915_sw_fence *fence)
{
wait_queue_entry_t *wq;
if (!__test_and_clear_bit(I915_SW_FENCE_CHECKED_BIT, &fence->flags))
return;
list_for_each_entry(wq, &fence->wait.head, entry) {
if (wq->func != i915_sw_fence_wake)
continue;
__i915_sw_fence_clear_checked_bit(wq->private);
}
}
static bool i915_sw_fence_check_if_after(struct i915_sw_fence *fence,
const struct i915_sw_fence * const signaler)
{
unsigned long flags;
bool err;
spin_lock_irqsave(&i915_sw_fence_lock, flags);
err = __i915_sw_fence_check_if_after(fence, signaler);
__i915_sw_fence_clear_checked_bit(fence);
spin_unlock_irqrestore(&i915_sw_fence_lock, flags);
return err;
}
#else
static bool i915_sw_fence_check_if_after(struct i915_sw_fence *fence,
const struct i915_sw_fence * const signaler)
{
return false;
}
#endif
static int __i915_sw_fence_await_sw_fence(struct i915_sw_fence *fence,
struct i915_sw_fence *signaler,
wait_queue_entry_t *wq, gfp_t gfp)
{
unsigned int pending;
unsigned long flags;
debug_fence_assert(fence);
might_sleep_if(gfpflags_allow_blocking(gfp));
if (i915_sw_fence_done(signaler)) {
i915_sw_fence_set_error_once(fence, signaler->error);
return 0;
}
debug_fence_assert(signaler);
/* The dependency graph must be acyclic. */
if (unlikely(i915_sw_fence_check_if_after(fence, signaler)))
return -EINVAL;
pending = I915_SW_FENCE_FLAG_FENCE;
if (!wq) {
wq = kmalloc(sizeof(*wq), gfp);
if (!wq) {
if (!gfpflags_allow_blocking(gfp))
return -ENOMEM;
i915_sw_fence_wait(signaler);
i915_sw_fence_set_error_once(fence, signaler->error);
return 0;
}
pending |= I915_SW_FENCE_FLAG_ALLOC;
}
INIT_LIST_HEAD(&wq->entry);
wq->flags = pending;
wq->func = i915_sw_fence_wake;
wq->private = fence;
i915_sw_fence_await(fence);
spin_lock_irqsave(&signaler->wait.lock, flags);
if (likely(!i915_sw_fence_done(signaler))) {
__add_wait_queue_entry_tail(&signaler->wait, wq);
pending = 1;
} else {
i915_sw_fence_wake(wq, 0, signaler->error, NULL);
pending = 0;
}
spin_unlock_irqrestore(&signaler->wait.lock, flags);
return pending;
}
int i915_sw_fence_await_sw_fence(struct i915_sw_fence *fence,
struct i915_sw_fence *signaler,
wait_queue_entry_t *wq)
{
return __i915_sw_fence_await_sw_fence(fence, signaler, wq, 0);
}
int i915_sw_fence_await_sw_fence_gfp(struct i915_sw_fence *fence,
struct i915_sw_fence *signaler,
gfp_t gfp)
{
return __i915_sw_fence_await_sw_fence(fence, signaler, NULL, gfp);
}
struct i915_sw_dma_fence_cb_timer {
struct i915_sw_dma_fence_cb base;
struct dma_fence *dma;
struct timer_list timer;
struct irq_work work;
struct rcu_head rcu;
};
static void dma_i915_sw_fence_wake(struct dma_fence *dma,
struct dma_fence_cb *data)
{
struct i915_sw_dma_fence_cb *cb = container_of(data, typeof(*cb), base);
i915_sw_fence_set_error_once(cb->fence, dma->error);
i915_sw_fence_complete(cb->fence);
kfree(cb);
}
static void timer_i915_sw_fence_wake(struct timer_list *t)
{
struct i915_sw_dma_fence_cb_timer *cb = from_timer(cb, t, timer);
struct i915_sw_fence *fence;
fence = xchg(&cb->base.fence, NULL);
if (!fence)
return;
pr_notice("Asynchronous wait on fence %s:%s:%llx timed out (hint:%ps)\n",
cb->dma->ops->get_driver_name(cb->dma),
cb->dma->ops->get_timeline_name(cb->dma),
cb->dma->seqno,
i915_sw_fence_debug_hint(fence));
i915_sw_fence_set_error_once(fence, -ETIMEDOUT);
i915_sw_fence_complete(fence);
}
static void dma_i915_sw_fence_wake_timer(struct dma_fence *dma,
struct dma_fence_cb *data)
{
struct i915_sw_dma_fence_cb_timer *cb =
container_of(data, typeof(*cb), base.base);
struct i915_sw_fence *fence;
fence = xchg(&cb->base.fence, NULL);
if (fence) {
i915_sw_fence_set_error_once(fence, dma->error);
i915_sw_fence_complete(fence);
}
irq_work_queue(&cb->work);
}
static void irq_i915_sw_fence_work(struct irq_work *wrk)
{
struct i915_sw_dma_fence_cb_timer *cb =
container_of(wrk, typeof(*cb), work);
timer_shutdown_sync(&cb->timer);
dma_fence_put(cb->dma);
kfree_rcu(cb, rcu);
}
int i915_sw_fence_await_dma_fence(struct i915_sw_fence *fence,
struct dma_fence *dma,
unsigned long timeout,
gfp_t gfp)
{
struct i915_sw_dma_fence_cb *cb;
dma_fence_func_t func;
int ret;
debug_fence_assert(fence);
might_sleep_if(gfpflags_allow_blocking(gfp));
if (dma_fence_is_signaled(dma)) {
i915_sw_fence_set_error_once(fence, dma->error);
return 0;
}
cb = kmalloc(timeout ?
sizeof(struct i915_sw_dma_fence_cb_timer) :
sizeof(struct i915_sw_dma_fence_cb),
gfp);
if (!cb) {
if (!gfpflags_allow_blocking(gfp))
return -ENOMEM;
ret = dma_fence_wait(dma, false);
if (ret)
return ret;
i915_sw_fence_set_error_once(fence, dma->error);
return 0;
}
cb->fence = fence;
i915_sw_fence_await(fence);
func = dma_i915_sw_fence_wake;
if (timeout) {
struct i915_sw_dma_fence_cb_timer *timer =
container_of(cb, typeof(*timer), base);
timer->dma = dma_fence_get(dma);
init_irq_work(&timer->work, irq_i915_sw_fence_work);
timer_setup(&timer->timer,
timer_i915_sw_fence_wake, TIMER_IRQSAFE);
mod_timer(&timer->timer, round_jiffies_up(jiffies + timeout));
func = dma_i915_sw_fence_wake_timer;
}
ret = dma_fence_add_callback(dma, &cb->base, func);
if (ret == 0) {
ret = 1;
} else {
func(dma, &cb->base);
if (ret == -ENOENT) /* fence already signaled */
ret = 0;
}
return ret;
}
static void __dma_i915_sw_fence_wake(struct dma_fence *dma,
struct dma_fence_cb *data)
{
struct i915_sw_dma_fence_cb *cb = container_of(data, typeof(*cb), base);
i915_sw_fence_set_error_once(cb->fence, dma->error);
i915_sw_fence_complete(cb->fence);
}
int __i915_sw_fence_await_dma_fence(struct i915_sw_fence *fence,
struct dma_fence *dma,
struct i915_sw_dma_fence_cb *cb)
{
int ret;
debug_fence_assert(fence);
if (dma_fence_is_signaled(dma)) {
i915_sw_fence_set_error_once(fence, dma->error);
return 0;
}
cb->fence = fence;
i915_sw_fence_await(fence);
ret = 1;
if (dma_fence_add_callback(dma, &cb->base, __dma_i915_sw_fence_wake)) {
/* fence already signaled */
__dma_i915_sw_fence_wake(dma, &cb->base);
ret = 0;
}
return ret;
}
int i915_sw_fence_await_reservation(struct i915_sw_fence *fence,
struct dma_resv *resv,
bool write,
unsigned long timeout,
gfp_t gfp)
{
struct dma_resv_iter cursor;
struct dma_fence *f;
int ret = 0, pending;
debug_fence_assert(fence);
might_sleep_if(gfpflags_allow_blocking(gfp));
dma_resv_iter_begin(&cursor, resv, dma_resv_usage_rw(write));
dma_resv_for_each_fence_unlocked(&cursor, f) {
pending = i915_sw_fence_await_dma_fence(fence, f, timeout,
gfp);
if (pending < 0) {
ret = pending;
break;
}
ret |= pending;
}
dma_resv_iter_end(&cursor);
return ret;
}
#if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
#include "selftests/lib_sw_fence.c"
#include "selftests/i915_sw_fence.c"
#endif
| linux-master | drivers/gpu/drm/i915/i915_sw_fence.c |
/*
* Copyright © 2008 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* Authors:
* Eric Anholt <[email protected]>
* Keith Packard <[email protected]>
*
*/
#include <linux/sched/mm.h>
#include <linux/sort.h>
#include <linux/string_helpers.h>
#include <drm/drm_debugfs.h>
#include "gem/i915_gem_context.h"
#include "gt/intel_gt.h"
#include "gt/intel_gt_buffer_pool.h"
#include "gt/intel_gt_clock_utils.h"
#include "gt/intel_gt_debugfs.h"
#include "gt/intel_gt_pm.h"
#include "gt/intel_gt_pm_debugfs.h"
#include "gt/intel_gt_regs.h"
#include "gt/intel_gt_requests.h"
#include "gt/intel_rc6.h"
#include "gt/intel_reset.h"
#include "gt/intel_rps.h"
#include "gt/intel_sseu_debugfs.h"
#include "i915_debugfs.h"
#include "i915_debugfs_params.h"
#include "i915_driver.h"
#include "i915_irq.h"
#include "i915_reg.h"
#include "i915_scheduler.h"
#include "intel_mchbar_regs.h"
static inline struct drm_i915_private *node_to_i915(struct drm_info_node *node)
{
return to_i915(node->minor->dev);
}
static int i915_capabilities(struct seq_file *m, void *data)
{
struct drm_i915_private *i915 = node_to_i915(m->private);
struct drm_printer p = drm_seq_file_printer(m);
seq_printf(m, "pch: %d\n", INTEL_PCH_TYPE(i915));
intel_device_info_print(INTEL_INFO(i915), RUNTIME_INFO(i915), &p);
intel_display_device_info_print(DISPLAY_INFO(i915), DISPLAY_RUNTIME_INFO(i915), &p);
i915_print_iommu_status(i915, &p);
intel_gt_info_print(&to_gt(i915)->info, &p);
intel_driver_caps_print(&i915->caps, &p);
kernel_param_lock(THIS_MODULE);
i915_params_dump(&i915->params, &p);
kernel_param_unlock(THIS_MODULE);
return 0;
}
static char get_tiling_flag(struct drm_i915_gem_object *obj)
{
switch (i915_gem_object_get_tiling(obj)) {
default:
case I915_TILING_NONE: return ' ';
case I915_TILING_X: return 'X';
case I915_TILING_Y: return 'Y';
}
}
static char get_global_flag(struct drm_i915_gem_object *obj)
{
return READ_ONCE(obj->userfault_count) ? 'g' : ' ';
}
static char get_pin_mapped_flag(struct drm_i915_gem_object *obj)
{
return obj->mm.mapping ? 'M' : ' ';
}
static const char *
stringify_page_sizes(unsigned int page_sizes, char *buf, size_t len)
{
size_t x = 0;
switch (page_sizes) {
case 0:
return "";
case I915_GTT_PAGE_SIZE_4K:
return "4K";
case I915_GTT_PAGE_SIZE_64K:
return "64K";
case I915_GTT_PAGE_SIZE_2M:
return "2M";
default:
if (!buf)
return "M";
if (page_sizes & I915_GTT_PAGE_SIZE_2M)
x += snprintf(buf + x, len - x, "2M, ");
if (page_sizes & I915_GTT_PAGE_SIZE_64K)
x += snprintf(buf + x, len - x, "64K, ");
if (page_sizes & I915_GTT_PAGE_SIZE_4K)
x += snprintf(buf + x, len - x, "4K, ");
buf[x-2] = '\0';
return buf;
}
}
static const char *stringify_vma_type(const struct i915_vma *vma)
{
if (i915_vma_is_ggtt(vma))
return "ggtt";
if (i915_vma_is_dpt(vma))
return "dpt";
return "ppgtt";
}
static const char *i915_cache_level_str(struct drm_i915_gem_object *obj)
{
struct drm_i915_private *i915 = obj_to_i915(obj);
if (IS_METEORLAKE(i915)) {
switch (obj->pat_index) {
case 0: return " WB";
case 1: return " WT";
case 2: return " UC";
case 3: return " WB (1-Way Coh)";
case 4: return " WB (2-Way Coh)";
default: return " not defined";
}
} else if (IS_PONTEVECCHIO(i915)) {
switch (obj->pat_index) {
case 0: return " UC";
case 1: return " WC";
case 2: return " WT";
case 3: return " WB";
case 4: return " WT (CLOS1)";
case 5: return " WB (CLOS1)";
case 6: return " WT (CLOS2)";
case 7: return " WT (CLOS2)";
default: return " not defined";
}
} else if (GRAPHICS_VER(i915) >= 12) {
switch (obj->pat_index) {
case 0: return " WB";
case 1: return " WC";
case 2: return " WT";
case 3: return " UC";
default: return " not defined";
}
} else {
switch (obj->pat_index) {
case 0: return " UC";
case 1: return HAS_LLC(i915) ?
" LLC" : " snooped";
case 2: return " L3+LLC";
case 3: return " WT";
default: return " not defined";
}
}
}
void
i915_debugfs_describe_obj(struct seq_file *m, struct drm_i915_gem_object *obj)
{
struct i915_vma *vma;
int pin_count = 0;
seq_printf(m, "%pK: %c%c%c %8zdKiB %02x %02x %s%s%s",
&obj->base,
get_tiling_flag(obj),
get_global_flag(obj),
get_pin_mapped_flag(obj),
obj->base.size / 1024,
obj->read_domains,
obj->write_domain,
i915_cache_level_str(obj),
obj->mm.dirty ? " dirty" : "",
obj->mm.madv == I915_MADV_DONTNEED ? " purgeable" : "");
if (obj->base.name)
seq_printf(m, " (name: %d)", obj->base.name);
spin_lock(&obj->vma.lock);
list_for_each_entry(vma, &obj->vma.list, obj_link) {
if (!drm_mm_node_allocated(&vma->node))
continue;
spin_unlock(&obj->vma.lock);
if (i915_vma_is_pinned(vma))
pin_count++;
seq_printf(m, " (%s offset: %08llx, size: %08llx, pages: %s",
stringify_vma_type(vma),
i915_vma_offset(vma), i915_vma_size(vma),
stringify_page_sizes(vma->resource->page_sizes_gtt,
NULL, 0));
if (i915_vma_is_ggtt(vma) || i915_vma_is_dpt(vma)) {
switch (vma->gtt_view.type) {
case I915_GTT_VIEW_NORMAL:
seq_puts(m, ", normal");
break;
case I915_GTT_VIEW_PARTIAL:
seq_printf(m, ", partial [%08llx+%x]",
vma->gtt_view.partial.offset << PAGE_SHIFT,
vma->gtt_view.partial.size << PAGE_SHIFT);
break;
case I915_GTT_VIEW_ROTATED:
seq_printf(m, ", rotated [(%ux%u, src_stride=%u, dst_stride=%u, offset=%u), (%ux%u, src_stride=%u, dst_stride=%u, offset=%u)]",
vma->gtt_view.rotated.plane[0].width,
vma->gtt_view.rotated.plane[0].height,
vma->gtt_view.rotated.plane[0].src_stride,
vma->gtt_view.rotated.plane[0].dst_stride,
vma->gtt_view.rotated.plane[0].offset,
vma->gtt_view.rotated.plane[1].width,
vma->gtt_view.rotated.plane[1].height,
vma->gtt_view.rotated.plane[1].src_stride,
vma->gtt_view.rotated.plane[1].dst_stride,
vma->gtt_view.rotated.plane[1].offset);
break;
case I915_GTT_VIEW_REMAPPED:
seq_printf(m, ", remapped [(%ux%u, src_stride=%u, dst_stride=%u, offset=%u), (%ux%u, src_stride=%u, dst_stride=%u, offset=%u)]",
vma->gtt_view.remapped.plane[0].width,
vma->gtt_view.remapped.plane[0].height,
vma->gtt_view.remapped.plane[0].src_stride,
vma->gtt_view.remapped.plane[0].dst_stride,
vma->gtt_view.remapped.plane[0].offset,
vma->gtt_view.remapped.plane[1].width,
vma->gtt_view.remapped.plane[1].height,
vma->gtt_view.remapped.plane[1].src_stride,
vma->gtt_view.remapped.plane[1].dst_stride,
vma->gtt_view.remapped.plane[1].offset);
break;
default:
MISSING_CASE(vma->gtt_view.type);
break;
}
}
if (vma->fence)
seq_printf(m, " , fence: %d", vma->fence->id);
seq_puts(m, ")");
spin_lock(&obj->vma.lock);
}
spin_unlock(&obj->vma.lock);
seq_printf(m, " (pinned x %d)", pin_count);
if (i915_gem_object_is_stolen(obj))
seq_printf(m, " (stolen: %08llx)", obj->stolen->start);
if (i915_gem_object_is_framebuffer(obj))
seq_printf(m, " (fb)");
}
static int i915_gem_object_info(struct seq_file *m, void *data)
{
struct drm_i915_private *i915 = node_to_i915(m->private);
struct drm_printer p = drm_seq_file_printer(m);
struct intel_memory_region *mr;
enum intel_region_id id;
seq_printf(m, "%u shrinkable [%u free] objects, %llu bytes\n",
i915->mm.shrink_count,
atomic_read(&i915->mm.free_count),
i915->mm.shrink_memory);
for_each_memory_region(mr, i915, id)
intel_memory_region_debug(mr, &p);
return 0;
}
#if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
static ssize_t gpu_state_read(struct file *file, char __user *ubuf,
size_t count, loff_t *pos)
{
struct i915_gpu_coredump *error;
ssize_t ret;
void *buf;
error = file->private_data;
if (!error)
return 0;
/* Bounce buffer required because of kernfs __user API convenience. */
buf = kmalloc(count, GFP_KERNEL);
if (!buf)
return -ENOMEM;
ret = i915_gpu_coredump_copy_to_buffer(error, buf, *pos, count);
if (ret <= 0)
goto out;
if (!copy_to_user(ubuf, buf, ret))
*pos += ret;
else
ret = -EFAULT;
out:
kfree(buf);
return ret;
}
static int gpu_state_release(struct inode *inode, struct file *file)
{
i915_gpu_coredump_put(file->private_data);
return 0;
}
static int i915_gpu_info_open(struct inode *inode, struct file *file)
{
struct drm_i915_private *i915 = inode->i_private;
struct i915_gpu_coredump *gpu;
intel_wakeref_t wakeref;
gpu = NULL;
with_intel_runtime_pm(&i915->runtime_pm, wakeref)
gpu = i915_gpu_coredump(to_gt(i915), ALL_ENGINES, CORE_DUMP_FLAG_NONE);
if (IS_ERR(gpu))
return PTR_ERR(gpu);
file->private_data = gpu;
return 0;
}
static const struct file_operations i915_gpu_info_fops = {
.owner = THIS_MODULE,
.open = i915_gpu_info_open,
.read = gpu_state_read,
.llseek = default_llseek,
.release = gpu_state_release,
};
static ssize_t
i915_error_state_write(struct file *filp,
const char __user *ubuf,
size_t cnt,
loff_t *ppos)
{
struct i915_gpu_coredump *error = filp->private_data;
if (!error)
return 0;
drm_dbg(&error->i915->drm, "Resetting error state\n");
i915_reset_error_state(error->i915);
return cnt;
}
static int i915_error_state_open(struct inode *inode, struct file *file)
{
struct i915_gpu_coredump *error;
error = i915_first_error_state(inode->i_private);
if (IS_ERR(error))
return PTR_ERR(error);
file->private_data = error;
return 0;
}
static const struct file_operations i915_error_state_fops = {
.owner = THIS_MODULE,
.open = i915_error_state_open,
.read = gpu_state_read,
.write = i915_error_state_write,
.llseek = default_llseek,
.release = gpu_state_release,
};
#endif
static int i915_frequency_info(struct seq_file *m, void *unused)
{
struct drm_i915_private *i915 = node_to_i915(m->private);
struct intel_gt *gt = to_gt(i915);
struct drm_printer p = drm_seq_file_printer(m);
intel_gt_pm_frequency_dump(gt, &p);
return 0;
}
static const char *swizzle_string(unsigned swizzle)
{
switch (swizzle) {
case I915_BIT_6_SWIZZLE_NONE:
return "none";
case I915_BIT_6_SWIZZLE_9:
return "bit9";
case I915_BIT_6_SWIZZLE_9_10:
return "bit9/bit10";
case I915_BIT_6_SWIZZLE_9_11:
return "bit9/bit11";
case I915_BIT_6_SWIZZLE_9_10_11:
return "bit9/bit10/bit11";
case I915_BIT_6_SWIZZLE_9_17:
return "bit9/bit17";
case I915_BIT_6_SWIZZLE_9_10_17:
return "bit9/bit10/bit17";
case I915_BIT_6_SWIZZLE_UNKNOWN:
return "unknown";
}
return "bug";
}
static int i915_swizzle_info(struct seq_file *m, void *data)
{
struct drm_i915_private *dev_priv = node_to_i915(m->private);
struct intel_uncore *uncore = &dev_priv->uncore;
intel_wakeref_t wakeref;
seq_printf(m, "bit6 swizzle for X-tiling = %s\n",
swizzle_string(to_gt(dev_priv)->ggtt->bit_6_swizzle_x));
seq_printf(m, "bit6 swizzle for Y-tiling = %s\n",
swizzle_string(to_gt(dev_priv)->ggtt->bit_6_swizzle_y));
if (dev_priv->gem_quirks & GEM_QUIRK_PIN_SWIZZLED_PAGES)
seq_puts(m, "L-shaped memory detected\n");
/* On BDW+, swizzling is not used. See detect_bit_6_swizzle() */
if (GRAPHICS_VER(dev_priv) >= 8 || IS_VALLEYVIEW(dev_priv))
return 0;
wakeref = intel_runtime_pm_get(&dev_priv->runtime_pm);
if (IS_GRAPHICS_VER(dev_priv, 3, 4)) {
seq_printf(m, "DDC = 0x%08x\n",
intel_uncore_read(uncore, DCC));
seq_printf(m, "DDC2 = 0x%08x\n",
intel_uncore_read(uncore, DCC2));
seq_printf(m, "C0DRB3 = 0x%04x\n",
intel_uncore_read16(uncore, C0DRB3_BW));
seq_printf(m, "C1DRB3 = 0x%04x\n",
intel_uncore_read16(uncore, C1DRB3_BW));
} else if (GRAPHICS_VER(dev_priv) >= 6) {
seq_printf(m, "MAD_DIMM_C0 = 0x%08x\n",
intel_uncore_read(uncore, MAD_DIMM_C0));
seq_printf(m, "MAD_DIMM_C1 = 0x%08x\n",
intel_uncore_read(uncore, MAD_DIMM_C1));
seq_printf(m, "MAD_DIMM_C2 = 0x%08x\n",
intel_uncore_read(uncore, MAD_DIMM_C2));
seq_printf(m, "TILECTL = 0x%08x\n",
intel_uncore_read(uncore, TILECTL));
if (GRAPHICS_VER(dev_priv) >= 8)
seq_printf(m, "GAMTARBMODE = 0x%08x\n",
intel_uncore_read(uncore, GAMTARBMODE));
else
seq_printf(m, "ARB_MODE = 0x%08x\n",
intel_uncore_read(uncore, ARB_MODE));
seq_printf(m, "DISP_ARB_CTL = 0x%08x\n",
intel_uncore_read(uncore, DISP_ARB_CTL));
}
intel_runtime_pm_put(&dev_priv->runtime_pm, wakeref);
return 0;
}
static int i915_rps_boost_info(struct seq_file *m, void *data)
{
struct drm_i915_private *dev_priv = node_to_i915(m->private);
struct intel_rps *rps = &to_gt(dev_priv)->rps;
seq_printf(m, "RPS enabled? %s\n",
str_yes_no(intel_rps_is_enabled(rps)));
seq_printf(m, "RPS active? %s\n",
str_yes_no(intel_rps_is_active(rps)));
seq_printf(m, "GPU busy? %s\n", str_yes_no(to_gt(dev_priv)->awake));
seq_printf(m, "Boosts outstanding? %d\n",
atomic_read(&rps->num_waiters));
seq_printf(m, "Interactive? %d\n", READ_ONCE(rps->power.interactive));
seq_printf(m, "Frequency requested %d, actual %d\n",
intel_gpu_freq(rps, rps->cur_freq),
intel_rps_read_actual_frequency(rps));
seq_printf(m, " min hard:%d, soft:%d; max soft:%d, hard:%d\n",
intel_gpu_freq(rps, rps->min_freq),
intel_gpu_freq(rps, rps->min_freq_softlimit),
intel_gpu_freq(rps, rps->max_freq_softlimit),
intel_gpu_freq(rps, rps->max_freq));
seq_printf(m, " idle:%d, efficient:%d, boost:%d\n",
intel_gpu_freq(rps, rps->idle_freq),
intel_gpu_freq(rps, rps->efficient_freq),
intel_gpu_freq(rps, rps->boost_freq));
seq_printf(m, "Wait boosts: %d\n", READ_ONCE(rps->boosts));
return 0;
}
static int i915_runtime_pm_status(struct seq_file *m, void *unused)
{
struct drm_i915_private *dev_priv = node_to_i915(m->private);
struct pci_dev *pdev = to_pci_dev(dev_priv->drm.dev);
if (!HAS_RUNTIME_PM(dev_priv))
seq_puts(m, "Runtime power management not supported\n");
seq_printf(m, "Runtime power status: %s\n",
str_enabled_disabled(!dev_priv->display.power.domains.init_wakeref));
seq_printf(m, "GPU idle: %s\n", str_yes_no(!to_gt(dev_priv)->awake));
seq_printf(m, "IRQs disabled: %s\n",
str_yes_no(!intel_irqs_enabled(dev_priv)));
#ifdef CONFIG_PM
seq_printf(m, "Usage count: %d\n",
atomic_read(&dev_priv->drm.dev->power.usage_count));
#else
seq_printf(m, "Device Power Management (CONFIG_PM) disabled\n");
#endif
seq_printf(m, "PCI device power state: %s [%d]\n",
pci_power_name(pdev->current_state),
pdev->current_state);
if (IS_ENABLED(CONFIG_DRM_I915_DEBUG_RUNTIME_PM)) {
struct drm_printer p = drm_seq_file_printer(m);
print_intel_runtime_pm_wakeref(&dev_priv->runtime_pm, &p);
}
return 0;
}
static int i915_engine_info(struct seq_file *m, void *unused)
{
struct drm_i915_private *i915 = node_to_i915(m->private);
struct intel_engine_cs *engine;
intel_wakeref_t wakeref;
struct drm_printer p;
wakeref = intel_runtime_pm_get(&i915->runtime_pm);
seq_printf(m, "GT awake? %s [%d], %llums\n",
str_yes_no(to_gt(i915)->awake),
atomic_read(&to_gt(i915)->wakeref.count),
ktime_to_ms(intel_gt_get_awake_time(to_gt(i915))));
seq_printf(m, "CS timestamp frequency: %u Hz, %d ns\n",
to_gt(i915)->clock_frequency,
to_gt(i915)->clock_period_ns);
p = drm_seq_file_printer(m);
for_each_uabi_engine(engine, i915)
intel_engine_dump(engine, &p, "%s\n", engine->name);
intel_gt_show_timelines(to_gt(i915), &p, i915_request_show_with_schedule);
intel_runtime_pm_put(&i915->runtime_pm, wakeref);
return 0;
}
static int i915_wa_registers(struct seq_file *m, void *unused)
{
struct drm_i915_private *i915 = node_to_i915(m->private);
struct intel_engine_cs *engine;
for_each_uabi_engine(engine, i915) {
const struct i915_wa_list *wal = &engine->ctx_wa_list;
const struct i915_wa *wa;
unsigned int count;
count = wal->count;
if (!count)
continue;
seq_printf(m, "%s: Workarounds applied: %u\n",
engine->name, count);
for (wa = wal->list; count--; wa++)
seq_printf(m, "0x%X: 0x%08X, mask: 0x%08X\n",
i915_mmio_reg_offset(wa->reg),
wa->set, wa->clr);
seq_printf(m, "\n");
}
return 0;
}
static int i915_wedged_get(void *data, u64 *val)
{
struct drm_i915_private *i915 = data;
struct intel_gt *gt;
unsigned int i;
*val = 0;
for_each_gt(gt, i915, i) {
int ret;
ret = intel_gt_debugfs_reset_show(gt, val);
if (ret)
return ret;
/* at least one tile should be wedged */
if (*val)
break;
}
return 0;
}
static int i915_wedged_set(void *data, u64 val)
{
struct drm_i915_private *i915 = data;
struct intel_gt *gt;
unsigned int i;
for_each_gt(gt, i915, i)
intel_gt_debugfs_reset_store(gt, val);
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(i915_wedged_fops,
i915_wedged_get, i915_wedged_set,
"%llu\n");
static int
i915_perf_noa_delay_set(void *data, u64 val)
{
struct drm_i915_private *i915 = data;
/*
* This would lead to infinite waits as we're doing timestamp
* difference on the CS with only 32bits.
*/
if (intel_gt_ns_to_clock_interval(to_gt(i915), val) > U32_MAX)
return -EINVAL;
atomic64_set(&i915->perf.noa_programming_delay, val);
return 0;
}
static int
i915_perf_noa_delay_get(void *data, u64 *val)
{
struct drm_i915_private *i915 = data;
*val = atomic64_read(&i915->perf.noa_programming_delay);
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(i915_perf_noa_delay_fops,
i915_perf_noa_delay_get,
i915_perf_noa_delay_set,
"%llu\n");
#define DROP_UNBOUND BIT(0)
#define DROP_BOUND BIT(1)
#define DROP_RETIRE BIT(2)
#define DROP_ACTIVE BIT(3)
#define DROP_FREED BIT(4)
#define DROP_SHRINK_ALL BIT(5)
#define DROP_IDLE BIT(6)
#define DROP_RESET_ACTIVE BIT(7)
#define DROP_RESET_SEQNO BIT(8)
#define DROP_RCU BIT(9)
#define DROP_ALL (DROP_UNBOUND | \
DROP_BOUND | \
DROP_RETIRE | \
DROP_ACTIVE | \
DROP_FREED | \
DROP_SHRINK_ALL |\
DROP_IDLE | \
DROP_RESET_ACTIVE | \
DROP_RESET_SEQNO | \
DROP_RCU)
static int
i915_drop_caches_get(void *data, u64 *val)
{
*val = DROP_ALL;
return 0;
}
static int
gt_drop_caches(struct intel_gt *gt, u64 val)
{
int ret;
if (val & DROP_RESET_ACTIVE &&
wait_for(intel_engines_are_idle(gt), 200))
intel_gt_set_wedged(gt);
if (val & DROP_RETIRE)
intel_gt_retire_requests(gt);
if (val & (DROP_IDLE | DROP_ACTIVE)) {
ret = intel_gt_wait_for_idle(gt, MAX_SCHEDULE_TIMEOUT);
if (ret)
return ret;
}
if (val & DROP_IDLE) {
ret = intel_gt_pm_wait_for_idle(gt);
if (ret)
return ret;
}
if (val & DROP_RESET_ACTIVE && intel_gt_terminally_wedged(gt))
intel_gt_handle_error(gt, ALL_ENGINES, 0, NULL);
if (val & DROP_FREED)
intel_gt_flush_buffer_pool(gt);
return 0;
}
static int
i915_drop_caches_set(void *data, u64 val)
{
struct drm_i915_private *i915 = data;
unsigned int flags;
int ret;
drm_dbg(&i915->drm, "Dropping caches: 0x%08llx [0x%08llx]\n",
val, val & DROP_ALL);
ret = gt_drop_caches(to_gt(i915), val);
if (ret)
return ret;
fs_reclaim_acquire(GFP_KERNEL);
flags = memalloc_noreclaim_save();
if (val & DROP_BOUND)
i915_gem_shrink(NULL, i915, LONG_MAX, NULL, I915_SHRINK_BOUND);
if (val & DROP_UNBOUND)
i915_gem_shrink(NULL, i915, LONG_MAX, NULL, I915_SHRINK_UNBOUND);
if (val & DROP_SHRINK_ALL)
i915_gem_shrink_all(i915);
memalloc_noreclaim_restore(flags);
fs_reclaim_release(GFP_KERNEL);
if (val & DROP_RCU)
rcu_barrier();
if (val & DROP_FREED)
i915_gem_drain_freed_objects(i915);
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(i915_drop_caches_fops,
i915_drop_caches_get, i915_drop_caches_set,
"0x%08llx\n");
static int i915_sseu_status(struct seq_file *m, void *unused)
{
struct drm_i915_private *i915 = node_to_i915(m->private);
struct intel_gt *gt = to_gt(i915);
return intel_sseu_status(m, gt);
}
static int i915_forcewake_open(struct inode *inode, struct file *file)
{
struct drm_i915_private *i915 = inode->i_private;
struct intel_gt *gt;
unsigned int i;
for_each_gt(gt, i915, i)
intel_gt_pm_debugfs_forcewake_user_open(gt);
return 0;
}
static int i915_forcewake_release(struct inode *inode, struct file *file)
{
struct drm_i915_private *i915 = inode->i_private;
struct intel_gt *gt;
unsigned int i;
for_each_gt(gt, i915, i)
intel_gt_pm_debugfs_forcewake_user_release(gt);
return 0;
}
static const struct file_operations i915_forcewake_fops = {
.owner = THIS_MODULE,
.open = i915_forcewake_open,
.release = i915_forcewake_release,
};
static const struct drm_info_list i915_debugfs_list[] = {
{"i915_capabilities", i915_capabilities, 0},
{"i915_gem_objects", i915_gem_object_info, 0},
{"i915_frequency_info", i915_frequency_info, 0},
{"i915_swizzle_info", i915_swizzle_info, 0},
{"i915_runtime_pm_status", i915_runtime_pm_status, 0},
{"i915_engine_info", i915_engine_info, 0},
{"i915_wa_registers", i915_wa_registers, 0},
{"i915_sseu_status", i915_sseu_status, 0},
{"i915_rps_boost_info", i915_rps_boost_info, 0},
};
static const struct i915_debugfs_files {
const char *name;
const struct file_operations *fops;
} i915_debugfs_files[] = {
{"i915_perf_noa_delay", &i915_perf_noa_delay_fops},
{"i915_wedged", &i915_wedged_fops},
{"i915_gem_drop_caches", &i915_drop_caches_fops},
#if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
{"i915_error_state", &i915_error_state_fops},
{"i915_gpu_info", &i915_gpu_info_fops},
#endif
};
void i915_debugfs_register(struct drm_i915_private *dev_priv)
{
struct drm_minor *minor = dev_priv->drm.primary;
int i;
i915_debugfs_params(dev_priv);
debugfs_create_file("i915_forcewake_user", S_IRUSR, minor->debugfs_root,
to_i915(minor->dev), &i915_forcewake_fops);
for (i = 0; i < ARRAY_SIZE(i915_debugfs_files); i++) {
debugfs_create_file(i915_debugfs_files[i].name,
S_IRUGO | S_IWUSR,
minor->debugfs_root,
to_i915(minor->dev),
i915_debugfs_files[i].fops);
}
drm_debugfs_create_files(i915_debugfs_list,
ARRAY_SIZE(i915_debugfs_list),
minor->debugfs_root, minor);
}
| linux-master | drivers/gpu/drm/i915/i915_debugfs.c |
/*
*
* Copyright 2008 (c) Intel Corporation
* Jesse Barnes <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
* IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "display/intel_de.h"
#include "display/intel_gmbus.h"
#include "display/intel_vga.h"
#include "i915_drv.h"
#include "i915_reg.h"
#include "i915_suspend.h"
#include "intel_pci_config.h"
static void intel_save_swf(struct drm_i915_private *dev_priv)
{
int i;
/* Scratch space */
if (GRAPHICS_VER(dev_priv) == 2 && IS_MOBILE(dev_priv)) {
for (i = 0; i < 7; i++) {
dev_priv->regfile.saveSWF0[i] = intel_de_read(dev_priv, SWF0(i));
dev_priv->regfile.saveSWF1[i] = intel_de_read(dev_priv, SWF1(i));
}
for (i = 0; i < 3; i++)
dev_priv->regfile.saveSWF3[i] = intel_de_read(dev_priv, SWF3(i));
} else if (GRAPHICS_VER(dev_priv) == 2) {
for (i = 0; i < 7; i++)
dev_priv->regfile.saveSWF1[i] = intel_de_read(dev_priv, SWF1(i));
} else if (HAS_GMCH(dev_priv)) {
for (i = 0; i < 16; i++) {
dev_priv->regfile.saveSWF0[i] = intel_de_read(dev_priv, SWF0(i));
dev_priv->regfile.saveSWF1[i] = intel_de_read(dev_priv, SWF1(i));
}
for (i = 0; i < 3; i++)
dev_priv->regfile.saveSWF3[i] = intel_de_read(dev_priv, SWF3(i));
}
}
static void intel_restore_swf(struct drm_i915_private *dev_priv)
{
int i;
/* Scratch space */
if (GRAPHICS_VER(dev_priv) == 2 && IS_MOBILE(dev_priv)) {
for (i = 0; i < 7; i++) {
intel_de_write(dev_priv, SWF0(i), dev_priv->regfile.saveSWF0[i]);
intel_de_write(dev_priv, SWF1(i), dev_priv->regfile.saveSWF1[i]);
}
for (i = 0; i < 3; i++)
intel_de_write(dev_priv, SWF3(i), dev_priv->regfile.saveSWF3[i]);
} else if (GRAPHICS_VER(dev_priv) == 2) {
for (i = 0; i < 7; i++)
intel_de_write(dev_priv, SWF1(i), dev_priv->regfile.saveSWF1[i]);
} else if (HAS_GMCH(dev_priv)) {
for (i = 0; i < 16; i++) {
intel_de_write(dev_priv, SWF0(i), dev_priv->regfile.saveSWF0[i]);
intel_de_write(dev_priv, SWF1(i), dev_priv->regfile.saveSWF1[i]);
}
for (i = 0; i < 3; i++)
intel_de_write(dev_priv, SWF3(i), dev_priv->regfile.saveSWF3[i]);
}
}
void i915_save_display(struct drm_i915_private *dev_priv)
{
struct pci_dev *pdev = to_pci_dev(dev_priv->drm.dev);
if (!HAS_DISPLAY(dev_priv))
return;
/* Display arbitration control */
if (GRAPHICS_VER(dev_priv) <= 4)
dev_priv->regfile.saveDSPARB = intel_de_read(dev_priv, DSPARB);
if (GRAPHICS_VER(dev_priv) == 4)
pci_read_config_word(pdev, GCDGMBUS,
&dev_priv->regfile.saveGCDGMBUS);
intel_save_swf(dev_priv);
}
void i915_restore_display(struct drm_i915_private *dev_priv)
{
struct pci_dev *pdev = to_pci_dev(dev_priv->drm.dev);
if (!HAS_DISPLAY(dev_priv))
return;
intel_restore_swf(dev_priv);
if (GRAPHICS_VER(dev_priv) == 4)
pci_write_config_word(pdev, GCDGMBUS,
dev_priv->regfile.saveGCDGMBUS);
/* Display arbitration */
if (GRAPHICS_VER(dev_priv) <= 4)
intel_de_write(dev_priv, DSPARB, dev_priv->regfile.saveDSPARB);
intel_vga_redisable(dev_priv);
intel_gmbus_reset(dev_priv);
}
| linux-master | drivers/gpu/drm/i915/i915_suspend.c |
/*
* SPDX-License-Identifier: MIT
*
* Copyright © 2019 Intel Corporation
*/
#include <linux/debugobjects.h>
#include "gt/intel_context.h"
#include "gt/intel_engine_heartbeat.h"
#include "gt/intel_engine_pm.h"
#include "gt/intel_ring.h"
#include "i915_drv.h"
#include "i915_active.h"
/*
* Active refs memory management
*
* To be more economical with memory, we reap all the i915_active trees as
* they idle (when we know the active requests are inactive) and allocate the
* nodes from a local slab cache to hopefully reduce the fragmentation.
*/
static struct kmem_cache *slab_cache;
struct active_node {
struct rb_node node;
struct i915_active_fence base;
struct i915_active *ref;
u64 timeline;
};
#define fetch_node(x) rb_entry(READ_ONCE(x), typeof(struct active_node), node)
static inline struct active_node *
node_from_active(struct i915_active_fence *active)
{
return container_of(active, struct active_node, base);
}
#define take_preallocated_barriers(x) llist_del_all(&(x)->preallocated_barriers)
static inline bool is_barrier(const struct i915_active_fence *active)
{
return IS_ERR(rcu_access_pointer(active->fence));
}
static inline struct llist_node *barrier_to_ll(struct active_node *node)
{
GEM_BUG_ON(!is_barrier(&node->base));
return (struct llist_node *)&node->base.cb.node;
}
static inline struct intel_engine_cs *
__barrier_to_engine(struct active_node *node)
{
return (struct intel_engine_cs *)READ_ONCE(node->base.cb.node.prev);
}
static inline struct intel_engine_cs *
barrier_to_engine(struct active_node *node)
{
GEM_BUG_ON(!is_barrier(&node->base));
return __barrier_to_engine(node);
}
static inline struct active_node *barrier_from_ll(struct llist_node *x)
{
return container_of((struct list_head *)x,
struct active_node, base.cb.node);
}
#if IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM) && IS_ENABLED(CONFIG_DEBUG_OBJECTS)
static void *active_debug_hint(void *addr)
{
struct i915_active *ref = addr;
return (void *)ref->active ?: (void *)ref->retire ?: (void *)ref;
}
static const struct debug_obj_descr active_debug_desc = {
.name = "i915_active",
.debug_hint = active_debug_hint,
};
static void debug_active_init(struct i915_active *ref)
{
debug_object_init(ref, &active_debug_desc);
}
static void debug_active_activate(struct i915_active *ref)
{
lockdep_assert_held(&ref->tree_lock);
debug_object_activate(ref, &active_debug_desc);
}
static void debug_active_deactivate(struct i915_active *ref)
{
lockdep_assert_held(&ref->tree_lock);
if (!atomic_read(&ref->count)) /* after the last dec */
debug_object_deactivate(ref, &active_debug_desc);
}
static void debug_active_fini(struct i915_active *ref)
{
debug_object_free(ref, &active_debug_desc);
}
static void debug_active_assert(struct i915_active *ref)
{
debug_object_assert_init(ref, &active_debug_desc);
}
#else
static inline void debug_active_init(struct i915_active *ref) { }
static inline void debug_active_activate(struct i915_active *ref) { }
static inline void debug_active_deactivate(struct i915_active *ref) { }
static inline void debug_active_fini(struct i915_active *ref) { }
static inline void debug_active_assert(struct i915_active *ref) { }
#endif
static void
__active_retire(struct i915_active *ref)
{
struct rb_root root = RB_ROOT;
struct active_node *it, *n;
unsigned long flags;
GEM_BUG_ON(i915_active_is_idle(ref));
/* return the unused nodes to our slabcache -- flushing the allocator */
if (!atomic_dec_and_lock_irqsave(&ref->count, &ref->tree_lock, flags))
return;
GEM_BUG_ON(rcu_access_pointer(ref->excl.fence));
debug_active_deactivate(ref);
/* Even if we have not used the cache, we may still have a barrier */
if (!ref->cache)
ref->cache = fetch_node(ref->tree.rb_node);
/* Keep the MRU cached node for reuse */
if (ref->cache) {
/* Discard all other nodes in the tree */
rb_erase(&ref->cache->node, &ref->tree);
root = ref->tree;
/* Rebuild the tree with only the cached node */
rb_link_node(&ref->cache->node, NULL, &ref->tree.rb_node);
rb_insert_color(&ref->cache->node, &ref->tree);
GEM_BUG_ON(ref->tree.rb_node != &ref->cache->node);
/* Make the cached node available for reuse with any timeline */
ref->cache->timeline = 0; /* needs cmpxchg(u64) */
}
spin_unlock_irqrestore(&ref->tree_lock, flags);
/* After the final retire, the entire struct may be freed */
if (ref->retire)
ref->retire(ref);
/* ... except if you wait on it, you must manage your own references! */
wake_up_var(ref);
/* Finally free the discarded timeline tree */
rbtree_postorder_for_each_entry_safe(it, n, &root, node) {
GEM_BUG_ON(i915_active_fence_isset(&it->base));
kmem_cache_free(slab_cache, it);
}
}
static void
active_work(struct work_struct *wrk)
{
struct i915_active *ref = container_of(wrk, typeof(*ref), work);
GEM_BUG_ON(!atomic_read(&ref->count));
if (atomic_add_unless(&ref->count, -1, 1))
return;
__active_retire(ref);
}
static void
active_retire(struct i915_active *ref)
{
GEM_BUG_ON(!atomic_read(&ref->count));
if (atomic_add_unless(&ref->count, -1, 1))
return;
if (ref->flags & I915_ACTIVE_RETIRE_SLEEPS) {
queue_work(system_unbound_wq, &ref->work);
return;
}
__active_retire(ref);
}
static inline struct dma_fence **
__active_fence_slot(struct i915_active_fence *active)
{
return (struct dma_fence ** __force)&active->fence;
}
static inline bool
active_fence_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
{
struct i915_active_fence *active =
container_of(cb, typeof(*active), cb);
return cmpxchg(__active_fence_slot(active), fence, NULL) == fence;
}
static void
node_retire(struct dma_fence *fence, struct dma_fence_cb *cb)
{
if (active_fence_cb(fence, cb))
active_retire(container_of(cb, struct active_node, base.cb)->ref);
}
static void
excl_retire(struct dma_fence *fence, struct dma_fence_cb *cb)
{
if (active_fence_cb(fence, cb))
active_retire(container_of(cb, struct i915_active, excl.cb));
}
static struct active_node *__active_lookup(struct i915_active *ref, u64 idx)
{
struct active_node *it;
GEM_BUG_ON(idx == 0); /* 0 is the unordered timeline, rsvd for cache */
/*
* We track the most recently used timeline to skip a rbtree search
* for the common case, under typical loads we never need the rbtree
* at all. We can reuse the last slot if it is empty, that is
* after the previous activity has been retired, or if it matches the
* current timeline.
*/
it = READ_ONCE(ref->cache);
if (it) {
u64 cached = READ_ONCE(it->timeline);
/* Once claimed, this slot will only belong to this idx */
if (cached == idx)
return it;
/*
* An unclaimed cache [.timeline=0] can only be claimed once.
*
* If the value is already non-zero, some other thread has
* claimed the cache and we know that is does not match our
* idx. If, and only if, the timeline is currently zero is it
* worth competing to claim it atomically for ourselves (for
* only the winner of that race will cmpxchg return the old
* value of 0).
*/
if (!cached && !cmpxchg64(&it->timeline, 0, idx))
return it;
}
BUILD_BUG_ON(offsetof(typeof(*it), node));
/* While active, the tree can only be built; not destroyed */
GEM_BUG_ON(i915_active_is_idle(ref));
it = fetch_node(ref->tree.rb_node);
while (it) {
if (it->timeline < idx) {
it = fetch_node(it->node.rb_right);
} else if (it->timeline > idx) {
it = fetch_node(it->node.rb_left);
} else {
WRITE_ONCE(ref->cache, it);
break;
}
}
/* NB: If the tree rotated beneath us, we may miss our target. */
return it;
}
static struct i915_active_fence *
active_instance(struct i915_active *ref, u64 idx)
{
struct active_node *node;
struct rb_node **p, *parent;
node = __active_lookup(ref, idx);
if (likely(node))
return &node->base;
spin_lock_irq(&ref->tree_lock);
GEM_BUG_ON(i915_active_is_idle(ref));
parent = NULL;
p = &ref->tree.rb_node;
while (*p) {
parent = *p;
node = rb_entry(parent, struct active_node, node);
if (node->timeline == idx)
goto out;
if (node->timeline < idx)
p = &parent->rb_right;
else
p = &parent->rb_left;
}
/*
* XXX: We should preallocate this before i915_active_ref() is ever
* called, but we cannot call into fs_reclaim() anyway, so use GFP_ATOMIC.
*/
node = kmem_cache_alloc(slab_cache, GFP_ATOMIC);
if (!node)
goto out;
__i915_active_fence_init(&node->base, NULL, node_retire);
node->ref = ref;
node->timeline = idx;
rb_link_node(&node->node, parent, p);
rb_insert_color(&node->node, &ref->tree);
out:
WRITE_ONCE(ref->cache, node);
spin_unlock_irq(&ref->tree_lock);
return &node->base;
}
void __i915_active_init(struct i915_active *ref,
int (*active)(struct i915_active *ref),
void (*retire)(struct i915_active *ref),
unsigned long flags,
struct lock_class_key *mkey,
struct lock_class_key *wkey)
{
debug_active_init(ref);
ref->flags = flags;
ref->active = active;
ref->retire = retire;
spin_lock_init(&ref->tree_lock);
ref->tree = RB_ROOT;
ref->cache = NULL;
init_llist_head(&ref->preallocated_barriers);
atomic_set(&ref->count, 0);
__mutex_init(&ref->mutex, "i915_active", mkey);
__i915_active_fence_init(&ref->excl, NULL, excl_retire);
INIT_WORK(&ref->work, active_work);
#if IS_ENABLED(CONFIG_LOCKDEP)
lockdep_init_map(&ref->work.lockdep_map, "i915_active.work", wkey, 0);
#endif
}
static bool ____active_del_barrier(struct i915_active *ref,
struct active_node *node,
struct intel_engine_cs *engine)
{
struct llist_node *head = NULL, *tail = NULL;
struct llist_node *pos, *next;
GEM_BUG_ON(node->timeline != engine->kernel_context->timeline->fence_context);
/*
* Rebuild the llist excluding our node. We may perform this
* outside of the kernel_context timeline mutex and so someone
* else may be manipulating the engine->barrier_tasks, in
* which case either we or they will be upset :)
*
* A second __active_del_barrier() will report failure to claim
* the active_node and the caller will just shrug and know not to
* claim ownership of its node.
*
* A concurrent i915_request_add_active_barriers() will miss adding
* any of the tasks, but we will try again on the next -- and since
* we are actively using the barrier, we know that there will be
* at least another opportunity when we idle.
*/
llist_for_each_safe(pos, next, llist_del_all(&engine->barrier_tasks)) {
if (node == barrier_from_ll(pos)) {
node = NULL;
continue;
}
pos->next = head;
head = pos;
if (!tail)
tail = pos;
}
if (head)
llist_add_batch(head, tail, &engine->barrier_tasks);
return !node;
}
static bool
__active_del_barrier(struct i915_active *ref, struct active_node *node)
{
return ____active_del_barrier(ref, node, barrier_to_engine(node));
}
static bool
replace_barrier(struct i915_active *ref, struct i915_active_fence *active)
{
if (!is_barrier(active)) /* proto-node used by our idle barrier? */
return false;
/*
* This request is on the kernel_context timeline, and so
* we can use it to substitute for the pending idle-barrer
* request that we want to emit on the kernel_context.
*/
return __active_del_barrier(ref, node_from_active(active));
}
int i915_active_add_request(struct i915_active *ref, struct i915_request *rq)
{
u64 idx = i915_request_timeline(rq)->fence_context;
struct dma_fence *fence = &rq->fence;
struct i915_active_fence *active;
int err;
/* Prevent reaping in case we malloc/wait while building the tree */
err = i915_active_acquire(ref);
if (err)
return err;
do {
active = active_instance(ref, idx);
if (!active) {
err = -ENOMEM;
goto out;
}
if (replace_barrier(ref, active)) {
RCU_INIT_POINTER(active->fence, NULL);
atomic_dec(&ref->count);
}
} while (unlikely(is_barrier(active)));
fence = __i915_active_fence_set(active, fence);
if (!fence)
__i915_active_acquire(ref);
else
dma_fence_put(fence);
out:
i915_active_release(ref);
return err;
}
static struct dma_fence *
__i915_active_set_fence(struct i915_active *ref,
struct i915_active_fence *active,
struct dma_fence *fence)
{
struct dma_fence *prev;
if (replace_barrier(ref, active)) {
RCU_INIT_POINTER(active->fence, fence);
return NULL;
}
prev = __i915_active_fence_set(active, fence);
if (!prev)
__i915_active_acquire(ref);
return prev;
}
struct dma_fence *
i915_active_set_exclusive(struct i915_active *ref, struct dma_fence *f)
{
/* We expect the caller to manage the exclusive timeline ordering */
return __i915_active_set_fence(ref, &ref->excl, f);
}
bool i915_active_acquire_if_busy(struct i915_active *ref)
{
debug_active_assert(ref);
return atomic_add_unless(&ref->count, 1, 0);
}
static void __i915_active_activate(struct i915_active *ref)
{
spin_lock_irq(&ref->tree_lock); /* __active_retire() */
if (!atomic_fetch_inc(&ref->count))
debug_active_activate(ref);
spin_unlock_irq(&ref->tree_lock);
}
int i915_active_acquire(struct i915_active *ref)
{
int err;
if (i915_active_acquire_if_busy(ref))
return 0;
if (!ref->active) {
__i915_active_activate(ref);
return 0;
}
err = mutex_lock_interruptible(&ref->mutex);
if (err)
return err;
if (likely(!i915_active_acquire_if_busy(ref))) {
err = ref->active(ref);
if (!err)
__i915_active_activate(ref);
}
mutex_unlock(&ref->mutex);
return err;
}
int i915_active_acquire_for_context(struct i915_active *ref, u64 idx)
{
struct i915_active_fence *active;
int err;
err = i915_active_acquire(ref);
if (err)
return err;
active = active_instance(ref, idx);
if (!active) {
i915_active_release(ref);
return -ENOMEM;
}
return 0; /* return with active ref */
}
void i915_active_release(struct i915_active *ref)
{
debug_active_assert(ref);
active_retire(ref);
}
static void enable_signaling(struct i915_active_fence *active)
{
struct dma_fence *fence;
if (unlikely(is_barrier(active)))
return;
fence = i915_active_fence_get(active);
if (!fence)
return;
dma_fence_enable_sw_signaling(fence);
dma_fence_put(fence);
}
static int flush_barrier(struct active_node *it)
{
struct intel_engine_cs *engine;
if (likely(!is_barrier(&it->base)))
return 0;
engine = __barrier_to_engine(it);
smp_rmb(); /* serialise with add_active_barriers */
if (!is_barrier(&it->base))
return 0;
return intel_engine_flush_barriers(engine);
}
static int flush_lazy_signals(struct i915_active *ref)
{
struct active_node *it, *n;
int err = 0;
enable_signaling(&ref->excl);
rbtree_postorder_for_each_entry_safe(it, n, &ref->tree, node) {
err = flush_barrier(it); /* unconnected idle barrier? */
if (err)
break;
enable_signaling(&it->base);
}
return err;
}
int __i915_active_wait(struct i915_active *ref, int state)
{
might_sleep();
/* Any fence added after the wait begins will not be auto-signaled */
if (i915_active_acquire_if_busy(ref)) {
int err;
err = flush_lazy_signals(ref);
i915_active_release(ref);
if (err)
return err;
if (___wait_var_event(ref, i915_active_is_idle(ref),
state, 0, 0, schedule()))
return -EINTR;
}
/*
* After the wait is complete, the caller may free the active.
* We have to flush any concurrent retirement before returning.
*/
flush_work(&ref->work);
return 0;
}
static int __await_active(struct i915_active_fence *active,
int (*fn)(void *arg, struct dma_fence *fence),
void *arg)
{
struct dma_fence *fence;
if (is_barrier(active)) /* XXX flush the barrier? */
return 0;
fence = i915_active_fence_get(active);
if (fence) {
int err;
err = fn(arg, fence);
dma_fence_put(fence);
if (err < 0)
return err;
}
return 0;
}
struct wait_barrier {
struct wait_queue_entry base;
struct i915_active *ref;
};
static int
barrier_wake(wait_queue_entry_t *wq, unsigned int mode, int flags, void *key)
{
struct wait_barrier *wb = container_of(wq, typeof(*wb), base);
if (i915_active_is_idle(wb->ref)) {
list_del(&wq->entry);
i915_sw_fence_complete(wq->private);
kfree(wq);
}
return 0;
}
static int __await_barrier(struct i915_active *ref, struct i915_sw_fence *fence)
{
struct wait_barrier *wb;
wb = kmalloc(sizeof(*wb), GFP_KERNEL);
if (unlikely(!wb))
return -ENOMEM;
GEM_BUG_ON(i915_active_is_idle(ref));
if (!i915_sw_fence_await(fence)) {
kfree(wb);
return -EINVAL;
}
wb->base.flags = 0;
wb->base.func = barrier_wake;
wb->base.private = fence;
wb->ref = ref;
add_wait_queue(__var_waitqueue(ref), &wb->base);
return 0;
}
static int await_active(struct i915_active *ref,
unsigned int flags,
int (*fn)(void *arg, struct dma_fence *fence),
void *arg, struct i915_sw_fence *barrier)
{
int err = 0;
if (!i915_active_acquire_if_busy(ref))
return 0;
if (flags & I915_ACTIVE_AWAIT_EXCL &&
rcu_access_pointer(ref->excl.fence)) {
err = __await_active(&ref->excl, fn, arg);
if (err)
goto out;
}
if (flags & I915_ACTIVE_AWAIT_ACTIVE) {
struct active_node *it, *n;
rbtree_postorder_for_each_entry_safe(it, n, &ref->tree, node) {
err = __await_active(&it->base, fn, arg);
if (err)
goto out;
}
}
if (flags & I915_ACTIVE_AWAIT_BARRIER) {
err = flush_lazy_signals(ref);
if (err)
goto out;
err = __await_barrier(ref, barrier);
if (err)
goto out;
}
out:
i915_active_release(ref);
return err;
}
static int rq_await_fence(void *arg, struct dma_fence *fence)
{
return i915_request_await_dma_fence(arg, fence);
}
int i915_request_await_active(struct i915_request *rq,
struct i915_active *ref,
unsigned int flags)
{
return await_active(ref, flags, rq_await_fence, rq, &rq->submit);
}
static int sw_await_fence(void *arg, struct dma_fence *fence)
{
return i915_sw_fence_await_dma_fence(arg, fence, 0,
GFP_NOWAIT | __GFP_NOWARN);
}
int i915_sw_fence_await_active(struct i915_sw_fence *fence,
struct i915_active *ref,
unsigned int flags)
{
return await_active(ref, flags, sw_await_fence, fence, fence);
}
void i915_active_fini(struct i915_active *ref)
{
debug_active_fini(ref);
GEM_BUG_ON(atomic_read(&ref->count));
GEM_BUG_ON(work_pending(&ref->work));
mutex_destroy(&ref->mutex);
if (ref->cache)
kmem_cache_free(slab_cache, ref->cache);
}
static inline bool is_idle_barrier(struct active_node *node, u64 idx)
{
return node->timeline == idx && !i915_active_fence_isset(&node->base);
}
static struct active_node *reuse_idle_barrier(struct i915_active *ref, u64 idx)
{
struct rb_node *prev, *p;
if (RB_EMPTY_ROOT(&ref->tree))
return NULL;
GEM_BUG_ON(i915_active_is_idle(ref));
/*
* Try to reuse any existing barrier nodes already allocated for this
* i915_active, due to overlapping active phases there is likely a
* node kept alive (as we reuse before parking). We prefer to reuse
* completely idle barriers (less hassle in manipulating the llists),
* but otherwise any will do.
*/
if (ref->cache && is_idle_barrier(ref->cache, idx)) {
p = &ref->cache->node;
goto match;
}
prev = NULL;
p = ref->tree.rb_node;
while (p) {
struct active_node *node =
rb_entry(p, struct active_node, node);
if (is_idle_barrier(node, idx))
goto match;
prev = p;
if (node->timeline < idx)
p = READ_ONCE(p->rb_right);
else
p = READ_ONCE(p->rb_left);
}
/*
* No quick match, but we did find the leftmost rb_node for the
* kernel_context. Walk the rb_tree in-order to see if there were
* any idle-barriers on this timeline that we missed, or just use
* the first pending barrier.
*/
for (p = prev; p; p = rb_next(p)) {
struct active_node *node =
rb_entry(p, struct active_node, node);
struct intel_engine_cs *engine;
if (node->timeline > idx)
break;
if (node->timeline < idx)
continue;
if (is_idle_barrier(node, idx))
goto match;
/*
* The list of pending barriers is protected by the
* kernel_context timeline, which notably we do not hold
* here. i915_request_add_active_barriers() may consume
* the barrier before we claim it, so we have to check
* for success.
*/
engine = __barrier_to_engine(node);
smp_rmb(); /* serialise with add_active_barriers */
if (is_barrier(&node->base) &&
____active_del_barrier(ref, node, engine))
goto match;
}
return NULL;
match:
spin_lock_irq(&ref->tree_lock);
rb_erase(p, &ref->tree); /* Hide from waits and sibling allocations */
if (p == &ref->cache->node)
WRITE_ONCE(ref->cache, NULL);
spin_unlock_irq(&ref->tree_lock);
return rb_entry(p, struct active_node, node);
}
int i915_active_acquire_preallocate_barrier(struct i915_active *ref,
struct intel_engine_cs *engine)
{
intel_engine_mask_t tmp, mask = engine->mask;
struct llist_node *first = NULL, *last = NULL;
struct intel_gt *gt = engine->gt;
GEM_BUG_ON(i915_active_is_idle(ref));
/* Wait until the previous preallocation is completed */
while (!llist_empty(&ref->preallocated_barriers))
cond_resched();
/*
* Preallocate a node for each physical engine supporting the target
* engine (remember virtual engines have more than one sibling).
* We can then use the preallocated nodes in
* i915_active_acquire_barrier()
*/
GEM_BUG_ON(!mask);
for_each_engine_masked(engine, gt, mask, tmp) {
u64 idx = engine->kernel_context->timeline->fence_context;
struct llist_node *prev = first;
struct active_node *node;
rcu_read_lock();
node = reuse_idle_barrier(ref, idx);
rcu_read_unlock();
if (!node) {
node = kmem_cache_alloc(slab_cache, GFP_KERNEL);
if (!node)
goto unwind;
RCU_INIT_POINTER(node->base.fence, NULL);
node->base.cb.func = node_retire;
node->timeline = idx;
node->ref = ref;
}
if (!i915_active_fence_isset(&node->base)) {
/*
* Mark this as being *our* unconnected proto-node.
*
* Since this node is not in any list, and we have
* decoupled it from the rbtree, we can reuse the
* request to indicate this is an idle-barrier node
* and then we can use the rb_node and list pointers
* for our tracking of the pending barrier.
*/
RCU_INIT_POINTER(node->base.fence, ERR_PTR(-EAGAIN));
node->base.cb.node.prev = (void *)engine;
__i915_active_acquire(ref);
}
GEM_BUG_ON(rcu_access_pointer(node->base.fence) != ERR_PTR(-EAGAIN));
GEM_BUG_ON(barrier_to_engine(node) != engine);
first = barrier_to_ll(node);
first->next = prev;
if (!last)
last = first;
intel_engine_pm_get(engine);
}
GEM_BUG_ON(!llist_empty(&ref->preallocated_barriers));
llist_add_batch(first, last, &ref->preallocated_barriers);
return 0;
unwind:
while (first) {
struct active_node *node = barrier_from_ll(first);
first = first->next;
atomic_dec(&ref->count);
intel_engine_pm_put(barrier_to_engine(node));
kmem_cache_free(slab_cache, node);
}
return -ENOMEM;
}
void i915_active_acquire_barrier(struct i915_active *ref)
{
struct llist_node *pos, *next;
unsigned long flags;
GEM_BUG_ON(i915_active_is_idle(ref));
/*
* Transfer the list of preallocated barriers into the
* i915_active rbtree, but only as proto-nodes. They will be
* populated by i915_request_add_active_barriers() to point to the
* request that will eventually release them.
*/
llist_for_each_safe(pos, next, take_preallocated_barriers(ref)) {
struct active_node *node = barrier_from_ll(pos);
struct intel_engine_cs *engine = barrier_to_engine(node);
struct rb_node **p, *parent;
spin_lock_irqsave_nested(&ref->tree_lock, flags,
SINGLE_DEPTH_NESTING);
parent = NULL;
p = &ref->tree.rb_node;
while (*p) {
struct active_node *it;
parent = *p;
it = rb_entry(parent, struct active_node, node);
if (it->timeline < node->timeline)
p = &parent->rb_right;
else
p = &parent->rb_left;
}
rb_link_node(&node->node, parent, p);
rb_insert_color(&node->node, &ref->tree);
spin_unlock_irqrestore(&ref->tree_lock, flags);
GEM_BUG_ON(!intel_engine_pm_is_awake(engine));
llist_add(barrier_to_ll(node), &engine->barrier_tasks);
intel_engine_pm_put_delay(engine, 2);
}
}
static struct dma_fence **ll_to_fence_slot(struct llist_node *node)
{
return __active_fence_slot(&barrier_from_ll(node)->base);
}
void i915_request_add_active_barriers(struct i915_request *rq)
{
struct intel_engine_cs *engine = rq->engine;
struct llist_node *node, *next;
unsigned long flags;
GEM_BUG_ON(!intel_context_is_barrier(rq->context));
GEM_BUG_ON(intel_engine_is_virtual(engine));
GEM_BUG_ON(i915_request_timeline(rq) != engine->kernel_context->timeline);
node = llist_del_all(&engine->barrier_tasks);
if (!node)
return;
/*
* Attach the list of proto-fences to the in-flight request such
* that the parent i915_active will be released when this request
* is retired.
*/
spin_lock_irqsave(&rq->lock, flags);
llist_for_each_safe(node, next, node) {
/* serialise with reuse_idle_barrier */
smp_store_mb(*ll_to_fence_slot(node), &rq->fence);
list_add_tail((struct list_head *)node, &rq->fence.cb_list);
}
spin_unlock_irqrestore(&rq->lock, flags);
}
/*
* __i915_active_fence_set: Update the last active fence along its timeline
* @active: the active tracker
* @fence: the new fence (under construction)
*
* Records the new @fence as the last active fence along its timeline in
* this active tracker, moving the tracking callbacks from the previous
* fence onto this one. Gets and returns a reference to the previous fence
* (if not already completed), which the caller must put after making sure
* that it is executed before the new fence. To ensure that the order of
* fences within the timeline of the i915_active_fence is understood, it
* should be locked by the caller.
*/
struct dma_fence *
__i915_active_fence_set(struct i915_active_fence *active,
struct dma_fence *fence)
{
struct dma_fence *prev;
unsigned long flags;
/*
* In case of fences embedded in i915_requests, their memory is
* SLAB_FAILSAFE_BY_RCU, then it can be reused right after release
* by new requests. Then, there is a risk of passing back a pointer
* to a new, completely unrelated fence that reuses the same memory
* while tracked under a different active tracker. Combined with i915
* perf open/close operations that build await dependencies between
* engine kernel context requests and user requests from different
* timelines, this can lead to dependency loops and infinite waits.
*
* As a countermeasure, we try to get a reference to the active->fence
* first, so if we succeed and pass it back to our user then it is not
* released and potentially reused by an unrelated request before the
* user has a chance to set up an await dependency on it.
*/
prev = i915_active_fence_get(active);
if (fence == prev)
return fence;
GEM_BUG_ON(test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags));
/*
* Consider that we have two threads arriving (A and B), with
* C already resident as the active->fence.
*
* Both A and B have got a reference to C or NULL, depending on the
* timing of the interrupt handler. Let's assume that if A has got C
* then it has locked C first (before B).
*
* Note the strong ordering of the timeline also provides consistent
* nesting rules for the fence->lock; the inner lock is always the
* older lock.
*/
spin_lock_irqsave(fence->lock, flags);
if (prev)
spin_lock_nested(prev->lock, SINGLE_DEPTH_NESTING);
/*
* A does the cmpxchg first, and so it sees C or NULL, as before, or
* something else, depending on the timing of other threads and/or
* interrupt handler. If not the same as before then A unlocks C if
* applicable and retries, starting from an attempt to get a new
* active->fence. Meanwhile, B follows the same path as A.
* Once A succeeds with cmpxch, B fails again, retires, gets A from
* active->fence, locks it as soon as A completes, and possibly
* succeeds with cmpxchg.
*/
while (cmpxchg(__active_fence_slot(active), prev, fence) != prev) {
if (prev) {
spin_unlock(prev->lock);
dma_fence_put(prev);
}
spin_unlock_irqrestore(fence->lock, flags);
prev = i915_active_fence_get(active);
GEM_BUG_ON(prev == fence);
spin_lock_irqsave(fence->lock, flags);
if (prev)
spin_lock_nested(prev->lock, SINGLE_DEPTH_NESTING);
}
/*
* If prev is NULL then the previous fence must have been signaled
* and we know that we are first on the timeline. If it is still
* present then, having the lock on that fence already acquired, we
* serialise with the interrupt handler, in the process of removing it
* from any future interrupt callback. A will then wait on C before
* executing (if present).
*
* As B is second, it sees A as the previous fence and so waits for
* it to complete its transition and takes over the occupancy for
* itself -- remembering that it needs to wait on A before executing.
*/
if (prev) {
__list_del_entry(&active->cb.node);
spin_unlock(prev->lock); /* serialise with prev->cb_list */
}
list_add_tail(&active->cb.node, &fence->cb_list);
spin_unlock_irqrestore(fence->lock, flags);
return prev;
}
int i915_active_fence_set(struct i915_active_fence *active,
struct i915_request *rq)
{
struct dma_fence *fence;
int err = 0;
/* Must maintain timeline ordering wrt previous active requests */
fence = __i915_active_fence_set(active, &rq->fence);
if (fence) {
err = i915_request_await_dma_fence(rq, fence);
dma_fence_put(fence);
}
return err;
}
void i915_active_noop(struct dma_fence *fence, struct dma_fence_cb *cb)
{
active_fence_cb(fence, cb);
}
struct auto_active {
struct i915_active base;
struct kref ref;
};
struct i915_active *i915_active_get(struct i915_active *ref)
{
struct auto_active *aa = container_of(ref, typeof(*aa), base);
kref_get(&aa->ref);
return &aa->base;
}
static void auto_release(struct kref *ref)
{
struct auto_active *aa = container_of(ref, typeof(*aa), ref);
i915_active_fini(&aa->base);
kfree(aa);
}
void i915_active_put(struct i915_active *ref)
{
struct auto_active *aa = container_of(ref, typeof(*aa), base);
kref_put(&aa->ref, auto_release);
}
static int auto_active(struct i915_active *ref)
{
i915_active_get(ref);
return 0;
}
static void auto_retire(struct i915_active *ref)
{
i915_active_put(ref);
}
struct i915_active *i915_active_create(void)
{
struct auto_active *aa;
aa = kmalloc(sizeof(*aa), GFP_KERNEL);
if (!aa)
return NULL;
kref_init(&aa->ref);
i915_active_init(&aa->base, auto_active, auto_retire, 0);
return &aa->base;
}
#if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
#include "selftests/i915_active.c"
#endif
void i915_active_module_exit(void)
{
kmem_cache_destroy(slab_cache);
}
int __init i915_active_module_init(void)
{
slab_cache = KMEM_CACHE(active_node, SLAB_HWCACHE_ALIGN);
if (!slab_cache)
return -ENOMEM;
return 0;
}
| linux-master | drivers/gpu/drm/i915/i915_active.c |
/*
* SPDX-License-Identifier: MIT
*
* Copyright © 2018 Intel Corporation
*/
#include <linux/nospec.h>
#include <linux/sched/signal.h>
#include <linux/uaccess.h>
#include <uapi/drm/i915_drm.h>
#include "i915_user_extensions.h"
#include "i915_utils.h"
int i915_user_extensions(struct i915_user_extension __user *ext,
const i915_user_extension_fn *tbl,
unsigned int count,
void *data)
{
unsigned int stackdepth = 512;
while (ext) {
int i, err;
u32 name;
u64 next;
if (!stackdepth--) /* recursion vs useful flexibility */
return -E2BIG;
err = check_user_mbz(&ext->flags);
if (err)
return err;
for (i = 0; i < ARRAY_SIZE(ext->rsvd); i++) {
err = check_user_mbz(&ext->rsvd[i]);
if (err)
return err;
}
if (get_user(name, &ext->name))
return -EFAULT;
err = -EINVAL;
if (name < count) {
name = array_index_nospec(name, count);
if (tbl[name])
err = tbl[name](ext, data);
}
if (err)
return err;
if (get_user(next, &ext->next_extension) ||
overflows_type(next, uintptr_t))
return -EFAULT;
ext = u64_to_user_ptr(next);
}
return 0;
}
| linux-master | drivers/gpu/drm/i915/i915_user_extensions.c |
/*
* Copyright © 2015-2016 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* Authors:
* Robert Bragg <[email protected]>
*/
/**
* DOC: i915 Perf Overview
*
* Gen graphics supports a large number of performance counters that can help
* driver and application developers understand and optimize their use of the
* GPU.
*
* This i915 perf interface enables userspace to configure and open a file
* descriptor representing a stream of GPU metrics which can then be read() as
* a stream of sample records.
*
* The interface is particularly suited to exposing buffered metrics that are
* captured by DMA from the GPU, unsynchronized with and unrelated to the CPU.
*
* Streams representing a single context are accessible to applications with a
* corresponding drm file descriptor, such that OpenGL can use the interface
* without special privileges. Access to system-wide metrics requires root
* privileges by default, unless changed via the dev.i915.perf_event_paranoid
* sysctl option.
*
*/
/**
* DOC: i915 Perf History and Comparison with Core Perf
*
* The interface was initially inspired by the core Perf infrastructure but
* some notable differences are:
*
* i915 perf file descriptors represent a "stream" instead of an "event"; where
* a perf event primarily corresponds to a single 64bit value, while a stream
* might sample sets of tightly-coupled counters, depending on the
* configuration. For example the Gen OA unit isn't designed to support
* orthogonal configurations of individual counters; it's configured for a set
* of related counters. Samples for an i915 perf stream capturing OA metrics
* will include a set of counter values packed in a compact HW specific format.
* The OA unit supports a number of different packing formats which can be
* selected by the user opening the stream. Perf has support for grouping
* events, but each event in the group is configured, validated and
* authenticated individually with separate system calls.
*
* i915 perf stream configurations are provided as an array of u64 (key,value)
* pairs, instead of a fixed struct with multiple miscellaneous config members,
* interleaved with event-type specific members.
*
* i915 perf doesn't support exposing metrics via an mmap'd circular buffer.
* The supported metrics are being written to memory by the GPU unsynchronized
* with the CPU, using HW specific packing formats for counter sets. Sometimes
* the constraints on HW configuration require reports to be filtered before it
* would be acceptable to expose them to unprivileged applications - to hide
* the metrics of other processes/contexts. For these use cases a read() based
* interface is a good fit, and provides an opportunity to filter data as it
* gets copied from the GPU mapped buffers to userspace buffers.
*
*
* Issues hit with first prototype based on Core Perf
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* The first prototype of this driver was based on the core perf
* infrastructure, and while we did make that mostly work, with some changes to
* perf, we found we were breaking or working around too many assumptions baked
* into perf's currently cpu centric design.
*
* In the end we didn't see a clear benefit to making perf's implementation and
* interface more complex by changing design assumptions while we knew we still
* wouldn't be able to use any existing perf based userspace tools.
*
* Also considering the Gen specific nature of the Observability hardware and
* how userspace will sometimes need to combine i915 perf OA metrics with
* side-band OA data captured via MI_REPORT_PERF_COUNT commands; we're
* expecting the interface to be used by a platform specific userspace such as
* OpenGL or tools. This is to say; we aren't inherently missing out on having
* a standard vendor/architecture agnostic interface by not using perf.
*
*
* For posterity, in case we might re-visit trying to adapt core perf to be
* better suited to exposing i915 metrics these were the main pain points we
* hit:
*
* - The perf based OA PMU driver broke some significant design assumptions:
*
* Existing perf pmus are used for profiling work on a cpu and we were
* introducing the idea of _IS_DEVICE pmus with different security
* implications, the need to fake cpu-related data (such as user/kernel
* registers) to fit with perf's current design, and adding _DEVICE records
* as a way to forward device-specific status records.
*
* The OA unit writes reports of counters into a circular buffer, without
* involvement from the CPU, making our PMU driver the first of a kind.
*
* Given the way we were periodically forward data from the GPU-mapped, OA
* buffer to perf's buffer, those bursts of sample writes looked to perf like
* we were sampling too fast and so we had to subvert its throttling checks.
*
* Perf supports groups of counters and allows those to be read via
* transactions internally but transactions currently seem designed to be
* explicitly initiated from the cpu (say in response to a userspace read())
* and while we could pull a report out of the OA buffer we can't
* trigger a report from the cpu on demand.
*
* Related to being report based; the OA counters are configured in HW as a
* set while perf generally expects counter configurations to be orthogonal.
* Although counters can be associated with a group leader as they are
* opened, there's no clear precedent for being able to provide group-wide
* configuration attributes (for example we want to let userspace choose the
* OA unit report format used to capture all counters in a set, or specify a
* GPU context to filter metrics on). We avoided using perf's grouping
* feature and forwarded OA reports to userspace via perf's 'raw' sample
* field. This suited our userspace well considering how coupled the counters
* are when dealing with normalizing. It would be inconvenient to split
* counters up into separate events, only to require userspace to recombine
* them. For Mesa it's also convenient to be forwarded raw, periodic reports
* for combining with the side-band raw reports it captures using
* MI_REPORT_PERF_COUNT commands.
*
* - As a side note on perf's grouping feature; there was also some concern
* that using PERF_FORMAT_GROUP as a way to pack together counter values
* would quite drastically inflate our sample sizes, which would likely
* lower the effective sampling resolutions we could use when the available
* memory bandwidth is limited.
*
* With the OA unit's report formats, counters are packed together as 32
* or 40bit values, with the largest report size being 256 bytes.
*
* PERF_FORMAT_GROUP values are 64bit, but there doesn't appear to be a
* documented ordering to the values, implying PERF_FORMAT_ID must also be
* used to add a 64bit ID before each value; giving 16 bytes per counter.
*
* Related to counter orthogonality; we can't time share the OA unit, while
* event scheduling is a central design idea within perf for allowing
* userspace to open + enable more events than can be configured in HW at any
* one time. The OA unit is not designed to allow re-configuration while in
* use. We can't reconfigure the OA unit without losing internal OA unit
* state which we can't access explicitly to save and restore. Reconfiguring
* the OA unit is also relatively slow, involving ~100 register writes. From
* userspace Mesa also depends on a stable OA configuration when emitting
* MI_REPORT_PERF_COUNT commands and importantly the OA unit can't be
* disabled while there are outstanding MI_RPC commands lest we hang the
* command streamer.
*
* The contents of sample records aren't extensible by device drivers (i.e.
* the sample_type bits). As an example; Sourab Gupta had been looking to
* attach GPU timestamps to our OA samples. We were shoehorning OA reports
* into sample records by using the 'raw' field, but it's tricky to pack more
* than one thing into this field because events/core.c currently only lets a
* pmu give a single raw data pointer plus len which will be copied into the
* ring buffer. To include more than the OA report we'd have to copy the
* report into an intermediate larger buffer. I'd been considering allowing a
* vector of data+len values to be specified for copying the raw data, but
* it felt like a kludge to being using the raw field for this purpose.
*
* - It felt like our perf based PMU was making some technical compromises
* just for the sake of using perf:
*
* perf_event_open() requires events to either relate to a pid or a specific
* cpu core, while our device pmu related to neither. Events opened with a
* pid will be automatically enabled/disabled according to the scheduling of
* that process - so not appropriate for us. When an event is related to a
* cpu id, perf ensures pmu methods will be invoked via an inter process
* interrupt on that core. To avoid invasive changes our userspace opened OA
* perf events for a specific cpu. This was workable but it meant the
* majority of the OA driver ran in atomic context, including all OA report
* forwarding, which wasn't really necessary in our case and seems to make
* our locking requirements somewhat complex as we handled the interaction
* with the rest of the i915 driver.
*/
#include <linux/anon_inodes.h>
#include <linux/nospec.h>
#include <linux/sizes.h>
#include <linux/uuid.h>
#include "gem/i915_gem_context.h"
#include "gem/i915_gem_internal.h"
#include "gt/intel_engine_pm.h"
#include "gt/intel_engine_regs.h"
#include "gt/intel_engine_user.h"
#include "gt/intel_execlists_submission.h"
#include "gt/intel_gpu_commands.h"
#include "gt/intel_gt.h"
#include "gt/intel_gt_clock_utils.h"
#include "gt/intel_gt_mcr.h"
#include "gt/intel_gt_regs.h"
#include "gt/intel_lrc.h"
#include "gt/intel_lrc_reg.h"
#include "gt/intel_rc6.h"
#include "gt/intel_ring.h"
#include "gt/uc/intel_guc_slpc.h"
#include "i915_drv.h"
#include "i915_file_private.h"
#include "i915_perf.h"
#include "i915_perf_oa_regs.h"
#include "i915_reg.h"
/* HW requires this to be a power of two, between 128k and 16M, though driver
* is currently generally designed assuming the largest 16M size is used such
* that the overflow cases are unlikely in normal operation.
*/
#define OA_BUFFER_SIZE SZ_16M
#define OA_TAKEN(tail, head) ((tail - head) & (OA_BUFFER_SIZE - 1))
/**
* DOC: OA Tail Pointer Race
*
* There's a HW race condition between OA unit tail pointer register updates and
* writes to memory whereby the tail pointer can sometimes get ahead of what's
* been written out to the OA buffer so far (in terms of what's visible to the
* CPU).
*
* Although this can be observed explicitly while copying reports to userspace
* by checking for a zeroed report-id field in tail reports, we want to account
* for this earlier, as part of the oa_buffer_check_unlocked to avoid lots of
* redundant read() attempts.
*
* We workaround this issue in oa_buffer_check_unlocked() by reading the reports
* in the OA buffer, starting from the tail reported by the HW until we find a
* report with its first 2 dwords not 0 meaning its previous report is
* completely in memory and ready to be read. Those dwords are also set to 0
* once read and the whole buffer is cleared upon OA buffer initialization. The
* first dword is the reason for this report while the second is the timestamp,
* making the chances of having those 2 fields at 0 fairly unlikely. A more
* detailed explanation is available in oa_buffer_check_unlocked().
*
* Most of the implementation details for this workaround are in
* oa_buffer_check_unlocked() and _append_oa_reports()
*
* Note for posterity: previously the driver used to define an effective tail
* pointer that lagged the real pointer by a 'tail margin' measured in bytes
* derived from %OA_TAIL_MARGIN_NSEC and the configured sampling frequency.
* This was flawed considering that the OA unit may also automatically generate
* non-periodic reports (such as on context switch) or the OA unit may be
* enabled without any periodic sampling.
*/
#define OA_TAIL_MARGIN_NSEC 100000ULL
#define INVALID_TAIL_PTR 0xffffffff
/* The default frequency for checking whether the OA unit has written new
* reports to the circular OA buffer...
*/
#define DEFAULT_POLL_FREQUENCY_HZ 200
#define DEFAULT_POLL_PERIOD_NS (NSEC_PER_SEC / DEFAULT_POLL_FREQUENCY_HZ)
/* for sysctl proc_dointvec_minmax of dev.i915.perf_stream_paranoid */
static u32 i915_perf_stream_paranoid = true;
/* The maximum exponent the hardware accepts is 63 (essentially it selects one
* of the 64bit timestamp bits to trigger reports from) but there's currently
* no known use case for sampling as infrequently as once per 47 thousand years.
*
* Since the timestamps included in OA reports are only 32bits it seems
* reasonable to limit the OA exponent where it's still possible to account for
* overflow in OA report timestamps.
*/
#define OA_EXPONENT_MAX 31
#define INVALID_CTX_ID 0xffffffff
/* On Gen8+ automatically triggered OA reports include a 'reason' field... */
#define OAREPORT_REASON_MASK 0x3f
#define OAREPORT_REASON_MASK_EXTENDED 0x7f
#define OAREPORT_REASON_SHIFT 19
#define OAREPORT_REASON_TIMER (1<<0)
#define OAREPORT_REASON_CTX_SWITCH (1<<3)
#define OAREPORT_REASON_CLK_RATIO (1<<5)
#define HAS_MI_SET_PREDICATE(i915) (GRAPHICS_VER_FULL(i915) >= IP_VER(12, 50))
/* For sysctl proc_dointvec_minmax of i915_oa_max_sample_rate
*
* The highest sampling frequency we can theoretically program the OA unit
* with is always half the timestamp frequency: E.g. 6.25Mhz for Haswell.
*
* Initialized just before we register the sysctl parameter.
*/
static int oa_sample_rate_hard_limit;
/* Theoretically we can program the OA unit to sample every 160ns but don't
* allow that by default unless root...
*
* The default threshold of 100000Hz is based on perf's similar
* kernel.perf_event_max_sample_rate sysctl parameter.
*/
static u32 i915_oa_max_sample_rate = 100000;
/* XXX: beware if future OA HW adds new report formats that the current
* code assumes all reports have a power-of-two size and ~(size - 1) can
* be used as a mask to align the OA tail pointer.
*/
static const struct i915_oa_format oa_formats[I915_OA_FORMAT_MAX] = {
[I915_OA_FORMAT_A13] = { 0, 64 },
[I915_OA_FORMAT_A29] = { 1, 128 },
[I915_OA_FORMAT_A13_B8_C8] = { 2, 128 },
/* A29_B8_C8 Disallowed as 192 bytes doesn't factor into buffer size */
[I915_OA_FORMAT_B4_C8] = { 4, 64 },
[I915_OA_FORMAT_A45_B8_C8] = { 5, 256 },
[I915_OA_FORMAT_B4_C8_A16] = { 6, 128 },
[I915_OA_FORMAT_C4_B8] = { 7, 64 },
[I915_OA_FORMAT_A12] = { 0, 64 },
[I915_OA_FORMAT_A12_B8_C8] = { 2, 128 },
[I915_OA_FORMAT_A32u40_A4u32_B8_C8] = { 5, 256 },
[I915_OAR_FORMAT_A32u40_A4u32_B8_C8] = { 5, 256 },
[I915_OA_FORMAT_A24u40_A14u32_B8_C8] = { 5, 256 },
[I915_OAM_FORMAT_MPEC8u64_B8_C8] = { 1, 192, TYPE_OAM, HDR_64_BIT },
[I915_OAM_FORMAT_MPEC8u32_B8_C8] = { 2, 128, TYPE_OAM, HDR_64_BIT },
};
static const u32 mtl_oa_base[] = {
[PERF_GROUP_OAM_SAMEDIA_0] = 0x393000,
};
#define SAMPLE_OA_REPORT (1<<0)
/**
* struct perf_open_properties - for validated properties given to open a stream
* @sample_flags: `DRM_I915_PERF_PROP_SAMPLE_*` properties are tracked as flags
* @single_context: Whether a single or all gpu contexts should be monitored
* @hold_preemption: Whether the preemption is disabled for the filtered
* context
* @ctx_handle: A gem ctx handle for use with @single_context
* @metrics_set: An ID for an OA unit metric set advertised via sysfs
* @oa_format: An OA unit HW report format
* @oa_periodic: Whether to enable periodic OA unit sampling
* @oa_period_exponent: The OA unit sampling period is derived from this
* @engine: The engine (typically rcs0) being monitored by the OA unit
* @has_sseu: Whether @sseu was specified by userspace
* @sseu: internal SSEU configuration computed either from the userspace
* specified configuration in the opening parameters or a default value
* (see get_default_sseu_config())
* @poll_oa_period: The period in nanoseconds at which the CPU will check for OA
* data availability
*
* As read_properties_unlocked() enumerates and validates the properties given
* to open a stream of metrics the configuration is built up in the structure
* which starts out zero initialized.
*/
struct perf_open_properties {
u32 sample_flags;
u64 single_context:1;
u64 hold_preemption:1;
u64 ctx_handle;
/* OA sampling state */
int metrics_set;
int oa_format;
bool oa_periodic;
int oa_period_exponent;
struct intel_engine_cs *engine;
bool has_sseu;
struct intel_sseu sseu;
u64 poll_oa_period;
};
struct i915_oa_config_bo {
struct llist_node node;
struct i915_oa_config *oa_config;
struct i915_vma *vma;
};
static struct ctl_table_header *sysctl_header;
static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer);
void i915_oa_config_release(struct kref *ref)
{
struct i915_oa_config *oa_config =
container_of(ref, typeof(*oa_config), ref);
kfree(oa_config->flex_regs);
kfree(oa_config->b_counter_regs);
kfree(oa_config->mux_regs);
kfree_rcu(oa_config, rcu);
}
struct i915_oa_config *
i915_perf_get_oa_config(struct i915_perf *perf, int metrics_set)
{
struct i915_oa_config *oa_config;
rcu_read_lock();
oa_config = idr_find(&perf->metrics_idr, metrics_set);
if (oa_config)
oa_config = i915_oa_config_get(oa_config);
rcu_read_unlock();
return oa_config;
}
static void free_oa_config_bo(struct i915_oa_config_bo *oa_bo)
{
i915_oa_config_put(oa_bo->oa_config);
i915_vma_put(oa_bo->vma);
kfree(oa_bo);
}
static inline const
struct i915_perf_regs *__oa_regs(struct i915_perf_stream *stream)
{
return &stream->engine->oa_group->regs;
}
static u32 gen12_oa_hw_tail_read(struct i915_perf_stream *stream)
{
struct intel_uncore *uncore = stream->uncore;
return intel_uncore_read(uncore, __oa_regs(stream)->oa_tail_ptr) &
GEN12_OAG_OATAILPTR_MASK;
}
static u32 gen8_oa_hw_tail_read(struct i915_perf_stream *stream)
{
struct intel_uncore *uncore = stream->uncore;
return intel_uncore_read(uncore, GEN8_OATAILPTR) & GEN8_OATAILPTR_MASK;
}
static u32 gen7_oa_hw_tail_read(struct i915_perf_stream *stream)
{
struct intel_uncore *uncore = stream->uncore;
u32 oastatus1 = intel_uncore_read(uncore, GEN7_OASTATUS1);
return oastatus1 & GEN7_OASTATUS1_TAIL_MASK;
}
#define oa_report_header_64bit(__s) \
((__s)->oa_buffer.format->header == HDR_64_BIT)
static u64 oa_report_id(struct i915_perf_stream *stream, void *report)
{
return oa_report_header_64bit(stream) ? *(u64 *)report : *(u32 *)report;
}
static u64 oa_report_reason(struct i915_perf_stream *stream, void *report)
{
return (oa_report_id(stream, report) >> OAREPORT_REASON_SHIFT) &
(GRAPHICS_VER(stream->perf->i915) == 12 ?
OAREPORT_REASON_MASK_EXTENDED :
OAREPORT_REASON_MASK);
}
static void oa_report_id_clear(struct i915_perf_stream *stream, u32 *report)
{
if (oa_report_header_64bit(stream))
*(u64 *)report = 0;
else
*report = 0;
}
static bool oa_report_ctx_invalid(struct i915_perf_stream *stream, void *report)
{
return !(oa_report_id(stream, report) &
stream->perf->gen8_valid_ctx_bit) &&
GRAPHICS_VER(stream->perf->i915) <= 11;
}
static u64 oa_timestamp(struct i915_perf_stream *stream, void *report)
{
return oa_report_header_64bit(stream) ?
*((u64 *)report + 1) :
*((u32 *)report + 1);
}
static void oa_timestamp_clear(struct i915_perf_stream *stream, u32 *report)
{
if (oa_report_header_64bit(stream))
*(u64 *)&report[2] = 0;
else
report[1] = 0;
}
static u32 oa_context_id(struct i915_perf_stream *stream, u32 *report)
{
u32 ctx_id = oa_report_header_64bit(stream) ? report[4] : report[2];
return ctx_id & stream->specific_ctx_id_mask;
}
static void oa_context_id_squash(struct i915_perf_stream *stream, u32 *report)
{
if (oa_report_header_64bit(stream))
report[4] = INVALID_CTX_ID;
else
report[2] = INVALID_CTX_ID;
}
/**
* oa_buffer_check_unlocked - check for data and update tail ptr state
* @stream: i915 stream instance
*
* This is either called via fops (for blocking reads in user ctx) or the poll
* check hrtimer (atomic ctx) to check the OA buffer tail pointer and check
* if there is data available for userspace to read.
*
* This function is central to providing a workaround for the OA unit tail
* pointer having a race with respect to what data is visible to the CPU.
* It is responsible for reading tail pointers from the hardware and giving
* the pointers time to 'age' before they are made available for reading.
* (See description of OA_TAIL_MARGIN_NSEC above for further details.)
*
* Besides returning true when there is data available to read() this function
* also updates the tail in the oa_buffer object.
*
* Note: It's safe to read OA config state here unlocked, assuming that this is
* only called while the stream is enabled, while the global OA configuration
* can't be modified.
*
* Returns: %true if the OA buffer contains data, else %false
*/
static bool oa_buffer_check_unlocked(struct i915_perf_stream *stream)
{
u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
int report_size = stream->oa_buffer.format->size;
u32 head, tail, read_tail;
unsigned long flags;
bool pollin;
u32 hw_tail;
u32 partial_report_size;
/* We have to consider the (unlikely) possibility that read() errors
* could result in an OA buffer reset which might reset the head and
* tail state.
*/
spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
hw_tail = stream->perf->ops.oa_hw_tail_read(stream);
/* The tail pointer increases in 64 byte increments, not in report_size
* steps. Also the report size may not be a power of 2. Compute
* potentially partially landed report in the OA buffer
*/
partial_report_size = OA_TAKEN(hw_tail, stream->oa_buffer.tail);
partial_report_size %= report_size;
/* Subtract partial amount off the tail */
hw_tail = OA_TAKEN(hw_tail, partial_report_size);
/* NB: The head we observe here might effectively be a little
* out of date. If a read() is in progress, the head could be
* anywhere between this head and stream->oa_buffer.tail.
*/
head = stream->oa_buffer.head - gtt_offset;
read_tail = stream->oa_buffer.tail - gtt_offset;
tail = hw_tail;
/* Walk the stream backward until we find a report with report
* id and timestmap not at 0. Since the circular buffer pointers
* progress by increments of 64 bytes and that reports can be up
* to 256 bytes long, we can't tell whether a report has fully
* landed in memory before the report id and timestamp of the
* following report have effectively landed.
*
* This is assuming that the writes of the OA unit land in
* memory in the order they were written to.
* If not : (╯°□°)╯︵ ┻━┻
*/
while (OA_TAKEN(tail, read_tail) >= report_size) {
void *report = stream->oa_buffer.vaddr + tail;
if (oa_report_id(stream, report) ||
oa_timestamp(stream, report))
break;
tail = (tail - report_size) & (OA_BUFFER_SIZE - 1);
}
if (OA_TAKEN(hw_tail, tail) > report_size &&
__ratelimit(&stream->perf->tail_pointer_race))
drm_notice(&stream->uncore->i915->drm,
"unlanded report(s) head=0x%x tail=0x%x hw_tail=0x%x\n",
head, tail, hw_tail);
stream->oa_buffer.tail = gtt_offset + tail;
pollin = OA_TAKEN(stream->oa_buffer.tail,
stream->oa_buffer.head) >= report_size;
spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
return pollin;
}
/**
* append_oa_status - Appends a status record to a userspace read() buffer.
* @stream: An i915-perf stream opened for OA metrics
* @buf: destination buffer given by userspace
* @count: the number of bytes userspace wants to read
* @offset: (inout): the current position for writing into @buf
* @type: The kind of status to report to userspace
*
* Writes a status record (such as `DRM_I915_PERF_RECORD_OA_REPORT_LOST`)
* into the userspace read() buffer.
*
* The @buf @offset will only be updated on success.
*
* Returns: 0 on success, negative error code on failure.
*/
static int append_oa_status(struct i915_perf_stream *stream,
char __user *buf,
size_t count,
size_t *offset,
enum drm_i915_perf_record_type type)
{
struct drm_i915_perf_record_header header = { type, 0, sizeof(header) };
if ((count - *offset) < header.size)
return -ENOSPC;
if (copy_to_user(buf + *offset, &header, sizeof(header)))
return -EFAULT;
(*offset) += header.size;
return 0;
}
/**
* append_oa_sample - Copies single OA report into userspace read() buffer.
* @stream: An i915-perf stream opened for OA metrics
* @buf: destination buffer given by userspace
* @count: the number of bytes userspace wants to read
* @offset: (inout): the current position for writing into @buf
* @report: A single OA report to (optionally) include as part of the sample
*
* The contents of a sample are configured through `DRM_I915_PERF_PROP_SAMPLE_*`
* properties when opening a stream, tracked as `stream->sample_flags`. This
* function copies the requested components of a single sample to the given
* read() @buf.
*
* The @buf @offset will only be updated on success.
*
* Returns: 0 on success, negative error code on failure.
*/
static int append_oa_sample(struct i915_perf_stream *stream,
char __user *buf,
size_t count,
size_t *offset,
const u8 *report)
{
int report_size = stream->oa_buffer.format->size;
struct drm_i915_perf_record_header header;
int report_size_partial;
u8 *oa_buf_end;
header.type = DRM_I915_PERF_RECORD_SAMPLE;
header.pad = 0;
header.size = stream->sample_size;
if ((count - *offset) < header.size)
return -ENOSPC;
buf += *offset;
if (copy_to_user(buf, &header, sizeof(header)))
return -EFAULT;
buf += sizeof(header);
oa_buf_end = stream->oa_buffer.vaddr + OA_BUFFER_SIZE;
report_size_partial = oa_buf_end - report;
if (report_size_partial < report_size) {
if (copy_to_user(buf, report, report_size_partial))
return -EFAULT;
buf += report_size_partial;
if (copy_to_user(buf, stream->oa_buffer.vaddr,
report_size - report_size_partial))
return -EFAULT;
} else if (copy_to_user(buf, report, report_size)) {
return -EFAULT;
}
(*offset) += header.size;
return 0;
}
/**
* gen8_append_oa_reports - Copies all buffered OA reports into
* userspace read() buffer.
* @stream: An i915-perf stream opened for OA metrics
* @buf: destination buffer given by userspace
* @count: the number of bytes userspace wants to read
* @offset: (inout): the current position for writing into @buf
*
* Notably any error condition resulting in a short read (-%ENOSPC or
* -%EFAULT) will be returned even though one or more records may
* have been successfully copied. In this case it's up to the caller
* to decide if the error should be squashed before returning to
* userspace.
*
* Note: reports are consumed from the head, and appended to the
* tail, so the tail chases the head?... If you think that's mad
* and back-to-front you're not alone, but this follows the
* Gen PRM naming convention.
*
* Returns: 0 on success, negative error code on failure.
*/
static int gen8_append_oa_reports(struct i915_perf_stream *stream,
char __user *buf,
size_t count,
size_t *offset)
{
struct intel_uncore *uncore = stream->uncore;
int report_size = stream->oa_buffer.format->size;
u8 *oa_buf_base = stream->oa_buffer.vaddr;
u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
u32 mask = (OA_BUFFER_SIZE - 1);
size_t start_offset = *offset;
unsigned long flags;
u32 head, tail;
int ret = 0;
if (drm_WARN_ON(&uncore->i915->drm, !stream->enabled))
return -EIO;
spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
head = stream->oa_buffer.head;
tail = stream->oa_buffer.tail;
spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
/*
* NB: oa_buffer.head/tail include the gtt_offset which we don't want
* while indexing relative to oa_buf_base.
*/
head -= gtt_offset;
tail -= gtt_offset;
/*
* An out of bounds or misaligned head or tail pointer implies a driver
* bug since we validate + align the tail pointers we read from the
* hardware and we are in full control of the head pointer which should
* only be incremented by multiples of the report size.
*/
if (drm_WARN_ONCE(&uncore->i915->drm,
head > OA_BUFFER_SIZE ||
tail > OA_BUFFER_SIZE,
"Inconsistent OA buffer pointers: head = %u, tail = %u\n",
head, tail))
return -EIO;
for (/* none */;
OA_TAKEN(tail, head);
head = (head + report_size) & mask) {
u8 *report = oa_buf_base + head;
u32 *report32 = (void *)report;
u32 ctx_id;
u64 reason;
/*
* The reason field includes flags identifying what
* triggered this specific report (mostly timer
* triggered or e.g. due to a context switch).
*
* In MMIO triggered reports, some platforms do not set the
* reason bit in this field and it is valid to have a reason
* field of zero.
*/
reason = oa_report_reason(stream, report);
ctx_id = oa_context_id(stream, report32);
/*
* Squash whatever is in the CTX_ID field if it's marked as
* invalid to be sure we avoid false-positive, single-context
* filtering below...
*
* Note: that we don't clear the valid_ctx_bit so userspace can
* understand that the ID has been squashed by the kernel.
*/
if (oa_report_ctx_invalid(stream, report)) {
ctx_id = INVALID_CTX_ID;
oa_context_id_squash(stream, report32);
}
/*
* NB: For Gen 8 the OA unit no longer supports clock gating
* off for a specific context and the kernel can't securely
* stop the counters from updating as system-wide / global
* values.
*
* Automatic reports now include a context ID so reports can be
* filtered on the cpu but it's not worth trying to
* automatically subtract/hide counter progress for other
* contexts while filtering since we can't stop userspace
* issuing MI_REPORT_PERF_COUNT commands which would still
* provide a side-band view of the real values.
*
* To allow userspace (such as Mesa/GL_INTEL_performance_query)
* to normalize counters for a single filtered context then it
* needs be forwarded bookend context-switch reports so that it
* can track switches in between MI_REPORT_PERF_COUNT commands
* and can itself subtract/ignore the progress of counters
* associated with other contexts. Note that the hardware
* automatically triggers reports when switching to a new
* context which are tagged with the ID of the newly active
* context. To avoid the complexity (and likely fragility) of
* reading ahead while parsing reports to try and minimize
* forwarding redundant context switch reports (i.e. between
* other, unrelated contexts) we simply elect to forward them
* all.
*
* We don't rely solely on the reason field to identify context
* switches since it's not-uncommon for periodic samples to
* identify a switch before any 'context switch' report.
*/
if (!stream->ctx ||
stream->specific_ctx_id == ctx_id ||
stream->oa_buffer.last_ctx_id == stream->specific_ctx_id ||
reason & OAREPORT_REASON_CTX_SWITCH) {
/*
* While filtering for a single context we avoid
* leaking the IDs of other contexts.
*/
if (stream->ctx &&
stream->specific_ctx_id != ctx_id) {
oa_context_id_squash(stream, report32);
}
ret = append_oa_sample(stream, buf, count, offset,
report);
if (ret)
break;
stream->oa_buffer.last_ctx_id = ctx_id;
}
if (is_power_of_2(report_size)) {
/*
* Clear out the report id and timestamp as a means
* to detect unlanded reports.
*/
oa_report_id_clear(stream, report32);
oa_timestamp_clear(stream, report32);
} else {
u8 *oa_buf_end = stream->oa_buffer.vaddr +
OA_BUFFER_SIZE;
u32 part = oa_buf_end - (u8 *)report32;
/* Zero out the entire report */
if (report_size <= part) {
memset(report32, 0, report_size);
} else {
memset(report32, 0, part);
memset(oa_buf_base, 0, report_size - part);
}
}
}
if (start_offset != *offset) {
i915_reg_t oaheadptr;
oaheadptr = GRAPHICS_VER(stream->perf->i915) == 12 ?
__oa_regs(stream)->oa_head_ptr :
GEN8_OAHEADPTR;
spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
/*
* We removed the gtt_offset for the copy loop above, indexing
* relative to oa_buf_base so put back here...
*/
head += gtt_offset;
intel_uncore_write(uncore, oaheadptr,
head & GEN12_OAG_OAHEADPTR_MASK);
stream->oa_buffer.head = head;
spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
}
return ret;
}
/**
* gen8_oa_read - copy status records then buffered OA reports
* @stream: An i915-perf stream opened for OA metrics
* @buf: destination buffer given by userspace
* @count: the number of bytes userspace wants to read
* @offset: (inout): the current position for writing into @buf
*
* Checks OA unit status registers and if necessary appends corresponding
* status records for userspace (such as for a buffer full condition) and then
* initiate appending any buffered OA reports.
*
* Updates @offset according to the number of bytes successfully copied into
* the userspace buffer.
*
* NB: some data may be successfully copied to the userspace buffer
* even if an error is returned, and this is reflected in the
* updated @offset.
*
* Returns: zero on success or a negative error code
*/
static int gen8_oa_read(struct i915_perf_stream *stream,
char __user *buf,
size_t count,
size_t *offset)
{
struct intel_uncore *uncore = stream->uncore;
u32 oastatus;
i915_reg_t oastatus_reg;
int ret;
if (drm_WARN_ON(&uncore->i915->drm, !stream->oa_buffer.vaddr))
return -EIO;
oastatus_reg = GRAPHICS_VER(stream->perf->i915) == 12 ?
__oa_regs(stream)->oa_status :
GEN8_OASTATUS;
oastatus = intel_uncore_read(uncore, oastatus_reg);
/*
* We treat OABUFFER_OVERFLOW as a significant error:
*
* Although theoretically we could handle this more gracefully
* sometimes, some Gens don't correctly suppress certain
* automatically triggered reports in this condition and so we
* have to assume that old reports are now being trampled
* over.
*
* Considering how we don't currently give userspace control
* over the OA buffer size and always configure a large 16MB
* buffer, then a buffer overflow does anyway likely indicate
* that something has gone quite badly wrong.
*/
if (oastatus & GEN8_OASTATUS_OABUFFER_OVERFLOW) {
ret = append_oa_status(stream, buf, count, offset,
DRM_I915_PERF_RECORD_OA_BUFFER_LOST);
if (ret)
return ret;
drm_dbg(&stream->perf->i915->drm,
"OA buffer overflow (exponent = %d): force restart\n",
stream->period_exponent);
stream->perf->ops.oa_disable(stream);
stream->perf->ops.oa_enable(stream);
/*
* Note: .oa_enable() is expected to re-init the oabuffer and
* reset GEN8_OASTATUS for us
*/
oastatus = intel_uncore_read(uncore, oastatus_reg);
}
if (oastatus & GEN8_OASTATUS_REPORT_LOST) {
ret = append_oa_status(stream, buf, count, offset,
DRM_I915_PERF_RECORD_OA_REPORT_LOST);
if (ret)
return ret;
intel_uncore_rmw(uncore, oastatus_reg,
GEN8_OASTATUS_COUNTER_OVERFLOW |
GEN8_OASTATUS_REPORT_LOST,
IS_GRAPHICS_VER(uncore->i915, 8, 11) ?
(GEN8_OASTATUS_HEAD_POINTER_WRAP |
GEN8_OASTATUS_TAIL_POINTER_WRAP) : 0);
}
return gen8_append_oa_reports(stream, buf, count, offset);
}
/**
* gen7_append_oa_reports - Copies all buffered OA reports into
* userspace read() buffer.
* @stream: An i915-perf stream opened for OA metrics
* @buf: destination buffer given by userspace
* @count: the number of bytes userspace wants to read
* @offset: (inout): the current position for writing into @buf
*
* Notably any error condition resulting in a short read (-%ENOSPC or
* -%EFAULT) will be returned even though one or more records may
* have been successfully copied. In this case it's up to the caller
* to decide if the error should be squashed before returning to
* userspace.
*
* Note: reports are consumed from the head, and appended to the
* tail, so the tail chases the head?... If you think that's mad
* and back-to-front you're not alone, but this follows the
* Gen PRM naming convention.
*
* Returns: 0 on success, negative error code on failure.
*/
static int gen7_append_oa_reports(struct i915_perf_stream *stream,
char __user *buf,
size_t count,
size_t *offset)
{
struct intel_uncore *uncore = stream->uncore;
int report_size = stream->oa_buffer.format->size;
u8 *oa_buf_base = stream->oa_buffer.vaddr;
u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
u32 mask = (OA_BUFFER_SIZE - 1);
size_t start_offset = *offset;
unsigned long flags;
u32 head, tail;
int ret = 0;
if (drm_WARN_ON(&uncore->i915->drm, !stream->enabled))
return -EIO;
spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
head = stream->oa_buffer.head;
tail = stream->oa_buffer.tail;
spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
/* NB: oa_buffer.head/tail include the gtt_offset which we don't want
* while indexing relative to oa_buf_base.
*/
head -= gtt_offset;
tail -= gtt_offset;
/* An out of bounds or misaligned head or tail pointer implies a driver
* bug since we validate + align the tail pointers we read from the
* hardware and we are in full control of the head pointer which should
* only be incremented by multiples of the report size (notably also
* all a power of two).
*/
if (drm_WARN_ONCE(&uncore->i915->drm,
head > OA_BUFFER_SIZE || head % report_size ||
tail > OA_BUFFER_SIZE || tail % report_size,
"Inconsistent OA buffer pointers: head = %u, tail = %u\n",
head, tail))
return -EIO;
for (/* none */;
OA_TAKEN(tail, head);
head = (head + report_size) & mask) {
u8 *report = oa_buf_base + head;
u32 *report32 = (void *)report;
/* All the report sizes factor neatly into the buffer
* size so we never expect to see a report split
* between the beginning and end of the buffer.
*
* Given the initial alignment check a misalignment
* here would imply a driver bug that would result
* in an overrun.
*/
if (drm_WARN_ON(&uncore->i915->drm,
(OA_BUFFER_SIZE - head) < report_size)) {
drm_err(&uncore->i915->drm,
"Spurious OA head ptr: non-integral report offset\n");
break;
}
/* The report-ID field for periodic samples includes
* some undocumented flags related to what triggered
* the report and is never expected to be zero so we
* can check that the report isn't invalid before
* copying it to userspace...
*/
if (report32[0] == 0) {
if (__ratelimit(&stream->perf->spurious_report_rs))
drm_notice(&uncore->i915->drm,
"Skipping spurious, invalid OA report\n");
continue;
}
ret = append_oa_sample(stream, buf, count, offset, report);
if (ret)
break;
/* Clear out the first 2 dwords as a mean to detect unlanded
* reports.
*/
report32[0] = 0;
report32[1] = 0;
}
if (start_offset != *offset) {
spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
/* We removed the gtt_offset for the copy loop above, indexing
* relative to oa_buf_base so put back here...
*/
head += gtt_offset;
intel_uncore_write(uncore, GEN7_OASTATUS2,
(head & GEN7_OASTATUS2_HEAD_MASK) |
GEN7_OASTATUS2_MEM_SELECT_GGTT);
stream->oa_buffer.head = head;
spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
}
return ret;
}
/**
* gen7_oa_read - copy status records then buffered OA reports
* @stream: An i915-perf stream opened for OA metrics
* @buf: destination buffer given by userspace
* @count: the number of bytes userspace wants to read
* @offset: (inout): the current position for writing into @buf
*
* Checks Gen 7 specific OA unit status registers and if necessary appends
* corresponding status records for userspace (such as for a buffer full
* condition) and then initiate appending any buffered OA reports.
*
* Updates @offset according to the number of bytes successfully copied into
* the userspace buffer.
*
* Returns: zero on success or a negative error code
*/
static int gen7_oa_read(struct i915_perf_stream *stream,
char __user *buf,
size_t count,
size_t *offset)
{
struct intel_uncore *uncore = stream->uncore;
u32 oastatus1;
int ret;
if (drm_WARN_ON(&uncore->i915->drm, !stream->oa_buffer.vaddr))
return -EIO;
oastatus1 = intel_uncore_read(uncore, GEN7_OASTATUS1);
/* XXX: On Haswell we don't have a safe way to clear oastatus1
* bits while the OA unit is enabled (while the tail pointer
* may be updated asynchronously) so we ignore status bits
* that have already been reported to userspace.
*/
oastatus1 &= ~stream->perf->gen7_latched_oastatus1;
/* We treat OABUFFER_OVERFLOW as a significant error:
*
* - The status can be interpreted to mean that the buffer is
* currently full (with a higher precedence than OA_TAKEN()
* which will start to report a near-empty buffer after an
* overflow) but it's awkward that we can't clear the status
* on Haswell, so without a reset we won't be able to catch
* the state again.
*
* - Since it also implies the HW has started overwriting old
* reports it may also affect our sanity checks for invalid
* reports when copying to userspace that assume new reports
* are being written to cleared memory.
*
* - In the future we may want to introduce a flight recorder
* mode where the driver will automatically maintain a safe
* guard band between head/tail, avoiding this overflow
* condition, but we avoid the added driver complexity for
* now.
*/
if (unlikely(oastatus1 & GEN7_OASTATUS1_OABUFFER_OVERFLOW)) {
ret = append_oa_status(stream, buf, count, offset,
DRM_I915_PERF_RECORD_OA_BUFFER_LOST);
if (ret)
return ret;
drm_dbg(&stream->perf->i915->drm,
"OA buffer overflow (exponent = %d): force restart\n",
stream->period_exponent);
stream->perf->ops.oa_disable(stream);
stream->perf->ops.oa_enable(stream);
oastatus1 = intel_uncore_read(uncore, GEN7_OASTATUS1);
}
if (unlikely(oastatus1 & GEN7_OASTATUS1_REPORT_LOST)) {
ret = append_oa_status(stream, buf, count, offset,
DRM_I915_PERF_RECORD_OA_REPORT_LOST);
if (ret)
return ret;
stream->perf->gen7_latched_oastatus1 |=
GEN7_OASTATUS1_REPORT_LOST;
}
return gen7_append_oa_reports(stream, buf, count, offset);
}
/**
* i915_oa_wait_unlocked - handles blocking IO until OA data available
* @stream: An i915-perf stream opened for OA metrics
*
* Called when userspace tries to read() from a blocking stream FD opened
* for OA metrics. It waits until the hrtimer callback finds a non-empty
* OA buffer and wakes us.
*
* Note: it's acceptable to have this return with some false positives
* since any subsequent read handling will return -EAGAIN if there isn't
* really data ready for userspace yet.
*
* Returns: zero on success or a negative error code
*/
static int i915_oa_wait_unlocked(struct i915_perf_stream *stream)
{
/* We would wait indefinitely if periodic sampling is not enabled */
if (!stream->periodic)
return -EIO;
return wait_event_interruptible(stream->poll_wq,
oa_buffer_check_unlocked(stream));
}
/**
* i915_oa_poll_wait - call poll_wait() for an OA stream poll()
* @stream: An i915-perf stream opened for OA metrics
* @file: An i915 perf stream file
* @wait: poll() state table
*
* For handling userspace polling on an i915 perf stream opened for OA metrics,
* this starts a poll_wait with the wait queue that our hrtimer callback wakes
* when it sees data ready to read in the circular OA buffer.
*/
static void i915_oa_poll_wait(struct i915_perf_stream *stream,
struct file *file,
poll_table *wait)
{
poll_wait(file, &stream->poll_wq, wait);
}
/**
* i915_oa_read - just calls through to &i915_oa_ops->read
* @stream: An i915-perf stream opened for OA metrics
* @buf: destination buffer given by userspace
* @count: the number of bytes userspace wants to read
* @offset: (inout): the current position for writing into @buf
*
* Updates @offset according to the number of bytes successfully copied into
* the userspace buffer.
*
* Returns: zero on success or a negative error code
*/
static int i915_oa_read(struct i915_perf_stream *stream,
char __user *buf,
size_t count,
size_t *offset)
{
return stream->perf->ops.read(stream, buf, count, offset);
}
static struct intel_context *oa_pin_context(struct i915_perf_stream *stream)
{
struct i915_gem_engines_iter it;
struct i915_gem_context *ctx = stream->ctx;
struct intel_context *ce;
struct i915_gem_ww_ctx ww;
int err = -ENODEV;
for_each_gem_engine(ce, i915_gem_context_lock_engines(ctx), it) {
if (ce->engine != stream->engine) /* first match! */
continue;
err = 0;
break;
}
i915_gem_context_unlock_engines(ctx);
if (err)
return ERR_PTR(err);
i915_gem_ww_ctx_init(&ww, true);
retry:
/*
* As the ID is the gtt offset of the context's vma we
* pin the vma to ensure the ID remains fixed.
*/
err = intel_context_pin_ww(ce, &ww);
if (err == -EDEADLK) {
err = i915_gem_ww_ctx_backoff(&ww);
if (!err)
goto retry;
}
i915_gem_ww_ctx_fini(&ww);
if (err)
return ERR_PTR(err);
stream->pinned_ctx = ce;
return stream->pinned_ctx;
}
static int
__store_reg_to_mem(struct i915_request *rq, i915_reg_t reg, u32 ggtt_offset)
{
u32 *cs, cmd;
cmd = MI_STORE_REGISTER_MEM | MI_SRM_LRM_GLOBAL_GTT;
if (GRAPHICS_VER(rq->i915) >= 8)
cmd++;
cs = intel_ring_begin(rq, 4);
if (IS_ERR(cs))
return PTR_ERR(cs);
*cs++ = cmd;
*cs++ = i915_mmio_reg_offset(reg);
*cs++ = ggtt_offset;
*cs++ = 0;
intel_ring_advance(rq, cs);
return 0;
}
static int
__read_reg(struct intel_context *ce, i915_reg_t reg, u32 ggtt_offset)
{
struct i915_request *rq;
int err;
rq = i915_request_create(ce);
if (IS_ERR(rq))
return PTR_ERR(rq);
i915_request_get(rq);
err = __store_reg_to_mem(rq, reg, ggtt_offset);
i915_request_add(rq);
if (!err && i915_request_wait(rq, 0, HZ / 2) < 0)
err = -ETIME;
i915_request_put(rq);
return err;
}
static int
gen12_guc_sw_ctx_id(struct intel_context *ce, u32 *ctx_id)
{
struct i915_vma *scratch;
u32 *val;
int err;
scratch = __vm_create_scratch_for_read_pinned(&ce->engine->gt->ggtt->vm, 4);
if (IS_ERR(scratch))
return PTR_ERR(scratch);
err = i915_vma_sync(scratch);
if (err)
goto err_scratch;
err = __read_reg(ce, RING_EXECLIST_STATUS_HI(ce->engine->mmio_base),
i915_ggtt_offset(scratch));
if (err)
goto err_scratch;
val = i915_gem_object_pin_map_unlocked(scratch->obj, I915_MAP_WB);
if (IS_ERR(val)) {
err = PTR_ERR(val);
goto err_scratch;
}
*ctx_id = *val;
i915_gem_object_unpin_map(scratch->obj);
err_scratch:
i915_vma_unpin_and_release(&scratch, 0);
return err;
}
/*
* For execlist mode of submission, pick an unused context id
* 0 - (NUM_CONTEXT_TAG -1) are used by other contexts
* XXX_MAX_CONTEXT_HW_ID is used by idle context
*
* For GuC mode of submission read context id from the upper dword of the
* EXECLIST_STATUS register. Note that we read this value only once and expect
* that the value stays fixed for the entire OA use case. There are cases where
* GuC KMD implementation may deregister a context to reuse it's context id, but
* we prevent that from happening to the OA context by pinning it.
*/
static int gen12_get_render_context_id(struct i915_perf_stream *stream)
{
u32 ctx_id, mask;
int ret;
if (intel_engine_uses_guc(stream->engine)) {
ret = gen12_guc_sw_ctx_id(stream->pinned_ctx, &ctx_id);
if (ret)
return ret;
mask = ((1U << GEN12_GUC_SW_CTX_ID_WIDTH) - 1) <<
(GEN12_GUC_SW_CTX_ID_SHIFT - 32);
} else if (GRAPHICS_VER_FULL(stream->engine->i915) >= IP_VER(12, 50)) {
ctx_id = (XEHP_MAX_CONTEXT_HW_ID - 1) <<
(XEHP_SW_CTX_ID_SHIFT - 32);
mask = ((1U << XEHP_SW_CTX_ID_WIDTH) - 1) <<
(XEHP_SW_CTX_ID_SHIFT - 32);
} else {
ctx_id = (GEN12_MAX_CONTEXT_HW_ID - 1) <<
(GEN11_SW_CTX_ID_SHIFT - 32);
mask = ((1U << GEN11_SW_CTX_ID_WIDTH) - 1) <<
(GEN11_SW_CTX_ID_SHIFT - 32);
}
stream->specific_ctx_id = ctx_id & mask;
stream->specific_ctx_id_mask = mask;
return 0;
}
static bool oa_find_reg_in_lri(u32 *state, u32 reg, u32 *offset, u32 end)
{
u32 idx = *offset;
u32 len = min(MI_LRI_LEN(state[idx]) + idx, end);
bool found = false;
idx++;
for (; idx < len; idx += 2) {
if (state[idx] == reg) {
found = true;
break;
}
}
*offset = idx;
return found;
}
static u32 oa_context_image_offset(struct intel_context *ce, u32 reg)
{
u32 offset, len = (ce->engine->context_size - PAGE_SIZE) / 4;
u32 *state = ce->lrc_reg_state;
if (drm_WARN_ON(&ce->engine->i915->drm, !state))
return U32_MAX;
for (offset = 0; offset < len; ) {
if (IS_MI_LRI_CMD(state[offset])) {
/*
* We expect reg-value pairs in MI_LRI command, so
* MI_LRI_LEN() should be even, if not, issue a warning.
*/
drm_WARN_ON(&ce->engine->i915->drm,
MI_LRI_LEN(state[offset]) & 0x1);
if (oa_find_reg_in_lri(state, reg, &offset, len))
break;
} else {
offset++;
}
}
return offset < len ? offset : U32_MAX;
}
static int set_oa_ctx_ctrl_offset(struct intel_context *ce)
{
i915_reg_t reg = GEN12_OACTXCONTROL(ce->engine->mmio_base);
struct i915_perf *perf = &ce->engine->i915->perf;
u32 offset = perf->ctx_oactxctrl_offset;
/* Do this only once. Failure is stored as offset of U32_MAX */
if (offset)
goto exit;
offset = oa_context_image_offset(ce, i915_mmio_reg_offset(reg));
perf->ctx_oactxctrl_offset = offset;
drm_dbg(&ce->engine->i915->drm,
"%s oa ctx control at 0x%08x dword offset\n",
ce->engine->name, offset);
exit:
return offset && offset != U32_MAX ? 0 : -ENODEV;
}
static bool engine_supports_mi_query(struct intel_engine_cs *engine)
{
return engine->class == RENDER_CLASS;
}
/**
* oa_get_render_ctx_id - determine and hold ctx hw id
* @stream: An i915-perf stream opened for OA metrics
*
* Determine the render context hw id, and ensure it remains fixed for the
* lifetime of the stream. This ensures that we don't have to worry about
* updating the context ID in OACONTROL on the fly.
*
* Returns: zero on success or a negative error code
*/
static int oa_get_render_ctx_id(struct i915_perf_stream *stream)
{
struct intel_context *ce;
int ret = 0;
ce = oa_pin_context(stream);
if (IS_ERR(ce))
return PTR_ERR(ce);
if (engine_supports_mi_query(stream->engine) &&
HAS_LOGICAL_RING_CONTEXTS(stream->perf->i915)) {
/*
* We are enabling perf query here. If we don't find the context
* offset here, just return an error.
*/
ret = set_oa_ctx_ctrl_offset(ce);
if (ret) {
intel_context_unpin(ce);
drm_err(&stream->perf->i915->drm,
"Enabling perf query failed for %s\n",
stream->engine->name);
return ret;
}
}
switch (GRAPHICS_VER(ce->engine->i915)) {
case 7: {
/*
* On Haswell we don't do any post processing of the reports
* and don't need to use the mask.
*/
stream->specific_ctx_id = i915_ggtt_offset(ce->state);
stream->specific_ctx_id_mask = 0;
break;
}
case 8:
case 9:
if (intel_engine_uses_guc(ce->engine)) {
/*
* When using GuC, the context descriptor we write in
* i915 is read by GuC and rewritten before it's
* actually written into the hardware. The LRCA is
* what is put into the context id field of the
* context descriptor by GuC. Because it's aligned to
* a page, the lower 12bits are always at 0 and
* dropped by GuC. They won't be part of the context
* ID in the OA reports, so squash those lower bits.
*/
stream->specific_ctx_id = ce->lrc.lrca >> 12;
/*
* GuC uses the top bit to signal proxy submission, so
* ignore that bit.
*/
stream->specific_ctx_id_mask =
(1U << (GEN8_CTX_ID_WIDTH - 1)) - 1;
} else {
stream->specific_ctx_id_mask =
(1U << GEN8_CTX_ID_WIDTH) - 1;
stream->specific_ctx_id = stream->specific_ctx_id_mask;
}
break;
case 11:
case 12:
ret = gen12_get_render_context_id(stream);
break;
default:
MISSING_CASE(GRAPHICS_VER(ce->engine->i915));
}
ce->tag = stream->specific_ctx_id;
drm_dbg(&stream->perf->i915->drm,
"filtering on ctx_id=0x%x ctx_id_mask=0x%x\n",
stream->specific_ctx_id,
stream->specific_ctx_id_mask);
return ret;
}
/**
* oa_put_render_ctx_id - counterpart to oa_get_render_ctx_id releases hold
* @stream: An i915-perf stream opened for OA metrics
*
* In case anything needed doing to ensure the context HW ID would remain valid
* for the lifetime of the stream, then that can be undone here.
*/
static void oa_put_render_ctx_id(struct i915_perf_stream *stream)
{
struct intel_context *ce;
ce = fetch_and_zero(&stream->pinned_ctx);
if (ce) {
ce->tag = 0; /* recomputed on next submission after parking */
intel_context_unpin(ce);
}
stream->specific_ctx_id = INVALID_CTX_ID;
stream->specific_ctx_id_mask = 0;
}
static void
free_oa_buffer(struct i915_perf_stream *stream)
{
i915_vma_unpin_and_release(&stream->oa_buffer.vma,
I915_VMA_RELEASE_MAP);
stream->oa_buffer.vaddr = NULL;
}
static void
free_oa_configs(struct i915_perf_stream *stream)
{
struct i915_oa_config_bo *oa_bo, *tmp;
i915_oa_config_put(stream->oa_config);
llist_for_each_entry_safe(oa_bo, tmp, stream->oa_config_bos.first, node)
free_oa_config_bo(oa_bo);
}
static void
free_noa_wait(struct i915_perf_stream *stream)
{
i915_vma_unpin_and_release(&stream->noa_wait, 0);
}
static bool engine_supports_oa(const struct intel_engine_cs *engine)
{
return engine->oa_group;
}
static bool engine_supports_oa_format(struct intel_engine_cs *engine, int type)
{
return engine->oa_group && engine->oa_group->type == type;
}
static void i915_oa_stream_destroy(struct i915_perf_stream *stream)
{
struct i915_perf *perf = stream->perf;
struct intel_gt *gt = stream->engine->gt;
struct i915_perf_group *g = stream->engine->oa_group;
if (WARN_ON(stream != g->exclusive_stream))
return;
/*
* Unset exclusive_stream first, it will be checked while disabling
* the metric set on gen8+.
*
* See i915_oa_init_reg_state() and lrc_configure_all_contexts()
*/
WRITE_ONCE(g->exclusive_stream, NULL);
perf->ops.disable_metric_set(stream);
free_oa_buffer(stream);
/*
* Wa_16011777198:dg2: Unset the override of GUCRC mode to enable rc6.
*/
if (stream->override_gucrc)
drm_WARN_ON(>->i915->drm,
intel_guc_slpc_unset_gucrc_mode(>->uc.guc.slpc));
intel_uncore_forcewake_put(stream->uncore, FORCEWAKE_ALL);
intel_engine_pm_put(stream->engine);
if (stream->ctx)
oa_put_render_ctx_id(stream);
free_oa_configs(stream);
free_noa_wait(stream);
if (perf->spurious_report_rs.missed) {
drm_notice(>->i915->drm,
"%d spurious OA report notices suppressed due to ratelimiting\n",
perf->spurious_report_rs.missed);
}
}
static void gen7_init_oa_buffer(struct i915_perf_stream *stream)
{
struct intel_uncore *uncore = stream->uncore;
u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
unsigned long flags;
spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
/* Pre-DevBDW: OABUFFER must be set with counters off,
* before OASTATUS1, but after OASTATUS2
*/
intel_uncore_write(uncore, GEN7_OASTATUS2, /* head */
gtt_offset | GEN7_OASTATUS2_MEM_SELECT_GGTT);
stream->oa_buffer.head = gtt_offset;
intel_uncore_write(uncore, GEN7_OABUFFER, gtt_offset);
intel_uncore_write(uncore, GEN7_OASTATUS1, /* tail */
gtt_offset | OABUFFER_SIZE_16M);
/* Mark that we need updated tail pointers to read from... */
stream->oa_buffer.tail = gtt_offset;
spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
/* On Haswell we have to track which OASTATUS1 flags we've
* already seen since they can't be cleared while periodic
* sampling is enabled.
*/
stream->perf->gen7_latched_oastatus1 = 0;
/* NB: although the OA buffer will initially be allocated
* zeroed via shmfs (and so this memset is redundant when
* first allocating), we may re-init the OA buffer, either
* when re-enabling a stream or in error/reset paths.
*
* The reason we clear the buffer for each re-init is for the
* sanity check in gen7_append_oa_reports() that looks at the
* report-id field to make sure it's non-zero which relies on
* the assumption that new reports are being written to zeroed
* memory...
*/
memset(stream->oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
}
static void gen8_init_oa_buffer(struct i915_perf_stream *stream)
{
struct intel_uncore *uncore = stream->uncore;
u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
unsigned long flags;
spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
intel_uncore_write(uncore, GEN8_OASTATUS, 0);
intel_uncore_write(uncore, GEN8_OAHEADPTR, gtt_offset);
stream->oa_buffer.head = gtt_offset;
intel_uncore_write(uncore, GEN8_OABUFFER_UDW, 0);
/*
* PRM says:
*
* "This MMIO must be set before the OATAILPTR
* register and after the OAHEADPTR register. This is
* to enable proper functionality of the overflow
* bit."
*/
intel_uncore_write(uncore, GEN8_OABUFFER, gtt_offset |
OABUFFER_SIZE_16M | GEN8_OABUFFER_MEM_SELECT_GGTT);
intel_uncore_write(uncore, GEN8_OATAILPTR, gtt_offset & GEN8_OATAILPTR_MASK);
/* Mark that we need updated tail pointers to read from... */
stream->oa_buffer.tail = gtt_offset;
/*
* Reset state used to recognise context switches, affecting which
* reports we will forward to userspace while filtering for a single
* context.
*/
stream->oa_buffer.last_ctx_id = INVALID_CTX_ID;
spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
/*
* NB: although the OA buffer will initially be allocated
* zeroed via shmfs (and so this memset is redundant when
* first allocating), we may re-init the OA buffer, either
* when re-enabling a stream or in error/reset paths.
*
* The reason we clear the buffer for each re-init is for the
* sanity check in gen8_append_oa_reports() that looks at the
* reason field to make sure it's non-zero which relies on
* the assumption that new reports are being written to zeroed
* memory...
*/
memset(stream->oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
}
static void gen12_init_oa_buffer(struct i915_perf_stream *stream)
{
struct intel_uncore *uncore = stream->uncore;
u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
unsigned long flags;
spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
intel_uncore_write(uncore, __oa_regs(stream)->oa_status, 0);
intel_uncore_write(uncore, __oa_regs(stream)->oa_head_ptr,
gtt_offset & GEN12_OAG_OAHEADPTR_MASK);
stream->oa_buffer.head = gtt_offset;
/*
* PRM says:
*
* "This MMIO must be set before the OATAILPTR
* register and after the OAHEADPTR register. This is
* to enable proper functionality of the overflow
* bit."
*/
intel_uncore_write(uncore, __oa_regs(stream)->oa_buffer, gtt_offset |
OABUFFER_SIZE_16M | GEN8_OABUFFER_MEM_SELECT_GGTT);
intel_uncore_write(uncore, __oa_regs(stream)->oa_tail_ptr,
gtt_offset & GEN12_OAG_OATAILPTR_MASK);
/* Mark that we need updated tail pointers to read from... */
stream->oa_buffer.tail = gtt_offset;
/*
* Reset state used to recognise context switches, affecting which
* reports we will forward to userspace while filtering for a single
* context.
*/
stream->oa_buffer.last_ctx_id = INVALID_CTX_ID;
spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
/*
* NB: although the OA buffer will initially be allocated
* zeroed via shmfs (and so this memset is redundant when
* first allocating), we may re-init the OA buffer, either
* when re-enabling a stream or in error/reset paths.
*
* The reason we clear the buffer for each re-init is for the
* sanity check in gen8_append_oa_reports() that looks at the
* reason field to make sure it's non-zero which relies on
* the assumption that new reports are being written to zeroed
* memory...
*/
memset(stream->oa_buffer.vaddr, 0,
stream->oa_buffer.vma->size);
}
static int alloc_oa_buffer(struct i915_perf_stream *stream)
{
struct drm_i915_private *i915 = stream->perf->i915;
struct intel_gt *gt = stream->engine->gt;
struct drm_i915_gem_object *bo;
struct i915_vma *vma;
int ret;
if (drm_WARN_ON(&i915->drm, stream->oa_buffer.vma))
return -ENODEV;
BUILD_BUG_ON_NOT_POWER_OF_2(OA_BUFFER_SIZE);
BUILD_BUG_ON(OA_BUFFER_SIZE < SZ_128K || OA_BUFFER_SIZE > SZ_16M);
bo = i915_gem_object_create_shmem(stream->perf->i915, OA_BUFFER_SIZE);
if (IS_ERR(bo)) {
drm_err(&i915->drm, "Failed to allocate OA buffer\n");
return PTR_ERR(bo);
}
i915_gem_object_set_cache_coherency(bo, I915_CACHE_LLC);
/* PreHSW required 512K alignment, HSW requires 16M */
vma = i915_vma_instance(bo, >->ggtt->vm, NULL);
if (IS_ERR(vma)) {
ret = PTR_ERR(vma);
goto err_unref;
}
/*
* PreHSW required 512K alignment.
* HSW and onwards, align to requested size of OA buffer.
*/
ret = i915_vma_pin(vma, 0, SZ_16M, PIN_GLOBAL | PIN_HIGH);
if (ret) {
drm_err(>->i915->drm, "Failed to pin OA buffer %d\n", ret);
goto err_unref;
}
stream->oa_buffer.vma = vma;
stream->oa_buffer.vaddr =
i915_gem_object_pin_map_unlocked(bo, I915_MAP_WB);
if (IS_ERR(stream->oa_buffer.vaddr)) {
ret = PTR_ERR(stream->oa_buffer.vaddr);
goto err_unpin;
}
return 0;
err_unpin:
__i915_vma_unpin(vma);
err_unref:
i915_gem_object_put(bo);
stream->oa_buffer.vaddr = NULL;
stream->oa_buffer.vma = NULL;
return ret;
}
static u32 *save_restore_register(struct i915_perf_stream *stream, u32 *cs,
bool save, i915_reg_t reg, u32 offset,
u32 dword_count)
{
u32 cmd;
u32 d;
cmd = save ? MI_STORE_REGISTER_MEM : MI_LOAD_REGISTER_MEM;
cmd |= MI_SRM_LRM_GLOBAL_GTT;
if (GRAPHICS_VER(stream->perf->i915) >= 8)
cmd++;
for (d = 0; d < dword_count; d++) {
*cs++ = cmd;
*cs++ = i915_mmio_reg_offset(reg) + 4 * d;
*cs++ = i915_ggtt_offset(stream->noa_wait) + offset + 4 * d;
*cs++ = 0;
}
return cs;
}
static int alloc_noa_wait(struct i915_perf_stream *stream)
{
struct drm_i915_private *i915 = stream->perf->i915;
struct intel_gt *gt = stream->engine->gt;
struct drm_i915_gem_object *bo;
struct i915_vma *vma;
const u64 delay_ticks = 0xffffffffffffffff -
intel_gt_ns_to_clock_interval(to_gt(stream->perf->i915),
atomic64_read(&stream->perf->noa_programming_delay));
const u32 base = stream->engine->mmio_base;
#define CS_GPR(x) GEN8_RING_CS_GPR(base, x)
u32 *batch, *ts0, *cs, *jump;
struct i915_gem_ww_ctx ww;
int ret, i;
enum {
START_TS,
NOW_TS,
DELTA_TS,
JUMP_PREDICATE,
DELTA_TARGET,
N_CS_GPR
};
i915_reg_t mi_predicate_result = HAS_MI_SET_PREDICATE(i915) ?
MI_PREDICATE_RESULT_2_ENGINE(base) :
MI_PREDICATE_RESULT_1(RENDER_RING_BASE);
/*
* gt->scratch was being used to save/restore the GPR registers, but on
* MTL the scratch uses stolen lmem. An MI_SRM to this memory region
* causes an engine hang. Instead allocate an additional page here to
* save/restore GPR registers
*/
bo = i915_gem_object_create_internal(i915, 8192);
if (IS_ERR(bo)) {
drm_err(&i915->drm,
"Failed to allocate NOA wait batchbuffer\n");
return PTR_ERR(bo);
}
i915_gem_ww_ctx_init(&ww, true);
retry:
ret = i915_gem_object_lock(bo, &ww);
if (ret)
goto out_ww;
/*
* We pin in GGTT because we jump into this buffer now because
* multiple OA config BOs will have a jump to this address and it
* needs to be fixed during the lifetime of the i915/perf stream.
*/
vma = i915_vma_instance(bo, >->ggtt->vm, NULL);
if (IS_ERR(vma)) {
ret = PTR_ERR(vma);
goto out_ww;
}
ret = i915_vma_pin_ww(vma, &ww, 0, 0, PIN_GLOBAL | PIN_HIGH);
if (ret)
goto out_ww;
batch = cs = i915_gem_object_pin_map(bo, I915_MAP_WB);
if (IS_ERR(batch)) {
ret = PTR_ERR(batch);
goto err_unpin;
}
stream->noa_wait = vma;
#define GPR_SAVE_OFFSET 4096
#define PREDICATE_SAVE_OFFSET 4160
/* Save registers. */
for (i = 0; i < N_CS_GPR; i++)
cs = save_restore_register(
stream, cs, true /* save */, CS_GPR(i),
GPR_SAVE_OFFSET + 8 * i, 2);
cs = save_restore_register(
stream, cs, true /* save */, mi_predicate_result,
PREDICATE_SAVE_OFFSET, 1);
/* First timestamp snapshot location. */
ts0 = cs;
/*
* Initial snapshot of the timestamp register to implement the wait.
* We work with 32b values, so clear out the top 32b bits of the
* register because the ALU works 64bits.
*/
*cs++ = MI_LOAD_REGISTER_IMM(1);
*cs++ = i915_mmio_reg_offset(CS_GPR(START_TS)) + 4;
*cs++ = 0;
*cs++ = MI_LOAD_REGISTER_REG | (3 - 2);
*cs++ = i915_mmio_reg_offset(RING_TIMESTAMP(base));
*cs++ = i915_mmio_reg_offset(CS_GPR(START_TS));
/*
* This is the location we're going to jump back into until the
* required amount of time has passed.
*/
jump = cs;
/*
* Take another snapshot of the timestamp register. Take care to clear
* up the top 32bits of CS_GPR(1) as we're using it for other
* operations below.
*/
*cs++ = MI_LOAD_REGISTER_IMM(1);
*cs++ = i915_mmio_reg_offset(CS_GPR(NOW_TS)) + 4;
*cs++ = 0;
*cs++ = MI_LOAD_REGISTER_REG | (3 - 2);
*cs++ = i915_mmio_reg_offset(RING_TIMESTAMP(base));
*cs++ = i915_mmio_reg_offset(CS_GPR(NOW_TS));
/*
* Do a diff between the 2 timestamps and store the result back into
* CS_GPR(1).
*/
*cs++ = MI_MATH(5);
*cs++ = MI_MATH_LOAD(MI_MATH_REG_SRCA, MI_MATH_REG(NOW_TS));
*cs++ = MI_MATH_LOAD(MI_MATH_REG_SRCB, MI_MATH_REG(START_TS));
*cs++ = MI_MATH_SUB;
*cs++ = MI_MATH_STORE(MI_MATH_REG(DELTA_TS), MI_MATH_REG_ACCU);
*cs++ = MI_MATH_STORE(MI_MATH_REG(JUMP_PREDICATE), MI_MATH_REG_CF);
/*
* Transfer the carry flag (set to 1 if ts1 < ts0, meaning the
* timestamp have rolled over the 32bits) into the predicate register
* to be used for the predicated jump.
*/
*cs++ = MI_LOAD_REGISTER_REG | (3 - 2);
*cs++ = i915_mmio_reg_offset(CS_GPR(JUMP_PREDICATE));
*cs++ = i915_mmio_reg_offset(mi_predicate_result);
if (HAS_MI_SET_PREDICATE(i915))
*cs++ = MI_SET_PREDICATE | 1;
/* Restart from the beginning if we had timestamps roll over. */
*cs++ = (GRAPHICS_VER(i915) < 8 ?
MI_BATCH_BUFFER_START :
MI_BATCH_BUFFER_START_GEN8) |
MI_BATCH_PREDICATE;
*cs++ = i915_ggtt_offset(vma) + (ts0 - batch) * 4;
*cs++ = 0;
if (HAS_MI_SET_PREDICATE(i915))
*cs++ = MI_SET_PREDICATE;
/*
* Now add the diff between to previous timestamps and add it to :
* (((1 * << 64) - 1) - delay_ns)
*
* When the Carry Flag contains 1 this means the elapsed time is
* longer than the expected delay, and we can exit the wait loop.
*/
*cs++ = MI_LOAD_REGISTER_IMM(2);
*cs++ = i915_mmio_reg_offset(CS_GPR(DELTA_TARGET));
*cs++ = lower_32_bits(delay_ticks);
*cs++ = i915_mmio_reg_offset(CS_GPR(DELTA_TARGET)) + 4;
*cs++ = upper_32_bits(delay_ticks);
*cs++ = MI_MATH(4);
*cs++ = MI_MATH_LOAD(MI_MATH_REG_SRCA, MI_MATH_REG(DELTA_TS));
*cs++ = MI_MATH_LOAD(MI_MATH_REG_SRCB, MI_MATH_REG(DELTA_TARGET));
*cs++ = MI_MATH_ADD;
*cs++ = MI_MATH_STOREINV(MI_MATH_REG(JUMP_PREDICATE), MI_MATH_REG_CF);
*cs++ = MI_ARB_CHECK;
/*
* Transfer the result into the predicate register to be used for the
* predicated jump.
*/
*cs++ = MI_LOAD_REGISTER_REG | (3 - 2);
*cs++ = i915_mmio_reg_offset(CS_GPR(JUMP_PREDICATE));
*cs++ = i915_mmio_reg_offset(mi_predicate_result);
if (HAS_MI_SET_PREDICATE(i915))
*cs++ = MI_SET_PREDICATE | 1;
/* Predicate the jump. */
*cs++ = (GRAPHICS_VER(i915) < 8 ?
MI_BATCH_BUFFER_START :
MI_BATCH_BUFFER_START_GEN8) |
MI_BATCH_PREDICATE;
*cs++ = i915_ggtt_offset(vma) + (jump - batch) * 4;
*cs++ = 0;
if (HAS_MI_SET_PREDICATE(i915))
*cs++ = MI_SET_PREDICATE;
/* Restore registers. */
for (i = 0; i < N_CS_GPR; i++)
cs = save_restore_register(
stream, cs, false /* restore */, CS_GPR(i),
GPR_SAVE_OFFSET + 8 * i, 2);
cs = save_restore_register(
stream, cs, false /* restore */, mi_predicate_result,
PREDICATE_SAVE_OFFSET, 1);
/* And return to the ring. */
*cs++ = MI_BATCH_BUFFER_END;
GEM_BUG_ON(cs - batch > PAGE_SIZE / sizeof(*batch));
i915_gem_object_flush_map(bo);
__i915_gem_object_release_map(bo);
goto out_ww;
err_unpin:
i915_vma_unpin_and_release(&vma, 0);
out_ww:
if (ret == -EDEADLK) {
ret = i915_gem_ww_ctx_backoff(&ww);
if (!ret)
goto retry;
}
i915_gem_ww_ctx_fini(&ww);
if (ret)
i915_gem_object_put(bo);
return ret;
}
static u32 *write_cs_mi_lri(u32 *cs,
const struct i915_oa_reg *reg_data,
u32 n_regs)
{
u32 i;
for (i = 0; i < n_regs; i++) {
if ((i % MI_LOAD_REGISTER_IMM_MAX_REGS) == 0) {
u32 n_lri = min_t(u32,
n_regs - i,
MI_LOAD_REGISTER_IMM_MAX_REGS);
*cs++ = MI_LOAD_REGISTER_IMM(n_lri);
}
*cs++ = i915_mmio_reg_offset(reg_data[i].addr);
*cs++ = reg_data[i].value;
}
return cs;
}
static int num_lri_dwords(int num_regs)
{
int count = 0;
if (num_regs > 0) {
count += DIV_ROUND_UP(num_regs, MI_LOAD_REGISTER_IMM_MAX_REGS);
count += num_regs * 2;
}
return count;
}
static struct i915_oa_config_bo *
alloc_oa_config_buffer(struct i915_perf_stream *stream,
struct i915_oa_config *oa_config)
{
struct drm_i915_gem_object *obj;
struct i915_oa_config_bo *oa_bo;
struct i915_gem_ww_ctx ww;
size_t config_length = 0;
u32 *cs;
int err;
oa_bo = kzalloc(sizeof(*oa_bo), GFP_KERNEL);
if (!oa_bo)
return ERR_PTR(-ENOMEM);
config_length += num_lri_dwords(oa_config->mux_regs_len);
config_length += num_lri_dwords(oa_config->b_counter_regs_len);
config_length += num_lri_dwords(oa_config->flex_regs_len);
config_length += 3; /* MI_BATCH_BUFFER_START */
config_length = ALIGN(sizeof(u32) * config_length, I915_GTT_PAGE_SIZE);
obj = i915_gem_object_create_shmem(stream->perf->i915, config_length);
if (IS_ERR(obj)) {
err = PTR_ERR(obj);
goto err_free;
}
i915_gem_ww_ctx_init(&ww, true);
retry:
err = i915_gem_object_lock(obj, &ww);
if (err)
goto out_ww;
cs = i915_gem_object_pin_map(obj, I915_MAP_WB);
if (IS_ERR(cs)) {
err = PTR_ERR(cs);
goto out_ww;
}
cs = write_cs_mi_lri(cs,
oa_config->mux_regs,
oa_config->mux_regs_len);
cs = write_cs_mi_lri(cs,
oa_config->b_counter_regs,
oa_config->b_counter_regs_len);
cs = write_cs_mi_lri(cs,
oa_config->flex_regs,
oa_config->flex_regs_len);
/* Jump into the active wait. */
*cs++ = (GRAPHICS_VER(stream->perf->i915) < 8 ?
MI_BATCH_BUFFER_START :
MI_BATCH_BUFFER_START_GEN8);
*cs++ = i915_ggtt_offset(stream->noa_wait);
*cs++ = 0;
i915_gem_object_flush_map(obj);
__i915_gem_object_release_map(obj);
oa_bo->vma = i915_vma_instance(obj,
&stream->engine->gt->ggtt->vm,
NULL);
if (IS_ERR(oa_bo->vma)) {
err = PTR_ERR(oa_bo->vma);
goto out_ww;
}
oa_bo->oa_config = i915_oa_config_get(oa_config);
llist_add(&oa_bo->node, &stream->oa_config_bos);
out_ww:
if (err == -EDEADLK) {
err = i915_gem_ww_ctx_backoff(&ww);
if (!err)
goto retry;
}
i915_gem_ww_ctx_fini(&ww);
if (err)
i915_gem_object_put(obj);
err_free:
if (err) {
kfree(oa_bo);
return ERR_PTR(err);
}
return oa_bo;
}
static struct i915_vma *
get_oa_vma(struct i915_perf_stream *stream, struct i915_oa_config *oa_config)
{
struct i915_oa_config_bo *oa_bo;
/*
* Look for the buffer in the already allocated BOs attached
* to the stream.
*/
llist_for_each_entry(oa_bo, stream->oa_config_bos.first, node) {
if (oa_bo->oa_config == oa_config &&
memcmp(oa_bo->oa_config->uuid,
oa_config->uuid,
sizeof(oa_config->uuid)) == 0)
goto out;
}
oa_bo = alloc_oa_config_buffer(stream, oa_config);
if (IS_ERR(oa_bo))
return ERR_CAST(oa_bo);
out:
return i915_vma_get(oa_bo->vma);
}
static int
emit_oa_config(struct i915_perf_stream *stream,
struct i915_oa_config *oa_config,
struct intel_context *ce,
struct i915_active *active)
{
struct i915_request *rq;
struct i915_vma *vma;
struct i915_gem_ww_ctx ww;
int err;
vma = get_oa_vma(stream, oa_config);
if (IS_ERR(vma))
return PTR_ERR(vma);
i915_gem_ww_ctx_init(&ww, true);
retry:
err = i915_gem_object_lock(vma->obj, &ww);
if (err)
goto err;
err = i915_vma_pin_ww(vma, &ww, 0, 0, PIN_GLOBAL | PIN_HIGH);
if (err)
goto err;
intel_engine_pm_get(ce->engine);
rq = i915_request_create(ce);
intel_engine_pm_put(ce->engine);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
goto err_vma_unpin;
}
if (!IS_ERR_OR_NULL(active)) {
/* After all individual context modifications */
err = i915_request_await_active(rq, active,
I915_ACTIVE_AWAIT_ACTIVE);
if (err)
goto err_add_request;
err = i915_active_add_request(active, rq);
if (err)
goto err_add_request;
}
err = i915_vma_move_to_active(vma, rq, 0);
if (err)
goto err_add_request;
err = rq->engine->emit_bb_start(rq,
i915_vma_offset(vma), 0,
I915_DISPATCH_SECURE);
if (err)
goto err_add_request;
err_add_request:
i915_request_add(rq);
err_vma_unpin:
i915_vma_unpin(vma);
err:
if (err == -EDEADLK) {
err = i915_gem_ww_ctx_backoff(&ww);
if (!err)
goto retry;
}
i915_gem_ww_ctx_fini(&ww);
i915_vma_put(vma);
return err;
}
static struct intel_context *oa_context(struct i915_perf_stream *stream)
{
return stream->pinned_ctx ?: stream->engine->kernel_context;
}
static int
hsw_enable_metric_set(struct i915_perf_stream *stream,
struct i915_active *active)
{
struct intel_uncore *uncore = stream->uncore;
/*
* PRM:
*
* OA unit is using “crclk” for its functionality. When trunk
* level clock gating takes place, OA clock would be gated,
* unable to count the events from non-render clock domain.
* Render clock gating must be disabled when OA is enabled to
* count the events from non-render domain. Unit level clock
* gating for RCS should also be disabled.
*/
intel_uncore_rmw(uncore, GEN7_MISCCPCTL,
GEN7_DOP_CLOCK_GATE_ENABLE, 0);
intel_uncore_rmw(uncore, GEN6_UCGCTL1,
0, GEN6_CSUNIT_CLOCK_GATE_DISABLE);
return emit_oa_config(stream,
stream->oa_config, oa_context(stream),
active);
}
static void hsw_disable_metric_set(struct i915_perf_stream *stream)
{
struct intel_uncore *uncore = stream->uncore;
intel_uncore_rmw(uncore, GEN6_UCGCTL1,
GEN6_CSUNIT_CLOCK_GATE_DISABLE, 0);
intel_uncore_rmw(uncore, GEN7_MISCCPCTL,
0, GEN7_DOP_CLOCK_GATE_ENABLE);
intel_uncore_rmw(uncore, GDT_CHICKEN_BITS, GT_NOA_ENABLE, 0);
}
static u32 oa_config_flex_reg(const struct i915_oa_config *oa_config,
i915_reg_t reg)
{
u32 mmio = i915_mmio_reg_offset(reg);
int i;
/*
* This arbitrary default will select the 'EU FPU0 Pipeline
* Active' event. In the future it's anticipated that there
* will be an explicit 'No Event' we can select, but not yet...
*/
if (!oa_config)
return 0;
for (i = 0; i < oa_config->flex_regs_len; i++) {
if (i915_mmio_reg_offset(oa_config->flex_regs[i].addr) == mmio)
return oa_config->flex_regs[i].value;
}
return 0;
}
/*
* NB: It must always remain pointer safe to run this even if the OA unit
* has been disabled.
*
* It's fine to put out-of-date values into these per-context registers
* in the case that the OA unit has been disabled.
*/
static void
gen8_update_reg_state_unlocked(const struct intel_context *ce,
const struct i915_perf_stream *stream)
{
u32 ctx_oactxctrl = stream->perf->ctx_oactxctrl_offset;
u32 ctx_flexeu0 = stream->perf->ctx_flexeu0_offset;
/* The MMIO offsets for Flex EU registers aren't contiguous */
static const i915_reg_t flex_regs[] = {
EU_PERF_CNTL0,
EU_PERF_CNTL1,
EU_PERF_CNTL2,
EU_PERF_CNTL3,
EU_PERF_CNTL4,
EU_PERF_CNTL5,
EU_PERF_CNTL6,
};
u32 *reg_state = ce->lrc_reg_state;
int i;
reg_state[ctx_oactxctrl + 1] =
(stream->period_exponent << GEN8_OA_TIMER_PERIOD_SHIFT) |
(stream->periodic ? GEN8_OA_TIMER_ENABLE : 0) |
GEN8_OA_COUNTER_RESUME;
for (i = 0; i < ARRAY_SIZE(flex_regs); i++)
reg_state[ctx_flexeu0 + i * 2 + 1] =
oa_config_flex_reg(stream->oa_config, flex_regs[i]);
}
struct flex {
i915_reg_t reg;
u32 offset;
u32 value;
};
static int
gen8_store_flex(struct i915_request *rq,
struct intel_context *ce,
const struct flex *flex, unsigned int count)
{
u32 offset;
u32 *cs;
cs = intel_ring_begin(rq, 4 * count);
if (IS_ERR(cs))
return PTR_ERR(cs);
offset = i915_ggtt_offset(ce->state) + LRC_STATE_OFFSET;
do {
*cs++ = MI_STORE_DWORD_IMM_GEN4 | MI_USE_GGTT;
*cs++ = offset + flex->offset * sizeof(u32);
*cs++ = 0;
*cs++ = flex->value;
} while (flex++, --count);
intel_ring_advance(rq, cs);
return 0;
}
static int
gen8_load_flex(struct i915_request *rq,
struct intel_context *ce,
const struct flex *flex, unsigned int count)
{
u32 *cs;
GEM_BUG_ON(!count || count > 63);
cs = intel_ring_begin(rq, 2 * count + 2);
if (IS_ERR(cs))
return PTR_ERR(cs);
*cs++ = MI_LOAD_REGISTER_IMM(count);
do {
*cs++ = i915_mmio_reg_offset(flex->reg);
*cs++ = flex->value;
} while (flex++, --count);
*cs++ = MI_NOOP;
intel_ring_advance(rq, cs);
return 0;
}
static int gen8_modify_context(struct intel_context *ce,
const struct flex *flex, unsigned int count)
{
struct i915_request *rq;
int err;
rq = intel_engine_create_kernel_request(ce->engine);
if (IS_ERR(rq))
return PTR_ERR(rq);
/* Serialise with the remote context */
err = intel_context_prepare_remote_request(ce, rq);
if (err == 0)
err = gen8_store_flex(rq, ce, flex, count);
i915_request_add(rq);
return err;
}
static int
gen8_modify_self(struct intel_context *ce,
const struct flex *flex, unsigned int count,
struct i915_active *active)
{
struct i915_request *rq;
int err;
intel_engine_pm_get(ce->engine);
rq = i915_request_create(ce);
intel_engine_pm_put(ce->engine);
if (IS_ERR(rq))
return PTR_ERR(rq);
if (!IS_ERR_OR_NULL(active)) {
err = i915_active_add_request(active, rq);
if (err)
goto err_add_request;
}
err = gen8_load_flex(rq, ce, flex, count);
if (err)
goto err_add_request;
err_add_request:
i915_request_add(rq);
return err;
}
static int gen8_configure_context(struct i915_perf_stream *stream,
struct i915_gem_context *ctx,
struct flex *flex, unsigned int count)
{
struct i915_gem_engines_iter it;
struct intel_context *ce;
int err = 0;
for_each_gem_engine(ce, i915_gem_context_lock_engines(ctx), it) {
GEM_BUG_ON(ce == ce->engine->kernel_context);
if (ce->engine->class != RENDER_CLASS)
continue;
/* Otherwise OA settings will be set upon first use */
if (!intel_context_pin_if_active(ce))
continue;
flex->value = intel_sseu_make_rpcs(ce->engine->gt, &ce->sseu);
err = gen8_modify_context(ce, flex, count);
intel_context_unpin(ce);
if (err)
break;
}
i915_gem_context_unlock_engines(ctx);
return err;
}
static int gen12_configure_oar_context(struct i915_perf_stream *stream,
struct i915_active *active)
{
int err;
struct intel_context *ce = stream->pinned_ctx;
u32 format = stream->oa_buffer.format->format;
u32 offset = stream->perf->ctx_oactxctrl_offset;
struct flex regs_context[] = {
{
GEN8_OACTXCONTROL,
offset + 1,
active ? GEN8_OA_COUNTER_RESUME : 0,
},
};
/* Offsets in regs_lri are not used since this configuration is only
* applied using LRI. Initialize the correct offsets for posterity.
*/
#define GEN12_OAR_OACONTROL_OFFSET 0x5B0
struct flex regs_lri[] = {
{
GEN12_OAR_OACONTROL,
GEN12_OAR_OACONTROL_OFFSET + 1,
(format << GEN12_OAR_OACONTROL_COUNTER_FORMAT_SHIFT) |
(active ? GEN12_OAR_OACONTROL_COUNTER_ENABLE : 0)
},
{
RING_CONTEXT_CONTROL(ce->engine->mmio_base),
CTX_CONTEXT_CONTROL,
_MASKED_FIELD(GEN12_CTX_CTRL_OAR_CONTEXT_ENABLE,
active ?
GEN12_CTX_CTRL_OAR_CONTEXT_ENABLE :
0)
},
};
/* Modify the context image of pinned context with regs_context */
err = intel_context_lock_pinned(ce);
if (err)
return err;
err = gen8_modify_context(ce, regs_context,
ARRAY_SIZE(regs_context));
intel_context_unlock_pinned(ce);
if (err)
return err;
/* Apply regs_lri using LRI with pinned context */
return gen8_modify_self(ce, regs_lri, ARRAY_SIZE(regs_lri), active);
}
/*
* Manages updating the per-context aspects of the OA stream
* configuration across all contexts.
*
* The awkward consideration here is that OACTXCONTROL controls the
* exponent for periodic sampling which is primarily used for system
* wide profiling where we'd like a consistent sampling period even in
* the face of context switches.
*
* Our approach of updating the register state context (as opposed to
* say using a workaround batch buffer) ensures that the hardware
* won't automatically reload an out-of-date timer exponent even
* transiently before a WA BB could be parsed.
*
* This function needs to:
* - Ensure the currently running context's per-context OA state is
* updated
* - Ensure that all existing contexts will have the correct per-context
* OA state if they are scheduled for use.
* - Ensure any new contexts will be initialized with the correct
* per-context OA state.
*
* Note: it's only the RCS/Render context that has any OA state.
* Note: the first flex register passed must always be R_PWR_CLK_STATE
*/
static int
oa_configure_all_contexts(struct i915_perf_stream *stream,
struct flex *regs,
size_t num_regs,
struct i915_active *active)
{
struct drm_i915_private *i915 = stream->perf->i915;
struct intel_engine_cs *engine;
struct intel_gt *gt = stream->engine->gt;
struct i915_gem_context *ctx, *cn;
int err;
lockdep_assert_held(>->perf.lock);
/*
* The OA register config is setup through the context image. This image
* might be written to by the GPU on context switch (in particular on
* lite-restore). This means we can't safely update a context's image,
* if this context is scheduled/submitted to run on the GPU.
*
* We could emit the OA register config through the batch buffer but
* this might leave small interval of time where the OA unit is
* configured at an invalid sampling period.
*
* Note that since we emit all requests from a single ring, there
* is still an implicit global barrier here that may cause a high
* priority context to wait for an otherwise independent low priority
* context. Contexts idle at the time of reconfiguration are not
* trapped behind the barrier.
*/
spin_lock(&i915->gem.contexts.lock);
list_for_each_entry_safe(ctx, cn, &i915->gem.contexts.list, link) {
if (!kref_get_unless_zero(&ctx->ref))
continue;
spin_unlock(&i915->gem.contexts.lock);
err = gen8_configure_context(stream, ctx, regs, num_regs);
if (err) {
i915_gem_context_put(ctx);
return err;
}
spin_lock(&i915->gem.contexts.lock);
list_safe_reset_next(ctx, cn, link);
i915_gem_context_put(ctx);
}
spin_unlock(&i915->gem.contexts.lock);
/*
* After updating all other contexts, we need to modify ourselves.
* If we don't modify the kernel_context, we do not get events while
* idle.
*/
for_each_uabi_engine(engine, i915) {
struct intel_context *ce = engine->kernel_context;
if (engine->class != RENDER_CLASS)
continue;
regs[0].value = intel_sseu_make_rpcs(engine->gt, &ce->sseu);
err = gen8_modify_self(ce, regs, num_regs, active);
if (err)
return err;
}
return 0;
}
static int
gen12_configure_all_contexts(struct i915_perf_stream *stream,
const struct i915_oa_config *oa_config,
struct i915_active *active)
{
struct flex regs[] = {
{
GEN8_R_PWR_CLK_STATE(RENDER_RING_BASE),
CTX_R_PWR_CLK_STATE,
},
};
if (stream->engine->class != RENDER_CLASS)
return 0;
return oa_configure_all_contexts(stream,
regs, ARRAY_SIZE(regs),
active);
}
static int
lrc_configure_all_contexts(struct i915_perf_stream *stream,
const struct i915_oa_config *oa_config,
struct i915_active *active)
{
u32 ctx_oactxctrl = stream->perf->ctx_oactxctrl_offset;
/* The MMIO offsets for Flex EU registers aren't contiguous */
const u32 ctx_flexeu0 = stream->perf->ctx_flexeu0_offset;
#define ctx_flexeuN(N) (ctx_flexeu0 + 2 * (N) + 1)
struct flex regs[] = {
{
GEN8_R_PWR_CLK_STATE(RENDER_RING_BASE),
CTX_R_PWR_CLK_STATE,
},
{
GEN8_OACTXCONTROL,
ctx_oactxctrl + 1,
},
{ EU_PERF_CNTL0, ctx_flexeuN(0) },
{ EU_PERF_CNTL1, ctx_flexeuN(1) },
{ EU_PERF_CNTL2, ctx_flexeuN(2) },
{ EU_PERF_CNTL3, ctx_flexeuN(3) },
{ EU_PERF_CNTL4, ctx_flexeuN(4) },
{ EU_PERF_CNTL5, ctx_flexeuN(5) },
{ EU_PERF_CNTL6, ctx_flexeuN(6) },
};
#undef ctx_flexeuN
int i;
regs[1].value =
(stream->period_exponent << GEN8_OA_TIMER_PERIOD_SHIFT) |
(stream->periodic ? GEN8_OA_TIMER_ENABLE : 0) |
GEN8_OA_COUNTER_RESUME;
for (i = 2; i < ARRAY_SIZE(regs); i++)
regs[i].value = oa_config_flex_reg(oa_config, regs[i].reg);
return oa_configure_all_contexts(stream,
regs, ARRAY_SIZE(regs),
active);
}
static int
gen8_enable_metric_set(struct i915_perf_stream *stream,
struct i915_active *active)
{
struct intel_uncore *uncore = stream->uncore;
struct i915_oa_config *oa_config = stream->oa_config;
int ret;
/*
* We disable slice/unslice clock ratio change reports on SKL since
* they are too noisy. The HW generates a lot of redundant reports
* where the ratio hasn't really changed causing a lot of redundant
* work to processes and increasing the chances we'll hit buffer
* overruns.
*
* Although we don't currently use the 'disable overrun' OABUFFER
* feature it's worth noting that clock ratio reports have to be
* disabled before considering to use that feature since the HW doesn't
* correctly block these reports.
*
* Currently none of the high-level metrics we have depend on knowing
* this ratio to normalize.
*
* Note: This register is not power context saved and restored, but
* that's OK considering that we disable RC6 while the OA unit is
* enabled.
*
* The _INCLUDE_CLK_RATIO bit allows the slice/unslice frequency to
* be read back from automatically triggered reports, as part of the
* RPT_ID field.
*/
if (IS_GRAPHICS_VER(stream->perf->i915, 9, 11)) {
intel_uncore_write(uncore, GEN8_OA_DEBUG,
_MASKED_BIT_ENABLE(GEN9_OA_DEBUG_DISABLE_CLK_RATIO_REPORTS |
GEN9_OA_DEBUG_INCLUDE_CLK_RATIO));
}
/*
* Update all contexts prior writing the mux configurations as we need
* to make sure all slices/subslices are ON before writing to NOA
* registers.
*/
ret = lrc_configure_all_contexts(stream, oa_config, active);
if (ret)
return ret;
return emit_oa_config(stream,
stream->oa_config, oa_context(stream),
active);
}
static u32 oag_report_ctx_switches(const struct i915_perf_stream *stream)
{
return _MASKED_FIELD(GEN12_OAG_OA_DEBUG_DISABLE_CTX_SWITCH_REPORTS,
(stream->sample_flags & SAMPLE_OA_REPORT) ?
0 : GEN12_OAG_OA_DEBUG_DISABLE_CTX_SWITCH_REPORTS);
}
static int
gen12_enable_metric_set(struct i915_perf_stream *stream,
struct i915_active *active)
{
struct drm_i915_private *i915 = stream->perf->i915;
struct intel_uncore *uncore = stream->uncore;
struct i915_oa_config *oa_config = stream->oa_config;
bool periodic = stream->periodic;
u32 period_exponent = stream->period_exponent;
u32 sqcnt1;
int ret;
/*
* Wa_1508761755:xehpsdv, dg2
* EU NOA signals behave incorrectly if EU clock gating is enabled.
* Disable thread stall DOP gating and EU DOP gating.
*/
if (IS_XEHPSDV(i915) || IS_DG2(i915)) {
intel_gt_mcr_multicast_write(uncore->gt, GEN8_ROW_CHICKEN,
_MASKED_BIT_ENABLE(STALL_DOP_GATING_DISABLE));
intel_uncore_write(uncore, GEN7_ROW_CHICKEN2,
_MASKED_BIT_ENABLE(GEN12_DISABLE_DOP_GATING));
}
intel_uncore_write(uncore, __oa_regs(stream)->oa_debug,
/* Disable clk ratio reports, like previous Gens. */
_MASKED_BIT_ENABLE(GEN12_OAG_OA_DEBUG_DISABLE_CLK_RATIO_REPORTS |
GEN12_OAG_OA_DEBUG_INCLUDE_CLK_RATIO) |
/*
* If the user didn't require OA reports, instruct
* the hardware not to emit ctx switch reports.
*/
oag_report_ctx_switches(stream));
intel_uncore_write(uncore, __oa_regs(stream)->oa_ctx_ctrl, periodic ?
(GEN12_OAG_OAGLBCTXCTRL_COUNTER_RESUME |
GEN12_OAG_OAGLBCTXCTRL_TIMER_ENABLE |
(period_exponent << GEN12_OAG_OAGLBCTXCTRL_TIMER_PERIOD_SHIFT))
: 0);
/*
* Initialize Super Queue Internal Cnt Register
* Set PMON Enable in order to collect valid metrics.
* Enable byets per clock reporting in OA for XEHPSDV onward.
*/
sqcnt1 = GEN12_SQCNT1_PMON_ENABLE |
(HAS_OA_BPC_REPORTING(i915) ? GEN12_SQCNT1_OABPC : 0);
intel_uncore_rmw(uncore, GEN12_SQCNT1, 0, sqcnt1);
/*
* Update all contexts prior writing the mux configurations as we need
* to make sure all slices/subslices are ON before writing to NOA
* registers.
*/
ret = gen12_configure_all_contexts(stream, oa_config, active);
if (ret)
return ret;
/*
* For Gen12, performance counters are context
* saved/restored. Only enable it for the context that
* requested this.
*/
if (stream->ctx) {
ret = gen12_configure_oar_context(stream, active);
if (ret)
return ret;
}
return emit_oa_config(stream,
stream->oa_config, oa_context(stream),
active);
}
static void gen8_disable_metric_set(struct i915_perf_stream *stream)
{
struct intel_uncore *uncore = stream->uncore;
/* Reset all contexts' slices/subslices configurations. */
lrc_configure_all_contexts(stream, NULL, NULL);
intel_uncore_rmw(uncore, GDT_CHICKEN_BITS, GT_NOA_ENABLE, 0);
}
static void gen11_disable_metric_set(struct i915_perf_stream *stream)
{
struct intel_uncore *uncore = stream->uncore;
/* Reset all contexts' slices/subslices configurations. */
lrc_configure_all_contexts(stream, NULL, NULL);
/* Make sure we disable noa to save power. */
intel_uncore_rmw(uncore, RPM_CONFIG1, GEN10_GT_NOA_ENABLE, 0);
}
static void gen12_disable_metric_set(struct i915_perf_stream *stream)
{
struct intel_uncore *uncore = stream->uncore;
struct drm_i915_private *i915 = stream->perf->i915;
u32 sqcnt1;
/*
* Wa_1508761755:xehpsdv, dg2
* Enable thread stall DOP gating and EU DOP gating.
*/
if (IS_XEHPSDV(i915) || IS_DG2(i915)) {
intel_gt_mcr_multicast_write(uncore->gt, GEN8_ROW_CHICKEN,
_MASKED_BIT_DISABLE(STALL_DOP_GATING_DISABLE));
intel_uncore_write(uncore, GEN7_ROW_CHICKEN2,
_MASKED_BIT_DISABLE(GEN12_DISABLE_DOP_GATING));
}
/* Reset all contexts' slices/subslices configurations. */
gen12_configure_all_contexts(stream, NULL, NULL);
/* disable the context save/restore or OAR counters */
if (stream->ctx)
gen12_configure_oar_context(stream, NULL);
/* Make sure we disable noa to save power. */
intel_uncore_rmw(uncore, RPM_CONFIG1, GEN10_GT_NOA_ENABLE, 0);
sqcnt1 = GEN12_SQCNT1_PMON_ENABLE |
(HAS_OA_BPC_REPORTING(i915) ? GEN12_SQCNT1_OABPC : 0);
/* Reset PMON Enable to save power. */
intel_uncore_rmw(uncore, GEN12_SQCNT1, sqcnt1, 0);
}
static void gen7_oa_enable(struct i915_perf_stream *stream)
{
struct intel_uncore *uncore = stream->uncore;
struct i915_gem_context *ctx = stream->ctx;
u32 ctx_id = stream->specific_ctx_id;
bool periodic = stream->periodic;
u32 period_exponent = stream->period_exponent;
u32 report_format = stream->oa_buffer.format->format;
/*
* Reset buf pointers so we don't forward reports from before now.
*
* Think carefully if considering trying to avoid this, since it
* also ensures status flags and the buffer itself are cleared
* in error paths, and we have checks for invalid reports based
* on the assumption that certain fields are written to zeroed
* memory which this helps maintains.
*/
gen7_init_oa_buffer(stream);
intel_uncore_write(uncore, GEN7_OACONTROL,
(ctx_id & GEN7_OACONTROL_CTX_MASK) |
(period_exponent <<
GEN7_OACONTROL_TIMER_PERIOD_SHIFT) |
(periodic ? GEN7_OACONTROL_TIMER_ENABLE : 0) |
(report_format << GEN7_OACONTROL_FORMAT_SHIFT) |
(ctx ? GEN7_OACONTROL_PER_CTX_ENABLE : 0) |
GEN7_OACONTROL_ENABLE);
}
static void gen8_oa_enable(struct i915_perf_stream *stream)
{
struct intel_uncore *uncore = stream->uncore;
u32 report_format = stream->oa_buffer.format->format;
/*
* Reset buf pointers so we don't forward reports from before now.
*
* Think carefully if considering trying to avoid this, since it
* also ensures status flags and the buffer itself are cleared
* in error paths, and we have checks for invalid reports based
* on the assumption that certain fields are written to zeroed
* memory which this helps maintains.
*/
gen8_init_oa_buffer(stream);
/*
* Note: we don't rely on the hardware to perform single context
* filtering and instead filter on the cpu based on the context-id
* field of reports
*/
intel_uncore_write(uncore, GEN8_OACONTROL,
(report_format << GEN8_OA_REPORT_FORMAT_SHIFT) |
GEN8_OA_COUNTER_ENABLE);
}
static void gen12_oa_enable(struct i915_perf_stream *stream)
{
const struct i915_perf_regs *regs;
u32 val;
/*
* If we don't want OA reports from the OA buffer, then we don't even
* need to program the OAG unit.
*/
if (!(stream->sample_flags & SAMPLE_OA_REPORT))
return;
gen12_init_oa_buffer(stream);
regs = __oa_regs(stream);
val = (stream->oa_buffer.format->format << regs->oa_ctrl_counter_format_shift) |
GEN12_OAG_OACONTROL_OA_COUNTER_ENABLE;
intel_uncore_write(stream->uncore, regs->oa_ctrl, val);
}
/**
* i915_oa_stream_enable - handle `I915_PERF_IOCTL_ENABLE` for OA stream
* @stream: An i915 perf stream opened for OA metrics
*
* [Re]enables hardware periodic sampling according to the period configured
* when opening the stream. This also starts a hrtimer that will periodically
* check for data in the circular OA buffer for notifying userspace (e.g.
* during a read() or poll()).
*/
static void i915_oa_stream_enable(struct i915_perf_stream *stream)
{
stream->pollin = false;
stream->perf->ops.oa_enable(stream);
if (stream->sample_flags & SAMPLE_OA_REPORT)
hrtimer_start(&stream->poll_check_timer,
ns_to_ktime(stream->poll_oa_period),
HRTIMER_MODE_REL_PINNED);
}
static void gen7_oa_disable(struct i915_perf_stream *stream)
{
struct intel_uncore *uncore = stream->uncore;
intel_uncore_write(uncore, GEN7_OACONTROL, 0);
if (intel_wait_for_register(uncore,
GEN7_OACONTROL, GEN7_OACONTROL_ENABLE, 0,
50))
drm_err(&stream->perf->i915->drm,
"wait for OA to be disabled timed out\n");
}
static void gen8_oa_disable(struct i915_perf_stream *stream)
{
struct intel_uncore *uncore = stream->uncore;
intel_uncore_write(uncore, GEN8_OACONTROL, 0);
if (intel_wait_for_register(uncore,
GEN8_OACONTROL, GEN8_OA_COUNTER_ENABLE, 0,
50))
drm_err(&stream->perf->i915->drm,
"wait for OA to be disabled timed out\n");
}
static void gen12_oa_disable(struct i915_perf_stream *stream)
{
struct intel_uncore *uncore = stream->uncore;
intel_uncore_write(uncore, __oa_regs(stream)->oa_ctrl, 0);
if (intel_wait_for_register(uncore,
__oa_regs(stream)->oa_ctrl,
GEN12_OAG_OACONTROL_OA_COUNTER_ENABLE, 0,
50))
drm_err(&stream->perf->i915->drm,
"wait for OA to be disabled timed out\n");
intel_uncore_write(uncore, GEN12_OA_TLB_INV_CR, 1);
if (intel_wait_for_register(uncore,
GEN12_OA_TLB_INV_CR,
1, 0,
50))
drm_err(&stream->perf->i915->drm,
"wait for OA tlb invalidate timed out\n");
}
/**
* i915_oa_stream_disable - handle `I915_PERF_IOCTL_DISABLE` for OA stream
* @stream: An i915 perf stream opened for OA metrics
*
* Stops the OA unit from periodically writing counter reports into the
* circular OA buffer. This also stops the hrtimer that periodically checks for
* data in the circular OA buffer, for notifying userspace.
*/
static void i915_oa_stream_disable(struct i915_perf_stream *stream)
{
stream->perf->ops.oa_disable(stream);
if (stream->sample_flags & SAMPLE_OA_REPORT)
hrtimer_cancel(&stream->poll_check_timer);
}
static const struct i915_perf_stream_ops i915_oa_stream_ops = {
.destroy = i915_oa_stream_destroy,
.enable = i915_oa_stream_enable,
.disable = i915_oa_stream_disable,
.wait_unlocked = i915_oa_wait_unlocked,
.poll_wait = i915_oa_poll_wait,
.read = i915_oa_read,
};
static int i915_perf_stream_enable_sync(struct i915_perf_stream *stream)
{
struct i915_active *active;
int err;
active = i915_active_create();
if (!active)
return -ENOMEM;
err = stream->perf->ops.enable_metric_set(stream, active);
if (err == 0)
__i915_active_wait(active, TASK_UNINTERRUPTIBLE);
i915_active_put(active);
return err;
}
static void
get_default_sseu_config(struct intel_sseu *out_sseu,
struct intel_engine_cs *engine)
{
const struct sseu_dev_info *devinfo_sseu = &engine->gt->info.sseu;
*out_sseu = intel_sseu_from_device_info(devinfo_sseu);
if (GRAPHICS_VER(engine->i915) == 11) {
/*
* We only need subslice count so it doesn't matter which ones
* we select - just turn off low bits in the amount of half of
* all available subslices per slice.
*/
out_sseu->subslice_mask =
~(~0 << (hweight8(out_sseu->subslice_mask) / 2));
out_sseu->slice_mask = 0x1;
}
}
static int
get_sseu_config(struct intel_sseu *out_sseu,
struct intel_engine_cs *engine,
const struct drm_i915_gem_context_param_sseu *drm_sseu)
{
if (drm_sseu->engine.engine_class != engine->uabi_class ||
drm_sseu->engine.engine_instance != engine->uabi_instance)
return -EINVAL;
return i915_gem_user_to_context_sseu(engine->gt, drm_sseu, out_sseu);
}
/*
* OA timestamp frequency = CS timestamp frequency in most platforms. On some
* platforms OA unit ignores the CTC_SHIFT and the 2 timestamps differ. In such
* cases, return the adjusted CS timestamp frequency to the user.
*/
u32 i915_perf_oa_timestamp_frequency(struct drm_i915_private *i915)
{
/*
* Wa_18013179988:dg2
* Wa_14015846243:mtl
*/
if (IS_DG2(i915) || IS_METEORLAKE(i915)) {
intel_wakeref_t wakeref;
u32 reg, shift;
with_intel_runtime_pm(to_gt(i915)->uncore->rpm, wakeref)
reg = intel_uncore_read(to_gt(i915)->uncore, RPM_CONFIG0);
shift = REG_FIELD_GET(GEN10_RPM_CONFIG0_CTC_SHIFT_PARAMETER_MASK,
reg);
return to_gt(i915)->clock_frequency << (3 - shift);
}
return to_gt(i915)->clock_frequency;
}
/**
* i915_oa_stream_init - validate combined props for OA stream and init
* @stream: An i915 perf stream
* @param: The open parameters passed to `DRM_I915_PERF_OPEN`
* @props: The property state that configures stream (individually validated)
*
* While read_properties_unlocked() validates properties in isolation it
* doesn't ensure that the combination necessarily makes sense.
*
* At this point it has been determined that userspace wants a stream of
* OA metrics, but still we need to further validate the combined
* properties are OK.
*
* If the configuration makes sense then we can allocate memory for
* a circular OA buffer and apply the requested metric set configuration.
*
* Returns: zero on success or a negative error code.
*/
static int i915_oa_stream_init(struct i915_perf_stream *stream,
struct drm_i915_perf_open_param *param,
struct perf_open_properties *props)
{
struct drm_i915_private *i915 = stream->perf->i915;
struct i915_perf *perf = stream->perf;
struct i915_perf_group *g;
struct intel_gt *gt;
int ret;
if (!props->engine) {
drm_dbg(&stream->perf->i915->drm,
"OA engine not specified\n");
return -EINVAL;
}
gt = props->engine->gt;
g = props->engine->oa_group;
/*
* If the sysfs metrics/ directory wasn't registered for some
* reason then don't let userspace try their luck with config
* IDs
*/
if (!perf->metrics_kobj) {
drm_dbg(&stream->perf->i915->drm,
"OA metrics weren't advertised via sysfs\n");
return -EINVAL;
}
if (!(props->sample_flags & SAMPLE_OA_REPORT) &&
(GRAPHICS_VER(perf->i915) < 12 || !stream->ctx)) {
drm_dbg(&stream->perf->i915->drm,
"Only OA report sampling supported\n");
return -EINVAL;
}
if (!perf->ops.enable_metric_set) {
drm_dbg(&stream->perf->i915->drm,
"OA unit not supported\n");
return -ENODEV;
}
/*
* To avoid the complexity of having to accurately filter
* counter reports and marshal to the appropriate client
* we currently only allow exclusive access
*/
if (g->exclusive_stream) {
drm_dbg(&stream->perf->i915->drm,
"OA unit already in use\n");
return -EBUSY;
}
if (!props->oa_format) {
drm_dbg(&stream->perf->i915->drm,
"OA report format not specified\n");
return -EINVAL;
}
stream->engine = props->engine;
stream->uncore = stream->engine->gt->uncore;
stream->sample_size = sizeof(struct drm_i915_perf_record_header);
stream->oa_buffer.format = &perf->oa_formats[props->oa_format];
if (drm_WARN_ON(&i915->drm, stream->oa_buffer.format->size == 0))
return -EINVAL;
stream->sample_flags = props->sample_flags;
stream->sample_size += stream->oa_buffer.format->size;
stream->hold_preemption = props->hold_preemption;
stream->periodic = props->oa_periodic;
if (stream->periodic)
stream->period_exponent = props->oa_period_exponent;
if (stream->ctx) {
ret = oa_get_render_ctx_id(stream);
if (ret) {
drm_dbg(&stream->perf->i915->drm,
"Invalid context id to filter with\n");
return ret;
}
}
ret = alloc_noa_wait(stream);
if (ret) {
drm_dbg(&stream->perf->i915->drm,
"Unable to allocate NOA wait batch buffer\n");
goto err_noa_wait_alloc;
}
stream->oa_config = i915_perf_get_oa_config(perf, props->metrics_set);
if (!stream->oa_config) {
drm_dbg(&stream->perf->i915->drm,
"Invalid OA config id=%i\n", props->metrics_set);
ret = -EINVAL;
goto err_config;
}
/* PRM - observability performance counters:
*
* OACONTROL, performance counter enable, note:
*
* "When this bit is set, in order to have coherent counts,
* RC6 power state and trunk clock gating must be disabled.
* This can be achieved by programming MMIO registers as
* 0xA094=0 and 0xA090[31]=1"
*
* In our case we are expecting that taking pm + FORCEWAKE
* references will effectively disable RC6.
*/
intel_engine_pm_get(stream->engine);
intel_uncore_forcewake_get(stream->uncore, FORCEWAKE_ALL);
/*
* Wa_16011777198:dg2: GuC resets render as part of the Wa. This causes
* OA to lose the configuration state. Prevent this by overriding GUCRC
* mode.
*/
if (intel_uc_uses_guc_rc(>->uc) &&
(IS_DG2_GRAPHICS_STEP(gt->i915, G10, STEP_A0, STEP_C0) ||
IS_DG2_GRAPHICS_STEP(gt->i915, G11, STEP_A0, STEP_B0))) {
ret = intel_guc_slpc_override_gucrc_mode(>->uc.guc.slpc,
SLPC_GUCRC_MODE_GUCRC_NO_RC6);
if (ret) {
drm_dbg(&stream->perf->i915->drm,
"Unable to override gucrc mode\n");
goto err_gucrc;
}
stream->override_gucrc = true;
}
ret = alloc_oa_buffer(stream);
if (ret)
goto err_oa_buf_alloc;
stream->ops = &i915_oa_stream_ops;
stream->engine->gt->perf.sseu = props->sseu;
WRITE_ONCE(g->exclusive_stream, stream);
ret = i915_perf_stream_enable_sync(stream);
if (ret) {
drm_dbg(&stream->perf->i915->drm,
"Unable to enable metric set\n");
goto err_enable;
}
drm_dbg(&stream->perf->i915->drm,
"opening stream oa config uuid=%s\n",
stream->oa_config->uuid);
hrtimer_init(&stream->poll_check_timer,
CLOCK_MONOTONIC, HRTIMER_MODE_REL);
stream->poll_check_timer.function = oa_poll_check_timer_cb;
init_waitqueue_head(&stream->poll_wq);
spin_lock_init(&stream->oa_buffer.ptr_lock);
mutex_init(&stream->lock);
return 0;
err_enable:
WRITE_ONCE(g->exclusive_stream, NULL);
perf->ops.disable_metric_set(stream);
free_oa_buffer(stream);
err_oa_buf_alloc:
if (stream->override_gucrc)
intel_guc_slpc_unset_gucrc_mode(>->uc.guc.slpc);
err_gucrc:
intel_uncore_forcewake_put(stream->uncore, FORCEWAKE_ALL);
intel_engine_pm_put(stream->engine);
free_oa_configs(stream);
err_config:
free_noa_wait(stream);
err_noa_wait_alloc:
if (stream->ctx)
oa_put_render_ctx_id(stream);
return ret;
}
void i915_oa_init_reg_state(const struct intel_context *ce,
const struct intel_engine_cs *engine)
{
struct i915_perf_stream *stream;
if (engine->class != RENDER_CLASS)
return;
/* perf.exclusive_stream serialised by lrc_configure_all_contexts() */
stream = READ_ONCE(engine->oa_group->exclusive_stream);
if (stream && GRAPHICS_VER(stream->perf->i915) < 12)
gen8_update_reg_state_unlocked(ce, stream);
}
/**
* i915_perf_read - handles read() FOP for i915 perf stream FDs
* @file: An i915 perf stream file
* @buf: destination buffer given by userspace
* @count: the number of bytes userspace wants to read
* @ppos: (inout) file seek position (unused)
*
* The entry point for handling a read() on a stream file descriptor from
* userspace. Most of the work is left to the i915_perf_read_locked() and
* &i915_perf_stream_ops->read but to save having stream implementations (of
* which we might have multiple later) we handle blocking read here.
*
* We can also consistently treat trying to read from a disabled stream
* as an IO error so implementations can assume the stream is enabled
* while reading.
*
* Returns: The number of bytes copied or a negative error code on failure.
*/
static ssize_t i915_perf_read(struct file *file,
char __user *buf,
size_t count,
loff_t *ppos)
{
struct i915_perf_stream *stream = file->private_data;
size_t offset = 0;
int ret;
/* To ensure it's handled consistently we simply treat all reads of a
* disabled stream as an error. In particular it might otherwise lead
* to a deadlock for blocking file descriptors...
*/
if (!stream->enabled || !(stream->sample_flags & SAMPLE_OA_REPORT))
return -EIO;
if (!(file->f_flags & O_NONBLOCK)) {
/* There's the small chance of false positives from
* stream->ops->wait_unlocked.
*
* E.g. with single context filtering since we only wait until
* oabuffer has >= 1 report we don't immediately know whether
* any reports really belong to the current context
*/
do {
ret = stream->ops->wait_unlocked(stream);
if (ret)
return ret;
mutex_lock(&stream->lock);
ret = stream->ops->read(stream, buf, count, &offset);
mutex_unlock(&stream->lock);
} while (!offset && !ret);
} else {
mutex_lock(&stream->lock);
ret = stream->ops->read(stream, buf, count, &offset);
mutex_unlock(&stream->lock);
}
/* We allow the poll checking to sometimes report false positive EPOLLIN
* events where we might actually report EAGAIN on read() if there's
* not really any data available. In this situation though we don't
* want to enter a busy loop between poll() reporting a EPOLLIN event
* and read() returning -EAGAIN. Clearing the oa.pollin state here
* effectively ensures we back off until the next hrtimer callback
* before reporting another EPOLLIN event.
* The exception to this is if ops->read() returned -ENOSPC which means
* that more OA data is available than could fit in the user provided
* buffer. In this case we want the next poll() call to not block.
*/
if (ret != -ENOSPC)
stream->pollin = false;
/* Possible values for ret are 0, -EFAULT, -ENOSPC, -EIO, ... */
return offset ?: (ret ?: -EAGAIN);
}
static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer)
{
struct i915_perf_stream *stream =
container_of(hrtimer, typeof(*stream), poll_check_timer);
if (oa_buffer_check_unlocked(stream)) {
stream->pollin = true;
wake_up(&stream->poll_wq);
}
hrtimer_forward_now(hrtimer,
ns_to_ktime(stream->poll_oa_period));
return HRTIMER_RESTART;
}
/**
* i915_perf_poll_locked - poll_wait() with a suitable wait queue for stream
* @stream: An i915 perf stream
* @file: An i915 perf stream file
* @wait: poll() state table
*
* For handling userspace polling on an i915 perf stream, this calls through to
* &i915_perf_stream_ops->poll_wait to call poll_wait() with a wait queue that
* will be woken for new stream data.
*
* Returns: any poll events that are ready without sleeping
*/
static __poll_t i915_perf_poll_locked(struct i915_perf_stream *stream,
struct file *file,
poll_table *wait)
{
__poll_t events = 0;
stream->ops->poll_wait(stream, file, wait);
/* Note: we don't explicitly check whether there's something to read
* here since this path may be very hot depending on what else
* userspace is polling, or on the timeout in use. We rely solely on
* the hrtimer/oa_poll_check_timer_cb to notify us when there are
* samples to read.
*/
if (stream->pollin)
events |= EPOLLIN;
return events;
}
/**
* i915_perf_poll - call poll_wait() with a suitable wait queue for stream
* @file: An i915 perf stream file
* @wait: poll() state table
*
* For handling userspace polling on an i915 perf stream, this ensures
* poll_wait() gets called with a wait queue that will be woken for new stream
* data.
*
* Note: Implementation deferred to i915_perf_poll_locked()
*
* Returns: any poll events that are ready without sleeping
*/
static __poll_t i915_perf_poll(struct file *file, poll_table *wait)
{
struct i915_perf_stream *stream = file->private_data;
__poll_t ret;
mutex_lock(&stream->lock);
ret = i915_perf_poll_locked(stream, file, wait);
mutex_unlock(&stream->lock);
return ret;
}
/**
* i915_perf_enable_locked - handle `I915_PERF_IOCTL_ENABLE` ioctl
* @stream: A disabled i915 perf stream
*
* [Re]enables the associated capture of data for this stream.
*
* If a stream was previously enabled then there's currently no intention
* to provide userspace any guarantee about the preservation of previously
* buffered data.
*/
static void i915_perf_enable_locked(struct i915_perf_stream *stream)
{
if (stream->enabled)
return;
/* Allow stream->ops->enable() to refer to this */
stream->enabled = true;
if (stream->ops->enable)
stream->ops->enable(stream);
if (stream->hold_preemption)
intel_context_set_nopreempt(stream->pinned_ctx);
}
/**
* i915_perf_disable_locked - handle `I915_PERF_IOCTL_DISABLE` ioctl
* @stream: An enabled i915 perf stream
*
* Disables the associated capture of data for this stream.
*
* The intention is that disabling an re-enabling a stream will ideally be
* cheaper than destroying and re-opening a stream with the same configuration,
* though there are no formal guarantees about what state or buffered data
* must be retained between disabling and re-enabling a stream.
*
* Note: while a stream is disabled it's considered an error for userspace
* to attempt to read from the stream (-EIO).
*/
static void i915_perf_disable_locked(struct i915_perf_stream *stream)
{
if (!stream->enabled)
return;
/* Allow stream->ops->disable() to refer to this */
stream->enabled = false;
if (stream->hold_preemption)
intel_context_clear_nopreempt(stream->pinned_ctx);
if (stream->ops->disable)
stream->ops->disable(stream);
}
static long i915_perf_config_locked(struct i915_perf_stream *stream,
unsigned long metrics_set)
{
struct i915_oa_config *config;
long ret = stream->oa_config->id;
config = i915_perf_get_oa_config(stream->perf, metrics_set);
if (!config)
return -EINVAL;
if (config != stream->oa_config) {
int err;
/*
* If OA is bound to a specific context, emit the
* reconfiguration inline from that context. The update
* will then be ordered with respect to submission on that
* context.
*
* When set globally, we use a low priority kernel context,
* so it will effectively take effect when idle.
*/
err = emit_oa_config(stream, config, oa_context(stream), NULL);
if (!err)
config = xchg(&stream->oa_config, config);
else
ret = err;
}
i915_oa_config_put(config);
return ret;
}
/**
* i915_perf_ioctl_locked - support ioctl() usage with i915 perf stream FDs
* @stream: An i915 perf stream
* @cmd: the ioctl request
* @arg: the ioctl data
*
* Returns: zero on success or a negative error code. Returns -EINVAL for
* an unknown ioctl request.
*/
static long i915_perf_ioctl_locked(struct i915_perf_stream *stream,
unsigned int cmd,
unsigned long arg)
{
switch (cmd) {
case I915_PERF_IOCTL_ENABLE:
i915_perf_enable_locked(stream);
return 0;
case I915_PERF_IOCTL_DISABLE:
i915_perf_disable_locked(stream);
return 0;
case I915_PERF_IOCTL_CONFIG:
return i915_perf_config_locked(stream, arg);
}
return -EINVAL;
}
/**
* i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
* @file: An i915 perf stream file
* @cmd: the ioctl request
* @arg: the ioctl data
*
* Implementation deferred to i915_perf_ioctl_locked().
*
* Returns: zero on success or a negative error code. Returns -EINVAL for
* an unknown ioctl request.
*/
static long i915_perf_ioctl(struct file *file,
unsigned int cmd,
unsigned long arg)
{
struct i915_perf_stream *stream = file->private_data;
long ret;
mutex_lock(&stream->lock);
ret = i915_perf_ioctl_locked(stream, cmd, arg);
mutex_unlock(&stream->lock);
return ret;
}
/**
* i915_perf_destroy_locked - destroy an i915 perf stream
* @stream: An i915 perf stream
*
* Frees all resources associated with the given i915 perf @stream, disabling
* any associated data capture in the process.
*
* Note: The >->perf.lock mutex has been taken to serialize
* with any non-file-operation driver hooks.
*/
static void i915_perf_destroy_locked(struct i915_perf_stream *stream)
{
if (stream->enabled)
i915_perf_disable_locked(stream);
if (stream->ops->destroy)
stream->ops->destroy(stream);
if (stream->ctx)
i915_gem_context_put(stream->ctx);
kfree(stream);
}
/**
* i915_perf_release - handles userspace close() of a stream file
* @inode: anonymous inode associated with file
* @file: An i915 perf stream file
*
* Cleans up any resources associated with an open i915 perf stream file.
*
* NB: close() can't really fail from the userspace point of view.
*
* Returns: zero on success or a negative error code.
*/
static int i915_perf_release(struct inode *inode, struct file *file)
{
struct i915_perf_stream *stream = file->private_data;
struct i915_perf *perf = stream->perf;
struct intel_gt *gt = stream->engine->gt;
/*
* Within this call, we know that the fd is being closed and we have no
* other user of stream->lock. Use the perf lock to destroy the stream
* here.
*/
mutex_lock(>->perf.lock);
i915_perf_destroy_locked(stream);
mutex_unlock(>->perf.lock);
/* Release the reference the perf stream kept on the driver. */
drm_dev_put(&perf->i915->drm);
return 0;
}
static const struct file_operations fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.release = i915_perf_release,
.poll = i915_perf_poll,
.read = i915_perf_read,
.unlocked_ioctl = i915_perf_ioctl,
/* Our ioctl have no arguments, so it's safe to use the same function
* to handle 32bits compatibility.
*/
.compat_ioctl = i915_perf_ioctl,
};
/**
* i915_perf_open_ioctl_locked - DRM ioctl() for userspace to open a stream FD
* @perf: i915 perf instance
* @param: The open parameters passed to 'DRM_I915_PERF_OPEN`
* @props: individually validated u64 property value pairs
* @file: drm file
*
* See i915_perf_ioctl_open() for interface details.
*
* Implements further stream config validation and stream initialization on
* behalf of i915_perf_open_ioctl() with the >->perf.lock mutex
* taken to serialize with any non-file-operation driver hooks.
*
* Note: at this point the @props have only been validated in isolation and
* it's still necessary to validate that the combination of properties makes
* sense.
*
* In the case where userspace is interested in OA unit metrics then further
* config validation and stream initialization details will be handled by
* i915_oa_stream_init(). The code here should only validate config state that
* will be relevant to all stream types / backends.
*
* Returns: zero on success or a negative error code.
*/
static int
i915_perf_open_ioctl_locked(struct i915_perf *perf,
struct drm_i915_perf_open_param *param,
struct perf_open_properties *props,
struct drm_file *file)
{
struct i915_gem_context *specific_ctx = NULL;
struct i915_perf_stream *stream = NULL;
unsigned long f_flags = 0;
bool privileged_op = true;
int stream_fd;
int ret;
if (props->single_context) {
u32 ctx_handle = props->ctx_handle;
struct drm_i915_file_private *file_priv = file->driver_priv;
specific_ctx = i915_gem_context_lookup(file_priv, ctx_handle);
if (IS_ERR(specific_ctx)) {
drm_dbg(&perf->i915->drm,
"Failed to look up context with ID %u for opening perf stream\n",
ctx_handle);
ret = PTR_ERR(specific_ctx);
goto err;
}
}
/*
* On Haswell the OA unit supports clock gating off for a specific
* context and in this mode there's no visibility of metrics for the
* rest of the system, which we consider acceptable for a
* non-privileged client.
*
* For Gen8->11 the OA unit no longer supports clock gating off for a
* specific context and the kernel can't securely stop the counters
* from updating as system-wide / global values. Even though we can
* filter reports based on the included context ID we can't block
* clients from seeing the raw / global counter values via
* MI_REPORT_PERF_COUNT commands and so consider it a privileged op to
* enable the OA unit by default.
*
* For Gen12+ we gain a new OAR unit that only monitors the RCS on a
* per context basis. So we can relax requirements there if the user
* doesn't request global stream access (i.e. query based sampling
* using MI_RECORD_PERF_COUNT.
*/
if (IS_HASWELL(perf->i915) && specific_ctx)
privileged_op = false;
else if (GRAPHICS_VER(perf->i915) == 12 && specific_ctx &&
(props->sample_flags & SAMPLE_OA_REPORT) == 0)
privileged_op = false;
if (props->hold_preemption) {
if (!props->single_context) {
drm_dbg(&perf->i915->drm,
"preemption disable with no context\n");
ret = -EINVAL;
goto err;
}
privileged_op = true;
}
/*
* Asking for SSEU configuration is a priviliged operation.
*/
if (props->has_sseu)
privileged_op = true;
else
get_default_sseu_config(&props->sseu, props->engine);
/* Similar to perf's kernel.perf_paranoid_cpu sysctl option
* we check a dev.i915.perf_stream_paranoid sysctl option
* to determine if it's ok to access system wide OA counters
* without CAP_PERFMON or CAP_SYS_ADMIN privileges.
*/
if (privileged_op &&
i915_perf_stream_paranoid && !perfmon_capable()) {
drm_dbg(&perf->i915->drm,
"Insufficient privileges to open i915 perf stream\n");
ret = -EACCES;
goto err_ctx;
}
stream = kzalloc(sizeof(*stream), GFP_KERNEL);
if (!stream) {
ret = -ENOMEM;
goto err_ctx;
}
stream->perf = perf;
stream->ctx = specific_ctx;
stream->poll_oa_period = props->poll_oa_period;
ret = i915_oa_stream_init(stream, param, props);
if (ret)
goto err_alloc;
/* we avoid simply assigning stream->sample_flags = props->sample_flags
* to have _stream_init check the combination of sample flags more
* thoroughly, but still this is the expected result at this point.
*/
if (WARN_ON(stream->sample_flags != props->sample_flags)) {
ret = -ENODEV;
goto err_flags;
}
if (param->flags & I915_PERF_FLAG_FD_CLOEXEC)
f_flags |= O_CLOEXEC;
if (param->flags & I915_PERF_FLAG_FD_NONBLOCK)
f_flags |= O_NONBLOCK;
stream_fd = anon_inode_getfd("[i915_perf]", &fops, stream, f_flags);
if (stream_fd < 0) {
ret = stream_fd;
goto err_flags;
}
if (!(param->flags & I915_PERF_FLAG_DISABLED))
i915_perf_enable_locked(stream);
/* Take a reference on the driver that will be kept with stream_fd
* until its release.
*/
drm_dev_get(&perf->i915->drm);
return stream_fd;
err_flags:
if (stream->ops->destroy)
stream->ops->destroy(stream);
err_alloc:
kfree(stream);
err_ctx:
if (specific_ctx)
i915_gem_context_put(specific_ctx);
err:
return ret;
}
static u64 oa_exponent_to_ns(struct i915_perf *perf, int exponent)
{
u64 nom = (2ULL << exponent) * NSEC_PER_SEC;
u32 den = i915_perf_oa_timestamp_frequency(perf->i915);
return div_u64(nom + den - 1, den);
}
static __always_inline bool
oa_format_valid(struct i915_perf *perf, enum drm_i915_oa_format format)
{
return test_bit(format, perf->format_mask);
}
static __always_inline void
oa_format_add(struct i915_perf *perf, enum drm_i915_oa_format format)
{
__set_bit(format, perf->format_mask);
}
/**
* read_properties_unlocked - validate + copy userspace stream open properties
* @perf: i915 perf instance
* @uprops: The array of u64 key value pairs given by userspace
* @n_props: The number of key value pairs expected in @uprops
* @props: The stream configuration built up while validating properties
*
* Note this function only validates properties in isolation it doesn't
* validate that the combination of properties makes sense or that all
* properties necessary for a particular kind of stream have been set.
*
* Note that there currently aren't any ordering requirements for properties so
* we shouldn't validate or assume anything about ordering here. This doesn't
* rule out defining new properties with ordering requirements in the future.
*/
static int read_properties_unlocked(struct i915_perf *perf,
u64 __user *uprops,
u32 n_props,
struct perf_open_properties *props)
{
struct drm_i915_gem_context_param_sseu user_sseu;
const struct i915_oa_format *f;
u64 __user *uprop = uprops;
bool config_instance = false;
bool config_class = false;
bool config_sseu = false;
u8 class, instance;
u32 i;
int ret;
memset(props, 0, sizeof(struct perf_open_properties));
props->poll_oa_period = DEFAULT_POLL_PERIOD_NS;
/* Considering that ID = 0 is reserved and assuming that we don't
* (currently) expect any configurations to ever specify duplicate
* values for a particular property ID then the last _PROP_MAX value is
* one greater than the maximum number of properties we expect to get
* from userspace.
*/
if (!n_props || n_props >= DRM_I915_PERF_PROP_MAX) {
drm_dbg(&perf->i915->drm,
"Invalid number of i915 perf properties given\n");
return -EINVAL;
}
/* Defaults when class:instance is not passed */
class = I915_ENGINE_CLASS_RENDER;
instance = 0;
for (i = 0; i < n_props; i++) {
u64 oa_period, oa_freq_hz;
u64 id, value;
ret = get_user(id, uprop);
if (ret)
return ret;
ret = get_user(value, uprop + 1);
if (ret)
return ret;
if (id == 0 || id >= DRM_I915_PERF_PROP_MAX) {
drm_dbg(&perf->i915->drm,
"Unknown i915 perf property ID\n");
return -EINVAL;
}
switch ((enum drm_i915_perf_property_id)id) {
case DRM_I915_PERF_PROP_CTX_HANDLE:
props->single_context = 1;
props->ctx_handle = value;
break;
case DRM_I915_PERF_PROP_SAMPLE_OA:
if (value)
props->sample_flags |= SAMPLE_OA_REPORT;
break;
case DRM_I915_PERF_PROP_OA_METRICS_SET:
if (value == 0) {
drm_dbg(&perf->i915->drm,
"Unknown OA metric set ID\n");
return -EINVAL;
}
props->metrics_set = value;
break;
case DRM_I915_PERF_PROP_OA_FORMAT:
if (value == 0 || value >= I915_OA_FORMAT_MAX) {
drm_dbg(&perf->i915->drm,
"Out-of-range OA report format %llu\n",
value);
return -EINVAL;
}
if (!oa_format_valid(perf, value)) {
drm_dbg(&perf->i915->drm,
"Unsupported OA report format %llu\n",
value);
return -EINVAL;
}
props->oa_format = value;
break;
case DRM_I915_PERF_PROP_OA_EXPONENT:
if (value > OA_EXPONENT_MAX) {
drm_dbg(&perf->i915->drm,
"OA timer exponent too high (> %u)\n",
OA_EXPONENT_MAX);
return -EINVAL;
}
/* Theoretically we can program the OA unit to sample
* e.g. every 160ns for HSW, 167ns for BDW/SKL or 104ns
* for BXT. We don't allow such high sampling
* frequencies by default unless root.
*/
BUILD_BUG_ON(sizeof(oa_period) != 8);
oa_period = oa_exponent_to_ns(perf, value);
/* This check is primarily to ensure that oa_period <=
* UINT32_MAX (before passing to do_div which only
* accepts a u32 denominator), but we can also skip
* checking anything < 1Hz which implicitly can't be
* limited via an integer oa_max_sample_rate.
*/
if (oa_period <= NSEC_PER_SEC) {
u64 tmp = NSEC_PER_SEC;
do_div(tmp, oa_period);
oa_freq_hz = tmp;
} else
oa_freq_hz = 0;
if (oa_freq_hz > i915_oa_max_sample_rate && !perfmon_capable()) {
drm_dbg(&perf->i915->drm,
"OA exponent would exceed the max sampling frequency (sysctl dev.i915.oa_max_sample_rate) %uHz without CAP_PERFMON or CAP_SYS_ADMIN privileges\n",
i915_oa_max_sample_rate);
return -EACCES;
}
props->oa_periodic = true;
props->oa_period_exponent = value;
break;
case DRM_I915_PERF_PROP_HOLD_PREEMPTION:
props->hold_preemption = !!value;
break;
case DRM_I915_PERF_PROP_GLOBAL_SSEU: {
if (GRAPHICS_VER_FULL(perf->i915) >= IP_VER(12, 50)) {
drm_dbg(&perf->i915->drm,
"SSEU config not supported on gfx %x\n",
GRAPHICS_VER_FULL(perf->i915));
return -ENODEV;
}
if (copy_from_user(&user_sseu,
u64_to_user_ptr(value),
sizeof(user_sseu))) {
drm_dbg(&perf->i915->drm,
"Unable to copy global sseu parameter\n");
return -EFAULT;
}
config_sseu = true;
break;
}
case DRM_I915_PERF_PROP_POLL_OA_PERIOD:
if (value < 100000 /* 100us */) {
drm_dbg(&perf->i915->drm,
"OA availability timer too small (%lluns < 100us)\n",
value);
return -EINVAL;
}
props->poll_oa_period = value;
break;
case DRM_I915_PERF_PROP_OA_ENGINE_CLASS:
class = (u8)value;
config_class = true;
break;
case DRM_I915_PERF_PROP_OA_ENGINE_INSTANCE:
instance = (u8)value;
config_instance = true;
break;
default:
MISSING_CASE(id);
return -EINVAL;
}
uprop += 2;
}
if ((config_class && !config_instance) ||
(config_instance && !config_class)) {
drm_dbg(&perf->i915->drm,
"OA engine-class and engine-instance parameters must be passed together\n");
return -EINVAL;
}
props->engine = intel_engine_lookup_user(perf->i915, class, instance);
if (!props->engine) {
drm_dbg(&perf->i915->drm,
"OA engine class and instance invalid %d:%d\n",
class, instance);
return -EINVAL;
}
if (!engine_supports_oa(props->engine)) {
drm_dbg(&perf->i915->drm,
"Engine not supported by OA %d:%d\n",
class, instance);
return -EINVAL;
}
/*
* Wa_14017512683: mtl[a0..c0): Use of OAM must be preceded with Media
* C6 disable in BIOS. Fail if Media C6 is enabled on steppings where OAM
* does not work as expected.
*/
if (IS_MTL_MEDIA_STEP(props->engine->i915, STEP_A0, STEP_C0) &&
props->engine->oa_group->type == TYPE_OAM &&
intel_check_bios_c6_setup(&props->engine->gt->rc6)) {
drm_dbg(&perf->i915->drm,
"OAM requires media C6 to be disabled in BIOS\n");
return -EINVAL;
}
i = array_index_nospec(props->oa_format, I915_OA_FORMAT_MAX);
f = &perf->oa_formats[i];
if (!engine_supports_oa_format(props->engine, f->type)) {
drm_dbg(&perf->i915->drm,
"Invalid OA format %d for class %d\n",
f->type, props->engine->class);
return -EINVAL;
}
if (config_sseu) {
ret = get_sseu_config(&props->sseu, props->engine, &user_sseu);
if (ret) {
drm_dbg(&perf->i915->drm,
"Invalid SSEU configuration\n");
return ret;
}
props->has_sseu = true;
}
return 0;
}
/**
* i915_perf_open_ioctl - DRM ioctl() for userspace to open a stream FD
* @dev: drm device
* @data: ioctl data copied from userspace (unvalidated)
* @file: drm file
*
* Validates the stream open parameters given by userspace including flags
* and an array of u64 key, value pair properties.
*
* Very little is assumed up front about the nature of the stream being
* opened (for instance we don't assume it's for periodic OA unit metrics). An
* i915-perf stream is expected to be a suitable interface for other forms of
* buffered data written by the GPU besides periodic OA metrics.
*
* Note we copy the properties from userspace outside of the i915 perf
* mutex to avoid an awkward lockdep with mmap_lock.
*
* Most of the implementation details are handled by
* i915_perf_open_ioctl_locked() after taking the >->perf.lock
* mutex for serializing with any non-file-operation driver hooks.
*
* Return: A newly opened i915 Perf stream file descriptor or negative
* error code on failure.
*/
int i915_perf_open_ioctl(struct drm_device *dev, void *data,
struct drm_file *file)
{
struct i915_perf *perf = &to_i915(dev)->perf;
struct drm_i915_perf_open_param *param = data;
struct intel_gt *gt;
struct perf_open_properties props;
u32 known_open_flags;
int ret;
if (!perf->i915) {
drm_dbg(&perf->i915->drm,
"i915 perf interface not available for this system\n");
return -ENOTSUPP;
}
known_open_flags = I915_PERF_FLAG_FD_CLOEXEC |
I915_PERF_FLAG_FD_NONBLOCK |
I915_PERF_FLAG_DISABLED;
if (param->flags & ~known_open_flags) {
drm_dbg(&perf->i915->drm,
"Unknown drm_i915_perf_open_param flag\n");
return -EINVAL;
}
ret = read_properties_unlocked(perf,
u64_to_user_ptr(param->properties_ptr),
param->num_properties,
&props);
if (ret)
return ret;
gt = props.engine->gt;
mutex_lock(>->perf.lock);
ret = i915_perf_open_ioctl_locked(perf, param, &props, file);
mutex_unlock(>->perf.lock);
return ret;
}
/**
* i915_perf_register - exposes i915-perf to userspace
* @i915: i915 device instance
*
* In particular OA metric sets are advertised under a sysfs metrics/
* directory allowing userspace to enumerate valid IDs that can be
* used to open an i915-perf stream.
*/
void i915_perf_register(struct drm_i915_private *i915)
{
struct i915_perf *perf = &i915->perf;
struct intel_gt *gt = to_gt(i915);
if (!perf->i915)
return;
/* To be sure we're synchronized with an attempted
* i915_perf_open_ioctl(); considering that we register after
* being exposed to userspace.
*/
mutex_lock(>->perf.lock);
perf->metrics_kobj =
kobject_create_and_add("metrics",
&i915->drm.primary->kdev->kobj);
mutex_unlock(>->perf.lock);
}
/**
* i915_perf_unregister - hide i915-perf from userspace
* @i915: i915 device instance
*
* i915-perf state cleanup is split up into an 'unregister' and
* 'deinit' phase where the interface is first hidden from
* userspace by i915_perf_unregister() before cleaning up
* remaining state in i915_perf_fini().
*/
void i915_perf_unregister(struct drm_i915_private *i915)
{
struct i915_perf *perf = &i915->perf;
if (!perf->metrics_kobj)
return;
kobject_put(perf->metrics_kobj);
perf->metrics_kobj = NULL;
}
static bool gen8_is_valid_flex_addr(struct i915_perf *perf, u32 addr)
{
static const i915_reg_t flex_eu_regs[] = {
EU_PERF_CNTL0,
EU_PERF_CNTL1,
EU_PERF_CNTL2,
EU_PERF_CNTL3,
EU_PERF_CNTL4,
EU_PERF_CNTL5,
EU_PERF_CNTL6,
};
int i;
for (i = 0; i < ARRAY_SIZE(flex_eu_regs); i++) {
if (i915_mmio_reg_offset(flex_eu_regs[i]) == addr)
return true;
}
return false;
}
static bool reg_in_range_table(u32 addr, const struct i915_range *table)
{
while (table->start || table->end) {
if (addr >= table->start && addr <= table->end)
return true;
table++;
}
return false;
}
#define REG_EQUAL(addr, mmio) \
((addr) == i915_mmio_reg_offset(mmio))
static const struct i915_range gen7_oa_b_counters[] = {
{ .start = 0x2710, .end = 0x272c }, /* OASTARTTRIG[1-8] */
{ .start = 0x2740, .end = 0x275c }, /* OAREPORTTRIG[1-8] */
{ .start = 0x2770, .end = 0x27ac }, /* OACEC[0-7][0-1] */
{}
};
static const struct i915_range gen12_oa_b_counters[] = {
{ .start = 0x2b2c, .end = 0x2b2c }, /* GEN12_OAG_OA_PESS */
{ .start = 0xd900, .end = 0xd91c }, /* GEN12_OAG_OASTARTTRIG[1-8] */
{ .start = 0xd920, .end = 0xd93c }, /* GEN12_OAG_OAREPORTTRIG1[1-8] */
{ .start = 0xd940, .end = 0xd97c }, /* GEN12_OAG_CEC[0-7][0-1] */
{ .start = 0xdc00, .end = 0xdc3c }, /* GEN12_OAG_SCEC[0-7][0-1] */
{ .start = 0xdc40, .end = 0xdc40 }, /* GEN12_OAG_SPCTR_CNF */
{ .start = 0xdc44, .end = 0xdc44 }, /* GEN12_OAA_DBG_REG */
{}
};
static const struct i915_range mtl_oam_b_counters[] = {
{ .start = 0x393000, .end = 0x39301c }, /* GEN12_OAM_STARTTRIG1[1-8] */
{ .start = 0x393020, .end = 0x39303c }, /* GEN12_OAM_REPORTTRIG1[1-8] */
{ .start = 0x393040, .end = 0x39307c }, /* GEN12_OAM_CEC[0-7][0-1] */
{ .start = 0x393200, .end = 0x39323C }, /* MPES[0-7] */
{}
};
static const struct i915_range xehp_oa_b_counters[] = {
{ .start = 0xdc48, .end = 0xdc48 }, /* OAA_ENABLE_REG */
{ .start = 0xdd00, .end = 0xdd48 }, /* OAG_LCE0_0 - OAA_LENABLE_REG */
{}
};
static const struct i915_range gen7_oa_mux_regs[] = {
{ .start = 0x91b8, .end = 0x91cc }, /* OA_PERFCNT[1-2], OA_PERFMATRIX */
{ .start = 0x9800, .end = 0x9888 }, /* MICRO_BP0_0 - NOA_WRITE */
{ .start = 0xe180, .end = 0xe180 }, /* HALF_SLICE_CHICKEN2 */
{}
};
static const struct i915_range hsw_oa_mux_regs[] = {
{ .start = 0x09e80, .end = 0x09ea4 }, /* HSW_MBVID2_NOA[0-9] */
{ .start = 0x09ec0, .end = 0x09ec0 }, /* HSW_MBVID2_MISR0 */
{ .start = 0x25100, .end = 0x2ff90 },
{}
};
static const struct i915_range chv_oa_mux_regs[] = {
{ .start = 0x182300, .end = 0x1823a4 },
{}
};
static const struct i915_range gen8_oa_mux_regs[] = {
{ .start = 0x0d00, .end = 0x0d2c }, /* RPM_CONFIG[0-1], NOA_CONFIG[0-8] */
{ .start = 0x20cc, .end = 0x20cc }, /* WAIT_FOR_RC6_EXIT */
{}
};
static const struct i915_range gen11_oa_mux_regs[] = {
{ .start = 0x91c8, .end = 0x91dc }, /* OA_PERFCNT[3-4] */
{}
};
static const struct i915_range gen12_oa_mux_regs[] = {
{ .start = 0x0d00, .end = 0x0d04 }, /* RPM_CONFIG[0-1] */
{ .start = 0x0d0c, .end = 0x0d2c }, /* NOA_CONFIG[0-8] */
{ .start = 0x9840, .end = 0x9840 }, /* GDT_CHICKEN_BITS */
{ .start = 0x9884, .end = 0x9888 }, /* NOA_WRITE */
{ .start = 0x20cc, .end = 0x20cc }, /* WAIT_FOR_RC6_EXIT */
{}
};
/*
* Ref: 14010536224:
* 0x20cc is repurposed on MTL, so use a separate array for MTL.
*/
static const struct i915_range mtl_oa_mux_regs[] = {
{ .start = 0x0d00, .end = 0x0d04 }, /* RPM_CONFIG[0-1] */
{ .start = 0x0d0c, .end = 0x0d2c }, /* NOA_CONFIG[0-8] */
{ .start = 0x9840, .end = 0x9840 }, /* GDT_CHICKEN_BITS */
{ .start = 0x9884, .end = 0x9888 }, /* NOA_WRITE */
{ .start = 0x38d100, .end = 0x38d114}, /* VISACTL */
{}
};
static bool gen7_is_valid_b_counter_addr(struct i915_perf *perf, u32 addr)
{
return reg_in_range_table(addr, gen7_oa_b_counters);
}
static bool gen8_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
{
return reg_in_range_table(addr, gen7_oa_mux_regs) ||
reg_in_range_table(addr, gen8_oa_mux_regs);
}
static bool gen11_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
{
return reg_in_range_table(addr, gen7_oa_mux_regs) ||
reg_in_range_table(addr, gen8_oa_mux_regs) ||
reg_in_range_table(addr, gen11_oa_mux_regs);
}
static bool hsw_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
{
return reg_in_range_table(addr, gen7_oa_mux_regs) ||
reg_in_range_table(addr, hsw_oa_mux_regs);
}
static bool chv_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
{
return reg_in_range_table(addr, gen7_oa_mux_regs) ||
reg_in_range_table(addr, chv_oa_mux_regs);
}
static bool gen12_is_valid_b_counter_addr(struct i915_perf *perf, u32 addr)
{
return reg_in_range_table(addr, gen12_oa_b_counters);
}
static bool mtl_is_valid_oam_b_counter_addr(struct i915_perf *perf, u32 addr)
{
if (HAS_OAM(perf->i915) &&
GRAPHICS_VER_FULL(perf->i915) >= IP_VER(12, 70))
return reg_in_range_table(addr, mtl_oam_b_counters);
return false;
}
static bool xehp_is_valid_b_counter_addr(struct i915_perf *perf, u32 addr)
{
return reg_in_range_table(addr, xehp_oa_b_counters) ||
reg_in_range_table(addr, gen12_oa_b_counters) ||
mtl_is_valid_oam_b_counter_addr(perf, addr);
}
static bool gen12_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
{
if (IS_METEORLAKE(perf->i915))
return reg_in_range_table(addr, mtl_oa_mux_regs);
else
return reg_in_range_table(addr, gen12_oa_mux_regs);
}
static u32 mask_reg_value(u32 reg, u32 val)
{
/* HALF_SLICE_CHICKEN2 is programmed with a the
* WaDisableSTUnitPowerOptimization workaround. Make sure the value
* programmed by userspace doesn't change this.
*/
if (REG_EQUAL(reg, HALF_SLICE_CHICKEN2))
val = val & ~_MASKED_BIT_ENABLE(GEN8_ST_PO_DISABLE);
/* WAIT_FOR_RC6_EXIT has only one bit fullfilling the function
* indicated by its name and a bunch of selection fields used by OA
* configs.
*/
if (REG_EQUAL(reg, WAIT_FOR_RC6_EXIT))
val = val & ~_MASKED_BIT_ENABLE(HSW_WAIT_FOR_RC6_EXIT_ENABLE);
return val;
}
static struct i915_oa_reg *alloc_oa_regs(struct i915_perf *perf,
bool (*is_valid)(struct i915_perf *perf, u32 addr),
u32 __user *regs,
u32 n_regs)
{
struct i915_oa_reg *oa_regs;
int err;
u32 i;
if (!n_regs)
return NULL;
/* No is_valid function means we're not allowing any register to be programmed. */
GEM_BUG_ON(!is_valid);
if (!is_valid)
return ERR_PTR(-EINVAL);
oa_regs = kmalloc_array(n_regs, sizeof(*oa_regs), GFP_KERNEL);
if (!oa_regs)
return ERR_PTR(-ENOMEM);
for (i = 0; i < n_regs; i++) {
u32 addr, value;
err = get_user(addr, regs);
if (err)
goto addr_err;
if (!is_valid(perf, addr)) {
drm_dbg(&perf->i915->drm,
"Invalid oa_reg address: %X\n", addr);
err = -EINVAL;
goto addr_err;
}
err = get_user(value, regs + 1);
if (err)
goto addr_err;
oa_regs[i].addr = _MMIO(addr);
oa_regs[i].value = mask_reg_value(addr, value);
regs += 2;
}
return oa_regs;
addr_err:
kfree(oa_regs);
return ERR_PTR(err);
}
static ssize_t show_dynamic_id(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
struct i915_oa_config *oa_config =
container_of(attr, typeof(*oa_config), sysfs_metric_id);
return sprintf(buf, "%d\n", oa_config->id);
}
static int create_dynamic_oa_sysfs_entry(struct i915_perf *perf,
struct i915_oa_config *oa_config)
{
sysfs_attr_init(&oa_config->sysfs_metric_id.attr);
oa_config->sysfs_metric_id.attr.name = "id";
oa_config->sysfs_metric_id.attr.mode = S_IRUGO;
oa_config->sysfs_metric_id.show = show_dynamic_id;
oa_config->sysfs_metric_id.store = NULL;
oa_config->attrs[0] = &oa_config->sysfs_metric_id.attr;
oa_config->attrs[1] = NULL;
oa_config->sysfs_metric.name = oa_config->uuid;
oa_config->sysfs_metric.attrs = oa_config->attrs;
return sysfs_create_group(perf->metrics_kobj,
&oa_config->sysfs_metric);
}
/**
* i915_perf_add_config_ioctl - DRM ioctl() for userspace to add a new OA config
* @dev: drm device
* @data: ioctl data (pointer to struct drm_i915_perf_oa_config) copied from
* userspace (unvalidated)
* @file: drm file
*
* Validates the submitted OA register to be saved into a new OA config that
* can then be used for programming the OA unit and its NOA network.
*
* Returns: A new allocated config number to be used with the perf open ioctl
* or a negative error code on failure.
*/
int i915_perf_add_config_ioctl(struct drm_device *dev, void *data,
struct drm_file *file)
{
struct i915_perf *perf = &to_i915(dev)->perf;
struct drm_i915_perf_oa_config *args = data;
struct i915_oa_config *oa_config, *tmp;
struct i915_oa_reg *regs;
int err, id;
if (!perf->i915) {
drm_dbg(&perf->i915->drm,
"i915 perf interface not available for this system\n");
return -ENOTSUPP;
}
if (!perf->metrics_kobj) {
drm_dbg(&perf->i915->drm,
"OA metrics weren't advertised via sysfs\n");
return -EINVAL;
}
if (i915_perf_stream_paranoid && !perfmon_capable()) {
drm_dbg(&perf->i915->drm,
"Insufficient privileges to add i915 OA config\n");
return -EACCES;
}
if ((!args->mux_regs_ptr || !args->n_mux_regs) &&
(!args->boolean_regs_ptr || !args->n_boolean_regs) &&
(!args->flex_regs_ptr || !args->n_flex_regs)) {
drm_dbg(&perf->i915->drm,
"No OA registers given\n");
return -EINVAL;
}
oa_config = kzalloc(sizeof(*oa_config), GFP_KERNEL);
if (!oa_config) {
drm_dbg(&perf->i915->drm,
"Failed to allocate memory for the OA config\n");
return -ENOMEM;
}
oa_config->perf = perf;
kref_init(&oa_config->ref);
if (!uuid_is_valid(args->uuid)) {
drm_dbg(&perf->i915->drm,
"Invalid uuid format for OA config\n");
err = -EINVAL;
goto reg_err;
}
/* Last character in oa_config->uuid will be 0 because oa_config is
* kzalloc.
*/
memcpy(oa_config->uuid, args->uuid, sizeof(args->uuid));
oa_config->mux_regs_len = args->n_mux_regs;
regs = alloc_oa_regs(perf,
perf->ops.is_valid_mux_reg,
u64_to_user_ptr(args->mux_regs_ptr),
args->n_mux_regs);
if (IS_ERR(regs)) {
drm_dbg(&perf->i915->drm,
"Failed to create OA config for mux_regs\n");
err = PTR_ERR(regs);
goto reg_err;
}
oa_config->mux_regs = regs;
oa_config->b_counter_regs_len = args->n_boolean_regs;
regs = alloc_oa_regs(perf,
perf->ops.is_valid_b_counter_reg,
u64_to_user_ptr(args->boolean_regs_ptr),
args->n_boolean_regs);
if (IS_ERR(regs)) {
drm_dbg(&perf->i915->drm,
"Failed to create OA config for b_counter_regs\n");
err = PTR_ERR(regs);
goto reg_err;
}
oa_config->b_counter_regs = regs;
if (GRAPHICS_VER(perf->i915) < 8) {
if (args->n_flex_regs != 0) {
err = -EINVAL;
goto reg_err;
}
} else {
oa_config->flex_regs_len = args->n_flex_regs;
regs = alloc_oa_regs(perf,
perf->ops.is_valid_flex_reg,
u64_to_user_ptr(args->flex_regs_ptr),
args->n_flex_regs);
if (IS_ERR(regs)) {
drm_dbg(&perf->i915->drm,
"Failed to create OA config for flex_regs\n");
err = PTR_ERR(regs);
goto reg_err;
}
oa_config->flex_regs = regs;
}
err = mutex_lock_interruptible(&perf->metrics_lock);
if (err)
goto reg_err;
/* We shouldn't have too many configs, so this iteration shouldn't be
* too costly.
*/
idr_for_each_entry(&perf->metrics_idr, tmp, id) {
if (!strcmp(tmp->uuid, oa_config->uuid)) {
drm_dbg(&perf->i915->drm,
"OA config already exists with this uuid\n");
err = -EADDRINUSE;
goto sysfs_err;
}
}
err = create_dynamic_oa_sysfs_entry(perf, oa_config);
if (err) {
drm_dbg(&perf->i915->drm,
"Failed to create sysfs entry for OA config\n");
goto sysfs_err;
}
/* Config id 0 is invalid, id 1 for kernel stored test config. */
oa_config->id = idr_alloc(&perf->metrics_idr,
oa_config, 2,
0, GFP_KERNEL);
if (oa_config->id < 0) {
drm_dbg(&perf->i915->drm,
"Failed to create sysfs entry for OA config\n");
err = oa_config->id;
goto sysfs_err;
}
id = oa_config->id;
drm_dbg(&perf->i915->drm,
"Added config %s id=%i\n", oa_config->uuid, oa_config->id);
mutex_unlock(&perf->metrics_lock);
return id;
sysfs_err:
mutex_unlock(&perf->metrics_lock);
reg_err:
i915_oa_config_put(oa_config);
drm_dbg(&perf->i915->drm,
"Failed to add new OA config\n");
return err;
}
/**
* i915_perf_remove_config_ioctl - DRM ioctl() for userspace to remove an OA config
* @dev: drm device
* @data: ioctl data (pointer to u64 integer) copied from userspace
* @file: drm file
*
* Configs can be removed while being used, the will stop appearing in sysfs
* and their content will be freed when the stream using the config is closed.
*
* Returns: 0 on success or a negative error code on failure.
*/
int i915_perf_remove_config_ioctl(struct drm_device *dev, void *data,
struct drm_file *file)
{
struct i915_perf *perf = &to_i915(dev)->perf;
u64 *arg = data;
struct i915_oa_config *oa_config;
int ret;
if (!perf->i915) {
drm_dbg(&perf->i915->drm,
"i915 perf interface not available for this system\n");
return -ENOTSUPP;
}
if (i915_perf_stream_paranoid && !perfmon_capable()) {
drm_dbg(&perf->i915->drm,
"Insufficient privileges to remove i915 OA config\n");
return -EACCES;
}
ret = mutex_lock_interruptible(&perf->metrics_lock);
if (ret)
return ret;
oa_config = idr_find(&perf->metrics_idr, *arg);
if (!oa_config) {
drm_dbg(&perf->i915->drm,
"Failed to remove unknown OA config\n");
ret = -ENOENT;
goto err_unlock;
}
GEM_BUG_ON(*arg != oa_config->id);
sysfs_remove_group(perf->metrics_kobj, &oa_config->sysfs_metric);
idr_remove(&perf->metrics_idr, *arg);
mutex_unlock(&perf->metrics_lock);
drm_dbg(&perf->i915->drm,
"Removed config %s id=%i\n", oa_config->uuid, oa_config->id);
i915_oa_config_put(oa_config);
return 0;
err_unlock:
mutex_unlock(&perf->metrics_lock);
return ret;
}
static struct ctl_table oa_table[] = {
{
.procname = "perf_stream_paranoid",
.data = &i915_perf_stream_paranoid,
.maxlen = sizeof(i915_perf_stream_paranoid),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = SYSCTL_ZERO,
.extra2 = SYSCTL_ONE,
},
{
.procname = "oa_max_sample_rate",
.data = &i915_oa_max_sample_rate,
.maxlen = sizeof(i915_oa_max_sample_rate),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = SYSCTL_ZERO,
.extra2 = &oa_sample_rate_hard_limit,
},
{}
};
static u32 num_perf_groups_per_gt(struct intel_gt *gt)
{
return 1;
}
static u32 __oam_engine_group(struct intel_engine_cs *engine)
{
if (GRAPHICS_VER_FULL(engine->i915) >= IP_VER(12, 70)) {
/*
* There's 1 SAMEDIA gt and 1 OAM per SAMEDIA gt. All media slices
* within the gt use the same OAM. All MTL SKUs list 1 SA MEDIA.
*/
drm_WARN_ON(&engine->i915->drm,
engine->gt->type != GT_MEDIA);
return PERF_GROUP_OAM_SAMEDIA_0;
}
return PERF_GROUP_INVALID;
}
static u32 __oa_engine_group(struct intel_engine_cs *engine)
{
switch (engine->class) {
case RENDER_CLASS:
return PERF_GROUP_OAG;
case VIDEO_DECODE_CLASS:
case VIDEO_ENHANCEMENT_CLASS:
return __oam_engine_group(engine);
default:
return PERF_GROUP_INVALID;
}
}
static struct i915_perf_regs __oam_regs(u32 base)
{
return (struct i915_perf_regs) {
base,
GEN12_OAM_HEAD_POINTER(base),
GEN12_OAM_TAIL_POINTER(base),
GEN12_OAM_BUFFER(base),
GEN12_OAM_CONTEXT_CONTROL(base),
GEN12_OAM_CONTROL(base),
GEN12_OAM_DEBUG(base),
GEN12_OAM_STATUS(base),
GEN12_OAM_CONTROL_COUNTER_FORMAT_SHIFT,
};
}
static struct i915_perf_regs __oag_regs(void)
{
return (struct i915_perf_regs) {
0,
GEN12_OAG_OAHEADPTR,
GEN12_OAG_OATAILPTR,
GEN12_OAG_OABUFFER,
GEN12_OAG_OAGLBCTXCTRL,
GEN12_OAG_OACONTROL,
GEN12_OAG_OA_DEBUG,
GEN12_OAG_OASTATUS,
GEN12_OAG_OACONTROL_OA_COUNTER_FORMAT_SHIFT,
};
}
static void oa_init_groups(struct intel_gt *gt)
{
int i, num_groups = gt->perf.num_perf_groups;
for (i = 0; i < num_groups; i++) {
struct i915_perf_group *g = >->perf.group[i];
/* Fused off engines can result in a group with num_engines == 0 */
if (g->num_engines == 0)
continue;
if (i == PERF_GROUP_OAG && gt->type != GT_MEDIA) {
g->regs = __oag_regs();
g->type = TYPE_OAG;
} else if (GRAPHICS_VER_FULL(gt->i915) >= IP_VER(12, 70)) {
g->regs = __oam_regs(mtl_oa_base[i]);
g->type = TYPE_OAM;
}
}
}
static int oa_init_gt(struct intel_gt *gt)
{
u32 num_groups = num_perf_groups_per_gt(gt);
struct intel_engine_cs *engine;
struct i915_perf_group *g;
intel_engine_mask_t tmp;
g = kcalloc(num_groups, sizeof(*g), GFP_KERNEL);
if (!g)
return -ENOMEM;
for_each_engine_masked(engine, gt, ALL_ENGINES, tmp) {
u32 index = __oa_engine_group(engine);
engine->oa_group = NULL;
if (index < num_groups) {
g[index].num_engines++;
engine->oa_group = &g[index];
}
}
gt->perf.num_perf_groups = num_groups;
gt->perf.group = g;
oa_init_groups(gt);
return 0;
}
static int oa_init_engine_groups(struct i915_perf *perf)
{
struct intel_gt *gt;
int i, ret;
for_each_gt(gt, perf->i915, i) {
ret = oa_init_gt(gt);
if (ret)
return ret;
}
return 0;
}
static void oa_init_supported_formats(struct i915_perf *perf)
{
struct drm_i915_private *i915 = perf->i915;
enum intel_platform platform = INTEL_INFO(i915)->platform;
switch (platform) {
case INTEL_HASWELL:
oa_format_add(perf, I915_OA_FORMAT_A13);
oa_format_add(perf, I915_OA_FORMAT_A13);
oa_format_add(perf, I915_OA_FORMAT_A29);
oa_format_add(perf, I915_OA_FORMAT_A13_B8_C8);
oa_format_add(perf, I915_OA_FORMAT_B4_C8);
oa_format_add(perf, I915_OA_FORMAT_A45_B8_C8);
oa_format_add(perf, I915_OA_FORMAT_B4_C8_A16);
oa_format_add(perf, I915_OA_FORMAT_C4_B8);
break;
case INTEL_BROADWELL:
case INTEL_CHERRYVIEW:
case INTEL_SKYLAKE:
case INTEL_BROXTON:
case INTEL_KABYLAKE:
case INTEL_GEMINILAKE:
case INTEL_COFFEELAKE:
case INTEL_COMETLAKE:
case INTEL_ICELAKE:
case INTEL_ELKHARTLAKE:
case INTEL_JASPERLAKE:
case INTEL_TIGERLAKE:
case INTEL_ROCKETLAKE:
case INTEL_DG1:
case INTEL_ALDERLAKE_S:
case INTEL_ALDERLAKE_P:
oa_format_add(perf, I915_OA_FORMAT_A12);
oa_format_add(perf, I915_OA_FORMAT_A12_B8_C8);
oa_format_add(perf, I915_OA_FORMAT_A32u40_A4u32_B8_C8);
oa_format_add(perf, I915_OA_FORMAT_C4_B8);
break;
case INTEL_DG2:
oa_format_add(perf, I915_OAR_FORMAT_A32u40_A4u32_B8_C8);
oa_format_add(perf, I915_OA_FORMAT_A24u40_A14u32_B8_C8);
break;
case INTEL_METEORLAKE:
oa_format_add(perf, I915_OAR_FORMAT_A32u40_A4u32_B8_C8);
oa_format_add(perf, I915_OA_FORMAT_A24u40_A14u32_B8_C8);
oa_format_add(perf, I915_OAM_FORMAT_MPEC8u64_B8_C8);
oa_format_add(perf, I915_OAM_FORMAT_MPEC8u32_B8_C8);
break;
default:
MISSING_CASE(platform);
}
}
static void i915_perf_init_info(struct drm_i915_private *i915)
{
struct i915_perf *perf = &i915->perf;
switch (GRAPHICS_VER(i915)) {
case 8:
perf->ctx_oactxctrl_offset = 0x120;
perf->ctx_flexeu0_offset = 0x2ce;
perf->gen8_valid_ctx_bit = BIT(25);
break;
case 9:
perf->ctx_oactxctrl_offset = 0x128;
perf->ctx_flexeu0_offset = 0x3de;
perf->gen8_valid_ctx_bit = BIT(16);
break;
case 11:
perf->ctx_oactxctrl_offset = 0x124;
perf->ctx_flexeu0_offset = 0x78e;
perf->gen8_valid_ctx_bit = BIT(16);
break;
case 12:
/*
* Calculate offset at runtime in oa_pin_context for gen12 and
* cache the value in perf->ctx_oactxctrl_offset.
*/
break;
default:
MISSING_CASE(GRAPHICS_VER(i915));
}
}
/**
* i915_perf_init - initialize i915-perf state on module bind
* @i915: i915 device instance
*
* Initializes i915-perf state without exposing anything to userspace.
*
* Note: i915-perf initialization is split into an 'init' and 'register'
* phase with the i915_perf_register() exposing state to userspace.
*/
int i915_perf_init(struct drm_i915_private *i915)
{
struct i915_perf *perf = &i915->perf;
perf->oa_formats = oa_formats;
if (IS_HASWELL(i915)) {
perf->ops.is_valid_b_counter_reg = gen7_is_valid_b_counter_addr;
perf->ops.is_valid_mux_reg = hsw_is_valid_mux_addr;
perf->ops.is_valid_flex_reg = NULL;
perf->ops.enable_metric_set = hsw_enable_metric_set;
perf->ops.disable_metric_set = hsw_disable_metric_set;
perf->ops.oa_enable = gen7_oa_enable;
perf->ops.oa_disable = gen7_oa_disable;
perf->ops.read = gen7_oa_read;
perf->ops.oa_hw_tail_read = gen7_oa_hw_tail_read;
} else if (HAS_LOGICAL_RING_CONTEXTS(i915)) {
/* Note: that although we could theoretically also support the
* legacy ringbuffer mode on BDW (and earlier iterations of
* this driver, before upstreaming did this) it didn't seem
* worth the complexity to maintain now that BDW+ enable
* execlist mode by default.
*/
perf->ops.read = gen8_oa_read;
i915_perf_init_info(i915);
if (IS_GRAPHICS_VER(i915, 8, 9)) {
perf->ops.is_valid_b_counter_reg =
gen7_is_valid_b_counter_addr;
perf->ops.is_valid_mux_reg =
gen8_is_valid_mux_addr;
perf->ops.is_valid_flex_reg =
gen8_is_valid_flex_addr;
if (IS_CHERRYVIEW(i915)) {
perf->ops.is_valid_mux_reg =
chv_is_valid_mux_addr;
}
perf->ops.oa_enable = gen8_oa_enable;
perf->ops.oa_disable = gen8_oa_disable;
perf->ops.enable_metric_set = gen8_enable_metric_set;
perf->ops.disable_metric_set = gen8_disable_metric_set;
perf->ops.oa_hw_tail_read = gen8_oa_hw_tail_read;
} else if (GRAPHICS_VER(i915) == 11) {
perf->ops.is_valid_b_counter_reg =
gen7_is_valid_b_counter_addr;
perf->ops.is_valid_mux_reg =
gen11_is_valid_mux_addr;
perf->ops.is_valid_flex_reg =
gen8_is_valid_flex_addr;
perf->ops.oa_enable = gen8_oa_enable;
perf->ops.oa_disable = gen8_oa_disable;
perf->ops.enable_metric_set = gen8_enable_metric_set;
perf->ops.disable_metric_set = gen11_disable_metric_set;
perf->ops.oa_hw_tail_read = gen8_oa_hw_tail_read;
} else if (GRAPHICS_VER(i915) == 12) {
perf->ops.is_valid_b_counter_reg =
HAS_OA_SLICE_CONTRIB_LIMITS(i915) ?
xehp_is_valid_b_counter_addr :
gen12_is_valid_b_counter_addr;
perf->ops.is_valid_mux_reg =
gen12_is_valid_mux_addr;
perf->ops.is_valid_flex_reg =
gen8_is_valid_flex_addr;
perf->ops.oa_enable = gen12_oa_enable;
perf->ops.oa_disable = gen12_oa_disable;
perf->ops.enable_metric_set = gen12_enable_metric_set;
perf->ops.disable_metric_set = gen12_disable_metric_set;
perf->ops.oa_hw_tail_read = gen12_oa_hw_tail_read;
}
}
if (perf->ops.enable_metric_set) {
struct intel_gt *gt;
int i, ret;
for_each_gt(gt, i915, i)
mutex_init(>->perf.lock);
/* Choose a representative limit */
oa_sample_rate_hard_limit = to_gt(i915)->clock_frequency / 2;
mutex_init(&perf->metrics_lock);
idr_init_base(&perf->metrics_idr, 1);
/* We set up some ratelimit state to potentially throttle any
* _NOTES about spurious, invalid OA reports which we don't
* forward to userspace.
*
* We print a _NOTE about any throttling when closing the
* stream instead of waiting until driver _fini which no one
* would ever see.
*
* Using the same limiting factors as printk_ratelimit()
*/
ratelimit_state_init(&perf->spurious_report_rs, 5 * HZ, 10);
/* Since we use a DRM_NOTE for spurious reports it would be
* inconsistent to let __ratelimit() automatically print a
* warning for throttling.
*/
ratelimit_set_flags(&perf->spurious_report_rs,
RATELIMIT_MSG_ON_RELEASE);
ratelimit_state_init(&perf->tail_pointer_race,
5 * HZ, 10);
ratelimit_set_flags(&perf->tail_pointer_race,
RATELIMIT_MSG_ON_RELEASE);
atomic64_set(&perf->noa_programming_delay,
500 * 1000 /* 500us */);
perf->i915 = i915;
ret = oa_init_engine_groups(perf);
if (ret) {
drm_err(&i915->drm,
"OA initialization failed %d\n", ret);
return ret;
}
oa_init_supported_formats(perf);
}
return 0;
}
static int destroy_config(int id, void *p, void *data)
{
i915_oa_config_put(p);
return 0;
}
int i915_perf_sysctl_register(void)
{
sysctl_header = register_sysctl("dev/i915", oa_table);
return 0;
}
void i915_perf_sysctl_unregister(void)
{
unregister_sysctl_table(sysctl_header);
}
/**
* i915_perf_fini - Counter part to i915_perf_init()
* @i915: i915 device instance
*/
void i915_perf_fini(struct drm_i915_private *i915)
{
struct i915_perf *perf = &i915->perf;
struct intel_gt *gt;
int i;
if (!perf->i915)
return;
for_each_gt(gt, perf->i915, i)
kfree(gt->perf.group);
idr_for_each(&perf->metrics_idr, destroy_config, perf);
idr_destroy(&perf->metrics_idr);
memset(&perf->ops, 0, sizeof(perf->ops));
perf->i915 = NULL;
}
/**
* i915_perf_ioctl_version - Version of the i915-perf subsystem
* @i915: The i915 device
*
* This version number is used by userspace to detect available features.
*/
int i915_perf_ioctl_version(struct drm_i915_private *i915)
{
/*
* 1: Initial version
* I915_PERF_IOCTL_ENABLE
* I915_PERF_IOCTL_DISABLE
*
* 2: Added runtime modification of OA config.
* I915_PERF_IOCTL_CONFIG
*
* 3: Add DRM_I915_PERF_PROP_HOLD_PREEMPTION parameter to hold
* preemption on a particular context so that performance data is
* accessible from a delta of MI_RPC reports without looking at the
* OA buffer.
*
* 4: Add DRM_I915_PERF_PROP_ALLOWED_SSEU to limit what contexts can
* be run for the duration of the performance recording based on
* their SSEU configuration.
*
* 5: Add DRM_I915_PERF_PROP_POLL_OA_PERIOD parameter that controls the
* interval for the hrtimer used to check for OA data.
*
* 6: Add DRM_I915_PERF_PROP_OA_ENGINE_CLASS and
* DRM_I915_PERF_PROP_OA_ENGINE_INSTANCE
*
* 7: Add support for video decode and enhancement classes.
*/
/*
* Wa_14017512683: mtl[a0..c0): Use of OAM must be preceded with Media
* C6 disable in BIOS. If Media C6 is enabled in BIOS, return version 6
* to indicate that OA media is not supported.
*/
if (IS_MTL_MEDIA_STEP(i915, STEP_A0, STEP_C0)) {
struct intel_gt *gt;
int i;
for_each_gt(gt, i915, i) {
if (gt->type == GT_MEDIA &&
intel_check_bios_c6_setup(>->rc6))
return 6;
}
}
return 7;
}
#if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
#include "selftests/i915_perf.c"
#endif
| linux-master | drivers/gpu/drm/i915/i915_perf.c |
/*
* SPDX-License-Identifier: MIT
*
* Copyright © 2018 Intel Corporation
*/
#include <linux/mutex.h>
#include "i915_drv.h"
#include "i915_request.h"
#include "i915_scheduler.h"
static struct kmem_cache *slab_dependencies;
static struct kmem_cache *slab_priorities;
static DEFINE_SPINLOCK(schedule_lock);
static const struct i915_request *
node_to_request(const struct i915_sched_node *node)
{
return container_of(node, const struct i915_request, sched);
}
static inline bool node_started(const struct i915_sched_node *node)
{
return i915_request_started(node_to_request(node));
}
static inline bool node_signaled(const struct i915_sched_node *node)
{
return i915_request_completed(node_to_request(node));
}
static inline struct i915_priolist *to_priolist(struct rb_node *rb)
{
return rb_entry(rb, struct i915_priolist, node);
}
static void assert_priolists(struct i915_sched_engine * const sched_engine)
{
struct rb_node *rb;
long last_prio;
if (!IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM))
return;
GEM_BUG_ON(rb_first_cached(&sched_engine->queue) !=
rb_first(&sched_engine->queue.rb_root));
last_prio = INT_MAX;
for (rb = rb_first_cached(&sched_engine->queue); rb; rb = rb_next(rb)) {
const struct i915_priolist *p = to_priolist(rb);
GEM_BUG_ON(p->priority > last_prio);
last_prio = p->priority;
}
}
struct list_head *
i915_sched_lookup_priolist(struct i915_sched_engine *sched_engine, int prio)
{
struct i915_priolist *p;
struct rb_node **parent, *rb;
bool first = true;
lockdep_assert_held(&sched_engine->lock);
assert_priolists(sched_engine);
if (unlikely(sched_engine->no_priolist))
prio = I915_PRIORITY_NORMAL;
find_priolist:
/* most positive priority is scheduled first, equal priorities fifo */
rb = NULL;
parent = &sched_engine->queue.rb_root.rb_node;
while (*parent) {
rb = *parent;
p = to_priolist(rb);
if (prio > p->priority) {
parent = &rb->rb_left;
} else if (prio < p->priority) {
parent = &rb->rb_right;
first = false;
} else {
return &p->requests;
}
}
if (prio == I915_PRIORITY_NORMAL) {
p = &sched_engine->default_priolist;
} else {
p = kmem_cache_alloc(slab_priorities, GFP_ATOMIC);
/* Convert an allocation failure to a priority bump */
if (unlikely(!p)) {
prio = I915_PRIORITY_NORMAL; /* recurses just once */
/* To maintain ordering with all rendering, after an
* allocation failure we have to disable all scheduling.
* Requests will then be executed in fifo, and schedule
* will ensure that dependencies are emitted in fifo.
* There will be still some reordering with existing
* requests, so if userspace lied about their
* dependencies that reordering may be visible.
*/
sched_engine->no_priolist = true;
goto find_priolist;
}
}
p->priority = prio;
INIT_LIST_HEAD(&p->requests);
rb_link_node(&p->node, rb, parent);
rb_insert_color_cached(&p->node, &sched_engine->queue, first);
return &p->requests;
}
void __i915_priolist_free(struct i915_priolist *p)
{
kmem_cache_free(slab_priorities, p);
}
struct sched_cache {
struct list_head *priolist;
};
static struct i915_sched_engine *
lock_sched_engine(struct i915_sched_node *node,
struct i915_sched_engine *locked,
struct sched_cache *cache)
{
const struct i915_request *rq = node_to_request(node);
struct i915_sched_engine *sched_engine;
GEM_BUG_ON(!locked);
/*
* Virtual engines complicate acquiring the engine timeline lock,
* as their rq->engine pointer is not stable until under that
* engine lock. The simple ploy we use is to take the lock then
* check that the rq still belongs to the newly locked engine.
*/
while (locked != (sched_engine = READ_ONCE(rq->engine)->sched_engine)) {
spin_unlock(&locked->lock);
memset(cache, 0, sizeof(*cache));
spin_lock(&sched_engine->lock);
locked = sched_engine;
}
GEM_BUG_ON(locked != sched_engine);
return locked;
}
static void __i915_schedule(struct i915_sched_node *node,
const struct i915_sched_attr *attr)
{
const int prio = max(attr->priority, node->attr.priority);
struct i915_sched_engine *sched_engine;
struct i915_dependency *dep, *p;
struct i915_dependency stack;
struct sched_cache cache;
LIST_HEAD(dfs);
/* Needed in order to use the temporary link inside i915_dependency */
lockdep_assert_held(&schedule_lock);
GEM_BUG_ON(prio == I915_PRIORITY_INVALID);
if (node_signaled(node))
return;
stack.signaler = node;
list_add(&stack.dfs_link, &dfs);
/*
* Recursively bump all dependent priorities to match the new request.
*
* A naive approach would be to use recursion:
* static void update_priorities(struct i915_sched_node *node, prio) {
* list_for_each_entry(dep, &node->signalers_list, signal_link)
* update_priorities(dep->signal, prio)
* queue_request(node);
* }
* but that may have unlimited recursion depth and so runs a very
* real risk of overunning the kernel stack. Instead, we build
* a flat list of all dependencies starting with the current request.
* As we walk the list of dependencies, we add all of its dependencies
* to the end of the list (this may include an already visited
* request) and continue to walk onwards onto the new dependencies. The
* end result is a topological list of requests in reverse order, the
* last element in the list is the request we must execute first.
*/
list_for_each_entry(dep, &dfs, dfs_link) {
struct i915_sched_node *node = dep->signaler;
/* If we are already flying, we know we have no signalers */
if (node_started(node))
continue;
/*
* Within an engine, there can be no cycle, but we may
* refer to the same dependency chain multiple times
* (redundant dependencies are not eliminated) and across
* engines.
*/
list_for_each_entry(p, &node->signalers_list, signal_link) {
GEM_BUG_ON(p == dep); /* no cycles! */
if (node_signaled(p->signaler))
continue;
if (prio > READ_ONCE(p->signaler->attr.priority))
list_move_tail(&p->dfs_link, &dfs);
}
}
/*
* If we didn't need to bump any existing priorities, and we haven't
* yet submitted this request (i.e. there is no potential race with
* execlists_submit_request()), we can set our own priority and skip
* acquiring the engine locks.
*/
if (node->attr.priority == I915_PRIORITY_INVALID) {
GEM_BUG_ON(!list_empty(&node->link));
node->attr = *attr;
if (stack.dfs_link.next == stack.dfs_link.prev)
return;
__list_del_entry(&stack.dfs_link);
}
memset(&cache, 0, sizeof(cache));
sched_engine = node_to_request(node)->engine->sched_engine;
spin_lock(&sched_engine->lock);
/* Fifo and depth-first replacement ensure our deps execute before us */
sched_engine = lock_sched_engine(node, sched_engine, &cache);
list_for_each_entry_safe_reverse(dep, p, &dfs, dfs_link) {
struct i915_request *from = container_of(dep->signaler,
struct i915_request,
sched);
INIT_LIST_HEAD(&dep->dfs_link);
node = dep->signaler;
sched_engine = lock_sched_engine(node, sched_engine, &cache);
lockdep_assert_held(&sched_engine->lock);
/* Recheck after acquiring the engine->timeline.lock */
if (prio <= node->attr.priority || node_signaled(node))
continue;
GEM_BUG_ON(node_to_request(node)->engine->sched_engine !=
sched_engine);
/* Must be called before changing the nodes priority */
if (sched_engine->bump_inflight_request_prio)
sched_engine->bump_inflight_request_prio(from, prio);
WRITE_ONCE(node->attr.priority, prio);
/*
* Once the request is ready, it will be placed into the
* priority lists and then onto the HW runlist. Before the
* request is ready, it does not contribute to our preemption
* decisions and we can safely ignore it, as it will, and
* any preemption required, be dealt with upon submission.
* See engine->submit_request()
*/
if (list_empty(&node->link))
continue;
if (i915_request_in_priority_queue(node_to_request(node))) {
if (!cache.priolist)
cache.priolist =
i915_sched_lookup_priolist(sched_engine,
prio);
list_move_tail(&node->link, cache.priolist);
}
/* Defer (tasklet) submission until after all of our updates. */
if (sched_engine->kick_backend)
sched_engine->kick_backend(node_to_request(node), prio);
}
spin_unlock(&sched_engine->lock);
}
void i915_schedule(struct i915_request *rq, const struct i915_sched_attr *attr)
{
spin_lock_irq(&schedule_lock);
__i915_schedule(&rq->sched, attr);
spin_unlock_irq(&schedule_lock);
}
void i915_sched_node_init(struct i915_sched_node *node)
{
INIT_LIST_HEAD(&node->signalers_list);
INIT_LIST_HEAD(&node->waiters_list);
INIT_LIST_HEAD(&node->link);
i915_sched_node_reinit(node);
}
void i915_sched_node_reinit(struct i915_sched_node *node)
{
node->attr.priority = I915_PRIORITY_INVALID;
node->semaphores = 0;
node->flags = 0;
GEM_BUG_ON(!list_empty(&node->signalers_list));
GEM_BUG_ON(!list_empty(&node->waiters_list));
GEM_BUG_ON(!list_empty(&node->link));
}
static struct i915_dependency *
i915_dependency_alloc(void)
{
return kmem_cache_alloc(slab_dependencies, GFP_KERNEL);
}
static void
i915_dependency_free(struct i915_dependency *dep)
{
kmem_cache_free(slab_dependencies, dep);
}
bool __i915_sched_node_add_dependency(struct i915_sched_node *node,
struct i915_sched_node *signal,
struct i915_dependency *dep,
unsigned long flags)
{
bool ret = false;
spin_lock_irq(&schedule_lock);
if (!node_signaled(signal)) {
INIT_LIST_HEAD(&dep->dfs_link);
dep->signaler = signal;
dep->waiter = node;
dep->flags = flags;
/* All set, now publish. Beware the lockless walkers. */
list_add_rcu(&dep->signal_link, &node->signalers_list);
list_add_rcu(&dep->wait_link, &signal->waiters_list);
/* Propagate the chains */
node->flags |= signal->flags;
ret = true;
}
spin_unlock_irq(&schedule_lock);
return ret;
}
int i915_sched_node_add_dependency(struct i915_sched_node *node,
struct i915_sched_node *signal,
unsigned long flags)
{
struct i915_dependency *dep;
dep = i915_dependency_alloc();
if (!dep)
return -ENOMEM;
if (!__i915_sched_node_add_dependency(node, signal, dep,
flags | I915_DEPENDENCY_ALLOC))
i915_dependency_free(dep);
return 0;
}
void i915_sched_node_fini(struct i915_sched_node *node)
{
struct i915_dependency *dep, *tmp;
spin_lock_irq(&schedule_lock);
/*
* Everyone we depended upon (the fences we wait to be signaled)
* should retire before us and remove themselves from our list.
* However, retirement is run independently on each timeline and
* so we may be called out-of-order.
*/
list_for_each_entry_safe(dep, tmp, &node->signalers_list, signal_link) {
GEM_BUG_ON(!list_empty(&dep->dfs_link));
list_del_rcu(&dep->wait_link);
if (dep->flags & I915_DEPENDENCY_ALLOC)
i915_dependency_free(dep);
}
INIT_LIST_HEAD(&node->signalers_list);
/* Remove ourselves from everyone who depends upon us */
list_for_each_entry_safe(dep, tmp, &node->waiters_list, wait_link) {
GEM_BUG_ON(dep->signaler != node);
GEM_BUG_ON(!list_empty(&dep->dfs_link));
list_del_rcu(&dep->signal_link);
if (dep->flags & I915_DEPENDENCY_ALLOC)
i915_dependency_free(dep);
}
INIT_LIST_HEAD(&node->waiters_list);
spin_unlock_irq(&schedule_lock);
}
void i915_request_show_with_schedule(struct drm_printer *m,
const struct i915_request *rq,
const char *prefix,
int indent)
{
struct i915_dependency *dep;
i915_request_show(m, rq, prefix, indent);
if (i915_request_completed(rq))
return;
rcu_read_lock();
for_each_signaler(dep, rq) {
const struct i915_request *signaler =
node_to_request(dep->signaler);
/* Dependencies along the same timeline are expected. */
if (signaler->timeline == rq->timeline)
continue;
if (__i915_request_is_complete(signaler))
continue;
i915_request_show(m, signaler, prefix, indent + 2);
}
rcu_read_unlock();
}
static void default_destroy(struct kref *kref)
{
struct i915_sched_engine *sched_engine =
container_of(kref, typeof(*sched_engine), ref);
tasklet_kill(&sched_engine->tasklet); /* flush the callback */
kfree(sched_engine);
}
static bool default_disabled(struct i915_sched_engine *sched_engine)
{
return false;
}
struct i915_sched_engine *
i915_sched_engine_create(unsigned int subclass)
{
struct i915_sched_engine *sched_engine;
sched_engine = kzalloc(sizeof(*sched_engine), GFP_KERNEL);
if (!sched_engine)
return NULL;
kref_init(&sched_engine->ref);
sched_engine->queue = RB_ROOT_CACHED;
sched_engine->queue_priority_hint = INT_MIN;
sched_engine->destroy = default_destroy;
sched_engine->disabled = default_disabled;
INIT_LIST_HEAD(&sched_engine->requests);
INIT_LIST_HEAD(&sched_engine->hold);
spin_lock_init(&sched_engine->lock);
lockdep_set_subclass(&sched_engine->lock, subclass);
/*
* Due to an interesting quirk in lockdep's internal debug tracking,
* after setting a subclass we must ensure the lock is used. Otherwise,
* nr_unused_locks is incremented once too often.
*/
#ifdef CONFIG_DEBUG_LOCK_ALLOC
local_irq_disable();
lock_map_acquire(&sched_engine->lock.dep_map);
lock_map_release(&sched_engine->lock.dep_map);
local_irq_enable();
#endif
return sched_engine;
}
void i915_scheduler_module_exit(void)
{
kmem_cache_destroy(slab_dependencies);
kmem_cache_destroy(slab_priorities);
}
int __init i915_scheduler_module_init(void)
{
slab_dependencies = KMEM_CACHE(i915_dependency,
SLAB_HWCACHE_ALIGN |
SLAB_TYPESAFE_BY_RCU);
if (!slab_dependencies)
return -ENOMEM;
slab_priorities = KMEM_CACHE(i915_priolist, 0);
if (!slab_priorities)
goto err_priorities;
return 0;
err_priorities:
kmem_cache_destroy(slab_priorities);
return -ENOMEM;
}
| linux-master | drivers/gpu/drm/i915/i915_scheduler.c |
/*
* Copyright © 2016 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
#include <drm/drm_color_mgmt.h>
#include <drm/drm_drv.h>
#include <drm/i915_pciids.h>
#include "display/intel_display.h"
#include "display/intel_display_driver.h"
#include "gt/intel_gt_regs.h"
#include "gt/intel_sa_media.h"
#include "gem/i915_gem_object_types.h"
#include "i915_driver.h"
#include "i915_drv.h"
#include "i915_pci.h"
#include "i915_reg.h"
#include "intel_pci_config.h"
#define PLATFORM(x) .platform = (x)
#define GEN(x) \
.__runtime.graphics.ip.ver = (x), \
.__runtime.media.ip.ver = (x)
#define LEGACY_CACHELEVEL \
.cachelevel_to_pat = { \
[I915_CACHE_NONE] = 0, \
[I915_CACHE_LLC] = 1, \
[I915_CACHE_L3_LLC] = 2, \
[I915_CACHE_WT] = 3, \
}
#define TGL_CACHELEVEL \
.cachelevel_to_pat = { \
[I915_CACHE_NONE] = 3, \
[I915_CACHE_LLC] = 0, \
[I915_CACHE_L3_LLC] = 0, \
[I915_CACHE_WT] = 2, \
}
#define PVC_CACHELEVEL \
.cachelevel_to_pat = { \
[I915_CACHE_NONE] = 0, \
[I915_CACHE_LLC] = 3, \
[I915_CACHE_L3_LLC] = 3, \
[I915_CACHE_WT] = 2, \
}
#define MTL_CACHELEVEL \
.cachelevel_to_pat = { \
[I915_CACHE_NONE] = 2, \
[I915_CACHE_LLC] = 3, \
[I915_CACHE_L3_LLC] = 3, \
[I915_CACHE_WT] = 1, \
}
/* Keep in gen based order, and chronological order within a gen */
#define GEN_DEFAULT_PAGE_SIZES \
.__runtime.page_sizes = I915_GTT_PAGE_SIZE_4K
#define GEN_DEFAULT_REGIONS \
.memory_regions = REGION_SMEM | REGION_STOLEN_SMEM
#define I830_FEATURES \
GEN(2), \
.is_mobile = 1, \
.gpu_reset_clobbers_display = true, \
.has_3d_pipeline = 1, \
.hws_needs_physical = 1, \
.unfenced_needs_alignment = 1, \
.platform_engine_mask = BIT(RCS0), \
.has_snoop = true, \
.has_coherent_ggtt = false, \
.dma_mask_size = 32, \
.max_pat_index = 3, \
GEN_DEFAULT_PAGE_SIZES, \
GEN_DEFAULT_REGIONS, \
LEGACY_CACHELEVEL
#define I845_FEATURES \
GEN(2), \
.has_3d_pipeline = 1, \
.gpu_reset_clobbers_display = true, \
.hws_needs_physical = 1, \
.unfenced_needs_alignment = 1, \
.platform_engine_mask = BIT(RCS0), \
.has_snoop = true, \
.has_coherent_ggtt = false, \
.dma_mask_size = 32, \
.max_pat_index = 3, \
GEN_DEFAULT_PAGE_SIZES, \
GEN_DEFAULT_REGIONS, \
LEGACY_CACHELEVEL
static const struct intel_device_info i830_info = {
I830_FEATURES,
PLATFORM(INTEL_I830),
};
static const struct intel_device_info i845g_info = {
I845_FEATURES,
PLATFORM(INTEL_I845G),
};
static const struct intel_device_info i85x_info = {
I830_FEATURES,
PLATFORM(INTEL_I85X),
};
static const struct intel_device_info i865g_info = {
I845_FEATURES,
PLATFORM(INTEL_I865G),
};
#define GEN3_FEATURES \
GEN(3), \
.gpu_reset_clobbers_display = true, \
.platform_engine_mask = BIT(RCS0), \
.has_3d_pipeline = 1, \
.has_snoop = true, \
.has_coherent_ggtt = true, \
.dma_mask_size = 32, \
.max_pat_index = 3, \
GEN_DEFAULT_PAGE_SIZES, \
GEN_DEFAULT_REGIONS, \
LEGACY_CACHELEVEL
static const struct intel_device_info i915g_info = {
GEN3_FEATURES,
PLATFORM(INTEL_I915G),
.has_coherent_ggtt = false,
.hws_needs_physical = 1,
.unfenced_needs_alignment = 1,
};
static const struct intel_device_info i915gm_info = {
GEN3_FEATURES,
PLATFORM(INTEL_I915GM),
.is_mobile = 1,
.hws_needs_physical = 1,
.unfenced_needs_alignment = 1,
};
static const struct intel_device_info i945g_info = {
GEN3_FEATURES,
PLATFORM(INTEL_I945G),
.hws_needs_physical = 1,
.unfenced_needs_alignment = 1,
};
static const struct intel_device_info i945gm_info = {
GEN3_FEATURES,
PLATFORM(INTEL_I945GM),
.is_mobile = 1,
.hws_needs_physical = 1,
.unfenced_needs_alignment = 1,
};
static const struct intel_device_info g33_info = {
GEN3_FEATURES,
PLATFORM(INTEL_G33),
.dma_mask_size = 36,
};
static const struct intel_device_info pnv_g_info = {
GEN3_FEATURES,
PLATFORM(INTEL_PINEVIEW),
.dma_mask_size = 36,
};
static const struct intel_device_info pnv_m_info = {
GEN3_FEATURES,
PLATFORM(INTEL_PINEVIEW),
.is_mobile = 1,
.dma_mask_size = 36,
};
#define GEN4_FEATURES \
GEN(4), \
.gpu_reset_clobbers_display = true, \
.platform_engine_mask = BIT(RCS0), \
.has_3d_pipeline = 1, \
.has_snoop = true, \
.has_coherent_ggtt = true, \
.dma_mask_size = 36, \
.max_pat_index = 3, \
GEN_DEFAULT_PAGE_SIZES, \
GEN_DEFAULT_REGIONS, \
LEGACY_CACHELEVEL
static const struct intel_device_info i965g_info = {
GEN4_FEATURES,
PLATFORM(INTEL_I965G),
.hws_needs_physical = 1,
.has_snoop = false,
};
static const struct intel_device_info i965gm_info = {
GEN4_FEATURES,
PLATFORM(INTEL_I965GM),
.is_mobile = 1,
.hws_needs_physical = 1,
.has_snoop = false,
};
static const struct intel_device_info g45_info = {
GEN4_FEATURES,
PLATFORM(INTEL_G45),
.platform_engine_mask = BIT(RCS0) | BIT(VCS0),
.gpu_reset_clobbers_display = false,
};
static const struct intel_device_info gm45_info = {
GEN4_FEATURES,
PLATFORM(INTEL_GM45),
.is_mobile = 1,
.platform_engine_mask = BIT(RCS0) | BIT(VCS0),
.gpu_reset_clobbers_display = false,
};
#define GEN5_FEATURES \
GEN(5), \
.platform_engine_mask = BIT(RCS0) | BIT(VCS0), \
.has_3d_pipeline = 1, \
.has_snoop = true, \
.has_coherent_ggtt = true, \
/* ilk does support rc6, but we do not implement [power] contexts */ \
.has_rc6 = 0, \
.dma_mask_size = 36, \
.max_pat_index = 3, \
GEN_DEFAULT_PAGE_SIZES, \
GEN_DEFAULT_REGIONS, \
LEGACY_CACHELEVEL
static const struct intel_device_info ilk_d_info = {
GEN5_FEATURES,
PLATFORM(INTEL_IRONLAKE),
};
static const struct intel_device_info ilk_m_info = {
GEN5_FEATURES,
PLATFORM(INTEL_IRONLAKE),
.is_mobile = 1,
.has_rps = true,
};
#define GEN6_FEATURES \
GEN(6), \
.platform_engine_mask = BIT(RCS0) | BIT(VCS0) | BIT(BCS0), \
.has_3d_pipeline = 1, \
.has_coherent_ggtt = true, \
.has_llc = 1, \
.has_rc6 = 1, \
/* snb does support rc6p, but enabling it causes various issues */ \
.has_rc6p = 0, \
.has_rps = true, \
.dma_mask_size = 40, \
.max_pat_index = 3, \
.__runtime.ppgtt_type = INTEL_PPGTT_ALIASING, \
.__runtime.ppgtt_size = 31, \
GEN_DEFAULT_PAGE_SIZES, \
GEN_DEFAULT_REGIONS, \
LEGACY_CACHELEVEL
#define SNB_D_PLATFORM \
GEN6_FEATURES, \
PLATFORM(INTEL_SANDYBRIDGE)
static const struct intel_device_info snb_d_gt1_info = {
SNB_D_PLATFORM,
.gt = 1,
};
static const struct intel_device_info snb_d_gt2_info = {
SNB_D_PLATFORM,
.gt = 2,
};
#define SNB_M_PLATFORM \
GEN6_FEATURES, \
PLATFORM(INTEL_SANDYBRIDGE), \
.is_mobile = 1
static const struct intel_device_info snb_m_gt1_info = {
SNB_M_PLATFORM,
.gt = 1,
};
static const struct intel_device_info snb_m_gt2_info = {
SNB_M_PLATFORM,
.gt = 2,
};
#define GEN7_FEATURES \
GEN(7), \
.platform_engine_mask = BIT(RCS0) | BIT(VCS0) | BIT(BCS0), \
.has_3d_pipeline = 1, \
.has_coherent_ggtt = true, \
.has_llc = 1, \
.has_rc6 = 1, \
.has_rc6p = 1, \
.has_reset_engine = true, \
.has_rps = true, \
.dma_mask_size = 40, \
.max_pat_index = 3, \
.__runtime.ppgtt_type = INTEL_PPGTT_ALIASING, \
.__runtime.ppgtt_size = 31, \
GEN_DEFAULT_PAGE_SIZES, \
GEN_DEFAULT_REGIONS, \
LEGACY_CACHELEVEL
#define IVB_D_PLATFORM \
GEN7_FEATURES, \
PLATFORM(INTEL_IVYBRIDGE), \
.has_l3_dpf = 1
static const struct intel_device_info ivb_d_gt1_info = {
IVB_D_PLATFORM,
.gt = 1,
};
static const struct intel_device_info ivb_d_gt2_info = {
IVB_D_PLATFORM,
.gt = 2,
};
#define IVB_M_PLATFORM \
GEN7_FEATURES, \
PLATFORM(INTEL_IVYBRIDGE), \
.is_mobile = 1, \
.has_l3_dpf = 1
static const struct intel_device_info ivb_m_gt1_info = {
IVB_M_PLATFORM,
.gt = 1,
};
static const struct intel_device_info ivb_m_gt2_info = {
IVB_M_PLATFORM,
.gt = 2,
};
static const struct intel_device_info ivb_q_info = {
GEN7_FEATURES,
PLATFORM(INTEL_IVYBRIDGE),
.gt = 2,
.has_l3_dpf = 1,
};
static const struct intel_device_info vlv_info = {
PLATFORM(INTEL_VALLEYVIEW),
GEN(7),
.is_lp = 1,
.has_runtime_pm = 1,
.has_rc6 = 1,
.has_reset_engine = true,
.has_rps = true,
.dma_mask_size = 40,
.max_pat_index = 3,
.__runtime.ppgtt_type = INTEL_PPGTT_ALIASING,
.__runtime.ppgtt_size = 31,
.has_snoop = true,
.has_coherent_ggtt = false,
.platform_engine_mask = BIT(RCS0) | BIT(VCS0) | BIT(BCS0),
GEN_DEFAULT_PAGE_SIZES,
GEN_DEFAULT_REGIONS,
LEGACY_CACHELEVEL,
};
#define G75_FEATURES \
GEN7_FEATURES, \
.platform_engine_mask = BIT(RCS0) | BIT(VCS0) | BIT(BCS0) | BIT(VECS0), \
.has_rc6p = 0 /* RC6p removed-by HSW */, \
.has_runtime_pm = 1
#define HSW_PLATFORM \
G75_FEATURES, \
PLATFORM(INTEL_HASWELL), \
.has_l3_dpf = 1
static const struct intel_device_info hsw_gt1_info = {
HSW_PLATFORM,
.gt = 1,
};
static const struct intel_device_info hsw_gt2_info = {
HSW_PLATFORM,
.gt = 2,
};
static const struct intel_device_info hsw_gt3_info = {
HSW_PLATFORM,
.gt = 3,
};
#define GEN8_FEATURES \
G75_FEATURES, \
GEN(8), \
.has_logical_ring_contexts = 1, \
.dma_mask_size = 39, \
.__runtime.ppgtt_type = INTEL_PPGTT_FULL, \
.__runtime.ppgtt_size = 48, \
.has_64bit_reloc = 1
#define BDW_PLATFORM \
GEN8_FEATURES, \
PLATFORM(INTEL_BROADWELL)
static const struct intel_device_info bdw_gt1_info = {
BDW_PLATFORM,
.gt = 1,
};
static const struct intel_device_info bdw_gt2_info = {
BDW_PLATFORM,
.gt = 2,
};
static const struct intel_device_info bdw_rsvd_info = {
BDW_PLATFORM,
.gt = 3,
/* According to the device ID those devices are GT3, they were
* previously treated as not GT3, keep it like that.
*/
};
static const struct intel_device_info bdw_gt3_info = {
BDW_PLATFORM,
.gt = 3,
.platform_engine_mask =
BIT(RCS0) | BIT(VCS0) | BIT(BCS0) | BIT(VECS0) | BIT(VCS1),
};
static const struct intel_device_info chv_info = {
PLATFORM(INTEL_CHERRYVIEW),
GEN(8),
.is_lp = 1,
.platform_engine_mask = BIT(RCS0) | BIT(VCS0) | BIT(BCS0) | BIT(VECS0),
.has_64bit_reloc = 1,
.has_runtime_pm = 1,
.has_rc6 = 1,
.has_rps = true,
.has_logical_ring_contexts = 1,
.dma_mask_size = 39,
.max_pat_index = 3,
.__runtime.ppgtt_type = INTEL_PPGTT_FULL,
.__runtime.ppgtt_size = 32,
.has_reset_engine = 1,
.has_snoop = true,
.has_coherent_ggtt = false,
GEN_DEFAULT_PAGE_SIZES,
GEN_DEFAULT_REGIONS,
LEGACY_CACHELEVEL,
};
#define GEN9_DEFAULT_PAGE_SIZES \
.__runtime.page_sizes = I915_GTT_PAGE_SIZE_4K | \
I915_GTT_PAGE_SIZE_64K
#define GEN9_FEATURES \
GEN8_FEATURES, \
GEN(9), \
GEN9_DEFAULT_PAGE_SIZES, \
.has_gt_uc = 1
#define SKL_PLATFORM \
GEN9_FEATURES, \
PLATFORM(INTEL_SKYLAKE)
static const struct intel_device_info skl_gt1_info = {
SKL_PLATFORM,
.gt = 1,
};
static const struct intel_device_info skl_gt2_info = {
SKL_PLATFORM,
.gt = 2,
};
#define SKL_GT3_PLUS_PLATFORM \
SKL_PLATFORM, \
.platform_engine_mask = \
BIT(RCS0) | BIT(VCS0) | BIT(BCS0) | BIT(VECS0) | BIT(VCS1)
static const struct intel_device_info skl_gt3_info = {
SKL_GT3_PLUS_PLATFORM,
.gt = 3,
};
static const struct intel_device_info skl_gt4_info = {
SKL_GT3_PLUS_PLATFORM,
.gt = 4,
};
#define GEN9_LP_FEATURES \
GEN(9), \
.is_lp = 1, \
.platform_engine_mask = BIT(RCS0) | BIT(VCS0) | BIT(BCS0) | BIT(VECS0), \
.has_3d_pipeline = 1, \
.has_64bit_reloc = 1, \
.has_runtime_pm = 1, \
.has_rc6 = 1, \
.has_rps = true, \
.has_logical_ring_contexts = 1, \
.has_gt_uc = 1, \
.dma_mask_size = 39, \
.__runtime.ppgtt_type = INTEL_PPGTT_FULL, \
.__runtime.ppgtt_size = 48, \
.has_reset_engine = 1, \
.has_snoop = true, \
.has_coherent_ggtt = false, \
.max_pat_index = 3, \
GEN9_DEFAULT_PAGE_SIZES, \
GEN_DEFAULT_REGIONS, \
LEGACY_CACHELEVEL
static const struct intel_device_info bxt_info = {
GEN9_LP_FEATURES,
PLATFORM(INTEL_BROXTON),
};
static const struct intel_device_info glk_info = {
GEN9_LP_FEATURES,
PLATFORM(INTEL_GEMINILAKE),
};
#define KBL_PLATFORM \
GEN9_FEATURES, \
PLATFORM(INTEL_KABYLAKE)
static const struct intel_device_info kbl_gt1_info = {
KBL_PLATFORM,
.gt = 1,
};
static const struct intel_device_info kbl_gt2_info = {
KBL_PLATFORM,
.gt = 2,
};
static const struct intel_device_info kbl_gt3_info = {
KBL_PLATFORM,
.gt = 3,
.platform_engine_mask =
BIT(RCS0) | BIT(VCS0) | BIT(BCS0) | BIT(VECS0) | BIT(VCS1),
};
#define CFL_PLATFORM \
GEN9_FEATURES, \
PLATFORM(INTEL_COFFEELAKE)
static const struct intel_device_info cfl_gt1_info = {
CFL_PLATFORM,
.gt = 1,
};
static const struct intel_device_info cfl_gt2_info = {
CFL_PLATFORM,
.gt = 2,
};
static const struct intel_device_info cfl_gt3_info = {
CFL_PLATFORM,
.gt = 3,
.platform_engine_mask =
BIT(RCS0) | BIT(VCS0) | BIT(BCS0) | BIT(VECS0) | BIT(VCS1),
};
#define CML_PLATFORM \
GEN9_FEATURES, \
PLATFORM(INTEL_COMETLAKE)
static const struct intel_device_info cml_gt1_info = {
CML_PLATFORM,
.gt = 1,
};
static const struct intel_device_info cml_gt2_info = {
CML_PLATFORM,
.gt = 2,
};
#define GEN11_DEFAULT_PAGE_SIZES \
.__runtime.page_sizes = I915_GTT_PAGE_SIZE_4K | \
I915_GTT_PAGE_SIZE_64K | \
I915_GTT_PAGE_SIZE_2M
#define GEN11_FEATURES \
GEN9_FEATURES, \
GEN11_DEFAULT_PAGE_SIZES, \
GEN(11), \
.has_coherent_ggtt = false, \
.has_logical_ring_elsq = 1
static const struct intel_device_info icl_info = {
GEN11_FEATURES,
PLATFORM(INTEL_ICELAKE),
.platform_engine_mask =
BIT(RCS0) | BIT(BCS0) | BIT(VECS0) | BIT(VCS0) | BIT(VCS2),
};
static const struct intel_device_info ehl_info = {
GEN11_FEATURES,
PLATFORM(INTEL_ELKHARTLAKE),
.platform_engine_mask = BIT(RCS0) | BIT(BCS0) | BIT(VCS0) | BIT(VECS0),
.__runtime.ppgtt_size = 36,
};
static const struct intel_device_info jsl_info = {
GEN11_FEATURES,
PLATFORM(INTEL_JASPERLAKE),
.platform_engine_mask = BIT(RCS0) | BIT(BCS0) | BIT(VCS0) | BIT(VECS0),
.__runtime.ppgtt_size = 36,
};
#define GEN12_FEATURES \
GEN11_FEATURES, \
GEN(12), \
TGL_CACHELEVEL, \
.has_global_mocs = 1, \
.has_pxp = 1, \
.max_pat_index = 3
static const struct intel_device_info tgl_info = {
GEN12_FEATURES,
PLATFORM(INTEL_TIGERLAKE),
.platform_engine_mask =
BIT(RCS0) | BIT(BCS0) | BIT(VECS0) | BIT(VCS0) | BIT(VCS2),
};
static const struct intel_device_info rkl_info = {
GEN12_FEATURES,
PLATFORM(INTEL_ROCKETLAKE),
.platform_engine_mask =
BIT(RCS0) | BIT(BCS0) | BIT(VECS0) | BIT(VCS0),
};
#define DGFX_FEATURES \
.memory_regions = REGION_SMEM | REGION_LMEM | REGION_STOLEN_LMEM, \
.has_llc = 0, \
.has_pxp = 0, \
.has_snoop = 1, \
.is_dgfx = 1, \
.has_heci_gscfi = 1
static const struct intel_device_info dg1_info = {
GEN12_FEATURES,
DGFX_FEATURES,
.__runtime.graphics.ip.rel = 10,
PLATFORM(INTEL_DG1),
.require_force_probe = 1,
.platform_engine_mask =
BIT(RCS0) | BIT(BCS0) | BIT(VECS0) |
BIT(VCS0) | BIT(VCS2),
/* Wa_16011227922 */
.__runtime.ppgtt_size = 47,
};
static const struct intel_device_info adl_s_info = {
GEN12_FEATURES,
PLATFORM(INTEL_ALDERLAKE_S),
.platform_engine_mask =
BIT(RCS0) | BIT(BCS0) | BIT(VECS0) | BIT(VCS0) | BIT(VCS2),
.dma_mask_size = 39,
};
static const struct intel_device_info adl_p_info = {
GEN12_FEATURES,
PLATFORM(INTEL_ALDERLAKE_P),
.platform_engine_mask =
BIT(RCS0) | BIT(BCS0) | BIT(VECS0) | BIT(VCS0) | BIT(VCS2),
.__runtime.ppgtt_size = 48,
.dma_mask_size = 39,
};
#undef GEN
#define XE_HP_PAGE_SIZES \
.__runtime.page_sizes = I915_GTT_PAGE_SIZE_4K | \
I915_GTT_PAGE_SIZE_64K | \
I915_GTT_PAGE_SIZE_2M
#define XE_HP_FEATURES \
.__runtime.graphics.ip.ver = 12, \
.__runtime.graphics.ip.rel = 50, \
XE_HP_PAGE_SIZES, \
TGL_CACHELEVEL, \
.dma_mask_size = 46, \
.has_3d_pipeline = 1, \
.has_64bit_reloc = 1, \
.has_flat_ccs = 1, \
.has_4tile = 1, \
.has_global_mocs = 1, \
.has_gt_uc = 1, \
.has_llc = 1, \
.has_logical_ring_contexts = 1, \
.has_logical_ring_elsq = 1, \
.has_mslice_steering = 1, \
.has_oa_bpc_reporting = 1, \
.has_oa_slice_contrib_limits = 1, \
.has_oam = 1, \
.has_rc6 = 1, \
.has_reset_engine = 1, \
.has_rps = 1, \
.has_runtime_pm = 1, \
.max_pat_index = 3, \
.__runtime.ppgtt_size = 48, \
.__runtime.ppgtt_type = INTEL_PPGTT_FULL
#define XE_HPM_FEATURES \
.__runtime.media.ip.ver = 12, \
.__runtime.media.ip.rel = 50
__maybe_unused
static const struct intel_device_info xehpsdv_info = {
XE_HP_FEATURES,
XE_HPM_FEATURES,
DGFX_FEATURES,
PLATFORM(INTEL_XEHPSDV),
.has_64k_pages = 1,
.has_media_ratio_mode = 1,
.platform_engine_mask =
BIT(RCS0) | BIT(BCS0) |
BIT(VECS0) | BIT(VECS1) | BIT(VECS2) | BIT(VECS3) |
BIT(VCS0) | BIT(VCS1) | BIT(VCS2) | BIT(VCS3) |
BIT(VCS4) | BIT(VCS5) | BIT(VCS6) | BIT(VCS7) |
BIT(CCS0) | BIT(CCS1) | BIT(CCS2) | BIT(CCS3),
.require_force_probe = 1,
};
#define DG2_FEATURES \
XE_HP_FEATURES, \
XE_HPM_FEATURES, \
DGFX_FEATURES, \
.__runtime.graphics.ip.rel = 55, \
.__runtime.media.ip.rel = 55, \
PLATFORM(INTEL_DG2), \
.has_64k_pages = 1, \
.has_guc_deprivilege = 1, \
.has_heci_pxp = 1, \
.has_media_ratio_mode = 1, \
.platform_engine_mask = \
BIT(RCS0) | BIT(BCS0) | \
BIT(VECS0) | BIT(VECS1) | \
BIT(VCS0) | BIT(VCS2) | \
BIT(CCS0) | BIT(CCS1) | BIT(CCS2) | BIT(CCS3)
static const struct intel_device_info dg2_info = {
DG2_FEATURES,
};
static const struct intel_device_info ats_m_info = {
DG2_FEATURES,
.require_force_probe = 1,
.tuning_thread_rr_after_dep = 1,
};
#define XE_HPC_FEATURES \
XE_HP_FEATURES, \
.dma_mask_size = 52, \
.has_3d_pipeline = 0, \
.has_guc_deprivilege = 1, \
.has_l3_ccs_read = 1, \
.has_mslice_steering = 0, \
.has_one_eu_per_fuse_bit = 1
__maybe_unused
static const struct intel_device_info pvc_info = {
XE_HPC_FEATURES,
XE_HPM_FEATURES,
DGFX_FEATURES,
.__runtime.graphics.ip.rel = 60,
.__runtime.media.ip.rel = 60,
PLATFORM(INTEL_PONTEVECCHIO),
.has_flat_ccs = 0,
.max_pat_index = 7,
.platform_engine_mask =
BIT(BCS0) |
BIT(VCS0) |
BIT(CCS0) | BIT(CCS1) | BIT(CCS2) | BIT(CCS3),
.require_force_probe = 1,
PVC_CACHELEVEL,
};
static const struct intel_gt_definition xelpmp_extra_gt[] = {
{
.type = GT_MEDIA,
.name = "Standalone Media GT",
.gsi_offset = MTL_MEDIA_GSI_BASE,
.engine_mask = BIT(VECS0) | BIT(VCS0) | BIT(VCS2) | BIT(GSC0),
},
{}
};
static const struct intel_device_info mtl_info = {
XE_HP_FEATURES,
/*
* Real graphics IP version will be obtained from hardware GMD_ID
* register. Value provided here is just for sanity checking.
*/
.__runtime.graphics.ip.ver = 12,
.__runtime.graphics.ip.rel = 70,
.__runtime.media.ip.ver = 13,
PLATFORM(INTEL_METEORLAKE),
.extra_gt_list = xelpmp_extra_gt,
.has_flat_ccs = 0,
.has_gmd_id = 1,
.has_guc_deprivilege = 1,
.has_llc = 0,
.has_mslice_steering = 0,
.has_snoop = 1,
.max_pat_index = 4,
.has_pxp = 1,
.memory_regions = REGION_SMEM | REGION_STOLEN_LMEM,
.platform_engine_mask = BIT(RCS0) | BIT(BCS0) | BIT(CCS0),
.require_force_probe = 1,
MTL_CACHELEVEL,
};
#undef PLATFORM
/*
* Make sure any device matches here are from most specific to most
* general. For example, since the Quanta match is based on the subsystem
* and subvendor IDs, we need it to come before the more general IVB
* PCI ID matches, otherwise we'll use the wrong info struct above.
*/
static const struct pci_device_id pciidlist[] = {
INTEL_I830_IDS(&i830_info),
INTEL_I845G_IDS(&i845g_info),
INTEL_I85X_IDS(&i85x_info),
INTEL_I865G_IDS(&i865g_info),
INTEL_I915G_IDS(&i915g_info),
INTEL_I915GM_IDS(&i915gm_info),
INTEL_I945G_IDS(&i945g_info),
INTEL_I945GM_IDS(&i945gm_info),
INTEL_I965G_IDS(&i965g_info),
INTEL_G33_IDS(&g33_info),
INTEL_I965GM_IDS(&i965gm_info),
INTEL_GM45_IDS(&gm45_info),
INTEL_G45_IDS(&g45_info),
INTEL_PINEVIEW_G_IDS(&pnv_g_info),
INTEL_PINEVIEW_M_IDS(&pnv_m_info),
INTEL_IRONLAKE_D_IDS(&ilk_d_info),
INTEL_IRONLAKE_M_IDS(&ilk_m_info),
INTEL_SNB_D_GT1_IDS(&snb_d_gt1_info),
INTEL_SNB_D_GT2_IDS(&snb_d_gt2_info),
INTEL_SNB_M_GT1_IDS(&snb_m_gt1_info),
INTEL_SNB_M_GT2_IDS(&snb_m_gt2_info),
INTEL_IVB_Q_IDS(&ivb_q_info), /* must be first IVB */
INTEL_IVB_M_GT1_IDS(&ivb_m_gt1_info),
INTEL_IVB_M_GT2_IDS(&ivb_m_gt2_info),
INTEL_IVB_D_GT1_IDS(&ivb_d_gt1_info),
INTEL_IVB_D_GT2_IDS(&ivb_d_gt2_info),
INTEL_HSW_GT1_IDS(&hsw_gt1_info),
INTEL_HSW_GT2_IDS(&hsw_gt2_info),
INTEL_HSW_GT3_IDS(&hsw_gt3_info),
INTEL_VLV_IDS(&vlv_info),
INTEL_BDW_GT1_IDS(&bdw_gt1_info),
INTEL_BDW_GT2_IDS(&bdw_gt2_info),
INTEL_BDW_GT3_IDS(&bdw_gt3_info),
INTEL_BDW_RSVD_IDS(&bdw_rsvd_info),
INTEL_CHV_IDS(&chv_info),
INTEL_SKL_GT1_IDS(&skl_gt1_info),
INTEL_SKL_GT2_IDS(&skl_gt2_info),
INTEL_SKL_GT3_IDS(&skl_gt3_info),
INTEL_SKL_GT4_IDS(&skl_gt4_info),
INTEL_BXT_IDS(&bxt_info),
INTEL_GLK_IDS(&glk_info),
INTEL_KBL_GT1_IDS(&kbl_gt1_info),
INTEL_KBL_GT2_IDS(&kbl_gt2_info),
INTEL_KBL_GT3_IDS(&kbl_gt3_info),
INTEL_KBL_GT4_IDS(&kbl_gt3_info),
INTEL_AML_KBL_GT2_IDS(&kbl_gt2_info),
INTEL_CFL_S_GT1_IDS(&cfl_gt1_info),
INTEL_CFL_S_GT2_IDS(&cfl_gt2_info),
INTEL_CFL_H_GT1_IDS(&cfl_gt1_info),
INTEL_CFL_H_GT2_IDS(&cfl_gt2_info),
INTEL_CFL_U_GT2_IDS(&cfl_gt2_info),
INTEL_CFL_U_GT3_IDS(&cfl_gt3_info),
INTEL_WHL_U_GT1_IDS(&cfl_gt1_info),
INTEL_WHL_U_GT2_IDS(&cfl_gt2_info),
INTEL_AML_CFL_GT2_IDS(&cfl_gt2_info),
INTEL_WHL_U_GT3_IDS(&cfl_gt3_info),
INTEL_CML_GT1_IDS(&cml_gt1_info),
INTEL_CML_GT2_IDS(&cml_gt2_info),
INTEL_CML_U_GT1_IDS(&cml_gt1_info),
INTEL_CML_U_GT2_IDS(&cml_gt2_info),
INTEL_ICL_11_IDS(&icl_info),
INTEL_EHL_IDS(&ehl_info),
INTEL_JSL_IDS(&jsl_info),
INTEL_TGL_12_IDS(&tgl_info),
INTEL_RKL_IDS(&rkl_info),
INTEL_ADLS_IDS(&adl_s_info),
INTEL_ADLP_IDS(&adl_p_info),
INTEL_ADLN_IDS(&adl_p_info),
INTEL_DG1_IDS(&dg1_info),
INTEL_RPLS_IDS(&adl_s_info),
INTEL_RPLP_IDS(&adl_p_info),
INTEL_DG2_IDS(&dg2_info),
INTEL_ATS_M_IDS(&ats_m_info),
INTEL_MTL_IDS(&mtl_info),
{0, 0, 0}
};
MODULE_DEVICE_TABLE(pci, pciidlist);
static void i915_pci_remove(struct pci_dev *pdev)
{
struct drm_i915_private *i915;
i915 = pci_get_drvdata(pdev);
if (!i915) /* driver load aborted, nothing to cleanup */
return;
i915_driver_remove(i915);
pci_set_drvdata(pdev, NULL);
}
/* is device_id present in comma separated list of ids */
static bool device_id_in_list(u16 device_id, const char *devices, bool negative)
{
char *s, *p, *tok;
bool ret;
if (!devices || !*devices)
return false;
/* match everything */
if (negative && strcmp(devices, "!*") == 0)
return true;
if (!negative && strcmp(devices, "*") == 0)
return true;
s = kstrdup(devices, GFP_KERNEL);
if (!s)
return false;
for (p = s, ret = false; (tok = strsep(&p, ",")) != NULL; ) {
u16 val;
if (negative && tok[0] == '!')
tok++;
else if ((negative && tok[0] != '!') ||
(!negative && tok[0] == '!'))
continue;
if (kstrtou16(tok, 16, &val) == 0 && val == device_id) {
ret = true;
break;
}
}
kfree(s);
return ret;
}
static bool id_forced(u16 device_id)
{
return device_id_in_list(device_id, i915_modparams.force_probe, false);
}
static bool id_blocked(u16 device_id)
{
return device_id_in_list(device_id, i915_modparams.force_probe, true);
}
bool i915_pci_resource_valid(struct pci_dev *pdev, int bar)
{
if (!pci_resource_flags(pdev, bar))
return false;
if (pci_resource_flags(pdev, bar) & IORESOURCE_UNSET)
return false;
if (!pci_resource_len(pdev, bar))
return false;
return true;
}
static bool intel_mmio_bar_valid(struct pci_dev *pdev, struct intel_device_info *intel_info)
{
return i915_pci_resource_valid(pdev, intel_mmio_bar(intel_info->__runtime.graphics.ip.ver));
}
static int i915_pci_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
struct intel_device_info *intel_info =
(struct intel_device_info *) ent->driver_data;
int err;
if (intel_info->require_force_probe && !id_forced(pdev->device)) {
dev_info(&pdev->dev,
"Your graphics device %04x is not properly supported by i915 in this\n"
"kernel version. To force driver probe anyway, use i915.force_probe=%04x\n"
"module parameter or CONFIG_DRM_I915_FORCE_PROBE=%04x configuration option,\n"
"or (recommended) check for kernel updates.\n",
pdev->device, pdev->device, pdev->device);
return -ENODEV;
}
if (id_blocked(pdev->device)) {
dev_info(&pdev->dev, "I915 probe blocked for Device ID %04x.\n",
pdev->device);
return -ENODEV;
}
if (intel_info->require_force_probe) {
dev_info(&pdev->dev, "Force probing unsupported Device ID %04x, tainting kernel\n",
pdev->device);
add_taint(TAINT_USER, LOCKDEP_STILL_OK);
}
/* Only bind to function 0 of the device. Early generations
* used function 1 as a placeholder for multi-head. This causes
* us confusion instead, especially on the systems where both
* functions have the same PCI-ID!
*/
if (PCI_FUNC(pdev->devfn))
return -ENODEV;
if (!intel_mmio_bar_valid(pdev, intel_info))
return -ENXIO;
/* Detect if we need to wait for other drivers early on */
if (intel_display_driver_probe_defer(pdev))
return -EPROBE_DEFER;
err = i915_driver_probe(pdev, ent);
if (err)
return err;
if (i915_inject_probe_failure(pci_get_drvdata(pdev))) {
i915_pci_remove(pdev);
return -ENODEV;
}
err = i915_live_selftests(pdev);
if (err) {
i915_pci_remove(pdev);
return err > 0 ? -ENOTTY : err;
}
err = i915_perf_selftests(pdev);
if (err) {
i915_pci_remove(pdev);
return err > 0 ? -ENOTTY : err;
}
return 0;
}
static void i915_pci_shutdown(struct pci_dev *pdev)
{
struct drm_i915_private *i915 = pci_get_drvdata(pdev);
i915_driver_shutdown(i915);
}
static struct pci_driver i915_pci_driver = {
.name = DRIVER_NAME,
.id_table = pciidlist,
.probe = i915_pci_probe,
.remove = i915_pci_remove,
.shutdown = i915_pci_shutdown,
.driver.pm = &i915_pm_ops,
};
int i915_pci_register_driver(void)
{
return pci_register_driver(&i915_pci_driver);
}
void i915_pci_unregister_driver(void)
{
pci_unregister_driver(&i915_pci_driver);
}
| linux-master | drivers/gpu/drm/i915/i915_pci.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2013-2021 Intel Corporation
*
* LPT/WPT IOSF sideband.
*/
#include "i915_drv.h"
#include "intel_sbi.h"
#include "i915_reg.h"
/* SBI access */
static int intel_sbi_rw(struct drm_i915_private *i915, u16 reg,
enum intel_sbi_destination destination,
u32 *val, bool is_read)
{
struct intel_uncore *uncore = &i915->uncore;
u32 cmd;
lockdep_assert_held(&i915->sb_lock);
if (intel_wait_for_register_fw(uncore,
SBI_CTL_STAT, SBI_BUSY, 0,
100)) {
drm_err(&i915->drm,
"timeout waiting for SBI to become ready\n");
return -EBUSY;
}
intel_uncore_write_fw(uncore, SBI_ADDR, (u32)reg << 16);
intel_uncore_write_fw(uncore, SBI_DATA, is_read ? 0 : *val);
if (destination == SBI_ICLK)
cmd = SBI_CTL_DEST_ICLK | SBI_CTL_OP_CRRD;
else
cmd = SBI_CTL_DEST_MPHY | SBI_CTL_OP_IORD;
if (!is_read)
cmd |= BIT(8);
intel_uncore_write_fw(uncore, SBI_CTL_STAT, cmd | SBI_BUSY);
if (__intel_wait_for_register_fw(uncore,
SBI_CTL_STAT, SBI_BUSY, 0,
100, 100, &cmd)) {
drm_err(&i915->drm,
"timeout waiting for SBI to complete read\n");
return -ETIMEDOUT;
}
if (cmd & SBI_RESPONSE_FAIL) {
drm_err(&i915->drm, "error during SBI read of reg %x\n", reg);
return -ENXIO;
}
if (is_read)
*val = intel_uncore_read_fw(uncore, SBI_DATA);
return 0;
}
u32 intel_sbi_read(struct drm_i915_private *i915, u16 reg,
enum intel_sbi_destination destination)
{
u32 result = 0;
intel_sbi_rw(i915, reg, destination, &result, true);
return result;
}
void intel_sbi_write(struct drm_i915_private *i915, u16 reg, u32 value,
enum intel_sbi_destination destination)
{
intel_sbi_rw(i915, reg, destination, &value, false);
}
| linux-master | drivers/gpu/drm/i915/intel_sbi.c |
/*
* Copyright © 2016 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
#include <linux/kernel.h>
#include <asm/fpu/api.h>
#include "i915_memcpy.h"
#if IS_ENABLED(CONFIG_DRM_I915_DEBUG)
#define CI_BUG_ON(expr) BUG_ON(expr)
#else
#define CI_BUG_ON(expr) BUILD_BUG_ON_INVALID(expr)
#endif
static DEFINE_STATIC_KEY_FALSE(has_movntdqa);
static void __memcpy_ntdqa(void *dst, const void *src, unsigned long len)
{
kernel_fpu_begin();
while (len >= 4) {
asm("movntdqa (%0), %%xmm0\n"
"movntdqa 16(%0), %%xmm1\n"
"movntdqa 32(%0), %%xmm2\n"
"movntdqa 48(%0), %%xmm3\n"
"movaps %%xmm0, (%1)\n"
"movaps %%xmm1, 16(%1)\n"
"movaps %%xmm2, 32(%1)\n"
"movaps %%xmm3, 48(%1)\n"
:: "r" (src), "r" (dst) : "memory");
src += 64;
dst += 64;
len -= 4;
}
while (len--) {
asm("movntdqa (%0), %%xmm0\n"
"movaps %%xmm0, (%1)\n"
:: "r" (src), "r" (dst) : "memory");
src += 16;
dst += 16;
}
kernel_fpu_end();
}
static void __memcpy_ntdqu(void *dst, const void *src, unsigned long len)
{
kernel_fpu_begin();
while (len >= 4) {
asm("movntdqa (%0), %%xmm0\n"
"movntdqa 16(%0), %%xmm1\n"
"movntdqa 32(%0), %%xmm2\n"
"movntdqa 48(%0), %%xmm3\n"
"movups %%xmm0, (%1)\n"
"movups %%xmm1, 16(%1)\n"
"movups %%xmm2, 32(%1)\n"
"movups %%xmm3, 48(%1)\n"
:: "r" (src), "r" (dst) : "memory");
src += 64;
dst += 64;
len -= 4;
}
while (len--) {
asm("movntdqa (%0), %%xmm0\n"
"movups %%xmm0, (%1)\n"
:: "r" (src), "r" (dst) : "memory");
src += 16;
dst += 16;
}
kernel_fpu_end();
}
/**
* i915_memcpy_from_wc: perform an accelerated *aligned* read from WC
* @dst: destination pointer
* @src: source pointer
* @len: how many bytes to copy
*
* i915_memcpy_from_wc copies @len bytes from @src to @dst using
* non-temporal instructions where available. Note that all arguments
* (@src, @dst) must be aligned to 16 bytes and @len must be a multiple
* of 16.
*
* To test whether accelerated reads from WC are supported, use
* i915_memcpy_from_wc(NULL, NULL, 0);
*
* Returns true if the copy was successful, false if the preconditions
* are not met.
*/
bool i915_memcpy_from_wc(void *dst, const void *src, unsigned long len)
{
if (unlikely(((unsigned long)dst | (unsigned long)src | len) & 15))
return false;
if (static_branch_likely(&has_movntdqa)) {
if (likely(len))
__memcpy_ntdqa(dst, src, len >> 4);
return true;
}
return false;
}
/**
* i915_unaligned_memcpy_from_wc: perform a mostly accelerated read from WC
* @dst: destination pointer
* @src: source pointer
* @len: how many bytes to copy
*
* Like i915_memcpy_from_wc(), the unaligned variant copies @len bytes from
* @src to @dst using * non-temporal instructions where available, but
* accepts that its arguments may not be aligned, but are valid for the
* potential 16-byte read past the end.
*/
void i915_unaligned_memcpy_from_wc(void *dst, const void *src, unsigned long len)
{
unsigned long addr;
CI_BUG_ON(!i915_has_memcpy_from_wc());
addr = (unsigned long)src;
if (!IS_ALIGNED(addr, 16)) {
unsigned long x = min(ALIGN(addr, 16) - addr, len);
memcpy(dst, src, x);
len -= x;
dst += x;
src += x;
}
if (likely(len))
__memcpy_ntdqu(dst, src, DIV_ROUND_UP(len, 16));
}
void i915_memcpy_init_early(struct drm_i915_private *dev_priv)
{
/*
* Some hypervisors (e.g. KVM) don't support VEX-prefix instructions
* emulation. So don't enable movntdqa in hypervisor guest.
*/
if (static_cpu_has(X86_FEATURE_XMM4_1) &&
!boot_cpu_has(X86_FEATURE_HYPERVISOR))
static_branch_enable(&has_movntdqa);
}
| linux-master | drivers/gpu/drm/i915/i915_memcpy.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2013-2021 Intel Corporation
*/
#include "i915_drv.h"
#include "i915_reg.h"
#include "intel_pcode.h"
static int gen6_check_mailbox_status(u32 mbox)
{
switch (mbox & GEN6_PCODE_ERROR_MASK) {
case GEN6_PCODE_SUCCESS:
return 0;
case GEN6_PCODE_UNIMPLEMENTED_CMD:
return -ENODEV;
case GEN6_PCODE_ILLEGAL_CMD:
return -ENXIO;
case GEN6_PCODE_MIN_FREQ_TABLE_GT_RATIO_OUT_OF_RANGE:
case GEN7_PCODE_MIN_FREQ_TABLE_GT_RATIO_OUT_OF_RANGE:
return -EOVERFLOW;
case GEN6_PCODE_TIMEOUT:
return -ETIMEDOUT;
default:
MISSING_CASE(mbox & GEN6_PCODE_ERROR_MASK);
return 0;
}
}
static int gen7_check_mailbox_status(u32 mbox)
{
switch (mbox & GEN6_PCODE_ERROR_MASK) {
case GEN6_PCODE_SUCCESS:
return 0;
case GEN6_PCODE_ILLEGAL_CMD:
return -ENXIO;
case GEN7_PCODE_TIMEOUT:
return -ETIMEDOUT;
case GEN7_PCODE_ILLEGAL_DATA:
return -EINVAL;
case GEN11_PCODE_ILLEGAL_SUBCOMMAND:
return -ENXIO;
case GEN11_PCODE_LOCKED:
return -EBUSY;
case GEN11_PCODE_REJECTED:
return -EACCES;
case GEN7_PCODE_MIN_FREQ_TABLE_GT_RATIO_OUT_OF_RANGE:
return -EOVERFLOW;
default:
MISSING_CASE(mbox & GEN6_PCODE_ERROR_MASK);
return 0;
}
}
static int __snb_pcode_rw(struct intel_uncore *uncore, u32 mbox,
u32 *val, u32 *val1,
int fast_timeout_us, int slow_timeout_ms,
bool is_read)
{
lockdep_assert_held(&uncore->i915->sb_lock);
/*
* GEN6_PCODE_* are outside of the forcewake domain, we can use
* intel_uncore_read/write_fw variants to reduce the amount of work
* required when reading/writing.
*/
if (intel_uncore_read_fw(uncore, GEN6_PCODE_MAILBOX) & GEN6_PCODE_READY)
return -EAGAIN;
intel_uncore_write_fw(uncore, GEN6_PCODE_DATA, *val);
intel_uncore_write_fw(uncore, GEN6_PCODE_DATA1, val1 ? *val1 : 0);
intel_uncore_write_fw(uncore,
GEN6_PCODE_MAILBOX, GEN6_PCODE_READY | mbox);
if (__intel_wait_for_register_fw(uncore,
GEN6_PCODE_MAILBOX,
GEN6_PCODE_READY, 0,
fast_timeout_us,
slow_timeout_ms,
&mbox))
return -ETIMEDOUT;
if (is_read)
*val = intel_uncore_read_fw(uncore, GEN6_PCODE_DATA);
if (is_read && val1)
*val1 = intel_uncore_read_fw(uncore, GEN6_PCODE_DATA1);
if (GRAPHICS_VER(uncore->i915) > 6)
return gen7_check_mailbox_status(mbox);
else
return gen6_check_mailbox_status(mbox);
}
int snb_pcode_read(struct intel_uncore *uncore, u32 mbox, u32 *val, u32 *val1)
{
int err;
mutex_lock(&uncore->i915->sb_lock);
err = __snb_pcode_rw(uncore, mbox, val, val1, 500, 20, true);
mutex_unlock(&uncore->i915->sb_lock);
if (err) {
drm_dbg(&uncore->i915->drm,
"warning: pcode (read from mbox %x) mailbox access failed for %ps: %d\n",
mbox, __builtin_return_address(0), err);
}
return err;
}
int snb_pcode_write_timeout(struct intel_uncore *uncore, u32 mbox, u32 val,
int fast_timeout_us, int slow_timeout_ms)
{
int err;
mutex_lock(&uncore->i915->sb_lock);
err = __snb_pcode_rw(uncore, mbox, &val, NULL,
fast_timeout_us, slow_timeout_ms, false);
mutex_unlock(&uncore->i915->sb_lock);
if (err) {
drm_dbg(&uncore->i915->drm,
"warning: pcode (write of 0x%08x to mbox %x) mailbox access failed for %ps: %d\n",
val, mbox, __builtin_return_address(0), err);
}
return err;
}
static bool skl_pcode_try_request(struct intel_uncore *uncore, u32 mbox,
u32 request, u32 reply_mask, u32 reply,
u32 *status)
{
*status = __snb_pcode_rw(uncore, mbox, &request, NULL, 500, 0, true);
return (*status == 0) && ((request & reply_mask) == reply);
}
/**
* skl_pcode_request - send PCODE request until acknowledgment
* @uncore: uncore
* @mbox: PCODE mailbox ID the request is targeted for
* @request: request ID
* @reply_mask: mask used to check for request acknowledgment
* @reply: value used to check for request acknowledgment
* @timeout_base_ms: timeout for polling with preemption enabled
*
* Keep resending the @request to @mbox until PCODE acknowledges it, PCODE
* reports an error or an overall timeout of @timeout_base_ms+50 ms expires.
* The request is acknowledged once the PCODE reply dword equals @reply after
* applying @reply_mask. Polling is first attempted with preemption enabled
* for @timeout_base_ms and if this times out for another 50 ms with
* preemption disabled.
*
* Returns 0 on success, %-ETIMEDOUT in case of a timeout, <0 in case of some
* other error as reported by PCODE.
*/
int skl_pcode_request(struct intel_uncore *uncore, u32 mbox, u32 request,
u32 reply_mask, u32 reply, int timeout_base_ms)
{
u32 status;
int ret;
mutex_lock(&uncore->i915->sb_lock);
#define COND \
skl_pcode_try_request(uncore, mbox, request, reply_mask, reply, &status)
/*
* Prime the PCODE by doing a request first. Normally it guarantees
* that a subsequent request, at most @timeout_base_ms later, succeeds.
* _wait_for() doesn't guarantee when its passed condition is evaluated
* first, so send the first request explicitly.
*/
if (COND) {
ret = 0;
goto out;
}
ret = _wait_for(COND, timeout_base_ms * 1000, 10, 10);
if (!ret)
goto out;
/*
* The above can time out if the number of requests was low (2 in the
* worst case) _and_ PCODE was busy for some reason even after a
* (queued) request and @timeout_base_ms delay. As a workaround retry
* the poll with preemption disabled to maximize the number of
* requests. Increase the timeout from @timeout_base_ms to 50ms to
* account for interrupts that could reduce the number of these
* requests, and for any quirks of the PCODE firmware that delays
* the request completion.
*/
drm_dbg_kms(&uncore->i915->drm,
"PCODE timeout, retrying with preemption disabled\n");
drm_WARN_ON_ONCE(&uncore->i915->drm, timeout_base_ms > 3);
preempt_disable();
ret = wait_for_atomic(COND, 50);
preempt_enable();
out:
mutex_unlock(&uncore->i915->sb_lock);
return status ? status : ret;
#undef COND
}
static int pcode_init_wait(struct intel_uncore *uncore, int timeout_ms)
{
if (__intel_wait_for_register_fw(uncore,
GEN6_PCODE_MAILBOX,
GEN6_PCODE_READY, 0,
500, timeout_ms,
NULL))
return -EPROBE_DEFER;
return skl_pcode_request(uncore,
DG1_PCODE_STATUS,
DG1_UNCORE_GET_INIT_STATUS,
DG1_UNCORE_INIT_STATUS_COMPLETE,
DG1_UNCORE_INIT_STATUS_COMPLETE, timeout_ms);
}
int intel_pcode_init(struct intel_uncore *uncore)
{
int err;
if (!IS_DGFX(uncore->i915))
return 0;
/*
* Wait 10 seconds so that the punit to settle and complete
* any outstanding transactions upon module load
*/
err = pcode_init_wait(uncore, 10000);
if (err) {
drm_notice(&uncore->i915->drm,
"Waiting for HW initialisation...\n");
err = pcode_init_wait(uncore, 180000);
}
return err;
}
int snb_pcode_read_p(struct intel_uncore *uncore, u32 mbcmd, u32 p1, u32 p2, u32 *val)
{
intel_wakeref_t wakeref;
u32 mbox;
int err;
mbox = REG_FIELD_PREP(GEN6_PCODE_MB_COMMAND, mbcmd)
| REG_FIELD_PREP(GEN6_PCODE_MB_PARAM1, p1)
| REG_FIELD_PREP(GEN6_PCODE_MB_PARAM2, p2);
with_intel_runtime_pm(uncore->rpm, wakeref)
err = snb_pcode_read(uncore, mbox, val, NULL);
return err;
}
int snb_pcode_write_p(struct intel_uncore *uncore, u32 mbcmd, u32 p1, u32 p2, u32 val)
{
intel_wakeref_t wakeref;
u32 mbox;
int err;
mbox = REG_FIELD_PREP(GEN6_PCODE_MB_COMMAND, mbcmd)
| REG_FIELD_PREP(GEN6_PCODE_MB_PARAM1, p1)
| REG_FIELD_PREP(GEN6_PCODE_MB_PARAM2, p2);
with_intel_runtime_pm(uncore->rpm, wakeref)
err = snb_pcode_write(uncore, mbox, val);
return err;
}
| linux-master | drivers/gpu/drm/i915/intel_pcode.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2019 Intel Corporation
*/
#include <linux/device.h>
#include <drm/drm_drv.h>
#include "i915_drv.h"
#include "i915_utils.h"
#define FDO_BUG_MSG "Please file a bug on drm/i915; see " FDO_BUG_URL " for details."
void
__i915_printk(struct drm_i915_private *dev_priv, const char *level,
const char *fmt, ...)
{
static bool shown_bug_once;
struct device *kdev = dev_priv->drm.dev;
bool is_error = level[1] <= KERN_ERR[1];
bool is_debug = level[1] == KERN_DEBUG[1];
struct va_format vaf;
va_list args;
if (is_debug && !drm_debug_enabled(DRM_UT_DRIVER))
return;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
if (is_error)
dev_printk(level, kdev, "%pV", &vaf);
else
dev_printk(level, kdev, "[" DRM_NAME ":%ps] %pV",
__builtin_return_address(0), &vaf);
va_end(args);
if (is_error && !shown_bug_once) {
/*
* Ask the user to file a bug report for the error, except
* if they may have caused the bug by fiddling with unsafe
* module parameters.
*/
if (!test_taint(TAINT_USER))
dev_notice(kdev, "%s", FDO_BUG_MSG);
shown_bug_once = true;
}
}
void add_taint_for_CI(struct drm_i915_private *i915, unsigned int taint)
{
__i915_printk(i915, KERN_NOTICE, "CI tainted:%#x by %pS\n",
taint, (void *)_RET_IP_);
/* Failures that occur during fault injection testing are expected */
if (!i915_error_injected())
__add_taint_for_CI(taint);
}
#if IS_ENABLED(CONFIG_DRM_I915_DEBUG)
static unsigned int i915_probe_fail_count;
int __i915_inject_probe_error(struct drm_i915_private *i915, int err,
const char *func, int line)
{
if (i915_probe_fail_count >= i915_modparams.inject_probe_failure)
return 0;
if (++i915_probe_fail_count < i915_modparams.inject_probe_failure)
return 0;
__i915_printk(i915, KERN_INFO,
"Injecting failure %d at checkpoint %u [%s:%d]\n",
err, i915_modparams.inject_probe_failure, func, line);
i915_modparams.inject_probe_failure = 0;
return err;
}
bool i915_error_injected(void)
{
return i915_probe_fail_count && !i915_modparams.inject_probe_failure;
}
#endif
void cancel_timer(struct timer_list *t)
{
if (!timer_active(t))
return;
del_timer(t);
WRITE_ONCE(t->expires, 0);
}
void set_timer_ms(struct timer_list *t, unsigned long timeout)
{
if (!timeout) {
cancel_timer(t);
return;
}
timeout = msecs_to_jiffies(timeout);
/*
* Paranoia to make sure the compiler computes the timeout before
* loading 'jiffies' as jiffies is volatile and may be updated in
* the background by a timer tick. All to reduce the complexity
* of the addition and reduce the risk of losing a jiffie.
*/
barrier();
/* Keep t->expires = 0 reserved to indicate a canceled timer. */
mod_timer(t, jiffies + timeout ?: 1);
}
bool i915_vtd_active(struct drm_i915_private *i915)
{
if (device_iommu_mapped(i915->drm.dev))
return true;
/* Running as a guest, we assume the host is enforcing VT'd */
return i915_run_as_guest();
}
| linux-master | drivers/gpu/drm/i915/i915_utils.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2022 Intel Corporation
*/
#include "gt/intel_engine_regs.h"
#include "i915_drv.h"
#include "i915_gem.h"
#include "i915_ioctl.h"
#include "i915_reg.h"
#include "intel_runtime_pm.h"
#include "intel_uncore.h"
/*
* This file is for small ioctl functions that are out of place everywhere else,
* and not big enough to warrant a file of their own.
*
* This is not the dumping ground for random ioctls.
*/
struct reg_whitelist {
i915_reg_t offset_ldw;
i915_reg_t offset_udw;
u8 min_graphics_ver;
u8 max_graphics_ver;
u8 size;
};
static const struct reg_whitelist reg_read_whitelist[] = {
{
.offset_ldw = RING_TIMESTAMP(RENDER_RING_BASE),
.offset_udw = RING_TIMESTAMP_UDW(RENDER_RING_BASE),
.min_graphics_ver = 4,
.max_graphics_ver = 12,
.size = 8
}
};
int i915_reg_read_ioctl(struct drm_device *dev,
void *data, struct drm_file *unused)
{
struct drm_i915_private *i915 = to_i915(dev);
struct intel_uncore *uncore = &i915->uncore;
struct drm_i915_reg_read *reg = data;
struct reg_whitelist const *entry;
intel_wakeref_t wakeref;
unsigned int flags;
int remain;
int ret = 0;
entry = reg_read_whitelist;
remain = ARRAY_SIZE(reg_read_whitelist);
while (remain) {
u32 entry_offset = i915_mmio_reg_offset(entry->offset_ldw);
GEM_BUG_ON(!is_power_of_2(entry->size));
GEM_BUG_ON(entry->size > 8);
GEM_BUG_ON(entry_offset & (entry->size - 1));
if (IS_GRAPHICS_VER(i915, entry->min_graphics_ver, entry->max_graphics_ver) &&
entry_offset == (reg->offset & -entry->size))
break;
entry++;
remain--;
}
if (!remain)
return -EINVAL;
flags = reg->offset & (entry->size - 1);
with_intel_runtime_pm(&i915->runtime_pm, wakeref) {
if (entry->size == 8 && flags == I915_REG_READ_8B_WA)
reg->val = intel_uncore_read64_2x32(uncore,
entry->offset_ldw,
entry->offset_udw);
else if (entry->size == 8 && flags == 0)
reg->val = intel_uncore_read64(uncore,
entry->offset_ldw);
else if (entry->size == 4 && flags == 0)
reg->val = intel_uncore_read(uncore, entry->offset_ldw);
else if (entry->size == 2 && flags == 0)
reg->val = intel_uncore_read16(uncore,
entry->offset_ldw);
else if (entry->size == 1 && flags == 0)
reg->val = intel_uncore_read8(uncore,
entry->offset_ldw);
else
ret = -EINVAL;
}
return ret;
}
| linux-master | drivers/gpu/drm/i915/i915_ioctl.c |
/*
* Copyright © 2012-2014 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* Authors:
* Eugeni Dodonov <[email protected]>
* Daniel Vetter <[email protected]>
*
*/
#include <linux/pm_runtime.h>
#include <drm/drm_print.h>
#include "i915_drv.h"
#include "i915_trace.h"
/**
* DOC: runtime pm
*
* The i915 driver supports dynamic enabling and disabling of entire hardware
* blocks at runtime. This is especially important on the display side where
* software is supposed to control many power gates manually on recent hardware,
* since on the GT side a lot of the power management is done by the hardware.
* But even there some manual control at the device level is required.
*
* Since i915 supports a diverse set of platforms with a unified codebase and
* hardware engineers just love to shuffle functionality around between power
* domains there's a sizeable amount of indirection required. This file provides
* generic functions to the driver for grabbing and releasing references for
* abstract power domains. It then maps those to the actual power wells
* present for a given platform.
*/
#if IS_ENABLED(CONFIG_DRM_I915_DEBUG_RUNTIME_PM)
#include <linux/sort.h>
#define STACKDEPTH 8
static noinline depot_stack_handle_t __save_depot_stack(void)
{
unsigned long entries[STACKDEPTH];
unsigned int n;
n = stack_trace_save(entries, ARRAY_SIZE(entries), 1);
return stack_depot_save(entries, n, GFP_NOWAIT | __GFP_NOWARN);
}
static void init_intel_runtime_pm_wakeref(struct intel_runtime_pm *rpm)
{
spin_lock_init(&rpm->debug.lock);
stack_depot_init();
}
static noinline depot_stack_handle_t
track_intel_runtime_pm_wakeref(struct intel_runtime_pm *rpm)
{
depot_stack_handle_t stack, *stacks;
unsigned long flags;
if (rpm->no_wakeref_tracking)
return -1;
stack = __save_depot_stack();
if (!stack)
return -1;
spin_lock_irqsave(&rpm->debug.lock, flags);
if (!rpm->debug.count)
rpm->debug.last_acquire = stack;
stacks = krealloc(rpm->debug.owners,
(rpm->debug.count + 1) * sizeof(*stacks),
GFP_NOWAIT | __GFP_NOWARN);
if (stacks) {
stacks[rpm->debug.count++] = stack;
rpm->debug.owners = stacks;
} else {
stack = -1;
}
spin_unlock_irqrestore(&rpm->debug.lock, flags);
return stack;
}
static void untrack_intel_runtime_pm_wakeref(struct intel_runtime_pm *rpm,
depot_stack_handle_t stack)
{
struct drm_i915_private *i915 = container_of(rpm,
struct drm_i915_private,
runtime_pm);
unsigned long flags, n;
bool found = false;
if (unlikely(stack == -1))
return;
spin_lock_irqsave(&rpm->debug.lock, flags);
for (n = rpm->debug.count; n--; ) {
if (rpm->debug.owners[n] == stack) {
memmove(rpm->debug.owners + n,
rpm->debug.owners + n + 1,
(--rpm->debug.count - n) * sizeof(stack));
found = true;
break;
}
}
spin_unlock_irqrestore(&rpm->debug.lock, flags);
if (drm_WARN(&i915->drm, !found,
"Unmatched wakeref (tracking %lu), count %u\n",
rpm->debug.count, atomic_read(&rpm->wakeref_count))) {
char *buf;
buf = kmalloc(PAGE_SIZE, GFP_NOWAIT | __GFP_NOWARN);
if (!buf)
return;
stack_depot_snprint(stack, buf, PAGE_SIZE, 2);
DRM_DEBUG_DRIVER("wakeref %x from\n%s", stack, buf);
stack = READ_ONCE(rpm->debug.last_release);
if (stack) {
stack_depot_snprint(stack, buf, PAGE_SIZE, 2);
DRM_DEBUG_DRIVER("wakeref last released at\n%s", buf);
}
kfree(buf);
}
}
static int cmphandle(const void *_a, const void *_b)
{
const depot_stack_handle_t * const a = _a, * const b = _b;
if (*a < *b)
return -1;
else if (*a > *b)
return 1;
else
return 0;
}
static void
__print_intel_runtime_pm_wakeref(struct drm_printer *p,
const struct intel_runtime_pm_debug *dbg)
{
unsigned long i;
char *buf;
buf = kmalloc(PAGE_SIZE, GFP_NOWAIT | __GFP_NOWARN);
if (!buf)
return;
if (dbg->last_acquire) {
stack_depot_snprint(dbg->last_acquire, buf, PAGE_SIZE, 2);
drm_printf(p, "Wakeref last acquired:\n%s", buf);
}
if (dbg->last_release) {
stack_depot_snprint(dbg->last_release, buf, PAGE_SIZE, 2);
drm_printf(p, "Wakeref last released:\n%s", buf);
}
drm_printf(p, "Wakeref count: %lu\n", dbg->count);
sort(dbg->owners, dbg->count, sizeof(*dbg->owners), cmphandle, NULL);
for (i = 0; i < dbg->count; i++) {
depot_stack_handle_t stack = dbg->owners[i];
unsigned long rep;
rep = 1;
while (i + 1 < dbg->count && dbg->owners[i + 1] == stack)
rep++, i++;
stack_depot_snprint(stack, buf, PAGE_SIZE, 2);
drm_printf(p, "Wakeref x%lu taken at:\n%s", rep, buf);
}
kfree(buf);
}
static noinline void
__untrack_all_wakerefs(struct intel_runtime_pm_debug *debug,
struct intel_runtime_pm_debug *saved)
{
*saved = *debug;
debug->owners = NULL;
debug->count = 0;
debug->last_release = __save_depot_stack();
}
static void
dump_and_free_wakeref_tracking(struct intel_runtime_pm_debug *debug)
{
if (debug->count) {
struct drm_printer p = drm_debug_printer("i915");
__print_intel_runtime_pm_wakeref(&p, debug);
}
kfree(debug->owners);
}
static noinline void
__intel_wakeref_dec_and_check_tracking(struct intel_runtime_pm *rpm)
{
struct intel_runtime_pm_debug dbg = {};
unsigned long flags;
if (!atomic_dec_and_lock_irqsave(&rpm->wakeref_count,
&rpm->debug.lock,
flags))
return;
__untrack_all_wakerefs(&rpm->debug, &dbg);
spin_unlock_irqrestore(&rpm->debug.lock, flags);
dump_and_free_wakeref_tracking(&dbg);
}
static noinline void
untrack_all_intel_runtime_pm_wakerefs(struct intel_runtime_pm *rpm)
{
struct intel_runtime_pm_debug dbg = {};
unsigned long flags;
spin_lock_irqsave(&rpm->debug.lock, flags);
__untrack_all_wakerefs(&rpm->debug, &dbg);
spin_unlock_irqrestore(&rpm->debug.lock, flags);
dump_and_free_wakeref_tracking(&dbg);
}
void print_intel_runtime_pm_wakeref(struct intel_runtime_pm *rpm,
struct drm_printer *p)
{
struct intel_runtime_pm_debug dbg = {};
do {
unsigned long alloc = dbg.count;
depot_stack_handle_t *s;
spin_lock_irq(&rpm->debug.lock);
dbg.count = rpm->debug.count;
if (dbg.count <= alloc) {
memcpy(dbg.owners,
rpm->debug.owners,
dbg.count * sizeof(*s));
}
dbg.last_acquire = rpm->debug.last_acquire;
dbg.last_release = rpm->debug.last_release;
spin_unlock_irq(&rpm->debug.lock);
if (dbg.count <= alloc)
break;
s = krealloc(dbg.owners,
dbg.count * sizeof(*s),
GFP_NOWAIT | __GFP_NOWARN);
if (!s)
goto out;
dbg.owners = s;
} while (1);
__print_intel_runtime_pm_wakeref(p, &dbg);
out:
kfree(dbg.owners);
}
#else
static void init_intel_runtime_pm_wakeref(struct intel_runtime_pm *rpm)
{
}
static depot_stack_handle_t
track_intel_runtime_pm_wakeref(struct intel_runtime_pm *rpm)
{
return -1;
}
static void untrack_intel_runtime_pm_wakeref(struct intel_runtime_pm *rpm,
intel_wakeref_t wref)
{
}
static void
__intel_wakeref_dec_and_check_tracking(struct intel_runtime_pm *rpm)
{
atomic_dec(&rpm->wakeref_count);
}
static void
untrack_all_intel_runtime_pm_wakerefs(struct intel_runtime_pm *rpm)
{
}
#endif
static void
intel_runtime_pm_acquire(struct intel_runtime_pm *rpm, bool wakelock)
{
if (wakelock) {
atomic_add(1 + INTEL_RPM_WAKELOCK_BIAS, &rpm->wakeref_count);
assert_rpm_wakelock_held(rpm);
} else {
atomic_inc(&rpm->wakeref_count);
assert_rpm_raw_wakeref_held(rpm);
}
}
static void
intel_runtime_pm_release(struct intel_runtime_pm *rpm, int wakelock)
{
if (wakelock) {
assert_rpm_wakelock_held(rpm);
atomic_sub(INTEL_RPM_WAKELOCK_BIAS, &rpm->wakeref_count);
} else {
assert_rpm_raw_wakeref_held(rpm);
}
__intel_wakeref_dec_and_check_tracking(rpm);
}
static intel_wakeref_t __intel_runtime_pm_get(struct intel_runtime_pm *rpm,
bool wakelock)
{
struct drm_i915_private *i915 = container_of(rpm,
struct drm_i915_private,
runtime_pm);
int ret;
ret = pm_runtime_get_sync(rpm->kdev);
drm_WARN_ONCE(&i915->drm, ret < 0,
"pm_runtime_get_sync() failed: %d\n", ret);
intel_runtime_pm_acquire(rpm, wakelock);
return track_intel_runtime_pm_wakeref(rpm);
}
/**
* intel_runtime_pm_get_raw - grab a raw runtime pm reference
* @rpm: the intel_runtime_pm structure
*
* This is the unlocked version of intel_display_power_is_enabled() and should
* only be used from error capture and recovery code where deadlocks are
* possible.
* This function grabs a device-level runtime pm reference (mostly used for
* asynchronous PM management from display code) and ensures that it is powered
* up. Raw references are not considered during wakelock assert checks.
*
* Any runtime pm reference obtained by this function must have a symmetric
* call to intel_runtime_pm_put_raw() to release the reference again.
*
* Returns: the wakeref cookie to pass to intel_runtime_pm_put_raw(), evaluates
* as True if the wakeref was acquired, or False otherwise.
*/
intel_wakeref_t intel_runtime_pm_get_raw(struct intel_runtime_pm *rpm)
{
return __intel_runtime_pm_get(rpm, false);
}
/**
* intel_runtime_pm_get - grab a runtime pm reference
* @rpm: the intel_runtime_pm structure
*
* This function grabs a device-level runtime pm reference (mostly used for GEM
* code to ensure the GTT or GT is on) and ensures that it is powered up.
*
* Any runtime pm reference obtained by this function must have a symmetric
* call to intel_runtime_pm_put() to release the reference again.
*
* Returns: the wakeref cookie to pass to intel_runtime_pm_put()
*/
intel_wakeref_t intel_runtime_pm_get(struct intel_runtime_pm *rpm)
{
return __intel_runtime_pm_get(rpm, true);
}
/**
* __intel_runtime_pm_get_if_active - grab a runtime pm reference if device is active
* @rpm: the intel_runtime_pm structure
* @ignore_usecount: get a ref even if dev->power.usage_count is 0
*
* This function grabs a device-level runtime pm reference if the device is
* already active and ensures that it is powered up. It is illegal to try
* and access the HW should intel_runtime_pm_get_if_active() report failure.
*
* If @ignore_usecount is true, a reference will be acquired even if there is no
* user requiring the device to be powered up (dev->power.usage_count == 0).
* If the function returns false in this case then it's guaranteed that the
* device's runtime suspend hook has been called already or that it will be
* called (and hence it's also guaranteed that the device's runtime resume
* hook will be called eventually).
*
* Any runtime pm reference obtained by this function must have a symmetric
* call to intel_runtime_pm_put() to release the reference again.
*
* Returns: the wakeref cookie to pass to intel_runtime_pm_put(), evaluates
* as True if the wakeref was acquired, or False otherwise.
*/
static intel_wakeref_t __intel_runtime_pm_get_if_active(struct intel_runtime_pm *rpm,
bool ignore_usecount)
{
if (IS_ENABLED(CONFIG_PM)) {
/*
* In cases runtime PM is disabled by the RPM core and we get
* an -EINVAL return value we are not supposed to call this
* function, since the power state is undefined. This applies
* atm to the late/early system suspend/resume handlers.
*/
if (pm_runtime_get_if_active(rpm->kdev, ignore_usecount) <= 0)
return 0;
}
intel_runtime_pm_acquire(rpm, true);
return track_intel_runtime_pm_wakeref(rpm);
}
intel_wakeref_t intel_runtime_pm_get_if_in_use(struct intel_runtime_pm *rpm)
{
return __intel_runtime_pm_get_if_active(rpm, false);
}
intel_wakeref_t intel_runtime_pm_get_if_active(struct intel_runtime_pm *rpm)
{
return __intel_runtime_pm_get_if_active(rpm, true);
}
/**
* intel_runtime_pm_get_noresume - grab a runtime pm reference
* @rpm: the intel_runtime_pm structure
*
* This function grabs a device-level runtime pm reference (mostly used for GEM
* code to ensure the GTT or GT is on).
*
* It will _not_ power up the device but instead only check that it's powered
* on. Therefore it is only valid to call this functions from contexts where
* the device is known to be powered up and where trying to power it up would
* result in hilarity and deadlocks. That pretty much means only the system
* suspend/resume code where this is used to grab runtime pm references for
* delayed setup down in work items.
*
* Any runtime pm reference obtained by this function must have a symmetric
* call to intel_runtime_pm_put() to release the reference again.
*
* Returns: the wakeref cookie to pass to intel_runtime_pm_put()
*/
intel_wakeref_t intel_runtime_pm_get_noresume(struct intel_runtime_pm *rpm)
{
assert_rpm_wakelock_held(rpm);
pm_runtime_get_noresume(rpm->kdev);
intel_runtime_pm_acquire(rpm, true);
return track_intel_runtime_pm_wakeref(rpm);
}
static void __intel_runtime_pm_put(struct intel_runtime_pm *rpm,
intel_wakeref_t wref,
bool wakelock)
{
struct device *kdev = rpm->kdev;
untrack_intel_runtime_pm_wakeref(rpm, wref);
intel_runtime_pm_release(rpm, wakelock);
pm_runtime_mark_last_busy(kdev);
pm_runtime_put_autosuspend(kdev);
}
/**
* intel_runtime_pm_put_raw - release a raw runtime pm reference
* @rpm: the intel_runtime_pm structure
* @wref: wakeref acquired for the reference that is being released
*
* This function drops the device-level runtime pm reference obtained by
* intel_runtime_pm_get_raw() and might power down the corresponding
* hardware block right away if this is the last reference.
*/
void
intel_runtime_pm_put_raw(struct intel_runtime_pm *rpm, intel_wakeref_t wref)
{
__intel_runtime_pm_put(rpm, wref, false);
}
/**
* intel_runtime_pm_put_unchecked - release an unchecked runtime pm reference
* @rpm: the intel_runtime_pm structure
*
* This function drops the device-level runtime pm reference obtained by
* intel_runtime_pm_get() and might power down the corresponding
* hardware block right away if this is the last reference.
*
* This function exists only for historical reasons and should be avoided in
* new code, as the correctness of its use cannot be checked. Always use
* intel_runtime_pm_put() instead.
*/
void intel_runtime_pm_put_unchecked(struct intel_runtime_pm *rpm)
{
__intel_runtime_pm_put(rpm, -1, true);
}
#if IS_ENABLED(CONFIG_DRM_I915_DEBUG_RUNTIME_PM)
/**
* intel_runtime_pm_put - release a runtime pm reference
* @rpm: the intel_runtime_pm structure
* @wref: wakeref acquired for the reference that is being released
*
* This function drops the device-level runtime pm reference obtained by
* intel_runtime_pm_get() and might power down the corresponding
* hardware block right away if this is the last reference.
*/
void intel_runtime_pm_put(struct intel_runtime_pm *rpm, intel_wakeref_t wref)
{
__intel_runtime_pm_put(rpm, wref, true);
}
#endif
/**
* intel_runtime_pm_enable - enable runtime pm
* @rpm: the intel_runtime_pm structure
*
* This function enables runtime pm at the end of the driver load sequence.
*
* Note that this function does currently not enable runtime pm for the
* subordinate display power domains. That is done by
* intel_power_domains_enable().
*/
void intel_runtime_pm_enable(struct intel_runtime_pm *rpm)
{
struct drm_i915_private *i915 = container_of(rpm,
struct drm_i915_private,
runtime_pm);
struct device *kdev = rpm->kdev;
/*
* Disable the system suspend direct complete optimization, which can
* leave the device suspended skipping the driver's suspend handlers
* if the device was already runtime suspended. This is needed due to
* the difference in our runtime and system suspend sequence and
* becaue the HDA driver may require us to enable the audio power
* domain during system suspend.
*/
dev_pm_set_driver_flags(kdev, DPM_FLAG_NO_DIRECT_COMPLETE);
pm_runtime_set_autosuspend_delay(kdev, 10000); /* 10s */
pm_runtime_mark_last_busy(kdev);
/*
* Take a permanent reference to disable the RPM functionality and drop
* it only when unloading the driver. Use the low level get/put helpers,
* so the driver's own RPM reference tracking asserts also work on
* platforms without RPM support.
*/
if (!rpm->available) {
int ret;
pm_runtime_dont_use_autosuspend(kdev);
ret = pm_runtime_get_sync(kdev);
drm_WARN(&i915->drm, ret < 0,
"pm_runtime_get_sync() failed: %d\n", ret);
} else {
pm_runtime_use_autosuspend(kdev);
}
/*
* FIXME: Temp hammer to keep autosupend disable on lmem supported platforms.
* As per PCIe specs 5.3.1.4.1, all iomem read write request over a PCIe
* function will be unsupported in case PCIe endpoint function is in D3.
* Let's keep i915 autosuspend control 'on' till we fix all known issue
* with lmem access in D3.
*/
if (!IS_DGFX(i915))
pm_runtime_allow(kdev);
/*
* The core calls the driver load handler with an RPM reference held.
* We drop that here and will reacquire it during unloading in
* intel_power_domains_fini().
*/
pm_runtime_put_autosuspend(kdev);
}
void intel_runtime_pm_disable(struct intel_runtime_pm *rpm)
{
struct drm_i915_private *i915 = container_of(rpm,
struct drm_i915_private,
runtime_pm);
struct device *kdev = rpm->kdev;
/* Transfer rpm ownership back to core */
drm_WARN(&i915->drm, pm_runtime_get_sync(kdev) < 0,
"Failed to pass rpm ownership back to core\n");
pm_runtime_dont_use_autosuspend(kdev);
if (!rpm->available)
pm_runtime_put(kdev);
}
void intel_runtime_pm_driver_release(struct intel_runtime_pm *rpm)
{
struct drm_i915_private *i915 = container_of(rpm,
struct drm_i915_private,
runtime_pm);
int count = atomic_read(&rpm->wakeref_count);
intel_wakeref_auto_fini(&rpm->userfault_wakeref);
drm_WARN(&i915->drm, count,
"i915 raw-wakerefs=%d wakelocks=%d on cleanup\n",
intel_rpm_raw_wakeref_count(count),
intel_rpm_wakelock_count(count));
untrack_all_intel_runtime_pm_wakerefs(rpm);
}
void intel_runtime_pm_init_early(struct intel_runtime_pm *rpm)
{
struct drm_i915_private *i915 =
container_of(rpm, struct drm_i915_private, runtime_pm);
struct pci_dev *pdev = to_pci_dev(i915->drm.dev);
struct device *kdev = &pdev->dev;
rpm->kdev = kdev;
rpm->available = HAS_RUNTIME_PM(i915);
rpm->suspended = false;
atomic_set(&rpm->wakeref_count, 0);
init_intel_runtime_pm_wakeref(rpm);
INIT_LIST_HEAD(&rpm->lmem_userfault_list);
spin_lock_init(&rpm->lmem_userfault_lock);
intel_wakeref_auto_init(&rpm->userfault_wakeref, i915);
}
| linux-master | drivers/gpu/drm/i915/intel_runtime_pm.c |
/*
* Copyright © 2012 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* Authors:
* Eugeni Dodonov <[email protected]>
*
*/
#include "display/intel_de.h"
#include "display/intel_display.h"
#include "display/intel_display_trace.h"
#include "display/skl_watermark.h"
#include "gt/intel_engine_regs.h"
#include "gt/intel_gt.h"
#include "gt/intel_gt_mcr.h"
#include "gt/intel_gt_regs.h"
#include "i915_drv.h"
#include "i915_reg.h"
#include "intel_clock_gating.h"
#include "intel_mchbar_regs.h"
#include "vlv_sideband.h"
struct drm_i915_clock_gating_funcs {
void (*init_clock_gating)(struct drm_i915_private *i915);
};
static void gen9_init_clock_gating(struct drm_i915_private *i915)
{
if (HAS_LLC(i915)) {
/*
* WaCompressedResourceDisplayNewHashMode:skl,kbl
* Display WA #0390: skl,kbl
*
* Must match Sampler, Pixel Back End, and Media. See
* WaCompressedResourceSamplerPbeMediaNewHashMode.
*/
intel_uncore_rmw(&i915->uncore, CHICKEN_PAR1_1, 0, SKL_DE_COMPRESSED_HASH_MODE);
}
/* See Bspec note for PSR2_CTL bit 31, Wa#828:skl,bxt,kbl,cfl */
intel_uncore_rmw(&i915->uncore, CHICKEN_PAR1_1, 0, SKL_EDP_PSR_FIX_RDWRAP);
/* WaEnableChickenDCPR:skl,bxt,kbl,glk,cfl */
intel_uncore_rmw(&i915->uncore, GEN8_CHICKEN_DCPR_1, 0, MASK_WAKEMEM);
/*
* WaFbcWakeMemOn:skl,bxt,kbl,glk,cfl
* Display WA #0859: skl,bxt,kbl,glk,cfl
*/
intel_uncore_rmw(&i915->uncore, DISP_ARB_CTL, 0, DISP_FBC_MEMORY_WAKE);
}
static void bxt_init_clock_gating(struct drm_i915_private *i915)
{
gen9_init_clock_gating(i915);
/* WaDisableSDEUnitClockGating:bxt */
intel_uncore_rmw(&i915->uncore, GEN8_UCGCTL6, 0, GEN8_SDEUNIT_CLOCK_GATE_DISABLE);
/*
* FIXME:
* GEN8_HDCUNIT_CLOCK_GATE_DISABLE_HDCREQ applies on 3x6 GT SKUs only.
*/
intel_uncore_rmw(&i915->uncore, GEN8_UCGCTL6, 0, GEN8_HDCUNIT_CLOCK_GATE_DISABLE_HDCREQ);
/*
* Wa: Backlight PWM may stop in the asserted state, causing backlight
* to stay fully on.
*/
intel_uncore_write(&i915->uncore, GEN9_CLKGATE_DIS_0,
intel_uncore_read(&i915->uncore, GEN9_CLKGATE_DIS_0) |
PWM1_GATING_DIS | PWM2_GATING_DIS);
/*
* Lower the display internal timeout.
* This is needed to avoid any hard hangs when DSI port PLL
* is off and a MMIO access is attempted by any privilege
* application, using batch buffers or any other means.
*/
intel_uncore_write(&i915->uncore, RM_TIMEOUT, MMIO_TIMEOUT_US(950));
/*
* WaFbcTurnOffFbcWatermark:bxt
* Display WA #0562: bxt
*/
intel_uncore_rmw(&i915->uncore, DISP_ARB_CTL, 0, DISP_FBC_WM_DIS);
/*
* WaFbcHighMemBwCorruptionAvoidance:bxt
* Display WA #0883: bxt
*/
intel_uncore_rmw(&i915->uncore, ILK_DPFC_CHICKEN(INTEL_FBC_A), 0, DPFC_DISABLE_DUMMY0);
}
static void glk_init_clock_gating(struct drm_i915_private *i915)
{
gen9_init_clock_gating(i915);
/*
* WaDisablePWMClockGating:glk
* Backlight PWM may stop in the asserted state, causing backlight
* to stay fully on.
*/
intel_uncore_write(&i915->uncore, GEN9_CLKGATE_DIS_0,
intel_uncore_read(&i915->uncore, GEN9_CLKGATE_DIS_0) |
PWM1_GATING_DIS | PWM2_GATING_DIS);
}
static void ibx_init_clock_gating(struct drm_i915_private *i915)
{
/*
* On Ibex Peak and Cougar Point, we need to disable clock
* gating for the panel power sequencer or it will fail to
* start up when no ports are active.
*/
intel_uncore_write(&i915->uncore, SOUTH_DSPCLK_GATE_D, PCH_DPLSUNIT_CLOCK_GATE_DISABLE);
}
static void g4x_disable_trickle_feed(struct drm_i915_private *dev_priv)
{
enum pipe pipe;
for_each_pipe(dev_priv, pipe) {
intel_uncore_rmw(&dev_priv->uncore, DSPCNTR(pipe), 0, DISP_TRICKLE_FEED_DISABLE);
intel_uncore_rmw(&dev_priv->uncore, DSPSURF(pipe), 0, 0);
intel_uncore_posting_read(&dev_priv->uncore, DSPSURF(pipe));
}
}
static void ilk_init_clock_gating(struct drm_i915_private *i915)
{
u32 dspclk_gate = ILK_VRHUNIT_CLOCK_GATE_DISABLE;
/*
* Required for FBC
* WaFbcDisableDpfcClockGating:ilk
*/
dspclk_gate |= ILK_DPFCRUNIT_CLOCK_GATE_DISABLE |
ILK_DPFCUNIT_CLOCK_GATE_DISABLE |
ILK_DPFDUNIT_CLOCK_GATE_ENABLE;
intel_uncore_write(&i915->uncore, PCH_3DCGDIS0,
MARIUNIT_CLOCK_GATE_DISABLE |
SVSMUNIT_CLOCK_GATE_DISABLE);
intel_uncore_write(&i915->uncore, PCH_3DCGDIS1,
VFMUNIT_CLOCK_GATE_DISABLE);
/*
* According to the spec the following bits should be set in
* order to enable memory self-refresh
* The bit 22/21 of 0x42004
* The bit 5 of 0x42020
* The bit 15 of 0x45000
*/
intel_uncore_write(&i915->uncore, ILK_DISPLAY_CHICKEN2,
(intel_uncore_read(&i915->uncore, ILK_DISPLAY_CHICKEN2) |
ILK_DPARB_GATE | ILK_VSDPFD_FULL));
dspclk_gate |= ILK_DPARBUNIT_CLOCK_GATE_ENABLE;
intel_uncore_write(&i915->uncore, DISP_ARB_CTL,
(intel_uncore_read(&i915->uncore, DISP_ARB_CTL) |
DISP_FBC_WM_DIS));
/*
* Based on the document from hardware guys the following bits
* should be set unconditionally in order to enable FBC.
* The bit 22 of 0x42000
* The bit 22 of 0x42004
* The bit 7,8,9 of 0x42020.
*/
if (IS_IRONLAKE_M(i915)) {
/* WaFbcAsynchFlipDisableFbcQueue:ilk */
intel_uncore_rmw(&i915->uncore, ILK_DISPLAY_CHICKEN1, 0, ILK_FBCQ_DIS);
intel_uncore_rmw(&i915->uncore, ILK_DISPLAY_CHICKEN2, 0, ILK_DPARB_GATE);
}
intel_uncore_write(&i915->uncore, ILK_DSPCLK_GATE_D, dspclk_gate);
intel_uncore_rmw(&i915->uncore, ILK_DISPLAY_CHICKEN2, 0, ILK_ELPIN_409_SELECT);
g4x_disable_trickle_feed(i915);
ibx_init_clock_gating(i915);
}
static void cpt_init_clock_gating(struct drm_i915_private *i915)
{
enum pipe pipe;
u32 val;
/*
* On Ibex Peak and Cougar Point, we need to disable clock
* gating for the panel power sequencer or it will fail to
* start up when no ports are active.
*/
intel_uncore_write(&i915->uncore, SOUTH_DSPCLK_GATE_D, PCH_DPLSUNIT_CLOCK_GATE_DISABLE |
PCH_DPLUNIT_CLOCK_GATE_DISABLE |
PCH_CPUNIT_CLOCK_GATE_DISABLE);
intel_uncore_rmw(&i915->uncore, SOUTH_CHICKEN2, 0, DPLS_EDP_PPS_FIX_DIS);
/* The below fixes the weird display corruption, a few pixels shifted
* downward, on (only) LVDS of some HP laptops with IVY.
*/
for_each_pipe(i915, pipe) {
val = intel_uncore_read(&i915->uncore, TRANS_CHICKEN2(pipe));
val |= TRANS_CHICKEN2_TIMING_OVERRIDE;
val &= ~TRANS_CHICKEN2_FDI_POLARITY_REVERSED;
if (i915->display.vbt.fdi_rx_polarity_inverted)
val |= TRANS_CHICKEN2_FDI_POLARITY_REVERSED;
val &= ~TRANS_CHICKEN2_DISABLE_DEEP_COLOR_COUNTER;
val &= ~TRANS_CHICKEN2_DISABLE_DEEP_COLOR_MODESWITCH;
intel_uncore_write(&i915->uncore, TRANS_CHICKEN2(pipe), val);
}
/* WADP0ClockGatingDisable */
for_each_pipe(i915, pipe) {
intel_uncore_write(&i915->uncore, TRANS_CHICKEN1(pipe),
TRANS_CHICKEN1_DP0UNIT_GC_DISABLE);
}
}
static void gen6_check_mch_setup(struct drm_i915_private *i915)
{
u32 tmp;
tmp = intel_uncore_read(&i915->uncore, MCH_SSKPD);
if (REG_FIELD_GET(SSKPD_WM0_MASK_SNB, tmp) != 12)
drm_dbg_kms(&i915->drm,
"Wrong MCH_SSKPD value: 0x%08x This can cause underruns.\n",
tmp);
}
static void gen6_init_clock_gating(struct drm_i915_private *i915)
{
u32 dspclk_gate = ILK_VRHUNIT_CLOCK_GATE_DISABLE;
intel_uncore_write(&i915->uncore, ILK_DSPCLK_GATE_D, dspclk_gate);
intel_uncore_rmw(&i915->uncore, ILK_DISPLAY_CHICKEN2, 0, ILK_ELPIN_409_SELECT);
intel_uncore_write(&i915->uncore, GEN6_UCGCTL1,
intel_uncore_read(&i915->uncore, GEN6_UCGCTL1) |
GEN6_BLBUNIT_CLOCK_GATE_DISABLE |
GEN6_CSUNIT_CLOCK_GATE_DISABLE);
/* According to the BSpec vol1g, bit 12 (RCPBUNIT) clock
* gating disable must be set. Failure to set it results in
* flickering pixels due to Z write ordering failures after
* some amount of runtime in the Mesa "fire" demo, and Unigine
* Sanctuary and Tropics, and apparently anything else with
* alpha test or pixel discard.
*
* According to the spec, bit 11 (RCCUNIT) must also be set,
* but we didn't debug actual testcases to find it out.
*
* WaDisableRCCUnitClockGating:snb
* WaDisableRCPBUnitClockGating:snb
*/
intel_uncore_write(&i915->uncore, GEN6_UCGCTL2,
GEN6_RCPBUNIT_CLOCK_GATE_DISABLE |
GEN6_RCCUNIT_CLOCK_GATE_DISABLE);
/*
* According to the spec the following bits should be
* set in order to enable memory self-refresh and fbc:
* The bit21 and bit22 of 0x42000
* The bit21 and bit22 of 0x42004
* The bit5 and bit7 of 0x42020
* The bit14 of 0x70180
* The bit14 of 0x71180
*
* WaFbcAsynchFlipDisableFbcQueue:snb
*/
intel_uncore_write(&i915->uncore, ILK_DISPLAY_CHICKEN1,
intel_uncore_read(&i915->uncore, ILK_DISPLAY_CHICKEN1) |
ILK_FBCQ_DIS | ILK_PABSTRETCH_DIS);
intel_uncore_write(&i915->uncore, ILK_DISPLAY_CHICKEN2,
intel_uncore_read(&i915->uncore, ILK_DISPLAY_CHICKEN2) |
ILK_DPARB_GATE | ILK_VSDPFD_FULL);
intel_uncore_write(&i915->uncore, ILK_DSPCLK_GATE_D,
intel_uncore_read(&i915->uncore, ILK_DSPCLK_GATE_D) |
ILK_DPARBUNIT_CLOCK_GATE_ENABLE |
ILK_DPFDUNIT_CLOCK_GATE_ENABLE);
g4x_disable_trickle_feed(i915);
cpt_init_clock_gating(i915);
gen6_check_mch_setup(i915);
}
static void lpt_init_clock_gating(struct drm_i915_private *i915)
{
/*
* TODO: this bit should only be enabled when really needed, then
* disabled when not needed anymore in order to save power.
*/
if (HAS_PCH_LPT_LP(i915))
intel_uncore_rmw(&i915->uncore, SOUTH_DSPCLK_GATE_D,
0, PCH_LP_PARTITION_LEVEL_DISABLE);
/* WADPOClockGatingDisable:hsw */
intel_uncore_rmw(&i915->uncore, TRANS_CHICKEN1(PIPE_A),
0, TRANS_CHICKEN1_DP0UNIT_GC_DISABLE);
}
static void gen8_set_l3sqc_credits(struct drm_i915_private *i915,
int general_prio_credits,
int high_prio_credits)
{
u32 misccpctl;
u32 val;
/* WaTempDisableDOPClkGating:bdw */
misccpctl = intel_uncore_rmw(&i915->uncore, GEN7_MISCCPCTL,
GEN7_DOP_CLOCK_GATE_ENABLE, 0);
val = intel_gt_mcr_read_any(to_gt(i915), GEN8_L3SQCREG1);
val &= ~L3_PRIO_CREDITS_MASK;
val |= L3_GENERAL_PRIO_CREDITS(general_prio_credits);
val |= L3_HIGH_PRIO_CREDITS(high_prio_credits);
intel_gt_mcr_multicast_write(to_gt(i915), GEN8_L3SQCREG1, val);
/*
* Wait at least 100 clocks before re-enabling clock gating.
* See the definition of L3SQCREG1 in BSpec.
*/
intel_gt_mcr_read_any(to_gt(i915), GEN8_L3SQCREG1);
udelay(1);
intel_uncore_write(&i915->uncore, GEN7_MISCCPCTL, misccpctl);
}
static void icl_init_clock_gating(struct drm_i915_private *i915)
{
/* Wa_1409120013:icl,ehl */
intel_uncore_write(&i915->uncore, ILK_DPFC_CHICKEN(INTEL_FBC_A),
DPFC_CHICKEN_COMP_DUMMY_PIXEL);
/*Wa_14010594013:icl, ehl */
intel_uncore_rmw(&i915->uncore, GEN8_CHICKEN_DCPR_1,
0, ICL_DELAY_PMRSP);
}
static void gen12lp_init_clock_gating(struct drm_i915_private *i915)
{
/* Wa_1409120013 */
if (DISPLAY_VER(i915) == 12)
intel_uncore_write(&i915->uncore, ILK_DPFC_CHICKEN(INTEL_FBC_A),
DPFC_CHICKEN_COMP_DUMMY_PIXEL);
/* Wa_14013723622:tgl,rkl,dg1,adl-s */
if (DISPLAY_VER(i915) == 12)
intel_uncore_rmw(&i915->uncore, CLKREQ_POLICY,
CLKREQ_POLICY_MEM_UP_OVRD, 0);
}
static void adlp_init_clock_gating(struct drm_i915_private *i915)
{
gen12lp_init_clock_gating(i915);
/* Wa_22011091694:adlp */
intel_de_rmw(i915, GEN9_CLKGATE_DIS_5, 0, DPCE_GATING_DIS);
/* Bspec/49189 Initialize Sequence */
intel_de_rmw(i915, GEN8_CHICKEN_DCPR_1, DDI_CLOCK_REG_ACCESS, 0);
}
static void xehpsdv_init_clock_gating(struct drm_i915_private *i915)
{
/* Wa_22010146351:xehpsdv */
if (IS_XEHPSDV_GRAPHICS_STEP(i915, STEP_A0, STEP_B0))
intel_uncore_rmw(&i915->uncore, XEHP_CLOCK_GATE_DIS, 0, SGR_DIS);
}
static void dg2_init_clock_gating(struct drm_i915_private *i915)
{
/* Wa_22010954014:dg2 */
intel_uncore_rmw(&i915->uncore, XEHP_CLOCK_GATE_DIS, 0,
SGSI_SIDECLK_DIS);
/*
* Wa_14010733611:dg2_g10
* Wa_22010146351:dg2_g10
*/
if (IS_DG2_GRAPHICS_STEP(i915, G10, STEP_A0, STEP_B0))
intel_uncore_rmw(&i915->uncore, XEHP_CLOCK_GATE_DIS, 0,
SGR_DIS | SGGI_DIS);
}
static void pvc_init_clock_gating(struct drm_i915_private *i915)
{
/* Wa_14012385139:pvc */
if (IS_PVC_BD_STEP(i915, STEP_A0, STEP_B0))
intel_uncore_rmw(&i915->uncore, XEHP_CLOCK_GATE_DIS, 0, SGR_DIS);
/* Wa_22010954014:pvc */
if (IS_PVC_BD_STEP(i915, STEP_A0, STEP_B0))
intel_uncore_rmw(&i915->uncore, XEHP_CLOCK_GATE_DIS, 0, SGSI_SIDECLK_DIS);
}
static void cnp_init_clock_gating(struct drm_i915_private *i915)
{
if (!HAS_PCH_CNP(i915))
return;
/* Display WA #1181 WaSouthDisplayDisablePWMCGEGating: cnp */
intel_uncore_rmw(&i915->uncore, SOUTH_DSPCLK_GATE_D, 0, CNP_PWM_CGE_GATING_DISABLE);
}
static void cfl_init_clock_gating(struct drm_i915_private *i915)
{
cnp_init_clock_gating(i915);
gen9_init_clock_gating(i915);
/* WAC6entrylatency:cfl */
intel_uncore_rmw(&i915->uncore, FBC_LLC_READ_CTRL, 0, FBC_LLC_FULLY_OPEN);
/*
* WaFbcTurnOffFbcWatermark:cfl
* Display WA #0562: cfl
*/
intel_uncore_rmw(&i915->uncore, DISP_ARB_CTL, 0, DISP_FBC_WM_DIS);
/*
* WaFbcNukeOnHostModify:cfl
* Display WA #0873: cfl
*/
intel_uncore_rmw(&i915->uncore, ILK_DPFC_CHICKEN(INTEL_FBC_A),
0, DPFC_NUKE_ON_ANY_MODIFICATION);
}
static void kbl_init_clock_gating(struct drm_i915_private *i915)
{
gen9_init_clock_gating(i915);
/* WAC6entrylatency:kbl */
intel_uncore_rmw(&i915->uncore, FBC_LLC_READ_CTRL, 0, FBC_LLC_FULLY_OPEN);
/* WaDisableSDEUnitClockGating:kbl */
if (IS_KABYLAKE(i915) && IS_GRAPHICS_STEP(i915, 0, STEP_C0))
intel_uncore_rmw(&i915->uncore, GEN8_UCGCTL6,
0, GEN8_SDEUNIT_CLOCK_GATE_DISABLE);
/* WaDisableGamClockGating:kbl */
if (IS_KABYLAKE(i915) && IS_GRAPHICS_STEP(i915, 0, STEP_C0))
intel_uncore_rmw(&i915->uncore, GEN6_UCGCTL1,
0, GEN6_GAMUNIT_CLOCK_GATE_DISABLE);
/*
* WaFbcTurnOffFbcWatermark:kbl
* Display WA #0562: kbl
*/
intel_uncore_rmw(&i915->uncore, DISP_ARB_CTL, 0, DISP_FBC_WM_DIS);
/*
* WaFbcNukeOnHostModify:kbl
* Display WA #0873: kbl
*/
intel_uncore_rmw(&i915->uncore, ILK_DPFC_CHICKEN(INTEL_FBC_A),
0, DPFC_NUKE_ON_ANY_MODIFICATION);
}
static void skl_init_clock_gating(struct drm_i915_private *i915)
{
gen9_init_clock_gating(i915);
/* WaDisableDopClockGating:skl */
intel_uncore_rmw(&i915->uncore, GEN7_MISCCPCTL,
GEN7_DOP_CLOCK_GATE_ENABLE, 0);
/* WAC6entrylatency:skl */
intel_uncore_rmw(&i915->uncore, FBC_LLC_READ_CTRL, 0, FBC_LLC_FULLY_OPEN);
/*
* WaFbcTurnOffFbcWatermark:skl
* Display WA #0562: skl
*/
intel_uncore_rmw(&i915->uncore, DISP_ARB_CTL, 0, DISP_FBC_WM_DIS);
/*
* WaFbcNukeOnHostModify:skl
* Display WA #0873: skl
*/
intel_uncore_rmw(&i915->uncore, ILK_DPFC_CHICKEN(INTEL_FBC_A),
0, DPFC_NUKE_ON_ANY_MODIFICATION);
/*
* WaFbcHighMemBwCorruptionAvoidance:skl
* Display WA #0883: skl
*/
intel_uncore_rmw(&i915->uncore, ILK_DPFC_CHICKEN(INTEL_FBC_A), 0, DPFC_DISABLE_DUMMY0);
}
static void bdw_init_clock_gating(struct drm_i915_private *i915)
{
enum pipe pipe;
/* WaFbcAsynchFlipDisableFbcQueue:hsw,bdw */
intel_uncore_rmw(&i915->uncore, CHICKEN_PIPESL_1(PIPE_A), 0, HSW_FBCQ_DIS);
/* WaSwitchSolVfFArbitrationPriority:bdw */
intel_uncore_rmw(&i915->uncore, GAM_ECOCHK, 0, HSW_ECOCHK_ARB_PRIO_SOL);
/* WaPsrDPAMaskVBlankInSRD:bdw */
intel_uncore_rmw(&i915->uncore, CHICKEN_PAR1_1, 0, HSW_MASK_VBL_TO_PIPE_IN_SRD);
for_each_pipe(i915, pipe) {
/* WaPsrDPRSUnmaskVBlankInSRD:bdw */
intel_uncore_rmw(&i915->uncore, CHICKEN_PIPESL_1(pipe),
0, BDW_UNMASK_VBL_TO_REGS_IN_SRD);
}
/* WaVSRefCountFullforceMissDisable:bdw */
/* WaDSRefCountFullforceMissDisable:bdw */
intel_uncore_rmw(&i915->uncore, GEN7_FF_THREAD_MODE,
GEN8_FF_DS_REF_CNT_FFME | GEN7_FF_VS_REF_CNT_FFME, 0);
intel_uncore_write(&i915->uncore, RING_PSMI_CTL(RENDER_RING_BASE),
_MASKED_BIT_ENABLE(GEN8_RC_SEMA_IDLE_MSG_DISABLE));
/* WaDisableSDEUnitClockGating:bdw */
intel_uncore_rmw(&i915->uncore, GEN8_UCGCTL6, 0, GEN8_SDEUNIT_CLOCK_GATE_DISABLE);
/* WaProgramL3SqcReg1Default:bdw */
gen8_set_l3sqc_credits(i915, 30, 2);
/* WaKVMNotificationOnConfigChange:bdw */
intel_uncore_rmw(&i915->uncore, CHICKEN_PAR2_1,
0, KVM_CONFIG_CHANGE_NOTIFICATION_SELECT);
lpt_init_clock_gating(i915);
/* WaDisableDopClockGating:bdw
*
* Also see the CHICKEN2 write in bdw_init_workarounds() to disable DOP
* clock gating.
*/
intel_uncore_rmw(&i915->uncore, GEN6_UCGCTL1, 0, GEN6_EU_TCUNIT_CLOCK_GATE_DISABLE);
}
static void hsw_init_clock_gating(struct drm_i915_private *i915)
{
enum pipe pipe;
/* WaFbcAsynchFlipDisableFbcQueue:hsw,bdw */
intel_uncore_rmw(&i915->uncore, CHICKEN_PIPESL_1(PIPE_A), 0, HSW_FBCQ_DIS);
/* WaPsrDPAMaskVBlankInSRD:hsw */
intel_uncore_rmw(&i915->uncore, CHICKEN_PAR1_1, 0, HSW_MASK_VBL_TO_PIPE_IN_SRD);
for_each_pipe(i915, pipe) {
/* WaPsrDPRSUnmaskVBlankInSRD:hsw */
intel_uncore_rmw(&i915->uncore, CHICKEN_PIPESL_1(pipe),
0, HSW_UNMASK_VBL_TO_REGS_IN_SRD);
}
/* This is required by WaCatErrorRejectionIssue:hsw */
intel_uncore_rmw(&i915->uncore, GEN7_SQ_CHICKEN_MBCUNIT_CONFIG,
0, GEN7_SQ_CHICKEN_MBCUNIT_SQINTMOB);
/* WaSwitchSolVfFArbitrationPriority:hsw */
intel_uncore_rmw(&i915->uncore, GAM_ECOCHK, 0, HSW_ECOCHK_ARB_PRIO_SOL);
lpt_init_clock_gating(i915);
}
static void ivb_init_clock_gating(struct drm_i915_private *i915)
{
intel_uncore_write(&i915->uncore, ILK_DSPCLK_GATE_D, ILK_VRHUNIT_CLOCK_GATE_DISABLE);
/* WaFbcAsynchFlipDisableFbcQueue:ivb */
intel_uncore_rmw(&i915->uncore, ILK_DISPLAY_CHICKEN1, 0, ILK_FBCQ_DIS);
/* WaDisableBackToBackFlipFix:ivb */
intel_uncore_write(&i915->uncore, IVB_CHICKEN3,
CHICKEN3_DGMG_REQ_OUT_FIX_DISABLE |
CHICKEN3_DGMG_DONE_FIX_DISABLE);
if (IS_IVB_GT1(i915))
intel_uncore_write(&i915->uncore, GEN7_ROW_CHICKEN2,
_MASKED_BIT_ENABLE(DOP_CLOCK_GATING_DISABLE));
else {
/* must write both registers */
intel_uncore_write(&i915->uncore, GEN7_ROW_CHICKEN2,
_MASKED_BIT_ENABLE(DOP_CLOCK_GATING_DISABLE));
intel_uncore_write(&i915->uncore, GEN7_ROW_CHICKEN2_GT2,
_MASKED_BIT_ENABLE(DOP_CLOCK_GATING_DISABLE));
}
/*
* According to the spec, bit 13 (RCZUNIT) must be set on IVB.
* This implements the WaDisableRCZUnitClockGating:ivb workaround.
*/
intel_uncore_write(&i915->uncore, GEN6_UCGCTL2,
GEN6_RCZUNIT_CLOCK_GATE_DISABLE);
/* This is required by WaCatErrorRejectionIssue:ivb */
intel_uncore_rmw(&i915->uncore, GEN7_SQ_CHICKEN_MBCUNIT_CONFIG,
0, GEN7_SQ_CHICKEN_MBCUNIT_SQINTMOB);
g4x_disable_trickle_feed(i915);
intel_uncore_rmw(&i915->uncore, GEN6_MBCUNIT_SNPCR, GEN6_MBC_SNPCR_MASK,
GEN6_MBC_SNPCR_MED);
if (!HAS_PCH_NOP(i915))
cpt_init_clock_gating(i915);
gen6_check_mch_setup(i915);
}
static void vlv_init_clock_gating(struct drm_i915_private *i915)
{
/* WaDisableBackToBackFlipFix:vlv */
intel_uncore_write(&i915->uncore, IVB_CHICKEN3,
CHICKEN3_DGMG_REQ_OUT_FIX_DISABLE |
CHICKEN3_DGMG_DONE_FIX_DISABLE);
/* WaDisableDopClockGating:vlv */
intel_uncore_write(&i915->uncore, GEN7_ROW_CHICKEN2,
_MASKED_BIT_ENABLE(DOP_CLOCK_GATING_DISABLE));
/* This is required by WaCatErrorRejectionIssue:vlv */
intel_uncore_rmw(&i915->uncore, GEN7_SQ_CHICKEN_MBCUNIT_CONFIG,
0, GEN7_SQ_CHICKEN_MBCUNIT_SQINTMOB);
/*
* According to the spec, bit 13 (RCZUNIT) must be set on IVB.
* This implements the WaDisableRCZUnitClockGating:vlv workaround.
*/
intel_uncore_write(&i915->uncore, GEN6_UCGCTL2,
GEN6_RCZUNIT_CLOCK_GATE_DISABLE);
/* WaDisableL3Bank2xClockGate:vlv
* Disabling L3 clock gating- MMIO 940c[25] = 1
* Set bit 25, to disable L3_BANK_2x_CLK_GATING */
intel_uncore_rmw(&i915->uncore, GEN7_UCGCTL4, 0, GEN7_L3BANK2X_CLOCK_GATE_DISABLE);
/*
* WaDisableVLVClockGating_VBIIssue:vlv
* Disable clock gating on th GCFG unit to prevent a delay
* in the reporting of vblank events.
*/
intel_uncore_write(&i915->uncore, VLV_GUNIT_CLOCK_GATE, GCFG_DIS);
}
static void chv_init_clock_gating(struct drm_i915_private *i915)
{
/* WaVSRefCountFullforceMissDisable:chv */
/* WaDSRefCountFullforceMissDisable:chv */
intel_uncore_rmw(&i915->uncore, GEN7_FF_THREAD_MODE,
GEN8_FF_DS_REF_CNT_FFME | GEN7_FF_VS_REF_CNT_FFME, 0);
/* WaDisableSemaphoreAndSyncFlipWait:chv */
intel_uncore_write(&i915->uncore, RING_PSMI_CTL(RENDER_RING_BASE),
_MASKED_BIT_ENABLE(GEN8_RC_SEMA_IDLE_MSG_DISABLE));
/* WaDisableCSUnitClockGating:chv */
intel_uncore_rmw(&i915->uncore, GEN6_UCGCTL1, 0, GEN6_CSUNIT_CLOCK_GATE_DISABLE);
/* WaDisableSDEUnitClockGating:chv */
intel_uncore_rmw(&i915->uncore, GEN8_UCGCTL6, 0, GEN8_SDEUNIT_CLOCK_GATE_DISABLE);
/*
* WaProgramL3SqcReg1Default:chv
* See gfxspecs/Related Documents/Performance Guide/
* LSQC Setting Recommendations.
*/
gen8_set_l3sqc_credits(i915, 38, 2);
}
static void g4x_init_clock_gating(struct drm_i915_private *i915)
{
u32 dspclk_gate;
intel_uncore_write(&i915->uncore, RENCLK_GATE_D1, 0);
intel_uncore_write(&i915->uncore, RENCLK_GATE_D2, VF_UNIT_CLOCK_GATE_DISABLE |
GS_UNIT_CLOCK_GATE_DISABLE |
CL_UNIT_CLOCK_GATE_DISABLE);
intel_uncore_write(&i915->uncore, RAMCLK_GATE_D, 0);
dspclk_gate = VRHUNIT_CLOCK_GATE_DISABLE |
OVRUNIT_CLOCK_GATE_DISABLE |
OVCUNIT_CLOCK_GATE_DISABLE;
if (IS_GM45(i915))
dspclk_gate |= DSSUNIT_CLOCK_GATE_DISABLE;
intel_uncore_write(&i915->uncore, DSPCLK_GATE_D(i915), dspclk_gate);
g4x_disable_trickle_feed(i915);
}
static void i965gm_init_clock_gating(struct drm_i915_private *i915)
{
struct intel_uncore *uncore = &i915->uncore;
intel_uncore_write(uncore, RENCLK_GATE_D1, I965_RCC_CLOCK_GATE_DISABLE);
intel_uncore_write(uncore, RENCLK_GATE_D2, 0);
intel_uncore_write(uncore, DSPCLK_GATE_D(i915), 0);
intel_uncore_write(uncore, RAMCLK_GATE_D, 0);
intel_uncore_write16(uncore, DEUC, 0);
intel_uncore_write(uncore,
MI_ARB_STATE,
_MASKED_BIT_ENABLE(MI_ARB_DISPLAY_TRICKLE_FEED_DISABLE));
}
static void i965g_init_clock_gating(struct drm_i915_private *i915)
{
intel_uncore_write(&i915->uncore, RENCLK_GATE_D1, I965_RCZ_CLOCK_GATE_DISABLE |
I965_RCC_CLOCK_GATE_DISABLE |
I965_RCPB_CLOCK_GATE_DISABLE |
I965_ISC_CLOCK_GATE_DISABLE |
I965_FBC_CLOCK_GATE_DISABLE);
intel_uncore_write(&i915->uncore, RENCLK_GATE_D2, 0);
intel_uncore_write(&i915->uncore, MI_ARB_STATE,
_MASKED_BIT_ENABLE(MI_ARB_DISPLAY_TRICKLE_FEED_DISABLE));
}
static void gen3_init_clock_gating(struct drm_i915_private *i915)
{
u32 dstate = intel_uncore_read(&i915->uncore, D_STATE);
dstate |= DSTATE_PLL_D3_OFF | DSTATE_GFX_CLOCK_GATING |
DSTATE_DOT_CLOCK_GATING;
intel_uncore_write(&i915->uncore, D_STATE, dstate);
if (IS_PINEVIEW(i915))
intel_uncore_write(&i915->uncore, ECOSKPD(RENDER_RING_BASE),
_MASKED_BIT_ENABLE(ECO_GATING_CX_ONLY));
/* IIR "flip pending" means done if this bit is set */
intel_uncore_write(&i915->uncore, ECOSKPD(RENDER_RING_BASE),
_MASKED_BIT_DISABLE(ECO_FLIP_DONE));
/* interrupts should cause a wake up from C3 */
intel_uncore_write(&i915->uncore, INSTPM, _MASKED_BIT_ENABLE(INSTPM_AGPBUSY_INT_EN));
/* On GEN3 we really need to make sure the ARB C3 LP bit is set */
intel_uncore_write(&i915->uncore, MI_ARB_STATE,
_MASKED_BIT_ENABLE(MI_ARB_C3_LP_WRITE_ENABLE));
intel_uncore_write(&i915->uncore, MI_ARB_STATE,
_MASKED_BIT_ENABLE(MI_ARB_DISPLAY_TRICKLE_FEED_DISABLE));
}
static void i85x_init_clock_gating(struct drm_i915_private *i915)
{
intel_uncore_write(&i915->uncore, RENCLK_GATE_D1, SV_CLOCK_GATE_DISABLE);
/* interrupts should cause a wake up from C3 */
intel_uncore_write(&i915->uncore, MI_STATE, _MASKED_BIT_ENABLE(MI_AGPBUSY_INT_EN) |
_MASKED_BIT_DISABLE(MI_AGPBUSY_830_MODE));
intel_uncore_write(&i915->uncore, MEM_MODE,
_MASKED_BIT_ENABLE(MEM_DISPLAY_TRICKLE_FEED_DISABLE));
/*
* Have FBC ignore 3D activity since we use software
* render tracking, and otherwise a pure 3D workload
* (even if it just renders a single frame and then does
* abosultely nothing) would not allow FBC to recompress
* until a 2D blit occurs.
*/
intel_uncore_write(&i915->uncore, SCPD0,
_MASKED_BIT_ENABLE(SCPD_FBC_IGNORE_3D));
}
static void i830_init_clock_gating(struct drm_i915_private *i915)
{
intel_uncore_write(&i915->uncore, MEM_MODE,
_MASKED_BIT_ENABLE(MEM_DISPLAY_A_TRICKLE_FEED_DISABLE) |
_MASKED_BIT_ENABLE(MEM_DISPLAY_B_TRICKLE_FEED_DISABLE));
}
void intel_clock_gating_init(struct drm_i915_private *i915)
{
i915->clock_gating_funcs->init_clock_gating(i915);
}
static void nop_init_clock_gating(struct drm_i915_private *i915)
{
drm_dbg_kms(&i915->drm,
"No clock gating settings or workarounds applied.\n");
}
#define CG_FUNCS(platform) \
static const struct drm_i915_clock_gating_funcs platform##_clock_gating_funcs = { \
.init_clock_gating = platform##_init_clock_gating, \
}
CG_FUNCS(pvc);
CG_FUNCS(dg2);
CG_FUNCS(xehpsdv);
CG_FUNCS(adlp);
CG_FUNCS(gen12lp);
CG_FUNCS(icl);
CG_FUNCS(cfl);
CG_FUNCS(skl);
CG_FUNCS(kbl);
CG_FUNCS(bxt);
CG_FUNCS(glk);
CG_FUNCS(bdw);
CG_FUNCS(chv);
CG_FUNCS(hsw);
CG_FUNCS(ivb);
CG_FUNCS(vlv);
CG_FUNCS(gen6);
CG_FUNCS(ilk);
CG_FUNCS(g4x);
CG_FUNCS(i965gm);
CG_FUNCS(i965g);
CG_FUNCS(gen3);
CG_FUNCS(i85x);
CG_FUNCS(i830);
CG_FUNCS(nop);
#undef CG_FUNCS
/**
* intel_clock_gating_hooks_init - setup the clock gating hooks
* @i915: device private
*
* Setup the hooks that configure which clocks of a given platform can be
* gated and also apply various GT and display specific workarounds for these
* platforms. Note that some GT specific workarounds are applied separately
* when GPU contexts or batchbuffers start their execution.
*/
void intel_clock_gating_hooks_init(struct drm_i915_private *i915)
{
if (IS_METEORLAKE(i915))
i915->clock_gating_funcs = &nop_clock_gating_funcs;
else if (IS_PONTEVECCHIO(i915))
i915->clock_gating_funcs = &pvc_clock_gating_funcs;
else if (IS_DG2(i915))
i915->clock_gating_funcs = &dg2_clock_gating_funcs;
else if (IS_XEHPSDV(i915))
i915->clock_gating_funcs = &xehpsdv_clock_gating_funcs;
else if (IS_ALDERLAKE_P(i915))
i915->clock_gating_funcs = &adlp_clock_gating_funcs;
else if (GRAPHICS_VER(i915) == 12)
i915->clock_gating_funcs = &gen12lp_clock_gating_funcs;
else if (GRAPHICS_VER(i915) == 11)
i915->clock_gating_funcs = &icl_clock_gating_funcs;
else if (IS_COFFEELAKE(i915) || IS_COMETLAKE(i915))
i915->clock_gating_funcs = &cfl_clock_gating_funcs;
else if (IS_SKYLAKE(i915))
i915->clock_gating_funcs = &skl_clock_gating_funcs;
else if (IS_KABYLAKE(i915))
i915->clock_gating_funcs = &kbl_clock_gating_funcs;
else if (IS_BROXTON(i915))
i915->clock_gating_funcs = &bxt_clock_gating_funcs;
else if (IS_GEMINILAKE(i915))
i915->clock_gating_funcs = &glk_clock_gating_funcs;
else if (IS_BROADWELL(i915))
i915->clock_gating_funcs = &bdw_clock_gating_funcs;
else if (IS_CHERRYVIEW(i915))
i915->clock_gating_funcs = &chv_clock_gating_funcs;
else if (IS_HASWELL(i915))
i915->clock_gating_funcs = &hsw_clock_gating_funcs;
else if (IS_IVYBRIDGE(i915))
i915->clock_gating_funcs = &ivb_clock_gating_funcs;
else if (IS_VALLEYVIEW(i915))
i915->clock_gating_funcs = &vlv_clock_gating_funcs;
else if (GRAPHICS_VER(i915) == 6)
i915->clock_gating_funcs = &gen6_clock_gating_funcs;
else if (GRAPHICS_VER(i915) == 5)
i915->clock_gating_funcs = &ilk_clock_gating_funcs;
else if (IS_G4X(i915))
i915->clock_gating_funcs = &g4x_clock_gating_funcs;
else if (IS_I965GM(i915))
i915->clock_gating_funcs = &i965gm_clock_gating_funcs;
else if (IS_I965G(i915))
i915->clock_gating_funcs = &i965g_clock_gating_funcs;
else if (GRAPHICS_VER(i915) == 3)
i915->clock_gating_funcs = &gen3_clock_gating_funcs;
else if (IS_I85X(i915) || IS_I865G(i915))
i915->clock_gating_funcs = &i85x_clock_gating_funcs;
else if (GRAPHICS_VER(i915) == 2)
i915->clock_gating_funcs = &i830_clock_gating_funcs;
else {
MISSING_CASE(INTEL_DEVID(i915));
i915->clock_gating_funcs = &nop_clock_gating_funcs;
}
}
| linux-master | drivers/gpu/drm/i915/intel_clock_gating.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2020 Intel Corporation
*/
#include <linux/dma-resv.h>
#include "i915_gem_ww.h"
#include "gem/i915_gem_object.h"
void i915_gem_ww_ctx_init(struct i915_gem_ww_ctx *ww, bool intr)
{
ww_acquire_init(&ww->ctx, &reservation_ww_class);
INIT_LIST_HEAD(&ww->obj_list);
ww->intr = intr;
ww->contended = NULL;
}
static void i915_gem_ww_ctx_unlock_all(struct i915_gem_ww_ctx *ww)
{
struct drm_i915_gem_object *obj;
while ((obj = list_first_entry_or_null(&ww->obj_list, struct drm_i915_gem_object, obj_link))) {
list_del(&obj->obj_link);
i915_gem_object_unlock(obj);
i915_gem_object_put(obj);
}
}
void i915_gem_ww_unlock_single(struct drm_i915_gem_object *obj)
{
list_del(&obj->obj_link);
i915_gem_object_unlock(obj);
i915_gem_object_put(obj);
}
void i915_gem_ww_ctx_fini(struct i915_gem_ww_ctx *ww)
{
i915_gem_ww_ctx_unlock_all(ww);
WARN_ON(ww->contended);
ww_acquire_fini(&ww->ctx);
}
int __must_check i915_gem_ww_ctx_backoff(struct i915_gem_ww_ctx *ww)
{
int ret = 0;
if (WARN_ON(!ww->contended))
return -EINVAL;
i915_gem_ww_ctx_unlock_all(ww);
if (ww->intr)
ret = dma_resv_lock_slow_interruptible(ww->contended->base.resv, &ww->ctx);
else
dma_resv_lock_slow(ww->contended->base.resv, &ww->ctx);
if (!ret)
list_add_tail(&ww->contended->obj_link, &ww->obj_list);
else
i915_gem_object_put(ww->contended);
ww->contended = NULL;
return ret;
}
| linux-master | drivers/gpu/drm/i915/i915_gem_ww.c |
/*
* SPDX-License-Identifier: MIT
*
* Copyright © 2018 Intel Corporation
*/
#include <linux/nospec.h>
#include "i915_drv.h"
#include "i915_perf.h"
#include "i915_query.h"
#include "gt/intel_engine_user.h"
#include <uapi/drm/i915_drm.h>
static int copy_query_item(void *query_hdr, size_t query_sz,
u32 total_length,
struct drm_i915_query_item *query_item)
{
if (query_item->length == 0)
return total_length;
if (query_item->length < total_length)
return -EINVAL;
if (copy_from_user(query_hdr, u64_to_user_ptr(query_item->data_ptr),
query_sz))
return -EFAULT;
return 0;
}
static int fill_topology_info(const struct sseu_dev_info *sseu,
struct drm_i915_query_item *query_item,
intel_sseu_ss_mask_t subslice_mask)
{
struct drm_i915_query_topology_info topo;
u32 slice_length, subslice_length, eu_length, total_length;
int ss_stride = GEN_SSEU_STRIDE(sseu->max_subslices);
int eu_stride = GEN_SSEU_STRIDE(sseu->max_eus_per_subslice);
int ret;
BUILD_BUG_ON(sizeof(u8) != sizeof(sseu->slice_mask));
if (sseu->max_slices == 0)
return -ENODEV;
slice_length = sizeof(sseu->slice_mask);
subslice_length = sseu->max_slices * ss_stride;
eu_length = sseu->max_slices * sseu->max_subslices * eu_stride;
total_length = sizeof(topo) + slice_length + subslice_length +
eu_length;
ret = copy_query_item(&topo, sizeof(topo), total_length, query_item);
if (ret != 0)
return ret;
memset(&topo, 0, sizeof(topo));
topo.max_slices = sseu->max_slices;
topo.max_subslices = sseu->max_subslices;
topo.max_eus_per_subslice = sseu->max_eus_per_subslice;
topo.subslice_offset = slice_length;
topo.subslice_stride = ss_stride;
topo.eu_offset = slice_length + subslice_length;
topo.eu_stride = eu_stride;
if (copy_to_user(u64_to_user_ptr(query_item->data_ptr),
&topo, sizeof(topo)))
return -EFAULT;
if (copy_to_user(u64_to_user_ptr(query_item->data_ptr + sizeof(topo)),
&sseu->slice_mask, slice_length))
return -EFAULT;
if (intel_sseu_copy_ssmask_to_user(u64_to_user_ptr(query_item->data_ptr +
sizeof(topo) + slice_length),
sseu))
return -EFAULT;
if (intel_sseu_copy_eumask_to_user(u64_to_user_ptr(query_item->data_ptr +
sizeof(topo) +
slice_length + subslice_length),
sseu))
return -EFAULT;
return total_length;
}
static int query_topology_info(struct drm_i915_private *dev_priv,
struct drm_i915_query_item *query_item)
{
const struct sseu_dev_info *sseu = &to_gt(dev_priv)->info.sseu;
if (query_item->flags != 0)
return -EINVAL;
return fill_topology_info(sseu, query_item, sseu->subslice_mask);
}
static int query_geometry_subslices(struct drm_i915_private *i915,
struct drm_i915_query_item *query_item)
{
const struct sseu_dev_info *sseu;
struct intel_engine_cs *engine;
struct i915_engine_class_instance classinstance;
if (GRAPHICS_VER_FULL(i915) < IP_VER(12, 50))
return -ENODEV;
classinstance = *((struct i915_engine_class_instance *)&query_item->flags);
engine = intel_engine_lookup_user(i915, (u8)classinstance.engine_class,
(u8)classinstance.engine_instance);
if (!engine)
return -EINVAL;
if (engine->class != RENDER_CLASS)
return -EINVAL;
sseu = &engine->gt->info.sseu;
return fill_topology_info(sseu, query_item, sseu->geometry_subslice_mask);
}
static int
query_engine_info(struct drm_i915_private *i915,
struct drm_i915_query_item *query_item)
{
struct drm_i915_query_engine_info __user *query_ptr =
u64_to_user_ptr(query_item->data_ptr);
struct drm_i915_engine_info __user *info_ptr;
struct drm_i915_query_engine_info query;
struct drm_i915_engine_info info = { };
unsigned int num_uabi_engines = 0;
struct intel_engine_cs *engine;
int len, ret;
if (query_item->flags)
return -EINVAL;
for_each_uabi_engine(engine, i915)
num_uabi_engines++;
len = struct_size(query_ptr, engines, num_uabi_engines);
ret = copy_query_item(&query, sizeof(query), len, query_item);
if (ret != 0)
return ret;
if (query.num_engines || query.rsvd[0] || query.rsvd[1] ||
query.rsvd[2])
return -EINVAL;
info_ptr = &query_ptr->engines[0];
for_each_uabi_engine(engine, i915) {
info.engine.engine_class = engine->uabi_class;
info.engine.engine_instance = engine->uabi_instance;
info.flags = I915_ENGINE_INFO_HAS_LOGICAL_INSTANCE;
info.capabilities = engine->uabi_capabilities;
info.logical_instance = ilog2(engine->logical_mask);
if (copy_to_user(info_ptr, &info, sizeof(info)))
return -EFAULT;
query.num_engines++;
info_ptr++;
}
if (copy_to_user(query_ptr, &query, sizeof(query)))
return -EFAULT;
return len;
}
static int can_copy_perf_config_registers_or_number(u32 user_n_regs,
u64 user_regs_ptr,
u32 kernel_n_regs)
{
/*
* We'll just put the number of registers, and won't copy the
* register.
*/
if (user_n_regs == 0)
return 0;
if (user_n_regs < kernel_n_regs)
return -EINVAL;
return 0;
}
static int copy_perf_config_registers_or_number(const struct i915_oa_reg *kernel_regs,
u32 kernel_n_regs,
u64 user_regs_ptr,
u32 *user_n_regs)
{
u32 __user *p = u64_to_user_ptr(user_regs_ptr);
u32 r;
if (*user_n_regs == 0) {
*user_n_regs = kernel_n_regs;
return 0;
}
*user_n_regs = kernel_n_regs;
if (!user_write_access_begin(p, 2 * sizeof(u32) * kernel_n_regs))
return -EFAULT;
for (r = 0; r < kernel_n_regs; r++, p += 2) {
unsafe_put_user(i915_mmio_reg_offset(kernel_regs[r].addr),
p, Efault);
unsafe_put_user(kernel_regs[r].value, p + 1, Efault);
}
user_write_access_end();
return 0;
Efault:
user_write_access_end();
return -EFAULT;
}
static int query_perf_config_data(struct drm_i915_private *i915,
struct drm_i915_query_item *query_item,
bool use_uuid)
{
struct drm_i915_query_perf_config __user *user_query_config_ptr =
u64_to_user_ptr(query_item->data_ptr);
struct drm_i915_perf_oa_config __user *user_config_ptr =
u64_to_user_ptr(query_item->data_ptr +
sizeof(struct drm_i915_query_perf_config));
struct drm_i915_perf_oa_config user_config;
struct i915_perf *perf = &i915->perf;
struct i915_oa_config *oa_config;
char uuid[UUID_STRING_LEN + 1];
u64 config_id;
u32 flags, total_size;
int ret;
if (!perf->i915)
return -ENODEV;
total_size =
sizeof(struct drm_i915_query_perf_config) +
sizeof(struct drm_i915_perf_oa_config);
if (query_item->length == 0)
return total_size;
if (query_item->length < total_size) {
drm_dbg(&i915->drm,
"Invalid query config data item size=%u expected=%u\n",
query_item->length, total_size);
return -EINVAL;
}
if (get_user(flags, &user_query_config_ptr->flags))
return -EFAULT;
if (flags != 0)
return -EINVAL;
if (use_uuid) {
struct i915_oa_config *tmp;
int id;
BUILD_BUG_ON(sizeof(user_query_config_ptr->uuid) >= sizeof(uuid));
memset(&uuid, 0, sizeof(uuid));
if (copy_from_user(uuid, user_query_config_ptr->uuid,
sizeof(user_query_config_ptr->uuid)))
return -EFAULT;
oa_config = NULL;
rcu_read_lock();
idr_for_each_entry(&perf->metrics_idr, tmp, id) {
if (!strcmp(tmp->uuid, uuid)) {
oa_config = i915_oa_config_get(tmp);
break;
}
}
rcu_read_unlock();
} else {
if (get_user(config_id, &user_query_config_ptr->config))
return -EFAULT;
oa_config = i915_perf_get_oa_config(perf, config_id);
}
if (!oa_config)
return -ENOENT;
if (copy_from_user(&user_config, user_config_ptr, sizeof(user_config))) {
ret = -EFAULT;
goto out;
}
ret = can_copy_perf_config_registers_or_number(user_config.n_boolean_regs,
user_config.boolean_regs_ptr,
oa_config->b_counter_regs_len);
if (ret)
goto out;
ret = can_copy_perf_config_registers_or_number(user_config.n_flex_regs,
user_config.flex_regs_ptr,
oa_config->flex_regs_len);
if (ret)
goto out;
ret = can_copy_perf_config_registers_or_number(user_config.n_mux_regs,
user_config.mux_regs_ptr,
oa_config->mux_regs_len);
if (ret)
goto out;
ret = copy_perf_config_registers_or_number(oa_config->b_counter_regs,
oa_config->b_counter_regs_len,
user_config.boolean_regs_ptr,
&user_config.n_boolean_regs);
if (ret)
goto out;
ret = copy_perf_config_registers_or_number(oa_config->flex_regs,
oa_config->flex_regs_len,
user_config.flex_regs_ptr,
&user_config.n_flex_regs);
if (ret)
goto out;
ret = copy_perf_config_registers_or_number(oa_config->mux_regs,
oa_config->mux_regs_len,
user_config.mux_regs_ptr,
&user_config.n_mux_regs);
if (ret)
goto out;
memcpy(user_config.uuid, oa_config->uuid, sizeof(user_config.uuid));
if (copy_to_user(user_config_ptr, &user_config, sizeof(user_config))) {
ret = -EFAULT;
goto out;
}
ret = total_size;
out:
i915_oa_config_put(oa_config);
return ret;
}
static size_t sizeof_perf_config_list(size_t count)
{
return sizeof(struct drm_i915_query_perf_config) + sizeof(u64) * count;
}
static size_t sizeof_perf_metrics(struct i915_perf *perf)
{
struct i915_oa_config *tmp;
size_t i;
int id;
i = 1;
rcu_read_lock();
idr_for_each_entry(&perf->metrics_idr, tmp, id)
i++;
rcu_read_unlock();
return sizeof_perf_config_list(i);
}
static int query_perf_config_list(struct drm_i915_private *i915,
struct drm_i915_query_item *query_item)
{
struct drm_i915_query_perf_config __user *user_query_config_ptr =
u64_to_user_ptr(query_item->data_ptr);
struct i915_perf *perf = &i915->perf;
u64 *oa_config_ids = NULL;
int alloc, n_configs;
u32 flags;
int ret;
if (!perf->i915)
return -ENODEV;
if (query_item->length == 0)
return sizeof_perf_metrics(perf);
if (get_user(flags, &user_query_config_ptr->flags))
return -EFAULT;
if (flags != 0)
return -EINVAL;
n_configs = 1;
do {
struct i915_oa_config *tmp;
u64 *ids;
int id;
ids = krealloc(oa_config_ids,
n_configs * sizeof(*oa_config_ids),
GFP_KERNEL);
if (!ids)
return -ENOMEM;
alloc = fetch_and_zero(&n_configs);
ids[n_configs++] = 1ull; /* reserved for test_config */
rcu_read_lock();
idr_for_each_entry(&perf->metrics_idr, tmp, id) {
if (n_configs < alloc)
ids[n_configs] = id;
n_configs++;
}
rcu_read_unlock();
oa_config_ids = ids;
} while (n_configs > alloc);
if (query_item->length < sizeof_perf_config_list(n_configs)) {
drm_dbg(&i915->drm,
"Invalid query config list item size=%u expected=%zu\n",
query_item->length,
sizeof_perf_config_list(n_configs));
kfree(oa_config_ids);
return -EINVAL;
}
if (put_user(n_configs, &user_query_config_ptr->config)) {
kfree(oa_config_ids);
return -EFAULT;
}
ret = copy_to_user(user_query_config_ptr + 1,
oa_config_ids,
n_configs * sizeof(*oa_config_ids));
kfree(oa_config_ids);
if (ret)
return -EFAULT;
return sizeof_perf_config_list(n_configs);
}
static int query_perf_config(struct drm_i915_private *i915,
struct drm_i915_query_item *query_item)
{
switch (query_item->flags) {
case DRM_I915_QUERY_PERF_CONFIG_LIST:
return query_perf_config_list(i915, query_item);
case DRM_I915_QUERY_PERF_CONFIG_DATA_FOR_UUID:
return query_perf_config_data(i915, query_item, true);
case DRM_I915_QUERY_PERF_CONFIG_DATA_FOR_ID:
return query_perf_config_data(i915, query_item, false);
default:
return -EINVAL;
}
}
static int query_memregion_info(struct drm_i915_private *i915,
struct drm_i915_query_item *query_item)
{
struct drm_i915_query_memory_regions __user *query_ptr =
u64_to_user_ptr(query_item->data_ptr);
struct drm_i915_memory_region_info __user *info_ptr =
&query_ptr->regions[0];
struct drm_i915_memory_region_info info = { };
struct drm_i915_query_memory_regions query;
struct intel_memory_region *mr;
u32 total_length;
int ret, id, i;
if (query_item->flags != 0)
return -EINVAL;
total_length = sizeof(query);
for_each_memory_region(mr, i915, id) {
if (mr->private)
continue;
total_length += sizeof(info);
}
ret = copy_query_item(&query, sizeof(query), total_length, query_item);
if (ret != 0)
return ret;
if (query.num_regions)
return -EINVAL;
for (i = 0; i < ARRAY_SIZE(query.rsvd); i++) {
if (query.rsvd[i])
return -EINVAL;
}
for_each_memory_region(mr, i915, id) {
if (mr->private)
continue;
info.region.memory_class = mr->type;
info.region.memory_instance = mr->instance;
info.probed_size = mr->total;
if (mr->type == INTEL_MEMORY_LOCAL)
info.probed_cpu_visible_size = mr->io_size;
else
info.probed_cpu_visible_size = mr->total;
if (perfmon_capable()) {
intel_memory_region_avail(mr,
&info.unallocated_size,
&info.unallocated_cpu_visible_size);
} else {
info.unallocated_size = info.probed_size;
info.unallocated_cpu_visible_size =
info.probed_cpu_visible_size;
}
if (__copy_to_user(info_ptr, &info, sizeof(info)))
return -EFAULT;
query.num_regions++;
info_ptr++;
}
if (__copy_to_user(query_ptr, &query, sizeof(query)))
return -EFAULT;
return total_length;
}
static int query_hwconfig_blob(struct drm_i915_private *i915,
struct drm_i915_query_item *query_item)
{
struct intel_gt *gt = to_gt(i915);
struct intel_hwconfig *hwconfig = >->info.hwconfig;
if (!hwconfig->size || !hwconfig->ptr)
return -ENODEV;
if (query_item->length == 0)
return hwconfig->size;
if (query_item->length < hwconfig->size)
return -EINVAL;
if (copy_to_user(u64_to_user_ptr(query_item->data_ptr),
hwconfig->ptr, hwconfig->size))
return -EFAULT;
return hwconfig->size;
}
static int (* const i915_query_funcs[])(struct drm_i915_private *dev_priv,
struct drm_i915_query_item *query_item) = {
query_topology_info,
query_engine_info,
query_perf_config,
query_memregion_info,
query_hwconfig_blob,
query_geometry_subslices,
};
int i915_query_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
{
struct drm_i915_private *dev_priv = to_i915(dev);
struct drm_i915_query *args = data;
struct drm_i915_query_item __user *user_item_ptr =
u64_to_user_ptr(args->items_ptr);
u32 i;
if (args->flags != 0)
return -EINVAL;
for (i = 0; i < args->num_items; i++, user_item_ptr++) {
struct drm_i915_query_item item;
unsigned long func_idx;
int ret;
if (copy_from_user(&item, user_item_ptr, sizeof(item)))
return -EFAULT;
if (item.query_id == 0)
return -EINVAL;
if (overflows_type(item.query_id - 1, unsigned long))
return -EINVAL;
func_idx = item.query_id - 1;
ret = -EINVAL;
if (func_idx < ARRAY_SIZE(i915_query_funcs)) {
func_idx = array_index_nospec(func_idx,
ARRAY_SIZE(i915_query_funcs));
ret = i915_query_funcs[func_idx](dev_priv, &item);
}
/* Only write the length back to userspace if they differ. */
if (ret != item.length && put_user(ret, &user_item_ptr->length))
return -EFAULT;
}
return 0;
}
| linux-master | drivers/gpu/drm/i915/i915_query.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2019 Intel Corporation
*/
#include "i915_sw_fence_work.h"
static void fence_complete(struct dma_fence_work *f)
{
if (f->ops->release)
f->ops->release(f);
dma_fence_signal(&f->dma);
}
static void fence_work(struct work_struct *work)
{
struct dma_fence_work *f = container_of(work, typeof(*f), work);
f->ops->work(f);
fence_complete(f);
dma_fence_put(&f->dma);
}
static int
fence_notify(struct i915_sw_fence *fence, enum i915_sw_fence_notify state)
{
struct dma_fence_work *f = container_of(fence, typeof(*f), chain);
switch (state) {
case FENCE_COMPLETE:
if (fence->error)
dma_fence_set_error(&f->dma, fence->error);
if (!f->dma.error) {
dma_fence_get(&f->dma);
if (test_bit(DMA_FENCE_WORK_IMM, &f->dma.flags))
fence_work(&f->work);
else
queue_work(system_unbound_wq, &f->work);
} else {
fence_complete(f);
}
break;
case FENCE_FREE:
dma_fence_put(&f->dma);
break;
}
return NOTIFY_DONE;
}
static const char *get_driver_name(struct dma_fence *fence)
{
return "dma-fence";
}
static const char *get_timeline_name(struct dma_fence *fence)
{
struct dma_fence_work *f = container_of(fence, typeof(*f), dma);
return f->ops->name ?: "work";
}
static void fence_release(struct dma_fence *fence)
{
struct dma_fence_work *f = container_of(fence, typeof(*f), dma);
i915_sw_fence_fini(&f->chain);
BUILD_BUG_ON(offsetof(typeof(*f), dma));
dma_fence_free(&f->dma);
}
static const struct dma_fence_ops fence_ops = {
.get_driver_name = get_driver_name,
.get_timeline_name = get_timeline_name,
.release = fence_release,
};
void dma_fence_work_init(struct dma_fence_work *f,
const struct dma_fence_work_ops *ops)
{
f->ops = ops;
spin_lock_init(&f->lock);
dma_fence_init(&f->dma, &fence_ops, &f->lock, 0, 0);
i915_sw_fence_init(&f->chain, fence_notify);
INIT_WORK(&f->work, fence_work);
}
int dma_fence_work_chain(struct dma_fence_work *f, struct dma_fence *signal)
{
if (!signal)
return 0;
return __i915_sw_fence_await_dma_fence(&f->chain, signal, &f->cb);
}
| linux-master | drivers/gpu/drm/i915/i915_sw_fence_work.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2019 Intel Corporation
*/
#include <linux/kernel.h>
#include "i915_debugfs_params.h"
#include "gt/intel_gt.h"
#include "gt/uc/intel_guc.h"
#include "i915_drv.h"
#include "i915_params.h"
#define MATCH_DEBUGFS_NODE_NAME(_file, _name) \
(strcmp((_file)->f_path.dentry->d_name.name, (_name)) == 0)
#define GET_I915(i915, name, ptr) \
do { \
struct i915_params *params; \
params = container_of(((void *)(ptr)), typeof(*params), name); \
(i915) = container_of(params, typeof(*(i915)), params); \
} while (0)
/* int param */
static int i915_param_int_show(struct seq_file *m, void *data)
{
int *value = m->private;
seq_printf(m, "%d\n", *value);
return 0;
}
static int i915_param_int_open(struct inode *inode, struct file *file)
{
return single_open(file, i915_param_int_show, inode->i_private);
}
static int notify_guc(struct drm_i915_private *i915)
{
int ret = 0;
if (intel_uc_uses_guc_submission(&to_gt(i915)->uc))
ret = intel_guc_global_policies_update(&to_gt(i915)->uc.guc);
return ret;
}
static ssize_t i915_param_int_write(struct file *file,
const char __user *ubuf, size_t len,
loff_t *offp)
{
struct seq_file *m = file->private_data;
int *value = m->private;
int ret;
ret = kstrtoint_from_user(ubuf, len, 0, value);
if (ret) {
/* support boolean values too */
bool b;
ret = kstrtobool_from_user(ubuf, len, &b);
if (!ret)
*value = b;
}
return ret ?: len;
}
static const struct file_operations i915_param_int_fops = {
.owner = THIS_MODULE,
.open = i915_param_int_open,
.read = seq_read,
.write = i915_param_int_write,
.llseek = default_llseek,
.release = single_release,
};
static const struct file_operations i915_param_int_fops_ro = {
.owner = THIS_MODULE,
.open = i915_param_int_open,
.read = seq_read,
.llseek = default_llseek,
.release = single_release,
};
/* unsigned int param */
static int i915_param_uint_show(struct seq_file *m, void *data)
{
unsigned int *value = m->private;
seq_printf(m, "%u\n", *value);
return 0;
}
static int i915_param_uint_open(struct inode *inode, struct file *file)
{
return single_open(file, i915_param_uint_show, inode->i_private);
}
static ssize_t i915_param_uint_write(struct file *file,
const char __user *ubuf, size_t len,
loff_t *offp)
{
struct drm_i915_private *i915;
struct seq_file *m = file->private_data;
unsigned int *value = m->private;
unsigned int old = *value;
int ret;
ret = kstrtouint_from_user(ubuf, len, 0, value);
if (ret) {
/* support boolean values too */
bool b;
ret = kstrtobool_from_user(ubuf, len, &b);
if (!ret)
*value = b;
}
if (!ret && MATCH_DEBUGFS_NODE_NAME(file, "reset")) {
GET_I915(i915, reset, value);
ret = notify_guc(i915);
if (ret)
*value = old;
}
return ret ?: len;
}
static const struct file_operations i915_param_uint_fops = {
.owner = THIS_MODULE,
.open = i915_param_uint_open,
.read = seq_read,
.write = i915_param_uint_write,
.llseek = default_llseek,
.release = single_release,
};
static const struct file_operations i915_param_uint_fops_ro = {
.owner = THIS_MODULE,
.open = i915_param_uint_open,
.read = seq_read,
.llseek = default_llseek,
.release = single_release,
};
/* char * param */
static int i915_param_charp_show(struct seq_file *m, void *data)
{
const char **s = m->private;
seq_printf(m, "%s\n", *s);
return 0;
}
static int i915_param_charp_open(struct inode *inode, struct file *file)
{
return single_open(file, i915_param_charp_show, inode->i_private);
}
static ssize_t i915_param_charp_write(struct file *file,
const char __user *ubuf, size_t len,
loff_t *offp)
{
struct seq_file *m = file->private_data;
char **s = m->private;
char *new, *old;
old = *s;
new = strndup_user(ubuf, PAGE_SIZE);
if (IS_ERR(new)) {
len = PTR_ERR(new);
goto out;
}
*s = new;
kfree(old);
out:
return len;
}
static const struct file_operations i915_param_charp_fops = {
.owner = THIS_MODULE,
.open = i915_param_charp_open,
.read = seq_read,
.write = i915_param_charp_write,
.llseek = default_llseek,
.release = single_release,
};
static const struct file_operations i915_param_charp_fops_ro = {
.owner = THIS_MODULE,
.open = i915_param_charp_open,
.read = seq_read,
.llseek = default_llseek,
.release = single_release,
};
#define RO(mode) (((mode) & 0222) == 0)
static struct dentry *
i915_debugfs_create_int(const char *name, umode_t mode,
struct dentry *parent, int *value)
{
return debugfs_create_file_unsafe(name, mode, parent, value,
RO(mode) ? &i915_param_int_fops_ro :
&i915_param_int_fops);
}
static struct dentry *
i915_debugfs_create_uint(const char *name, umode_t mode,
struct dentry *parent, unsigned int *value)
{
return debugfs_create_file_unsafe(name, mode, parent, value,
RO(mode) ? &i915_param_uint_fops_ro :
&i915_param_uint_fops);
}
static struct dentry *
i915_debugfs_create_charp(const char *name, umode_t mode,
struct dentry *parent, char **value)
{
return debugfs_create_file(name, mode, parent, value,
RO(mode) ? &i915_param_charp_fops_ro :
&i915_param_charp_fops);
}
#define _i915_param_create_file(parent, name, mode, valp) \
do { \
if (mode) \
_Generic(valp, \
bool *: debugfs_create_bool, \
int *: i915_debugfs_create_int, \
unsigned int *: i915_debugfs_create_uint, \
unsigned long *: debugfs_create_ulong, \
char **: i915_debugfs_create_charp)(name, mode, parent, valp); \
} while(0)
/* add a subdirectory with files for each i915 param */
struct dentry *i915_debugfs_params(struct drm_i915_private *i915)
{
struct drm_minor *minor = i915->drm.primary;
struct i915_params *params = &i915->params;
struct dentry *dir;
dir = debugfs_create_dir("i915_params", minor->debugfs_root);
if (IS_ERR(dir))
return dir;
/*
* Note: We could create files for params needing special handling
* here. Set mode in params to 0 to skip the generic create file, or
* just let the generic create file fail silently with -EEXIST.
*/
#define REGISTER(T, x, unused, mode, ...) _i915_param_create_file(dir, #x, mode, ¶ms->x);
I915_PARAMS_FOR_EACH(REGISTER);
#undef REGISTER
return dir;
}
| linux-master | drivers/gpu/drm/i915/i915_debugfs_params.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2021 Intel Corporation
*/
#include <linux/kernel.h>
#include <linux/moduleparam.h>
#include <linux/slab.h>
#include <linux/string.h>
#include "i915_driver.h"
#include "i915_drv.h"
#include "i915_mitigations.h"
static unsigned long mitigations __read_mostly = ~0UL;
enum {
CLEAR_RESIDUALS = 0,
};
static const char * const names[] = {
[CLEAR_RESIDUALS] = "residuals",
};
bool i915_mitigate_clear_residuals(void)
{
return READ_ONCE(mitigations) & BIT(CLEAR_RESIDUALS);
}
static int mitigations_set(const char *val, const struct kernel_param *kp)
{
unsigned long new = ~0UL;
char *str, *sep, *tok;
bool first = true;
int err = 0;
BUILD_BUG_ON(ARRAY_SIZE(names) >= BITS_PER_TYPE(mitigations));
str = kstrdup(val, GFP_KERNEL);
if (!str)
return -ENOMEM;
for (sep = str; (tok = strsep(&sep, ","));) {
bool enable = true;
int i;
/* Be tolerant of leading/trailing whitespace */
tok = strim(tok);
if (first) {
first = false;
if (!strcmp(tok, "auto"))
continue;
new = 0;
if (!strcmp(tok, "off"))
continue;
}
if (*tok == '!') {
enable = !enable;
tok++;
}
if (!strncmp(tok, "no", 2)) {
enable = !enable;
tok += 2;
}
if (*tok == '\0')
continue;
for (i = 0; i < ARRAY_SIZE(names); i++) {
if (!strcmp(tok, names[i])) {
if (enable)
new |= BIT(i);
else
new &= ~BIT(i);
break;
}
}
if (i == ARRAY_SIZE(names)) {
pr_err("Bad \"%s.mitigations=%s\", '%s' is unknown\n",
DRIVER_NAME, val, tok);
err = -EINVAL;
break;
}
}
kfree(str);
if (err)
return err;
WRITE_ONCE(mitigations, new);
return 0;
}
static int mitigations_get(char *buffer, const struct kernel_param *kp)
{
unsigned long local = READ_ONCE(mitigations);
int count, i;
bool enable;
if (!local)
return scnprintf(buffer, PAGE_SIZE, "%s\n", "off");
if (local & BIT(BITS_PER_LONG - 1)) {
count = scnprintf(buffer, PAGE_SIZE, "%s,", "auto");
enable = false;
} else {
enable = true;
count = 0;
}
for (i = 0; i < ARRAY_SIZE(names); i++) {
if ((local & BIT(i)) != enable)
continue;
count += scnprintf(buffer + count, PAGE_SIZE - count,
"%s%s,", enable ? "" : "!", names[i]);
}
buffer[count - 1] = '\n';
return count;
}
static const struct kernel_param_ops ops = {
.set = mitigations_set,
.get = mitigations_get,
};
module_param_cb_unsafe(mitigations, &ops, NULL, 0600);
MODULE_PARM_DESC(mitigations,
"Selectively enable security mitigations for all Intel® GPUs in the system.\n"
"\n"
" auto -- enables all mitigations required for the platform [default]\n"
" off -- disables all mitigations\n"
"\n"
"Individual mitigations can be enabled by passing a comma-separated string,\n"
"e.g. mitigations=residuals to enable only clearing residuals or\n"
"mitigations=auto,noresiduals to disable only the clear residual mitigation.\n"
"Either '!' or 'no' may be used to switch from enabling the mitigation to\n"
"disabling it.\n"
"\n"
"Active mitigations for Ivybridge, Baytrail, Haswell:\n"
" residuals -- clear all thread-local registers between contexts"
);
| linux-master | drivers/gpu/drm/i915/i915_mitigations.c |
// SPDX-License-Identifier: GPL-2.0
/*
* Copyright © 2009 Intel Corporation
*
* Authors:
* Chris Wilson <[email protected]>
*/
#include "i915_drv.h"
#ifndef __CHECKER__
#define CREATE_TRACE_POINTS
#include "i915_trace.h"
#endif
| linux-master | drivers/gpu/drm/i915/i915_trace_points.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2021 Intel Corporation
*/
#include <linux/slab.h>
#include <drm/ttm/ttm_placement.h>
#include <drm/ttm/ttm_bo.h>
#include <drm/drm_buddy.h>
#include "i915_ttm_buddy_manager.h"
#include "i915_gem.h"
struct i915_ttm_buddy_manager {
struct ttm_resource_manager manager;
struct drm_buddy mm;
struct list_head reserved;
struct mutex lock;
unsigned long visible_size;
unsigned long visible_avail;
unsigned long visible_reserved;
u64 default_page_size;
};
static struct i915_ttm_buddy_manager *
to_buddy_manager(struct ttm_resource_manager *man)
{
return container_of(man, struct i915_ttm_buddy_manager, manager);
}
static int i915_ttm_buddy_man_alloc(struct ttm_resource_manager *man,
struct ttm_buffer_object *bo,
const struct ttm_place *place,
struct ttm_resource **res)
{
struct i915_ttm_buddy_manager *bman = to_buddy_manager(man);
struct i915_ttm_buddy_resource *bman_res;
struct drm_buddy *mm = &bman->mm;
unsigned long n_pages, lpfn;
u64 min_page_size;
u64 size;
int err;
lpfn = place->lpfn;
if (!lpfn)
lpfn = man->size;
bman_res = kzalloc(sizeof(*bman_res), GFP_KERNEL);
if (!bman_res)
return -ENOMEM;
ttm_resource_init(bo, place, &bman_res->base);
INIT_LIST_HEAD(&bman_res->blocks);
bman_res->mm = mm;
if (place->flags & TTM_PL_FLAG_TOPDOWN)
bman_res->flags |= DRM_BUDDY_TOPDOWN_ALLOCATION;
if (place->fpfn || lpfn != man->size)
bman_res->flags |= DRM_BUDDY_RANGE_ALLOCATION;
GEM_BUG_ON(!bman_res->base.size);
size = bman_res->base.size;
min_page_size = bman->default_page_size;
if (bo->page_alignment)
min_page_size = bo->page_alignment << PAGE_SHIFT;
GEM_BUG_ON(min_page_size < mm->chunk_size);
GEM_BUG_ON(!IS_ALIGNED(size, min_page_size));
if (place->fpfn + PFN_UP(bman_res->base.size) != place->lpfn &&
place->flags & TTM_PL_FLAG_CONTIGUOUS) {
unsigned long pages;
size = roundup_pow_of_two(size);
min_page_size = size;
pages = size >> ilog2(mm->chunk_size);
if (pages > lpfn)
lpfn = pages;
}
if (size > lpfn << PAGE_SHIFT) {
err = -E2BIG;
goto err_free_res;
}
n_pages = size >> ilog2(mm->chunk_size);
mutex_lock(&bman->lock);
if (lpfn <= bman->visible_size && n_pages > bman->visible_avail) {
mutex_unlock(&bman->lock);
err = -ENOSPC;
goto err_free_res;
}
err = drm_buddy_alloc_blocks(mm, (u64)place->fpfn << PAGE_SHIFT,
(u64)lpfn << PAGE_SHIFT,
(u64)n_pages << PAGE_SHIFT,
min_page_size,
&bman_res->blocks,
bman_res->flags);
if (unlikely(err))
goto err_free_blocks;
if (place->flags & TTM_PL_FLAG_CONTIGUOUS) {
u64 original_size = (u64)bman_res->base.size;
drm_buddy_block_trim(mm,
original_size,
&bman_res->blocks);
}
if (lpfn <= bman->visible_size) {
bman_res->used_visible_size = PFN_UP(bman_res->base.size);
} else {
struct drm_buddy_block *block;
list_for_each_entry(block, &bman_res->blocks, link) {
unsigned long start =
drm_buddy_block_offset(block) >> PAGE_SHIFT;
if (start < bman->visible_size) {
unsigned long end = start +
(drm_buddy_block_size(mm, block) >> PAGE_SHIFT);
bman_res->used_visible_size +=
min(end, bman->visible_size) - start;
}
}
}
if (bman_res->used_visible_size)
bman->visible_avail -= bman_res->used_visible_size;
mutex_unlock(&bman->lock);
*res = &bman_res->base;
return 0;
err_free_blocks:
drm_buddy_free_list(mm, &bman_res->blocks);
mutex_unlock(&bman->lock);
err_free_res:
ttm_resource_fini(man, &bman_res->base);
kfree(bman_res);
return err;
}
static void i915_ttm_buddy_man_free(struct ttm_resource_manager *man,
struct ttm_resource *res)
{
struct i915_ttm_buddy_resource *bman_res = to_ttm_buddy_resource(res);
struct i915_ttm_buddy_manager *bman = to_buddy_manager(man);
mutex_lock(&bman->lock);
drm_buddy_free_list(&bman->mm, &bman_res->blocks);
bman->visible_avail += bman_res->used_visible_size;
mutex_unlock(&bman->lock);
ttm_resource_fini(man, res);
kfree(bman_res);
}
static bool i915_ttm_buddy_man_intersects(struct ttm_resource_manager *man,
struct ttm_resource *res,
const struct ttm_place *place,
size_t size)
{
struct i915_ttm_buddy_resource *bman_res = to_ttm_buddy_resource(res);
struct i915_ttm_buddy_manager *bman = to_buddy_manager(man);
struct drm_buddy *mm = &bman->mm;
struct drm_buddy_block *block;
if (!place->fpfn && !place->lpfn)
return true;
GEM_BUG_ON(!place->lpfn);
/*
* If we just want something mappable then we can quickly check
* if the current victim resource is using any of the CPU
* visible portion.
*/
if (!place->fpfn &&
place->lpfn == i915_ttm_buddy_man_visible_size(man))
return bman_res->used_visible_size > 0;
/* Check each drm buddy block individually */
list_for_each_entry(block, &bman_res->blocks, link) {
unsigned long fpfn =
drm_buddy_block_offset(block) >> PAGE_SHIFT;
unsigned long lpfn = fpfn +
(drm_buddy_block_size(mm, block) >> PAGE_SHIFT);
if (place->fpfn < lpfn && place->lpfn > fpfn)
return true;
}
return false;
}
static bool i915_ttm_buddy_man_compatible(struct ttm_resource_manager *man,
struct ttm_resource *res,
const struct ttm_place *place,
size_t size)
{
struct i915_ttm_buddy_resource *bman_res = to_ttm_buddy_resource(res);
struct i915_ttm_buddy_manager *bman = to_buddy_manager(man);
struct drm_buddy *mm = &bman->mm;
struct drm_buddy_block *block;
if (!place->fpfn && !place->lpfn)
return true;
GEM_BUG_ON(!place->lpfn);
if (!place->fpfn &&
place->lpfn == i915_ttm_buddy_man_visible_size(man))
return bman_res->used_visible_size == PFN_UP(res->size);
/* Check each drm buddy block individually */
list_for_each_entry(block, &bman_res->blocks, link) {
unsigned long fpfn =
drm_buddy_block_offset(block) >> PAGE_SHIFT;
unsigned long lpfn = fpfn +
(drm_buddy_block_size(mm, block) >> PAGE_SHIFT);
if (fpfn < place->fpfn || lpfn > place->lpfn)
return false;
}
return true;
}
static void i915_ttm_buddy_man_debug(struct ttm_resource_manager *man,
struct drm_printer *printer)
{
struct i915_ttm_buddy_manager *bman = to_buddy_manager(man);
struct drm_buddy_block *block;
mutex_lock(&bman->lock);
drm_printf(printer, "default_page_size: %lluKiB\n",
bman->default_page_size >> 10);
drm_printf(printer, "visible_avail: %lluMiB\n",
(u64)bman->visible_avail << PAGE_SHIFT >> 20);
drm_printf(printer, "visible_size: %lluMiB\n",
(u64)bman->visible_size << PAGE_SHIFT >> 20);
drm_printf(printer, "visible_reserved: %lluMiB\n",
(u64)bman->visible_reserved << PAGE_SHIFT >> 20);
drm_buddy_print(&bman->mm, printer);
drm_printf(printer, "reserved:\n");
list_for_each_entry(block, &bman->reserved, link)
drm_buddy_block_print(&bman->mm, block, printer);
mutex_unlock(&bman->lock);
}
static const struct ttm_resource_manager_func i915_ttm_buddy_manager_func = {
.alloc = i915_ttm_buddy_man_alloc,
.free = i915_ttm_buddy_man_free,
.intersects = i915_ttm_buddy_man_intersects,
.compatible = i915_ttm_buddy_man_compatible,
.debug = i915_ttm_buddy_man_debug,
};
/**
* i915_ttm_buddy_man_init - Setup buddy allocator based ttm manager
* @bdev: The ttm device
* @type: Memory type we want to manage
* @use_tt: Set use_tt for the manager
* @size: The size in bytes to manage
* @visible_size: The CPU visible size in bytes to manage
* @default_page_size: The default minimum page size in bytes for allocations,
* this must be at least as large as @chunk_size, and can be overridden by
* setting the BO page_alignment, to be larger or smaller as needed.
* @chunk_size: The minimum page size in bytes for our allocations i.e
* order-zero
*
* Note that the starting address is assumed to be zero here, since this
* simplifies keeping the property where allocated blocks having natural
* power-of-two alignment. So long as the real starting address is some large
* power-of-two, or naturally start from zero, then this should be fine. Also
* the &i915_ttm_buddy_man_reserve interface can be used to preserve alignment
* if say there is some unusable range from the start of the region. We can
* revisit this in the future and make the interface accept an actual starting
* offset and let it take care of the rest.
*
* Note that if the @size is not aligned to the @chunk_size then we perform the
* required rounding to get the usable size. The final size in pages can be
* taken from &ttm_resource_manager.size.
*
* Return: 0 on success, negative error code on failure.
*/
int i915_ttm_buddy_man_init(struct ttm_device *bdev,
unsigned int type, bool use_tt,
u64 size, u64 visible_size, u64 default_page_size,
u64 chunk_size)
{
struct ttm_resource_manager *man;
struct i915_ttm_buddy_manager *bman;
int err;
bman = kzalloc(sizeof(*bman), GFP_KERNEL);
if (!bman)
return -ENOMEM;
err = drm_buddy_init(&bman->mm, size, chunk_size);
if (err)
goto err_free_bman;
mutex_init(&bman->lock);
INIT_LIST_HEAD(&bman->reserved);
GEM_BUG_ON(default_page_size < chunk_size);
bman->default_page_size = default_page_size;
bman->visible_size = visible_size >> PAGE_SHIFT;
bman->visible_avail = bman->visible_size;
man = &bman->manager;
man->use_tt = use_tt;
man->func = &i915_ttm_buddy_manager_func;
ttm_resource_manager_init(man, bdev, bman->mm.size >> PAGE_SHIFT);
ttm_resource_manager_set_used(man, true);
ttm_set_driver_manager(bdev, type, man);
return 0;
err_free_bman:
kfree(bman);
return err;
}
/**
* i915_ttm_buddy_man_fini - Destroy the buddy allocator ttm manager
* @bdev: The ttm device
* @type: Memory type we want to manage
*
* Note that if we reserved anything with &i915_ttm_buddy_man_reserve, this will
* also be freed for us here.
*
* Return: 0 on success, negative error code on failure.
*/
int i915_ttm_buddy_man_fini(struct ttm_device *bdev, unsigned int type)
{
struct ttm_resource_manager *man = ttm_manager_type(bdev, type);
struct i915_ttm_buddy_manager *bman = to_buddy_manager(man);
struct drm_buddy *mm = &bman->mm;
int ret;
ttm_resource_manager_set_used(man, false);
ret = ttm_resource_manager_evict_all(bdev, man);
if (ret)
return ret;
ttm_set_driver_manager(bdev, type, NULL);
mutex_lock(&bman->lock);
drm_buddy_free_list(mm, &bman->reserved);
drm_buddy_fini(mm);
bman->visible_avail += bman->visible_reserved;
WARN_ON_ONCE(bman->visible_avail != bman->visible_size);
mutex_unlock(&bman->lock);
ttm_resource_manager_cleanup(man);
kfree(bman);
return 0;
}
/**
* i915_ttm_buddy_man_reserve - Reserve address range
* @man: The buddy allocator ttm manager
* @start: The offset in bytes, where the region start is assumed to be zero
* @size: The size in bytes
*
* Note that the starting address for the region is always assumed to be zero.
*
* Return: 0 on success, negative error code on failure.
*/
int i915_ttm_buddy_man_reserve(struct ttm_resource_manager *man,
u64 start, u64 size)
{
struct i915_ttm_buddy_manager *bman = to_buddy_manager(man);
struct drm_buddy *mm = &bman->mm;
unsigned long fpfn = start >> PAGE_SHIFT;
unsigned long flags = 0;
int ret;
flags |= DRM_BUDDY_RANGE_ALLOCATION;
mutex_lock(&bman->lock);
ret = drm_buddy_alloc_blocks(mm, start,
start + size,
size, mm->chunk_size,
&bman->reserved,
flags);
if (fpfn < bman->visible_size) {
unsigned long lpfn = fpfn + (size >> PAGE_SHIFT);
unsigned long visible = min(lpfn, bman->visible_size) - fpfn;
bman->visible_reserved += visible;
bman->visible_avail -= visible;
}
mutex_unlock(&bman->lock);
return ret;
}
/**
* i915_ttm_buddy_man_visible_size - Return the size of the CPU visible portion
* in pages.
* @man: The buddy allocator ttm manager
*/
u64 i915_ttm_buddy_man_visible_size(struct ttm_resource_manager *man)
{
struct i915_ttm_buddy_manager *bman = to_buddy_manager(man);
return bman->visible_size;
}
/**
* i915_ttm_buddy_man_avail - Query the avail tracking for the manager.
*
* @man: The buddy allocator ttm manager
* @avail: The total available memory in pages for the entire manager.
* @visible_avail: The total available memory in pages for the CPU visible
* portion. Note that this will always give the same value as @avail on
* configurations that don't have a small BAR.
*/
void i915_ttm_buddy_man_avail(struct ttm_resource_manager *man,
u64 *avail, u64 *visible_avail)
{
struct i915_ttm_buddy_manager *bman = to_buddy_manager(man);
mutex_lock(&bman->lock);
*avail = bman->mm.avail >> PAGE_SHIFT;
*visible_avail = bman->visible_avail;
mutex_unlock(&bman->lock);
}
#if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
void i915_ttm_buddy_man_force_visible_size(struct ttm_resource_manager *man,
u64 size)
{
struct i915_ttm_buddy_manager *bman = to_buddy_manager(man);
bman->visible_size = size;
}
#endif
| linux-master | drivers/gpu/drm/i915/i915_ttm_buddy_manager.c |
/*
* Copyright © 2008-2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* Authors:
* Eric Anholt <[email protected]>
* Chris Wilson <[email protected]>
*
*/
#include "gem/i915_gem_context.h"
#include "gt/intel_gt.h"
#include "gt/intel_gt_requests.h"
#include "i915_drv.h"
#include "i915_gem_evict.h"
#include "i915_trace.h"
I915_SELFTEST_DECLARE(static struct igt_evict_ctl {
bool fail_if_busy:1;
} igt_evict_ctl;)
static bool dying_vma(struct i915_vma *vma)
{
return !kref_read(&vma->obj->base.refcount);
}
static int ggtt_flush(struct i915_address_space *vm)
{
struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
struct intel_gt *gt;
int ret = 0;
list_for_each_entry(gt, &ggtt->gt_list, ggtt_link) {
/*
* Not everything in the GGTT is tracked via vma (otherwise we
* could evict as required with minimal stalling) so we are forced
* to idle the GPU and explicitly retire outstanding requests in
* the hopes that we can then remove contexts and the like only
* bound by their active reference.
*/
ret = intel_gt_wait_for_idle(gt, MAX_SCHEDULE_TIMEOUT);
if (ret)
return ret;
}
return ret;
}
static bool grab_vma(struct i915_vma *vma, struct i915_gem_ww_ctx *ww)
{
/*
* We add the extra refcount so the object doesn't drop to zero until
* after ungrab_vma(), this way trylock is always paired with unlock.
*/
if (i915_gem_object_get_rcu(vma->obj)) {
if (!i915_gem_object_trylock(vma->obj, ww)) {
i915_gem_object_put(vma->obj);
return false;
}
} else {
/* Dead objects don't need pins */
atomic_and(~I915_VMA_PIN_MASK, &vma->flags);
}
return true;
}
static void ungrab_vma(struct i915_vma *vma)
{
if (dying_vma(vma))
return;
i915_gem_object_unlock(vma->obj);
i915_gem_object_put(vma->obj);
}
static bool
mark_free(struct drm_mm_scan *scan,
struct i915_gem_ww_ctx *ww,
struct i915_vma *vma,
unsigned int flags,
struct list_head *unwind)
{
if (i915_vma_is_pinned(vma))
return false;
if (!grab_vma(vma, ww))
return false;
list_add(&vma->evict_link, unwind);
return drm_mm_scan_add_block(scan, &vma->node);
}
static bool defer_evict(struct i915_vma *vma)
{
if (i915_vma_is_active(vma))
return true;
if (i915_vma_is_scanout(vma))
return true;
return false;
}
/**
* i915_gem_evict_something - Evict vmas to make room for binding a new one
* @vm: address space to evict from
* @ww: An optional struct i915_gem_ww_ctx.
* @min_size: size of the desired free space
* @alignment: alignment constraint of the desired free space
* @color: color for the desired space
* @start: start (inclusive) of the range from which to evict objects
* @end: end (exclusive) of the range from which to evict objects
* @flags: additional flags to control the eviction algorithm
*
* This function will try to evict vmas until a free space satisfying the
* requirements is found. Callers must check first whether any such hole exists
* already before calling this function.
*
* This function is used by the object/vma binding code.
*
* Since this function is only used to free up virtual address space it only
* ignores pinned vmas, and not object where the backing storage itself is
* pinned. Hence obj->pages_pin_count does not protect against eviction.
*
* To clarify: This is for freeing up virtual address space, not for freeing
* memory in e.g. the shrinker.
*/
int
i915_gem_evict_something(struct i915_address_space *vm,
struct i915_gem_ww_ctx *ww,
u64 min_size, u64 alignment,
unsigned long color,
u64 start, u64 end,
unsigned flags)
{
struct drm_mm_scan scan;
struct list_head eviction_list;
struct i915_vma *vma, *next;
struct drm_mm_node *node;
enum drm_mm_insert_mode mode;
struct i915_vma *active;
struct intel_gt *gt;
int ret;
lockdep_assert_held(&vm->mutex);
trace_i915_gem_evict(vm, min_size, alignment, flags);
/*
* The goal is to evict objects and amalgamate space in rough LRU order.
* Since both active and inactive objects reside on the same list,
* in a mix of creation and last scanned order, as we process the list
* we sort it into inactive/active, which keeps the active portion
* in a rough MRU order.
*
* The retirement sequence is thus:
* 1. Inactive objects (already retired, random order)
* 2. Active objects (will stall on unbinding, oldest scanned first)
*/
mode = DRM_MM_INSERT_BEST;
if (flags & PIN_HIGH)
mode = DRM_MM_INSERT_HIGH;
if (flags & PIN_MAPPABLE)
mode = DRM_MM_INSERT_LOW;
drm_mm_scan_init_with_range(&scan, &vm->mm,
min_size, alignment, color,
start, end, mode);
if (i915_is_ggtt(vm)) {
struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
list_for_each_entry(gt, &ggtt->gt_list, ggtt_link)
intel_gt_retire_requests(gt);
} else {
intel_gt_retire_requests(vm->gt);
}
search_again:
active = NULL;
INIT_LIST_HEAD(&eviction_list);
list_for_each_entry_safe(vma, next, &vm->bound_list, vm_link) {
if (vma == active) { /* now seen this vma twice */
if (flags & PIN_NONBLOCK)
break;
active = ERR_PTR(-EAGAIN);
}
/*
* We keep this list in a rough least-recently scanned order
* of active elements (inactive elements are cheap to reap).
* New entries are added to the end, and we move anything we
* scan to the end. The assumption is that the working set
* of applications is either steady state (and thanks to the
* userspace bo cache it almost always is) or volatile and
* frequently replaced after a frame, which are self-evicting!
* Given that assumption, the MRU order of the scan list is
* fairly static, and keeping it in least-recently scan order
* is suitable.
*
* To notice when we complete one full cycle, we record the
* first active element seen, before moving it to the tail.
*/
if (active != ERR_PTR(-EAGAIN) && defer_evict(vma)) {
if (!active)
active = vma;
list_move_tail(&vma->vm_link, &vm->bound_list);
continue;
}
if (mark_free(&scan, ww, vma, flags, &eviction_list))
goto found;
}
/* Nothing found, clean up and bail out! */
list_for_each_entry_safe(vma, next, &eviction_list, evict_link) {
ret = drm_mm_scan_remove_block(&scan, &vma->node);
BUG_ON(ret);
ungrab_vma(vma);
}
/*
* Can we unpin some objects such as idle hw contents,
* or pending flips? But since only the GGTT has global entries
* such as scanouts, rinbuffers and contexts, we can skip the
* purge when inspecting per-process local address spaces.
*/
if (!i915_is_ggtt(vm) || flags & PIN_NONBLOCK)
return -ENOSPC;
/*
* Not everything in the GGTT is tracked via VMA using
* i915_vma_move_to_active(), otherwise we could evict as required
* with minimal stalling. Instead we are forced to idle the GPU and
* explicitly retire outstanding requests which will then remove
* the pinning for active objects such as contexts and ring,
* enabling us to evict them on the next iteration.
*
* To ensure that all user contexts are evictable, we perform
* a switch to the perma-pinned kernel context. This all also gives
* us a termination condition, when the last retired context is
* the kernel's there is no more we can evict.
*/
if (I915_SELFTEST_ONLY(igt_evict_ctl.fail_if_busy))
return -EBUSY;
ret = ggtt_flush(vm);
if (ret)
return ret;
cond_resched();
flags |= PIN_NONBLOCK;
goto search_again;
found:
/* drm_mm doesn't allow any other other operations while
* scanning, therefore store to-be-evicted objects on a
* temporary list and take a reference for all before
* calling unbind (which may remove the active reference
* of any of our objects, thus corrupting the list).
*/
list_for_each_entry_safe(vma, next, &eviction_list, evict_link) {
if (drm_mm_scan_remove_block(&scan, &vma->node)) {
__i915_vma_pin(vma);
} else {
list_del(&vma->evict_link);
ungrab_vma(vma);
}
}
/* Unbinding will emit any required flushes */
ret = 0;
list_for_each_entry_safe(vma, next, &eviction_list, evict_link) {
__i915_vma_unpin(vma);
if (ret == 0)
ret = __i915_vma_unbind(vma);
ungrab_vma(vma);
}
while (ret == 0 && (node = drm_mm_scan_color_evict(&scan))) {
vma = container_of(node, struct i915_vma, node);
/* If we find any non-objects (!vma), we cannot evict them */
if (vma->node.color != I915_COLOR_UNEVICTABLE &&
grab_vma(vma, ww)) {
ret = __i915_vma_unbind(vma);
ungrab_vma(vma);
} else {
ret = -ENOSPC;
}
}
return ret;
}
/**
* i915_gem_evict_for_node - Evict vmas to make room for binding a new one
* @vm: address space to evict from
* @ww: An optional struct i915_gem_ww_ctx.
* @target: range (and color) to evict for
* @flags: additional flags to control the eviction algorithm
*
* This function will try to evict vmas that overlap the target node.
*
* To clarify: This is for freeing up virtual address space, not for freeing
* memory in e.g. the shrinker.
*/
int i915_gem_evict_for_node(struct i915_address_space *vm,
struct i915_gem_ww_ctx *ww,
struct drm_mm_node *target,
unsigned int flags)
{
LIST_HEAD(eviction_list);
struct drm_mm_node *node;
u64 start = target->start;
u64 end = start + target->size;
struct i915_vma *vma, *next;
int ret = 0;
lockdep_assert_held(&vm->mutex);
GEM_BUG_ON(!IS_ALIGNED(start, I915_GTT_PAGE_SIZE));
GEM_BUG_ON(!IS_ALIGNED(end, I915_GTT_PAGE_SIZE));
trace_i915_gem_evict_node(vm, target, flags);
/*
* Retire before we search the active list. Although we have
* reasonable accuracy in our retirement lists, we may have
* a stray pin (preventing eviction) that can only be resolved by
* retiring.
*/
if (i915_is_ggtt(vm)) {
struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
struct intel_gt *gt;
list_for_each_entry(gt, &ggtt->gt_list, ggtt_link)
intel_gt_retire_requests(gt);
} else {
intel_gt_retire_requests(vm->gt);
}
if (i915_vm_has_cache_coloring(vm)) {
/* Expand search to cover neighbouring guard pages (or lack!) */
if (start)
start -= I915_GTT_PAGE_SIZE;
/* Always look at the page afterwards to avoid the end-of-GTT */
end += I915_GTT_PAGE_SIZE;
}
GEM_BUG_ON(start >= end);
drm_mm_for_each_node_in_range(node, &vm->mm, start, end) {
/* If we find any non-objects (!vma), we cannot evict them */
if (node->color == I915_COLOR_UNEVICTABLE) {
ret = -ENOSPC;
break;
}
GEM_BUG_ON(!drm_mm_node_allocated(node));
vma = container_of(node, typeof(*vma), node);
/*
* If we are using coloring to insert guard pages between
* different cache domains within the address space, we have
* to check whether the objects on either side of our range
* abutt and conflict. If they are in conflict, then we evict
* those as well to make room for our guard pages.
*/
if (i915_vm_has_cache_coloring(vm)) {
if (node->start + node->size == target->start) {
if (node->color == target->color)
continue;
}
if (node->start == target->start + target->size) {
if (node->color == target->color)
continue;
}
}
if (i915_vma_is_pinned(vma)) {
ret = -ENOSPC;
break;
}
if (flags & PIN_NONBLOCK && i915_vma_is_active(vma)) {
ret = -ENOSPC;
break;
}
if (!grab_vma(vma, ww)) {
ret = -ENOSPC;
break;
}
/*
* Never show fear in the face of dragons!
*
* We cannot directly remove this node from within this
* iterator and as with i915_gem_evict_something() we employ
* the vma pin_count in order to prevent the action of
* unbinding one vma from freeing (by dropping its active
* reference) another in our eviction list.
*/
__i915_vma_pin(vma);
list_add(&vma->evict_link, &eviction_list);
}
list_for_each_entry_safe(vma, next, &eviction_list, evict_link) {
__i915_vma_unpin(vma);
if (ret == 0)
ret = __i915_vma_unbind(vma);
ungrab_vma(vma);
}
return ret;
}
/**
* i915_gem_evict_vm - Evict all idle vmas from a vm
* @vm: Address space to cleanse
* @ww: An optional struct i915_gem_ww_ctx. If not NULL, i915_gem_evict_vm
* will be able to evict vma's locked by the ww as well.
* @busy_bo: Optional pointer to struct drm_i915_gem_object. If not NULL, then
* in the event i915_gem_evict_vm() is unable to trylock an object for eviction,
* then @busy_bo will point to it. -EBUSY is also returned. The caller must drop
* the vm->mutex, before trying again to acquire the contended lock. The caller
* also owns a reference to the object.
*
* This function evicts all vmas from a vm.
*
* This is used by the execbuf code as a last-ditch effort to defragment the
* address space.
*
* To clarify: This is for freeing up virtual address space, not for freeing
* memory in e.g. the shrinker.
*/
int i915_gem_evict_vm(struct i915_address_space *vm, struct i915_gem_ww_ctx *ww,
struct drm_i915_gem_object **busy_bo)
{
int ret = 0;
lockdep_assert_held(&vm->mutex);
trace_i915_gem_evict_vm(vm);
/* Switch back to the default context in order to unpin
* the existing context objects. However, such objects only
* pin themselves inside the global GTT and performing the
* switch otherwise is ineffective.
*/
if (i915_is_ggtt(vm)) {
ret = ggtt_flush(vm);
if (ret)
return ret;
}
do {
struct i915_vma *vma, *vn;
LIST_HEAD(eviction_list);
LIST_HEAD(locked_eviction_list);
list_for_each_entry(vma, &vm->bound_list, vm_link) {
if (i915_vma_is_pinned(vma))
continue;
/*
* If we already own the lock, trylock fails. In case
* the resv is shared among multiple objects, we still
* need the object ref.
*/
if (!i915_gem_object_get_rcu(vma->obj) ||
(ww && (dma_resv_locking_ctx(vma->obj->base.resv) == &ww->ctx))) {
__i915_vma_pin(vma);
list_add(&vma->evict_link, &locked_eviction_list);
continue;
}
if (!i915_gem_object_trylock(vma->obj, ww)) {
if (busy_bo) {
*busy_bo = vma->obj; /* holds ref */
ret = -EBUSY;
break;
}
i915_gem_object_put(vma->obj);
continue;
}
__i915_vma_pin(vma);
list_add(&vma->evict_link, &eviction_list);
}
if (list_empty(&eviction_list) && list_empty(&locked_eviction_list))
break;
/* Unbind locked objects first, before unlocking the eviction_list */
list_for_each_entry_safe(vma, vn, &locked_eviction_list, evict_link) {
__i915_vma_unpin(vma);
if (ret == 0) {
ret = __i915_vma_unbind(vma);
if (ret != -EINTR) /* "Get me out of here!" */
ret = 0;
}
if (!dying_vma(vma))
i915_gem_object_put(vma->obj);
}
list_for_each_entry_safe(vma, vn, &eviction_list, evict_link) {
__i915_vma_unpin(vma);
if (ret == 0) {
ret = __i915_vma_unbind(vma);
if (ret != -EINTR) /* "Get me out of here!" */
ret = 0;
}
i915_gem_object_unlock(vma->obj);
i915_gem_object_put(vma->obj);
}
} while (ret == 0);
return ret;
}
#if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
#include "selftests/i915_gem_evict.c"
#endif
| linux-master | drivers/gpu/drm/i915/i915_gem_evict.c |
/*
* Copyright © 2013 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* Authors:
* Brad Volkin <[email protected]>
*
*/
#include <linux/highmem.h>
#include <drm/drm_cache.h>
#include "gt/intel_engine.h"
#include "gt/intel_engine_regs.h"
#include "gt/intel_gpu_commands.h"
#include "gt/intel_gt_regs.h"
#include "i915_cmd_parser.h"
#include "i915_drv.h"
#include "i915_memcpy.h"
#include "i915_reg.h"
/**
* DOC: batch buffer command parser
*
* Motivation:
* Certain OpenGL features (e.g. transform feedback, performance monitoring)
* require userspace code to submit batches containing commands such as
* MI_LOAD_REGISTER_IMM to access various registers. Unfortunately, some
* generations of the hardware will noop these commands in "unsecure" batches
* (which includes all userspace batches submitted via i915) even though the
* commands may be safe and represent the intended programming model of the
* device.
*
* The software command parser is similar in operation to the command parsing
* done in hardware for unsecure batches. However, the software parser allows
* some operations that would be noop'd by hardware, if the parser determines
* the operation is safe, and submits the batch as "secure" to prevent hardware
* parsing.
*
* Threats:
* At a high level, the hardware (and software) checks attempt to prevent
* granting userspace undue privileges. There are three categories of privilege.
*
* First, commands which are explicitly defined as privileged or which should
* only be used by the kernel driver. The parser rejects such commands
*
* Second, commands which access registers. To support correct/enhanced
* userspace functionality, particularly certain OpenGL extensions, the parser
* provides a whitelist of registers which userspace may safely access
*
* Third, commands which access privileged memory (i.e. GGTT, HWS page, etc).
* The parser always rejects such commands.
*
* The majority of the problematic commands fall in the MI_* range, with only a
* few specific commands on each engine (e.g. PIPE_CONTROL and MI_FLUSH_DW).
*
* Implementation:
* Each engine maintains tables of commands and registers which the parser
* uses in scanning batch buffers submitted to that engine.
*
* Since the set of commands that the parser must check for is significantly
* smaller than the number of commands supported, the parser tables contain only
* those commands required by the parser. This generally works because command
* opcode ranges have standard command length encodings. So for commands that
* the parser does not need to check, it can easily skip them. This is
* implemented via a per-engine length decoding vfunc.
*
* Unfortunately, there are a number of commands that do not follow the standard
* length encoding for their opcode range, primarily amongst the MI_* commands.
* To handle this, the parser provides a way to define explicit "skip" entries
* in the per-engine command tables.
*
* Other command table entries map fairly directly to high level categories
* mentioned above: rejected, register whitelist. The parser implements a number
* of checks, including the privileged memory checks, via a general bitmasking
* mechanism.
*/
/*
* A command that requires special handling by the command parser.
*/
struct drm_i915_cmd_descriptor {
/*
* Flags describing how the command parser processes the command.
*
* CMD_DESC_FIXED: The command has a fixed length if this is set,
* a length mask if not set
* CMD_DESC_SKIP: The command is allowed but does not follow the
* standard length encoding for the opcode range in
* which it falls
* CMD_DESC_REJECT: The command is never allowed
* CMD_DESC_REGISTER: The command should be checked against the
* register whitelist for the appropriate ring
*/
u32 flags;
#define CMD_DESC_FIXED (1<<0)
#define CMD_DESC_SKIP (1<<1)
#define CMD_DESC_REJECT (1<<2)
#define CMD_DESC_REGISTER (1<<3)
#define CMD_DESC_BITMASK (1<<4)
/*
* The command's unique identification bits and the bitmask to get them.
* This isn't strictly the opcode field as defined in the spec and may
* also include type, subtype, and/or subop fields.
*/
struct {
u32 value;
u32 mask;
} cmd;
/*
* The command's length. The command is either fixed length (i.e. does
* not include a length field) or has a length field mask. The flag
* CMD_DESC_FIXED indicates a fixed length. Otherwise, the command has
* a length mask. All command entries in a command table must include
* length information.
*/
union {
u32 fixed;
u32 mask;
} length;
/*
* Describes where to find a register address in the command to check
* against the ring's register whitelist. Only valid if flags has the
* CMD_DESC_REGISTER bit set.
*
* A non-zero step value implies that the command may access multiple
* registers in sequence (e.g. LRI), in that case step gives the
* distance in dwords between individual offset fields.
*/
struct {
u32 offset;
u32 mask;
u32 step;
} reg;
#define MAX_CMD_DESC_BITMASKS 3
/*
* Describes command checks where a particular dword is masked and
* compared against an expected value. If the command does not match
* the expected value, the parser rejects it. Only valid if flags has
* the CMD_DESC_BITMASK bit set. Only entries where mask is non-zero
* are valid.
*
* If the check specifies a non-zero condition_mask then the parser
* only performs the check when the bits specified by condition_mask
* are non-zero.
*/
struct {
u32 offset;
u32 mask;
u32 expected;
u32 condition_offset;
u32 condition_mask;
} bits[MAX_CMD_DESC_BITMASKS];
};
/*
* A table of commands requiring special handling by the command parser.
*
* Each engine has an array of tables. Each table consists of an array of
* command descriptors, which must be sorted with command opcodes in
* ascending order.
*/
struct drm_i915_cmd_table {
const struct drm_i915_cmd_descriptor *table;
int count;
};
#define STD_MI_OPCODE_SHIFT (32 - 9)
#define STD_3D_OPCODE_SHIFT (32 - 16)
#define STD_2D_OPCODE_SHIFT (32 - 10)
#define STD_MFX_OPCODE_SHIFT (32 - 16)
#define MIN_OPCODE_SHIFT 16
#define CMD(op, opm, f, lm, fl, ...) \
{ \
.flags = (fl) | ((f) ? CMD_DESC_FIXED : 0), \
.cmd = { (op & ~0u << (opm)), ~0u << (opm) }, \
.length = { (lm) }, \
__VA_ARGS__ \
}
/* Convenience macros to compress the tables */
#define SMI STD_MI_OPCODE_SHIFT
#define S3D STD_3D_OPCODE_SHIFT
#define S2D STD_2D_OPCODE_SHIFT
#define SMFX STD_MFX_OPCODE_SHIFT
#define F true
#define S CMD_DESC_SKIP
#define R CMD_DESC_REJECT
#define W CMD_DESC_REGISTER
#define B CMD_DESC_BITMASK
/* Command Mask Fixed Len Action
---------------------------------------------------------- */
static const struct drm_i915_cmd_descriptor gen7_common_cmds[] = {
CMD( MI_NOOP, SMI, F, 1, S ),
CMD( MI_USER_INTERRUPT, SMI, F, 1, R ),
CMD( MI_WAIT_FOR_EVENT, SMI, F, 1, R ),
CMD( MI_ARB_CHECK, SMI, F, 1, S ),
CMD( MI_REPORT_HEAD, SMI, F, 1, S ),
CMD( MI_SUSPEND_FLUSH, SMI, F, 1, S ),
CMD( MI_SEMAPHORE_MBOX, SMI, !F, 0xFF, R ),
CMD( MI_STORE_DWORD_INDEX, SMI, !F, 0xFF, R ),
CMD( MI_LOAD_REGISTER_IMM(1), SMI, !F, 0xFF, W,
.reg = { .offset = 1, .mask = 0x007FFFFC, .step = 2 } ),
CMD( MI_STORE_REGISTER_MEM, SMI, F, 3, W | B,
.reg = { .offset = 1, .mask = 0x007FFFFC },
.bits = {{
.offset = 0,
.mask = MI_GLOBAL_GTT,
.expected = 0,
}}, ),
CMD( MI_LOAD_REGISTER_MEM, SMI, F, 3, W | B,
.reg = { .offset = 1, .mask = 0x007FFFFC },
.bits = {{
.offset = 0,
.mask = MI_GLOBAL_GTT,
.expected = 0,
}}, ),
/*
* MI_BATCH_BUFFER_START requires some special handling. It's not
* really a 'skip' action but it doesn't seem like it's worth adding
* a new action. See intel_engine_cmd_parser().
*/
CMD( MI_BATCH_BUFFER_START, SMI, !F, 0xFF, S ),
};
static const struct drm_i915_cmd_descriptor gen7_render_cmds[] = {
CMD( MI_FLUSH, SMI, F, 1, S ),
CMD( MI_ARB_ON_OFF, SMI, F, 1, R ),
CMD( MI_PREDICATE, SMI, F, 1, S ),
CMD( MI_TOPOLOGY_FILTER, SMI, F, 1, S ),
CMD( MI_SET_APPID, SMI, F, 1, S ),
CMD( MI_DISPLAY_FLIP, SMI, !F, 0xFF, R ),
CMD( MI_SET_CONTEXT, SMI, !F, 0xFF, R ),
CMD( MI_URB_CLEAR, SMI, !F, 0xFF, S ),
CMD( MI_STORE_DWORD_IMM, SMI, !F, 0x3F, B,
.bits = {{
.offset = 0,
.mask = MI_GLOBAL_GTT,
.expected = 0,
}}, ),
CMD( MI_UPDATE_GTT, SMI, !F, 0xFF, R ),
CMD( MI_CLFLUSH, SMI, !F, 0x3FF, B,
.bits = {{
.offset = 0,
.mask = MI_GLOBAL_GTT,
.expected = 0,
}}, ),
CMD( MI_REPORT_PERF_COUNT, SMI, !F, 0x3F, B,
.bits = {{
.offset = 1,
.mask = MI_REPORT_PERF_COUNT_GGTT,
.expected = 0,
}}, ),
CMD( MI_CONDITIONAL_BATCH_BUFFER_END, SMI, !F, 0xFF, B,
.bits = {{
.offset = 0,
.mask = MI_GLOBAL_GTT,
.expected = 0,
}}, ),
CMD( GFX_OP_3DSTATE_VF_STATISTICS, S3D, F, 1, S ),
CMD( PIPELINE_SELECT, S3D, F, 1, S ),
CMD( MEDIA_VFE_STATE, S3D, !F, 0xFFFF, B,
.bits = {{
.offset = 2,
.mask = MEDIA_VFE_STATE_MMIO_ACCESS_MASK,
.expected = 0,
}}, ),
CMD( GPGPU_OBJECT, S3D, !F, 0xFF, S ),
CMD( GPGPU_WALKER, S3D, !F, 0xFF, S ),
CMD( GFX_OP_3DSTATE_SO_DECL_LIST, S3D, !F, 0x1FF, S ),
CMD( GFX_OP_PIPE_CONTROL(5), S3D, !F, 0xFF, B,
.bits = {{
.offset = 1,
.mask = (PIPE_CONTROL_MMIO_WRITE | PIPE_CONTROL_NOTIFY),
.expected = 0,
},
{
.offset = 1,
.mask = (PIPE_CONTROL_GLOBAL_GTT_IVB |
PIPE_CONTROL_STORE_DATA_INDEX),
.expected = 0,
.condition_offset = 1,
.condition_mask = PIPE_CONTROL_POST_SYNC_OP_MASK,
}}, ),
};
static const struct drm_i915_cmd_descriptor hsw_render_cmds[] = {
CMD( MI_SET_PREDICATE, SMI, F, 1, S ),
CMD( MI_RS_CONTROL, SMI, F, 1, S ),
CMD( MI_URB_ATOMIC_ALLOC, SMI, F, 1, S ),
CMD( MI_SET_APPID, SMI, F, 1, S ),
CMD( MI_RS_CONTEXT, SMI, F, 1, S ),
CMD( MI_LOAD_SCAN_LINES_INCL, SMI, !F, 0x3F, R ),
CMD( MI_LOAD_SCAN_LINES_EXCL, SMI, !F, 0x3F, R ),
CMD( MI_LOAD_REGISTER_REG, SMI, !F, 0xFF, W,
.reg = { .offset = 1, .mask = 0x007FFFFC, .step = 1 } ),
CMD( MI_RS_STORE_DATA_IMM, SMI, !F, 0xFF, S ),
CMD( MI_LOAD_URB_MEM, SMI, !F, 0xFF, S ),
CMD( MI_STORE_URB_MEM, SMI, !F, 0xFF, S ),
CMD( GFX_OP_3DSTATE_DX9_CONSTANTF_VS, S3D, !F, 0x7FF, S ),
CMD( GFX_OP_3DSTATE_DX9_CONSTANTF_PS, S3D, !F, 0x7FF, S ),
CMD( GFX_OP_3DSTATE_BINDING_TABLE_EDIT_VS, S3D, !F, 0x1FF, S ),
CMD( GFX_OP_3DSTATE_BINDING_TABLE_EDIT_GS, S3D, !F, 0x1FF, S ),
CMD( GFX_OP_3DSTATE_BINDING_TABLE_EDIT_HS, S3D, !F, 0x1FF, S ),
CMD( GFX_OP_3DSTATE_BINDING_TABLE_EDIT_DS, S3D, !F, 0x1FF, S ),
CMD( GFX_OP_3DSTATE_BINDING_TABLE_EDIT_PS, S3D, !F, 0x1FF, S ),
};
static const struct drm_i915_cmd_descriptor gen7_video_cmds[] = {
CMD( MI_ARB_ON_OFF, SMI, F, 1, R ),
CMD( MI_SET_APPID, SMI, F, 1, S ),
CMD( MI_STORE_DWORD_IMM, SMI, !F, 0xFF, B,
.bits = {{
.offset = 0,
.mask = MI_GLOBAL_GTT,
.expected = 0,
}}, ),
CMD( MI_UPDATE_GTT, SMI, !F, 0x3F, R ),
CMD( MI_FLUSH_DW, SMI, !F, 0x3F, B,
.bits = {{
.offset = 0,
.mask = MI_FLUSH_DW_NOTIFY,
.expected = 0,
},
{
.offset = 1,
.mask = MI_FLUSH_DW_USE_GTT,
.expected = 0,
.condition_offset = 0,
.condition_mask = MI_FLUSH_DW_OP_MASK,
},
{
.offset = 0,
.mask = MI_FLUSH_DW_STORE_INDEX,
.expected = 0,
.condition_offset = 0,
.condition_mask = MI_FLUSH_DW_OP_MASK,
}}, ),
CMD( MI_CONDITIONAL_BATCH_BUFFER_END, SMI, !F, 0xFF, B,
.bits = {{
.offset = 0,
.mask = MI_GLOBAL_GTT,
.expected = 0,
}}, ),
/*
* MFX_WAIT doesn't fit the way we handle length for most commands.
* It has a length field but it uses a non-standard length bias.
* It is always 1 dword though, so just treat it as fixed length.
*/
CMD( MFX_WAIT, SMFX, F, 1, S ),
};
static const struct drm_i915_cmd_descriptor gen7_vecs_cmds[] = {
CMD( MI_ARB_ON_OFF, SMI, F, 1, R ),
CMD( MI_SET_APPID, SMI, F, 1, S ),
CMD( MI_STORE_DWORD_IMM, SMI, !F, 0xFF, B,
.bits = {{
.offset = 0,
.mask = MI_GLOBAL_GTT,
.expected = 0,
}}, ),
CMD( MI_UPDATE_GTT, SMI, !F, 0x3F, R ),
CMD( MI_FLUSH_DW, SMI, !F, 0x3F, B,
.bits = {{
.offset = 0,
.mask = MI_FLUSH_DW_NOTIFY,
.expected = 0,
},
{
.offset = 1,
.mask = MI_FLUSH_DW_USE_GTT,
.expected = 0,
.condition_offset = 0,
.condition_mask = MI_FLUSH_DW_OP_MASK,
},
{
.offset = 0,
.mask = MI_FLUSH_DW_STORE_INDEX,
.expected = 0,
.condition_offset = 0,
.condition_mask = MI_FLUSH_DW_OP_MASK,
}}, ),
CMD( MI_CONDITIONAL_BATCH_BUFFER_END, SMI, !F, 0xFF, B,
.bits = {{
.offset = 0,
.mask = MI_GLOBAL_GTT,
.expected = 0,
}}, ),
};
static const struct drm_i915_cmd_descriptor gen7_blt_cmds[] = {
CMD( MI_DISPLAY_FLIP, SMI, !F, 0xFF, R ),
CMD( MI_STORE_DWORD_IMM, SMI, !F, 0x3FF, B,
.bits = {{
.offset = 0,
.mask = MI_GLOBAL_GTT,
.expected = 0,
}}, ),
CMD( MI_UPDATE_GTT, SMI, !F, 0x3F, R ),
CMD( MI_FLUSH_DW, SMI, !F, 0x3F, B,
.bits = {{
.offset = 0,
.mask = MI_FLUSH_DW_NOTIFY,
.expected = 0,
},
{
.offset = 1,
.mask = MI_FLUSH_DW_USE_GTT,
.expected = 0,
.condition_offset = 0,
.condition_mask = MI_FLUSH_DW_OP_MASK,
},
{
.offset = 0,
.mask = MI_FLUSH_DW_STORE_INDEX,
.expected = 0,
.condition_offset = 0,
.condition_mask = MI_FLUSH_DW_OP_MASK,
}}, ),
CMD( COLOR_BLT, S2D, !F, 0x3F, S ),
CMD( SRC_COPY_BLT, S2D, !F, 0x3F, S ),
};
static const struct drm_i915_cmd_descriptor hsw_blt_cmds[] = {
CMD( MI_LOAD_SCAN_LINES_INCL, SMI, !F, 0x3F, R ),
CMD( MI_LOAD_SCAN_LINES_EXCL, SMI, !F, 0x3F, R ),
};
/*
* For Gen9 we can still rely on the h/w to enforce cmd security, and only
* need to re-enforce the register access checks. We therefore only need to
* teach the cmdparser how to find the end of each command, and identify
* register accesses. The table doesn't need to reject any commands, and so
* the only commands listed here are:
* 1) Those that touch registers
* 2) Those that do not have the default 8-bit length
*
* Note that the default MI length mask chosen for this table is 0xFF, not
* the 0x3F used on older devices. This is because the vast majority of MI
* cmds on Gen9 use a standard 8-bit Length field.
* All the Gen9 blitter instructions are standard 0xFF length mask, and
* none allow access to non-general registers, so in fact no BLT cmds are
* included in the table at all.
*
*/
static const struct drm_i915_cmd_descriptor gen9_blt_cmds[] = {
CMD( MI_NOOP, SMI, F, 1, S ),
CMD( MI_USER_INTERRUPT, SMI, F, 1, S ),
CMD( MI_WAIT_FOR_EVENT, SMI, F, 1, S ),
CMD( MI_FLUSH, SMI, F, 1, S ),
CMD( MI_ARB_CHECK, SMI, F, 1, S ),
CMD( MI_REPORT_HEAD, SMI, F, 1, S ),
CMD( MI_ARB_ON_OFF, SMI, F, 1, S ),
CMD( MI_SUSPEND_FLUSH, SMI, F, 1, S ),
CMD( MI_LOAD_SCAN_LINES_INCL, SMI, !F, 0x3F, S ),
CMD( MI_LOAD_SCAN_LINES_EXCL, SMI, !F, 0x3F, S ),
CMD( MI_STORE_DWORD_IMM, SMI, !F, 0x3FF, S ),
CMD( MI_LOAD_REGISTER_IMM(1), SMI, !F, 0xFF, W,
.reg = { .offset = 1, .mask = 0x007FFFFC, .step = 2 } ),
CMD( MI_UPDATE_GTT, SMI, !F, 0x3FF, S ),
CMD( MI_STORE_REGISTER_MEM_GEN8, SMI, F, 4, W,
.reg = { .offset = 1, .mask = 0x007FFFFC } ),
CMD( MI_FLUSH_DW, SMI, !F, 0x3F, S ),
CMD( MI_LOAD_REGISTER_MEM_GEN8, SMI, F, 4, W,
.reg = { .offset = 1, .mask = 0x007FFFFC } ),
CMD( MI_LOAD_REGISTER_REG, SMI, !F, 0xFF, W,
.reg = { .offset = 1, .mask = 0x007FFFFC, .step = 1 } ),
/*
* We allow BB_START but apply further checks. We just sanitize the
* basic fields here.
*/
#define MI_BB_START_OPERAND_MASK GENMASK(SMI-1, 0)
#define MI_BB_START_OPERAND_EXPECT (MI_BATCH_PPGTT_HSW | 1)
CMD( MI_BATCH_BUFFER_START_GEN8, SMI, !F, 0xFF, B,
.bits = {{
.offset = 0,
.mask = MI_BB_START_OPERAND_MASK,
.expected = MI_BB_START_OPERAND_EXPECT,
}}, ),
};
static const struct drm_i915_cmd_descriptor noop_desc =
CMD(MI_NOOP, SMI, F, 1, S);
#undef CMD
#undef SMI
#undef S3D
#undef S2D
#undef SMFX
#undef F
#undef S
#undef R
#undef W
#undef B
static const struct drm_i915_cmd_table gen7_render_cmd_table[] = {
{ gen7_common_cmds, ARRAY_SIZE(gen7_common_cmds) },
{ gen7_render_cmds, ARRAY_SIZE(gen7_render_cmds) },
};
static const struct drm_i915_cmd_table hsw_render_ring_cmd_table[] = {
{ gen7_common_cmds, ARRAY_SIZE(gen7_common_cmds) },
{ gen7_render_cmds, ARRAY_SIZE(gen7_render_cmds) },
{ hsw_render_cmds, ARRAY_SIZE(hsw_render_cmds) },
};
static const struct drm_i915_cmd_table gen7_video_cmd_table[] = {
{ gen7_common_cmds, ARRAY_SIZE(gen7_common_cmds) },
{ gen7_video_cmds, ARRAY_SIZE(gen7_video_cmds) },
};
static const struct drm_i915_cmd_table hsw_vebox_cmd_table[] = {
{ gen7_common_cmds, ARRAY_SIZE(gen7_common_cmds) },
{ gen7_vecs_cmds, ARRAY_SIZE(gen7_vecs_cmds) },
};
static const struct drm_i915_cmd_table gen7_blt_cmd_table[] = {
{ gen7_common_cmds, ARRAY_SIZE(gen7_common_cmds) },
{ gen7_blt_cmds, ARRAY_SIZE(gen7_blt_cmds) },
};
static const struct drm_i915_cmd_table hsw_blt_ring_cmd_table[] = {
{ gen7_common_cmds, ARRAY_SIZE(gen7_common_cmds) },
{ gen7_blt_cmds, ARRAY_SIZE(gen7_blt_cmds) },
{ hsw_blt_cmds, ARRAY_SIZE(hsw_blt_cmds) },
};
static const struct drm_i915_cmd_table gen9_blt_cmd_table[] = {
{ gen9_blt_cmds, ARRAY_SIZE(gen9_blt_cmds) },
};
/*
* Register whitelists, sorted by increasing register offset.
*/
/*
* An individual whitelist entry granting access to register addr. If
* mask is non-zero the argument of immediate register writes will be
* AND-ed with mask, and the command will be rejected if the result
* doesn't match value.
*
* Registers with non-zero mask are only allowed to be written using
* LRI.
*/
struct drm_i915_reg_descriptor {
i915_reg_t addr;
u32 mask;
u32 value;
};
/* Convenience macro for adding 32-bit registers. */
#define REG32(_reg, ...) \
{ .addr = (_reg), __VA_ARGS__ }
#define REG32_IDX(_reg, idx) \
{ .addr = _reg(idx) }
/*
* Convenience macro for adding 64-bit registers.
*
* Some registers that userspace accesses are 64 bits. The register
* access commands only allow 32-bit accesses. Hence, we have to include
* entries for both halves of the 64-bit registers.
*/
#define REG64(_reg) \
{ .addr = _reg }, \
{ .addr = _reg ## _UDW }
#define REG64_IDX(_reg, idx) \
{ .addr = _reg(idx) }, \
{ .addr = _reg ## _UDW(idx) }
#define REG64_BASE_IDX(_reg, base, idx) \
{ .addr = _reg(base, idx) }, \
{ .addr = _reg ## _UDW(base, idx) }
static const struct drm_i915_reg_descriptor gen7_render_regs[] = {
REG64(GPGPU_THREADS_DISPATCHED),
REG64(HS_INVOCATION_COUNT),
REG64(DS_INVOCATION_COUNT),
REG64(IA_VERTICES_COUNT),
REG64(IA_PRIMITIVES_COUNT),
REG64(VS_INVOCATION_COUNT),
REG64(GS_INVOCATION_COUNT),
REG64(GS_PRIMITIVES_COUNT),
REG64(CL_INVOCATION_COUNT),
REG64(CL_PRIMITIVES_COUNT),
REG64(PS_INVOCATION_COUNT),
REG64(PS_DEPTH_COUNT),
REG64_IDX(RING_TIMESTAMP, RENDER_RING_BASE),
REG64_IDX(MI_PREDICATE_SRC0, RENDER_RING_BASE),
REG64_IDX(MI_PREDICATE_SRC1, RENDER_RING_BASE),
REG32(GEN7_3DPRIM_END_OFFSET),
REG32(GEN7_3DPRIM_START_VERTEX),
REG32(GEN7_3DPRIM_VERTEX_COUNT),
REG32(GEN7_3DPRIM_INSTANCE_COUNT),
REG32(GEN7_3DPRIM_START_INSTANCE),
REG32(GEN7_3DPRIM_BASE_VERTEX),
REG32(GEN7_GPGPU_DISPATCHDIMX),
REG32(GEN7_GPGPU_DISPATCHDIMY),
REG32(GEN7_GPGPU_DISPATCHDIMZ),
REG64_IDX(RING_TIMESTAMP, BSD_RING_BASE),
REG64_IDX(GEN7_SO_NUM_PRIMS_WRITTEN, 0),
REG64_IDX(GEN7_SO_NUM_PRIMS_WRITTEN, 1),
REG64_IDX(GEN7_SO_NUM_PRIMS_WRITTEN, 2),
REG64_IDX(GEN7_SO_NUM_PRIMS_WRITTEN, 3),
REG64_IDX(GEN7_SO_PRIM_STORAGE_NEEDED, 0),
REG64_IDX(GEN7_SO_PRIM_STORAGE_NEEDED, 1),
REG64_IDX(GEN7_SO_PRIM_STORAGE_NEEDED, 2),
REG64_IDX(GEN7_SO_PRIM_STORAGE_NEEDED, 3),
REG32(GEN7_SO_WRITE_OFFSET(0)),
REG32(GEN7_SO_WRITE_OFFSET(1)),
REG32(GEN7_SO_WRITE_OFFSET(2)),
REG32(GEN7_SO_WRITE_OFFSET(3)),
REG32(GEN7_L3SQCREG1),
REG32(GEN7_L3CNTLREG2),
REG32(GEN7_L3CNTLREG3),
REG64_IDX(RING_TIMESTAMP, BLT_RING_BASE),
};
static const struct drm_i915_reg_descriptor hsw_render_regs[] = {
REG64_BASE_IDX(GEN8_RING_CS_GPR, RENDER_RING_BASE, 0),
REG64_BASE_IDX(GEN8_RING_CS_GPR, RENDER_RING_BASE, 1),
REG64_BASE_IDX(GEN8_RING_CS_GPR, RENDER_RING_BASE, 2),
REG64_BASE_IDX(GEN8_RING_CS_GPR, RENDER_RING_BASE, 3),
REG64_BASE_IDX(GEN8_RING_CS_GPR, RENDER_RING_BASE, 4),
REG64_BASE_IDX(GEN8_RING_CS_GPR, RENDER_RING_BASE, 5),
REG64_BASE_IDX(GEN8_RING_CS_GPR, RENDER_RING_BASE, 6),
REG64_BASE_IDX(GEN8_RING_CS_GPR, RENDER_RING_BASE, 7),
REG64_BASE_IDX(GEN8_RING_CS_GPR, RENDER_RING_BASE, 8),
REG64_BASE_IDX(GEN8_RING_CS_GPR, RENDER_RING_BASE, 9),
REG64_BASE_IDX(GEN8_RING_CS_GPR, RENDER_RING_BASE, 10),
REG64_BASE_IDX(GEN8_RING_CS_GPR, RENDER_RING_BASE, 11),
REG64_BASE_IDX(GEN8_RING_CS_GPR, RENDER_RING_BASE, 12),
REG64_BASE_IDX(GEN8_RING_CS_GPR, RENDER_RING_BASE, 13),
REG64_BASE_IDX(GEN8_RING_CS_GPR, RENDER_RING_BASE, 14),
REG64_BASE_IDX(GEN8_RING_CS_GPR, RENDER_RING_BASE, 15),
REG32(HSW_SCRATCH1,
.mask = ~HSW_SCRATCH1_L3_DATA_ATOMICS_DISABLE,
.value = 0),
REG32(HSW_ROW_CHICKEN3,
.mask = ~(HSW_ROW_CHICKEN3_L3_GLOBAL_ATOMICS_DISABLE << 16 |
HSW_ROW_CHICKEN3_L3_GLOBAL_ATOMICS_DISABLE),
.value = 0),
};
static const struct drm_i915_reg_descriptor gen7_blt_regs[] = {
REG64_IDX(RING_TIMESTAMP, RENDER_RING_BASE),
REG64_IDX(RING_TIMESTAMP, BSD_RING_BASE),
REG32(BCS_SWCTRL),
REG64_IDX(RING_TIMESTAMP, BLT_RING_BASE),
};
static const struct drm_i915_reg_descriptor gen9_blt_regs[] = {
REG64_IDX(RING_TIMESTAMP, RENDER_RING_BASE),
REG64_IDX(RING_TIMESTAMP, BSD_RING_BASE),
REG32(BCS_SWCTRL),
REG64_IDX(RING_TIMESTAMP, BLT_RING_BASE),
REG32_IDX(RING_CTX_TIMESTAMP, BLT_RING_BASE),
REG64_BASE_IDX(GEN8_RING_CS_GPR, BLT_RING_BASE, 0),
REG64_BASE_IDX(GEN8_RING_CS_GPR, BLT_RING_BASE, 1),
REG64_BASE_IDX(GEN8_RING_CS_GPR, BLT_RING_BASE, 2),
REG64_BASE_IDX(GEN8_RING_CS_GPR, BLT_RING_BASE, 3),
REG64_BASE_IDX(GEN8_RING_CS_GPR, BLT_RING_BASE, 4),
REG64_BASE_IDX(GEN8_RING_CS_GPR, BLT_RING_BASE, 5),
REG64_BASE_IDX(GEN8_RING_CS_GPR, BLT_RING_BASE, 6),
REG64_BASE_IDX(GEN8_RING_CS_GPR, BLT_RING_BASE, 7),
REG64_BASE_IDX(GEN8_RING_CS_GPR, BLT_RING_BASE, 8),
REG64_BASE_IDX(GEN8_RING_CS_GPR, BLT_RING_BASE, 9),
REG64_BASE_IDX(GEN8_RING_CS_GPR, BLT_RING_BASE, 10),
REG64_BASE_IDX(GEN8_RING_CS_GPR, BLT_RING_BASE, 11),
REG64_BASE_IDX(GEN8_RING_CS_GPR, BLT_RING_BASE, 12),
REG64_BASE_IDX(GEN8_RING_CS_GPR, BLT_RING_BASE, 13),
REG64_BASE_IDX(GEN8_RING_CS_GPR, BLT_RING_BASE, 14),
REG64_BASE_IDX(GEN8_RING_CS_GPR, BLT_RING_BASE, 15),
};
#undef REG64
#undef REG32
struct drm_i915_reg_table {
const struct drm_i915_reg_descriptor *regs;
int num_regs;
};
static const struct drm_i915_reg_table ivb_render_reg_tables[] = {
{ gen7_render_regs, ARRAY_SIZE(gen7_render_regs) },
};
static const struct drm_i915_reg_table ivb_blt_reg_tables[] = {
{ gen7_blt_regs, ARRAY_SIZE(gen7_blt_regs) },
};
static const struct drm_i915_reg_table hsw_render_reg_tables[] = {
{ gen7_render_regs, ARRAY_SIZE(gen7_render_regs) },
{ hsw_render_regs, ARRAY_SIZE(hsw_render_regs) },
};
static const struct drm_i915_reg_table hsw_blt_reg_tables[] = {
{ gen7_blt_regs, ARRAY_SIZE(gen7_blt_regs) },
};
static const struct drm_i915_reg_table gen9_blt_reg_tables[] = {
{ gen9_blt_regs, ARRAY_SIZE(gen9_blt_regs) },
};
static u32 gen7_render_get_cmd_length_mask(u32 cmd_header)
{
u32 client = cmd_header >> INSTR_CLIENT_SHIFT;
u32 subclient =
(cmd_header & INSTR_SUBCLIENT_MASK) >> INSTR_SUBCLIENT_SHIFT;
if (client == INSTR_MI_CLIENT)
return 0x3F;
else if (client == INSTR_RC_CLIENT) {
if (subclient == INSTR_MEDIA_SUBCLIENT)
return 0xFFFF;
else
return 0xFF;
}
DRM_DEBUG("CMD: Abnormal rcs cmd length! 0x%08X\n", cmd_header);
return 0;
}
static u32 gen7_bsd_get_cmd_length_mask(u32 cmd_header)
{
u32 client = cmd_header >> INSTR_CLIENT_SHIFT;
u32 subclient =
(cmd_header & INSTR_SUBCLIENT_MASK) >> INSTR_SUBCLIENT_SHIFT;
u32 op = (cmd_header & INSTR_26_TO_24_MASK) >> INSTR_26_TO_24_SHIFT;
if (client == INSTR_MI_CLIENT)
return 0x3F;
else if (client == INSTR_RC_CLIENT) {
if (subclient == INSTR_MEDIA_SUBCLIENT) {
if (op == 6)
return 0xFFFF;
else
return 0xFFF;
} else
return 0xFF;
}
DRM_DEBUG("CMD: Abnormal bsd cmd length! 0x%08X\n", cmd_header);
return 0;
}
static u32 gen7_blt_get_cmd_length_mask(u32 cmd_header)
{
u32 client = cmd_header >> INSTR_CLIENT_SHIFT;
if (client == INSTR_MI_CLIENT)
return 0x3F;
else if (client == INSTR_BC_CLIENT)
return 0xFF;
DRM_DEBUG("CMD: Abnormal blt cmd length! 0x%08X\n", cmd_header);
return 0;
}
static u32 gen9_blt_get_cmd_length_mask(u32 cmd_header)
{
u32 client = cmd_header >> INSTR_CLIENT_SHIFT;
if (client == INSTR_MI_CLIENT || client == INSTR_BC_CLIENT)
return 0xFF;
DRM_DEBUG("CMD: Abnormal blt cmd length! 0x%08X\n", cmd_header);
return 0;
}
static bool validate_cmds_sorted(const struct intel_engine_cs *engine,
const struct drm_i915_cmd_table *cmd_tables,
int cmd_table_count)
{
int i;
bool ret = true;
if (!cmd_tables || cmd_table_count == 0)
return true;
for (i = 0; i < cmd_table_count; i++) {
const struct drm_i915_cmd_table *table = &cmd_tables[i];
u32 previous = 0;
int j;
for (j = 0; j < table->count; j++) {
const struct drm_i915_cmd_descriptor *desc =
&table->table[j];
u32 curr = desc->cmd.value & desc->cmd.mask;
if (curr < previous) {
drm_err(&engine->i915->drm,
"CMD: %s [%d] command table not sorted: "
"table=%d entry=%d cmd=0x%08X prev=0x%08X\n",
engine->name, engine->id,
i, j, curr, previous);
ret = false;
}
previous = curr;
}
}
return ret;
}
static bool check_sorted(const struct intel_engine_cs *engine,
const struct drm_i915_reg_descriptor *reg_table,
int reg_count)
{
int i;
u32 previous = 0;
bool ret = true;
for (i = 0; i < reg_count; i++) {
u32 curr = i915_mmio_reg_offset(reg_table[i].addr);
if (curr < previous) {
drm_err(&engine->i915->drm,
"CMD: %s [%d] register table not sorted: "
"entry=%d reg=0x%08X prev=0x%08X\n",
engine->name, engine->id,
i, curr, previous);
ret = false;
}
previous = curr;
}
return ret;
}
static bool validate_regs_sorted(struct intel_engine_cs *engine)
{
int i;
const struct drm_i915_reg_table *table;
for (i = 0; i < engine->reg_table_count; i++) {
table = &engine->reg_tables[i];
if (!check_sorted(engine, table->regs, table->num_regs))
return false;
}
return true;
}
struct cmd_node {
const struct drm_i915_cmd_descriptor *desc;
struct hlist_node node;
};
/*
* Different command ranges have different numbers of bits for the opcode. For
* example, MI commands use bits 31:23 while 3D commands use bits 31:16. The
* problem is that, for example, MI commands use bits 22:16 for other fields
* such as GGTT vs PPGTT bits. If we include those bits in the mask then when
* we mask a command from a batch it could hash to the wrong bucket due to
* non-opcode bits being set. But if we don't include those bits, some 3D
* commands may hash to the same bucket due to not including opcode bits that
* make the command unique. For now, we will risk hashing to the same bucket.
*/
static inline u32 cmd_header_key(u32 x)
{
switch (x >> INSTR_CLIENT_SHIFT) {
default:
case INSTR_MI_CLIENT:
return x >> STD_MI_OPCODE_SHIFT;
case INSTR_RC_CLIENT:
return x >> STD_3D_OPCODE_SHIFT;
case INSTR_BC_CLIENT:
return x >> STD_2D_OPCODE_SHIFT;
}
}
static int init_hash_table(struct intel_engine_cs *engine,
const struct drm_i915_cmd_table *cmd_tables,
int cmd_table_count)
{
int i, j;
hash_init(engine->cmd_hash);
for (i = 0; i < cmd_table_count; i++) {
const struct drm_i915_cmd_table *table = &cmd_tables[i];
for (j = 0; j < table->count; j++) {
const struct drm_i915_cmd_descriptor *desc =
&table->table[j];
struct cmd_node *desc_node =
kmalloc(sizeof(*desc_node), GFP_KERNEL);
if (!desc_node)
return -ENOMEM;
desc_node->desc = desc;
hash_add(engine->cmd_hash, &desc_node->node,
cmd_header_key(desc->cmd.value));
}
}
return 0;
}
static void fini_hash_table(struct intel_engine_cs *engine)
{
struct hlist_node *tmp;
struct cmd_node *desc_node;
int i;
hash_for_each_safe(engine->cmd_hash, i, tmp, desc_node, node) {
hash_del(&desc_node->node);
kfree(desc_node);
}
}
/**
* intel_engine_init_cmd_parser() - set cmd parser related fields for an engine
* @engine: the engine to initialize
*
* Optionally initializes fields related to batch buffer command parsing in the
* struct intel_engine_cs based on whether the platform requires software
* command parsing.
*/
int intel_engine_init_cmd_parser(struct intel_engine_cs *engine)
{
const struct drm_i915_cmd_table *cmd_tables;
int cmd_table_count;
int ret;
if (GRAPHICS_VER(engine->i915) != 7 && !(GRAPHICS_VER(engine->i915) == 9 &&
engine->class == COPY_ENGINE_CLASS))
return 0;
switch (engine->class) {
case RENDER_CLASS:
if (IS_HASWELL(engine->i915)) {
cmd_tables = hsw_render_ring_cmd_table;
cmd_table_count =
ARRAY_SIZE(hsw_render_ring_cmd_table);
} else {
cmd_tables = gen7_render_cmd_table;
cmd_table_count = ARRAY_SIZE(gen7_render_cmd_table);
}
if (IS_HASWELL(engine->i915)) {
engine->reg_tables = hsw_render_reg_tables;
engine->reg_table_count = ARRAY_SIZE(hsw_render_reg_tables);
} else {
engine->reg_tables = ivb_render_reg_tables;
engine->reg_table_count = ARRAY_SIZE(ivb_render_reg_tables);
}
engine->get_cmd_length_mask = gen7_render_get_cmd_length_mask;
break;
case VIDEO_DECODE_CLASS:
cmd_tables = gen7_video_cmd_table;
cmd_table_count = ARRAY_SIZE(gen7_video_cmd_table);
engine->get_cmd_length_mask = gen7_bsd_get_cmd_length_mask;
break;
case COPY_ENGINE_CLASS:
engine->get_cmd_length_mask = gen7_blt_get_cmd_length_mask;
if (GRAPHICS_VER(engine->i915) == 9) {
cmd_tables = gen9_blt_cmd_table;
cmd_table_count = ARRAY_SIZE(gen9_blt_cmd_table);
engine->get_cmd_length_mask =
gen9_blt_get_cmd_length_mask;
/* BCS Engine unsafe without parser */
engine->flags |= I915_ENGINE_REQUIRES_CMD_PARSER;
} else if (IS_HASWELL(engine->i915)) {
cmd_tables = hsw_blt_ring_cmd_table;
cmd_table_count = ARRAY_SIZE(hsw_blt_ring_cmd_table);
} else {
cmd_tables = gen7_blt_cmd_table;
cmd_table_count = ARRAY_SIZE(gen7_blt_cmd_table);
}
if (GRAPHICS_VER(engine->i915) == 9) {
engine->reg_tables = gen9_blt_reg_tables;
engine->reg_table_count =
ARRAY_SIZE(gen9_blt_reg_tables);
} else if (IS_HASWELL(engine->i915)) {
engine->reg_tables = hsw_blt_reg_tables;
engine->reg_table_count = ARRAY_SIZE(hsw_blt_reg_tables);
} else {
engine->reg_tables = ivb_blt_reg_tables;
engine->reg_table_count = ARRAY_SIZE(ivb_blt_reg_tables);
}
break;
case VIDEO_ENHANCEMENT_CLASS:
cmd_tables = hsw_vebox_cmd_table;
cmd_table_count = ARRAY_SIZE(hsw_vebox_cmd_table);
/* VECS can use the same length_mask function as VCS */
engine->get_cmd_length_mask = gen7_bsd_get_cmd_length_mask;
break;
default:
MISSING_CASE(engine->class);
goto out;
}
if (!validate_cmds_sorted(engine, cmd_tables, cmd_table_count)) {
drm_err(&engine->i915->drm,
"%s: command descriptions are not sorted\n",
engine->name);
goto out;
}
if (!validate_regs_sorted(engine)) {
drm_err(&engine->i915->drm,
"%s: registers are not sorted\n", engine->name);
goto out;
}
ret = init_hash_table(engine, cmd_tables, cmd_table_count);
if (ret) {
drm_err(&engine->i915->drm,
"%s: initialised failed!\n", engine->name);
fini_hash_table(engine);
goto out;
}
engine->flags |= I915_ENGINE_USING_CMD_PARSER;
out:
if (intel_engine_requires_cmd_parser(engine) &&
!intel_engine_using_cmd_parser(engine))
return -EINVAL;
return 0;
}
/**
* intel_engine_cleanup_cmd_parser() - clean up cmd parser related fields
* @engine: the engine to clean up
*
* Releases any resources related to command parsing that may have been
* initialized for the specified engine.
*/
void intel_engine_cleanup_cmd_parser(struct intel_engine_cs *engine)
{
if (!intel_engine_using_cmd_parser(engine))
return;
fini_hash_table(engine);
}
static const struct drm_i915_cmd_descriptor*
find_cmd_in_table(struct intel_engine_cs *engine,
u32 cmd_header)
{
struct cmd_node *desc_node;
hash_for_each_possible(engine->cmd_hash, desc_node, node,
cmd_header_key(cmd_header)) {
const struct drm_i915_cmd_descriptor *desc = desc_node->desc;
if (((cmd_header ^ desc->cmd.value) & desc->cmd.mask) == 0)
return desc;
}
return NULL;
}
/*
* Returns a pointer to a descriptor for the command specified by cmd_header.
*
* The caller must supply space for a default descriptor via the default_desc
* parameter. If no descriptor for the specified command exists in the engine's
* command parser tables, this function fills in default_desc based on the
* engine's default length encoding and returns default_desc.
*/
static const struct drm_i915_cmd_descriptor*
find_cmd(struct intel_engine_cs *engine,
u32 cmd_header,
const struct drm_i915_cmd_descriptor *desc,
struct drm_i915_cmd_descriptor *default_desc)
{
u32 mask;
if (((cmd_header ^ desc->cmd.value) & desc->cmd.mask) == 0)
return desc;
desc = find_cmd_in_table(engine, cmd_header);
if (desc)
return desc;
mask = engine->get_cmd_length_mask(cmd_header);
if (!mask)
return NULL;
default_desc->cmd.value = cmd_header;
default_desc->cmd.mask = ~0u << MIN_OPCODE_SHIFT;
default_desc->length.mask = mask;
default_desc->flags = CMD_DESC_SKIP;
return default_desc;
}
static const struct drm_i915_reg_descriptor *
__find_reg(const struct drm_i915_reg_descriptor *table, int count, u32 addr)
{
int start = 0, end = count;
while (start < end) {
int mid = start + (end - start) / 2;
int ret = addr - i915_mmio_reg_offset(table[mid].addr);
if (ret < 0)
end = mid;
else if (ret > 0)
start = mid + 1;
else
return &table[mid];
}
return NULL;
}
static const struct drm_i915_reg_descriptor *
find_reg(const struct intel_engine_cs *engine, u32 addr)
{
const struct drm_i915_reg_table *table = engine->reg_tables;
const struct drm_i915_reg_descriptor *reg = NULL;
int count = engine->reg_table_count;
for (; !reg && (count > 0); ++table, --count)
reg = __find_reg(table->regs, table->num_regs, addr);
return reg;
}
/* Returns a vmap'd pointer to dst_obj, which the caller must unmap */
static u32 *copy_batch(struct drm_i915_gem_object *dst_obj,
struct drm_i915_gem_object *src_obj,
unsigned long offset, unsigned long length,
bool *needs_clflush_after)
{
unsigned int src_needs_clflush;
unsigned int dst_needs_clflush;
void *dst, *src;
int ret;
ret = i915_gem_object_prepare_write(dst_obj, &dst_needs_clflush);
if (ret)
return ERR_PTR(ret);
dst = i915_gem_object_pin_map(dst_obj, I915_MAP_WB);
i915_gem_object_finish_access(dst_obj);
if (IS_ERR(dst))
return dst;
ret = i915_gem_object_prepare_read(src_obj, &src_needs_clflush);
if (ret) {
i915_gem_object_unpin_map(dst_obj);
return ERR_PTR(ret);
}
src = ERR_PTR(-ENODEV);
if (src_needs_clflush && i915_has_memcpy_from_wc()) {
src = i915_gem_object_pin_map(src_obj, I915_MAP_WC);
if (!IS_ERR(src)) {
i915_unaligned_memcpy_from_wc(dst,
src + offset,
length);
i915_gem_object_unpin_map(src_obj);
}
}
if (IS_ERR(src)) {
unsigned long x, n, remain;
void *ptr;
/*
* We can avoid clflushing partial cachelines before the write
* if we only every write full cache-lines. Since we know that
* both the source and destination are in multiples of
* PAGE_SIZE, we can simply round up to the next cacheline.
* We don't care about copying too much here as we only
* validate up to the end of the batch.
*/
remain = length;
if (dst_needs_clflush & CLFLUSH_BEFORE)
remain = round_up(remain,
boot_cpu_data.x86_clflush_size);
ptr = dst;
x = offset_in_page(offset);
for (n = offset >> PAGE_SHIFT; remain; n++) {
int len = min(remain, PAGE_SIZE - x);
src = kmap_atomic(i915_gem_object_get_page(src_obj, n));
if (src_needs_clflush)
drm_clflush_virt_range(src + x, len);
memcpy(ptr, src + x, len);
kunmap_atomic(src);
ptr += len;
remain -= len;
x = 0;
}
}
i915_gem_object_finish_access(src_obj);
memset32(dst + length, 0, (dst_obj->base.size - length) / sizeof(u32));
/* dst_obj is returned with vmap pinned */
*needs_clflush_after = dst_needs_clflush & CLFLUSH_AFTER;
return dst;
}
static inline bool cmd_desc_is(const struct drm_i915_cmd_descriptor * const desc,
const u32 cmd)
{
return desc->cmd.value == (cmd & desc->cmd.mask);
}
static bool check_cmd(const struct intel_engine_cs *engine,
const struct drm_i915_cmd_descriptor *desc,
const u32 *cmd, u32 length)
{
if (desc->flags & CMD_DESC_SKIP)
return true;
if (desc->flags & CMD_DESC_REJECT) {
DRM_DEBUG("CMD: Rejected command: 0x%08X\n", *cmd);
return false;
}
if (desc->flags & CMD_DESC_REGISTER) {
/*
* Get the distance between individual register offset
* fields if the command can perform more than one
* access at a time.
*/
const u32 step = desc->reg.step ? desc->reg.step : length;
u32 offset;
for (offset = desc->reg.offset; offset < length;
offset += step) {
const u32 reg_addr = cmd[offset] & desc->reg.mask;
const struct drm_i915_reg_descriptor *reg =
find_reg(engine, reg_addr);
if (!reg) {
DRM_DEBUG("CMD: Rejected register 0x%08X in command: 0x%08X (%s)\n",
reg_addr, *cmd, engine->name);
return false;
}
/*
* Check the value written to the register against the
* allowed mask/value pair given in the whitelist entry.
*/
if (reg->mask) {
if (cmd_desc_is(desc, MI_LOAD_REGISTER_MEM)) {
DRM_DEBUG("CMD: Rejected LRM to masked register 0x%08X\n",
reg_addr);
return false;
}
if (cmd_desc_is(desc, MI_LOAD_REGISTER_REG)) {
DRM_DEBUG("CMD: Rejected LRR to masked register 0x%08X\n",
reg_addr);
return false;
}
if (cmd_desc_is(desc, MI_LOAD_REGISTER_IMM(1)) &&
(offset + 2 > length ||
(cmd[offset + 1] & reg->mask) != reg->value)) {
DRM_DEBUG("CMD: Rejected LRI to masked register 0x%08X\n",
reg_addr);
return false;
}
}
}
}
if (desc->flags & CMD_DESC_BITMASK) {
int i;
for (i = 0; i < MAX_CMD_DESC_BITMASKS; i++) {
u32 dword;
if (desc->bits[i].mask == 0)
break;
if (desc->bits[i].condition_mask != 0) {
u32 offset =
desc->bits[i].condition_offset;
u32 condition = cmd[offset] &
desc->bits[i].condition_mask;
if (condition == 0)
continue;
}
if (desc->bits[i].offset >= length) {
DRM_DEBUG("CMD: Rejected command 0x%08X, too short to check bitmask (%s)\n",
*cmd, engine->name);
return false;
}
dword = cmd[desc->bits[i].offset] &
desc->bits[i].mask;
if (dword != desc->bits[i].expected) {
DRM_DEBUG("CMD: Rejected command 0x%08X for bitmask 0x%08X (exp=0x%08X act=0x%08X) (%s)\n",
*cmd,
desc->bits[i].mask,
desc->bits[i].expected,
dword, engine->name);
return false;
}
}
}
return true;
}
static int check_bbstart(u32 *cmd, u32 offset, u32 length,
u32 batch_length,
u64 batch_addr,
u64 shadow_addr,
const unsigned long *jump_whitelist)
{
u64 jump_offset, jump_target;
u32 target_cmd_offset, target_cmd_index;
/* For igt compatibility on older platforms */
if (!jump_whitelist) {
DRM_DEBUG("CMD: Rejecting BB_START for ggtt based submission\n");
return -EACCES;
}
if (length != 3) {
DRM_DEBUG("CMD: Recursive BB_START with bad length(%u)\n",
length);
return -EINVAL;
}
jump_target = *(u64 *)(cmd + 1);
jump_offset = jump_target - batch_addr;
/*
* Any underflow of jump_target is guaranteed to be outside the range
* of a u32, so >= test catches both too large and too small
*/
if (jump_offset >= batch_length) {
DRM_DEBUG("CMD: BB_START to 0x%llx jumps out of BB\n",
jump_target);
return -EINVAL;
}
/*
* This cannot overflow a u32 because we already checked jump_offset
* is within the BB, and the batch_length is a u32
*/
target_cmd_offset = lower_32_bits(jump_offset);
target_cmd_index = target_cmd_offset / sizeof(u32);
*(u64 *)(cmd + 1) = shadow_addr + target_cmd_offset;
if (target_cmd_index == offset)
return 0;
if (IS_ERR(jump_whitelist))
return PTR_ERR(jump_whitelist);
if (!test_bit(target_cmd_index, jump_whitelist)) {
DRM_DEBUG("CMD: BB_START to 0x%llx not a previously executed cmd\n",
jump_target);
return -EINVAL;
}
return 0;
}
static unsigned long *alloc_whitelist(u32 batch_length)
{
unsigned long *jmp;
/*
* We expect batch_length to be less than 256KiB for known users,
* i.e. we need at most an 8KiB bitmap allocation which should be
* reasonably cheap due to kmalloc caches.
*/
/* Prefer to report transient allocation failure rather than hit oom */
jmp = bitmap_zalloc(DIV_ROUND_UP(batch_length, sizeof(u32)),
GFP_KERNEL | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
if (!jmp)
return ERR_PTR(-ENOMEM);
return jmp;
}
#define LENGTH_BIAS 2
/**
* intel_engine_cmd_parser() - parse a batch buffer for privilege violations
* @engine: the engine on which the batch is to execute
* @batch: the batch buffer in question
* @batch_offset: byte offset in the batch at which execution starts
* @batch_length: length of the commands in batch_obj
* @shadow: validated copy of the batch buffer in question
* @trampoline: true if we need to trampoline into privileged execution
*
* Parses the specified batch buffer looking for privilege violations as
* described in the overview.
*
* Return: non-zero if the parser finds violations or otherwise fails; -EACCES
* if the batch appears legal but should use hardware parsing
*/
int intel_engine_cmd_parser(struct intel_engine_cs *engine,
struct i915_vma *batch,
unsigned long batch_offset,
unsigned long batch_length,
struct i915_vma *shadow,
bool trampoline)
{
u32 *cmd, *batch_end, offset = 0;
struct drm_i915_cmd_descriptor default_desc = noop_desc;
const struct drm_i915_cmd_descriptor *desc = &default_desc;
bool needs_clflush_after = false;
unsigned long *jump_whitelist;
u64 batch_addr, shadow_addr;
int ret = 0;
GEM_BUG_ON(!IS_ALIGNED(batch_offset, sizeof(*cmd)));
GEM_BUG_ON(!IS_ALIGNED(batch_length, sizeof(*cmd)));
GEM_BUG_ON(range_overflows_t(u64, batch_offset, batch_length,
batch->size));
GEM_BUG_ON(!batch_length);
cmd = copy_batch(shadow->obj, batch->obj,
batch_offset, batch_length,
&needs_clflush_after);
if (IS_ERR(cmd)) {
DRM_DEBUG("CMD: Failed to copy batch\n");
return PTR_ERR(cmd);
}
jump_whitelist = NULL;
if (!trampoline)
/* Defer failure until attempted use */
jump_whitelist = alloc_whitelist(batch_length);
shadow_addr = gen8_canonical_addr(i915_vma_offset(shadow));
batch_addr = gen8_canonical_addr(i915_vma_offset(batch) + batch_offset);
/*
* We use the batch length as size because the shadow object is as
* large or larger and copy_batch() will write MI_NOPs to the extra
* space. Parsing should be faster in some cases this way.
*/
batch_end = cmd + batch_length / sizeof(*batch_end);
do {
u32 length;
if (*cmd == MI_BATCH_BUFFER_END)
break;
desc = find_cmd(engine, *cmd, desc, &default_desc);
if (!desc) {
DRM_DEBUG("CMD: Unrecognized command: 0x%08X\n", *cmd);
ret = -EINVAL;
break;
}
if (desc->flags & CMD_DESC_FIXED)
length = desc->length.fixed;
else
length = (*cmd & desc->length.mask) + LENGTH_BIAS;
if ((batch_end - cmd) < length) {
DRM_DEBUG("CMD: Command length exceeds batch length: 0x%08X length=%u batchlen=%td\n",
*cmd,
length,
batch_end - cmd);
ret = -EINVAL;
break;
}
if (!check_cmd(engine, desc, cmd, length)) {
ret = -EACCES;
break;
}
if (cmd_desc_is(desc, MI_BATCH_BUFFER_START)) {
ret = check_bbstart(cmd, offset, length, batch_length,
batch_addr, shadow_addr,
jump_whitelist);
break;
}
if (!IS_ERR_OR_NULL(jump_whitelist))
__set_bit(offset, jump_whitelist);
cmd += length;
offset += length;
if (cmd >= batch_end) {
DRM_DEBUG("CMD: Got to the end of the buffer w/o a BBE cmd!\n");
ret = -EINVAL;
break;
}
} while (1);
if (trampoline) {
/*
* With the trampoline, the shadow is executed twice.
*
* 1 - starting at offset 0, in privileged mode
* 2 - starting at offset batch_len, as non-privileged
*
* Only if the batch is valid and safe to execute, do we
* allow the first privileged execution to proceed. If not,
* we terminate the first batch and use the second batchbuffer
* entry to chain to the original unsafe non-privileged batch,
* leaving it to the HW to validate.
*/
*batch_end = MI_BATCH_BUFFER_END;
if (ret) {
/* Batch unsafe to execute with privileges, cancel! */
cmd = page_mask_bits(shadow->obj->mm.mapping);
*cmd = MI_BATCH_BUFFER_END;
/* If batch is unsafe but valid, jump to the original */
if (ret == -EACCES) {
unsigned int flags;
flags = MI_BATCH_NON_SECURE_I965;
if (IS_HASWELL(engine->i915))
flags = MI_BATCH_NON_SECURE_HSW;
GEM_BUG_ON(!IS_GRAPHICS_VER(engine->i915, 6, 7));
__gen6_emit_bb_start(batch_end,
batch_addr,
flags);
ret = 0; /* allow execution */
}
}
}
i915_gem_object_flush_map(shadow->obj);
if (!IS_ERR_OR_NULL(jump_whitelist))
kfree(jump_whitelist);
i915_gem_object_unpin_map(shadow->obj);
return ret;
}
/**
* i915_cmd_parser_get_version() - get the cmd parser version number
* @dev_priv: i915 device private
*
* The cmd parser maintains a simple increasing integer version number suitable
* for passing to userspace clients to determine what operations are permitted.
*
* Return: the current version number of the cmd parser
*/
int i915_cmd_parser_get_version(struct drm_i915_private *dev_priv)
{
struct intel_engine_cs *engine;
bool active = false;
/* If the command parser is not enabled, report 0 - unsupported */
for_each_uabi_engine(engine, dev_priv) {
if (intel_engine_using_cmd_parser(engine)) {
active = true;
break;
}
}
if (!active)
return 0;
/*
* Command parser version history
*
* 1. Initial version. Checks batches and reports violations, but leaves
* hardware parsing enabled (so does not allow new use cases).
* 2. Allow access to the MI_PREDICATE_SRC0 and
* MI_PREDICATE_SRC1 registers.
* 3. Allow access to the GPGPU_THREADS_DISPATCHED register.
* 4. L3 atomic chicken bits of HSW_SCRATCH1 and HSW_ROW_CHICKEN3.
* 5. GPGPU dispatch compute indirect registers.
* 6. TIMESTAMP register and Haswell CS GPR registers
* 7. Allow MI_LOAD_REGISTER_REG between whitelisted registers.
* 8. Don't report cmd_check() failures as EINVAL errors to userspace;
* rely on the HW to NOOP disallowed commands as it would without
* the parser enabled.
* 9. Don't whitelist or handle oacontrol specially, as ownership
* for oacontrol state is moving to i915-perf.
* 10. Support for Gen9 BCS Parsing
*/
return 10;
}
| linux-master | drivers/gpu/drm/i915/i915_cmd_parser.c |
/*
* SPDX-License-Identifier: MIT
*
* Copyright © 2019 Intel Corporation
*/
#include <linux/wait_bit.h>
#include "intel_runtime_pm.h"
#include "intel_wakeref.h"
#include "i915_drv.h"
static void rpm_get(struct intel_wakeref *wf)
{
wf->wakeref = intel_runtime_pm_get(&wf->i915->runtime_pm);
}
static void rpm_put(struct intel_wakeref *wf)
{
intel_wakeref_t wakeref = fetch_and_zero(&wf->wakeref);
intel_runtime_pm_put(&wf->i915->runtime_pm, wakeref);
INTEL_WAKEREF_BUG_ON(!wakeref);
}
int __intel_wakeref_get_first(struct intel_wakeref *wf)
{
/*
* Treat get/put as different subclasses, as we may need to run
* the put callback from under the shrinker and do not want to
* cross-contanimate that callback with any extra work performed
* upon acquiring the wakeref.
*/
mutex_lock_nested(&wf->mutex, SINGLE_DEPTH_NESTING);
if (!atomic_read(&wf->count)) {
int err;
rpm_get(wf);
err = wf->ops->get(wf);
if (unlikely(err)) {
rpm_put(wf);
mutex_unlock(&wf->mutex);
return err;
}
smp_mb__before_atomic(); /* release wf->count */
}
atomic_inc(&wf->count);
mutex_unlock(&wf->mutex);
INTEL_WAKEREF_BUG_ON(atomic_read(&wf->count) <= 0);
return 0;
}
static void ____intel_wakeref_put_last(struct intel_wakeref *wf)
{
INTEL_WAKEREF_BUG_ON(atomic_read(&wf->count) <= 0);
if (unlikely(!atomic_dec_and_test(&wf->count)))
goto unlock;
/* ops->put() must reschedule its own release on error/deferral */
if (likely(!wf->ops->put(wf))) {
rpm_put(wf);
wake_up_var(&wf->wakeref);
}
unlock:
mutex_unlock(&wf->mutex);
}
void __intel_wakeref_put_last(struct intel_wakeref *wf, unsigned long flags)
{
INTEL_WAKEREF_BUG_ON(delayed_work_pending(&wf->work));
/* Assume we are not in process context and so cannot sleep. */
if (flags & INTEL_WAKEREF_PUT_ASYNC || !mutex_trylock(&wf->mutex)) {
mod_delayed_work(wf->i915->unordered_wq, &wf->work,
FIELD_GET(INTEL_WAKEREF_PUT_DELAY, flags));
return;
}
____intel_wakeref_put_last(wf);
}
static void __intel_wakeref_put_work(struct work_struct *wrk)
{
struct intel_wakeref *wf = container_of(wrk, typeof(*wf), work.work);
if (atomic_add_unless(&wf->count, -1, 1))
return;
mutex_lock(&wf->mutex);
____intel_wakeref_put_last(wf);
}
void __intel_wakeref_init(struct intel_wakeref *wf,
struct drm_i915_private *i915,
const struct intel_wakeref_ops *ops,
struct intel_wakeref_lockclass *key)
{
wf->i915 = i915;
wf->ops = ops;
__mutex_init(&wf->mutex, "wakeref.mutex", &key->mutex);
atomic_set(&wf->count, 0);
wf->wakeref = 0;
INIT_DELAYED_WORK(&wf->work, __intel_wakeref_put_work);
lockdep_init_map(&wf->work.work.lockdep_map,
"wakeref.work", &key->work, 0);
}
int intel_wakeref_wait_for_idle(struct intel_wakeref *wf)
{
int err;
might_sleep();
err = wait_var_event_killable(&wf->wakeref,
!intel_wakeref_is_active(wf));
if (err)
return err;
intel_wakeref_unlock_wait(wf);
return 0;
}
static void wakeref_auto_timeout(struct timer_list *t)
{
struct intel_wakeref_auto *wf = from_timer(wf, t, timer);
intel_wakeref_t wakeref;
unsigned long flags;
if (!refcount_dec_and_lock_irqsave(&wf->count, &wf->lock, &flags))
return;
wakeref = fetch_and_zero(&wf->wakeref);
spin_unlock_irqrestore(&wf->lock, flags);
intel_runtime_pm_put(&wf->i915->runtime_pm, wakeref);
}
void intel_wakeref_auto_init(struct intel_wakeref_auto *wf,
struct drm_i915_private *i915)
{
spin_lock_init(&wf->lock);
timer_setup(&wf->timer, wakeref_auto_timeout, 0);
refcount_set(&wf->count, 0);
wf->wakeref = 0;
wf->i915 = i915;
}
void intel_wakeref_auto(struct intel_wakeref_auto *wf, unsigned long timeout)
{
unsigned long flags;
if (!timeout) {
if (del_timer_sync(&wf->timer))
wakeref_auto_timeout(&wf->timer);
return;
}
/* Our mission is that we only extend an already active wakeref */
assert_rpm_wakelock_held(&wf->i915->runtime_pm);
if (!refcount_inc_not_zero(&wf->count)) {
spin_lock_irqsave(&wf->lock, flags);
if (!refcount_inc_not_zero(&wf->count)) {
INTEL_WAKEREF_BUG_ON(wf->wakeref);
wf->wakeref =
intel_runtime_pm_get_if_in_use(&wf->i915->runtime_pm);
refcount_set(&wf->count, 1);
}
spin_unlock_irqrestore(&wf->lock, flags);
}
/*
* If we extend a pending timer, we will only get a single timer
* callback and so need to cancel the local inc by running the
* elided callback to keep the wf->count balanced.
*/
if (mod_timer(&wf->timer, jiffies + timeout))
wakeref_auto_timeout(&wf->timer);
}
void intel_wakeref_auto_fini(struct intel_wakeref_auto *wf)
{
intel_wakeref_auto(wf, 0);
INTEL_WAKEREF_BUG_ON(wf->wakeref);
}
| linux-master | drivers/gpu/drm/i915/intel_wakeref.c |
/*
* Copyright © 2013 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <drm/drm_managed.h>
#include <linux/pm_runtime.h>
#include "gt/intel_engine_regs.h"
#include "gt/intel_gt_regs.h"
#include "i915_drv.h"
#include "i915_iosf_mbi.h"
#include "i915_reg.h"
#include "i915_trace.h"
#include "i915_vgpu.h"
#define FORCEWAKE_ACK_TIMEOUT_MS 50
#define GT_FIFO_TIMEOUT_MS 10
#define __raw_posting_read(...) ((void)__raw_uncore_read32(__VA_ARGS__))
static void
fw_domains_get(struct intel_uncore *uncore, enum forcewake_domains fw_domains)
{
uncore->fw_get_funcs->force_wake_get(uncore, fw_domains);
}
void
intel_uncore_mmio_debug_init_early(struct drm_i915_private *i915)
{
spin_lock_init(&i915->mmio_debug.lock);
i915->mmio_debug.unclaimed_mmio_check = 1;
i915->uncore.debug = &i915->mmio_debug;
}
static void mmio_debug_suspend(struct intel_uncore *uncore)
{
if (!uncore->debug)
return;
spin_lock(&uncore->debug->lock);
/* Save and disable mmio debugging for the user bypass */
if (!uncore->debug->suspend_count++) {
uncore->debug->saved_mmio_check = uncore->debug->unclaimed_mmio_check;
uncore->debug->unclaimed_mmio_check = 0;
}
spin_unlock(&uncore->debug->lock);
}
static bool check_for_unclaimed_mmio(struct intel_uncore *uncore);
static void mmio_debug_resume(struct intel_uncore *uncore)
{
if (!uncore->debug)
return;
spin_lock(&uncore->debug->lock);
if (!--uncore->debug->suspend_count)
uncore->debug->unclaimed_mmio_check = uncore->debug->saved_mmio_check;
if (check_for_unclaimed_mmio(uncore))
drm_info(&uncore->i915->drm,
"Invalid mmio detected during user access\n");
spin_unlock(&uncore->debug->lock);
}
static const char * const forcewake_domain_names[] = {
"render",
"gt",
"media",
"vdbox0",
"vdbox1",
"vdbox2",
"vdbox3",
"vdbox4",
"vdbox5",
"vdbox6",
"vdbox7",
"vebox0",
"vebox1",
"vebox2",
"vebox3",
"gsc",
};
const char *
intel_uncore_forcewake_domain_to_str(const enum forcewake_domain_id id)
{
BUILD_BUG_ON(ARRAY_SIZE(forcewake_domain_names) != FW_DOMAIN_ID_COUNT);
if (id >= 0 && id < FW_DOMAIN_ID_COUNT)
return forcewake_domain_names[id];
WARN_ON(id);
return "unknown";
}
#define fw_ack(d) readl((d)->reg_ack)
#define fw_set(d, val) writel(_MASKED_BIT_ENABLE((val)), (d)->reg_set)
#define fw_clear(d, val) writel(_MASKED_BIT_DISABLE((val)), (d)->reg_set)
static inline void
fw_domain_reset(const struct intel_uncore_forcewake_domain *d)
{
/*
* We don't really know if the powerwell for the forcewake domain we are
* trying to reset here does exist at this point (engines could be fused
* off in ICL+), so no waiting for acks
*/
/* WaRsClearFWBitsAtReset */
if (GRAPHICS_VER(d->uncore->i915) >= 12)
fw_clear(d, 0xefff);
else
fw_clear(d, 0xffff);
}
static inline void
fw_domain_arm_timer(struct intel_uncore_forcewake_domain *d)
{
GEM_BUG_ON(d->uncore->fw_domains_timer & d->mask);
d->uncore->fw_domains_timer |= d->mask;
d->wake_count++;
hrtimer_start_range_ns(&d->timer,
NSEC_PER_MSEC,
NSEC_PER_MSEC,
HRTIMER_MODE_REL);
}
static inline int
__wait_for_ack(const struct intel_uncore_forcewake_domain *d,
const u32 ack,
const u32 value)
{
return wait_for_atomic((fw_ack(d) & ack) == value,
FORCEWAKE_ACK_TIMEOUT_MS);
}
static inline int
wait_ack_clear(const struct intel_uncore_forcewake_domain *d,
const u32 ack)
{
return __wait_for_ack(d, ack, 0);
}
static inline int
wait_ack_set(const struct intel_uncore_forcewake_domain *d,
const u32 ack)
{
return __wait_for_ack(d, ack, ack);
}
static inline void
fw_domain_wait_ack_clear(const struct intel_uncore_forcewake_domain *d)
{
if (!wait_ack_clear(d, FORCEWAKE_KERNEL))
return;
if (fw_ack(d) == ~0)
drm_err(&d->uncore->i915->drm,
"%s: MMIO unreliable (forcewake register returns 0xFFFFFFFF)!\n",
intel_uncore_forcewake_domain_to_str(d->id));
else
drm_err(&d->uncore->i915->drm,
"%s: timed out waiting for forcewake ack to clear.\n",
intel_uncore_forcewake_domain_to_str(d->id));
add_taint_for_CI(d->uncore->i915, TAINT_WARN); /* CI now unreliable */
}
enum ack_type {
ACK_CLEAR = 0,
ACK_SET
};
static int
fw_domain_wait_ack_with_fallback(const struct intel_uncore_forcewake_domain *d,
const enum ack_type type)
{
const u32 ack_bit = FORCEWAKE_KERNEL;
const u32 value = type == ACK_SET ? ack_bit : 0;
unsigned int pass;
bool ack_detected;
/*
* There is a possibility of driver's wake request colliding
* with hardware's own wake requests and that can cause
* hardware to not deliver the driver's ack message.
*
* Use a fallback bit toggle to kick the gpu state machine
* in the hope that the original ack will be delivered along with
* the fallback ack.
*
* This workaround is described in HSDES #1604254524 and it's known as:
* WaRsForcewakeAddDelayForAck:skl,bxt,kbl,glk,cfl,cnl,icl
* although the name is a bit misleading.
*/
pass = 1;
do {
wait_ack_clear(d, FORCEWAKE_KERNEL_FALLBACK);
fw_set(d, FORCEWAKE_KERNEL_FALLBACK);
/* Give gt some time to relax before the polling frenzy */
udelay(10 * pass);
wait_ack_set(d, FORCEWAKE_KERNEL_FALLBACK);
ack_detected = (fw_ack(d) & ack_bit) == value;
fw_clear(d, FORCEWAKE_KERNEL_FALLBACK);
} while (!ack_detected && pass++ < 10);
drm_dbg(&d->uncore->i915->drm,
"%s had to use fallback to %s ack, 0x%x (passes %u)\n",
intel_uncore_forcewake_domain_to_str(d->id),
type == ACK_SET ? "set" : "clear",
fw_ack(d),
pass);
return ack_detected ? 0 : -ETIMEDOUT;
}
static inline void
fw_domain_wait_ack_clear_fallback(const struct intel_uncore_forcewake_domain *d)
{
if (likely(!wait_ack_clear(d, FORCEWAKE_KERNEL)))
return;
if (fw_domain_wait_ack_with_fallback(d, ACK_CLEAR))
fw_domain_wait_ack_clear(d);
}
static inline void
fw_domain_get(const struct intel_uncore_forcewake_domain *d)
{
fw_set(d, FORCEWAKE_KERNEL);
}
static inline void
fw_domain_wait_ack_set(const struct intel_uncore_forcewake_domain *d)
{
if (wait_ack_set(d, FORCEWAKE_KERNEL)) {
drm_err(&d->uncore->i915->drm,
"%s: timed out waiting for forcewake ack request.\n",
intel_uncore_forcewake_domain_to_str(d->id));
add_taint_for_CI(d->uncore->i915, TAINT_WARN); /* CI now unreliable */
}
}
static inline void
fw_domain_wait_ack_set_fallback(const struct intel_uncore_forcewake_domain *d)
{
if (likely(!wait_ack_set(d, FORCEWAKE_KERNEL)))
return;
if (fw_domain_wait_ack_with_fallback(d, ACK_SET))
fw_domain_wait_ack_set(d);
}
static inline void
fw_domain_put(const struct intel_uncore_forcewake_domain *d)
{
fw_clear(d, FORCEWAKE_KERNEL);
}
static void
fw_domains_get_normal(struct intel_uncore *uncore, enum forcewake_domains fw_domains)
{
struct intel_uncore_forcewake_domain *d;
unsigned int tmp;
GEM_BUG_ON(fw_domains & ~uncore->fw_domains);
for_each_fw_domain_masked(d, fw_domains, uncore, tmp) {
fw_domain_wait_ack_clear(d);
fw_domain_get(d);
}
for_each_fw_domain_masked(d, fw_domains, uncore, tmp)
fw_domain_wait_ack_set(d);
uncore->fw_domains_active |= fw_domains;
}
static void
fw_domains_get_with_fallback(struct intel_uncore *uncore,
enum forcewake_domains fw_domains)
{
struct intel_uncore_forcewake_domain *d;
unsigned int tmp;
GEM_BUG_ON(fw_domains & ~uncore->fw_domains);
for_each_fw_domain_masked(d, fw_domains, uncore, tmp) {
fw_domain_wait_ack_clear_fallback(d);
fw_domain_get(d);
}
for_each_fw_domain_masked(d, fw_domains, uncore, tmp)
fw_domain_wait_ack_set_fallback(d);
uncore->fw_domains_active |= fw_domains;
}
static void
fw_domains_put(struct intel_uncore *uncore, enum forcewake_domains fw_domains)
{
struct intel_uncore_forcewake_domain *d;
unsigned int tmp;
GEM_BUG_ON(fw_domains & ~uncore->fw_domains);
for_each_fw_domain_masked(d, fw_domains, uncore, tmp)
fw_domain_put(d);
uncore->fw_domains_active &= ~fw_domains;
}
static void
fw_domains_reset(struct intel_uncore *uncore,
enum forcewake_domains fw_domains)
{
struct intel_uncore_forcewake_domain *d;
unsigned int tmp;
if (!fw_domains)
return;
GEM_BUG_ON(fw_domains & ~uncore->fw_domains);
for_each_fw_domain_masked(d, fw_domains, uncore, tmp)
fw_domain_reset(d);
}
static inline u32 gt_thread_status(struct intel_uncore *uncore)
{
u32 val;
val = __raw_uncore_read32(uncore, GEN6_GT_THREAD_STATUS_REG);
val &= GEN6_GT_THREAD_STATUS_CORE_MASK;
return val;
}
static void __gen6_gt_wait_for_thread_c0(struct intel_uncore *uncore)
{
/*
* w/a for a sporadic read returning 0 by waiting for the GT
* thread to wake up.
*/
drm_WARN_ONCE(&uncore->i915->drm,
wait_for_atomic_us(gt_thread_status(uncore) == 0, 5000),
"GT thread status wait timed out\n");
}
static void fw_domains_get_with_thread_status(struct intel_uncore *uncore,
enum forcewake_domains fw_domains)
{
fw_domains_get_normal(uncore, fw_domains);
/* WaRsForcewakeWaitTC0:snb,ivb,hsw,bdw,vlv */
__gen6_gt_wait_for_thread_c0(uncore);
}
static inline u32 fifo_free_entries(struct intel_uncore *uncore)
{
u32 count = __raw_uncore_read32(uncore, GTFIFOCTL);
return count & GT_FIFO_FREE_ENTRIES_MASK;
}
static void __gen6_gt_wait_for_fifo(struct intel_uncore *uncore)
{
u32 n;
/* On VLV, FIFO will be shared by both SW and HW.
* So, we need to read the FREE_ENTRIES everytime */
if (IS_VALLEYVIEW(uncore->i915))
n = fifo_free_entries(uncore);
else
n = uncore->fifo_count;
if (n <= GT_FIFO_NUM_RESERVED_ENTRIES) {
if (wait_for_atomic((n = fifo_free_entries(uncore)) >
GT_FIFO_NUM_RESERVED_ENTRIES,
GT_FIFO_TIMEOUT_MS)) {
drm_dbg(&uncore->i915->drm,
"GT_FIFO timeout, entries: %u\n", n);
return;
}
}
uncore->fifo_count = n - 1;
}
static enum hrtimer_restart
intel_uncore_fw_release_timer(struct hrtimer *timer)
{
struct intel_uncore_forcewake_domain *domain =
container_of(timer, struct intel_uncore_forcewake_domain, timer);
struct intel_uncore *uncore = domain->uncore;
unsigned long irqflags;
assert_rpm_device_not_suspended(uncore->rpm);
if (xchg(&domain->active, false))
return HRTIMER_RESTART;
spin_lock_irqsave(&uncore->lock, irqflags);
uncore->fw_domains_timer &= ~domain->mask;
GEM_BUG_ON(!domain->wake_count);
if (--domain->wake_count == 0)
fw_domains_put(uncore, domain->mask);
spin_unlock_irqrestore(&uncore->lock, irqflags);
return HRTIMER_NORESTART;
}
/* Note callers must have acquired the PUNIT->PMIC bus, before calling this. */
static unsigned int
intel_uncore_forcewake_reset(struct intel_uncore *uncore)
{
unsigned long irqflags;
struct intel_uncore_forcewake_domain *domain;
int retry_count = 100;
enum forcewake_domains fw, active_domains;
iosf_mbi_assert_punit_acquired();
/* Hold uncore.lock across reset to prevent any register access
* with forcewake not set correctly. Wait until all pending
* timers are run before holding.
*/
while (1) {
unsigned int tmp;
active_domains = 0;
for_each_fw_domain(domain, uncore, tmp) {
smp_store_mb(domain->active, false);
if (hrtimer_cancel(&domain->timer) == 0)
continue;
intel_uncore_fw_release_timer(&domain->timer);
}
spin_lock_irqsave(&uncore->lock, irqflags);
for_each_fw_domain(domain, uncore, tmp) {
if (hrtimer_active(&domain->timer))
active_domains |= domain->mask;
}
if (active_domains == 0)
break;
if (--retry_count == 0) {
drm_err(&uncore->i915->drm, "Timed out waiting for forcewake timers to finish\n");
break;
}
spin_unlock_irqrestore(&uncore->lock, irqflags);
cond_resched();
}
drm_WARN_ON(&uncore->i915->drm, active_domains);
fw = uncore->fw_domains_active;
if (fw)
fw_domains_put(uncore, fw);
fw_domains_reset(uncore, uncore->fw_domains);
assert_forcewakes_inactive(uncore);
spin_unlock_irqrestore(&uncore->lock, irqflags);
return fw; /* track the lost user forcewake domains */
}
static bool
fpga_check_for_unclaimed_mmio(struct intel_uncore *uncore)
{
u32 dbg;
dbg = __raw_uncore_read32(uncore, FPGA_DBG);
if (likely(!(dbg & FPGA_DBG_RM_NOCLAIM)))
return false;
/*
* Bugs in PCI programming (or failing hardware) can occasionally cause
* us to lose access to the MMIO BAR. When this happens, register
* reads will come back with 0xFFFFFFFF for every register and things
* go bad very quickly. Let's try to detect that special case and at
* least try to print a more informative message about what has
* happened.
*
* During normal operation the FPGA_DBG register has several unused
* bits that will always read back as 0's so we can use them as canaries
* to recognize when MMIO accesses are just busted.
*/
if (unlikely(dbg == ~0))
drm_err(&uncore->i915->drm,
"Lost access to MMIO BAR; all registers now read back as 0xFFFFFFFF!\n");
__raw_uncore_write32(uncore, FPGA_DBG, FPGA_DBG_RM_NOCLAIM);
return true;
}
static bool
vlv_check_for_unclaimed_mmio(struct intel_uncore *uncore)
{
u32 cer;
cer = __raw_uncore_read32(uncore, CLAIM_ER);
if (likely(!(cer & (CLAIM_ER_OVERFLOW | CLAIM_ER_CTR_MASK))))
return false;
__raw_uncore_write32(uncore, CLAIM_ER, CLAIM_ER_CLR);
return true;
}
static bool
gen6_check_for_fifo_debug(struct intel_uncore *uncore)
{
u32 fifodbg;
fifodbg = __raw_uncore_read32(uncore, GTFIFODBG);
if (unlikely(fifodbg)) {
drm_dbg(&uncore->i915->drm, "GTFIFODBG = 0x08%x\n", fifodbg);
__raw_uncore_write32(uncore, GTFIFODBG, fifodbg);
}
return fifodbg;
}
static bool
check_for_unclaimed_mmio(struct intel_uncore *uncore)
{
bool ret = false;
lockdep_assert_held(&uncore->debug->lock);
if (uncore->debug->suspend_count)
return false;
if (intel_uncore_has_fpga_dbg_unclaimed(uncore))
ret |= fpga_check_for_unclaimed_mmio(uncore);
if (intel_uncore_has_dbg_unclaimed(uncore))
ret |= vlv_check_for_unclaimed_mmio(uncore);
if (intel_uncore_has_fifo(uncore))
ret |= gen6_check_for_fifo_debug(uncore);
return ret;
}
static void forcewake_early_sanitize(struct intel_uncore *uncore,
unsigned int restore_forcewake)
{
GEM_BUG_ON(!intel_uncore_has_forcewake(uncore));
/* WaDisableShadowRegForCpd:chv */
if (IS_CHERRYVIEW(uncore->i915)) {
__raw_uncore_write32(uncore, GTFIFOCTL,
__raw_uncore_read32(uncore, GTFIFOCTL) |
GT_FIFO_CTL_BLOCK_ALL_POLICY_STALL |
GT_FIFO_CTL_RC6_POLICY_STALL);
}
iosf_mbi_punit_acquire();
intel_uncore_forcewake_reset(uncore);
if (restore_forcewake) {
spin_lock_irq(&uncore->lock);
fw_domains_get(uncore, restore_forcewake);
if (intel_uncore_has_fifo(uncore))
uncore->fifo_count = fifo_free_entries(uncore);
spin_unlock_irq(&uncore->lock);
}
iosf_mbi_punit_release();
}
void intel_uncore_suspend(struct intel_uncore *uncore)
{
if (!intel_uncore_has_forcewake(uncore))
return;
iosf_mbi_punit_acquire();
iosf_mbi_unregister_pmic_bus_access_notifier_unlocked(
&uncore->pmic_bus_access_nb);
uncore->fw_domains_saved = intel_uncore_forcewake_reset(uncore);
iosf_mbi_punit_release();
}
void intel_uncore_resume_early(struct intel_uncore *uncore)
{
unsigned int restore_forcewake;
if (intel_uncore_unclaimed_mmio(uncore))
drm_dbg(&uncore->i915->drm, "unclaimed mmio detected on resume, clearing\n");
if (!intel_uncore_has_forcewake(uncore))
return;
restore_forcewake = fetch_and_zero(&uncore->fw_domains_saved);
forcewake_early_sanitize(uncore, restore_forcewake);
iosf_mbi_register_pmic_bus_access_notifier(&uncore->pmic_bus_access_nb);
}
void intel_uncore_runtime_resume(struct intel_uncore *uncore)
{
if (!intel_uncore_has_forcewake(uncore))
return;
iosf_mbi_register_pmic_bus_access_notifier(&uncore->pmic_bus_access_nb);
}
static void __intel_uncore_forcewake_get(struct intel_uncore *uncore,
enum forcewake_domains fw_domains)
{
struct intel_uncore_forcewake_domain *domain;
unsigned int tmp;
fw_domains &= uncore->fw_domains;
for_each_fw_domain_masked(domain, fw_domains, uncore, tmp) {
if (domain->wake_count++) {
fw_domains &= ~domain->mask;
domain->active = true;
}
}
if (fw_domains)
fw_domains_get(uncore, fw_domains);
}
/**
* intel_uncore_forcewake_get - grab forcewake domain references
* @uncore: the intel_uncore structure
* @fw_domains: forcewake domains to get reference on
*
* This function can be used get GT's forcewake domain references.
* Normal register access will handle the forcewake domains automatically.
* However if some sequence requires the GT to not power down a particular
* forcewake domains this function should be called at the beginning of the
* sequence. And subsequently the reference should be dropped by symmetric
* call to intel_unforce_forcewake_put(). Usually caller wants all the domains
* to be kept awake so the @fw_domains would be then FORCEWAKE_ALL.
*/
void intel_uncore_forcewake_get(struct intel_uncore *uncore,
enum forcewake_domains fw_domains)
{
unsigned long irqflags;
if (!uncore->fw_get_funcs)
return;
assert_rpm_wakelock_held(uncore->rpm);
spin_lock_irqsave(&uncore->lock, irqflags);
__intel_uncore_forcewake_get(uncore, fw_domains);
spin_unlock_irqrestore(&uncore->lock, irqflags);
}
/**
* intel_uncore_forcewake_user_get - claim forcewake on behalf of userspace
* @uncore: the intel_uncore structure
*
* This function is a wrapper around intel_uncore_forcewake_get() to acquire
* the GT powerwell and in the process disable our debugging for the
* duration of userspace's bypass.
*/
void intel_uncore_forcewake_user_get(struct intel_uncore *uncore)
{
spin_lock_irq(&uncore->lock);
if (!uncore->user_forcewake_count++) {
intel_uncore_forcewake_get__locked(uncore, FORCEWAKE_ALL);
mmio_debug_suspend(uncore);
}
spin_unlock_irq(&uncore->lock);
}
/**
* intel_uncore_forcewake_user_put - release forcewake on behalf of userspace
* @uncore: the intel_uncore structure
*
* This function complements intel_uncore_forcewake_user_get() and releases
* the GT powerwell taken on behalf of the userspace bypass.
*/
void intel_uncore_forcewake_user_put(struct intel_uncore *uncore)
{
spin_lock_irq(&uncore->lock);
if (!--uncore->user_forcewake_count) {
mmio_debug_resume(uncore);
intel_uncore_forcewake_put__locked(uncore, FORCEWAKE_ALL);
}
spin_unlock_irq(&uncore->lock);
}
/**
* intel_uncore_forcewake_get__locked - grab forcewake domain references
* @uncore: the intel_uncore structure
* @fw_domains: forcewake domains to get reference on
*
* See intel_uncore_forcewake_get(). This variant places the onus
* on the caller to explicitly handle the dev_priv->uncore.lock spinlock.
*/
void intel_uncore_forcewake_get__locked(struct intel_uncore *uncore,
enum forcewake_domains fw_domains)
{
lockdep_assert_held(&uncore->lock);
if (!uncore->fw_get_funcs)
return;
__intel_uncore_forcewake_get(uncore, fw_domains);
}
static void __intel_uncore_forcewake_put(struct intel_uncore *uncore,
enum forcewake_domains fw_domains,
bool delayed)
{
struct intel_uncore_forcewake_domain *domain;
unsigned int tmp;
fw_domains &= uncore->fw_domains;
for_each_fw_domain_masked(domain, fw_domains, uncore, tmp) {
GEM_BUG_ON(!domain->wake_count);
if (--domain->wake_count) {
domain->active = true;
continue;
}
if (delayed &&
!(domain->uncore->fw_domains_timer & domain->mask))
fw_domain_arm_timer(domain);
else
fw_domains_put(uncore, domain->mask);
}
}
/**
* intel_uncore_forcewake_put - release a forcewake domain reference
* @uncore: the intel_uncore structure
* @fw_domains: forcewake domains to put references
*
* This function drops the device-level forcewakes for specified
* domains obtained by intel_uncore_forcewake_get().
*/
void intel_uncore_forcewake_put(struct intel_uncore *uncore,
enum forcewake_domains fw_domains)
{
unsigned long irqflags;
if (!uncore->fw_get_funcs)
return;
spin_lock_irqsave(&uncore->lock, irqflags);
__intel_uncore_forcewake_put(uncore, fw_domains, false);
spin_unlock_irqrestore(&uncore->lock, irqflags);
}
void intel_uncore_forcewake_put_delayed(struct intel_uncore *uncore,
enum forcewake_domains fw_domains)
{
unsigned long irqflags;
if (!uncore->fw_get_funcs)
return;
spin_lock_irqsave(&uncore->lock, irqflags);
__intel_uncore_forcewake_put(uncore, fw_domains, true);
spin_unlock_irqrestore(&uncore->lock, irqflags);
}
/**
* intel_uncore_forcewake_flush - flush the delayed release
* @uncore: the intel_uncore structure
* @fw_domains: forcewake domains to flush
*/
void intel_uncore_forcewake_flush(struct intel_uncore *uncore,
enum forcewake_domains fw_domains)
{
struct intel_uncore_forcewake_domain *domain;
unsigned int tmp;
if (!uncore->fw_get_funcs)
return;
fw_domains &= uncore->fw_domains;
for_each_fw_domain_masked(domain, fw_domains, uncore, tmp) {
WRITE_ONCE(domain->active, false);
if (hrtimer_cancel(&domain->timer))
intel_uncore_fw_release_timer(&domain->timer);
}
}
/**
* intel_uncore_forcewake_put__locked - release forcewake domain references
* @uncore: the intel_uncore structure
* @fw_domains: forcewake domains to put references
*
* See intel_uncore_forcewake_put(). This variant places the onus
* on the caller to explicitly handle the dev_priv->uncore.lock spinlock.
*/
void intel_uncore_forcewake_put__locked(struct intel_uncore *uncore,
enum forcewake_domains fw_domains)
{
lockdep_assert_held(&uncore->lock);
if (!uncore->fw_get_funcs)
return;
__intel_uncore_forcewake_put(uncore, fw_domains, false);
}
void assert_forcewakes_inactive(struct intel_uncore *uncore)
{
if (!uncore->fw_get_funcs)
return;
drm_WARN(&uncore->i915->drm, uncore->fw_domains_active,
"Expected all fw_domains to be inactive, but %08x are still on\n",
uncore->fw_domains_active);
}
void assert_forcewakes_active(struct intel_uncore *uncore,
enum forcewake_domains fw_domains)
{
struct intel_uncore_forcewake_domain *domain;
unsigned int tmp;
if (!IS_ENABLED(CONFIG_DRM_I915_DEBUG_RUNTIME_PM))
return;
if (!uncore->fw_get_funcs)
return;
spin_lock_irq(&uncore->lock);
assert_rpm_wakelock_held(uncore->rpm);
fw_domains &= uncore->fw_domains;
drm_WARN(&uncore->i915->drm, fw_domains & ~uncore->fw_domains_active,
"Expected %08x fw_domains to be active, but %08x are off\n",
fw_domains, fw_domains & ~uncore->fw_domains_active);
/*
* Check that the caller has an explicit wakeref and we don't mistake
* it for the auto wakeref.
*/
for_each_fw_domain_masked(domain, fw_domains, uncore, tmp) {
unsigned int actual = READ_ONCE(domain->wake_count);
unsigned int expect = 1;
if (uncore->fw_domains_timer & domain->mask)
expect++; /* pending automatic release */
if (drm_WARN(&uncore->i915->drm, actual < expect,
"Expected domain %d to be held awake by caller, count=%d\n",
domain->id, actual))
break;
}
spin_unlock_irq(&uncore->lock);
}
/*
* We give fast paths for the really cool registers. The second range includes
* media domains (and the GSC starting from Xe_LPM+)
*/
#define NEEDS_FORCE_WAKE(reg) ({ \
u32 __reg = (reg); \
__reg < 0x40000 || __reg >= 0x116000; \
})
static int fw_range_cmp(u32 offset, const struct intel_forcewake_range *entry)
{
if (offset < entry->start)
return -1;
else if (offset > entry->end)
return 1;
else
return 0;
}
/* Copied and "macroized" from lib/bsearch.c */
#define BSEARCH(key, base, num, cmp) ({ \
unsigned int start__ = 0, end__ = (num); \
typeof(base) result__ = NULL; \
while (start__ < end__) { \
unsigned int mid__ = start__ + (end__ - start__) / 2; \
int ret__ = (cmp)((key), (base) + mid__); \
if (ret__ < 0) { \
end__ = mid__; \
} else if (ret__ > 0) { \
start__ = mid__ + 1; \
} else { \
result__ = (base) + mid__; \
break; \
} \
} \
result__; \
})
static enum forcewake_domains
find_fw_domain(struct intel_uncore *uncore, u32 offset)
{
const struct intel_forcewake_range *entry;
if (IS_GSI_REG(offset))
offset += uncore->gsi_offset;
entry = BSEARCH(offset,
uncore->fw_domains_table,
uncore->fw_domains_table_entries,
fw_range_cmp);
if (!entry)
return 0;
/*
* The list of FW domains depends on the SKU in gen11+ so we
* can't determine it statically. We use FORCEWAKE_ALL and
* translate it here to the list of available domains.
*/
if (entry->domains == FORCEWAKE_ALL)
return uncore->fw_domains;
drm_WARN(&uncore->i915->drm, entry->domains & ~uncore->fw_domains,
"Uninitialized forcewake domain(s) 0x%x accessed at 0x%x\n",
entry->domains & ~uncore->fw_domains, offset);
return entry->domains;
}
/*
* Shadowed register tables describe special register ranges that i915 is
* allowed to write to without acquiring forcewake. If these registers' power
* wells are down, the hardware will save values written by i915 to a shadow
* copy and automatically transfer them into the real register the next time
* the power well is woken up. Shadowing only applies to writes; forcewake
* must still be acquired when reading from registers in these ranges.
*
* The documentation for shadowed registers is somewhat spotty on older
* platforms. However missing registers from these lists is non-fatal; it just
* means we'll wake up the hardware for some register accesses where we didn't
* really need to.
*
* The ranges listed in these tables must be sorted by offset.
*
* When adding new tables here, please also add them to
* intel_shadow_table_check() in selftests/intel_uncore.c so that they will be
* scanned for obvious mistakes or typos by the selftests.
*/
static const struct i915_range gen8_shadowed_regs[] = {
{ .start = 0x2030, .end = 0x2030 },
{ .start = 0xA008, .end = 0xA00C },
{ .start = 0x12030, .end = 0x12030 },
{ .start = 0x1a030, .end = 0x1a030 },
{ .start = 0x22030, .end = 0x22030 },
};
static const struct i915_range gen11_shadowed_regs[] = {
{ .start = 0x2030, .end = 0x2030 },
{ .start = 0x2550, .end = 0x2550 },
{ .start = 0xA008, .end = 0xA00C },
{ .start = 0x22030, .end = 0x22030 },
{ .start = 0x22230, .end = 0x22230 },
{ .start = 0x22510, .end = 0x22550 },
{ .start = 0x1C0030, .end = 0x1C0030 },
{ .start = 0x1C0230, .end = 0x1C0230 },
{ .start = 0x1C0510, .end = 0x1C0550 },
{ .start = 0x1C4030, .end = 0x1C4030 },
{ .start = 0x1C4230, .end = 0x1C4230 },
{ .start = 0x1C4510, .end = 0x1C4550 },
{ .start = 0x1C8030, .end = 0x1C8030 },
{ .start = 0x1C8230, .end = 0x1C8230 },
{ .start = 0x1C8510, .end = 0x1C8550 },
{ .start = 0x1D0030, .end = 0x1D0030 },
{ .start = 0x1D0230, .end = 0x1D0230 },
{ .start = 0x1D0510, .end = 0x1D0550 },
{ .start = 0x1D4030, .end = 0x1D4030 },
{ .start = 0x1D4230, .end = 0x1D4230 },
{ .start = 0x1D4510, .end = 0x1D4550 },
{ .start = 0x1D8030, .end = 0x1D8030 },
{ .start = 0x1D8230, .end = 0x1D8230 },
{ .start = 0x1D8510, .end = 0x1D8550 },
};
static const struct i915_range gen12_shadowed_regs[] = {
{ .start = 0x2030, .end = 0x2030 },
{ .start = 0x2510, .end = 0x2550 },
{ .start = 0xA008, .end = 0xA00C },
{ .start = 0xA188, .end = 0xA188 },
{ .start = 0xA278, .end = 0xA278 },
{ .start = 0xA540, .end = 0xA56C },
{ .start = 0xC4C8, .end = 0xC4C8 },
{ .start = 0xC4D4, .end = 0xC4D4 },
{ .start = 0xC600, .end = 0xC600 },
{ .start = 0x22030, .end = 0x22030 },
{ .start = 0x22510, .end = 0x22550 },
{ .start = 0x1C0030, .end = 0x1C0030 },
{ .start = 0x1C0510, .end = 0x1C0550 },
{ .start = 0x1C4030, .end = 0x1C4030 },
{ .start = 0x1C4510, .end = 0x1C4550 },
{ .start = 0x1C8030, .end = 0x1C8030 },
{ .start = 0x1C8510, .end = 0x1C8550 },
{ .start = 0x1D0030, .end = 0x1D0030 },
{ .start = 0x1D0510, .end = 0x1D0550 },
{ .start = 0x1D4030, .end = 0x1D4030 },
{ .start = 0x1D4510, .end = 0x1D4550 },
{ .start = 0x1D8030, .end = 0x1D8030 },
{ .start = 0x1D8510, .end = 0x1D8550 },
/*
* The rest of these ranges are specific to Xe_HP and beyond, but
* are reserved/unused ranges on earlier gen12 platforms, so they can
* be safely added to the gen12 table.
*/
{ .start = 0x1E0030, .end = 0x1E0030 },
{ .start = 0x1E0510, .end = 0x1E0550 },
{ .start = 0x1E4030, .end = 0x1E4030 },
{ .start = 0x1E4510, .end = 0x1E4550 },
{ .start = 0x1E8030, .end = 0x1E8030 },
{ .start = 0x1E8510, .end = 0x1E8550 },
{ .start = 0x1F0030, .end = 0x1F0030 },
{ .start = 0x1F0510, .end = 0x1F0550 },
{ .start = 0x1F4030, .end = 0x1F4030 },
{ .start = 0x1F4510, .end = 0x1F4550 },
{ .start = 0x1F8030, .end = 0x1F8030 },
{ .start = 0x1F8510, .end = 0x1F8550 },
};
static const struct i915_range dg2_shadowed_regs[] = {
{ .start = 0x2030, .end = 0x2030 },
{ .start = 0x2510, .end = 0x2550 },
{ .start = 0xA008, .end = 0xA00C },
{ .start = 0xA188, .end = 0xA188 },
{ .start = 0xA278, .end = 0xA278 },
{ .start = 0xA540, .end = 0xA56C },
{ .start = 0xC4C8, .end = 0xC4C8 },
{ .start = 0xC4E0, .end = 0xC4E0 },
{ .start = 0xC600, .end = 0xC600 },
{ .start = 0xC658, .end = 0xC658 },
{ .start = 0x22030, .end = 0x22030 },
{ .start = 0x22510, .end = 0x22550 },
{ .start = 0x1C0030, .end = 0x1C0030 },
{ .start = 0x1C0510, .end = 0x1C0550 },
{ .start = 0x1C4030, .end = 0x1C4030 },
{ .start = 0x1C4510, .end = 0x1C4550 },
{ .start = 0x1C8030, .end = 0x1C8030 },
{ .start = 0x1C8510, .end = 0x1C8550 },
{ .start = 0x1D0030, .end = 0x1D0030 },
{ .start = 0x1D0510, .end = 0x1D0550 },
{ .start = 0x1D4030, .end = 0x1D4030 },
{ .start = 0x1D4510, .end = 0x1D4550 },
{ .start = 0x1D8030, .end = 0x1D8030 },
{ .start = 0x1D8510, .end = 0x1D8550 },
{ .start = 0x1E0030, .end = 0x1E0030 },
{ .start = 0x1E0510, .end = 0x1E0550 },
{ .start = 0x1E4030, .end = 0x1E4030 },
{ .start = 0x1E4510, .end = 0x1E4550 },
{ .start = 0x1E8030, .end = 0x1E8030 },
{ .start = 0x1E8510, .end = 0x1E8550 },
{ .start = 0x1F0030, .end = 0x1F0030 },
{ .start = 0x1F0510, .end = 0x1F0550 },
{ .start = 0x1F4030, .end = 0x1F4030 },
{ .start = 0x1F4510, .end = 0x1F4550 },
{ .start = 0x1F8030, .end = 0x1F8030 },
{ .start = 0x1F8510, .end = 0x1F8550 },
};
static const struct i915_range pvc_shadowed_regs[] = {
{ .start = 0x2030, .end = 0x2030 },
{ .start = 0x2510, .end = 0x2550 },
{ .start = 0xA008, .end = 0xA00C },
{ .start = 0xA188, .end = 0xA188 },
{ .start = 0xA278, .end = 0xA278 },
{ .start = 0xA540, .end = 0xA56C },
{ .start = 0xC4C8, .end = 0xC4C8 },
{ .start = 0xC4E0, .end = 0xC4E0 },
{ .start = 0xC600, .end = 0xC600 },
{ .start = 0xC658, .end = 0xC658 },
{ .start = 0x22030, .end = 0x22030 },
{ .start = 0x22510, .end = 0x22550 },
{ .start = 0x1C0030, .end = 0x1C0030 },
{ .start = 0x1C0510, .end = 0x1C0550 },
{ .start = 0x1C4030, .end = 0x1C4030 },
{ .start = 0x1C4510, .end = 0x1C4550 },
{ .start = 0x1C8030, .end = 0x1C8030 },
{ .start = 0x1C8510, .end = 0x1C8550 },
{ .start = 0x1D0030, .end = 0x1D0030 },
{ .start = 0x1D0510, .end = 0x1D0550 },
{ .start = 0x1D4030, .end = 0x1D4030 },
{ .start = 0x1D4510, .end = 0x1D4550 },
{ .start = 0x1D8030, .end = 0x1D8030 },
{ .start = 0x1D8510, .end = 0x1D8550 },
{ .start = 0x1E0030, .end = 0x1E0030 },
{ .start = 0x1E0510, .end = 0x1E0550 },
{ .start = 0x1E4030, .end = 0x1E4030 },
{ .start = 0x1E4510, .end = 0x1E4550 },
{ .start = 0x1E8030, .end = 0x1E8030 },
{ .start = 0x1E8510, .end = 0x1E8550 },
{ .start = 0x1F0030, .end = 0x1F0030 },
{ .start = 0x1F0510, .end = 0x1F0550 },
{ .start = 0x1F4030, .end = 0x1F4030 },
{ .start = 0x1F4510, .end = 0x1F4550 },
{ .start = 0x1F8030, .end = 0x1F8030 },
{ .start = 0x1F8510, .end = 0x1F8550 },
};
static const struct i915_range mtl_shadowed_regs[] = {
{ .start = 0x2030, .end = 0x2030 },
{ .start = 0x2510, .end = 0x2550 },
{ .start = 0xA008, .end = 0xA00C },
{ .start = 0xA188, .end = 0xA188 },
{ .start = 0xA278, .end = 0xA278 },
{ .start = 0xA540, .end = 0xA56C },
{ .start = 0xC050, .end = 0xC050 },
{ .start = 0xC340, .end = 0xC340 },
{ .start = 0xC4C8, .end = 0xC4C8 },
{ .start = 0xC4E0, .end = 0xC4E0 },
{ .start = 0xC600, .end = 0xC600 },
{ .start = 0xC658, .end = 0xC658 },
{ .start = 0xCFD4, .end = 0xCFDC },
{ .start = 0x22030, .end = 0x22030 },
{ .start = 0x22510, .end = 0x22550 },
};
static const struct i915_range xelpmp_shadowed_regs[] = {
{ .start = 0x1C0030, .end = 0x1C0030 },
{ .start = 0x1C0510, .end = 0x1C0550 },
{ .start = 0x1C8030, .end = 0x1C8030 },
{ .start = 0x1C8510, .end = 0x1C8550 },
{ .start = 0x1D0030, .end = 0x1D0030 },
{ .start = 0x1D0510, .end = 0x1D0550 },
{ .start = 0x38A008, .end = 0x38A00C },
{ .start = 0x38A188, .end = 0x38A188 },
{ .start = 0x38A278, .end = 0x38A278 },
{ .start = 0x38A540, .end = 0x38A56C },
{ .start = 0x38A618, .end = 0x38A618 },
{ .start = 0x38C050, .end = 0x38C050 },
{ .start = 0x38C340, .end = 0x38C340 },
{ .start = 0x38C4C8, .end = 0x38C4C8 },
{ .start = 0x38C4E0, .end = 0x38C4E4 },
{ .start = 0x38C600, .end = 0x38C600 },
{ .start = 0x38C658, .end = 0x38C658 },
{ .start = 0x38CFD4, .end = 0x38CFDC },
};
static int mmio_range_cmp(u32 key, const struct i915_range *range)
{
if (key < range->start)
return -1;
else if (key > range->end)
return 1;
else
return 0;
}
static bool is_shadowed(struct intel_uncore *uncore, u32 offset)
{
if (drm_WARN_ON(&uncore->i915->drm, !uncore->shadowed_reg_table))
return false;
if (IS_GSI_REG(offset))
offset += uncore->gsi_offset;
return BSEARCH(offset,
uncore->shadowed_reg_table,
uncore->shadowed_reg_table_entries,
mmio_range_cmp);
}
static enum forcewake_domains
gen6_reg_write_fw_domains(struct intel_uncore *uncore, i915_reg_t reg)
{
return FORCEWAKE_RENDER;
}
#define __fwtable_reg_read_fw_domains(uncore, offset) \
({ \
enum forcewake_domains __fwd = 0; \
if (NEEDS_FORCE_WAKE((offset))) \
__fwd = find_fw_domain(uncore, offset); \
__fwd; \
})
#define __fwtable_reg_write_fw_domains(uncore, offset) \
({ \
enum forcewake_domains __fwd = 0; \
const u32 __offset = (offset); \
if (NEEDS_FORCE_WAKE((__offset)) && !is_shadowed(uncore, __offset)) \
__fwd = find_fw_domain(uncore, __offset); \
__fwd; \
})
#define GEN_FW_RANGE(s, e, d) \
{ .start = (s), .end = (e), .domains = (d) }
/*
* All platforms' forcewake tables below must be sorted by offset ranges.
* Furthermore, new forcewake tables added should be "watertight" and have
* no gaps between ranges.
*
* When there are multiple consecutive ranges listed in the bspec with
* the same forcewake domain, it is customary to combine them into a single
* row in the tables below to keep the tables small and lookups fast.
* Likewise, reserved/unused ranges may be combined with the preceding and/or
* following ranges since the driver will never be making MMIO accesses in
* those ranges.
*
* For example, if the bspec were to list:
*
* ...
* 0x1000 - 0x1fff: GT
* 0x2000 - 0x2cff: GT
* 0x2d00 - 0x2fff: unused/reserved
* 0x3000 - 0xffff: GT
* ...
*
* these could all be represented by a single line in the code:
*
* GEN_FW_RANGE(0x1000, 0xffff, FORCEWAKE_GT)
*
* When adding new forcewake tables here, please also add them to
* intel_uncore_mock_selftests in selftests/intel_uncore.c so that they will be
* scanned for obvious mistakes or typos by the selftests.
*/
static const struct intel_forcewake_range __gen6_fw_ranges[] = {
GEN_FW_RANGE(0x0, 0x3ffff, FORCEWAKE_RENDER),
};
static const struct intel_forcewake_range __vlv_fw_ranges[] = {
GEN_FW_RANGE(0x2000, 0x3fff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x5000, 0x7fff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0xb000, 0x11fff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x12000, 0x13fff, FORCEWAKE_MEDIA),
GEN_FW_RANGE(0x22000, 0x23fff, FORCEWAKE_MEDIA),
GEN_FW_RANGE(0x2e000, 0x2ffff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x30000, 0x3ffff, FORCEWAKE_MEDIA),
};
static const struct intel_forcewake_range __chv_fw_ranges[] = {
GEN_FW_RANGE(0x2000, 0x3fff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x4000, 0x4fff, FORCEWAKE_RENDER | FORCEWAKE_MEDIA),
GEN_FW_RANGE(0x5200, 0x7fff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x8000, 0x82ff, FORCEWAKE_RENDER | FORCEWAKE_MEDIA),
GEN_FW_RANGE(0x8300, 0x84ff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x8500, 0x85ff, FORCEWAKE_RENDER | FORCEWAKE_MEDIA),
GEN_FW_RANGE(0x8800, 0x88ff, FORCEWAKE_MEDIA),
GEN_FW_RANGE(0x9000, 0xafff, FORCEWAKE_RENDER | FORCEWAKE_MEDIA),
GEN_FW_RANGE(0xb000, 0xb47f, FORCEWAKE_RENDER),
GEN_FW_RANGE(0xd000, 0xd7ff, FORCEWAKE_MEDIA),
GEN_FW_RANGE(0xe000, 0xe7ff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0xf000, 0xffff, FORCEWAKE_RENDER | FORCEWAKE_MEDIA),
GEN_FW_RANGE(0x12000, 0x13fff, FORCEWAKE_MEDIA),
GEN_FW_RANGE(0x1a000, 0x1bfff, FORCEWAKE_MEDIA),
GEN_FW_RANGE(0x1e800, 0x1e9ff, FORCEWAKE_MEDIA),
GEN_FW_RANGE(0x30000, 0x37fff, FORCEWAKE_MEDIA),
};
static const struct intel_forcewake_range __gen9_fw_ranges[] = {
GEN_FW_RANGE(0x0, 0xaff, FORCEWAKE_GT),
GEN_FW_RANGE(0xb00, 0x1fff, 0), /* uncore range */
GEN_FW_RANGE(0x2000, 0x26ff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x2700, 0x2fff, FORCEWAKE_GT),
GEN_FW_RANGE(0x3000, 0x3fff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x4000, 0x51ff, FORCEWAKE_GT),
GEN_FW_RANGE(0x5200, 0x7fff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x8000, 0x812f, FORCEWAKE_GT),
GEN_FW_RANGE(0x8130, 0x813f, FORCEWAKE_MEDIA),
GEN_FW_RANGE(0x8140, 0x815f, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x8160, 0x82ff, FORCEWAKE_GT),
GEN_FW_RANGE(0x8300, 0x84ff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x8500, 0x87ff, FORCEWAKE_GT),
GEN_FW_RANGE(0x8800, 0x89ff, FORCEWAKE_MEDIA),
GEN_FW_RANGE(0x8a00, 0x8bff, FORCEWAKE_GT),
GEN_FW_RANGE(0x8c00, 0x8cff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x8d00, 0x93ff, FORCEWAKE_GT),
GEN_FW_RANGE(0x9400, 0x97ff, FORCEWAKE_RENDER | FORCEWAKE_MEDIA),
GEN_FW_RANGE(0x9800, 0xafff, FORCEWAKE_GT),
GEN_FW_RANGE(0xb000, 0xb47f, FORCEWAKE_RENDER),
GEN_FW_RANGE(0xb480, 0xcfff, FORCEWAKE_GT),
GEN_FW_RANGE(0xd000, 0xd7ff, FORCEWAKE_MEDIA),
GEN_FW_RANGE(0xd800, 0xdfff, FORCEWAKE_GT),
GEN_FW_RANGE(0xe000, 0xe8ff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0xe900, 0x11fff, FORCEWAKE_GT),
GEN_FW_RANGE(0x12000, 0x13fff, FORCEWAKE_MEDIA),
GEN_FW_RANGE(0x14000, 0x19fff, FORCEWAKE_GT),
GEN_FW_RANGE(0x1a000, 0x1e9ff, FORCEWAKE_MEDIA),
GEN_FW_RANGE(0x1ea00, 0x243ff, FORCEWAKE_GT),
GEN_FW_RANGE(0x24400, 0x247ff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x24800, 0x2ffff, FORCEWAKE_GT),
GEN_FW_RANGE(0x30000, 0x3ffff, FORCEWAKE_MEDIA),
};
static const struct intel_forcewake_range __gen11_fw_ranges[] = {
GEN_FW_RANGE(0x0, 0x1fff, 0), /* uncore range */
GEN_FW_RANGE(0x2000, 0x26ff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x2700, 0x2fff, FORCEWAKE_GT),
GEN_FW_RANGE(0x3000, 0x3fff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x4000, 0x51ff, FORCEWAKE_GT),
GEN_FW_RANGE(0x5200, 0x7fff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x8000, 0x813f, FORCEWAKE_GT),
GEN_FW_RANGE(0x8140, 0x815f, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x8160, 0x82ff, FORCEWAKE_GT),
GEN_FW_RANGE(0x8300, 0x84ff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x8500, 0x87ff, FORCEWAKE_GT),
GEN_FW_RANGE(0x8800, 0x8bff, 0),
GEN_FW_RANGE(0x8c00, 0x8cff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x8d00, 0x94cf, FORCEWAKE_GT),
GEN_FW_RANGE(0x94d0, 0x955f, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x9560, 0x95ff, 0),
GEN_FW_RANGE(0x9600, 0xafff, FORCEWAKE_GT),
GEN_FW_RANGE(0xb000, 0xb47f, FORCEWAKE_RENDER),
GEN_FW_RANGE(0xb480, 0xdeff, FORCEWAKE_GT),
GEN_FW_RANGE(0xdf00, 0xe8ff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0xe900, 0x16dff, FORCEWAKE_GT),
GEN_FW_RANGE(0x16e00, 0x19fff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x1a000, 0x23fff, FORCEWAKE_GT),
GEN_FW_RANGE(0x24000, 0x2407f, 0),
GEN_FW_RANGE(0x24080, 0x2417f, FORCEWAKE_GT),
GEN_FW_RANGE(0x24180, 0x242ff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x24300, 0x243ff, FORCEWAKE_GT),
GEN_FW_RANGE(0x24400, 0x24fff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x25000, 0x3ffff, FORCEWAKE_GT),
GEN_FW_RANGE(0x40000, 0x1bffff, 0),
GEN_FW_RANGE(0x1c0000, 0x1c3fff, FORCEWAKE_MEDIA_VDBOX0),
GEN_FW_RANGE(0x1c4000, 0x1c7fff, 0),
GEN_FW_RANGE(0x1c8000, 0x1cffff, FORCEWAKE_MEDIA_VEBOX0),
GEN_FW_RANGE(0x1d0000, 0x1d3fff, FORCEWAKE_MEDIA_VDBOX2),
GEN_FW_RANGE(0x1d4000, 0x1dbfff, 0)
};
static const struct intel_forcewake_range __gen12_fw_ranges[] = {
GEN_FW_RANGE(0x0, 0x1fff, 0), /*
0x0 - 0xaff: reserved
0xb00 - 0x1fff: always on */
GEN_FW_RANGE(0x2000, 0x26ff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x2700, 0x27ff, FORCEWAKE_GT),
GEN_FW_RANGE(0x2800, 0x2aff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x2b00, 0x2fff, FORCEWAKE_GT),
GEN_FW_RANGE(0x3000, 0x3fff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x4000, 0x51ff, FORCEWAKE_GT), /*
0x4000 - 0x48ff: gt
0x4900 - 0x51ff: reserved */
GEN_FW_RANGE(0x5200, 0x7fff, FORCEWAKE_RENDER), /*
0x5200 - 0x53ff: render
0x5400 - 0x54ff: reserved
0x5500 - 0x7fff: render */
GEN_FW_RANGE(0x8000, 0x813f, FORCEWAKE_GT),
GEN_FW_RANGE(0x8140, 0x815f, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x8160, 0x81ff, 0), /*
0x8160 - 0x817f: reserved
0x8180 - 0x81ff: always on */
GEN_FW_RANGE(0x8200, 0x82ff, FORCEWAKE_GT),
GEN_FW_RANGE(0x8300, 0x84ff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x8500, 0x94cf, FORCEWAKE_GT), /*
0x8500 - 0x87ff: gt
0x8800 - 0x8fff: reserved
0x9000 - 0x947f: gt
0x9480 - 0x94cf: reserved */
GEN_FW_RANGE(0x94d0, 0x955f, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x9560, 0x97ff, 0), /*
0x9560 - 0x95ff: always on
0x9600 - 0x97ff: reserved */
GEN_FW_RANGE(0x9800, 0xafff, FORCEWAKE_GT),
GEN_FW_RANGE(0xb000, 0xb3ff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0xb400, 0xcfff, FORCEWAKE_GT), /*
0xb400 - 0xbf7f: gt
0xb480 - 0xbfff: reserved
0xc000 - 0xcfff: gt */
GEN_FW_RANGE(0xd000, 0xd7ff, 0),
GEN_FW_RANGE(0xd800, 0xd8ff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0xd900, 0xdbff, FORCEWAKE_GT),
GEN_FW_RANGE(0xdc00, 0xefff, FORCEWAKE_RENDER), /*
0xdc00 - 0xddff: render
0xde00 - 0xde7f: reserved
0xde80 - 0xe8ff: render
0xe900 - 0xefff: reserved */
GEN_FW_RANGE(0xf000, 0x147ff, FORCEWAKE_GT), /*
0xf000 - 0xffff: gt
0x10000 - 0x147ff: reserved */
GEN_FW_RANGE(0x14800, 0x1ffff, FORCEWAKE_RENDER), /*
0x14800 - 0x14fff: render
0x15000 - 0x16dff: reserved
0x16e00 - 0x1bfff: render
0x1c000 - 0x1ffff: reserved */
GEN_FW_RANGE(0x20000, 0x20fff, FORCEWAKE_MEDIA_VDBOX0),
GEN_FW_RANGE(0x21000, 0x21fff, FORCEWAKE_MEDIA_VDBOX2),
GEN_FW_RANGE(0x22000, 0x23fff, FORCEWAKE_GT),
GEN_FW_RANGE(0x24000, 0x2417f, 0), /*
0x24000 - 0x2407f: always on
0x24080 - 0x2417f: reserved */
GEN_FW_RANGE(0x24180, 0x249ff, FORCEWAKE_GT), /*
0x24180 - 0x241ff: gt
0x24200 - 0x249ff: reserved */
GEN_FW_RANGE(0x24a00, 0x251ff, FORCEWAKE_RENDER), /*
0x24a00 - 0x24a7f: render
0x24a80 - 0x251ff: reserved */
GEN_FW_RANGE(0x25200, 0x255ff, FORCEWAKE_GT), /*
0x25200 - 0x252ff: gt
0x25300 - 0x255ff: reserved */
GEN_FW_RANGE(0x25600, 0x2567f, FORCEWAKE_MEDIA_VDBOX0),
GEN_FW_RANGE(0x25680, 0x259ff, FORCEWAKE_MEDIA_VDBOX2), /*
0x25680 - 0x256ff: VD2
0x25700 - 0x259ff: reserved */
GEN_FW_RANGE(0x25a00, 0x25a7f, FORCEWAKE_MEDIA_VDBOX0),
GEN_FW_RANGE(0x25a80, 0x2ffff, FORCEWAKE_MEDIA_VDBOX2), /*
0x25a80 - 0x25aff: VD2
0x25b00 - 0x2ffff: reserved */
GEN_FW_RANGE(0x30000, 0x3ffff, FORCEWAKE_GT),
GEN_FW_RANGE(0x40000, 0x1bffff, 0),
GEN_FW_RANGE(0x1c0000, 0x1c3fff, FORCEWAKE_MEDIA_VDBOX0), /*
0x1c0000 - 0x1c2bff: VD0
0x1c2c00 - 0x1c2cff: reserved
0x1c2d00 - 0x1c2dff: VD0
0x1c2e00 - 0x1c3eff: reserved
0x1c3f00 - 0x1c3fff: VD0 */
GEN_FW_RANGE(0x1c4000, 0x1c7fff, 0),
GEN_FW_RANGE(0x1c8000, 0x1cbfff, FORCEWAKE_MEDIA_VEBOX0), /*
0x1c8000 - 0x1ca0ff: VE0
0x1ca100 - 0x1cbeff: reserved
0x1cbf00 - 0x1cbfff: VE0 */
GEN_FW_RANGE(0x1cc000, 0x1cffff, FORCEWAKE_MEDIA_VDBOX0), /*
0x1cc000 - 0x1ccfff: VD0
0x1cd000 - 0x1cffff: reserved */
GEN_FW_RANGE(0x1d0000, 0x1d3fff, FORCEWAKE_MEDIA_VDBOX2), /*
0x1d0000 - 0x1d2bff: VD2
0x1d2c00 - 0x1d2cff: reserved
0x1d2d00 - 0x1d2dff: VD2
0x1d2e00 - 0x1d3eff: reserved
0x1d3f00 - 0x1d3fff: VD2 */
};
/*
* Graphics IP version 12.55 brings a slight change to the 0xd800 range,
* switching it from the GT domain to the render domain.
*/
#define XEHP_FWRANGES(FW_RANGE_D800) \
GEN_FW_RANGE(0x0, 0x1fff, 0), /* \
0x0 - 0xaff: reserved \
0xb00 - 0x1fff: always on */ \
GEN_FW_RANGE(0x2000, 0x26ff, FORCEWAKE_RENDER), \
GEN_FW_RANGE(0x2700, 0x4aff, FORCEWAKE_GT), \
GEN_FW_RANGE(0x4b00, 0x51ff, 0), /* \
0x4b00 - 0x4fff: reserved \
0x5000 - 0x51ff: always on */ \
GEN_FW_RANGE(0x5200, 0x7fff, FORCEWAKE_RENDER), \
GEN_FW_RANGE(0x8000, 0x813f, FORCEWAKE_GT), \
GEN_FW_RANGE(0x8140, 0x815f, FORCEWAKE_RENDER), \
GEN_FW_RANGE(0x8160, 0x81ff, 0), /* \
0x8160 - 0x817f: reserved \
0x8180 - 0x81ff: always on */ \
GEN_FW_RANGE(0x8200, 0x82ff, FORCEWAKE_GT), \
GEN_FW_RANGE(0x8300, 0x84ff, FORCEWAKE_RENDER), \
GEN_FW_RANGE(0x8500, 0x8cff, FORCEWAKE_GT), /* \
0x8500 - 0x87ff: gt \
0x8800 - 0x8c7f: reserved \
0x8c80 - 0x8cff: gt (DG2 only) */ \
GEN_FW_RANGE(0x8d00, 0x8fff, FORCEWAKE_RENDER), /* \
0x8d00 - 0x8dff: render (DG2 only) \
0x8e00 - 0x8fff: reserved */ \
GEN_FW_RANGE(0x9000, 0x94cf, FORCEWAKE_GT), /* \
0x9000 - 0x947f: gt \
0x9480 - 0x94cf: reserved */ \
GEN_FW_RANGE(0x94d0, 0x955f, FORCEWAKE_RENDER), \
GEN_FW_RANGE(0x9560, 0x967f, 0), /* \
0x9560 - 0x95ff: always on \
0x9600 - 0x967f: reserved */ \
GEN_FW_RANGE(0x9680, 0x97ff, FORCEWAKE_RENDER), /* \
0x9680 - 0x96ff: render (DG2 only) \
0x9700 - 0x97ff: reserved */ \
GEN_FW_RANGE(0x9800, 0xcfff, FORCEWAKE_GT), /* \
0x9800 - 0xb4ff: gt \
0xb500 - 0xbfff: reserved \
0xc000 - 0xcfff: gt */ \
GEN_FW_RANGE(0xd000, 0xd7ff, 0), \
GEN_FW_RANGE(0xd800, 0xd87f, FW_RANGE_D800), \
GEN_FW_RANGE(0xd880, 0xdbff, FORCEWAKE_GT), \
GEN_FW_RANGE(0xdc00, 0xdcff, FORCEWAKE_RENDER), \
GEN_FW_RANGE(0xdd00, 0xde7f, FORCEWAKE_GT), /* \
0xdd00 - 0xddff: gt \
0xde00 - 0xde7f: reserved */ \
GEN_FW_RANGE(0xde80, 0xe8ff, FORCEWAKE_RENDER), /* \
0xde80 - 0xdfff: render \
0xe000 - 0xe0ff: reserved \
0xe100 - 0xe8ff: render */ \
GEN_FW_RANGE(0xe900, 0xffff, FORCEWAKE_GT), /* \
0xe900 - 0xe9ff: gt \
0xea00 - 0xefff: reserved \
0xf000 - 0xffff: gt */ \
GEN_FW_RANGE(0x10000, 0x12fff, 0), /* \
0x10000 - 0x11fff: reserved \
0x12000 - 0x127ff: always on \
0x12800 - 0x12fff: reserved */ \
GEN_FW_RANGE(0x13000, 0x131ff, FORCEWAKE_MEDIA_VDBOX0), /* DG2 only */ \
GEN_FW_RANGE(0x13200, 0x13fff, FORCEWAKE_MEDIA_VDBOX2), /* \
0x13200 - 0x133ff: VD2 (DG2 only) \
0x13400 - 0x13fff: reserved */ \
GEN_FW_RANGE(0x14000, 0x141ff, FORCEWAKE_MEDIA_VDBOX0), /* XEHPSDV only */ \
GEN_FW_RANGE(0x14200, 0x143ff, FORCEWAKE_MEDIA_VDBOX2), /* XEHPSDV only */ \
GEN_FW_RANGE(0x14400, 0x145ff, FORCEWAKE_MEDIA_VDBOX4), /* XEHPSDV only */ \
GEN_FW_RANGE(0x14600, 0x147ff, FORCEWAKE_MEDIA_VDBOX6), /* XEHPSDV only */ \
GEN_FW_RANGE(0x14800, 0x14fff, FORCEWAKE_RENDER), \
GEN_FW_RANGE(0x15000, 0x16dff, FORCEWAKE_GT), /* \
0x15000 - 0x15fff: gt (DG2 only) \
0x16000 - 0x16dff: reserved */ \
GEN_FW_RANGE(0x16e00, 0x1ffff, FORCEWAKE_RENDER), \
GEN_FW_RANGE(0x20000, 0x21fff, FORCEWAKE_MEDIA_VDBOX0), /* \
0x20000 - 0x20fff: VD0 (XEHPSDV only) \
0x21000 - 0x21fff: reserved */ \
GEN_FW_RANGE(0x22000, 0x23fff, FORCEWAKE_GT), \
GEN_FW_RANGE(0x24000, 0x2417f, 0), /* \
0x24000 - 0x2407f: always on \
0x24080 - 0x2417f: reserved */ \
GEN_FW_RANGE(0x24180, 0x249ff, FORCEWAKE_GT), /* \
0x24180 - 0x241ff: gt \
0x24200 - 0x249ff: reserved */ \
GEN_FW_RANGE(0x24a00, 0x251ff, FORCEWAKE_RENDER), /* \
0x24a00 - 0x24a7f: render \
0x24a80 - 0x251ff: reserved */ \
GEN_FW_RANGE(0x25200, 0x25fff, FORCEWAKE_GT), /* \
0x25200 - 0x252ff: gt \
0x25300 - 0x25fff: reserved */ \
GEN_FW_RANGE(0x26000, 0x2ffff, FORCEWAKE_RENDER), /* \
0x26000 - 0x27fff: render \
0x28000 - 0x29fff: reserved \
0x2a000 - 0x2ffff: undocumented */ \
GEN_FW_RANGE(0x30000, 0x3ffff, FORCEWAKE_GT), \
GEN_FW_RANGE(0x40000, 0x1bffff, 0), \
GEN_FW_RANGE(0x1c0000, 0x1c3fff, FORCEWAKE_MEDIA_VDBOX0), /* \
0x1c0000 - 0x1c2bff: VD0 \
0x1c2c00 - 0x1c2cff: reserved \
0x1c2d00 - 0x1c2dff: VD0 \
0x1c2e00 - 0x1c3eff: VD0 (DG2 only) \
0x1c3f00 - 0x1c3fff: VD0 */ \
GEN_FW_RANGE(0x1c4000, 0x1c7fff, FORCEWAKE_MEDIA_VDBOX1), /* \
0x1c4000 - 0x1c6bff: VD1 \
0x1c6c00 - 0x1c6cff: reserved \
0x1c6d00 - 0x1c6dff: VD1 \
0x1c6e00 - 0x1c7fff: reserved */ \
GEN_FW_RANGE(0x1c8000, 0x1cbfff, FORCEWAKE_MEDIA_VEBOX0), /* \
0x1c8000 - 0x1ca0ff: VE0 \
0x1ca100 - 0x1cbfff: reserved */ \
GEN_FW_RANGE(0x1cc000, 0x1ccfff, FORCEWAKE_MEDIA_VDBOX0), \
GEN_FW_RANGE(0x1cd000, 0x1cdfff, FORCEWAKE_MEDIA_VDBOX2), \
GEN_FW_RANGE(0x1ce000, 0x1cefff, FORCEWAKE_MEDIA_VDBOX4), \
GEN_FW_RANGE(0x1cf000, 0x1cffff, FORCEWAKE_MEDIA_VDBOX6), \
GEN_FW_RANGE(0x1d0000, 0x1d3fff, FORCEWAKE_MEDIA_VDBOX2), /* \
0x1d0000 - 0x1d2bff: VD2 \
0x1d2c00 - 0x1d2cff: reserved \
0x1d2d00 - 0x1d2dff: VD2 \
0x1d2e00 - 0x1d3dff: VD2 (DG2 only) \
0x1d3e00 - 0x1d3eff: reserved \
0x1d3f00 - 0x1d3fff: VD2 */ \
GEN_FW_RANGE(0x1d4000, 0x1d7fff, FORCEWAKE_MEDIA_VDBOX3), /* \
0x1d4000 - 0x1d6bff: VD3 \
0x1d6c00 - 0x1d6cff: reserved \
0x1d6d00 - 0x1d6dff: VD3 \
0x1d6e00 - 0x1d7fff: reserved */ \
GEN_FW_RANGE(0x1d8000, 0x1dffff, FORCEWAKE_MEDIA_VEBOX1), /* \
0x1d8000 - 0x1da0ff: VE1 \
0x1da100 - 0x1dffff: reserved */ \
GEN_FW_RANGE(0x1e0000, 0x1e3fff, FORCEWAKE_MEDIA_VDBOX4), /* \
0x1e0000 - 0x1e2bff: VD4 \
0x1e2c00 - 0x1e2cff: reserved \
0x1e2d00 - 0x1e2dff: VD4 \
0x1e2e00 - 0x1e3eff: reserved \
0x1e3f00 - 0x1e3fff: VD4 */ \
GEN_FW_RANGE(0x1e4000, 0x1e7fff, FORCEWAKE_MEDIA_VDBOX5), /* \
0x1e4000 - 0x1e6bff: VD5 \
0x1e6c00 - 0x1e6cff: reserved \
0x1e6d00 - 0x1e6dff: VD5 \
0x1e6e00 - 0x1e7fff: reserved */ \
GEN_FW_RANGE(0x1e8000, 0x1effff, FORCEWAKE_MEDIA_VEBOX2), /* \
0x1e8000 - 0x1ea0ff: VE2 \
0x1ea100 - 0x1effff: reserved */ \
GEN_FW_RANGE(0x1f0000, 0x1f3fff, FORCEWAKE_MEDIA_VDBOX6), /* \
0x1f0000 - 0x1f2bff: VD6 \
0x1f2c00 - 0x1f2cff: reserved \
0x1f2d00 - 0x1f2dff: VD6 \
0x1f2e00 - 0x1f3eff: reserved \
0x1f3f00 - 0x1f3fff: VD6 */ \
GEN_FW_RANGE(0x1f4000, 0x1f7fff, FORCEWAKE_MEDIA_VDBOX7), /* \
0x1f4000 - 0x1f6bff: VD7 \
0x1f6c00 - 0x1f6cff: reserved \
0x1f6d00 - 0x1f6dff: VD7 \
0x1f6e00 - 0x1f7fff: reserved */ \
GEN_FW_RANGE(0x1f8000, 0x1fa0ff, FORCEWAKE_MEDIA_VEBOX3),
static const struct intel_forcewake_range __xehp_fw_ranges[] = {
XEHP_FWRANGES(FORCEWAKE_GT)
};
static const struct intel_forcewake_range __dg2_fw_ranges[] = {
XEHP_FWRANGES(FORCEWAKE_RENDER)
};
static const struct intel_forcewake_range __pvc_fw_ranges[] = {
GEN_FW_RANGE(0x0, 0xaff, 0),
GEN_FW_RANGE(0xb00, 0xbff, FORCEWAKE_GT),
GEN_FW_RANGE(0xc00, 0xfff, 0),
GEN_FW_RANGE(0x1000, 0x1fff, FORCEWAKE_GT),
GEN_FW_RANGE(0x2000, 0x26ff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x2700, 0x2fff, FORCEWAKE_GT),
GEN_FW_RANGE(0x3000, 0x3fff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x4000, 0x813f, FORCEWAKE_GT), /*
0x4000 - 0x4aff: gt
0x4b00 - 0x4fff: reserved
0x5000 - 0x51ff: gt
0x5200 - 0x52ff: reserved
0x5300 - 0x53ff: gt
0x5400 - 0x7fff: reserved
0x8000 - 0x813f: gt */
GEN_FW_RANGE(0x8140, 0x817f, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x8180, 0x81ff, 0),
GEN_FW_RANGE(0x8200, 0x94cf, FORCEWAKE_GT), /*
0x8200 - 0x82ff: gt
0x8300 - 0x84ff: reserved
0x8500 - 0x887f: gt
0x8880 - 0x8a7f: reserved
0x8a80 - 0x8aff: gt
0x8b00 - 0x8fff: reserved
0x9000 - 0x947f: gt
0x9480 - 0x94cf: reserved */
GEN_FW_RANGE(0x94d0, 0x955f, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x9560, 0x967f, 0), /*
0x9560 - 0x95ff: always on
0x9600 - 0x967f: reserved */
GEN_FW_RANGE(0x9680, 0x97ff, FORCEWAKE_RENDER), /*
0x9680 - 0x96ff: render
0x9700 - 0x97ff: reserved */
GEN_FW_RANGE(0x9800, 0xcfff, FORCEWAKE_GT), /*
0x9800 - 0xb4ff: gt
0xb500 - 0xbfff: reserved
0xc000 - 0xcfff: gt */
GEN_FW_RANGE(0xd000, 0xd3ff, 0),
GEN_FW_RANGE(0xd400, 0xdbff, FORCEWAKE_GT),
GEN_FW_RANGE(0xdc00, 0xdcff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0xdd00, 0xde7f, FORCEWAKE_GT), /*
0xdd00 - 0xddff: gt
0xde00 - 0xde7f: reserved */
GEN_FW_RANGE(0xde80, 0xe8ff, FORCEWAKE_RENDER), /*
0xde80 - 0xdeff: render
0xdf00 - 0xe1ff: reserved
0xe200 - 0xe7ff: render
0xe800 - 0xe8ff: reserved */
GEN_FW_RANGE(0xe900, 0x11fff, FORCEWAKE_GT), /*
0xe900 - 0xe9ff: gt
0xea00 - 0xebff: reserved
0xec00 - 0xffff: gt
0x10000 - 0x11fff: reserved */
GEN_FW_RANGE(0x12000, 0x12fff, 0), /*
0x12000 - 0x127ff: always on
0x12800 - 0x12fff: reserved */
GEN_FW_RANGE(0x13000, 0x19fff, FORCEWAKE_GT), /*
0x13000 - 0x135ff: gt
0x13600 - 0x147ff: reserved
0x14800 - 0x153ff: gt
0x15400 - 0x19fff: reserved */
GEN_FW_RANGE(0x1a000, 0x21fff, FORCEWAKE_RENDER), /*
0x1a000 - 0x1ffff: render
0x20000 - 0x21fff: reserved */
GEN_FW_RANGE(0x22000, 0x23fff, FORCEWAKE_GT),
GEN_FW_RANGE(0x24000, 0x2417f, 0), /*
24000 - 0x2407f: always on
24080 - 0x2417f: reserved */
GEN_FW_RANGE(0x24180, 0x25fff, FORCEWAKE_GT), /*
0x24180 - 0x241ff: gt
0x24200 - 0x251ff: reserved
0x25200 - 0x252ff: gt
0x25300 - 0x25fff: reserved */
GEN_FW_RANGE(0x26000, 0x2ffff, FORCEWAKE_RENDER), /*
0x26000 - 0x27fff: render
0x28000 - 0x2ffff: reserved */
GEN_FW_RANGE(0x30000, 0x3ffff, FORCEWAKE_GT),
GEN_FW_RANGE(0x40000, 0x1bffff, 0),
GEN_FW_RANGE(0x1c0000, 0x1c3fff, FORCEWAKE_MEDIA_VDBOX0), /*
0x1c0000 - 0x1c2bff: VD0
0x1c2c00 - 0x1c2cff: reserved
0x1c2d00 - 0x1c2dff: VD0
0x1c2e00 - 0x1c3eff: reserved
0x1c3f00 - 0x1c3fff: VD0 */
GEN_FW_RANGE(0x1c4000, 0x1cffff, FORCEWAKE_MEDIA_VDBOX1), /*
0x1c4000 - 0x1c6aff: VD1
0x1c6b00 - 0x1c7eff: reserved
0x1c7f00 - 0x1c7fff: VD1
0x1c8000 - 0x1cffff: reserved */
GEN_FW_RANGE(0x1d0000, 0x23ffff, FORCEWAKE_MEDIA_VDBOX2), /*
0x1d0000 - 0x1d2aff: VD2
0x1d2b00 - 0x1d3eff: reserved
0x1d3f00 - 0x1d3fff: VD2
0x1d4000 - 0x23ffff: reserved */
GEN_FW_RANGE(0x240000, 0x3dffff, 0),
GEN_FW_RANGE(0x3e0000, 0x3effff, FORCEWAKE_GT),
};
static const struct intel_forcewake_range __mtl_fw_ranges[] = {
GEN_FW_RANGE(0x0, 0xaff, 0),
GEN_FW_RANGE(0xb00, 0xbff, FORCEWAKE_GT),
GEN_FW_RANGE(0xc00, 0xfff, 0),
GEN_FW_RANGE(0x1000, 0x1fff, FORCEWAKE_GT),
GEN_FW_RANGE(0x2000, 0x26ff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x2700, 0x2fff, FORCEWAKE_GT),
GEN_FW_RANGE(0x3000, 0x3fff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x4000, 0x51ff, FORCEWAKE_GT), /*
0x4000 - 0x48ff: render
0x4900 - 0x51ff: reserved */
GEN_FW_RANGE(0x5200, 0x7fff, FORCEWAKE_RENDER), /*
0x5200 - 0x53ff: render
0x5400 - 0x54ff: reserved
0x5500 - 0x7fff: render */
GEN_FW_RANGE(0x8000, 0x813f, FORCEWAKE_GT),
GEN_FW_RANGE(0x8140, 0x817f, FORCEWAKE_RENDER), /*
0x8140 - 0x815f: render
0x8160 - 0x817f: reserved */
GEN_FW_RANGE(0x8180, 0x81ff, 0),
GEN_FW_RANGE(0x8200, 0x94cf, FORCEWAKE_GT), /*
0x8200 - 0x87ff: gt
0x8800 - 0x8dff: reserved
0x8e00 - 0x8f7f: gt
0x8f80 - 0x8fff: reserved
0x9000 - 0x947f: gt
0x9480 - 0x94cf: reserved */
GEN_FW_RANGE(0x94d0, 0x955f, FORCEWAKE_RENDER),
GEN_FW_RANGE(0x9560, 0x967f, 0), /*
0x9560 - 0x95ff: always on
0x9600 - 0x967f: reserved */
GEN_FW_RANGE(0x9680, 0x97ff, FORCEWAKE_RENDER), /*
0x9680 - 0x96ff: render
0x9700 - 0x97ff: reserved */
GEN_FW_RANGE(0x9800, 0xcfff, FORCEWAKE_GT), /*
0x9800 - 0xb4ff: gt
0xb500 - 0xbfff: reserved
0xc000 - 0xcfff: gt */
GEN_FW_RANGE(0xd000, 0xd7ff, 0), /*
0xd000 - 0xd3ff: always on
0xd400 - 0xd7ff: reserved */
GEN_FW_RANGE(0xd800, 0xd87f, FORCEWAKE_RENDER),
GEN_FW_RANGE(0xd880, 0xdbff, FORCEWAKE_GT),
GEN_FW_RANGE(0xdc00, 0xdcff, FORCEWAKE_RENDER),
GEN_FW_RANGE(0xdd00, 0xde7f, FORCEWAKE_GT), /*
0xdd00 - 0xddff: gt
0xde00 - 0xde7f: reserved */
GEN_FW_RANGE(0xde80, 0xe8ff, FORCEWAKE_RENDER), /*
0xde80 - 0xdfff: render
0xe000 - 0xe0ff: reserved
0xe100 - 0xe8ff: render */
GEN_FW_RANGE(0xe900, 0xe9ff, FORCEWAKE_GT),
GEN_FW_RANGE(0xea00, 0x147ff, 0), /*
0xea00 - 0x11fff: reserved
0x12000 - 0x127ff: always on
0x12800 - 0x147ff: reserved */
GEN_FW_RANGE(0x14800, 0x19fff, FORCEWAKE_GT), /*
0x14800 - 0x153ff: gt
0x15400 - 0x19fff: reserved */
GEN_FW_RANGE(0x1a000, 0x21fff, FORCEWAKE_RENDER), /*
0x1a000 - 0x1bfff: render
0x1c000 - 0x21fff: reserved */
GEN_FW_RANGE(0x22000, 0x23fff, FORCEWAKE_GT),
GEN_FW_RANGE(0x24000, 0x2ffff, 0), /*
0x24000 - 0x2407f: always on
0x24080 - 0x2ffff: reserved */
GEN_FW_RANGE(0x30000, 0x3ffff, FORCEWAKE_GT)
};
/*
* Note that the register ranges here are the final offsets after
* translation of the GSI block to the 0x380000 offset.
*
* NOTE: There are a couple MCR ranges near the bottom of this table
* that need to power up either VD0 or VD2 depending on which replicated
* instance of the register we're trying to access. Our forcewake logic
* at the moment doesn't have a good way to take steering into consideration,
* and the driver doesn't even access any registers in those ranges today,
* so for now we just mark those ranges as FORCEWAKE_ALL. That will ensure
* proper operation if we do start using the ranges in the future, and we
* can determine at that time whether it's worth adding extra complexity to
* the forcewake handling to take steering into consideration.
*/
static const struct intel_forcewake_range __xelpmp_fw_ranges[] = {
GEN_FW_RANGE(0x0, 0x115fff, 0), /* render GT range */
GEN_FW_RANGE(0x116000, 0x11ffff, FORCEWAKE_GSC), /*
0x116000 - 0x117fff: gsc
0x118000 - 0x119fff: reserved
0x11a000 - 0x11efff: gsc
0x11f000 - 0x11ffff: reserved */
GEN_FW_RANGE(0x120000, 0x1bffff, 0), /* non-GT range */
GEN_FW_RANGE(0x1c0000, 0x1c7fff, FORCEWAKE_MEDIA_VDBOX0), /*
0x1c0000 - 0x1c3dff: VD0
0x1c3e00 - 0x1c3eff: reserved
0x1c3f00 - 0x1c3fff: VD0
0x1c4000 - 0x1c7fff: reserved */
GEN_FW_RANGE(0x1c8000, 0x1cbfff, FORCEWAKE_MEDIA_VEBOX0), /*
0x1c8000 - 0x1ca0ff: VE0
0x1ca100 - 0x1cbfff: reserved */
GEN_FW_RANGE(0x1cc000, 0x1cffff, FORCEWAKE_MEDIA_VDBOX0), /*
0x1cc000 - 0x1cdfff: VD0
0x1ce000 - 0x1cffff: reserved */
GEN_FW_RANGE(0x1d0000, 0x1d7fff, FORCEWAKE_MEDIA_VDBOX2), /*
0x1d0000 - 0x1d3dff: VD2
0x1d3e00 - 0x1d3eff: reserved
0x1d4000 - 0x1d7fff: VD2 */
GEN_FW_RANGE(0x1d8000, 0x1da0ff, FORCEWAKE_MEDIA_VEBOX1),
GEN_FW_RANGE(0x1da100, 0x380aff, 0), /*
0x1da100 - 0x23ffff: reserved
0x240000 - 0x37ffff: non-GT range
0x380000 - 0x380aff: reserved */
GEN_FW_RANGE(0x380b00, 0x380bff, FORCEWAKE_GT),
GEN_FW_RANGE(0x380c00, 0x380fff, 0),
GEN_FW_RANGE(0x381000, 0x38817f, FORCEWAKE_GT), /*
0x381000 - 0x381fff: gt
0x382000 - 0x383fff: reserved
0x384000 - 0x384aff: gt
0x384b00 - 0x3851ff: reserved
0x385200 - 0x3871ff: gt
0x387200 - 0x387fff: reserved
0x388000 - 0x38813f: gt
0x388140 - 0x38817f: reserved */
GEN_FW_RANGE(0x388180, 0x3882ff, 0), /*
0x388180 - 0x3881ff: always on
0x388200 - 0x3882ff: reserved */
GEN_FW_RANGE(0x388300, 0x38955f, FORCEWAKE_GT), /*
0x388300 - 0x38887f: gt
0x388880 - 0x388fff: reserved
0x389000 - 0x38947f: gt
0x389480 - 0x38955f: reserved */
GEN_FW_RANGE(0x389560, 0x389fff, 0), /*
0x389560 - 0x3895ff: always on
0x389600 - 0x389fff: reserved */
GEN_FW_RANGE(0x38a000, 0x38cfff, FORCEWAKE_GT), /*
0x38a000 - 0x38afff: gt
0x38b000 - 0x38bfff: reserved
0x38c000 - 0x38cfff: gt */
GEN_FW_RANGE(0x38d000, 0x38d11f, 0),
GEN_FW_RANGE(0x38d120, 0x391fff, FORCEWAKE_GT), /*
0x38d120 - 0x38dfff: gt
0x38e000 - 0x38efff: reserved
0x38f000 - 0x38ffff: gt
0x389000 - 0x391fff: reserved */
GEN_FW_RANGE(0x392000, 0x392fff, 0), /*
0x392000 - 0x3927ff: always on
0x392800 - 0x292fff: reserved */
GEN_FW_RANGE(0x393000, 0x3931ff, FORCEWAKE_GT),
GEN_FW_RANGE(0x393200, 0x39323f, FORCEWAKE_ALL), /* instance-based, see note above */
GEN_FW_RANGE(0x393240, 0x3933ff, FORCEWAKE_GT),
GEN_FW_RANGE(0x393400, 0x3934ff, FORCEWAKE_ALL), /* instance-based, see note above */
GEN_FW_RANGE(0x393500, 0x393c7f, 0), /*
0x393500 - 0x393bff: reserved
0x393c00 - 0x393c7f: always on */
GEN_FW_RANGE(0x393c80, 0x393dff, FORCEWAKE_GT),
};
static void
ilk_dummy_write(struct intel_uncore *uncore)
{
/* WaIssueDummyWriteToWakeupFromRC6:ilk Issue a dummy write to wake up
* the chip from rc6 before touching it for real. MI_MODE is masked,
* hence harmless to write 0 into. */
__raw_uncore_write32(uncore, RING_MI_MODE(RENDER_RING_BASE), 0);
}
static void
__unclaimed_reg_debug(struct intel_uncore *uncore,
const i915_reg_t reg,
const bool read)
{
if (drm_WARN(&uncore->i915->drm,
check_for_unclaimed_mmio(uncore),
"Unclaimed %s register 0x%x\n",
read ? "read from" : "write to",
i915_mmio_reg_offset(reg)))
/* Only report the first N failures */
uncore->i915->params.mmio_debug--;
}
static void
__unclaimed_previous_reg_debug(struct intel_uncore *uncore,
const i915_reg_t reg,
const bool read)
{
if (check_for_unclaimed_mmio(uncore))
drm_dbg(&uncore->i915->drm,
"Unclaimed access detected before %s register 0x%x\n",
read ? "read from" : "write to",
i915_mmio_reg_offset(reg));
}
static inline bool __must_check
unclaimed_reg_debug_header(struct intel_uncore *uncore,
const i915_reg_t reg, const bool read)
{
if (likely(!uncore->i915->params.mmio_debug) || !uncore->debug)
return false;
/* interrupts are disabled and re-enabled around uncore->lock usage */
lockdep_assert_held(&uncore->lock);
spin_lock(&uncore->debug->lock);
__unclaimed_previous_reg_debug(uncore, reg, read);
return true;
}
static inline void
unclaimed_reg_debug_footer(struct intel_uncore *uncore,
const i915_reg_t reg, const bool read)
{
/* interrupts are disabled and re-enabled around uncore->lock usage */
lockdep_assert_held(&uncore->lock);
__unclaimed_reg_debug(uncore, reg, read);
spin_unlock(&uncore->debug->lock);
}
#define __vgpu_read(x) \
static u##x \
vgpu_read##x(struct intel_uncore *uncore, i915_reg_t reg, bool trace) { \
u##x val = __raw_uncore_read##x(uncore, reg); \
trace_i915_reg_rw(false, reg, val, sizeof(val), trace); \
return val; \
}
__vgpu_read(8)
__vgpu_read(16)
__vgpu_read(32)
__vgpu_read(64)
#define GEN2_READ_HEADER(x) \
u##x val = 0; \
assert_rpm_wakelock_held(uncore->rpm);
#define GEN2_READ_FOOTER \
trace_i915_reg_rw(false, reg, val, sizeof(val), trace); \
return val
#define __gen2_read(x) \
static u##x \
gen2_read##x(struct intel_uncore *uncore, i915_reg_t reg, bool trace) { \
GEN2_READ_HEADER(x); \
val = __raw_uncore_read##x(uncore, reg); \
GEN2_READ_FOOTER; \
}
#define __gen5_read(x) \
static u##x \
gen5_read##x(struct intel_uncore *uncore, i915_reg_t reg, bool trace) { \
GEN2_READ_HEADER(x); \
ilk_dummy_write(uncore); \
val = __raw_uncore_read##x(uncore, reg); \
GEN2_READ_FOOTER; \
}
__gen5_read(8)
__gen5_read(16)
__gen5_read(32)
__gen5_read(64)
__gen2_read(8)
__gen2_read(16)
__gen2_read(32)
__gen2_read(64)
#undef __gen5_read
#undef __gen2_read
#undef GEN2_READ_FOOTER
#undef GEN2_READ_HEADER
#define GEN6_READ_HEADER(x) \
u32 offset = i915_mmio_reg_offset(reg); \
unsigned long irqflags; \
bool unclaimed_reg_debug; \
u##x val = 0; \
assert_rpm_wakelock_held(uncore->rpm); \
spin_lock_irqsave(&uncore->lock, irqflags); \
unclaimed_reg_debug = unclaimed_reg_debug_header(uncore, reg, true)
#define GEN6_READ_FOOTER \
if (unclaimed_reg_debug) \
unclaimed_reg_debug_footer(uncore, reg, true); \
spin_unlock_irqrestore(&uncore->lock, irqflags); \
trace_i915_reg_rw(false, reg, val, sizeof(val), trace); \
return val
static noinline void ___force_wake_auto(struct intel_uncore *uncore,
enum forcewake_domains fw_domains)
{
struct intel_uncore_forcewake_domain *domain;
unsigned int tmp;
GEM_BUG_ON(fw_domains & ~uncore->fw_domains);
for_each_fw_domain_masked(domain, fw_domains, uncore, tmp)
fw_domain_arm_timer(domain);
fw_domains_get(uncore, fw_domains);
}
static inline void __force_wake_auto(struct intel_uncore *uncore,
enum forcewake_domains fw_domains)
{
GEM_BUG_ON(!fw_domains);
/* Turn on all requested but inactive supported forcewake domains. */
fw_domains &= uncore->fw_domains;
fw_domains &= ~uncore->fw_domains_active;
if (fw_domains)
___force_wake_auto(uncore, fw_domains);
}
#define __gen_fwtable_read(x) \
static u##x \
fwtable_read##x(struct intel_uncore *uncore, i915_reg_t reg, bool trace) \
{ \
enum forcewake_domains fw_engine; \
GEN6_READ_HEADER(x); \
fw_engine = __fwtable_reg_read_fw_domains(uncore, offset); \
if (fw_engine) \
__force_wake_auto(uncore, fw_engine); \
val = __raw_uncore_read##x(uncore, reg); \
GEN6_READ_FOOTER; \
}
static enum forcewake_domains
fwtable_reg_read_fw_domains(struct intel_uncore *uncore, i915_reg_t reg) {
return __fwtable_reg_read_fw_domains(uncore, i915_mmio_reg_offset(reg));
}
__gen_fwtable_read(8)
__gen_fwtable_read(16)
__gen_fwtable_read(32)
__gen_fwtable_read(64)
#undef __gen_fwtable_read
#undef GEN6_READ_FOOTER
#undef GEN6_READ_HEADER
#define GEN2_WRITE_HEADER \
trace_i915_reg_rw(true, reg, val, sizeof(val), trace); \
assert_rpm_wakelock_held(uncore->rpm); \
#define GEN2_WRITE_FOOTER
#define __gen2_write(x) \
static void \
gen2_write##x(struct intel_uncore *uncore, i915_reg_t reg, u##x val, bool trace) { \
GEN2_WRITE_HEADER; \
__raw_uncore_write##x(uncore, reg, val); \
GEN2_WRITE_FOOTER; \
}
#define __gen5_write(x) \
static void \
gen5_write##x(struct intel_uncore *uncore, i915_reg_t reg, u##x val, bool trace) { \
GEN2_WRITE_HEADER; \
ilk_dummy_write(uncore); \
__raw_uncore_write##x(uncore, reg, val); \
GEN2_WRITE_FOOTER; \
}
__gen5_write(8)
__gen5_write(16)
__gen5_write(32)
__gen2_write(8)
__gen2_write(16)
__gen2_write(32)
#undef __gen5_write
#undef __gen2_write
#undef GEN2_WRITE_FOOTER
#undef GEN2_WRITE_HEADER
#define GEN6_WRITE_HEADER \
u32 offset = i915_mmio_reg_offset(reg); \
unsigned long irqflags; \
bool unclaimed_reg_debug; \
trace_i915_reg_rw(true, reg, val, sizeof(val), trace); \
assert_rpm_wakelock_held(uncore->rpm); \
spin_lock_irqsave(&uncore->lock, irqflags); \
unclaimed_reg_debug = unclaimed_reg_debug_header(uncore, reg, false)
#define GEN6_WRITE_FOOTER \
if (unclaimed_reg_debug) \
unclaimed_reg_debug_footer(uncore, reg, false); \
spin_unlock_irqrestore(&uncore->lock, irqflags)
#define __gen6_write(x) \
static void \
gen6_write##x(struct intel_uncore *uncore, i915_reg_t reg, u##x val, bool trace) { \
GEN6_WRITE_HEADER; \
if (NEEDS_FORCE_WAKE(offset)) \
__gen6_gt_wait_for_fifo(uncore); \
__raw_uncore_write##x(uncore, reg, val); \
GEN6_WRITE_FOOTER; \
}
__gen6_write(8)
__gen6_write(16)
__gen6_write(32)
#define __gen_fwtable_write(x) \
static void \
fwtable_write##x(struct intel_uncore *uncore, i915_reg_t reg, u##x val, bool trace) { \
enum forcewake_domains fw_engine; \
GEN6_WRITE_HEADER; \
fw_engine = __fwtable_reg_write_fw_domains(uncore, offset); \
if (fw_engine) \
__force_wake_auto(uncore, fw_engine); \
__raw_uncore_write##x(uncore, reg, val); \
GEN6_WRITE_FOOTER; \
}
static enum forcewake_domains
fwtable_reg_write_fw_domains(struct intel_uncore *uncore, i915_reg_t reg)
{
return __fwtable_reg_write_fw_domains(uncore, i915_mmio_reg_offset(reg));
}
__gen_fwtable_write(8)
__gen_fwtable_write(16)
__gen_fwtable_write(32)
#undef __gen_fwtable_write
#undef GEN6_WRITE_FOOTER
#undef GEN6_WRITE_HEADER
#define __vgpu_write(x) \
static void \
vgpu_write##x(struct intel_uncore *uncore, i915_reg_t reg, u##x val, bool trace) { \
trace_i915_reg_rw(true, reg, val, sizeof(val), trace); \
__raw_uncore_write##x(uncore, reg, val); \
}
__vgpu_write(8)
__vgpu_write(16)
__vgpu_write(32)
#define ASSIGN_RAW_WRITE_MMIO_VFUNCS(uncore, x) \
do { \
(uncore)->funcs.mmio_writeb = x##_write8; \
(uncore)->funcs.mmio_writew = x##_write16; \
(uncore)->funcs.mmio_writel = x##_write32; \
} while (0)
#define ASSIGN_RAW_READ_MMIO_VFUNCS(uncore, x) \
do { \
(uncore)->funcs.mmio_readb = x##_read8; \
(uncore)->funcs.mmio_readw = x##_read16; \
(uncore)->funcs.mmio_readl = x##_read32; \
(uncore)->funcs.mmio_readq = x##_read64; \
} while (0)
#define ASSIGN_WRITE_MMIO_VFUNCS(uncore, x) \
do { \
ASSIGN_RAW_WRITE_MMIO_VFUNCS((uncore), x); \
(uncore)->funcs.write_fw_domains = x##_reg_write_fw_domains; \
} while (0)
#define ASSIGN_READ_MMIO_VFUNCS(uncore, x) \
do { \
ASSIGN_RAW_READ_MMIO_VFUNCS(uncore, x); \
(uncore)->funcs.read_fw_domains = x##_reg_read_fw_domains; \
} while (0)
static int __fw_domain_init(struct intel_uncore *uncore,
enum forcewake_domain_id domain_id,
i915_reg_t reg_set,
i915_reg_t reg_ack)
{
struct intel_uncore_forcewake_domain *d;
GEM_BUG_ON(domain_id >= FW_DOMAIN_ID_COUNT);
GEM_BUG_ON(uncore->fw_domain[domain_id]);
if (i915_inject_probe_failure(uncore->i915))
return -ENOMEM;
d = kzalloc(sizeof(*d), GFP_KERNEL);
if (!d)
return -ENOMEM;
drm_WARN_ON(&uncore->i915->drm, !i915_mmio_reg_valid(reg_set));
drm_WARN_ON(&uncore->i915->drm, !i915_mmio_reg_valid(reg_ack));
d->uncore = uncore;
d->wake_count = 0;
d->reg_set = uncore->regs + i915_mmio_reg_offset(reg_set) + uncore->gsi_offset;
d->reg_ack = uncore->regs + i915_mmio_reg_offset(reg_ack) + uncore->gsi_offset;
d->id = domain_id;
BUILD_BUG_ON(FORCEWAKE_RENDER != (1 << FW_DOMAIN_ID_RENDER));
BUILD_BUG_ON(FORCEWAKE_GT != (1 << FW_DOMAIN_ID_GT));
BUILD_BUG_ON(FORCEWAKE_MEDIA != (1 << FW_DOMAIN_ID_MEDIA));
BUILD_BUG_ON(FORCEWAKE_MEDIA_VDBOX0 != (1 << FW_DOMAIN_ID_MEDIA_VDBOX0));
BUILD_BUG_ON(FORCEWAKE_MEDIA_VDBOX1 != (1 << FW_DOMAIN_ID_MEDIA_VDBOX1));
BUILD_BUG_ON(FORCEWAKE_MEDIA_VDBOX2 != (1 << FW_DOMAIN_ID_MEDIA_VDBOX2));
BUILD_BUG_ON(FORCEWAKE_MEDIA_VDBOX3 != (1 << FW_DOMAIN_ID_MEDIA_VDBOX3));
BUILD_BUG_ON(FORCEWAKE_MEDIA_VDBOX4 != (1 << FW_DOMAIN_ID_MEDIA_VDBOX4));
BUILD_BUG_ON(FORCEWAKE_MEDIA_VDBOX5 != (1 << FW_DOMAIN_ID_MEDIA_VDBOX5));
BUILD_BUG_ON(FORCEWAKE_MEDIA_VDBOX6 != (1 << FW_DOMAIN_ID_MEDIA_VDBOX6));
BUILD_BUG_ON(FORCEWAKE_MEDIA_VDBOX7 != (1 << FW_DOMAIN_ID_MEDIA_VDBOX7));
BUILD_BUG_ON(FORCEWAKE_MEDIA_VEBOX0 != (1 << FW_DOMAIN_ID_MEDIA_VEBOX0));
BUILD_BUG_ON(FORCEWAKE_MEDIA_VEBOX1 != (1 << FW_DOMAIN_ID_MEDIA_VEBOX1));
BUILD_BUG_ON(FORCEWAKE_MEDIA_VEBOX2 != (1 << FW_DOMAIN_ID_MEDIA_VEBOX2));
BUILD_BUG_ON(FORCEWAKE_MEDIA_VEBOX3 != (1 << FW_DOMAIN_ID_MEDIA_VEBOX3));
BUILD_BUG_ON(FORCEWAKE_GSC != (1 << FW_DOMAIN_ID_GSC));
d->mask = BIT(domain_id);
hrtimer_init(&d->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
d->timer.function = intel_uncore_fw_release_timer;
uncore->fw_domains |= BIT(domain_id);
fw_domain_reset(d);
uncore->fw_domain[domain_id] = d;
return 0;
}
static void fw_domain_fini(struct intel_uncore *uncore,
enum forcewake_domain_id domain_id)
{
struct intel_uncore_forcewake_domain *d;
GEM_BUG_ON(domain_id >= FW_DOMAIN_ID_COUNT);
d = fetch_and_zero(&uncore->fw_domain[domain_id]);
if (!d)
return;
uncore->fw_domains &= ~BIT(domain_id);
drm_WARN_ON(&uncore->i915->drm, d->wake_count);
drm_WARN_ON(&uncore->i915->drm, hrtimer_cancel(&d->timer));
kfree(d);
}
static void intel_uncore_fw_domains_fini(struct intel_uncore *uncore)
{
struct intel_uncore_forcewake_domain *d;
int tmp;
for_each_fw_domain(d, uncore, tmp)
fw_domain_fini(uncore, d->id);
}
static const struct intel_uncore_fw_get uncore_get_fallback = {
.force_wake_get = fw_domains_get_with_fallback
};
static const struct intel_uncore_fw_get uncore_get_normal = {
.force_wake_get = fw_domains_get_normal,
};
static const struct intel_uncore_fw_get uncore_get_thread_status = {
.force_wake_get = fw_domains_get_with_thread_status
};
static int intel_uncore_fw_domains_init(struct intel_uncore *uncore)
{
struct drm_i915_private *i915 = uncore->i915;
int ret = 0;
GEM_BUG_ON(!intel_uncore_has_forcewake(uncore));
#define fw_domain_init(uncore__, id__, set__, ack__) \
(ret ?: (ret = __fw_domain_init((uncore__), (id__), (set__), (ack__))))
if (GRAPHICS_VER(i915) >= 11) {
intel_engine_mask_t emask;
int i;
/* we'll prune the domains of missing engines later */
emask = uncore->gt->info.engine_mask;
uncore->fw_get_funcs = &uncore_get_fallback;
if (GRAPHICS_VER_FULL(i915) >= IP_VER(12, 70))
fw_domain_init(uncore, FW_DOMAIN_ID_GT,
FORCEWAKE_GT_GEN9,
FORCEWAKE_ACK_GT_MTL);
else
fw_domain_init(uncore, FW_DOMAIN_ID_GT,
FORCEWAKE_GT_GEN9,
FORCEWAKE_ACK_GT_GEN9);
if (RCS_MASK(uncore->gt) || CCS_MASK(uncore->gt))
fw_domain_init(uncore, FW_DOMAIN_ID_RENDER,
FORCEWAKE_RENDER_GEN9,
FORCEWAKE_ACK_RENDER_GEN9);
for (i = 0; i < I915_MAX_VCS; i++) {
if (!__HAS_ENGINE(emask, _VCS(i)))
continue;
fw_domain_init(uncore, FW_DOMAIN_ID_MEDIA_VDBOX0 + i,
FORCEWAKE_MEDIA_VDBOX_GEN11(i),
FORCEWAKE_ACK_MEDIA_VDBOX_GEN11(i));
}
for (i = 0; i < I915_MAX_VECS; i++) {
if (!__HAS_ENGINE(emask, _VECS(i)))
continue;
fw_domain_init(uncore, FW_DOMAIN_ID_MEDIA_VEBOX0 + i,
FORCEWAKE_MEDIA_VEBOX_GEN11(i),
FORCEWAKE_ACK_MEDIA_VEBOX_GEN11(i));
}
if (uncore->gt->type == GT_MEDIA)
fw_domain_init(uncore, FW_DOMAIN_ID_GSC,
FORCEWAKE_REQ_GSC, FORCEWAKE_ACK_GSC);
} else if (IS_GRAPHICS_VER(i915, 9, 10)) {
uncore->fw_get_funcs = &uncore_get_fallback;
fw_domain_init(uncore, FW_DOMAIN_ID_RENDER,
FORCEWAKE_RENDER_GEN9,
FORCEWAKE_ACK_RENDER_GEN9);
fw_domain_init(uncore, FW_DOMAIN_ID_GT,
FORCEWAKE_GT_GEN9,
FORCEWAKE_ACK_GT_GEN9);
fw_domain_init(uncore, FW_DOMAIN_ID_MEDIA,
FORCEWAKE_MEDIA_GEN9, FORCEWAKE_ACK_MEDIA_GEN9);
} else if (IS_VALLEYVIEW(i915) || IS_CHERRYVIEW(i915)) {
uncore->fw_get_funcs = &uncore_get_normal;
fw_domain_init(uncore, FW_DOMAIN_ID_RENDER,
FORCEWAKE_VLV, FORCEWAKE_ACK_VLV);
fw_domain_init(uncore, FW_DOMAIN_ID_MEDIA,
FORCEWAKE_MEDIA_VLV, FORCEWAKE_ACK_MEDIA_VLV);
} else if (IS_HASWELL(i915) || IS_BROADWELL(i915)) {
uncore->fw_get_funcs = &uncore_get_thread_status;
fw_domain_init(uncore, FW_DOMAIN_ID_RENDER,
FORCEWAKE_MT, FORCEWAKE_ACK_HSW);
} else if (IS_IVYBRIDGE(i915)) {
u32 ecobus;
/* IVB configs may use multi-threaded forcewake */
/* A small trick here - if the bios hasn't configured
* MT forcewake, and if the device is in RC6, then
* force_wake_mt_get will not wake the device and the
* ECOBUS read will return zero. Which will be
* (correctly) interpreted by the test below as MT
* forcewake being disabled.
*/
uncore->fw_get_funcs = &uncore_get_thread_status;
/* We need to init first for ECOBUS access and then
* determine later if we want to reinit, in case of MT access is
* not working. In this stage we don't know which flavour this
* ivb is, so it is better to reset also the gen6 fw registers
* before the ecobus check.
*/
__raw_uncore_write32(uncore, FORCEWAKE, 0);
__raw_posting_read(uncore, ECOBUS);
ret = __fw_domain_init(uncore, FW_DOMAIN_ID_RENDER,
FORCEWAKE_MT, FORCEWAKE_MT_ACK);
if (ret)
goto out;
spin_lock_irq(&uncore->lock);
fw_domains_get_with_thread_status(uncore, FORCEWAKE_RENDER);
ecobus = __raw_uncore_read32(uncore, ECOBUS);
fw_domains_put(uncore, FORCEWAKE_RENDER);
spin_unlock_irq(&uncore->lock);
if (!(ecobus & FORCEWAKE_MT_ENABLE)) {
drm_info(&i915->drm, "No MT forcewake available on Ivybridge, this can result in issues\n");
drm_info(&i915->drm, "when using vblank-synced partial screen updates.\n");
fw_domain_fini(uncore, FW_DOMAIN_ID_RENDER);
fw_domain_init(uncore, FW_DOMAIN_ID_RENDER,
FORCEWAKE, FORCEWAKE_ACK);
}
} else if (GRAPHICS_VER(i915) == 6) {
uncore->fw_get_funcs = &uncore_get_thread_status;
fw_domain_init(uncore, FW_DOMAIN_ID_RENDER,
FORCEWAKE, FORCEWAKE_ACK);
}
#undef fw_domain_init
/* All future platforms are expected to require complex power gating */
drm_WARN_ON(&i915->drm, !ret && uncore->fw_domains == 0);
out:
if (ret)
intel_uncore_fw_domains_fini(uncore);
return ret;
}
#define ASSIGN_FW_DOMAINS_TABLE(uncore, d) \
{ \
(uncore)->fw_domains_table = \
(struct intel_forcewake_range *)(d); \
(uncore)->fw_domains_table_entries = ARRAY_SIZE((d)); \
}
#define ASSIGN_SHADOW_TABLE(uncore, d) \
{ \
(uncore)->shadowed_reg_table = d; \
(uncore)->shadowed_reg_table_entries = ARRAY_SIZE((d)); \
}
static int i915_pmic_bus_access_notifier(struct notifier_block *nb,
unsigned long action, void *data)
{
struct intel_uncore *uncore = container_of(nb,
struct intel_uncore, pmic_bus_access_nb);
switch (action) {
case MBI_PMIC_BUS_ACCESS_BEGIN:
/*
* forcewake all now to make sure that we don't need to do a
* forcewake later which on systems where this notifier gets
* called requires the punit to access to the shared pmic i2c
* bus, which will be busy after this notification, leading to:
* "render: timed out waiting for forcewake ack request."
* errors.
*
* The notifier is unregistered during intel_runtime_suspend(),
* so it's ok to access the HW here without holding a RPM
* wake reference -> disable wakeref asserts for the time of
* the access.
*/
disable_rpm_wakeref_asserts(uncore->rpm);
intel_uncore_forcewake_get(uncore, FORCEWAKE_ALL);
enable_rpm_wakeref_asserts(uncore->rpm);
break;
case MBI_PMIC_BUS_ACCESS_END:
intel_uncore_forcewake_put(uncore, FORCEWAKE_ALL);
break;
}
return NOTIFY_OK;
}
static void uncore_unmap_mmio(struct drm_device *drm, void *regs)
{
iounmap((void __iomem *)regs);
}
int intel_uncore_setup_mmio(struct intel_uncore *uncore, phys_addr_t phys_addr)
{
struct drm_i915_private *i915 = uncore->i915;
int mmio_size;
/*
* Before gen4, the registers and the GTT are behind different BARs.
* However, from gen4 onwards, the registers and the GTT are shared
* in the same BAR, so we want to restrict this ioremap from
* clobbering the GTT which we want ioremap_wc instead. Fortunately,
* the register BAR remains the same size for all the earlier
* generations up to Ironlake.
* For dgfx chips register range is expanded to 4MB, and this larger
* range is also used for integrated gpus beginning with Meteor Lake.
*/
if (IS_DGFX(i915) || GRAPHICS_VER_FULL(i915) >= IP_VER(12, 70))
mmio_size = 4 * 1024 * 1024;
else if (GRAPHICS_VER(i915) >= 5)
mmio_size = 2 * 1024 * 1024;
else
mmio_size = 512 * 1024;
uncore->regs = ioremap(phys_addr, mmio_size);
if (uncore->regs == NULL) {
drm_err(&i915->drm, "failed to map registers\n");
return -EIO;
}
return drmm_add_action_or_reset(&i915->drm, uncore_unmap_mmio,
(void __force *)uncore->regs);
}
void intel_uncore_init_early(struct intel_uncore *uncore,
struct intel_gt *gt)
{
spin_lock_init(&uncore->lock);
uncore->i915 = gt->i915;
uncore->gt = gt;
uncore->rpm = >->i915->runtime_pm;
}
static void uncore_raw_init(struct intel_uncore *uncore)
{
GEM_BUG_ON(intel_uncore_has_forcewake(uncore));
if (intel_vgpu_active(uncore->i915)) {
ASSIGN_RAW_WRITE_MMIO_VFUNCS(uncore, vgpu);
ASSIGN_RAW_READ_MMIO_VFUNCS(uncore, vgpu);
} else if (GRAPHICS_VER(uncore->i915) == 5) {
ASSIGN_RAW_WRITE_MMIO_VFUNCS(uncore, gen5);
ASSIGN_RAW_READ_MMIO_VFUNCS(uncore, gen5);
} else {
ASSIGN_RAW_WRITE_MMIO_VFUNCS(uncore, gen2);
ASSIGN_RAW_READ_MMIO_VFUNCS(uncore, gen2);
}
}
static int uncore_media_forcewake_init(struct intel_uncore *uncore)
{
struct drm_i915_private *i915 = uncore->i915;
if (MEDIA_VER(i915) >= 13) {
ASSIGN_FW_DOMAINS_TABLE(uncore, __xelpmp_fw_ranges);
ASSIGN_SHADOW_TABLE(uncore, xelpmp_shadowed_regs);
ASSIGN_WRITE_MMIO_VFUNCS(uncore, fwtable);
} else {
MISSING_CASE(MEDIA_VER(i915));
return -ENODEV;
}
return 0;
}
static int uncore_forcewake_init(struct intel_uncore *uncore)
{
struct drm_i915_private *i915 = uncore->i915;
int ret;
GEM_BUG_ON(!intel_uncore_has_forcewake(uncore));
ret = intel_uncore_fw_domains_init(uncore);
if (ret)
return ret;
forcewake_early_sanitize(uncore, 0);
ASSIGN_READ_MMIO_VFUNCS(uncore, fwtable);
if (uncore->gt->type == GT_MEDIA)
return uncore_media_forcewake_init(uncore);
if (GRAPHICS_VER_FULL(i915) >= IP_VER(12, 70)) {
ASSIGN_FW_DOMAINS_TABLE(uncore, __mtl_fw_ranges);
ASSIGN_SHADOW_TABLE(uncore, mtl_shadowed_regs);
ASSIGN_WRITE_MMIO_VFUNCS(uncore, fwtable);
} else if (GRAPHICS_VER_FULL(i915) >= IP_VER(12, 60)) {
ASSIGN_FW_DOMAINS_TABLE(uncore, __pvc_fw_ranges);
ASSIGN_SHADOW_TABLE(uncore, pvc_shadowed_regs);
ASSIGN_WRITE_MMIO_VFUNCS(uncore, fwtable);
} else if (GRAPHICS_VER_FULL(i915) >= IP_VER(12, 55)) {
ASSIGN_FW_DOMAINS_TABLE(uncore, __dg2_fw_ranges);
ASSIGN_SHADOW_TABLE(uncore, dg2_shadowed_regs);
ASSIGN_WRITE_MMIO_VFUNCS(uncore, fwtable);
} else if (GRAPHICS_VER_FULL(i915) >= IP_VER(12, 50)) {
ASSIGN_FW_DOMAINS_TABLE(uncore, __xehp_fw_ranges);
ASSIGN_SHADOW_TABLE(uncore, gen12_shadowed_regs);
ASSIGN_WRITE_MMIO_VFUNCS(uncore, fwtable);
} else if (GRAPHICS_VER(i915) >= 12) {
ASSIGN_FW_DOMAINS_TABLE(uncore, __gen12_fw_ranges);
ASSIGN_SHADOW_TABLE(uncore, gen12_shadowed_regs);
ASSIGN_WRITE_MMIO_VFUNCS(uncore, fwtable);
} else if (GRAPHICS_VER(i915) == 11) {
ASSIGN_FW_DOMAINS_TABLE(uncore, __gen11_fw_ranges);
ASSIGN_SHADOW_TABLE(uncore, gen11_shadowed_regs);
ASSIGN_WRITE_MMIO_VFUNCS(uncore, fwtable);
} else if (IS_GRAPHICS_VER(i915, 9, 10)) {
ASSIGN_FW_DOMAINS_TABLE(uncore, __gen9_fw_ranges);
ASSIGN_SHADOW_TABLE(uncore, gen8_shadowed_regs);
ASSIGN_WRITE_MMIO_VFUNCS(uncore, fwtable);
} else if (IS_CHERRYVIEW(i915)) {
ASSIGN_FW_DOMAINS_TABLE(uncore, __chv_fw_ranges);
ASSIGN_SHADOW_TABLE(uncore, gen8_shadowed_regs);
ASSIGN_WRITE_MMIO_VFUNCS(uncore, fwtable);
} else if (GRAPHICS_VER(i915) == 8) {
ASSIGN_FW_DOMAINS_TABLE(uncore, __gen6_fw_ranges);
ASSIGN_SHADOW_TABLE(uncore, gen8_shadowed_regs);
ASSIGN_WRITE_MMIO_VFUNCS(uncore, fwtable);
} else if (IS_VALLEYVIEW(i915)) {
ASSIGN_FW_DOMAINS_TABLE(uncore, __vlv_fw_ranges);
ASSIGN_WRITE_MMIO_VFUNCS(uncore, gen6);
} else if (IS_GRAPHICS_VER(i915, 6, 7)) {
ASSIGN_FW_DOMAINS_TABLE(uncore, __gen6_fw_ranges);
ASSIGN_WRITE_MMIO_VFUNCS(uncore, gen6);
}
uncore->pmic_bus_access_nb.notifier_call = i915_pmic_bus_access_notifier;
iosf_mbi_register_pmic_bus_access_notifier(&uncore->pmic_bus_access_nb);
return 0;
}
static int sanity_check_mmio_access(struct intel_uncore *uncore)
{
struct drm_i915_private *i915 = uncore->i915;
if (GRAPHICS_VER(i915) < 8)
return 0;
/*
* Sanitycheck that MMIO access to the device is working properly. If
* the CPU is unable to communcate with a PCI device, BAR reads will
* return 0xFFFFFFFF. Let's make sure the device isn't in this state
* before we start trying to access registers.
*
* We use the primary GT's forcewake register as our guinea pig since
* it's been around since HSW and it's a masked register so the upper
* 16 bits can never read back as 1's if device access is operating
* properly.
*
* If MMIO isn't working, we'll wait up to 2 seconds to see if it
* recovers, then give up.
*/
#define COND (__raw_uncore_read32(uncore, FORCEWAKE_MT) != ~0)
if (wait_for(COND, 2000) == -ETIMEDOUT) {
drm_err(&i915->drm, "Device is non-operational; MMIO access returns 0xFFFFFFFF!\n");
return -EIO;
}
return 0;
}
int intel_uncore_init_mmio(struct intel_uncore *uncore)
{
struct drm_i915_private *i915 = uncore->i915;
int ret;
ret = sanity_check_mmio_access(uncore);
if (ret)
return ret;
/*
* The boot firmware initializes local memory and assesses its health.
* If memory training fails, the punit will have been instructed to
* keep the GT powered down; we won't be able to communicate with it
* and we should not continue with driver initialization.
*/
if (IS_DGFX(i915) &&
!(__raw_uncore_read32(uncore, GU_CNTL) & LMEM_INIT)) {
drm_err(&i915->drm, "LMEM not initialized by firmware\n");
return -ENODEV;
}
if (GRAPHICS_VER(i915) > 5 && !intel_vgpu_active(i915))
uncore->flags |= UNCORE_HAS_FORCEWAKE;
if (!intel_uncore_has_forcewake(uncore)) {
uncore_raw_init(uncore);
} else {
ret = uncore_forcewake_init(uncore);
if (ret)
return ret;
}
/* make sure fw funcs are set if and only if we have fw*/
GEM_BUG_ON(intel_uncore_has_forcewake(uncore) != !!uncore->fw_get_funcs);
GEM_BUG_ON(intel_uncore_has_forcewake(uncore) != !!uncore->funcs.read_fw_domains);
GEM_BUG_ON(intel_uncore_has_forcewake(uncore) != !!uncore->funcs.write_fw_domains);
if (HAS_FPGA_DBG_UNCLAIMED(i915))
uncore->flags |= UNCORE_HAS_FPGA_DBG_UNCLAIMED;
if (IS_VALLEYVIEW(i915) || IS_CHERRYVIEW(i915))
uncore->flags |= UNCORE_HAS_DBG_UNCLAIMED;
if (IS_GRAPHICS_VER(i915, 6, 7))
uncore->flags |= UNCORE_HAS_FIFO;
/* clear out unclaimed reg detection bit */
if (intel_uncore_unclaimed_mmio(uncore))
drm_dbg(&i915->drm, "unclaimed mmio detected on uncore init, clearing\n");
return 0;
}
/*
* We might have detected that some engines are fused off after we initialized
* the forcewake domains. Prune them, to make sure they only reference existing
* engines.
*/
void intel_uncore_prune_engine_fw_domains(struct intel_uncore *uncore,
struct intel_gt *gt)
{
enum forcewake_domains fw_domains = uncore->fw_domains;
enum forcewake_domain_id domain_id;
int i;
if (!intel_uncore_has_forcewake(uncore) || GRAPHICS_VER(uncore->i915) < 11)
return;
for (i = 0; i < I915_MAX_VCS; i++) {
domain_id = FW_DOMAIN_ID_MEDIA_VDBOX0 + i;
if (HAS_ENGINE(gt, _VCS(i)))
continue;
/*
* Starting with XeHP, the power well for an even-numbered
* VDBOX is also used for shared units within the
* media slice such as SFC. So even if the engine
* itself is fused off, we still need to initialize
* the forcewake domain if any of the other engines
* in the same media slice are present.
*/
if (GRAPHICS_VER_FULL(uncore->i915) >= IP_VER(12, 50) && i % 2 == 0) {
if ((i + 1 < I915_MAX_VCS) && HAS_ENGINE(gt, _VCS(i + 1)))
continue;
if (HAS_ENGINE(gt, _VECS(i / 2)))
continue;
}
if (fw_domains & BIT(domain_id))
fw_domain_fini(uncore, domain_id);
}
for (i = 0; i < I915_MAX_VECS; i++) {
domain_id = FW_DOMAIN_ID_MEDIA_VEBOX0 + i;
if (HAS_ENGINE(gt, _VECS(i)))
continue;
if (fw_domains & BIT(domain_id))
fw_domain_fini(uncore, domain_id);
}
if ((fw_domains & BIT(FW_DOMAIN_ID_GSC)) && !HAS_ENGINE(gt, GSC0))
fw_domain_fini(uncore, FW_DOMAIN_ID_GSC);
}
/*
* The driver-initiated FLR is the highest level of reset that we can trigger
* from within the driver. It is different from the PCI FLR in that it doesn't
* fully reset the SGUnit and doesn't modify the PCI config space and therefore
* it doesn't require a re-enumeration of the PCI BARs. However, the
* driver-initiated FLR does still cause a reset of both GT and display and a
* memory wipe of local and stolen memory, so recovery would require a full HW
* re-init and saving/restoring (or re-populating) the wiped memory. Since we
* perform the FLR as the very last action before releasing access to the HW
* during the driver release flow, we don't attempt recovery at all, because
* if/when a new instance of i915 is bound to the device it will do a full
* re-init anyway.
*/
static void driver_initiated_flr(struct intel_uncore *uncore)
{
struct drm_i915_private *i915 = uncore->i915;
const unsigned int flr_timeout_ms = 3000; /* specs recommend a 3s wait */
int ret;
drm_dbg(&i915->drm, "Triggering Driver-FLR\n");
/*
* Make sure any pending FLR requests have cleared by waiting for the
* FLR trigger bit to go to zero. Also clear GU_DEBUG's DRIVERFLR_STATUS
* to make sure it's not still set from a prior attempt (it's a write to
* clear bit).
* Note that we should never be in a situation where a previous attempt
* is still pending (unless the HW is totally dead), but better to be
* safe in case something unexpected happens
*/
ret = intel_wait_for_register_fw(uncore, GU_CNTL, DRIVERFLR, 0, flr_timeout_ms);
if (ret) {
drm_err(&i915->drm,
"Failed to wait for Driver-FLR bit to clear! %d\n",
ret);
return;
}
intel_uncore_write_fw(uncore, GU_DEBUG, DRIVERFLR_STATUS);
/* Trigger the actual Driver-FLR */
intel_uncore_rmw_fw(uncore, GU_CNTL, 0, DRIVERFLR);
/* Wait for hardware teardown to complete */
ret = intel_wait_for_register_fw(uncore, GU_CNTL,
DRIVERFLR, 0,
flr_timeout_ms);
if (ret) {
drm_err(&i915->drm, "Driver-FLR-teardown wait completion failed! %d\n", ret);
return;
}
/* Wait for hardware/firmware re-init to complete */
ret = intel_wait_for_register_fw(uncore, GU_DEBUG,
DRIVERFLR_STATUS, DRIVERFLR_STATUS,
flr_timeout_ms);
if (ret) {
drm_err(&i915->drm, "Driver-FLR-reinit wait completion failed! %d\n", ret);
return;
}
/* Clear sticky completion status */
intel_uncore_write_fw(uncore, GU_DEBUG, DRIVERFLR_STATUS);
}
/* Called via drm-managed action */
void intel_uncore_fini_mmio(struct drm_device *dev, void *data)
{
struct intel_uncore *uncore = data;
if (intel_uncore_has_forcewake(uncore)) {
iosf_mbi_punit_acquire();
iosf_mbi_unregister_pmic_bus_access_notifier_unlocked(
&uncore->pmic_bus_access_nb);
intel_uncore_forcewake_reset(uncore);
intel_uncore_fw_domains_fini(uncore);
iosf_mbi_punit_release();
}
if (intel_uncore_needs_flr_on_fini(uncore))
driver_initiated_flr(uncore);
}
/**
* __intel_wait_for_register_fw - wait until register matches expected state
* @uncore: the struct intel_uncore
* @reg: the register to read
* @mask: mask to apply to register value
* @value: expected value
* @fast_timeout_us: fast timeout in microsecond for atomic/tight wait
* @slow_timeout_ms: slow timeout in millisecond
* @out_value: optional placeholder to hold registry value
*
* This routine waits until the target register @reg contains the expected
* @value after applying the @mask, i.e. it waits until ::
*
* (intel_uncore_read_fw(uncore, reg) & mask) == value
*
* Otherwise, the wait will timeout after @slow_timeout_ms milliseconds.
* For atomic context @slow_timeout_ms must be zero and @fast_timeout_us
* must be not larger than 20,0000 microseconds.
*
* Note that this routine assumes the caller holds forcewake asserted, it is
* not suitable for very long waits. See intel_wait_for_register() if you
* wish to wait without holding forcewake for the duration (i.e. you expect
* the wait to be slow).
*
* Return: 0 if the register matches the desired condition, or -ETIMEDOUT.
*/
int __intel_wait_for_register_fw(struct intel_uncore *uncore,
i915_reg_t reg,
u32 mask,
u32 value,
unsigned int fast_timeout_us,
unsigned int slow_timeout_ms,
u32 *out_value)
{
u32 reg_value = 0;
#define done (((reg_value = intel_uncore_read_fw(uncore, reg)) & mask) == value)
int ret;
/* Catch any overuse of this function */
might_sleep_if(slow_timeout_ms);
GEM_BUG_ON(fast_timeout_us > 20000);
GEM_BUG_ON(!fast_timeout_us && !slow_timeout_ms);
ret = -ETIMEDOUT;
if (fast_timeout_us && fast_timeout_us <= 20000)
ret = _wait_for_atomic(done, fast_timeout_us, 0);
if (ret && slow_timeout_ms)
ret = wait_for(done, slow_timeout_ms);
if (out_value)
*out_value = reg_value;
return ret;
#undef done
}
/**
* __intel_wait_for_register - wait until register matches expected state
* @uncore: the struct intel_uncore
* @reg: the register to read
* @mask: mask to apply to register value
* @value: expected value
* @fast_timeout_us: fast timeout in microsecond for atomic/tight wait
* @slow_timeout_ms: slow timeout in millisecond
* @out_value: optional placeholder to hold registry value
*
* This routine waits until the target register @reg contains the expected
* @value after applying the @mask, i.e. it waits until ::
*
* (intel_uncore_read(uncore, reg) & mask) == value
*
* Otherwise, the wait will timeout after @timeout_ms milliseconds.
*
* Return: 0 if the register matches the desired condition, or -ETIMEDOUT.
*/
int __intel_wait_for_register(struct intel_uncore *uncore,
i915_reg_t reg,
u32 mask,
u32 value,
unsigned int fast_timeout_us,
unsigned int slow_timeout_ms,
u32 *out_value)
{
unsigned fw =
intel_uncore_forcewake_for_reg(uncore, reg, FW_REG_READ);
u32 reg_value;
int ret;
might_sleep_if(slow_timeout_ms);
spin_lock_irq(&uncore->lock);
intel_uncore_forcewake_get__locked(uncore, fw);
ret = __intel_wait_for_register_fw(uncore,
reg, mask, value,
fast_timeout_us, 0, ®_value);
intel_uncore_forcewake_put__locked(uncore, fw);
spin_unlock_irq(&uncore->lock);
if (ret && slow_timeout_ms)
ret = __wait_for(reg_value = intel_uncore_read_notrace(uncore,
reg),
(reg_value & mask) == value,
slow_timeout_ms * 1000, 10, 1000);
/* just trace the final value */
trace_i915_reg_rw(false, reg, reg_value, sizeof(reg_value), true);
if (out_value)
*out_value = reg_value;
return ret;
}
bool intel_uncore_unclaimed_mmio(struct intel_uncore *uncore)
{
bool ret;
if (!uncore->debug)
return false;
spin_lock_irq(&uncore->debug->lock);
ret = check_for_unclaimed_mmio(uncore);
spin_unlock_irq(&uncore->debug->lock);
return ret;
}
bool
intel_uncore_arm_unclaimed_mmio_detection(struct intel_uncore *uncore)
{
bool ret = false;
if (drm_WARN_ON(&uncore->i915->drm, !uncore->debug))
return false;
spin_lock_irq(&uncore->debug->lock);
if (unlikely(uncore->debug->unclaimed_mmio_check <= 0))
goto out;
if (unlikely(check_for_unclaimed_mmio(uncore))) {
if (!uncore->i915->params.mmio_debug) {
drm_dbg(&uncore->i915->drm,
"Unclaimed register detected, "
"enabling oneshot unclaimed register reporting. "
"Please use i915.mmio_debug=N for more information.\n");
uncore->i915->params.mmio_debug++;
}
uncore->debug->unclaimed_mmio_check--;
ret = true;
}
out:
spin_unlock_irq(&uncore->debug->lock);
return ret;
}
/**
* intel_uncore_forcewake_for_reg - which forcewake domains are needed to access
* a register
* @uncore: pointer to struct intel_uncore
* @reg: register in question
* @op: operation bitmask of FW_REG_READ and/or FW_REG_WRITE
*
* Returns a set of forcewake domains required to be taken with for example
* intel_uncore_forcewake_get for the specified register to be accessible in the
* specified mode (read, write or read/write) with raw mmio accessors.
*
* NOTE: On Gen6 and Gen7 write forcewake domain (FORCEWAKE_RENDER) requires the
* callers to do FIFO management on their own or risk losing writes.
*/
enum forcewake_domains
intel_uncore_forcewake_for_reg(struct intel_uncore *uncore,
i915_reg_t reg, unsigned int op)
{
enum forcewake_domains fw_domains = 0;
drm_WARN_ON(&uncore->i915->drm, !op);
if (!intel_uncore_has_forcewake(uncore))
return 0;
if (op & FW_REG_READ)
fw_domains = uncore->funcs.read_fw_domains(uncore, reg);
if (op & FW_REG_WRITE)
fw_domains |= uncore->funcs.write_fw_domains(uncore, reg);
drm_WARN_ON(&uncore->i915->drm, fw_domains & ~uncore->fw_domains);
return fw_domains;
}
#if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
#include "selftests/mock_uncore.c"
#include "selftests/intel_uncore.c"
#endif
| linux-master | drivers/gpu/drm/i915/intel_uncore.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2010 Daniel Vetter
* Copyright © 2020 Intel Corporation
*/
#include <linux/slab.h> /* fault-inject.h is not standalone! */
#include <linux/fault-inject.h>
#include <linux/log2.h>
#include <linux/random.h>
#include <linux/seq_file.h>
#include <linux/stop_machine.h>
#include <asm/set_memory.h>
#include <asm/smp.h>
#include "display/intel_frontbuffer.h"
#include "gt/intel_gt.h"
#include "gt/intel_gt_requests.h"
#include "i915_drv.h"
#include "i915_gem_evict.h"
#include "i915_scatterlist.h"
#include "i915_trace.h"
#include "i915_vgpu.h"
int i915_gem_gtt_prepare_pages(struct drm_i915_gem_object *obj,
struct sg_table *pages)
{
do {
if (dma_map_sg_attrs(obj->base.dev->dev,
pages->sgl, pages->nents,
DMA_BIDIRECTIONAL,
DMA_ATTR_SKIP_CPU_SYNC |
DMA_ATTR_NO_KERNEL_MAPPING |
DMA_ATTR_NO_WARN))
return 0;
/*
* If the DMA remap fails, one cause can be that we have
* too many objects pinned in a small remapping table,
* such as swiotlb. Incrementally purge all other objects and
* try again - if there are no more pages to remove from
* the DMA remapper, i915_gem_shrink will return 0.
*/
GEM_BUG_ON(obj->mm.pages == pages);
} while (i915_gem_shrink(NULL, to_i915(obj->base.dev),
obj->base.size >> PAGE_SHIFT, NULL,
I915_SHRINK_BOUND |
I915_SHRINK_UNBOUND));
return -ENOSPC;
}
void i915_gem_gtt_finish_pages(struct drm_i915_gem_object *obj,
struct sg_table *pages)
{
struct drm_i915_private *i915 = to_i915(obj->base.dev);
struct i915_ggtt *ggtt = to_gt(i915)->ggtt;
/* XXX This does not prevent more requests being submitted! */
if (unlikely(ggtt->do_idle_maps))
/* Wait a bit, in the hope it avoids the hang */
usleep_range(100, 250);
dma_unmap_sg(i915->drm.dev, pages->sgl, pages->nents,
DMA_BIDIRECTIONAL);
}
/**
* i915_gem_gtt_reserve - reserve a node in an address_space (GTT)
* @vm: the &struct i915_address_space
* @ww: An optional struct i915_gem_ww_ctx.
* @node: the &struct drm_mm_node (typically i915_vma.mode)
* @size: how much space to allocate inside the GTT,
* must be #I915_GTT_PAGE_SIZE aligned
* @offset: where to insert inside the GTT,
* must be #I915_GTT_MIN_ALIGNMENT aligned, and the node
* (@offset + @size) must fit within the address space
* @color: color to apply to node, if this node is not from a VMA,
* color must be #I915_COLOR_UNEVICTABLE
* @flags: control search and eviction behaviour
*
* i915_gem_gtt_reserve() tries to insert the @node at the exact @offset inside
* the address space (using @size and @color). If the @node does not fit, it
* tries to evict any overlapping nodes from the GTT, including any
* neighbouring nodes if the colors do not match (to ensure guard pages between
* differing domains). See i915_gem_evict_for_node() for the gory details
* on the eviction algorithm. #PIN_NONBLOCK may used to prevent waiting on
* evicting active overlapping objects, and any overlapping node that is pinned
* or marked as unevictable will also result in failure.
*
* Returns: 0 on success, -ENOSPC if no suitable hole is found, -EINTR if
* asked to wait for eviction and interrupted.
*/
int i915_gem_gtt_reserve(struct i915_address_space *vm,
struct i915_gem_ww_ctx *ww,
struct drm_mm_node *node,
u64 size, u64 offset, unsigned long color,
unsigned int flags)
{
int err;
GEM_BUG_ON(!size);
GEM_BUG_ON(!IS_ALIGNED(size, I915_GTT_PAGE_SIZE));
GEM_BUG_ON(!IS_ALIGNED(offset, I915_GTT_MIN_ALIGNMENT));
GEM_BUG_ON(range_overflows(offset, size, vm->total));
GEM_BUG_ON(vm == &to_gt(vm->i915)->ggtt->alias->vm);
GEM_BUG_ON(drm_mm_node_allocated(node));
node->size = size;
node->start = offset;
node->color = color;
err = drm_mm_reserve_node(&vm->mm, node);
if (err != -ENOSPC)
return err;
if (flags & PIN_NOEVICT)
return -ENOSPC;
err = i915_gem_evict_for_node(vm, ww, node, flags);
if (err == 0)
err = drm_mm_reserve_node(&vm->mm, node);
return err;
}
static u64 random_offset(u64 start, u64 end, u64 len, u64 align)
{
u64 range, addr;
GEM_BUG_ON(range_overflows(start, len, end));
GEM_BUG_ON(round_up(start, align) > round_down(end - len, align));
range = round_down(end - len, align) - round_up(start, align);
if (range) {
if (sizeof(unsigned long) == sizeof(u64)) {
addr = get_random_u64();
} else {
addr = get_random_u32();
if (range > U32_MAX) {
addr <<= 32;
addr |= get_random_u32();
}
}
div64_u64_rem(addr, range, &addr);
start += addr;
}
return round_up(start, align);
}
/**
* i915_gem_gtt_insert - insert a node into an address_space (GTT)
* @vm: the &struct i915_address_space
* @ww: An optional struct i915_gem_ww_ctx.
* @node: the &struct drm_mm_node (typically i915_vma.node)
* @size: how much space to allocate inside the GTT,
* must be #I915_GTT_PAGE_SIZE aligned
* @alignment: required alignment of starting offset, may be 0 but
* if specified, this must be a power-of-two and at least
* #I915_GTT_MIN_ALIGNMENT
* @color: color to apply to node
* @start: start of any range restriction inside GTT (0 for all),
* must be #I915_GTT_PAGE_SIZE aligned
* @end: end of any range restriction inside GTT (U64_MAX for all),
* must be #I915_GTT_PAGE_SIZE aligned if not U64_MAX
* @flags: control search and eviction behaviour
*
* i915_gem_gtt_insert() first searches for an available hole into which
* is can insert the node. The hole address is aligned to @alignment and
* its @size must then fit entirely within the [@start, @end] bounds. The
* nodes on either side of the hole must match @color, or else a guard page
* will be inserted between the two nodes (or the node evicted). If no
* suitable hole is found, first a victim is randomly selected and tested
* for eviction, otherwise then the LRU list of objects within the GTT
* is scanned to find the first set of replacement nodes to create the hole.
* Those old overlapping nodes are evicted from the GTT (and so must be
* rebound before any future use). Any node that is currently pinned cannot
* be evicted (see i915_vma_pin()). Similar if the node's VMA is currently
* active and #PIN_NONBLOCK is specified, that node is also skipped when
* searching for an eviction candidate. See i915_gem_evict_something() for
* the gory details on the eviction algorithm.
*
* Returns: 0 on success, -ENOSPC if no suitable hole is found, -EINTR if
* asked to wait for eviction and interrupted.
*/
int i915_gem_gtt_insert(struct i915_address_space *vm,
struct i915_gem_ww_ctx *ww,
struct drm_mm_node *node,
u64 size, u64 alignment, unsigned long color,
u64 start, u64 end, unsigned int flags)
{
enum drm_mm_insert_mode mode;
u64 offset;
int err;
lockdep_assert_held(&vm->mutex);
GEM_BUG_ON(!size);
GEM_BUG_ON(!IS_ALIGNED(size, I915_GTT_PAGE_SIZE));
GEM_BUG_ON(alignment && !is_power_of_2(alignment));
GEM_BUG_ON(alignment && !IS_ALIGNED(alignment, I915_GTT_MIN_ALIGNMENT));
GEM_BUG_ON(start >= end);
GEM_BUG_ON(start > 0 && !IS_ALIGNED(start, I915_GTT_PAGE_SIZE));
GEM_BUG_ON(end < U64_MAX && !IS_ALIGNED(end, I915_GTT_PAGE_SIZE));
GEM_BUG_ON(vm == &to_gt(vm->i915)->ggtt->alias->vm);
GEM_BUG_ON(drm_mm_node_allocated(node));
if (unlikely(range_overflows(start, size, end)))
return -ENOSPC;
if (unlikely(round_up(start, alignment) > round_down(end - size, alignment)))
return -ENOSPC;
mode = DRM_MM_INSERT_BEST;
if (flags & PIN_HIGH)
mode = DRM_MM_INSERT_HIGHEST;
if (flags & PIN_MAPPABLE)
mode = DRM_MM_INSERT_LOW;
/* We only allocate in PAGE_SIZE/GTT_PAGE_SIZE (4096) chunks,
* so we know that we always have a minimum alignment of 4096.
* The drm_mm range manager is optimised to return results
* with zero alignment, so where possible use the optimal
* path.
*/
BUILD_BUG_ON(I915_GTT_MIN_ALIGNMENT > I915_GTT_PAGE_SIZE);
if (alignment <= I915_GTT_MIN_ALIGNMENT)
alignment = 0;
err = drm_mm_insert_node_in_range(&vm->mm, node,
size, alignment, color,
start, end, mode);
if (err != -ENOSPC)
return err;
if (mode & DRM_MM_INSERT_ONCE) {
err = drm_mm_insert_node_in_range(&vm->mm, node,
size, alignment, color,
start, end,
DRM_MM_INSERT_BEST);
if (err != -ENOSPC)
return err;
}
if (flags & PIN_NOEVICT)
return -ENOSPC;
/*
* No free space, pick a slot at random.
*
* There is a pathological case here using a GTT shared between
* mmap and GPU (i.e. ggtt/aliasing_ppgtt but not full-ppgtt):
*
* |<-- 256 MiB aperture -->||<-- 1792 MiB unmappable -->|
* (64k objects) (448k objects)
*
* Now imagine that the eviction LRU is ordered top-down (just because
* pathology meets real life), and that we need to evict an object to
* make room inside the aperture. The eviction scan then has to walk
* the 448k list before it finds one within range. And now imagine that
* it has to search for a new hole between every byte inside the memcpy,
* for several simultaneous clients.
*
* On a full-ppgtt system, if we have run out of available space, there
* will be lots and lots of objects in the eviction list! Again,
* searching that LRU list may be slow if we are also applying any
* range restrictions (e.g. restriction to low 4GiB) and so, for
* simplicity and similarilty between different GTT, try the single
* random replacement first.
*/
offset = random_offset(start, end,
size, alignment ?: I915_GTT_MIN_ALIGNMENT);
err = i915_gem_gtt_reserve(vm, ww, node, size, offset, color, flags);
if (err != -ENOSPC)
return err;
if (flags & PIN_NOSEARCH)
return -ENOSPC;
/* Randomly selected placement is pinned, do a search */
err = i915_gem_evict_something(vm, ww, size, alignment, color,
start, end, flags);
if (err)
return err;
return drm_mm_insert_node_in_range(&vm->mm, node,
size, alignment, color,
start, end, DRM_MM_INSERT_EVICT);
}
#if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
#include "selftests/i915_gem_gtt.c"
#endif
| linux-master | drivers/gpu/drm/i915/i915_gem_gtt.c |
/*
* SPDX-License-Identifier: MIT
*
* Copyright © 2021 Intel Corporation
*/
#include <drm/drm_drv.h>
#include "gem/i915_gem_context.h"
#include "gem/i915_gem_object.h"
#include "i915_active.h"
#include "i915_driver.h"
#include "i915_params.h"
#include "i915_pci.h"
#include "i915_perf.h"
#include "i915_request.h"
#include "i915_scheduler.h"
#include "i915_selftest.h"
#include "i915_vma.h"
#include "i915_vma_resource.h"
static int i915_check_nomodeset(void)
{
bool use_kms = true;
/*
* Enable KMS by default, unless explicitly overriden by
* either the i915.modeset parameter or by the
* nomodeset boot option.
*/
if (i915_modparams.modeset == 0)
use_kms = false;
if (drm_firmware_drivers_only() && i915_modparams.modeset == -1)
use_kms = false;
if (!use_kms) {
/* Silently fail loading to not upset userspace. */
DRM_DEBUG_DRIVER("KMS disabled.\n");
return 1;
}
return 0;
}
static const struct {
int (*init)(void);
void (*exit)(void);
} init_funcs[] = {
{ .init = i915_check_nomodeset },
{ .init = i915_active_module_init,
.exit = i915_active_module_exit },
{ .init = i915_context_module_init,
.exit = i915_context_module_exit },
{ .init = i915_gem_context_module_init,
.exit = i915_gem_context_module_exit },
{ .init = i915_objects_module_init,
.exit = i915_objects_module_exit },
{ .init = i915_request_module_init,
.exit = i915_request_module_exit },
{ .init = i915_scheduler_module_init,
.exit = i915_scheduler_module_exit },
{ .init = i915_vma_module_init,
.exit = i915_vma_module_exit },
{ .init = i915_vma_resource_module_init,
.exit = i915_vma_resource_module_exit },
{ .init = i915_mock_selftests },
{ .init = i915_pmu_init,
.exit = i915_pmu_exit },
{ .init = i915_pci_register_driver,
.exit = i915_pci_unregister_driver },
{ .init = i915_perf_sysctl_register,
.exit = i915_perf_sysctl_unregister },
};
static int init_progress;
static int __init i915_init(void)
{
int err, i;
for (i = 0; i < ARRAY_SIZE(init_funcs); i++) {
err = init_funcs[i].init();
if (err < 0) {
while (i--) {
if (init_funcs[i].exit)
init_funcs[i].exit();
}
return err;
} else if (err > 0) {
/*
* Early-exit success is reserved for things which
* don't have an exit() function because we have no
* idea how far they got or how to partially tear
* them down.
*/
WARN_ON(init_funcs[i].exit);
break;
}
}
init_progress = i;
return 0;
}
static void __exit i915_exit(void)
{
int i;
for (i = init_progress - 1; i >= 0; i--) {
GEM_BUG_ON(i >= ARRAY_SIZE(init_funcs));
if (init_funcs[i].exit)
init_funcs[i].exit();
}
}
module_init(i915_init);
module_exit(i915_exit);
MODULE_AUTHOR("Tungsten Graphics, Inc.");
MODULE_AUTHOR("Intel Corporation");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL and additional rights");
| linux-master | drivers/gpu/drm/i915/i915_module.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2020 Intel Corporation
*/
#include <linux/string_helpers.h>
#include <linux/kernel.h>
#include <drm/drm_print.h>
#include "i915_drv.h"
#include "i915_reg.h"
#include "i915_trace.h"
#include "i915_utils.h"
#include "intel_clock_gating.h"
#include "vlv_suspend.h"
#include "gt/intel_gt_regs.h"
struct vlv_s0ix_state {
/* GAM */
u32 wr_watermark;
u32 gfx_prio_ctrl;
u32 arb_mode;
u32 gfx_pend_tlb0;
u32 gfx_pend_tlb1;
u32 lra_limits[GEN7_LRA_LIMITS_REG_NUM];
u32 media_max_req_count;
u32 gfx_max_req_count;
u32 render_hwsp;
u32 ecochk;
u32 bsd_hwsp;
u32 blt_hwsp;
u32 tlb_rd_addr;
/* MBC */
u32 g3dctl;
u32 gsckgctl;
u32 mbctl;
/* GCP */
u32 ucgctl1;
u32 ucgctl3;
u32 rcgctl1;
u32 rcgctl2;
u32 rstctl;
u32 misccpctl;
/* GPM */
u32 gfxpause;
u32 rpdeuhwtc;
u32 rpdeuc;
u32 ecobus;
u32 pwrdwnupctl;
u32 rp_down_timeout;
u32 rp_deucsw;
u32 rcubmabdtmr;
u32 rcedata;
u32 spare2gh;
/* Display 1 CZ domain */
u32 gt_imr;
u32 gt_ier;
u32 pm_imr;
u32 pm_ier;
u32 gt_scratch[GEN7_GT_SCRATCH_REG_NUM];
/* GT SA CZ domain */
u32 tilectl;
u32 gt_fifoctl;
u32 gtlc_wake_ctrl;
u32 gtlc_survive;
u32 pmwgicz;
/* Display 2 CZ domain */
u32 gu_ctl0;
u32 gu_ctl1;
u32 pcbr;
u32 clock_gate_dis2;
};
/*
* Save all Gunit registers that may be lost after a D3 and a subsequent
* S0i[R123] transition. The list of registers needing a save/restore is
* defined in the VLV2_S0IXRegs document. This documents marks all Gunit
* registers in the following way:
* - Driver: saved/restored by the driver
* - Punit : saved/restored by the Punit firmware
* - No, w/o marking: no need to save/restore, since the register is R/O or
* used internally by the HW in a way that doesn't depend
* keeping the content across a suspend/resume.
* - Debug : used for debugging
*
* We save/restore all registers marked with 'Driver', with the following
* exceptions:
* - Registers out of use, including also registers marked with 'Debug'.
* These have no effect on the driver's operation, so we don't save/restore
* them to reduce the overhead.
* - Registers that are fully setup by an initialization function called from
* the resume path. For example many clock gating and RPS/RC6 registers.
* - Registers that provide the right functionality with their reset defaults.
*
* TODO: Except for registers that based on the above 3 criteria can be safely
* ignored, we save/restore all others, practically treating the HW context as
* a black-box for the driver. Further investigation is needed to reduce the
* saved/restored registers even further, by following the same 3 criteria.
*/
static void vlv_save_gunit_s0ix_state(struct drm_i915_private *i915)
{
struct vlv_s0ix_state *s = i915->vlv_s0ix_state;
struct intel_uncore *uncore = &i915->uncore;
int i;
if (!s)
return;
/* GAM 0x4000-0x4770 */
s->wr_watermark = intel_uncore_read(uncore, GEN7_WR_WATERMARK);
s->gfx_prio_ctrl = intel_uncore_read(uncore, GEN7_GFX_PRIO_CTRL);
s->arb_mode = intel_uncore_read(uncore, ARB_MODE);
s->gfx_pend_tlb0 = intel_uncore_read(uncore, GEN7_GFX_PEND_TLB0);
s->gfx_pend_tlb1 = intel_uncore_read(uncore, GEN7_GFX_PEND_TLB1);
for (i = 0; i < ARRAY_SIZE(s->lra_limits); i++)
s->lra_limits[i] = intel_uncore_read(uncore, GEN7_LRA_LIMITS(i));
s->media_max_req_count = intel_uncore_read(uncore, GEN7_MEDIA_MAX_REQ_COUNT);
s->gfx_max_req_count = intel_uncore_read(uncore, GEN7_GFX_MAX_REQ_COUNT);
s->render_hwsp = intel_uncore_read(uncore, RENDER_HWS_PGA_GEN7);
s->ecochk = intel_uncore_read(uncore, GAM_ECOCHK);
s->bsd_hwsp = intel_uncore_read(uncore, BSD_HWS_PGA_GEN7);
s->blt_hwsp = intel_uncore_read(uncore, BLT_HWS_PGA_GEN7);
s->tlb_rd_addr = intel_uncore_read(uncore, GEN7_TLB_RD_ADDR);
/* MBC 0x9024-0x91D0, 0x8500 */
s->g3dctl = intel_uncore_read(uncore, VLV_G3DCTL);
s->gsckgctl = intel_uncore_read(uncore, VLV_GSCKGCTL);
s->mbctl = intel_uncore_read(uncore, GEN6_MBCTL);
/* GCP 0x9400-0x9424, 0x8100-0x810C */
s->ucgctl1 = intel_uncore_read(uncore, GEN6_UCGCTL1);
s->ucgctl3 = intel_uncore_read(uncore, GEN6_UCGCTL3);
s->rcgctl1 = intel_uncore_read(uncore, GEN6_RCGCTL1);
s->rcgctl2 = intel_uncore_read(uncore, GEN6_RCGCTL2);
s->rstctl = intel_uncore_read(uncore, GEN6_RSTCTL);
s->misccpctl = intel_uncore_read(uncore, GEN7_MISCCPCTL);
/* GPM 0xA000-0xAA84, 0x8000-0x80FC */
s->gfxpause = intel_uncore_read(uncore, GEN6_GFXPAUSE);
s->rpdeuhwtc = intel_uncore_read(uncore, GEN6_RPDEUHWTC);
s->rpdeuc = intel_uncore_read(uncore, GEN6_RPDEUC);
s->ecobus = intel_uncore_read(uncore, ECOBUS);
s->pwrdwnupctl = intel_uncore_read(uncore, VLV_PWRDWNUPCTL);
s->rp_down_timeout = intel_uncore_read(uncore, GEN6_RP_DOWN_TIMEOUT);
s->rp_deucsw = intel_uncore_read(uncore, GEN6_RPDEUCSW);
s->rcubmabdtmr = intel_uncore_read(uncore, GEN6_RCUBMABDTMR);
s->rcedata = intel_uncore_read(uncore, VLV_RCEDATA);
s->spare2gh = intel_uncore_read(uncore, VLV_SPAREG2H);
/* Display CZ domain, 0x4400C-0x4402C, 0x4F000-0x4F11F */
s->gt_imr = intel_uncore_read(uncore, GTIMR);
s->gt_ier = intel_uncore_read(uncore, GTIER);
s->pm_imr = intel_uncore_read(uncore, GEN6_PMIMR);
s->pm_ier = intel_uncore_read(uncore, GEN6_PMIER);
for (i = 0; i < ARRAY_SIZE(s->gt_scratch); i++)
s->gt_scratch[i] = intel_uncore_read(uncore, GEN7_GT_SCRATCH(i));
/* GT SA CZ domain, 0x100000-0x138124 */
s->tilectl = intel_uncore_read(uncore, TILECTL);
s->gt_fifoctl = intel_uncore_read(uncore, GTFIFOCTL);
s->gtlc_wake_ctrl = intel_uncore_read(uncore, VLV_GTLC_WAKE_CTRL);
s->gtlc_survive = intel_uncore_read(uncore, VLV_GTLC_SURVIVABILITY_REG);
s->pmwgicz = intel_uncore_read(uncore, VLV_PMWGICZ);
/* Gunit-Display CZ domain, 0x182028-0x1821CF */
s->gu_ctl0 = intel_uncore_read(uncore, VLV_GU_CTL0);
s->gu_ctl1 = intel_uncore_read(uncore, VLV_GU_CTL1);
s->pcbr = intel_uncore_read(uncore, VLV_PCBR);
s->clock_gate_dis2 = intel_uncore_read(uncore, VLV_GUNIT_CLOCK_GATE2);
/*
* Not saving any of:
* DFT, 0x9800-0x9EC0
* SARB, 0xB000-0xB1FC
* GAC, 0x5208-0x524C, 0x14000-0x14C000
* PCI CFG
*/
}
static void vlv_restore_gunit_s0ix_state(struct drm_i915_private *i915)
{
struct vlv_s0ix_state *s = i915->vlv_s0ix_state;
struct intel_uncore *uncore = &i915->uncore;
int i;
if (!s)
return;
/* GAM 0x4000-0x4770 */
intel_uncore_write(uncore, GEN7_WR_WATERMARK, s->wr_watermark);
intel_uncore_write(uncore, GEN7_GFX_PRIO_CTRL, s->gfx_prio_ctrl);
intel_uncore_write(uncore, ARB_MODE, s->arb_mode | (0xffff << 16));
intel_uncore_write(uncore, GEN7_GFX_PEND_TLB0, s->gfx_pend_tlb0);
intel_uncore_write(uncore, GEN7_GFX_PEND_TLB1, s->gfx_pend_tlb1);
for (i = 0; i < ARRAY_SIZE(s->lra_limits); i++)
intel_uncore_write(uncore, GEN7_LRA_LIMITS(i), s->lra_limits[i]);
intel_uncore_write(uncore, GEN7_MEDIA_MAX_REQ_COUNT, s->media_max_req_count);
intel_uncore_write(uncore, GEN7_GFX_MAX_REQ_COUNT, s->gfx_max_req_count);
intel_uncore_write(uncore, RENDER_HWS_PGA_GEN7, s->render_hwsp);
intel_uncore_write(uncore, GAM_ECOCHK, s->ecochk);
intel_uncore_write(uncore, BSD_HWS_PGA_GEN7, s->bsd_hwsp);
intel_uncore_write(uncore, BLT_HWS_PGA_GEN7, s->blt_hwsp);
intel_uncore_write(uncore, GEN7_TLB_RD_ADDR, s->tlb_rd_addr);
/* MBC 0x9024-0x91D0, 0x8500 */
intel_uncore_write(uncore, VLV_G3DCTL, s->g3dctl);
intel_uncore_write(uncore, VLV_GSCKGCTL, s->gsckgctl);
intel_uncore_write(uncore, GEN6_MBCTL, s->mbctl);
/* GCP 0x9400-0x9424, 0x8100-0x810C */
intel_uncore_write(uncore, GEN6_UCGCTL1, s->ucgctl1);
intel_uncore_write(uncore, GEN6_UCGCTL3, s->ucgctl3);
intel_uncore_write(uncore, GEN6_RCGCTL1, s->rcgctl1);
intel_uncore_write(uncore, GEN6_RCGCTL2, s->rcgctl2);
intel_uncore_write(uncore, GEN6_RSTCTL, s->rstctl);
intel_uncore_write(uncore, GEN7_MISCCPCTL, s->misccpctl);
/* GPM 0xA000-0xAA84, 0x8000-0x80FC */
intel_uncore_write(uncore, GEN6_GFXPAUSE, s->gfxpause);
intel_uncore_write(uncore, GEN6_RPDEUHWTC, s->rpdeuhwtc);
intel_uncore_write(uncore, GEN6_RPDEUC, s->rpdeuc);
intel_uncore_write(uncore, ECOBUS, s->ecobus);
intel_uncore_write(uncore, VLV_PWRDWNUPCTL, s->pwrdwnupctl);
intel_uncore_write(uncore, GEN6_RP_DOWN_TIMEOUT, s->rp_down_timeout);
intel_uncore_write(uncore, GEN6_RPDEUCSW, s->rp_deucsw);
intel_uncore_write(uncore, GEN6_RCUBMABDTMR, s->rcubmabdtmr);
intel_uncore_write(uncore, VLV_RCEDATA, s->rcedata);
intel_uncore_write(uncore, VLV_SPAREG2H, s->spare2gh);
/* Display CZ domain, 0x4400C-0x4402C, 0x4F000-0x4F11F */
intel_uncore_write(uncore, GTIMR, s->gt_imr);
intel_uncore_write(uncore, GTIER, s->gt_ier);
intel_uncore_write(uncore, GEN6_PMIMR, s->pm_imr);
intel_uncore_write(uncore, GEN6_PMIER, s->pm_ier);
for (i = 0; i < ARRAY_SIZE(s->gt_scratch); i++)
intel_uncore_write(uncore, GEN7_GT_SCRATCH(i), s->gt_scratch[i]);
/* GT SA CZ domain, 0x100000-0x138124 */
intel_uncore_write(uncore, TILECTL, s->tilectl);
intel_uncore_write(uncore, GTFIFOCTL, s->gt_fifoctl);
/*
* Preserve the GT allow wake and GFX force clock bit, they are not
* be restored, as they are used to control the s0ix suspend/resume
* sequence by the caller.
*/
intel_uncore_rmw(uncore, VLV_GTLC_WAKE_CTRL, ~VLV_GTLC_ALLOWWAKEREQ,
s->gtlc_wake_ctrl & ~VLV_GTLC_ALLOWWAKEREQ);
intel_uncore_rmw(uncore, VLV_GTLC_SURVIVABILITY_REG, ~VLV_GFX_CLK_FORCE_ON_BIT,
s->gtlc_survive & ~VLV_GFX_CLK_FORCE_ON_BIT);
intel_uncore_write(uncore, VLV_PMWGICZ, s->pmwgicz);
/* Gunit-Display CZ domain, 0x182028-0x1821CF */
intel_uncore_write(uncore, VLV_GU_CTL0, s->gu_ctl0);
intel_uncore_write(uncore, VLV_GU_CTL1, s->gu_ctl1);
intel_uncore_write(uncore, VLV_PCBR, s->pcbr);
intel_uncore_write(uncore, VLV_GUNIT_CLOCK_GATE2, s->clock_gate_dis2);
}
static int vlv_wait_for_pw_status(struct drm_i915_private *i915,
u32 mask, u32 val)
{
i915_reg_t reg = VLV_GTLC_PW_STATUS;
u32 reg_value;
int ret;
/* The HW does not like us polling for PW_STATUS frequently, so
* use the sleeping loop rather than risk the busy spin within
* intel_wait_for_register().
*
* Transitioning between RC6 states should be at most 2ms (see
* valleyview_enable_rps) so use a 3ms timeout.
*/
ret = wait_for(((reg_value =
intel_uncore_read_notrace(&i915->uncore, reg)) & mask)
== val, 3);
/* just trace the final value */
trace_i915_reg_rw(false, reg, reg_value, sizeof(reg_value), true);
return ret;
}
static int vlv_force_gfx_clock(struct drm_i915_private *i915, bool force_on)
{
struct intel_uncore *uncore = &i915->uncore;
int err;
intel_uncore_rmw(uncore, VLV_GTLC_SURVIVABILITY_REG, VLV_GFX_CLK_FORCE_ON_BIT,
force_on ? VLV_GFX_CLK_FORCE_ON_BIT : 0);
if (!force_on)
return 0;
err = intel_wait_for_register(uncore,
VLV_GTLC_SURVIVABILITY_REG,
VLV_GFX_CLK_STATUS_BIT,
VLV_GFX_CLK_STATUS_BIT,
20);
if (err)
drm_err(&i915->drm,
"timeout waiting for GFX clock force-on (%08x)\n",
intel_uncore_read(uncore, VLV_GTLC_SURVIVABILITY_REG));
return err;
}
static int vlv_allow_gt_wake(struct drm_i915_private *i915, bool allow)
{
struct intel_uncore *uncore = &i915->uncore;
u32 mask;
u32 val;
int err;
intel_uncore_rmw(uncore, VLV_GTLC_WAKE_CTRL, VLV_GTLC_ALLOWWAKEREQ,
allow ? VLV_GTLC_ALLOWWAKEREQ : 0);
intel_uncore_posting_read(uncore, VLV_GTLC_WAKE_CTRL);
mask = VLV_GTLC_ALLOWWAKEACK;
val = allow ? mask : 0;
err = vlv_wait_for_pw_status(i915, mask, val);
if (err)
drm_err(&i915->drm, "timeout disabling GT waking\n");
return err;
}
static void vlv_wait_for_gt_wells(struct drm_i915_private *dev_priv,
bool wait_for_on)
{
u32 mask;
u32 val;
mask = VLV_GTLC_PW_MEDIA_STATUS_MASK | VLV_GTLC_PW_RENDER_STATUS_MASK;
val = wait_for_on ? mask : 0;
/*
* RC6 transitioning can be delayed up to 2 msec (see
* valleyview_enable_rps), use 3 msec for safety.
*
* This can fail to turn off the rc6 if the GPU is stuck after a failed
* reset and we are trying to force the machine to sleep.
*/
if (vlv_wait_for_pw_status(dev_priv, mask, val))
drm_dbg(&dev_priv->drm,
"timeout waiting for GT wells to go %s\n",
str_on_off(wait_for_on));
}
static void vlv_check_no_gt_access(struct drm_i915_private *i915)
{
struct intel_uncore *uncore = &i915->uncore;
if (!(intel_uncore_read(uncore, VLV_GTLC_PW_STATUS) & VLV_GTLC_ALLOWWAKEERR))
return;
drm_dbg(&i915->drm, "GT register access while GT waking disabled\n");
intel_uncore_write(uncore, VLV_GTLC_PW_STATUS, VLV_GTLC_ALLOWWAKEERR);
}
int vlv_suspend_complete(struct drm_i915_private *dev_priv)
{
u32 mask;
int err;
if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv))
return 0;
/*
* Bspec defines the following GT well on flags as debug only, so
* don't treat them as hard failures.
*/
vlv_wait_for_gt_wells(dev_priv, false);
mask = VLV_GTLC_RENDER_CTX_EXISTS | VLV_GTLC_MEDIA_CTX_EXISTS;
drm_WARN_ON(&dev_priv->drm,
(intel_uncore_read(&dev_priv->uncore, VLV_GTLC_WAKE_CTRL) & mask) != mask);
vlv_check_no_gt_access(dev_priv);
err = vlv_force_gfx_clock(dev_priv, true);
if (err)
goto err1;
err = vlv_allow_gt_wake(dev_priv, false);
if (err)
goto err2;
vlv_save_gunit_s0ix_state(dev_priv);
err = vlv_force_gfx_clock(dev_priv, false);
if (err)
goto err2;
return 0;
err2:
/* For safety always re-enable waking and disable gfx clock forcing */
vlv_allow_gt_wake(dev_priv, true);
err1:
vlv_force_gfx_clock(dev_priv, false);
return err;
}
int vlv_resume_prepare(struct drm_i915_private *dev_priv, bool rpm_resume)
{
int err;
int ret;
if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv))
return 0;
/*
* If any of the steps fail just try to continue, that's the best we
* can do at this point. Return the first error code (which will also
* leave RPM permanently disabled).
*/
ret = vlv_force_gfx_clock(dev_priv, true);
vlv_restore_gunit_s0ix_state(dev_priv);
err = vlv_allow_gt_wake(dev_priv, true);
if (!ret)
ret = err;
err = vlv_force_gfx_clock(dev_priv, false);
if (!ret)
ret = err;
vlv_check_no_gt_access(dev_priv);
if (rpm_resume)
intel_clock_gating_init(dev_priv);
return ret;
}
int vlv_suspend_init(struct drm_i915_private *i915)
{
if (!IS_VALLEYVIEW(i915))
return 0;
/* we write all the values in the struct, so no need to zero it out */
i915->vlv_s0ix_state = kmalloc(sizeof(*i915->vlv_s0ix_state),
GFP_KERNEL);
if (!i915->vlv_s0ix_state)
return -ENOMEM;
return 0;
}
void vlv_suspend_cleanup(struct drm_i915_private *i915)
{
if (!i915->vlv_s0ix_state)
return;
kfree(i915->vlv_s0ix_state);
i915->vlv_s0ix_state = NULL;
}
| linux-master | drivers/gpu/drm/i915/vlv_suspend.c |
/*
* Copyright(c) 2011-2015 Intel Corporation. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "i915_drv.h"
#include "i915_pvinfo.h"
#include "i915_vgpu.h"
/**
* DOC: Intel GVT-g guest support
*
* Intel GVT-g is a graphics virtualization technology which shares the
* GPU among multiple virtual machines on a time-sharing basis. Each
* virtual machine is presented a virtual GPU (vGPU), which has equivalent
* features as the underlying physical GPU (pGPU), so i915 driver can run
* seamlessly in a virtual machine. This file provides vGPU specific
* optimizations when running in a virtual machine, to reduce the complexity
* of vGPU emulation and to improve the overall performance.
*
* A primary function introduced here is so-called "address space ballooning"
* technique. Intel GVT-g partitions global graphics memory among multiple VMs,
* so each VM can directly access a portion of the memory without hypervisor's
* intervention, e.g. filling textures or queuing commands. However with the
* partitioning an unmodified i915 driver would assume a smaller graphics
* memory starting from address ZERO, then requires vGPU emulation module to
* translate the graphics address between 'guest view' and 'host view', for
* all registers and command opcodes which contain a graphics memory address.
* To reduce the complexity, Intel GVT-g introduces "address space ballooning",
* by telling the exact partitioning knowledge to each guest i915 driver, which
* then reserves and prevents non-allocated portions from allocation. Thus vGPU
* emulation module only needs to scan and validate graphics addresses without
* complexity of address translation.
*
*/
/**
* intel_vgpu_detect - detect virtual GPU
* @dev_priv: i915 device private
*
* This function is called at the initialization stage, to detect whether
* running on a vGPU.
*/
void intel_vgpu_detect(struct drm_i915_private *dev_priv)
{
struct pci_dev *pdev = to_pci_dev(dev_priv->drm.dev);
u64 magic;
u16 version_major;
void __iomem *shared_area;
BUILD_BUG_ON(sizeof(struct vgt_if) != VGT_PVINFO_SIZE);
/*
* This is called before we setup the main MMIO BAR mappings used via
* the uncore structure, so we need to access the BAR directly. Since
* we do not support VGT on older gens, return early so we don't have
* to consider differently numbered or sized MMIO bars
*/
if (GRAPHICS_VER(dev_priv) < 6)
return;
shared_area = pci_iomap_range(pdev, 0, VGT_PVINFO_PAGE, VGT_PVINFO_SIZE);
if (!shared_area) {
drm_err(&dev_priv->drm,
"failed to map MMIO bar to check for VGT\n");
return;
}
magic = readq(shared_area + vgtif_offset(magic));
if (magic != VGT_MAGIC)
goto out;
version_major = readw(shared_area + vgtif_offset(version_major));
if (version_major < VGT_VERSION_MAJOR) {
drm_info(&dev_priv->drm, "VGT interface version mismatch!\n");
goto out;
}
dev_priv->vgpu.caps = readl(shared_area + vgtif_offset(vgt_caps));
dev_priv->vgpu.active = true;
mutex_init(&dev_priv->vgpu.lock);
drm_info(&dev_priv->drm, "Virtual GPU for Intel GVT-g detected.\n");
out:
pci_iounmap(pdev, shared_area);
}
void intel_vgpu_register(struct drm_i915_private *i915)
{
/*
* Notify a valid surface after modesetting, when running inside a VM.
*/
if (intel_vgpu_active(i915))
intel_uncore_write(&i915->uncore, vgtif_reg(display_ready),
VGT_DRV_DISPLAY_READY);
}
bool intel_vgpu_active(struct drm_i915_private *dev_priv)
{
return dev_priv->vgpu.active;
}
bool intel_vgpu_has_full_ppgtt(struct drm_i915_private *dev_priv)
{
return dev_priv->vgpu.caps & VGT_CAPS_FULL_PPGTT;
}
bool intel_vgpu_has_hwsp_emulation(struct drm_i915_private *dev_priv)
{
return dev_priv->vgpu.caps & VGT_CAPS_HWSP_EMULATION;
}
bool intel_vgpu_has_huge_gtt(struct drm_i915_private *dev_priv)
{
return dev_priv->vgpu.caps & VGT_CAPS_HUGE_GTT;
}
struct _balloon_info_ {
/*
* There are up to 2 regions per mappable/unmappable graphic
* memory that might be ballooned. Here, index 0/1 is for mappable
* graphic memory, 2/3 for unmappable graphic memory.
*/
struct drm_mm_node space[4];
};
static struct _balloon_info_ bl_info;
static void vgt_deballoon_space(struct i915_ggtt *ggtt,
struct drm_mm_node *node)
{
struct drm_i915_private *dev_priv = ggtt->vm.i915;
if (!drm_mm_node_allocated(node))
return;
drm_dbg(&dev_priv->drm,
"deballoon space: range [0x%llx - 0x%llx] %llu KiB.\n",
node->start,
node->start + node->size,
node->size / 1024);
ggtt->vm.reserved -= node->size;
drm_mm_remove_node(node);
}
/**
* intel_vgt_deballoon - deballoon reserved graphics address trunks
* @ggtt: the global GGTT from which we reserved earlier
*
* This function is called to deallocate the ballooned-out graphic memory, when
* driver is unloaded or when ballooning fails.
*/
void intel_vgt_deballoon(struct i915_ggtt *ggtt)
{
struct drm_i915_private *dev_priv = ggtt->vm.i915;
int i;
if (!intel_vgpu_active(ggtt->vm.i915))
return;
drm_dbg(&dev_priv->drm, "VGT deballoon.\n");
for (i = 0; i < 4; i++)
vgt_deballoon_space(ggtt, &bl_info.space[i]);
}
static int vgt_balloon_space(struct i915_ggtt *ggtt,
struct drm_mm_node *node,
unsigned long start, unsigned long end)
{
struct drm_i915_private *dev_priv = ggtt->vm.i915;
unsigned long size = end - start;
int ret;
if (start >= end)
return -EINVAL;
drm_info(&dev_priv->drm,
"balloon space: range [ 0x%lx - 0x%lx ] %lu KiB.\n",
start, end, size / 1024);
ret = i915_gem_gtt_reserve(&ggtt->vm, NULL, node,
size, start, I915_COLOR_UNEVICTABLE,
0);
if (!ret)
ggtt->vm.reserved += size;
return ret;
}
/**
* intel_vgt_balloon - balloon out reserved graphics address trunks
* @ggtt: the global GGTT from which to reserve
*
* This function is called at the initialization stage, to balloon out the
* graphic address space allocated to other vGPUs, by marking these spaces as
* reserved. The ballooning related knowledge(starting address and size of
* the mappable/unmappable graphic memory) is described in the vgt_if structure
* in a reserved mmio range.
*
* To give an example, the drawing below depicts one typical scenario after
* ballooning. Here the vGPU1 has 2 pieces of graphic address spaces ballooned
* out each for the mappable and the non-mappable part. From the vGPU1 point of
* view, the total size is the same as the physical one, with the start address
* of its graphic space being zero. Yet there are some portions ballooned out(
* the shadow part, which are marked as reserved by drm allocator). From the
* host point of view, the graphic address space is partitioned by multiple
* vGPUs in different VMs. ::
*
* vGPU1 view Host view
* 0 ------> +-----------+ +-----------+
* ^ |###########| | vGPU3 |
* | |###########| +-----------+
* | |###########| | vGPU2 |
* | +-----------+ +-----------+
* mappable GM | available | ==> | vGPU1 |
* | +-----------+ +-----------+
* | |###########| | |
* v |###########| | Host |
* +=======+===========+ +===========+
* ^ |###########| | vGPU3 |
* | |###########| +-----------+
* | |###########| | vGPU2 |
* | +-----------+ +-----------+
* unmappable GM | available | ==> | vGPU1 |
* | +-----------+ +-----------+
* | |###########| | |
* | |###########| | Host |
* v |###########| | |
* total GM size ------> +-----------+ +-----------+
*
* Returns:
* zero on success, non-zero if configuration invalid or ballooning failed
*/
int intel_vgt_balloon(struct i915_ggtt *ggtt)
{
struct drm_i915_private *dev_priv = ggtt->vm.i915;
struct intel_uncore *uncore = &dev_priv->uncore;
unsigned long ggtt_end = ggtt->vm.total;
unsigned long mappable_base, mappable_size, mappable_end;
unsigned long unmappable_base, unmappable_size, unmappable_end;
int ret;
if (!intel_vgpu_active(ggtt->vm.i915))
return 0;
mappable_base =
intel_uncore_read(uncore, vgtif_reg(avail_rs.mappable_gmadr.base));
mappable_size =
intel_uncore_read(uncore, vgtif_reg(avail_rs.mappable_gmadr.size));
unmappable_base =
intel_uncore_read(uncore, vgtif_reg(avail_rs.nonmappable_gmadr.base));
unmappable_size =
intel_uncore_read(uncore, vgtif_reg(avail_rs.nonmappable_gmadr.size));
mappable_end = mappable_base + mappable_size;
unmappable_end = unmappable_base + unmappable_size;
drm_info(&dev_priv->drm, "VGT ballooning configuration:\n");
drm_info(&dev_priv->drm,
"Mappable graphic memory: base 0x%lx size %ldKiB\n",
mappable_base, mappable_size / 1024);
drm_info(&dev_priv->drm,
"Unmappable graphic memory: base 0x%lx size %ldKiB\n",
unmappable_base, unmappable_size / 1024);
if (mappable_end > ggtt->mappable_end ||
unmappable_base < ggtt->mappable_end ||
unmappable_end > ggtt_end) {
drm_err(&dev_priv->drm, "Invalid ballooning configuration!\n");
return -EINVAL;
}
/* Unmappable graphic memory ballooning */
if (unmappable_base > ggtt->mappable_end) {
ret = vgt_balloon_space(ggtt, &bl_info.space[2],
ggtt->mappable_end, unmappable_base);
if (ret)
goto err;
}
if (unmappable_end < ggtt_end) {
ret = vgt_balloon_space(ggtt, &bl_info.space[3],
unmappable_end, ggtt_end);
if (ret)
goto err_upon_mappable;
}
/* Mappable graphic memory ballooning */
if (mappable_base) {
ret = vgt_balloon_space(ggtt, &bl_info.space[0],
0, mappable_base);
if (ret)
goto err_upon_unmappable;
}
if (mappable_end < ggtt->mappable_end) {
ret = vgt_balloon_space(ggtt, &bl_info.space[1],
mappable_end, ggtt->mappable_end);
if (ret)
goto err_below_mappable;
}
drm_info(&dev_priv->drm, "VGT balloon successfully\n");
return 0;
err_below_mappable:
vgt_deballoon_space(ggtt, &bl_info.space[0]);
err_upon_unmappable:
vgt_deballoon_space(ggtt, &bl_info.space[3]);
err_upon_mappable:
vgt_deballoon_space(ggtt, &bl_info.space[2]);
err:
drm_err(&dev_priv->drm, "VGT balloon fail\n");
return ret;
}
| linux-master | drivers/gpu/drm/i915/i915_vgpu.c |
/*
* Copyright © 2008-2015 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
#include <linux/dma-fence-array.h>
#include <linux/dma-fence-chain.h>
#include <linux/irq_work.h>
#include <linux/prefetch.h>
#include <linux/sched.h>
#include <linux/sched/clock.h>
#include <linux/sched/signal.h>
#include <linux/sched/mm.h>
#include "gem/i915_gem_context.h"
#include "gt/intel_breadcrumbs.h"
#include "gt/intel_context.h"
#include "gt/intel_engine.h"
#include "gt/intel_engine_heartbeat.h"
#include "gt/intel_engine_regs.h"
#include "gt/intel_gpu_commands.h"
#include "gt/intel_reset.h"
#include "gt/intel_ring.h"
#include "gt/intel_rps.h"
#include "i915_active.h"
#include "i915_config.h"
#include "i915_deps.h"
#include "i915_driver.h"
#include "i915_drv.h"
#include "i915_trace.h"
struct execute_cb {
struct irq_work work;
struct i915_sw_fence *fence;
struct i915_request *signal;
};
static struct kmem_cache *slab_requests;
static struct kmem_cache *slab_execute_cbs;
static const char *i915_fence_get_driver_name(struct dma_fence *fence)
{
return dev_name(to_request(fence)->i915->drm.dev);
}
static const char *i915_fence_get_timeline_name(struct dma_fence *fence)
{
const struct i915_gem_context *ctx;
/*
* The timeline struct (as part of the ppgtt underneath a context)
* may be freed when the request is no longer in use by the GPU.
* We could extend the life of a context to beyond that of all
* fences, possibly keeping the hw resource around indefinitely,
* or we just give them a false name. Since
* dma_fence_ops.get_timeline_name is a debug feature, the occasional
* lie seems justifiable.
*/
if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
return "signaled";
ctx = i915_request_gem_context(to_request(fence));
if (!ctx)
return "[" DRIVER_NAME "]";
return ctx->name;
}
static bool i915_fence_signaled(struct dma_fence *fence)
{
return i915_request_completed(to_request(fence));
}
static bool i915_fence_enable_signaling(struct dma_fence *fence)
{
return i915_request_enable_breadcrumb(to_request(fence));
}
static signed long i915_fence_wait(struct dma_fence *fence,
bool interruptible,
signed long timeout)
{
return i915_request_wait_timeout(to_request(fence),
interruptible | I915_WAIT_PRIORITY,
timeout);
}
struct kmem_cache *i915_request_slab_cache(void)
{
return slab_requests;
}
static void i915_fence_release(struct dma_fence *fence)
{
struct i915_request *rq = to_request(fence);
GEM_BUG_ON(rq->guc_prio != GUC_PRIO_INIT &&
rq->guc_prio != GUC_PRIO_FINI);
i915_request_free_capture_list(fetch_and_zero(&rq->capture_list));
if (rq->batch_res) {
i915_vma_resource_put(rq->batch_res);
rq->batch_res = NULL;
}
/*
* The request is put onto a RCU freelist (i.e. the address
* is immediately reused), mark the fences as being freed now.
* Otherwise the debugobjects for the fences are only marked as
* freed when the slab cache itself is freed, and so we would get
* caught trying to reuse dead objects.
*/
i915_sw_fence_fini(&rq->submit);
i915_sw_fence_fini(&rq->semaphore);
/*
* Keep one request on each engine for reserved use under mempressure.
*
* We do not hold a reference to the engine here and so have to be
* very careful in what rq->engine we poke. The virtual engine is
* referenced via the rq->context and we released that ref during
* i915_request_retire(), ergo we must not dereference a virtual
* engine here. Not that we would want to, as the only consumer of
* the reserved engine->request_pool is the power management parking,
* which must-not-fail, and that is only run on the physical engines.
*
* Since the request must have been executed to be have completed,
* we know that it will have been processed by the HW and will
* not be unsubmitted again, so rq->engine and rq->execution_mask
* at this point is stable. rq->execution_mask will be a single
* bit if the last and _only_ engine it could execution on was a
* physical engine, if it's multiple bits then it started on and
* could still be on a virtual engine. Thus if the mask is not a
* power-of-two we assume that rq->engine may still be a virtual
* engine and so a dangling invalid pointer that we cannot dereference
*
* For example, consider the flow of a bonded request through a virtual
* engine. The request is created with a wide engine mask (all engines
* that we might execute on). On processing the bond, the request mask
* is reduced to one or more engines. If the request is subsequently
* bound to a single engine, it will then be constrained to only
* execute on that engine and never returned to the virtual engine
* after timeslicing away, see __unwind_incomplete_requests(). Thus we
* know that if the rq->execution_mask is a single bit, rq->engine
* can be a physical engine with the exact corresponding mask.
*/
if (is_power_of_2(rq->execution_mask) &&
!cmpxchg(&rq->engine->request_pool, NULL, rq))
return;
kmem_cache_free(slab_requests, rq);
}
const struct dma_fence_ops i915_fence_ops = {
.get_driver_name = i915_fence_get_driver_name,
.get_timeline_name = i915_fence_get_timeline_name,
.enable_signaling = i915_fence_enable_signaling,
.signaled = i915_fence_signaled,
.wait = i915_fence_wait,
.release = i915_fence_release,
};
static void irq_execute_cb(struct irq_work *wrk)
{
struct execute_cb *cb = container_of(wrk, typeof(*cb), work);
i915_sw_fence_complete(cb->fence);
kmem_cache_free(slab_execute_cbs, cb);
}
static __always_inline void
__notify_execute_cb(struct i915_request *rq, bool (*fn)(struct irq_work *wrk))
{
struct execute_cb *cb, *cn;
if (llist_empty(&rq->execute_cb))
return;
llist_for_each_entry_safe(cb, cn,
llist_del_all(&rq->execute_cb),
work.node.llist)
fn(&cb->work);
}
static void __notify_execute_cb_irq(struct i915_request *rq)
{
__notify_execute_cb(rq, irq_work_queue);
}
static bool irq_work_imm(struct irq_work *wrk)
{
wrk->func(wrk);
return false;
}
void i915_request_notify_execute_cb_imm(struct i915_request *rq)
{
__notify_execute_cb(rq, irq_work_imm);
}
static void __i915_request_fill(struct i915_request *rq, u8 val)
{
void *vaddr = rq->ring->vaddr;
u32 head;
head = rq->infix;
if (rq->postfix < head) {
memset(vaddr + head, val, rq->ring->size - head);
head = 0;
}
memset(vaddr + head, val, rq->postfix - head);
}
/**
* i915_request_active_engine
* @rq: request to inspect
* @active: pointer in which to return the active engine
*
* Fills the currently active engine to the @active pointer if the request
* is active and still not completed.
*
* Returns true if request was active or false otherwise.
*/
bool
i915_request_active_engine(struct i915_request *rq,
struct intel_engine_cs **active)
{
struct intel_engine_cs *engine, *locked;
bool ret = false;
/*
* Serialise with __i915_request_submit() so that it sees
* is-banned?, or we know the request is already inflight.
*
* Note that rq->engine is unstable, and so we double
* check that we have acquired the lock on the final engine.
*/
locked = READ_ONCE(rq->engine);
spin_lock_irq(&locked->sched_engine->lock);
while (unlikely(locked != (engine = READ_ONCE(rq->engine)))) {
spin_unlock(&locked->sched_engine->lock);
locked = engine;
spin_lock(&locked->sched_engine->lock);
}
if (i915_request_is_active(rq)) {
if (!__i915_request_is_complete(rq))
*active = locked;
ret = true;
}
spin_unlock_irq(&locked->sched_engine->lock);
return ret;
}
static void __rq_init_watchdog(struct i915_request *rq)
{
rq->watchdog.timer.function = NULL;
}
static enum hrtimer_restart __rq_watchdog_expired(struct hrtimer *hrtimer)
{
struct i915_request *rq =
container_of(hrtimer, struct i915_request, watchdog.timer);
struct intel_gt *gt = rq->engine->gt;
if (!i915_request_completed(rq)) {
if (llist_add(&rq->watchdog.link, >->watchdog.list))
queue_work(gt->i915->unordered_wq, >->watchdog.work);
} else {
i915_request_put(rq);
}
return HRTIMER_NORESTART;
}
static void __rq_arm_watchdog(struct i915_request *rq)
{
struct i915_request_watchdog *wdg = &rq->watchdog;
struct intel_context *ce = rq->context;
if (!ce->watchdog.timeout_us)
return;
i915_request_get(rq);
hrtimer_init(&wdg->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
wdg->timer.function = __rq_watchdog_expired;
hrtimer_start_range_ns(&wdg->timer,
ns_to_ktime(ce->watchdog.timeout_us *
NSEC_PER_USEC),
NSEC_PER_MSEC,
HRTIMER_MODE_REL);
}
static void __rq_cancel_watchdog(struct i915_request *rq)
{
struct i915_request_watchdog *wdg = &rq->watchdog;
if (wdg->timer.function && hrtimer_try_to_cancel(&wdg->timer) > 0)
i915_request_put(rq);
}
#if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
/**
* i915_request_free_capture_list - Free a capture list
* @capture: Pointer to the first list item or NULL
*
*/
void i915_request_free_capture_list(struct i915_capture_list *capture)
{
while (capture) {
struct i915_capture_list *next = capture->next;
i915_vma_resource_put(capture->vma_res);
kfree(capture);
capture = next;
}
}
#define assert_capture_list_is_null(_rq) GEM_BUG_ON((_rq)->capture_list)
#define clear_capture_list(_rq) ((_rq)->capture_list = NULL)
#else
#define i915_request_free_capture_list(_a) do {} while (0)
#define assert_capture_list_is_null(_a) do {} while (0)
#define clear_capture_list(_rq) do {} while (0)
#endif
bool i915_request_retire(struct i915_request *rq)
{
if (!__i915_request_is_complete(rq))
return false;
RQ_TRACE(rq, "\n");
GEM_BUG_ON(!i915_sw_fence_signaled(&rq->submit));
trace_i915_request_retire(rq);
i915_request_mark_complete(rq);
__rq_cancel_watchdog(rq);
/*
* We know the GPU must have read the request to have
* sent us the seqno + interrupt, so use the position
* of tail of the request to update the last known position
* of the GPU head.
*
* Note this requires that we are always called in request
* completion order.
*/
GEM_BUG_ON(!list_is_first(&rq->link,
&i915_request_timeline(rq)->requests));
if (IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM))
/* Poison before we release our space in the ring */
__i915_request_fill(rq, POISON_FREE);
rq->ring->head = rq->postfix;
if (!i915_request_signaled(rq)) {
spin_lock_irq(&rq->lock);
dma_fence_signal_locked(&rq->fence);
spin_unlock_irq(&rq->lock);
}
if (test_and_set_bit(I915_FENCE_FLAG_BOOST, &rq->fence.flags))
intel_rps_dec_waiters(&rq->engine->gt->rps);
/*
* We only loosely track inflight requests across preemption,
* and so we may find ourselves attempting to retire a _completed_
* request that we have removed from the HW and put back on a run
* queue.
*
* As we set I915_FENCE_FLAG_ACTIVE on the request, this should be
* after removing the breadcrumb and signaling it, so that we do not
* inadvertently attach the breadcrumb to a completed request.
*/
rq->engine->remove_active_request(rq);
GEM_BUG_ON(!llist_empty(&rq->execute_cb));
__list_del_entry(&rq->link); /* poison neither prev/next (RCU walks) */
intel_context_exit(rq->context);
intel_context_unpin(rq->context);
i915_sched_node_fini(&rq->sched);
i915_request_put(rq);
return true;
}
void i915_request_retire_upto(struct i915_request *rq)
{
struct intel_timeline * const tl = i915_request_timeline(rq);
struct i915_request *tmp;
RQ_TRACE(rq, "\n");
GEM_BUG_ON(!__i915_request_is_complete(rq));
do {
tmp = list_first_entry(&tl->requests, typeof(*tmp), link);
GEM_BUG_ON(!i915_request_completed(tmp));
} while (i915_request_retire(tmp) && tmp != rq);
}
static struct i915_request * const *
__engine_active(struct intel_engine_cs *engine)
{
return READ_ONCE(engine->execlists.active);
}
static bool __request_in_flight(const struct i915_request *signal)
{
struct i915_request * const *port, *rq;
bool inflight = false;
if (!i915_request_is_ready(signal))
return false;
/*
* Even if we have unwound the request, it may still be on
* the GPU (preempt-to-busy). If that request is inside an
* unpreemptible critical section, it will not be removed. Some
* GPU functions may even be stuck waiting for the paired request
* (__await_execution) to be submitted and cannot be preempted
* until the bond is executing.
*
* As we know that there are always preemption points between
* requests, we know that only the currently executing request
* may be still active even though we have cleared the flag.
* However, we can't rely on our tracking of ELSP[0] to know
* which request is currently active and so maybe stuck, as
* the tracking maybe an event behind. Instead assume that
* if the context is still inflight, then it is still active
* even if the active flag has been cleared.
*
* To further complicate matters, if there a pending promotion, the HW
* may either perform a context switch to the second inflight execlists,
* or it may switch to the pending set of execlists. In the case of the
* latter, it may send the ACK and we process the event copying the
* pending[] over top of inflight[], _overwriting_ our *active. Since
* this implies the HW is arbitrating and not struck in *active, we do
* not worry about complete accuracy, but we do require no read/write
* tearing of the pointer [the read of the pointer must be valid, even
* as the array is being overwritten, for which we require the writes
* to avoid tearing.]
*
* Note that the read of *execlists->active may race with the promotion
* of execlists->pending[] to execlists->inflight[], overwritting
* the value at *execlists->active. This is fine. The promotion implies
* that we received an ACK from the HW, and so the context is not
* stuck -- if we do not see ourselves in *active, the inflight status
* is valid. If instead we see ourselves being copied into *active,
* we are inflight and may signal the callback.
*/
if (!intel_context_inflight(signal->context))
return false;
rcu_read_lock();
for (port = __engine_active(signal->engine);
(rq = READ_ONCE(*port)); /* may race with promotion of pending[] */
port++) {
if (rq->context == signal->context) {
inflight = i915_seqno_passed(rq->fence.seqno,
signal->fence.seqno);
break;
}
}
rcu_read_unlock();
return inflight;
}
static int
__await_execution(struct i915_request *rq,
struct i915_request *signal,
gfp_t gfp)
{
struct execute_cb *cb;
if (i915_request_is_active(signal))
return 0;
cb = kmem_cache_alloc(slab_execute_cbs, gfp);
if (!cb)
return -ENOMEM;
cb->fence = &rq->submit;
i915_sw_fence_await(cb->fence);
init_irq_work(&cb->work, irq_execute_cb);
/*
* Register the callback first, then see if the signaler is already
* active. This ensures that if we race with the
* __notify_execute_cb from i915_request_submit() and we are not
* included in that list, we get a second bite of the cherry and
* execute it ourselves. After this point, a future
* i915_request_submit() will notify us.
*
* In i915_request_retire() we set the ACTIVE bit on a completed
* request (then flush the execute_cb). So by registering the
* callback first, then checking the ACTIVE bit, we serialise with
* the completed/retired request.
*/
if (llist_add(&cb->work.node.llist, &signal->execute_cb)) {
if (i915_request_is_active(signal) ||
__request_in_flight(signal))
i915_request_notify_execute_cb_imm(signal);
}
return 0;
}
static bool fatal_error(int error)
{
switch (error) {
case 0: /* not an error! */
case -EAGAIN: /* innocent victim of a GT reset (__i915_request_reset) */
case -ETIMEDOUT: /* waiting for Godot (timer_i915_sw_fence_wake) */
return false;
default:
return true;
}
}
void __i915_request_skip(struct i915_request *rq)
{
GEM_BUG_ON(!fatal_error(rq->fence.error));
if (rq->infix == rq->postfix)
return;
RQ_TRACE(rq, "error: %d\n", rq->fence.error);
/*
* As this request likely depends on state from the lost
* context, clear out all the user operations leaving the
* breadcrumb at the end (so we get the fence notifications).
*/
__i915_request_fill(rq, 0);
rq->infix = rq->postfix;
}
bool i915_request_set_error_once(struct i915_request *rq, int error)
{
int old;
GEM_BUG_ON(!IS_ERR_VALUE((long)error));
if (i915_request_signaled(rq))
return false;
old = READ_ONCE(rq->fence.error);
do {
if (fatal_error(old))
return false;
} while (!try_cmpxchg(&rq->fence.error, &old, error));
return true;
}
struct i915_request *i915_request_mark_eio(struct i915_request *rq)
{
if (__i915_request_is_complete(rq))
return NULL;
GEM_BUG_ON(i915_request_signaled(rq));
/* As soon as the request is completed, it may be retired */
rq = i915_request_get(rq);
i915_request_set_error_once(rq, -EIO);
i915_request_mark_complete(rq);
return rq;
}
bool __i915_request_submit(struct i915_request *request)
{
struct intel_engine_cs *engine = request->engine;
bool result = false;
RQ_TRACE(request, "\n");
GEM_BUG_ON(!irqs_disabled());
lockdep_assert_held(&engine->sched_engine->lock);
/*
* With the advent of preempt-to-busy, we frequently encounter
* requests that we have unsubmitted from HW, but left running
* until the next ack and so have completed in the meantime. On
* resubmission of that completed request, we can skip
* updating the payload, and execlists can even skip submitting
* the request.
*
* We must remove the request from the caller's priority queue,
* and the caller must only call us when the request is in their
* priority queue, under the sched_engine->lock. This ensures that the
* request has *not* yet been retired and we can safely move
* the request into the engine->active.list where it will be
* dropped upon retiring. (Otherwise if resubmit a *retired*
* request, this would be a horrible use-after-free.)
*/
if (__i915_request_is_complete(request)) {
list_del_init(&request->sched.link);
goto active;
}
if (unlikely(!intel_context_is_schedulable(request->context)))
i915_request_set_error_once(request, -EIO);
if (unlikely(fatal_error(request->fence.error)))
__i915_request_skip(request);
/*
* Are we using semaphores when the gpu is already saturated?
*
* Using semaphores incurs a cost in having the GPU poll a
* memory location, busywaiting for it to change. The continual
* memory reads can have a noticeable impact on the rest of the
* system with the extra bus traffic, stalling the cpu as it too
* tries to access memory across the bus (perf stat -e bus-cycles).
*
* If we installed a semaphore on this request and we only submit
* the request after the signaler completed, that indicates the
* system is overloaded and using semaphores at this time only
* increases the amount of work we are doing. If so, we disable
* further use of semaphores until we are idle again, whence we
* optimistically try again.
*/
if (request->sched.semaphores &&
i915_sw_fence_signaled(&request->semaphore))
engine->saturated |= request->sched.semaphores;
engine->emit_fini_breadcrumb(request,
request->ring->vaddr + request->postfix);
trace_i915_request_execute(request);
if (engine->bump_serial)
engine->bump_serial(engine);
else
engine->serial++;
result = true;
GEM_BUG_ON(test_bit(I915_FENCE_FLAG_ACTIVE, &request->fence.flags));
engine->add_active_request(request);
active:
clear_bit(I915_FENCE_FLAG_PQUEUE, &request->fence.flags);
set_bit(I915_FENCE_FLAG_ACTIVE, &request->fence.flags);
/*
* XXX Rollback bonded-execution on __i915_request_unsubmit()?
*
* In the future, perhaps when we have an active time-slicing scheduler,
* it will be interesting to unsubmit parallel execution and remove
* busywaits from the GPU until their master is restarted. This is
* quite hairy, we have to carefully rollback the fence and do a
* preempt-to-idle cycle on the target engine, all the while the
* master execute_cb may refire.
*/
__notify_execute_cb_irq(request);
/* We may be recursing from the signal callback of another i915 fence */
if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &request->fence.flags))
i915_request_enable_breadcrumb(request);
return result;
}
void i915_request_submit(struct i915_request *request)
{
struct intel_engine_cs *engine = request->engine;
unsigned long flags;
/* Will be called from irq-context when using foreign fences. */
spin_lock_irqsave(&engine->sched_engine->lock, flags);
__i915_request_submit(request);
spin_unlock_irqrestore(&engine->sched_engine->lock, flags);
}
void __i915_request_unsubmit(struct i915_request *request)
{
struct intel_engine_cs *engine = request->engine;
/*
* Only unwind in reverse order, required so that the per-context list
* is kept in seqno/ring order.
*/
RQ_TRACE(request, "\n");
GEM_BUG_ON(!irqs_disabled());
lockdep_assert_held(&engine->sched_engine->lock);
/*
* Before we remove this breadcrumb from the signal list, we have
* to ensure that a concurrent dma_fence_enable_signaling() does not
* attach itself. We first mark the request as no longer active and
* make sure that is visible to other cores, and then remove the
* breadcrumb if attached.
*/
GEM_BUG_ON(!test_bit(I915_FENCE_FLAG_ACTIVE, &request->fence.flags));
clear_bit_unlock(I915_FENCE_FLAG_ACTIVE, &request->fence.flags);
if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &request->fence.flags))
i915_request_cancel_breadcrumb(request);
/* We've already spun, don't charge on resubmitting. */
if (request->sched.semaphores && __i915_request_has_started(request))
request->sched.semaphores = 0;
/*
* We don't need to wake_up any waiters on request->execute, they
* will get woken by any other event or us re-adding this request
* to the engine timeline (__i915_request_submit()). The waiters
* should be quite adapt at finding that the request now has a new
* global_seqno to the one they went to sleep on.
*/
}
void i915_request_unsubmit(struct i915_request *request)
{
struct intel_engine_cs *engine = request->engine;
unsigned long flags;
/* Will be called from irq-context when using foreign fences. */
spin_lock_irqsave(&engine->sched_engine->lock, flags);
__i915_request_unsubmit(request);
spin_unlock_irqrestore(&engine->sched_engine->lock, flags);
}
void i915_request_cancel(struct i915_request *rq, int error)
{
if (!i915_request_set_error_once(rq, error))
return;
set_bit(I915_FENCE_FLAG_SENTINEL, &rq->fence.flags);
intel_context_cancel_request(rq->context, rq);
}
static int
submit_notify(struct i915_sw_fence *fence, enum i915_sw_fence_notify state)
{
struct i915_request *request =
container_of(fence, typeof(*request), submit);
switch (state) {
case FENCE_COMPLETE:
trace_i915_request_submit(request);
if (unlikely(fence->error))
i915_request_set_error_once(request, fence->error);
else
__rq_arm_watchdog(request);
/*
* We need to serialize use of the submit_request() callback
* with its hotplugging performed during an emergency
* i915_gem_set_wedged(). We use the RCU mechanism to mark the
* critical section in order to force i915_gem_set_wedged() to
* wait until the submit_request() is completed before
* proceeding.
*/
rcu_read_lock();
request->engine->submit_request(request);
rcu_read_unlock();
break;
case FENCE_FREE:
i915_request_put(request);
break;
}
return NOTIFY_DONE;
}
static int
semaphore_notify(struct i915_sw_fence *fence, enum i915_sw_fence_notify state)
{
struct i915_request *rq = container_of(fence, typeof(*rq), semaphore);
switch (state) {
case FENCE_COMPLETE:
break;
case FENCE_FREE:
i915_request_put(rq);
break;
}
return NOTIFY_DONE;
}
static void retire_requests(struct intel_timeline *tl)
{
struct i915_request *rq, *rn;
list_for_each_entry_safe(rq, rn, &tl->requests, link)
if (!i915_request_retire(rq))
break;
}
static noinline struct i915_request *
request_alloc_slow(struct intel_timeline *tl,
struct i915_request **rsvd,
gfp_t gfp)
{
struct i915_request *rq;
/* If we cannot wait, dip into our reserves */
if (!gfpflags_allow_blocking(gfp)) {
rq = xchg(rsvd, NULL);
if (!rq) /* Use the normal failure path for one final WARN */
goto out;
return rq;
}
if (list_empty(&tl->requests))
goto out;
/* Move our oldest request to the slab-cache (if not in use!) */
rq = list_first_entry(&tl->requests, typeof(*rq), link);
i915_request_retire(rq);
rq = kmem_cache_alloc(slab_requests,
gfp | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
if (rq)
return rq;
/* Ratelimit ourselves to prevent oom from malicious clients */
rq = list_last_entry(&tl->requests, typeof(*rq), link);
cond_synchronize_rcu(rq->rcustate);
/* Retire our old requests in the hope that we free some */
retire_requests(tl);
out:
return kmem_cache_alloc(slab_requests, gfp);
}
static void __i915_request_ctor(void *arg)
{
struct i915_request *rq = arg;
spin_lock_init(&rq->lock);
i915_sched_node_init(&rq->sched);
i915_sw_fence_init(&rq->submit, submit_notify);
i915_sw_fence_init(&rq->semaphore, semaphore_notify);
clear_capture_list(rq);
rq->batch_res = NULL;
init_llist_head(&rq->execute_cb);
}
#if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
#define clear_batch_ptr(_rq) ((_rq)->batch = NULL)
#else
#define clear_batch_ptr(_a) do {} while (0)
#endif
struct i915_request *
__i915_request_create(struct intel_context *ce, gfp_t gfp)
{
struct intel_timeline *tl = ce->timeline;
struct i915_request *rq;
u32 seqno;
int ret;
might_alloc(gfp);
/* Check that the caller provided an already pinned context */
__intel_context_pin(ce);
/*
* Beware: Dragons be flying overhead.
*
* We use RCU to look up requests in flight. The lookups may
* race with the request being allocated from the slab freelist.
* That is the request we are writing to here, may be in the process
* of being read by __i915_active_request_get_rcu(). As such,
* we have to be very careful when overwriting the contents. During
* the RCU lookup, we change chase the request->engine pointer,
* read the request->global_seqno and increment the reference count.
*
* The reference count is incremented atomically. If it is zero,
* the lookup knows the request is unallocated and complete. Otherwise,
* it is either still in use, or has been reallocated and reset
* with dma_fence_init(). This increment is safe for release as we
* check that the request we have a reference to and matches the active
* request.
*
* Before we increment the refcount, we chase the request->engine
* pointer. We must not call kmem_cache_zalloc() or else we set
* that pointer to NULL and cause a crash during the lookup. If
* we see the request is completed (based on the value of the
* old engine and seqno), the lookup is complete and reports NULL.
* If we decide the request is not completed (new engine or seqno),
* then we grab a reference and double check that it is still the
* active request - which it won't be and restart the lookup.
*
* Do not use kmem_cache_zalloc() here!
*/
rq = kmem_cache_alloc(slab_requests,
gfp | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
if (unlikely(!rq)) {
rq = request_alloc_slow(tl, &ce->engine->request_pool, gfp);
if (!rq) {
ret = -ENOMEM;
goto err_unreserve;
}
}
rq->context = ce;
rq->engine = ce->engine;
rq->ring = ce->ring;
rq->execution_mask = ce->engine->mask;
rq->i915 = ce->engine->i915;
ret = intel_timeline_get_seqno(tl, rq, &seqno);
if (ret)
goto err_free;
dma_fence_init(&rq->fence, &i915_fence_ops, &rq->lock,
tl->fence_context, seqno);
RCU_INIT_POINTER(rq->timeline, tl);
rq->hwsp_seqno = tl->hwsp_seqno;
GEM_BUG_ON(__i915_request_is_complete(rq));
rq->rcustate = get_state_synchronize_rcu(); /* acts as smp_mb() */
rq->guc_prio = GUC_PRIO_INIT;
/* We bump the ref for the fence chain */
i915_sw_fence_reinit(&i915_request_get(rq)->submit);
i915_sw_fence_reinit(&i915_request_get(rq)->semaphore);
i915_sched_node_reinit(&rq->sched);
/* No zalloc, everything must be cleared after use */
clear_batch_ptr(rq);
__rq_init_watchdog(rq);
assert_capture_list_is_null(rq);
GEM_BUG_ON(!llist_empty(&rq->execute_cb));
GEM_BUG_ON(rq->batch_res);
/*
* Reserve space in the ring buffer for all the commands required to
* eventually emit this request. This is to guarantee that the
* i915_request_add() call can't fail. Note that the reserve may need
* to be redone if the request is not actually submitted straight
* away, e.g. because a GPU scheduler has deferred it.
*
* Note that due to how we add reserved_space to intel_ring_begin()
* we need to double our request to ensure that if we need to wrap
* around inside i915_request_add() there is sufficient space at
* the beginning of the ring as well.
*/
rq->reserved_space =
2 * rq->engine->emit_fini_breadcrumb_dw * sizeof(u32);
/*
* Record the position of the start of the request so that
* should we detect the updated seqno part-way through the
* GPU processing the request, we never over-estimate the
* position of the head.
*/
rq->head = rq->ring->emit;
ret = rq->engine->request_alloc(rq);
if (ret)
goto err_unwind;
rq->infix = rq->ring->emit; /* end of header; start of user payload */
intel_context_mark_active(ce);
list_add_tail_rcu(&rq->link, &tl->requests);
return rq;
err_unwind:
ce->ring->emit = rq->head;
/* Make sure we didn't add ourselves to external state before freeing */
GEM_BUG_ON(!list_empty(&rq->sched.signalers_list));
GEM_BUG_ON(!list_empty(&rq->sched.waiters_list));
err_free:
kmem_cache_free(slab_requests, rq);
err_unreserve:
intel_context_unpin(ce);
return ERR_PTR(ret);
}
struct i915_request *
i915_request_create(struct intel_context *ce)
{
struct i915_request *rq;
struct intel_timeline *tl;
tl = intel_context_timeline_lock(ce);
if (IS_ERR(tl))
return ERR_CAST(tl);
/* Move our oldest request to the slab-cache (if not in use!) */
rq = list_first_entry(&tl->requests, typeof(*rq), link);
if (!list_is_last(&rq->link, &tl->requests))
i915_request_retire(rq);
intel_context_enter(ce);
rq = __i915_request_create(ce, GFP_KERNEL);
intel_context_exit(ce); /* active reference transferred to request */
if (IS_ERR(rq))
goto err_unlock;
/* Check that we do not interrupt ourselves with a new request */
rq->cookie = lockdep_pin_lock(&tl->mutex);
return rq;
err_unlock:
intel_context_timeline_unlock(tl);
return rq;
}
static int
i915_request_await_start(struct i915_request *rq, struct i915_request *signal)
{
struct dma_fence *fence;
int err;
if (i915_request_timeline(rq) == rcu_access_pointer(signal->timeline))
return 0;
if (i915_request_started(signal))
return 0;
/*
* The caller holds a reference on @signal, but we do not serialise
* against it being retired and removed from the lists.
*
* We do not hold a reference to the request before @signal, and
* so must be very careful to ensure that it is not _recycled_ as
* we follow the link backwards.
*/
fence = NULL;
rcu_read_lock();
do {
struct list_head *pos = READ_ONCE(signal->link.prev);
struct i915_request *prev;
/* Confirm signal has not been retired, the link is valid */
if (unlikely(__i915_request_has_started(signal)))
break;
/* Is signal the earliest request on its timeline? */
if (pos == &rcu_dereference(signal->timeline)->requests)
break;
/*
* Peek at the request before us in the timeline. That
* request will only be valid before it is retired, so
* after acquiring a reference to it, confirm that it is
* still part of the signaler's timeline.
*/
prev = list_entry(pos, typeof(*prev), link);
if (!i915_request_get_rcu(prev))
break;
/* After the strong barrier, confirm prev is still attached */
if (unlikely(READ_ONCE(prev->link.next) != &signal->link)) {
i915_request_put(prev);
break;
}
fence = &prev->fence;
} while (0);
rcu_read_unlock();
if (!fence)
return 0;
err = 0;
if (!intel_timeline_sync_is_later(i915_request_timeline(rq), fence))
err = i915_sw_fence_await_dma_fence(&rq->submit,
fence, 0,
I915_FENCE_GFP);
dma_fence_put(fence);
return err;
}
static intel_engine_mask_t
already_busywaiting(struct i915_request *rq)
{
/*
* Polling a semaphore causes bus traffic, delaying other users of
* both the GPU and CPU. We want to limit the impact on others,
* while taking advantage of early submission to reduce GPU
* latency. Therefore we restrict ourselves to not using more
* than one semaphore from each source, and not using a semaphore
* if we have detected the engine is saturated (i.e. would not be
* submitted early and cause bus traffic reading an already passed
* semaphore).
*
* See the are-we-too-late? check in __i915_request_submit().
*/
return rq->sched.semaphores | READ_ONCE(rq->engine->saturated);
}
static int
__emit_semaphore_wait(struct i915_request *to,
struct i915_request *from,
u32 seqno)
{
const int has_token = GRAPHICS_VER(to->engine->i915) >= 12;
u32 hwsp_offset;
int len, err;
u32 *cs;
GEM_BUG_ON(GRAPHICS_VER(to->engine->i915) < 8);
GEM_BUG_ON(i915_request_has_initial_breadcrumb(to));
/* We need to pin the signaler's HWSP until we are finished reading. */
err = intel_timeline_read_hwsp(from, to, &hwsp_offset);
if (err)
return err;
len = 4;
if (has_token)
len += 2;
cs = intel_ring_begin(to, len);
if (IS_ERR(cs))
return PTR_ERR(cs);
/*
* Using greater-than-or-equal here means we have to worry
* about seqno wraparound. To side step that issue, we swap
* the timeline HWSP upon wrapping, so that everyone listening
* for the old (pre-wrap) values do not see the much smaller
* (post-wrap) values than they were expecting (and so wait
* forever).
*/
*cs++ = (MI_SEMAPHORE_WAIT |
MI_SEMAPHORE_GLOBAL_GTT |
MI_SEMAPHORE_POLL |
MI_SEMAPHORE_SAD_GTE_SDD) +
has_token;
*cs++ = seqno;
*cs++ = hwsp_offset;
*cs++ = 0;
if (has_token) {
*cs++ = 0;
*cs++ = MI_NOOP;
}
intel_ring_advance(to, cs);
return 0;
}
static bool
can_use_semaphore_wait(struct i915_request *to, struct i915_request *from)
{
return to->engine->gt->ggtt == from->engine->gt->ggtt;
}
static int
emit_semaphore_wait(struct i915_request *to,
struct i915_request *from,
gfp_t gfp)
{
const intel_engine_mask_t mask = READ_ONCE(from->engine)->mask;
struct i915_sw_fence *wait = &to->submit;
if (!can_use_semaphore_wait(to, from))
goto await_fence;
if (!intel_context_use_semaphores(to->context))
goto await_fence;
if (i915_request_has_initial_breadcrumb(to))
goto await_fence;
/*
* If this or its dependents are waiting on an external fence
* that may fail catastrophically, then we want to avoid using
* semaphores as they bypass the fence signaling metadata, and we
* lose the fence->error propagation.
*/
if (from->sched.flags & I915_SCHED_HAS_EXTERNAL_CHAIN)
goto await_fence;
/* Just emit the first semaphore we see as request space is limited. */
if (already_busywaiting(to) & mask)
goto await_fence;
if (i915_request_await_start(to, from) < 0)
goto await_fence;
/* Only submit our spinner after the signaler is running! */
if (__await_execution(to, from, gfp))
goto await_fence;
if (__emit_semaphore_wait(to, from, from->fence.seqno))
goto await_fence;
to->sched.semaphores |= mask;
wait = &to->semaphore;
await_fence:
return i915_sw_fence_await_dma_fence(wait,
&from->fence, 0,
I915_FENCE_GFP);
}
static bool intel_timeline_sync_has_start(struct intel_timeline *tl,
struct dma_fence *fence)
{
return __intel_timeline_sync_is_later(tl,
fence->context,
fence->seqno - 1);
}
static int intel_timeline_sync_set_start(struct intel_timeline *tl,
const struct dma_fence *fence)
{
return __intel_timeline_sync_set(tl, fence->context, fence->seqno - 1);
}
static int
__i915_request_await_execution(struct i915_request *to,
struct i915_request *from)
{
int err;
GEM_BUG_ON(intel_context_is_barrier(from->context));
/* Submit both requests at the same time */
err = __await_execution(to, from, I915_FENCE_GFP);
if (err)
return err;
/* Squash repeated depenendices to the same timelines */
if (intel_timeline_sync_has_start(i915_request_timeline(to),
&from->fence))
return 0;
/*
* Wait until the start of this request.
*
* The execution cb fires when we submit the request to HW. But in
* many cases this may be long before the request itself is ready to
* run (consider that we submit 2 requests for the same context, where
* the request of interest is behind an indefinite spinner). So we hook
* up to both to reduce our queues and keep the execution lag minimised
* in the worst case, though we hope that the await_start is elided.
*/
err = i915_request_await_start(to, from);
if (err < 0)
return err;
/*
* Ensure both start together [after all semaphores in signal]
*
* Now that we are queued to the HW at roughly the same time (thanks
* to the execute cb) and are ready to run at roughly the same time
* (thanks to the await start), our signaler may still be indefinitely
* delayed by waiting on a semaphore from a remote engine. If our
* signaler depends on a semaphore, so indirectly do we, and we do not
* want to start our payload until our signaler also starts theirs.
* So we wait.
*
* However, there is also a second condition for which we need to wait
* for the precise start of the signaler. Consider that the signaler
* was submitted in a chain of requests following another context
* (with just an ordinary intra-engine fence dependency between the
* two). In this case the signaler is queued to HW, but not for
* immediate execution, and so we must wait until it reaches the
* active slot.
*/
if (can_use_semaphore_wait(to, from) &&
intel_engine_has_semaphores(to->engine) &&
!i915_request_has_initial_breadcrumb(to)) {
err = __emit_semaphore_wait(to, from, from->fence.seqno - 1);
if (err < 0)
return err;
}
/* Couple the dependency tree for PI on this exposed to->fence */
if (to->engine->sched_engine->schedule) {
err = i915_sched_node_add_dependency(&to->sched,
&from->sched,
I915_DEPENDENCY_WEAK);
if (err < 0)
return err;
}
return intel_timeline_sync_set_start(i915_request_timeline(to),
&from->fence);
}
static void mark_external(struct i915_request *rq)
{
/*
* The downside of using semaphores is that we lose metadata passing
* along the signaling chain. This is particularly nasty when we
* need to pass along a fatal error such as EFAULT or EDEADLK. For
* fatal errors we want to scrub the request before it is executed,
* which means that we cannot preload the request onto HW and have
* it wait upon a semaphore.
*/
rq->sched.flags |= I915_SCHED_HAS_EXTERNAL_CHAIN;
}
static int
__i915_request_await_external(struct i915_request *rq, struct dma_fence *fence)
{
mark_external(rq);
return i915_sw_fence_await_dma_fence(&rq->submit, fence,
i915_fence_context_timeout(rq->i915,
fence->context),
I915_FENCE_GFP);
}
static int
i915_request_await_external(struct i915_request *rq, struct dma_fence *fence)
{
struct dma_fence *iter;
int err = 0;
if (!to_dma_fence_chain(fence))
return __i915_request_await_external(rq, fence);
dma_fence_chain_for_each(iter, fence) {
struct dma_fence_chain *chain = to_dma_fence_chain(iter);
if (!dma_fence_is_i915(chain->fence)) {
err = __i915_request_await_external(rq, iter);
break;
}
err = i915_request_await_dma_fence(rq, chain->fence);
if (err < 0)
break;
}
dma_fence_put(iter);
return err;
}
static inline bool is_parallel_rq(struct i915_request *rq)
{
return intel_context_is_parallel(rq->context);
}
static inline struct intel_context *request_to_parent(struct i915_request *rq)
{
return intel_context_to_parent(rq->context);
}
static bool is_same_parallel_context(struct i915_request *to,
struct i915_request *from)
{
if (is_parallel_rq(to))
return request_to_parent(to) == request_to_parent(from);
return false;
}
int
i915_request_await_execution(struct i915_request *rq,
struct dma_fence *fence)
{
struct dma_fence **child = &fence;
unsigned int nchild = 1;
int ret;
if (dma_fence_is_array(fence)) {
struct dma_fence_array *array = to_dma_fence_array(fence);
/* XXX Error for signal-on-any fence arrays */
child = array->fences;
nchild = array->num_fences;
GEM_BUG_ON(!nchild);
}
do {
fence = *child++;
if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
continue;
if (fence->context == rq->fence.context)
continue;
/*
* We don't squash repeated fence dependencies here as we
* want to run our callback in all cases.
*/
if (dma_fence_is_i915(fence)) {
if (is_same_parallel_context(rq, to_request(fence)))
continue;
ret = __i915_request_await_execution(rq,
to_request(fence));
} else {
ret = i915_request_await_external(rq, fence);
}
if (ret < 0)
return ret;
} while (--nchild);
return 0;
}
static int
await_request_submit(struct i915_request *to, struct i915_request *from)
{
/*
* If we are waiting on a virtual engine, then it may be
* constrained to execute on a single engine *prior* to submission.
* When it is submitted, it will be first submitted to the virtual
* engine and then passed to the physical engine. We cannot allow
* the waiter to be submitted immediately to the physical engine
* as it may then bypass the virtual request.
*/
if (to->engine == READ_ONCE(from->engine))
return i915_sw_fence_await_sw_fence_gfp(&to->submit,
&from->submit,
I915_FENCE_GFP);
else
return __i915_request_await_execution(to, from);
}
static int
i915_request_await_request(struct i915_request *to, struct i915_request *from)
{
int ret;
GEM_BUG_ON(to == from);
GEM_BUG_ON(to->timeline == from->timeline);
if (i915_request_completed(from)) {
i915_sw_fence_set_error_once(&to->submit, from->fence.error);
return 0;
}
if (to->engine->sched_engine->schedule) {
ret = i915_sched_node_add_dependency(&to->sched,
&from->sched,
I915_DEPENDENCY_EXTERNAL);
if (ret < 0)
return ret;
}
if (!intel_engine_uses_guc(to->engine) &&
is_power_of_2(to->execution_mask | READ_ONCE(from->execution_mask)))
ret = await_request_submit(to, from);
else
ret = emit_semaphore_wait(to, from, I915_FENCE_GFP);
if (ret < 0)
return ret;
return 0;
}
int
i915_request_await_dma_fence(struct i915_request *rq, struct dma_fence *fence)
{
struct dma_fence **child = &fence;
unsigned int nchild = 1;
int ret;
/*
* Note that if the fence-array was created in signal-on-any mode,
* we should *not* decompose it into its individual fences. However,
* we don't currently store which mode the fence-array is operating
* in. Fortunately, the only user of signal-on-any is private to
* amdgpu and we should not see any incoming fence-array from
* sync-file being in signal-on-any mode.
*/
if (dma_fence_is_array(fence)) {
struct dma_fence_array *array = to_dma_fence_array(fence);
child = array->fences;
nchild = array->num_fences;
GEM_BUG_ON(!nchild);
}
do {
fence = *child++;
if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
continue;
/*
* Requests on the same timeline are explicitly ordered, along
* with their dependencies, by i915_request_add() which ensures
* that requests are submitted in-order through each ring.
*/
if (fence->context == rq->fence.context)
continue;
/* Squash repeated waits to the same timelines */
if (fence->context &&
intel_timeline_sync_is_later(i915_request_timeline(rq),
fence))
continue;
if (dma_fence_is_i915(fence)) {
if (is_same_parallel_context(rq, to_request(fence)))
continue;
ret = i915_request_await_request(rq, to_request(fence));
} else {
ret = i915_request_await_external(rq, fence);
}
if (ret < 0)
return ret;
/* Record the latest fence used against each timeline */
if (fence->context)
intel_timeline_sync_set(i915_request_timeline(rq),
fence);
} while (--nchild);
return 0;
}
/**
* i915_request_await_deps - set this request to (async) wait upon a struct
* i915_deps dma_fence collection
* @rq: request we are wishing to use
* @deps: The struct i915_deps containing the dependencies.
*
* Returns 0 if successful, negative error code on error.
*/
int i915_request_await_deps(struct i915_request *rq, const struct i915_deps *deps)
{
int i, err;
for (i = 0; i < deps->num_deps; ++i) {
err = i915_request_await_dma_fence(rq, deps->fences[i]);
if (err)
return err;
}
return 0;
}
/**
* i915_request_await_object - set this request to (async) wait upon a bo
* @to: request we are wishing to use
* @obj: object which may be in use on another ring.
* @write: whether the wait is on behalf of a writer
*
* This code is meant to abstract object synchronization with the GPU.
* Conceptually we serialise writes between engines inside the GPU.
* We only allow one engine to write into a buffer at any time, but
* multiple readers. To ensure each has a coherent view of memory, we must:
*
* - If there is an outstanding write request to the object, the new
* request must wait for it to complete (either CPU or in hw, requests
* on the same ring will be naturally ordered).
*
* - If we are a write request (pending_write_domain is set), the new
* request must wait for outstanding read requests to complete.
*
* Returns 0 if successful, else propagates up the lower layer error.
*/
int
i915_request_await_object(struct i915_request *to,
struct drm_i915_gem_object *obj,
bool write)
{
struct dma_resv_iter cursor;
struct dma_fence *fence;
int ret = 0;
dma_resv_for_each_fence(&cursor, obj->base.resv,
dma_resv_usage_rw(write), fence) {
ret = i915_request_await_dma_fence(to, fence);
if (ret)
break;
}
return ret;
}
static void i915_request_await_huc(struct i915_request *rq)
{
struct intel_huc *huc = &rq->context->engine->gt->uc.huc;
/* don't stall kernel submissions! */
if (!rcu_access_pointer(rq->context->gem_context))
return;
if (intel_huc_wait_required(huc))
i915_sw_fence_await_sw_fence(&rq->submit,
&huc->delayed_load.fence,
&rq->hucq);
}
static struct i915_request *
__i915_request_ensure_parallel_ordering(struct i915_request *rq,
struct intel_timeline *timeline)
{
struct i915_request *prev;
GEM_BUG_ON(!is_parallel_rq(rq));
prev = request_to_parent(rq)->parallel.last_rq;
if (prev) {
if (!__i915_request_is_complete(prev)) {
i915_sw_fence_await_sw_fence(&rq->submit,
&prev->submit,
&rq->submitq);
if (rq->engine->sched_engine->schedule)
__i915_sched_node_add_dependency(&rq->sched,
&prev->sched,
&rq->dep,
0);
}
i915_request_put(prev);
}
request_to_parent(rq)->parallel.last_rq = i915_request_get(rq);
/*
* Users have to put a reference potentially got by
* __i915_active_fence_set() to the returned request
* when no longer needed
*/
return to_request(__i915_active_fence_set(&timeline->last_request,
&rq->fence));
}
static struct i915_request *
__i915_request_ensure_ordering(struct i915_request *rq,
struct intel_timeline *timeline)
{
struct i915_request *prev;
GEM_BUG_ON(is_parallel_rq(rq));
prev = to_request(__i915_active_fence_set(&timeline->last_request,
&rq->fence));
if (prev && !__i915_request_is_complete(prev)) {
bool uses_guc = intel_engine_uses_guc(rq->engine);
bool pow2 = is_power_of_2(READ_ONCE(prev->engine)->mask |
rq->engine->mask);
bool same_context = prev->context == rq->context;
/*
* The requests are supposed to be kept in order. However,
* we need to be wary in case the timeline->last_request
* is used as a barrier for external modification to this
* context.
*/
GEM_BUG_ON(same_context &&
i915_seqno_passed(prev->fence.seqno,
rq->fence.seqno));
if ((same_context && uses_guc) || (!uses_guc && pow2))
i915_sw_fence_await_sw_fence(&rq->submit,
&prev->submit,
&rq->submitq);
else
__i915_sw_fence_await_dma_fence(&rq->submit,
&prev->fence,
&rq->dmaq);
if (rq->engine->sched_engine->schedule)
__i915_sched_node_add_dependency(&rq->sched,
&prev->sched,
&rq->dep,
0);
}
/*
* Users have to put the reference to prev potentially got
* by __i915_active_fence_set() when no longer needed
*/
return prev;
}
static struct i915_request *
__i915_request_add_to_timeline(struct i915_request *rq)
{
struct intel_timeline *timeline = i915_request_timeline(rq);
struct i915_request *prev;
/*
* Media workloads may require HuC, so stall them until HuC loading is
* complete. Note that HuC not being loaded when a user submission
* arrives can only happen when HuC is loaded via GSC and in that case
* we still expect the window between us starting to accept submissions
* and HuC loading completion to be small (a few hundred ms).
*/
if (rq->engine->class == VIDEO_DECODE_CLASS)
i915_request_await_huc(rq);
/*
* Dependency tracking and request ordering along the timeline
* is special cased so that we can eliminate redundant ordering
* operations while building the request (we know that the timeline
* itself is ordered, and here we guarantee it).
*
* As we know we will need to emit tracking along the timeline,
* we embed the hooks into our request struct -- at the cost of
* having to have specialised no-allocation interfaces (which will
* be beneficial elsewhere).
*
* A second benefit to open-coding i915_request_await_request is
* that we can apply a slight variant of the rules specialised
* for timelines that jump between engines (such as virtual engines).
* If we consider the case of virtual engine, we must emit a dma-fence
* to prevent scheduling of the second request until the first is
* complete (to maximise our greedy late load balancing) and this
* precludes optimising to use semaphores serialisation of a single
* timeline across engines.
*
* We do not order parallel submission requests on the timeline as each
* parallel submission context has its own timeline and the ordering
* rules for parallel requests are that they must be submitted in the
* order received from the execbuf IOCTL. So rather than using the
* timeline we store a pointer to last request submitted in the
* relationship in the gem context and insert a submission fence
* between that request and request passed into this function or
* alternatively we use completion fence if gem context has a single
* timeline and this is the first submission of an execbuf IOCTL.
*/
if (likely(!is_parallel_rq(rq)))
prev = __i915_request_ensure_ordering(rq, timeline);
else
prev = __i915_request_ensure_parallel_ordering(rq, timeline);
if (prev)
i915_request_put(prev);
/*
* Make sure that no request gazumped us - if it was allocated after
* our i915_request_alloc() and called __i915_request_add() before
* us, the timeline will hold its seqno which is later than ours.
*/
GEM_BUG_ON(timeline->seqno != rq->fence.seqno);
return prev;
}
/*
* NB: This function is not allowed to fail. Doing so would mean the the
* request is not being tracked for completion but the work itself is
* going to happen on the hardware. This would be a Bad Thing(tm).
*/
struct i915_request *__i915_request_commit(struct i915_request *rq)
{
struct intel_engine_cs *engine = rq->engine;
struct intel_ring *ring = rq->ring;
u32 *cs;
RQ_TRACE(rq, "\n");
/*
* To ensure that this call will not fail, space for its emissions
* should already have been reserved in the ring buffer. Let the ring
* know that it is time to use that space up.
*/
GEM_BUG_ON(rq->reserved_space > ring->space);
rq->reserved_space = 0;
rq->emitted_jiffies = jiffies;
/*
* Record the position of the start of the breadcrumb so that
* should we detect the updated seqno part-way through the
* GPU processing the request, we never over-estimate the
* position of the ring's HEAD.
*/
cs = intel_ring_begin(rq, engine->emit_fini_breadcrumb_dw);
GEM_BUG_ON(IS_ERR(cs));
rq->postfix = intel_ring_offset(rq, cs);
return __i915_request_add_to_timeline(rq);
}
void __i915_request_queue_bh(struct i915_request *rq)
{
i915_sw_fence_commit(&rq->semaphore);
i915_sw_fence_commit(&rq->submit);
}
void __i915_request_queue(struct i915_request *rq,
const struct i915_sched_attr *attr)
{
/*
* Let the backend know a new request has arrived that may need
* to adjust the existing execution schedule due to a high priority
* request - i.e. we may want to preempt the current request in order
* to run a high priority dependency chain *before* we can execute this
* request.
*
* This is called before the request is ready to run so that we can
* decide whether to preempt the entire chain so that it is ready to
* run at the earliest possible convenience.
*/
if (attr && rq->engine->sched_engine->schedule)
rq->engine->sched_engine->schedule(rq, attr);
local_bh_disable();
__i915_request_queue_bh(rq);
local_bh_enable(); /* kick tasklets */
}
void i915_request_add(struct i915_request *rq)
{
struct intel_timeline * const tl = i915_request_timeline(rq);
struct i915_sched_attr attr = {};
struct i915_gem_context *ctx;
lockdep_assert_held(&tl->mutex);
lockdep_unpin_lock(&tl->mutex, rq->cookie);
trace_i915_request_add(rq);
__i915_request_commit(rq);
/* XXX placeholder for selftests */
rcu_read_lock();
ctx = rcu_dereference(rq->context->gem_context);
if (ctx)
attr = ctx->sched;
rcu_read_unlock();
__i915_request_queue(rq, &attr);
mutex_unlock(&tl->mutex);
}
static unsigned long local_clock_ns(unsigned int *cpu)
{
unsigned long t;
/*
* Cheaply and approximately convert from nanoseconds to microseconds.
* The result and subsequent calculations are also defined in the same
* approximate microseconds units. The principal source of timing
* error here is from the simple truncation.
*
* Note that local_clock() is only defined wrt to the current CPU;
* the comparisons are no longer valid if we switch CPUs. Instead of
* blocking preemption for the entire busywait, we can detect the CPU
* switch and use that as indicator of system load and a reason to
* stop busywaiting, see busywait_stop().
*/
*cpu = get_cpu();
t = local_clock();
put_cpu();
return t;
}
static bool busywait_stop(unsigned long timeout, unsigned int cpu)
{
unsigned int this_cpu;
if (time_after(local_clock_ns(&this_cpu), timeout))
return true;
return this_cpu != cpu;
}
static bool __i915_spin_request(struct i915_request * const rq, int state)
{
unsigned long timeout_ns;
unsigned int cpu;
/*
* Only wait for the request if we know it is likely to complete.
*
* We don't track the timestamps around requests, nor the average
* request length, so we do not have a good indicator that this
* request will complete within the timeout. What we do know is the
* order in which requests are executed by the context and so we can
* tell if the request has been started. If the request is not even
* running yet, it is a fair assumption that it will not complete
* within our relatively short timeout.
*/
if (!i915_request_is_running(rq))
return false;
/*
* When waiting for high frequency requests, e.g. during synchronous
* rendering split between the CPU and GPU, the finite amount of time
* required to set up the irq and wait upon it limits the response
* rate. By busywaiting on the request completion for a short while we
* can service the high frequency waits as quick as possible. However,
* if it is a slow request, we want to sleep as quickly as possible.
* The tradeoff between waiting and sleeping is roughly the time it
* takes to sleep on a request, on the order of a microsecond.
*/
timeout_ns = READ_ONCE(rq->engine->props.max_busywait_duration_ns);
timeout_ns += local_clock_ns(&cpu);
do {
if (dma_fence_is_signaled(&rq->fence))
return true;
if (signal_pending_state(state, current))
break;
if (busywait_stop(timeout_ns, cpu))
break;
cpu_relax();
} while (!need_resched());
return false;
}
struct request_wait {
struct dma_fence_cb cb;
struct task_struct *tsk;
};
static void request_wait_wake(struct dma_fence *fence, struct dma_fence_cb *cb)
{
struct request_wait *wait = container_of(cb, typeof(*wait), cb);
wake_up_process(fetch_and_zero(&wait->tsk));
}
/**
* i915_request_wait_timeout - wait until execution of request has finished
* @rq: the request to wait upon
* @flags: how to wait
* @timeout: how long to wait in jiffies
*
* i915_request_wait_timeout() waits for the request to be completed, for a
* maximum of @timeout jiffies (with MAX_SCHEDULE_TIMEOUT implying an
* unbounded wait).
*
* Returns the remaining time (in jiffies) if the request completed, which may
* be zero if the request is unfinished after the timeout expires.
* If the timeout is 0, it will return 1 if the fence is signaled.
*
* May return -EINTR is called with I915_WAIT_INTERRUPTIBLE and a signal is
* pending before the request completes.
*
* NOTE: This function has the same wait semantics as dma-fence.
*/
long i915_request_wait_timeout(struct i915_request *rq,
unsigned int flags,
long timeout)
{
const int state = flags & I915_WAIT_INTERRUPTIBLE ?
TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE;
struct request_wait wait;
might_sleep();
GEM_BUG_ON(timeout < 0);
if (dma_fence_is_signaled(&rq->fence))
return timeout ?: 1;
if (!timeout)
return -ETIME;
trace_i915_request_wait_begin(rq, flags);
/*
* We must never wait on the GPU while holding a lock as we
* may need to perform a GPU reset. So while we don't need to
* serialise wait/reset with an explicit lock, we do want
* lockdep to detect potential dependency cycles.
*/
mutex_acquire(&rq->engine->gt->reset.mutex.dep_map, 0, 0, _THIS_IP_);
/*
* Optimistic spin before touching IRQs.
*
* We may use a rather large value here to offset the penalty of
* switching away from the active task. Frequently, the client will
* wait upon an old swapbuffer to throttle itself to remain within a
* frame of the gpu. If the client is running in lockstep with the gpu,
* then it should not be waiting long at all, and a sleep now will incur
* extra scheduler latency in producing the next frame. To try to
* avoid adding the cost of enabling/disabling the interrupt to the
* short wait, we first spin to see if the request would have completed
* in the time taken to setup the interrupt.
*
* We need upto 5us to enable the irq, and upto 20us to hide the
* scheduler latency of a context switch, ignoring the secondary
* impacts from a context switch such as cache eviction.
*
* The scheme used for low-latency IO is called "hybrid interrupt
* polling". The suggestion there is to sleep until just before you
* expect to be woken by the device interrupt and then poll for its
* completion. That requires having a good predictor for the request
* duration, which we currently lack.
*/
if (CONFIG_DRM_I915_MAX_REQUEST_BUSYWAIT &&
__i915_spin_request(rq, state))
goto out;
/*
* This client is about to stall waiting for the GPU. In many cases
* this is undesirable and limits the throughput of the system, as
* many clients cannot continue processing user input/output whilst
* blocked. RPS autotuning may take tens of milliseconds to respond
* to the GPU load and thus incurs additional latency for the client.
* We can circumvent that by promoting the GPU frequency to maximum
* before we sleep. This makes the GPU throttle up much more quickly
* (good for benchmarks and user experience, e.g. window animations),
* but at a cost of spending more power processing the workload
* (bad for battery).
*/
if (flags & I915_WAIT_PRIORITY && !i915_request_started(rq))
intel_rps_boost(rq);
wait.tsk = current;
if (dma_fence_add_callback(&rq->fence, &wait.cb, request_wait_wake))
goto out;
/*
* Flush the submission tasklet, but only if it may help this request.
*
* We sometimes experience some latency between the HW interrupts and
* tasklet execution (mostly due to ksoftirqd latency, but it can also
* be due to lazy CS events), so lets run the tasklet manually if there
* is a chance it may submit this request. If the request is not ready
* to run, as it is waiting for other fences to be signaled, flushing
* the tasklet is busy work without any advantage for this client.
*
* If the HW is being lazy, this is the last chance before we go to
* sleep to catch any pending events. We will check periodically in
* the heartbeat to flush the submission tasklets as a last resort
* for unhappy HW.
*/
if (i915_request_is_ready(rq))
__intel_engine_flush_submission(rq->engine, false);
for (;;) {
set_current_state(state);
if (dma_fence_is_signaled(&rq->fence))
break;
if (signal_pending_state(state, current)) {
timeout = -ERESTARTSYS;
break;
}
if (!timeout) {
timeout = -ETIME;
break;
}
timeout = io_schedule_timeout(timeout);
}
__set_current_state(TASK_RUNNING);
if (READ_ONCE(wait.tsk))
dma_fence_remove_callback(&rq->fence, &wait.cb);
GEM_BUG_ON(!list_empty(&wait.cb.node));
out:
mutex_release(&rq->engine->gt->reset.mutex.dep_map, _THIS_IP_);
trace_i915_request_wait_end(rq);
return timeout;
}
/**
* i915_request_wait - wait until execution of request has finished
* @rq: the request to wait upon
* @flags: how to wait
* @timeout: how long to wait in jiffies
*
* i915_request_wait() waits for the request to be completed, for a
* maximum of @timeout jiffies (with MAX_SCHEDULE_TIMEOUT implying an
* unbounded wait).
*
* Returns the remaining time (in jiffies) if the request completed, which may
* be zero or -ETIME if the request is unfinished after the timeout expires.
* May return -EINTR is called with I915_WAIT_INTERRUPTIBLE and a signal is
* pending before the request completes.
*
* NOTE: This function behaves differently from dma-fence wait semantics for
* timeout = 0. It returns 0 on success, and -ETIME if not signaled.
*/
long i915_request_wait(struct i915_request *rq,
unsigned int flags,
long timeout)
{
long ret = i915_request_wait_timeout(rq, flags, timeout);
if (!ret)
return -ETIME;
if (ret > 0 && !timeout)
return 0;
return ret;
}
static int print_sched_attr(const struct i915_sched_attr *attr,
char *buf, int x, int len)
{
if (attr->priority == I915_PRIORITY_INVALID)
return x;
x += snprintf(buf + x, len - x,
" prio=%d", attr->priority);
return x;
}
static char queue_status(const struct i915_request *rq)
{
if (i915_request_is_active(rq))
return 'E';
if (i915_request_is_ready(rq))
return intel_engine_is_virtual(rq->engine) ? 'V' : 'R';
return 'U';
}
static const char *run_status(const struct i915_request *rq)
{
if (__i915_request_is_complete(rq))
return "!";
if (__i915_request_has_started(rq))
return "*";
if (!i915_sw_fence_signaled(&rq->semaphore))
return "&";
return "";
}
static const char *fence_status(const struct i915_request *rq)
{
if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &rq->fence.flags))
return "+";
if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &rq->fence.flags))
return "-";
return "";
}
void i915_request_show(struct drm_printer *m,
const struct i915_request *rq,
const char *prefix,
int indent)
{
const char *name = rq->fence.ops->get_timeline_name((struct dma_fence *)&rq->fence);
char buf[80] = "";
int x = 0;
/*
* The prefix is used to show the queue status, for which we use
* the following flags:
*
* U [Unready]
* - initial status upon being submitted by the user
*
* - the request is not ready for execution as it is waiting
* for external fences
*
* R [Ready]
* - all fences the request was waiting on have been signaled,
* and the request is now ready for execution and will be
* in a backend queue
*
* - a ready request may still need to wait on semaphores
* [internal fences]
*
* V [Ready/virtual]
* - same as ready, but queued over multiple backends
*
* E [Executing]
* - the request has been transferred from the backend queue and
* submitted for execution on HW
*
* - a completed request may still be regarded as executing, its
* status may not be updated until it is retired and removed
* from the lists
*/
x = print_sched_attr(&rq->sched.attr, buf, x, sizeof(buf));
drm_printf(m, "%s%.*s%c %llx:%lld%s%s %s @ %dms: %s\n",
prefix, indent, " ",
queue_status(rq),
rq->fence.context, rq->fence.seqno,
run_status(rq),
fence_status(rq),
buf,
jiffies_to_msecs(jiffies - rq->emitted_jiffies),
name);
}
static bool engine_match_ring(struct intel_engine_cs *engine, struct i915_request *rq)
{
u32 ring = ENGINE_READ(engine, RING_START);
return ring == i915_ggtt_offset(rq->ring->vma);
}
static bool match_ring(struct i915_request *rq)
{
struct intel_engine_cs *engine;
bool found;
int i;
if (!intel_engine_is_virtual(rq->engine))
return engine_match_ring(rq->engine, rq);
found = false;
i = 0;
while ((engine = intel_engine_get_sibling(rq->engine, i++))) {
found = engine_match_ring(engine, rq);
if (found)
break;
}
return found;
}
enum i915_request_state i915_test_request_state(struct i915_request *rq)
{
if (i915_request_completed(rq))
return I915_REQUEST_COMPLETE;
if (!i915_request_started(rq))
return I915_REQUEST_PENDING;
if (match_ring(rq))
return I915_REQUEST_ACTIVE;
return I915_REQUEST_QUEUED;
}
#if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
#include "selftests/mock_request.c"
#include "selftests/i915_request.c"
#endif
void i915_request_module_exit(void)
{
kmem_cache_destroy(slab_execute_cbs);
kmem_cache_destroy(slab_requests);
}
int __init i915_request_module_init(void)
{
slab_requests =
kmem_cache_create("i915_request",
sizeof(struct i915_request),
__alignof__(struct i915_request),
SLAB_HWCACHE_ALIGN |
SLAB_RECLAIM_ACCOUNT |
SLAB_TYPESAFE_BY_RCU,
__i915_request_ctor);
if (!slab_requests)
return -ENOMEM;
slab_execute_cbs = KMEM_CACHE(execute_cb,
SLAB_HWCACHE_ALIGN |
SLAB_RECLAIM_ACCOUNT |
SLAB_TYPESAFE_BY_RCU);
if (!slab_execute_cbs)
goto err_requests;
return 0;
err_requests:
kmem_cache_destroy(slab_requests);
return -ENOMEM;
}
| linux-master | drivers/gpu/drm/i915/i915_request.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2013-2021 Intel Corporation
*/
#include "i915_drv.h"
#include "i915_iosf_mbi.h"
#include "i915_reg.h"
#include "vlv_sideband.h"
#include "display/intel_dpio_phy.h"
#include "display/intel_display_types.h"
/*
* IOSF sideband, see VLV2_SidebandMsg_HAS.docx and
* VLV_VLV2_PUNIT_HAS_0.8.docx
*/
/* Standard MMIO read, non-posted */
#define SB_MRD_NP 0x00
/* Standard MMIO write, non-posted */
#define SB_MWR_NP 0x01
/* Private register read, double-word addressing, non-posted */
#define SB_CRRDDA_NP 0x06
/* Private register write, double-word addressing, non-posted */
#define SB_CRWRDA_NP 0x07
static void ping(void *info)
{
}
static void __vlv_punit_get(struct drm_i915_private *i915)
{
iosf_mbi_punit_acquire();
/*
* Prevent the cpu from sleeping while we use this sideband, otherwise
* the punit may cause a machine hang. The issue appears to be isolated
* with changing the power state of the CPU package while changing
* the power state via the punit, and we have only observed it
* reliably on 4-core Baytail systems suggesting the issue is in the
* power delivery mechanism and likely to be board/function
* specific. Hence we presume the workaround needs only be applied
* to the Valleyview P-unit and not all sideband communications.
*/
if (IS_VALLEYVIEW(i915)) {
cpu_latency_qos_update_request(&i915->sb_qos, 0);
on_each_cpu(ping, NULL, 1);
}
}
static void __vlv_punit_put(struct drm_i915_private *i915)
{
if (IS_VALLEYVIEW(i915))
cpu_latency_qos_update_request(&i915->sb_qos,
PM_QOS_DEFAULT_VALUE);
iosf_mbi_punit_release();
}
void vlv_iosf_sb_get(struct drm_i915_private *i915, unsigned long ports)
{
if (ports & BIT(VLV_IOSF_SB_PUNIT))
__vlv_punit_get(i915);
mutex_lock(&i915->sb_lock);
}
void vlv_iosf_sb_put(struct drm_i915_private *i915, unsigned long ports)
{
mutex_unlock(&i915->sb_lock);
if (ports & BIT(VLV_IOSF_SB_PUNIT))
__vlv_punit_put(i915);
}
static int vlv_sideband_rw(struct drm_i915_private *i915,
u32 devfn, u32 port, u32 opcode,
u32 addr, u32 *val)
{
struct intel_uncore *uncore = &i915->uncore;
const bool is_read = (opcode == SB_MRD_NP || opcode == SB_CRRDDA_NP);
int err;
lockdep_assert_held(&i915->sb_lock);
if (port == IOSF_PORT_PUNIT)
iosf_mbi_assert_punit_acquired();
/* Flush the previous comms, just in case it failed last time. */
if (intel_wait_for_register(uncore,
VLV_IOSF_DOORBELL_REQ, IOSF_SB_BUSY, 0,
5)) {
drm_dbg(&i915->drm, "IOSF sideband idle wait (%s) timed out\n",
is_read ? "read" : "write");
return -EAGAIN;
}
preempt_disable();
intel_uncore_write_fw(uncore, VLV_IOSF_ADDR, addr);
intel_uncore_write_fw(uncore, VLV_IOSF_DATA, is_read ? 0 : *val);
intel_uncore_write_fw(uncore, VLV_IOSF_DOORBELL_REQ,
(devfn << IOSF_DEVFN_SHIFT) |
(opcode << IOSF_OPCODE_SHIFT) |
(port << IOSF_PORT_SHIFT) |
(0xf << IOSF_BYTE_ENABLES_SHIFT) |
(0 << IOSF_BAR_SHIFT) |
IOSF_SB_BUSY);
if (__intel_wait_for_register_fw(uncore,
VLV_IOSF_DOORBELL_REQ, IOSF_SB_BUSY, 0,
10000, 0, NULL) == 0) {
if (is_read)
*val = intel_uncore_read_fw(uncore, VLV_IOSF_DATA);
err = 0;
} else {
drm_dbg(&i915->drm, "IOSF sideband finish wait (%s) timed out\n",
is_read ? "read" : "write");
err = -ETIMEDOUT;
}
preempt_enable();
return err;
}
u32 vlv_punit_read(struct drm_i915_private *i915, u32 addr)
{
u32 val = 0;
vlv_sideband_rw(i915, PCI_DEVFN(0, 0), IOSF_PORT_PUNIT,
SB_CRRDDA_NP, addr, &val);
return val;
}
int vlv_punit_write(struct drm_i915_private *i915, u32 addr, u32 val)
{
return vlv_sideband_rw(i915, PCI_DEVFN(0, 0), IOSF_PORT_PUNIT,
SB_CRWRDA_NP, addr, &val);
}
u32 vlv_bunit_read(struct drm_i915_private *i915, u32 reg)
{
u32 val = 0;
vlv_sideband_rw(i915, PCI_DEVFN(0, 0), IOSF_PORT_BUNIT,
SB_CRRDDA_NP, reg, &val);
return val;
}
void vlv_bunit_write(struct drm_i915_private *i915, u32 reg, u32 val)
{
vlv_sideband_rw(i915, PCI_DEVFN(0, 0), IOSF_PORT_BUNIT,
SB_CRWRDA_NP, reg, &val);
}
u32 vlv_nc_read(struct drm_i915_private *i915, u8 addr)
{
u32 val = 0;
vlv_sideband_rw(i915, PCI_DEVFN(0, 0), IOSF_PORT_NC,
SB_CRRDDA_NP, addr, &val);
return val;
}
u32 vlv_iosf_sb_read(struct drm_i915_private *i915, u8 port, u32 reg)
{
u32 val = 0;
vlv_sideband_rw(i915, PCI_DEVFN(0, 0), port,
SB_CRRDDA_NP, reg, &val);
return val;
}
void vlv_iosf_sb_write(struct drm_i915_private *i915,
u8 port, u32 reg, u32 val)
{
vlv_sideband_rw(i915, PCI_DEVFN(0, 0), port,
SB_CRWRDA_NP, reg, &val);
}
u32 vlv_cck_read(struct drm_i915_private *i915, u32 reg)
{
u32 val = 0;
vlv_sideband_rw(i915, PCI_DEVFN(0, 0), IOSF_PORT_CCK,
SB_CRRDDA_NP, reg, &val);
return val;
}
void vlv_cck_write(struct drm_i915_private *i915, u32 reg, u32 val)
{
vlv_sideband_rw(i915, PCI_DEVFN(0, 0), IOSF_PORT_CCK,
SB_CRWRDA_NP, reg, &val);
}
u32 vlv_ccu_read(struct drm_i915_private *i915, u32 reg)
{
u32 val = 0;
vlv_sideband_rw(i915, PCI_DEVFN(0, 0), IOSF_PORT_CCU,
SB_CRRDDA_NP, reg, &val);
return val;
}
void vlv_ccu_write(struct drm_i915_private *i915, u32 reg, u32 val)
{
vlv_sideband_rw(i915, PCI_DEVFN(0, 0), IOSF_PORT_CCU,
SB_CRWRDA_NP, reg, &val);
}
static u32 vlv_dpio_phy_iosf_port(struct drm_i915_private *i915, enum dpio_phy phy)
{
/*
* IOSF_PORT_DPIO: VLV x2 PHY (DP/HDMI B and C), CHV x1 PHY (DP/HDMI D)
* IOSF_PORT_DPIO_2: CHV x2 PHY (DP/HDMI B and C)
*/
if (IS_CHERRYVIEW(i915))
return phy == DPIO_PHY0 ? IOSF_PORT_DPIO_2 : IOSF_PORT_DPIO;
else
return IOSF_PORT_DPIO;
}
u32 vlv_dpio_read(struct drm_i915_private *i915, enum pipe pipe, int reg)
{
u32 port = vlv_dpio_phy_iosf_port(i915, DPIO_PHY(pipe));
u32 val = 0;
vlv_sideband_rw(i915, DPIO_DEVFN, port, SB_MRD_NP, reg, &val);
/*
* FIXME: There might be some registers where all 1's is a valid value,
* so ideally we should check the register offset instead...
*/
drm_WARN(&i915->drm, val == 0xffffffff,
"DPIO read pipe %c reg 0x%x == 0x%x\n",
pipe_name(pipe), reg, val);
return val;
}
void vlv_dpio_write(struct drm_i915_private *i915,
enum pipe pipe, int reg, u32 val)
{
u32 port = vlv_dpio_phy_iosf_port(i915, DPIO_PHY(pipe));
vlv_sideband_rw(i915, DPIO_DEVFN, port, SB_MWR_NP, reg, &val);
}
u32 vlv_flisdsi_read(struct drm_i915_private *i915, u32 reg)
{
u32 val = 0;
vlv_sideband_rw(i915, DPIO_DEVFN, IOSF_PORT_FLISDSI, SB_CRRDDA_NP,
reg, &val);
return val;
}
void vlv_flisdsi_write(struct drm_i915_private *i915, u32 reg, u32 val)
{
vlv_sideband_rw(i915, DPIO_DEVFN, IOSF_PORT_FLISDSI, SB_CRWRDA_NP,
reg, &val);
}
| linux-master | drivers/gpu/drm/i915/vlv_sideband.c |
/*
* Copyright © 2017 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
#include <linux/slab.h>
#include "i915_syncmap.h"
#include "i915_gem.h" /* GEM_BUG_ON() */
#include "i915_selftest.h"
#define SHIFT ilog2(KSYNCMAP)
#define MASK (KSYNCMAP - 1)
/*
* struct i915_syncmap is a layer of a radixtree that maps a u64 fence
* context id to the last u32 fence seqno waited upon from that context.
* Unlike lib/radixtree it uses a parent pointer that allows traversal back to
* the root. This allows us to access the whole tree via a single pointer
* to the most recently used layer. We expect fence contexts to be dense
* and most reuse to be on the same i915_gem_context but on neighbouring
* engines (i.e. on adjacent contexts) and reuse the same leaf, a very
* effective lookup cache. If the new lookup is not on the same leaf, we
* expect it to be on the neighbouring branch.
*
* A leaf holds an array of u32 seqno, and has height 0. The bitmap field
* allows us to store whether a particular seqno is valid (i.e. allows us
* to distinguish unset from 0).
*
* A branch holds an array of layer pointers, and has height > 0, and always
* has at least 2 layers (either branches or leaves) below it.
*
* For example,
* for x in
* 0 1 2 0x10 0x11 0x200 0x201
* 0x500000 0x500001 0x503000 0x503001
* 0xE<<60:
* i915_syncmap_set(&sync, x, lower_32_bits(x));
* will build a tree like:
* 0xXXXXXXXXXXXXXXXX
* 0-> 0x0000000000XXXXXX
* | 0-> 0x0000000000000XXX
* | | 0-> 0x00000000000000XX
* | | | 0-> 0x000000000000000X 0:0, 1:1, 2:2
* | | | 1-> 0x000000000000001X 0:10, 1:11
* | | 2-> 0x000000000000020X 0:200, 1:201
* | 5-> 0x000000000050XXXX
* | 0-> 0x000000000050000X 0:500000, 1:500001
* | 3-> 0x000000000050300X 0:503000, 1:503001
* e-> 0xe00000000000000X e:e
*/
struct i915_syncmap {
u64 prefix;
unsigned int height;
unsigned int bitmap;
struct i915_syncmap *parent;
/*
* Following this header is an array of either seqno or child pointers:
* union {
* u32 seqno[KSYNCMAP];
* struct i915_syncmap *child[KSYNCMAP];
* };
*/
};
/**
* i915_syncmap_init -- initialise the #i915_syncmap
* @root: pointer to the #i915_syncmap
*/
void i915_syncmap_init(struct i915_syncmap **root)
{
BUILD_BUG_ON_NOT_POWER_OF_2(KSYNCMAP);
BUILD_BUG_ON_NOT_POWER_OF_2(SHIFT);
BUILD_BUG_ON(KSYNCMAP > BITS_PER_TYPE((*root)->bitmap));
*root = NULL;
}
static inline u32 *__sync_seqno(struct i915_syncmap *p)
{
GEM_BUG_ON(p->height);
return (u32 *)(p + 1);
}
static inline struct i915_syncmap **__sync_child(struct i915_syncmap *p)
{
GEM_BUG_ON(!p->height);
return (struct i915_syncmap **)(p + 1);
}
static inline unsigned int
__sync_branch_idx(const struct i915_syncmap *p, u64 id)
{
return (id >> p->height) & MASK;
}
static inline unsigned int
__sync_leaf_idx(const struct i915_syncmap *p, u64 id)
{
GEM_BUG_ON(p->height);
return id & MASK;
}
static inline u64 __sync_branch_prefix(const struct i915_syncmap *p, u64 id)
{
return id >> p->height >> SHIFT;
}
static inline u64 __sync_leaf_prefix(const struct i915_syncmap *p, u64 id)
{
GEM_BUG_ON(p->height);
return id >> SHIFT;
}
static inline bool seqno_later(u32 a, u32 b)
{
return (s32)(a - b) >= 0;
}
/**
* i915_syncmap_is_later -- compare against the last know sync point
* @root: pointer to the #i915_syncmap
* @id: the context id (other timeline) we are synchronising to
* @seqno: the sequence number along the other timeline
*
* If we have already synchronised this @root timeline with another (@id) then
* we can omit any repeated or earlier synchronisation requests. If the two
* timelines are already coupled, we can also omit the dependency between the
* two as that is already known via the timeline.
*
* Returns true if the two timelines are already synchronised wrt to @seqno,
* false if not and the synchronisation must be emitted.
*/
bool i915_syncmap_is_later(struct i915_syncmap **root, u64 id, u32 seqno)
{
struct i915_syncmap *p;
unsigned int idx;
p = *root;
if (!p)
return false;
if (likely(__sync_leaf_prefix(p, id) == p->prefix))
goto found;
/* First climb the tree back to a parent branch */
do {
p = p->parent;
if (!p)
return false;
if (__sync_branch_prefix(p, id) == p->prefix)
break;
} while (1);
/* And then descend again until we find our leaf */
do {
if (!p->height)
break;
p = __sync_child(p)[__sync_branch_idx(p, id)];
if (!p)
return false;
if (__sync_branch_prefix(p, id) != p->prefix)
return false;
} while (1);
*root = p;
found:
idx = __sync_leaf_idx(p, id);
if (!(p->bitmap & BIT(idx)))
return false;
return seqno_later(__sync_seqno(p)[idx], seqno);
}
static struct i915_syncmap *
__sync_alloc_leaf(struct i915_syncmap *parent, u64 id)
{
struct i915_syncmap *p;
p = kmalloc(sizeof(*p) + KSYNCMAP * sizeof(u32), GFP_KERNEL);
if (unlikely(!p))
return NULL;
p->parent = parent;
p->height = 0;
p->bitmap = 0;
p->prefix = __sync_leaf_prefix(p, id);
return p;
}
static inline void __sync_set_seqno(struct i915_syncmap *p, u64 id, u32 seqno)
{
unsigned int idx = __sync_leaf_idx(p, id);
p->bitmap |= BIT(idx);
__sync_seqno(p)[idx] = seqno;
}
static inline void __sync_set_child(struct i915_syncmap *p,
unsigned int idx,
struct i915_syncmap *child)
{
p->bitmap |= BIT(idx);
__sync_child(p)[idx] = child;
}
static noinline int __sync_set(struct i915_syncmap **root, u64 id, u32 seqno)
{
struct i915_syncmap *p = *root;
unsigned int idx;
if (!p) {
p = __sync_alloc_leaf(NULL, id);
if (unlikely(!p))
return -ENOMEM;
goto found;
}
/* Caller handled the likely cached case */
GEM_BUG_ON(__sync_leaf_prefix(p, id) == p->prefix);
/* Climb back up the tree until we find a common prefix */
do {
if (!p->parent)
break;
p = p->parent;
if (__sync_branch_prefix(p, id) == p->prefix)
break;
} while (1);
/*
* No shortcut, we have to descend the tree to find the right layer
* containing this fence.
*
* Each layer in the tree holds 16 (KSYNCMAP) pointers, either fences
* or lower layers. Leaf nodes (height = 0) contain the fences, all
* other nodes (height > 0) are internal layers that point to a lower
* node. Each internal layer has at least 2 descendents.
*
* Starting at the top, we check whether the current prefix matches. If
* it doesn't, we have gone past our target and need to insert a join
* into the tree, and a new leaf node for the target as a descendent
* of the join, as well as the original layer.
*
* The matching prefix means we are still following the right branch
* of the tree. If it has height 0, we have found our leaf and just
* need to replace the fence slot with ourselves. If the height is
* not zero, our slot contains the next layer in the tree (unless
* it is empty, in which case we can add ourselves as a new leaf).
* As descend the tree the prefix grows (and height decreases).
*/
do {
struct i915_syncmap *next;
if (__sync_branch_prefix(p, id) != p->prefix) {
unsigned int above;
/* Insert a join above the current layer */
next = kzalloc(sizeof(*next) + KSYNCMAP * sizeof(next),
GFP_KERNEL);
if (unlikely(!next))
return -ENOMEM;
/* Compute the height at which these two diverge */
above = fls64(__sync_branch_prefix(p, id) ^ p->prefix);
above = round_up(above, SHIFT);
next->height = above + p->height;
next->prefix = __sync_branch_prefix(next, id);
/* Insert the join into the parent */
if (p->parent) {
idx = __sync_branch_idx(p->parent, id);
__sync_child(p->parent)[idx] = next;
GEM_BUG_ON(!(p->parent->bitmap & BIT(idx)));
}
next->parent = p->parent;
/* Compute the idx of the other branch, not our id! */
idx = p->prefix >> (above - SHIFT) & MASK;
__sync_set_child(next, idx, p);
p->parent = next;
/* Ascend to the join */
p = next;
} else {
if (!p->height)
break;
}
/* Descend into the next layer */
GEM_BUG_ON(!p->height);
idx = __sync_branch_idx(p, id);
next = __sync_child(p)[idx];
if (!next) {
next = __sync_alloc_leaf(p, id);
if (unlikely(!next))
return -ENOMEM;
__sync_set_child(p, idx, next);
p = next;
break;
}
p = next;
} while (1);
found:
GEM_BUG_ON(p->prefix != __sync_leaf_prefix(p, id));
__sync_set_seqno(p, id, seqno);
*root = p;
return 0;
}
/**
* i915_syncmap_set -- mark the most recent syncpoint between contexts
* @root: pointer to the #i915_syncmap
* @id: the context id (other timeline) we have synchronised to
* @seqno: the sequence number along the other timeline
*
* When we synchronise this @root timeline with another (@id), we also know
* that we have synchronized with all previous seqno along that timeline. If
* we then have a request to synchronise with the same seqno or older, we can
* omit it, see i915_syncmap_is_later()
*
* Returns 0 on success, or a negative error code.
*/
int i915_syncmap_set(struct i915_syncmap **root, u64 id, u32 seqno)
{
struct i915_syncmap *p = *root;
/*
* We expect to be called in sequence following is_later(id), which
* should have preloaded the root for us.
*/
if (likely(p && __sync_leaf_prefix(p, id) == p->prefix)) {
__sync_set_seqno(p, id, seqno);
return 0;
}
return __sync_set(root, id, seqno);
}
static void __sync_free(struct i915_syncmap *p)
{
if (p->height) {
unsigned int i;
while ((i = ffs(p->bitmap))) {
p->bitmap &= ~0u << i;
__sync_free(__sync_child(p)[i - 1]);
}
}
kfree(p);
}
/**
* i915_syncmap_free -- free all memory associated with the syncmap
* @root: pointer to the #i915_syncmap
*
* Either when the timeline is to be freed and we no longer need the sync
* point tracking, or when the fences are all known to be signaled and the
* sync point tracking is redundant, we can free the #i915_syncmap to recover
* its allocations.
*
* Will reinitialise the @root pointer so that the #i915_syncmap is ready for
* reuse.
*/
void i915_syncmap_free(struct i915_syncmap **root)
{
struct i915_syncmap *p;
p = *root;
if (!p)
return;
while (p->parent)
p = p->parent;
__sync_free(p);
*root = NULL;
}
#if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
#include "selftests/i915_syncmap.c"
#endif
| linux-master | drivers/gpu/drm/i915/i915_syncmap.c |
/*
* SPDX-License-Identifier: MIT
*
* Copyright © 2017-2018 Intel Corporation
*/
#include <linux/pm_runtime.h>
#include "gt/intel_engine.h"
#include "gt/intel_engine_pm.h"
#include "gt/intel_engine_regs.h"
#include "gt/intel_engine_user.h"
#include "gt/intel_gt.h"
#include "gt/intel_gt_pm.h"
#include "gt/intel_gt_regs.h"
#include "gt/intel_rc6.h"
#include "gt/intel_rps.h"
#include "i915_drv.h"
#include "i915_pmu.h"
/* Frequency for the sampling timer for events which need it. */
#define FREQUENCY 200
#define PERIOD max_t(u64, 10000, NSEC_PER_SEC / FREQUENCY)
#define ENGINE_SAMPLE_MASK \
(BIT(I915_SAMPLE_BUSY) | \
BIT(I915_SAMPLE_WAIT) | \
BIT(I915_SAMPLE_SEMA))
static cpumask_t i915_pmu_cpumask;
static unsigned int i915_pmu_target_cpu = -1;
static u8 engine_config_sample(u64 config)
{
return config & I915_PMU_SAMPLE_MASK;
}
static u8 engine_event_sample(struct perf_event *event)
{
return engine_config_sample(event->attr.config);
}
static u8 engine_event_class(struct perf_event *event)
{
return (event->attr.config >> I915_PMU_CLASS_SHIFT) & 0xff;
}
static u8 engine_event_instance(struct perf_event *event)
{
return (event->attr.config >> I915_PMU_SAMPLE_BITS) & 0xff;
}
static bool is_engine_config(const u64 config)
{
return config < __I915_PMU_OTHER(0);
}
static unsigned int config_gt_id(const u64 config)
{
return config >> __I915_PMU_GT_SHIFT;
}
static u64 config_counter(const u64 config)
{
return config & ~(~0ULL << __I915_PMU_GT_SHIFT);
}
static unsigned int other_bit(const u64 config)
{
unsigned int val;
switch (config_counter(config)) {
case I915_PMU_ACTUAL_FREQUENCY:
val = __I915_PMU_ACTUAL_FREQUENCY_ENABLED;
break;
case I915_PMU_REQUESTED_FREQUENCY:
val = __I915_PMU_REQUESTED_FREQUENCY_ENABLED;
break;
case I915_PMU_RC6_RESIDENCY:
val = __I915_PMU_RC6_RESIDENCY_ENABLED;
break;
default:
/*
* Events that do not require sampling, or tracking state
* transitions between enabled and disabled can be ignored.
*/
return -1;
}
return I915_ENGINE_SAMPLE_COUNT +
config_gt_id(config) * __I915_PMU_TRACKED_EVENT_COUNT +
val;
}
static unsigned int config_bit(const u64 config)
{
if (is_engine_config(config))
return engine_config_sample(config);
else
return other_bit(config);
}
static u32 config_mask(const u64 config)
{
unsigned int bit = config_bit(config);
if (__builtin_constant_p(config))
BUILD_BUG_ON(bit >
BITS_PER_TYPE(typeof_member(struct i915_pmu,
enable)) - 1);
else
WARN_ON_ONCE(bit >
BITS_PER_TYPE(typeof_member(struct i915_pmu,
enable)) - 1);
return BIT(config_bit(config));
}
static bool is_engine_event(struct perf_event *event)
{
return is_engine_config(event->attr.config);
}
static unsigned int event_bit(struct perf_event *event)
{
return config_bit(event->attr.config);
}
static u32 frequency_enabled_mask(void)
{
unsigned int i;
u32 mask = 0;
for (i = 0; i < I915_PMU_MAX_GT; i++)
mask |= config_mask(__I915_PMU_ACTUAL_FREQUENCY(i)) |
config_mask(__I915_PMU_REQUESTED_FREQUENCY(i));
return mask;
}
static bool pmu_needs_timer(struct i915_pmu *pmu)
{
struct drm_i915_private *i915 = container_of(pmu, typeof(*i915), pmu);
u32 enable;
/*
* Only some counters need the sampling timer.
*
* We start with a bitmask of all currently enabled events.
*/
enable = pmu->enable;
/*
* Mask out all the ones which do not need the timer, or in
* other words keep all the ones that could need the timer.
*/
enable &= frequency_enabled_mask() | ENGINE_SAMPLE_MASK;
/*
* Also there is software busyness tracking available we do not
* need the timer for I915_SAMPLE_BUSY counter.
*/
if (i915->caps.scheduler & I915_SCHEDULER_CAP_ENGINE_BUSY_STATS)
enable &= ~BIT(I915_SAMPLE_BUSY);
/*
* If some bits remain it means we need the sampling timer running.
*/
return enable;
}
static u64 __get_rc6(struct intel_gt *gt)
{
struct drm_i915_private *i915 = gt->i915;
u64 val;
val = intel_rc6_residency_ns(>->rc6, INTEL_RC6_RES_RC6);
if (HAS_RC6p(i915))
val += intel_rc6_residency_ns(>->rc6, INTEL_RC6_RES_RC6p);
if (HAS_RC6pp(i915))
val += intel_rc6_residency_ns(>->rc6, INTEL_RC6_RES_RC6pp);
return val;
}
static inline s64 ktime_since_raw(const ktime_t kt)
{
return ktime_to_ns(ktime_sub(ktime_get_raw(), kt));
}
static u64 read_sample(struct i915_pmu *pmu, unsigned int gt_id, int sample)
{
return pmu->sample[gt_id][sample].cur;
}
static void
store_sample(struct i915_pmu *pmu, unsigned int gt_id, int sample, u64 val)
{
pmu->sample[gt_id][sample].cur = val;
}
static void
add_sample_mult(struct i915_pmu *pmu, unsigned int gt_id, int sample, u32 val, u32 mul)
{
pmu->sample[gt_id][sample].cur += mul_u32_u32(val, mul);
}
static u64 get_rc6(struct intel_gt *gt)
{
struct drm_i915_private *i915 = gt->i915;
const unsigned int gt_id = gt->info.id;
struct i915_pmu *pmu = &i915->pmu;
unsigned long flags;
bool awake = false;
u64 val;
if (intel_gt_pm_get_if_awake(gt)) {
val = __get_rc6(gt);
intel_gt_pm_put_async(gt);
awake = true;
}
spin_lock_irqsave(&pmu->lock, flags);
if (awake) {
store_sample(pmu, gt_id, __I915_SAMPLE_RC6, val);
} else {
/*
* We think we are runtime suspended.
*
* Report the delta from when the device was suspended to now,
* on top of the last known real value, as the approximated RC6
* counter value.
*/
val = ktime_since_raw(pmu->sleep_last[gt_id]);
val += read_sample(pmu, gt_id, __I915_SAMPLE_RC6);
}
if (val < read_sample(pmu, gt_id, __I915_SAMPLE_RC6_LAST_REPORTED))
val = read_sample(pmu, gt_id, __I915_SAMPLE_RC6_LAST_REPORTED);
else
store_sample(pmu, gt_id, __I915_SAMPLE_RC6_LAST_REPORTED, val);
spin_unlock_irqrestore(&pmu->lock, flags);
return val;
}
static void init_rc6(struct i915_pmu *pmu)
{
struct drm_i915_private *i915 = container_of(pmu, typeof(*i915), pmu);
struct intel_gt *gt;
unsigned int i;
for_each_gt(gt, i915, i) {
intel_wakeref_t wakeref;
with_intel_runtime_pm(gt->uncore->rpm, wakeref) {
u64 val = __get_rc6(gt);
store_sample(pmu, i, __I915_SAMPLE_RC6, val);
store_sample(pmu, i, __I915_SAMPLE_RC6_LAST_REPORTED,
val);
pmu->sleep_last[i] = ktime_get_raw();
}
}
}
static void park_rc6(struct intel_gt *gt)
{
struct i915_pmu *pmu = >->i915->pmu;
store_sample(pmu, gt->info.id, __I915_SAMPLE_RC6, __get_rc6(gt));
pmu->sleep_last[gt->info.id] = ktime_get_raw();
}
static void __i915_pmu_maybe_start_timer(struct i915_pmu *pmu)
{
if (!pmu->timer_enabled && pmu_needs_timer(pmu)) {
pmu->timer_enabled = true;
pmu->timer_last = ktime_get();
hrtimer_start_range_ns(&pmu->timer,
ns_to_ktime(PERIOD), 0,
HRTIMER_MODE_REL_PINNED);
}
}
void i915_pmu_gt_parked(struct intel_gt *gt)
{
struct i915_pmu *pmu = >->i915->pmu;
if (!pmu->base.event_init)
return;
spin_lock_irq(&pmu->lock);
park_rc6(gt);
/*
* Signal sampling timer to stop if only engine events are enabled and
* GPU went idle.
*/
pmu->unparked &= ~BIT(gt->info.id);
if (pmu->unparked == 0)
pmu->timer_enabled = false;
spin_unlock_irq(&pmu->lock);
}
void i915_pmu_gt_unparked(struct intel_gt *gt)
{
struct i915_pmu *pmu = >->i915->pmu;
if (!pmu->base.event_init)
return;
spin_lock_irq(&pmu->lock);
/*
* Re-enable sampling timer when GPU goes active.
*/
if (pmu->unparked == 0)
__i915_pmu_maybe_start_timer(pmu);
pmu->unparked |= BIT(gt->info.id);
spin_unlock_irq(&pmu->lock);
}
static void
add_sample(struct i915_pmu_sample *sample, u32 val)
{
sample->cur += val;
}
static bool exclusive_mmio_access(const struct drm_i915_private *i915)
{
/*
* We have to avoid concurrent mmio cache line access on gen7 or
* risk a machine hang. For a fun history lesson dig out the old
* userspace intel_gpu_top and run it on Ivybridge or Haswell!
*/
return GRAPHICS_VER(i915) == 7;
}
static void engine_sample(struct intel_engine_cs *engine, unsigned int period_ns)
{
struct intel_engine_pmu *pmu = &engine->pmu;
bool busy;
u32 val;
val = ENGINE_READ_FW(engine, RING_CTL);
if (val == 0) /* powerwell off => engine idle */
return;
if (val & RING_WAIT)
add_sample(&pmu->sample[I915_SAMPLE_WAIT], period_ns);
if (val & RING_WAIT_SEMAPHORE)
add_sample(&pmu->sample[I915_SAMPLE_SEMA], period_ns);
/* No need to sample when busy stats are supported. */
if (intel_engine_supports_stats(engine))
return;
/*
* While waiting on a semaphore or event, MI_MODE reports the
* ring as idle. However, previously using the seqno, and with
* execlists sampling, we account for the ring waiting as the
* engine being busy. Therefore, we record the sample as being
* busy if either waiting or !idle.
*/
busy = val & (RING_WAIT_SEMAPHORE | RING_WAIT);
if (!busy) {
val = ENGINE_READ_FW(engine, RING_MI_MODE);
busy = !(val & MODE_IDLE);
}
if (busy)
add_sample(&pmu->sample[I915_SAMPLE_BUSY], period_ns);
}
static void
engines_sample(struct intel_gt *gt, unsigned int period_ns)
{
struct drm_i915_private *i915 = gt->i915;
struct intel_engine_cs *engine;
enum intel_engine_id id;
unsigned long flags;
if ((i915->pmu.enable & ENGINE_SAMPLE_MASK) == 0)
return;
if (!intel_gt_pm_is_awake(gt))
return;
for_each_engine(engine, gt, id) {
if (!engine->pmu.enable)
continue;
if (!intel_engine_pm_get_if_awake(engine))
continue;
if (exclusive_mmio_access(i915)) {
spin_lock_irqsave(&engine->uncore->lock, flags);
engine_sample(engine, period_ns);
spin_unlock_irqrestore(&engine->uncore->lock, flags);
} else {
engine_sample(engine, period_ns);
}
intel_engine_pm_put_async(engine);
}
}
static bool
frequency_sampling_enabled(struct i915_pmu *pmu, unsigned int gt)
{
return pmu->enable &
(config_mask(__I915_PMU_ACTUAL_FREQUENCY(gt)) |
config_mask(__I915_PMU_REQUESTED_FREQUENCY(gt)));
}
static void
frequency_sample(struct intel_gt *gt, unsigned int period_ns)
{
struct drm_i915_private *i915 = gt->i915;
const unsigned int gt_id = gt->info.id;
struct i915_pmu *pmu = &i915->pmu;
struct intel_rps *rps = >->rps;
if (!frequency_sampling_enabled(pmu, gt_id))
return;
/* Report 0/0 (actual/requested) frequency while parked. */
if (!intel_gt_pm_get_if_awake(gt))
return;
if (pmu->enable & config_mask(__I915_PMU_ACTUAL_FREQUENCY(gt_id))) {
u32 val;
/*
* We take a quick peek here without using forcewake
* so that we don't perturb the system under observation
* (forcewake => !rc6 => increased power use). We expect
* that if the read fails because it is outside of the
* mmio power well, then it will return 0 -- in which
* case we assume the system is running at the intended
* frequency. Fortunately, the read should rarely fail!
*/
val = intel_rps_read_actual_frequency_fw(rps);
if (!val)
val = intel_gpu_freq(rps, rps->cur_freq);
add_sample_mult(pmu, gt_id, __I915_SAMPLE_FREQ_ACT,
val, period_ns / 1000);
}
if (pmu->enable & config_mask(__I915_PMU_REQUESTED_FREQUENCY(gt_id))) {
add_sample_mult(pmu, gt_id, __I915_SAMPLE_FREQ_REQ,
intel_rps_get_requested_frequency(rps),
period_ns / 1000);
}
intel_gt_pm_put_async(gt);
}
static enum hrtimer_restart i915_sample(struct hrtimer *hrtimer)
{
struct drm_i915_private *i915 =
container_of(hrtimer, struct drm_i915_private, pmu.timer);
struct i915_pmu *pmu = &i915->pmu;
unsigned int period_ns;
struct intel_gt *gt;
unsigned int i;
ktime_t now;
if (!READ_ONCE(pmu->timer_enabled))
return HRTIMER_NORESTART;
now = ktime_get();
period_ns = ktime_to_ns(ktime_sub(now, pmu->timer_last));
pmu->timer_last = now;
/*
* Strictly speaking the passed in period may not be 100% accurate for
* all internal calculation, since some amount of time can be spent on
* grabbing the forcewake. However the potential error from timer call-
* back delay greatly dominates this so we keep it simple.
*/
for_each_gt(gt, i915, i) {
if (!(pmu->unparked & BIT(i)))
continue;
engines_sample(gt, period_ns);
frequency_sample(gt, period_ns);
}
hrtimer_forward(hrtimer, now, ns_to_ktime(PERIOD));
return HRTIMER_RESTART;
}
static void i915_pmu_event_destroy(struct perf_event *event)
{
struct drm_i915_private *i915 =
container_of(event->pmu, typeof(*i915), pmu.base);
drm_WARN_ON(&i915->drm, event->parent);
drm_dev_put(&i915->drm);
}
static int
engine_event_status(struct intel_engine_cs *engine,
enum drm_i915_pmu_engine_sample sample)
{
switch (sample) {
case I915_SAMPLE_BUSY:
case I915_SAMPLE_WAIT:
break;
case I915_SAMPLE_SEMA:
if (GRAPHICS_VER(engine->i915) < 6)
return -ENODEV;
break;
default:
return -ENOENT;
}
return 0;
}
static int
config_status(struct drm_i915_private *i915, u64 config)
{
struct intel_gt *gt = to_gt(i915);
unsigned int gt_id = config_gt_id(config);
unsigned int max_gt_id = HAS_EXTRA_GT_LIST(i915) ? 1 : 0;
if (gt_id > max_gt_id)
return -ENOENT;
switch (config_counter(config)) {
case I915_PMU_ACTUAL_FREQUENCY:
if (IS_VALLEYVIEW(i915) || IS_CHERRYVIEW(i915))
/* Requires a mutex for sampling! */
return -ENODEV;
fallthrough;
case I915_PMU_REQUESTED_FREQUENCY:
if (GRAPHICS_VER(i915) < 6)
return -ENODEV;
break;
case I915_PMU_INTERRUPTS:
if (gt_id)
return -ENOENT;
break;
case I915_PMU_RC6_RESIDENCY:
if (!gt->rc6.supported)
return -ENODEV;
break;
case I915_PMU_SOFTWARE_GT_AWAKE_TIME:
break;
default:
return -ENOENT;
}
return 0;
}
static int engine_event_init(struct perf_event *event)
{
struct drm_i915_private *i915 =
container_of(event->pmu, typeof(*i915), pmu.base);
struct intel_engine_cs *engine;
engine = intel_engine_lookup_user(i915, engine_event_class(event),
engine_event_instance(event));
if (!engine)
return -ENODEV;
return engine_event_status(engine, engine_event_sample(event));
}
static int i915_pmu_event_init(struct perf_event *event)
{
struct drm_i915_private *i915 =
container_of(event->pmu, typeof(*i915), pmu.base);
struct i915_pmu *pmu = &i915->pmu;
int ret;
if (pmu->closed)
return -ENODEV;
if (event->attr.type != event->pmu->type)
return -ENOENT;
/* unsupported modes and filters */
if (event->attr.sample_period) /* no sampling */
return -EINVAL;
if (has_branch_stack(event))
return -EOPNOTSUPP;
if (event->cpu < 0)
return -EINVAL;
/* only allow running on one cpu at a time */
if (!cpumask_test_cpu(event->cpu, &i915_pmu_cpumask))
return -EINVAL;
if (is_engine_event(event))
ret = engine_event_init(event);
else
ret = config_status(i915, event->attr.config);
if (ret)
return ret;
if (!event->parent) {
drm_dev_get(&i915->drm);
event->destroy = i915_pmu_event_destroy;
}
return 0;
}
static u64 __i915_pmu_event_read(struct perf_event *event)
{
struct drm_i915_private *i915 =
container_of(event->pmu, typeof(*i915), pmu.base);
struct i915_pmu *pmu = &i915->pmu;
u64 val = 0;
if (is_engine_event(event)) {
u8 sample = engine_event_sample(event);
struct intel_engine_cs *engine;
engine = intel_engine_lookup_user(i915,
engine_event_class(event),
engine_event_instance(event));
if (drm_WARN_ON_ONCE(&i915->drm, !engine)) {
/* Do nothing */
} else if (sample == I915_SAMPLE_BUSY &&
intel_engine_supports_stats(engine)) {
ktime_t unused;
val = ktime_to_ns(intel_engine_get_busy_time(engine,
&unused));
} else {
val = engine->pmu.sample[sample].cur;
}
} else {
const unsigned int gt_id = config_gt_id(event->attr.config);
const u64 config = config_counter(event->attr.config);
switch (config) {
case I915_PMU_ACTUAL_FREQUENCY:
val =
div_u64(read_sample(pmu, gt_id,
__I915_SAMPLE_FREQ_ACT),
USEC_PER_SEC /* to MHz */);
break;
case I915_PMU_REQUESTED_FREQUENCY:
val =
div_u64(read_sample(pmu, gt_id,
__I915_SAMPLE_FREQ_REQ),
USEC_PER_SEC /* to MHz */);
break;
case I915_PMU_INTERRUPTS:
val = READ_ONCE(pmu->irq_count);
break;
case I915_PMU_RC6_RESIDENCY:
val = get_rc6(i915->gt[gt_id]);
break;
case I915_PMU_SOFTWARE_GT_AWAKE_TIME:
val = ktime_to_ns(intel_gt_get_awake_time(to_gt(i915)));
break;
}
}
return val;
}
static void i915_pmu_event_read(struct perf_event *event)
{
struct drm_i915_private *i915 =
container_of(event->pmu, typeof(*i915), pmu.base);
struct hw_perf_event *hwc = &event->hw;
struct i915_pmu *pmu = &i915->pmu;
u64 prev, new;
if (pmu->closed) {
event->hw.state = PERF_HES_STOPPED;
return;
}
again:
prev = local64_read(&hwc->prev_count);
new = __i915_pmu_event_read(event);
if (local64_cmpxchg(&hwc->prev_count, prev, new) != prev)
goto again;
local64_add(new - prev, &event->count);
}
static void i915_pmu_enable(struct perf_event *event)
{
struct drm_i915_private *i915 =
container_of(event->pmu, typeof(*i915), pmu.base);
const unsigned int bit = event_bit(event);
struct i915_pmu *pmu = &i915->pmu;
unsigned long flags;
if (bit == -1)
goto update;
spin_lock_irqsave(&pmu->lock, flags);
/*
* Update the bitmask of enabled events and increment
* the event reference counter.
*/
BUILD_BUG_ON(ARRAY_SIZE(pmu->enable_count) != I915_PMU_MASK_BITS);
GEM_BUG_ON(bit >= ARRAY_SIZE(pmu->enable_count));
GEM_BUG_ON(pmu->enable_count[bit] == ~0);
pmu->enable |= BIT(bit);
pmu->enable_count[bit]++;
/*
* Start the sampling timer if needed and not already enabled.
*/
__i915_pmu_maybe_start_timer(pmu);
/*
* For per-engine events the bitmask and reference counting
* is stored per engine.
*/
if (is_engine_event(event)) {
u8 sample = engine_event_sample(event);
struct intel_engine_cs *engine;
engine = intel_engine_lookup_user(i915,
engine_event_class(event),
engine_event_instance(event));
BUILD_BUG_ON(ARRAY_SIZE(engine->pmu.enable_count) !=
I915_ENGINE_SAMPLE_COUNT);
BUILD_BUG_ON(ARRAY_SIZE(engine->pmu.sample) !=
I915_ENGINE_SAMPLE_COUNT);
GEM_BUG_ON(sample >= ARRAY_SIZE(engine->pmu.enable_count));
GEM_BUG_ON(sample >= ARRAY_SIZE(engine->pmu.sample));
GEM_BUG_ON(engine->pmu.enable_count[sample] == ~0);
engine->pmu.enable |= BIT(sample);
engine->pmu.enable_count[sample]++;
}
spin_unlock_irqrestore(&pmu->lock, flags);
update:
/*
* Store the current counter value so we can report the correct delta
* for all listeners. Even when the event was already enabled and has
* an existing non-zero value.
*/
local64_set(&event->hw.prev_count, __i915_pmu_event_read(event));
}
static void i915_pmu_disable(struct perf_event *event)
{
struct drm_i915_private *i915 =
container_of(event->pmu, typeof(*i915), pmu.base);
const unsigned int bit = event_bit(event);
struct i915_pmu *pmu = &i915->pmu;
unsigned long flags;
if (bit == -1)
return;
spin_lock_irqsave(&pmu->lock, flags);
if (is_engine_event(event)) {
u8 sample = engine_event_sample(event);
struct intel_engine_cs *engine;
engine = intel_engine_lookup_user(i915,
engine_event_class(event),
engine_event_instance(event));
GEM_BUG_ON(sample >= ARRAY_SIZE(engine->pmu.enable_count));
GEM_BUG_ON(sample >= ARRAY_SIZE(engine->pmu.sample));
GEM_BUG_ON(engine->pmu.enable_count[sample] == 0);
/*
* Decrement the reference count and clear the enabled
* bitmask when the last listener on an event goes away.
*/
if (--engine->pmu.enable_count[sample] == 0)
engine->pmu.enable &= ~BIT(sample);
}
GEM_BUG_ON(bit >= ARRAY_SIZE(pmu->enable_count));
GEM_BUG_ON(pmu->enable_count[bit] == 0);
/*
* Decrement the reference count and clear the enabled
* bitmask when the last listener on an event goes away.
*/
if (--pmu->enable_count[bit] == 0) {
pmu->enable &= ~BIT(bit);
pmu->timer_enabled &= pmu_needs_timer(pmu);
}
spin_unlock_irqrestore(&pmu->lock, flags);
}
static void i915_pmu_event_start(struct perf_event *event, int flags)
{
struct drm_i915_private *i915 =
container_of(event->pmu, typeof(*i915), pmu.base);
struct i915_pmu *pmu = &i915->pmu;
if (pmu->closed)
return;
i915_pmu_enable(event);
event->hw.state = 0;
}
static void i915_pmu_event_stop(struct perf_event *event, int flags)
{
if (flags & PERF_EF_UPDATE)
i915_pmu_event_read(event);
i915_pmu_disable(event);
event->hw.state = PERF_HES_STOPPED;
}
static int i915_pmu_event_add(struct perf_event *event, int flags)
{
struct drm_i915_private *i915 =
container_of(event->pmu, typeof(*i915), pmu.base);
struct i915_pmu *pmu = &i915->pmu;
if (pmu->closed)
return -ENODEV;
if (flags & PERF_EF_START)
i915_pmu_event_start(event, flags);
return 0;
}
static void i915_pmu_event_del(struct perf_event *event, int flags)
{
i915_pmu_event_stop(event, PERF_EF_UPDATE);
}
static int i915_pmu_event_event_idx(struct perf_event *event)
{
return 0;
}
struct i915_str_attribute {
struct device_attribute attr;
const char *str;
};
static ssize_t i915_pmu_format_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct i915_str_attribute *eattr;
eattr = container_of(attr, struct i915_str_attribute, attr);
return sprintf(buf, "%s\n", eattr->str);
}
#define I915_PMU_FORMAT_ATTR(_name, _config) \
(&((struct i915_str_attribute[]) { \
{ .attr = __ATTR(_name, 0444, i915_pmu_format_show, NULL), \
.str = _config, } \
})[0].attr.attr)
static struct attribute *i915_pmu_format_attrs[] = {
I915_PMU_FORMAT_ATTR(i915_eventid, "config:0-20"),
NULL,
};
static const struct attribute_group i915_pmu_format_attr_group = {
.name = "format",
.attrs = i915_pmu_format_attrs,
};
struct i915_ext_attribute {
struct device_attribute attr;
unsigned long val;
};
static ssize_t i915_pmu_event_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct i915_ext_attribute *eattr;
eattr = container_of(attr, struct i915_ext_attribute, attr);
return sprintf(buf, "config=0x%lx\n", eattr->val);
}
static ssize_t cpumask_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return cpumap_print_to_pagebuf(true, buf, &i915_pmu_cpumask);
}
static DEVICE_ATTR_RO(cpumask);
static struct attribute *i915_cpumask_attrs[] = {
&dev_attr_cpumask.attr,
NULL,
};
static const struct attribute_group i915_pmu_cpumask_attr_group = {
.attrs = i915_cpumask_attrs,
};
#define __event(__counter, __name, __unit) \
{ \
.counter = (__counter), \
.name = (__name), \
.unit = (__unit), \
.global = false, \
}
#define __global_event(__counter, __name, __unit) \
{ \
.counter = (__counter), \
.name = (__name), \
.unit = (__unit), \
.global = true, \
}
#define __engine_event(__sample, __name) \
{ \
.sample = (__sample), \
.name = (__name), \
}
static struct i915_ext_attribute *
add_i915_attr(struct i915_ext_attribute *attr, const char *name, u64 config)
{
sysfs_attr_init(&attr->attr.attr);
attr->attr.attr.name = name;
attr->attr.attr.mode = 0444;
attr->attr.show = i915_pmu_event_show;
attr->val = config;
return ++attr;
}
static struct perf_pmu_events_attr *
add_pmu_attr(struct perf_pmu_events_attr *attr, const char *name,
const char *str)
{
sysfs_attr_init(&attr->attr.attr);
attr->attr.attr.name = name;
attr->attr.attr.mode = 0444;
attr->attr.show = perf_event_sysfs_show;
attr->event_str = str;
return ++attr;
}
static struct attribute **
create_event_attributes(struct i915_pmu *pmu)
{
struct drm_i915_private *i915 = container_of(pmu, typeof(*i915), pmu);
static const struct {
unsigned int counter;
const char *name;
const char *unit;
bool global;
} events[] = {
__event(0, "actual-frequency", "M"),
__event(1, "requested-frequency", "M"),
__global_event(2, "interrupts", NULL),
__event(3, "rc6-residency", "ns"),
__event(4, "software-gt-awake-time", "ns"),
};
static const struct {
enum drm_i915_pmu_engine_sample sample;
char *name;
} engine_events[] = {
__engine_event(I915_SAMPLE_BUSY, "busy"),
__engine_event(I915_SAMPLE_SEMA, "sema"),
__engine_event(I915_SAMPLE_WAIT, "wait"),
};
unsigned int count = 0;
struct perf_pmu_events_attr *pmu_attr = NULL, *pmu_iter;
struct i915_ext_attribute *i915_attr = NULL, *i915_iter;
struct attribute **attr = NULL, **attr_iter;
struct intel_engine_cs *engine;
struct intel_gt *gt;
unsigned int i, j;
/* Count how many counters we will be exposing. */
for_each_gt(gt, i915, j) {
for (i = 0; i < ARRAY_SIZE(events); i++) {
u64 config = ___I915_PMU_OTHER(j, events[i].counter);
if (!config_status(i915, config))
count++;
}
}
for_each_uabi_engine(engine, i915) {
for (i = 0; i < ARRAY_SIZE(engine_events); i++) {
if (!engine_event_status(engine,
engine_events[i].sample))
count++;
}
}
/* Allocate attribute objects and table. */
i915_attr = kcalloc(count, sizeof(*i915_attr), GFP_KERNEL);
if (!i915_attr)
goto err_alloc;
pmu_attr = kcalloc(count, sizeof(*pmu_attr), GFP_KERNEL);
if (!pmu_attr)
goto err_alloc;
/* Max one pointer of each attribute type plus a termination entry. */
attr = kcalloc(count * 2 + 1, sizeof(*attr), GFP_KERNEL);
if (!attr)
goto err_alloc;
i915_iter = i915_attr;
pmu_iter = pmu_attr;
attr_iter = attr;
/* Initialize supported non-engine counters. */
for_each_gt(gt, i915, j) {
for (i = 0; i < ARRAY_SIZE(events); i++) {
u64 config = ___I915_PMU_OTHER(j, events[i].counter);
char *str;
if (config_status(i915, config))
continue;
if (events[i].global || !HAS_EXTRA_GT_LIST(i915))
str = kstrdup(events[i].name, GFP_KERNEL);
else
str = kasprintf(GFP_KERNEL, "%s-gt%u",
events[i].name, j);
if (!str)
goto err;
*attr_iter++ = &i915_iter->attr.attr;
i915_iter = add_i915_attr(i915_iter, str, config);
if (events[i].unit) {
if (events[i].global || !HAS_EXTRA_GT_LIST(i915))
str = kasprintf(GFP_KERNEL, "%s.unit",
events[i].name);
else
str = kasprintf(GFP_KERNEL, "%s-gt%u.unit",
events[i].name, j);
if (!str)
goto err;
*attr_iter++ = &pmu_iter->attr.attr;
pmu_iter = add_pmu_attr(pmu_iter, str,
events[i].unit);
}
}
}
/* Initialize supported engine counters. */
for_each_uabi_engine(engine, i915) {
for (i = 0; i < ARRAY_SIZE(engine_events); i++) {
char *str;
if (engine_event_status(engine,
engine_events[i].sample))
continue;
str = kasprintf(GFP_KERNEL, "%s-%s",
engine->name, engine_events[i].name);
if (!str)
goto err;
*attr_iter++ = &i915_iter->attr.attr;
i915_iter =
add_i915_attr(i915_iter, str,
__I915_PMU_ENGINE(engine->uabi_class,
engine->uabi_instance,
engine_events[i].sample));
str = kasprintf(GFP_KERNEL, "%s-%s.unit",
engine->name, engine_events[i].name);
if (!str)
goto err;
*attr_iter++ = &pmu_iter->attr.attr;
pmu_iter = add_pmu_attr(pmu_iter, str, "ns");
}
}
pmu->i915_attr = i915_attr;
pmu->pmu_attr = pmu_attr;
return attr;
err:;
for (attr_iter = attr; *attr_iter; attr_iter++)
kfree((*attr_iter)->name);
err_alloc:
kfree(attr);
kfree(i915_attr);
kfree(pmu_attr);
return NULL;
}
static void free_event_attributes(struct i915_pmu *pmu)
{
struct attribute **attr_iter = pmu->events_attr_group.attrs;
for (; *attr_iter; attr_iter++)
kfree((*attr_iter)->name);
kfree(pmu->events_attr_group.attrs);
kfree(pmu->i915_attr);
kfree(pmu->pmu_attr);
pmu->events_attr_group.attrs = NULL;
pmu->i915_attr = NULL;
pmu->pmu_attr = NULL;
}
static int i915_pmu_cpu_online(unsigned int cpu, struct hlist_node *node)
{
struct i915_pmu *pmu = hlist_entry_safe(node, typeof(*pmu), cpuhp.node);
GEM_BUG_ON(!pmu->base.event_init);
/* Select the first online CPU as a designated reader. */
if (cpumask_empty(&i915_pmu_cpumask))
cpumask_set_cpu(cpu, &i915_pmu_cpumask);
return 0;
}
static int i915_pmu_cpu_offline(unsigned int cpu, struct hlist_node *node)
{
struct i915_pmu *pmu = hlist_entry_safe(node, typeof(*pmu), cpuhp.node);
unsigned int target = i915_pmu_target_cpu;
GEM_BUG_ON(!pmu->base.event_init);
/*
* Unregistering an instance generates a CPU offline event which we must
* ignore to avoid incorrectly modifying the shared i915_pmu_cpumask.
*/
if (pmu->closed)
return 0;
if (cpumask_test_and_clear_cpu(cpu, &i915_pmu_cpumask)) {
target = cpumask_any_but(topology_sibling_cpumask(cpu), cpu);
/* Migrate events if there is a valid target */
if (target < nr_cpu_ids) {
cpumask_set_cpu(target, &i915_pmu_cpumask);
i915_pmu_target_cpu = target;
}
}
if (target < nr_cpu_ids && target != pmu->cpuhp.cpu) {
perf_pmu_migrate_context(&pmu->base, cpu, target);
pmu->cpuhp.cpu = target;
}
return 0;
}
static enum cpuhp_state cpuhp_slot = CPUHP_INVALID;
int i915_pmu_init(void)
{
int ret;
ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN,
"perf/x86/intel/i915:online",
i915_pmu_cpu_online,
i915_pmu_cpu_offline);
if (ret < 0)
pr_notice("Failed to setup cpuhp state for i915 PMU! (%d)\n",
ret);
else
cpuhp_slot = ret;
return 0;
}
void i915_pmu_exit(void)
{
if (cpuhp_slot != CPUHP_INVALID)
cpuhp_remove_multi_state(cpuhp_slot);
}
static int i915_pmu_register_cpuhp_state(struct i915_pmu *pmu)
{
if (cpuhp_slot == CPUHP_INVALID)
return -EINVAL;
return cpuhp_state_add_instance(cpuhp_slot, &pmu->cpuhp.node);
}
static void i915_pmu_unregister_cpuhp_state(struct i915_pmu *pmu)
{
cpuhp_state_remove_instance(cpuhp_slot, &pmu->cpuhp.node);
}
static bool is_igp(struct drm_i915_private *i915)
{
struct pci_dev *pdev = to_pci_dev(i915->drm.dev);
/* IGP is 0000:00:02.0 */
return pci_domain_nr(pdev->bus) == 0 &&
pdev->bus->number == 0 &&
PCI_SLOT(pdev->devfn) == 2 &&
PCI_FUNC(pdev->devfn) == 0;
}
void i915_pmu_register(struct drm_i915_private *i915)
{
struct i915_pmu *pmu = &i915->pmu;
const struct attribute_group *attr_groups[] = {
&i915_pmu_format_attr_group,
&pmu->events_attr_group,
&i915_pmu_cpumask_attr_group,
NULL
};
int ret = -ENOMEM;
if (GRAPHICS_VER(i915) <= 2) {
drm_info(&i915->drm, "PMU not supported for this GPU.");
return;
}
spin_lock_init(&pmu->lock);
hrtimer_init(&pmu->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
pmu->timer.function = i915_sample;
pmu->cpuhp.cpu = -1;
init_rc6(pmu);
if (!is_igp(i915)) {
pmu->name = kasprintf(GFP_KERNEL,
"i915_%s",
dev_name(i915->drm.dev));
if (pmu->name) {
/* tools/perf reserves colons as special. */
strreplace((char *)pmu->name, ':', '_');
}
} else {
pmu->name = "i915";
}
if (!pmu->name)
goto err;
pmu->events_attr_group.name = "events";
pmu->events_attr_group.attrs = create_event_attributes(pmu);
if (!pmu->events_attr_group.attrs)
goto err_name;
pmu->base.attr_groups = kmemdup(attr_groups, sizeof(attr_groups),
GFP_KERNEL);
if (!pmu->base.attr_groups)
goto err_attr;
pmu->base.module = THIS_MODULE;
pmu->base.task_ctx_nr = perf_invalid_context;
pmu->base.event_init = i915_pmu_event_init;
pmu->base.add = i915_pmu_event_add;
pmu->base.del = i915_pmu_event_del;
pmu->base.start = i915_pmu_event_start;
pmu->base.stop = i915_pmu_event_stop;
pmu->base.read = i915_pmu_event_read;
pmu->base.event_idx = i915_pmu_event_event_idx;
ret = perf_pmu_register(&pmu->base, pmu->name, -1);
if (ret)
goto err_groups;
ret = i915_pmu_register_cpuhp_state(pmu);
if (ret)
goto err_unreg;
return;
err_unreg:
perf_pmu_unregister(&pmu->base);
err_groups:
kfree(pmu->base.attr_groups);
err_attr:
pmu->base.event_init = NULL;
free_event_attributes(pmu);
err_name:
if (!is_igp(i915))
kfree(pmu->name);
err:
drm_notice(&i915->drm, "Failed to register PMU!\n");
}
void i915_pmu_unregister(struct drm_i915_private *i915)
{
struct i915_pmu *pmu = &i915->pmu;
if (!pmu->base.event_init)
return;
/*
* "Disconnect" the PMU callbacks - since all are atomic synchronize_rcu
* ensures all currently executing ones will have exited before we
* proceed with unregistration.
*/
pmu->closed = true;
synchronize_rcu();
hrtimer_cancel(&pmu->timer);
i915_pmu_unregister_cpuhp_state(pmu);
perf_pmu_unregister(&pmu->base);
pmu->base.event_init = NULL;
kfree(pmu->base.attr_groups);
if (!is_igp(i915))
kfree(pmu->name);
free_event_attributes(pmu);
}
| linux-master | drivers/gpu/drm/i915/i915_pmu.c |
/*
* SPDX-License-Identifier: MIT
*
* Copyright © 2016 Intel Corporation
*/
#include "i915_scatterlist.h"
#include "i915_ttm_buddy_manager.h"
#include <drm/drm_buddy.h>
#include <drm/drm_mm.h>
#include <linux/slab.h>
bool i915_sg_trim(struct sg_table *orig_st)
{
struct sg_table new_st;
struct scatterlist *sg, *new_sg;
unsigned int i;
if (orig_st->nents == orig_st->orig_nents)
return false;
if (sg_alloc_table(&new_st, orig_st->nents, GFP_KERNEL | __GFP_NOWARN))
return false;
new_sg = new_st.sgl;
for_each_sg(orig_st->sgl, sg, orig_st->nents, i) {
sg_set_page(new_sg, sg_page(sg), sg->length, 0);
sg_dma_address(new_sg) = sg_dma_address(sg);
sg_dma_len(new_sg) = sg_dma_len(sg);
new_sg = sg_next(new_sg);
}
GEM_BUG_ON(new_sg); /* Should walk exactly nents and hit the end */
sg_free_table(orig_st);
*orig_st = new_st;
return true;
}
static void i915_refct_sgt_release(struct kref *ref)
{
struct i915_refct_sgt *rsgt =
container_of(ref, typeof(*rsgt), kref);
sg_free_table(&rsgt->table);
kfree(rsgt);
}
static const struct i915_refct_sgt_ops rsgt_ops = {
.release = i915_refct_sgt_release
};
/**
* i915_refct_sgt_init - Initialize a struct i915_refct_sgt with default ops
* @rsgt: The struct i915_refct_sgt to initialize.
* @size: The size of the underlying memory buffer.
*/
void i915_refct_sgt_init(struct i915_refct_sgt *rsgt, size_t size)
{
__i915_refct_sgt_init(rsgt, size, &rsgt_ops);
}
/**
* i915_rsgt_from_mm_node - Create a refcounted sg_table from a struct
* drm_mm_node
* @node: The drm_mm_node.
* @region_start: An offset to add to the dma addresses of the sg list.
* @page_alignment: Required page alignment for each sg entry. Power of two.
*
* Create a struct sg_table, initializing it from a struct drm_mm_node,
* taking a maximum segment length into account, splitting into segments
* if necessary.
*
* Return: A pointer to a kmalloced struct i915_refct_sgt on success, negative
* error code cast to an error pointer on failure.
*/
struct i915_refct_sgt *i915_rsgt_from_mm_node(const struct drm_mm_node *node,
u64 region_start,
u32 page_alignment)
{
const u32 max_segment = round_down(UINT_MAX, page_alignment);
const u32 segment_pages = max_segment >> PAGE_SHIFT;
u64 block_size, offset, prev_end;
struct i915_refct_sgt *rsgt;
struct sg_table *st;
struct scatterlist *sg;
GEM_BUG_ON(!max_segment);
rsgt = kmalloc(sizeof(*rsgt), GFP_KERNEL);
if (!rsgt)
return ERR_PTR(-ENOMEM);
i915_refct_sgt_init(rsgt, node->size << PAGE_SHIFT);
st = &rsgt->table;
/* restricted by sg_alloc_table */
if (WARN_ON(overflows_type(DIV_ROUND_UP_ULL(node->size, segment_pages),
unsigned int))) {
i915_refct_sgt_put(rsgt);
return ERR_PTR(-E2BIG);
}
if (sg_alloc_table(st, DIV_ROUND_UP_ULL(node->size, segment_pages),
GFP_KERNEL)) {
i915_refct_sgt_put(rsgt);
return ERR_PTR(-ENOMEM);
}
sg = st->sgl;
st->nents = 0;
prev_end = (resource_size_t)-1;
block_size = node->size << PAGE_SHIFT;
offset = node->start << PAGE_SHIFT;
while (block_size) {
u64 len;
if (offset != prev_end || sg->length >= max_segment) {
if (st->nents)
sg = __sg_next(sg);
sg_dma_address(sg) = region_start + offset;
GEM_BUG_ON(!IS_ALIGNED(sg_dma_address(sg),
page_alignment));
sg_dma_len(sg) = 0;
sg->length = 0;
st->nents++;
}
len = min_t(u64, block_size, max_segment - sg->length);
sg->length += len;
sg_dma_len(sg) += len;
offset += len;
block_size -= len;
prev_end = offset;
}
sg_mark_end(sg);
i915_sg_trim(st);
return rsgt;
}
/**
* i915_rsgt_from_buddy_resource - Create a refcounted sg_table from a struct
* i915_buddy_block list
* @res: The struct i915_ttm_buddy_resource.
* @region_start: An offset to add to the dma addresses of the sg list.
* @page_alignment: Required page alignment for each sg entry. Power of two.
*
* Create a struct sg_table, initializing it from struct i915_buddy_block list,
* taking a maximum segment length into account, splitting into segments
* if necessary.
*
* Return: A pointer to a kmalloced struct i915_refct_sgts on success, negative
* error code cast to an error pointer on failure.
*/
struct i915_refct_sgt *i915_rsgt_from_buddy_resource(struct ttm_resource *res,
u64 region_start,
u32 page_alignment)
{
struct i915_ttm_buddy_resource *bman_res = to_ttm_buddy_resource(res);
const u64 size = res->size;
const u32 max_segment = round_down(UINT_MAX, page_alignment);
struct drm_buddy *mm = bman_res->mm;
struct list_head *blocks = &bman_res->blocks;
struct drm_buddy_block *block;
struct i915_refct_sgt *rsgt;
struct scatterlist *sg;
struct sg_table *st;
resource_size_t prev_end;
GEM_BUG_ON(list_empty(blocks));
GEM_BUG_ON(!max_segment);
rsgt = kmalloc(sizeof(*rsgt), GFP_KERNEL);
if (!rsgt)
return ERR_PTR(-ENOMEM);
i915_refct_sgt_init(rsgt, size);
st = &rsgt->table;
/* restricted by sg_alloc_table */
if (WARN_ON(overflows_type(PFN_UP(res->size), unsigned int))) {
i915_refct_sgt_put(rsgt);
return ERR_PTR(-E2BIG);
}
if (sg_alloc_table(st, PFN_UP(res->size), GFP_KERNEL)) {
i915_refct_sgt_put(rsgt);
return ERR_PTR(-ENOMEM);
}
sg = st->sgl;
st->nents = 0;
prev_end = (resource_size_t)-1;
list_for_each_entry(block, blocks, link) {
u64 block_size, offset;
block_size = min_t(u64, size, drm_buddy_block_size(mm, block));
offset = drm_buddy_block_offset(block);
while (block_size) {
u64 len;
if (offset != prev_end || sg->length >= max_segment) {
if (st->nents)
sg = __sg_next(sg);
sg_dma_address(sg) = region_start + offset;
GEM_BUG_ON(!IS_ALIGNED(sg_dma_address(sg),
page_alignment));
sg_dma_len(sg) = 0;
sg->length = 0;
st->nents++;
}
len = min_t(u64, block_size, max_segment - sg->length);
sg->length += len;
sg_dma_len(sg) += len;
offset += len;
block_size -= len;
prev_end = offset;
}
}
sg_mark_end(sg);
i915_sg_trim(st);
return rsgt;
}
#if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
#include "selftests/scatterlist.c"
#endif
| linux-master | drivers/gpu/drm/i915/i915_scatterlist.c |
/*
* Copyright(c) 2011-2016 Intel Corporation. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "i915_drv.h"
#include "i915_vgpu.h"
#include "intel_gvt.h"
#include "gem/i915_gem_dmabuf.h"
#include "gt/intel_context.h"
#include "gt/intel_ring.h"
#include "gt/shmem_utils.h"
/**
* DOC: Intel GVT-g host support
*
* Intel GVT-g is a graphics virtualization technology which shares the
* GPU among multiple virtual machines on a time-sharing basis. Each
* virtual machine is presented a virtual GPU (vGPU), which has equivalent
* features as the underlying physical GPU (pGPU), so i915 driver can run
* seamlessly in a virtual machine.
*
* To virtualize GPU resources GVT-g driver depends on hypervisor technology
* e.g KVM/VFIO/mdev, Xen, etc. to provide resource access trapping capability
* and be virtualized within GVT-g device module. More architectural design
* doc is available on https://01.org/group/2230/documentation-list.
*/
static LIST_HEAD(intel_gvt_devices);
static const struct intel_vgpu_ops *intel_gvt_ops;
static DEFINE_MUTEX(intel_gvt_mutex);
static bool is_supported_device(struct drm_i915_private *dev_priv)
{
if (IS_BROADWELL(dev_priv))
return true;
if (IS_SKYLAKE(dev_priv))
return true;
if (IS_KABYLAKE(dev_priv))
return true;
if (IS_BROXTON(dev_priv))
return true;
if (IS_COFFEELAKE(dev_priv))
return true;
if (IS_COMETLAKE(dev_priv))
return true;
return false;
}
static void free_initial_hw_state(struct drm_i915_private *dev_priv)
{
struct i915_virtual_gpu *vgpu = &dev_priv->vgpu;
vfree(vgpu->initial_mmio);
vgpu->initial_mmio = NULL;
kfree(vgpu->initial_cfg_space);
vgpu->initial_cfg_space = NULL;
}
static void save_mmio(struct intel_gvt_mmio_table_iter *iter, u32 offset,
u32 size)
{
struct drm_i915_private *dev_priv = iter->i915;
u32 *mmio, i;
for (i = offset; i < offset + size; i += 4) {
mmio = iter->data + i;
*mmio = intel_uncore_read_notrace(to_gt(dev_priv)->uncore,
_MMIO(i));
}
}
static int handle_mmio(struct intel_gvt_mmio_table_iter *iter,
u32 offset, u32 size)
{
if (WARN_ON(!IS_ALIGNED(offset, 4)))
return -EINVAL;
save_mmio(iter, offset, size);
return 0;
}
static int save_initial_hw_state(struct drm_i915_private *dev_priv)
{
struct pci_dev *pdev = to_pci_dev(dev_priv->drm.dev);
struct i915_virtual_gpu *vgpu = &dev_priv->vgpu;
struct intel_gvt_mmio_table_iter iter;
void *mem;
int i, ret;
mem = kzalloc(PCI_CFG_SPACE_EXP_SIZE, GFP_KERNEL);
if (!mem)
return -ENOMEM;
vgpu->initial_cfg_space = mem;
for (i = 0; i < PCI_CFG_SPACE_EXP_SIZE; i += 4)
pci_read_config_dword(pdev, i, mem + i);
mem = vzalloc(2 * SZ_1M);
if (!mem) {
ret = -ENOMEM;
goto err_mmio;
}
vgpu->initial_mmio = mem;
iter.i915 = dev_priv;
iter.data = vgpu->initial_mmio;
iter.handle_mmio_cb = handle_mmio;
ret = intel_gvt_iterate_mmio_table(&iter);
if (ret)
goto err_iterate;
return 0;
err_iterate:
vfree(vgpu->initial_mmio);
vgpu->initial_mmio = NULL;
err_mmio:
kfree(vgpu->initial_cfg_space);
vgpu->initial_cfg_space = NULL;
return ret;
}
static void intel_gvt_init_device(struct drm_i915_private *dev_priv)
{
if (!dev_priv->params.enable_gvt) {
drm_dbg(&dev_priv->drm,
"GVT-g is disabled by kernel params\n");
return;
}
if (intel_vgpu_active(dev_priv)) {
drm_info(&dev_priv->drm, "GVT-g is disabled for guest\n");
return;
}
if (!is_supported_device(dev_priv)) {
drm_info(&dev_priv->drm,
"Unsupported device. GVT-g is disabled\n");
return;
}
if (intel_uc_wants_guc_submission(&to_gt(dev_priv)->uc)) {
drm_err(&dev_priv->drm,
"Graphics virtualization is not yet supported with GuC submission\n");
return;
}
if (save_initial_hw_state(dev_priv)) {
drm_dbg(&dev_priv->drm, "Failed to save initial HW state\n");
return;
}
if (intel_gvt_ops->init_device(dev_priv))
drm_dbg(&dev_priv->drm, "Fail to init GVT device\n");
}
static void intel_gvt_clean_device(struct drm_i915_private *dev_priv)
{
if (dev_priv->gvt)
intel_gvt_ops->clean_device(dev_priv);
free_initial_hw_state(dev_priv);
}
int intel_gvt_set_ops(const struct intel_vgpu_ops *ops)
{
struct drm_i915_private *dev_priv;
mutex_lock(&intel_gvt_mutex);
if (intel_gvt_ops) {
mutex_unlock(&intel_gvt_mutex);
return -EINVAL;
}
intel_gvt_ops = ops;
list_for_each_entry(dev_priv, &intel_gvt_devices, vgpu.entry)
intel_gvt_init_device(dev_priv);
mutex_unlock(&intel_gvt_mutex);
return 0;
}
EXPORT_SYMBOL_NS_GPL(intel_gvt_set_ops, I915_GVT);
void intel_gvt_clear_ops(const struct intel_vgpu_ops *ops)
{
struct drm_i915_private *dev_priv;
mutex_lock(&intel_gvt_mutex);
if (intel_gvt_ops != ops) {
mutex_unlock(&intel_gvt_mutex);
return;
}
list_for_each_entry(dev_priv, &intel_gvt_devices, vgpu.entry)
intel_gvt_clean_device(dev_priv);
intel_gvt_ops = NULL;
mutex_unlock(&intel_gvt_mutex);
}
EXPORT_SYMBOL_NS_GPL(intel_gvt_clear_ops, I915_GVT);
/**
* intel_gvt_init - initialize GVT components
* @dev_priv: drm i915 private data
*
* This function is called at the initialization stage to create a GVT device.
*
* Returns:
* Zero on success, negative error code if failed.
*
*/
int intel_gvt_init(struct drm_i915_private *dev_priv)
{
if (i915_inject_probe_failure(dev_priv))
return -ENODEV;
mutex_lock(&intel_gvt_mutex);
list_add_tail(&dev_priv->vgpu.entry, &intel_gvt_devices);
if (intel_gvt_ops)
intel_gvt_init_device(dev_priv);
mutex_unlock(&intel_gvt_mutex);
return 0;
}
/**
* intel_gvt_driver_remove - cleanup GVT components when i915 driver is
* unbinding
* @dev_priv: drm i915 private *
*
* This function is called at the i915 driver unloading stage, to shutdown
* GVT components and release the related resources.
*/
void intel_gvt_driver_remove(struct drm_i915_private *dev_priv)
{
mutex_lock(&intel_gvt_mutex);
intel_gvt_clean_device(dev_priv);
list_del(&dev_priv->vgpu.entry);
mutex_unlock(&intel_gvt_mutex);
}
/**
* intel_gvt_resume - GVT resume routine wapper
*
* @dev_priv: drm i915 private *
*
* This function is called at the i915 driver resume stage to restore required
* HW status for GVT so that vGPU can continue running after resumed.
*/
void intel_gvt_resume(struct drm_i915_private *dev_priv)
{
mutex_lock(&intel_gvt_mutex);
if (dev_priv->gvt)
intel_gvt_ops->pm_resume(dev_priv);
mutex_unlock(&intel_gvt_mutex);
}
/*
* Exported here so that the exports only get created when GVT support is
* actually enabled.
*/
EXPORT_SYMBOL_NS_GPL(i915_gem_object_alloc, I915_GVT);
EXPORT_SYMBOL_NS_GPL(i915_gem_object_create_shmem, I915_GVT);
EXPORT_SYMBOL_NS_GPL(i915_gem_object_init, I915_GVT);
EXPORT_SYMBOL_NS_GPL(i915_gem_object_ggtt_pin_ww, I915_GVT);
EXPORT_SYMBOL_NS_GPL(i915_gem_object_pin_map, I915_GVT);
EXPORT_SYMBOL_NS_GPL(i915_gem_object_set_to_cpu_domain, I915_GVT);
EXPORT_SYMBOL_NS_GPL(__i915_gem_object_flush_map, I915_GVT);
EXPORT_SYMBOL_NS_GPL(__i915_gem_object_set_pages, I915_GVT);
EXPORT_SYMBOL_NS_GPL(i915_gem_gtt_insert, I915_GVT);
EXPORT_SYMBOL_NS_GPL(i915_gem_prime_export, I915_GVT);
EXPORT_SYMBOL_NS_GPL(i915_gem_ww_ctx_init, I915_GVT);
EXPORT_SYMBOL_NS_GPL(i915_gem_ww_ctx_backoff, I915_GVT);
EXPORT_SYMBOL_NS_GPL(i915_gem_ww_ctx_fini, I915_GVT);
EXPORT_SYMBOL_NS_GPL(i915_ppgtt_create, I915_GVT);
EXPORT_SYMBOL_NS_GPL(i915_request_add, I915_GVT);
EXPORT_SYMBOL_NS_GPL(i915_request_create, I915_GVT);
EXPORT_SYMBOL_NS_GPL(i915_request_wait, I915_GVT);
EXPORT_SYMBOL_NS_GPL(i915_reserve_fence, I915_GVT);
EXPORT_SYMBOL_NS_GPL(i915_unreserve_fence, I915_GVT);
EXPORT_SYMBOL_NS_GPL(i915_vm_release, I915_GVT);
EXPORT_SYMBOL_NS_GPL(_i915_vma_move_to_active, I915_GVT);
EXPORT_SYMBOL_NS_GPL(intel_context_create, I915_GVT);
EXPORT_SYMBOL_NS_GPL(__intel_context_do_pin, I915_GVT);
EXPORT_SYMBOL_NS_GPL(__intel_context_do_unpin, I915_GVT);
EXPORT_SYMBOL_NS_GPL(intel_ring_begin, I915_GVT);
EXPORT_SYMBOL_NS_GPL(intel_runtime_pm_get, I915_GVT);
#if IS_ENABLED(CONFIG_DRM_I915_DEBUG_RUNTIME_PM)
EXPORT_SYMBOL_NS_GPL(intel_runtime_pm_put, I915_GVT);
#endif
EXPORT_SYMBOL_NS_GPL(intel_runtime_pm_put_unchecked, I915_GVT);
EXPORT_SYMBOL_NS_GPL(intel_uncore_forcewake_for_reg, I915_GVT);
EXPORT_SYMBOL_NS_GPL(intel_uncore_forcewake_get, I915_GVT);
EXPORT_SYMBOL_NS_GPL(intel_uncore_forcewake_put, I915_GVT);
EXPORT_SYMBOL_NS_GPL(shmem_pin_map, I915_GVT);
EXPORT_SYMBOL_NS_GPL(shmem_unpin_map, I915_GVT);
EXPORT_SYMBOL_NS_GPL(__px_dma, I915_GVT);
EXPORT_SYMBOL_NS_GPL(i915_fence_ops, I915_GVT);
| linux-master | drivers/gpu/drm/i915/intel_gvt.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2020 Intel Corporation
*/
#include "display/intel_audio_regs.h"
#include "display/intel_backlight_regs.h"
#include "display/intel_display_types.h"
#include "display/intel_dmc_regs.h"
#include "display/intel_dp_aux_regs.h"
#include "display/intel_dpio_phy.h"
#include "display/intel_fdi_regs.h"
#include "display/intel_lvds_regs.h"
#include "display/intel_psr_regs.h"
#include "display/skl_watermark_regs.h"
#include "display/vlv_dsi_pll_regs.h"
#include "gt/intel_gt_regs.h"
#include "gvt/gvt.h"
#include "i915_drv.h"
#include "i915_pvinfo.h"
#include "i915_reg.h"
#include "intel_gvt.h"
#include "intel_mchbar_regs.h"
#define MMIO_F(reg, s) do { \
int ret; \
ret = iter->handle_mmio_cb(iter, i915_mmio_reg_offset(reg), s); \
if (ret) \
return ret; \
} while (0)
#define MMIO_D(reg) MMIO_F(reg, 4)
#define MMIO_RING_F(prefix, s) do { \
MMIO_F(prefix(RENDER_RING_BASE), s); \
MMIO_F(prefix(BLT_RING_BASE), s); \
MMIO_F(prefix(GEN6_BSD_RING_BASE), s); \
MMIO_F(prefix(VEBOX_RING_BASE), s); \
if (HAS_ENGINE(to_gt(iter->i915), VCS1)) \
MMIO_F(prefix(GEN8_BSD2_RING_BASE), s); \
} while (0)
#define MMIO_RING_D(prefix) \
MMIO_RING_F(prefix, 4)
static int iterate_generic_mmio(struct intel_gvt_mmio_table_iter *iter)
{
struct drm_i915_private *dev_priv = iter->i915;
MMIO_RING_D(RING_IMR);
MMIO_D(SDEIMR);
MMIO_D(SDEIER);
MMIO_D(SDEIIR);
MMIO_D(SDEISR);
MMIO_RING_D(RING_HWSTAM);
MMIO_D(BSD_HWS_PGA_GEN7);
MMIO_D(BLT_HWS_PGA_GEN7);
MMIO_D(VEBOX_HWS_PGA_GEN7);
#define RING_REG(base) _MMIO((base) + 0x28)
MMIO_RING_D(RING_REG);
#undef RING_REG
#define RING_REG(base) _MMIO((base) + 0x134)
MMIO_RING_D(RING_REG);
#undef RING_REG
#define RING_REG(base) _MMIO((base) + 0x6c)
MMIO_RING_D(RING_REG);
#undef RING_REG
MMIO_D(_MMIO(0x2148));
MMIO_D(CCID(RENDER_RING_BASE));
MMIO_D(_MMIO(0x12198));
MMIO_D(GEN7_CXT_SIZE);
MMIO_RING_D(RING_TAIL);
MMIO_RING_D(RING_HEAD);
MMIO_RING_D(RING_CTL);
MMIO_RING_D(RING_ACTHD);
MMIO_RING_D(RING_START);
/* RING MODE */
#define RING_REG(base) _MMIO((base) + 0x29c)
MMIO_RING_D(RING_REG);
#undef RING_REG
MMIO_RING_D(RING_MI_MODE);
MMIO_RING_D(RING_INSTPM);
MMIO_RING_D(RING_TIMESTAMP);
MMIO_RING_D(RING_TIMESTAMP_UDW);
MMIO_D(GEN7_GT_MODE);
MMIO_D(CACHE_MODE_0_GEN7);
MMIO_D(CACHE_MODE_1);
MMIO_D(CACHE_MODE_0);
MMIO_D(_MMIO(0x2124));
MMIO_D(_MMIO(0x20dc));
MMIO_D(_3D_CHICKEN3);
MMIO_D(_MMIO(0x2088));
MMIO_D(FF_SLICE_CS_CHICKEN2);
MMIO_D(_MMIO(0x2470));
MMIO_D(GAM_ECOCHK);
MMIO_D(GEN7_COMMON_SLICE_CHICKEN1);
MMIO_D(COMMON_SLICE_CHICKEN2);
MMIO_D(_MMIO(0x9030));
MMIO_D(_MMIO(0x20a0));
MMIO_D(_MMIO(0x2420));
MMIO_D(_MMIO(0x2430));
MMIO_D(_MMIO(0x2434));
MMIO_D(_MMIO(0x2438));
MMIO_D(_MMIO(0x243c));
MMIO_D(_MMIO(0x7018));
MMIO_D(HSW_HALF_SLICE_CHICKEN3);
MMIO_D(GEN7_HALF_SLICE_CHICKEN1);
/* display */
MMIO_F(_MMIO(0x60220), 0x20);
MMIO_D(_MMIO(0x602a0));
MMIO_D(_MMIO(0x65050));
MMIO_D(_MMIO(0x650b4));
MMIO_D(_MMIO(0xc4040));
MMIO_D(DERRMR);
MMIO_D(PIPEDSL(PIPE_A));
MMIO_D(PIPEDSL(PIPE_B));
MMIO_D(PIPEDSL(PIPE_C));
MMIO_D(PIPEDSL(_PIPE_EDP));
MMIO_D(TRANSCONF(TRANSCODER_A));
MMIO_D(TRANSCONF(TRANSCODER_B));
MMIO_D(TRANSCONF(TRANSCODER_C));
MMIO_D(TRANSCONF(TRANSCODER_EDP));
MMIO_D(PIPESTAT(PIPE_A));
MMIO_D(PIPESTAT(PIPE_B));
MMIO_D(PIPESTAT(PIPE_C));
MMIO_D(PIPESTAT(_PIPE_EDP));
MMIO_D(PIPE_FLIPCOUNT_G4X(PIPE_A));
MMIO_D(PIPE_FLIPCOUNT_G4X(PIPE_B));
MMIO_D(PIPE_FLIPCOUNT_G4X(PIPE_C));
MMIO_D(PIPE_FLIPCOUNT_G4X(_PIPE_EDP));
MMIO_D(PIPE_FRMCOUNT_G4X(PIPE_A));
MMIO_D(PIPE_FRMCOUNT_G4X(PIPE_B));
MMIO_D(PIPE_FRMCOUNT_G4X(PIPE_C));
MMIO_D(PIPE_FRMCOUNT_G4X(_PIPE_EDP));
MMIO_D(CURCNTR(PIPE_A));
MMIO_D(CURCNTR(PIPE_B));
MMIO_D(CURCNTR(PIPE_C));
MMIO_D(CURPOS(PIPE_A));
MMIO_D(CURPOS(PIPE_B));
MMIO_D(CURPOS(PIPE_C));
MMIO_D(CURBASE(PIPE_A));
MMIO_D(CURBASE(PIPE_B));
MMIO_D(CURBASE(PIPE_C));
MMIO_D(CUR_FBC_CTL(PIPE_A));
MMIO_D(CUR_FBC_CTL(PIPE_B));
MMIO_D(CUR_FBC_CTL(PIPE_C));
MMIO_D(_MMIO(0x700ac));
MMIO_D(_MMIO(0x710ac));
MMIO_D(_MMIO(0x720ac));
MMIO_D(_MMIO(0x70090));
MMIO_D(_MMIO(0x70094));
MMIO_D(_MMIO(0x70098));
MMIO_D(_MMIO(0x7009c));
MMIO_D(DSPCNTR(PIPE_A));
MMIO_D(DSPADDR(PIPE_A));
MMIO_D(DSPSTRIDE(PIPE_A));
MMIO_D(DSPPOS(PIPE_A));
MMIO_D(DSPSIZE(PIPE_A));
MMIO_D(DSPSURF(PIPE_A));
MMIO_D(DSPOFFSET(PIPE_A));
MMIO_D(DSPSURFLIVE(PIPE_A));
MMIO_D(REG_50080(PIPE_A, PLANE_PRIMARY));
MMIO_D(DSPCNTR(PIPE_B));
MMIO_D(DSPADDR(PIPE_B));
MMIO_D(DSPSTRIDE(PIPE_B));
MMIO_D(DSPPOS(PIPE_B));
MMIO_D(DSPSIZE(PIPE_B));
MMIO_D(DSPSURF(PIPE_B));
MMIO_D(DSPOFFSET(PIPE_B));
MMIO_D(DSPSURFLIVE(PIPE_B));
MMIO_D(REG_50080(PIPE_B, PLANE_PRIMARY));
MMIO_D(DSPCNTR(PIPE_C));
MMIO_D(DSPADDR(PIPE_C));
MMIO_D(DSPSTRIDE(PIPE_C));
MMIO_D(DSPPOS(PIPE_C));
MMIO_D(DSPSIZE(PIPE_C));
MMIO_D(DSPSURF(PIPE_C));
MMIO_D(DSPOFFSET(PIPE_C));
MMIO_D(DSPSURFLIVE(PIPE_C));
MMIO_D(REG_50080(PIPE_C, PLANE_PRIMARY));
MMIO_D(SPRCTL(PIPE_A));
MMIO_D(SPRLINOFF(PIPE_A));
MMIO_D(SPRSTRIDE(PIPE_A));
MMIO_D(SPRPOS(PIPE_A));
MMIO_D(SPRSIZE(PIPE_A));
MMIO_D(SPRKEYVAL(PIPE_A));
MMIO_D(SPRKEYMSK(PIPE_A));
MMIO_D(SPRSURF(PIPE_A));
MMIO_D(SPRKEYMAX(PIPE_A));
MMIO_D(SPROFFSET(PIPE_A));
MMIO_D(SPRSCALE(PIPE_A));
MMIO_D(SPRSURFLIVE(PIPE_A));
MMIO_D(REG_50080(PIPE_A, PLANE_SPRITE0));
MMIO_D(SPRCTL(PIPE_B));
MMIO_D(SPRLINOFF(PIPE_B));
MMIO_D(SPRSTRIDE(PIPE_B));
MMIO_D(SPRPOS(PIPE_B));
MMIO_D(SPRSIZE(PIPE_B));
MMIO_D(SPRKEYVAL(PIPE_B));
MMIO_D(SPRKEYMSK(PIPE_B));
MMIO_D(SPRSURF(PIPE_B));
MMIO_D(SPRKEYMAX(PIPE_B));
MMIO_D(SPROFFSET(PIPE_B));
MMIO_D(SPRSCALE(PIPE_B));
MMIO_D(SPRSURFLIVE(PIPE_B));
MMIO_D(REG_50080(PIPE_B, PLANE_SPRITE0));
MMIO_D(SPRCTL(PIPE_C));
MMIO_D(SPRLINOFF(PIPE_C));
MMIO_D(SPRSTRIDE(PIPE_C));
MMIO_D(SPRPOS(PIPE_C));
MMIO_D(SPRSIZE(PIPE_C));
MMIO_D(SPRKEYVAL(PIPE_C));
MMIO_D(SPRKEYMSK(PIPE_C));
MMIO_D(SPRSURF(PIPE_C));
MMIO_D(SPRKEYMAX(PIPE_C));
MMIO_D(SPROFFSET(PIPE_C));
MMIO_D(SPRSCALE(PIPE_C));
MMIO_D(SPRSURFLIVE(PIPE_C));
MMIO_D(REG_50080(PIPE_C, PLANE_SPRITE0));
MMIO_D(TRANS_HTOTAL(TRANSCODER_A));
MMIO_D(TRANS_HBLANK(TRANSCODER_A));
MMIO_D(TRANS_HSYNC(TRANSCODER_A));
MMIO_D(TRANS_VTOTAL(TRANSCODER_A));
MMIO_D(TRANS_VBLANK(TRANSCODER_A));
MMIO_D(TRANS_VSYNC(TRANSCODER_A));
MMIO_D(BCLRPAT(TRANSCODER_A));
MMIO_D(TRANS_VSYNCSHIFT(TRANSCODER_A));
MMIO_D(PIPESRC(TRANSCODER_A));
MMIO_D(TRANS_HTOTAL(TRANSCODER_B));
MMIO_D(TRANS_HBLANK(TRANSCODER_B));
MMIO_D(TRANS_HSYNC(TRANSCODER_B));
MMIO_D(TRANS_VTOTAL(TRANSCODER_B));
MMIO_D(TRANS_VBLANK(TRANSCODER_B));
MMIO_D(TRANS_VSYNC(TRANSCODER_B));
MMIO_D(BCLRPAT(TRANSCODER_B));
MMIO_D(TRANS_VSYNCSHIFT(TRANSCODER_B));
MMIO_D(PIPESRC(TRANSCODER_B));
MMIO_D(TRANS_HTOTAL(TRANSCODER_C));
MMIO_D(TRANS_HBLANK(TRANSCODER_C));
MMIO_D(TRANS_HSYNC(TRANSCODER_C));
MMIO_D(TRANS_VTOTAL(TRANSCODER_C));
MMIO_D(TRANS_VBLANK(TRANSCODER_C));
MMIO_D(TRANS_VSYNC(TRANSCODER_C));
MMIO_D(BCLRPAT(TRANSCODER_C));
MMIO_D(TRANS_VSYNCSHIFT(TRANSCODER_C));
MMIO_D(PIPESRC(TRANSCODER_C));
MMIO_D(TRANS_HTOTAL(TRANSCODER_EDP));
MMIO_D(TRANS_HBLANK(TRANSCODER_EDP));
MMIO_D(TRANS_HSYNC(TRANSCODER_EDP));
MMIO_D(TRANS_VTOTAL(TRANSCODER_EDP));
MMIO_D(TRANS_VBLANK(TRANSCODER_EDP));
MMIO_D(TRANS_VSYNC(TRANSCODER_EDP));
MMIO_D(BCLRPAT(TRANSCODER_EDP));
MMIO_D(TRANS_VSYNCSHIFT(TRANSCODER_EDP));
MMIO_D(PIPE_DATA_M1(TRANSCODER_A));
MMIO_D(PIPE_DATA_N1(TRANSCODER_A));
MMIO_D(PIPE_DATA_M2(TRANSCODER_A));
MMIO_D(PIPE_DATA_N2(TRANSCODER_A));
MMIO_D(PIPE_LINK_M1(TRANSCODER_A));
MMIO_D(PIPE_LINK_N1(TRANSCODER_A));
MMIO_D(PIPE_LINK_M2(TRANSCODER_A));
MMIO_D(PIPE_LINK_N2(TRANSCODER_A));
MMIO_D(PIPE_DATA_M1(TRANSCODER_B));
MMIO_D(PIPE_DATA_N1(TRANSCODER_B));
MMIO_D(PIPE_DATA_M2(TRANSCODER_B));
MMIO_D(PIPE_DATA_N2(TRANSCODER_B));
MMIO_D(PIPE_LINK_M1(TRANSCODER_B));
MMIO_D(PIPE_LINK_N1(TRANSCODER_B));
MMIO_D(PIPE_LINK_M2(TRANSCODER_B));
MMIO_D(PIPE_LINK_N2(TRANSCODER_B));
MMIO_D(PIPE_DATA_M1(TRANSCODER_C));
MMIO_D(PIPE_DATA_N1(TRANSCODER_C));
MMIO_D(PIPE_DATA_M2(TRANSCODER_C));
MMIO_D(PIPE_DATA_N2(TRANSCODER_C));
MMIO_D(PIPE_LINK_M1(TRANSCODER_C));
MMIO_D(PIPE_LINK_N1(TRANSCODER_C));
MMIO_D(PIPE_LINK_M2(TRANSCODER_C));
MMIO_D(PIPE_LINK_N2(TRANSCODER_C));
MMIO_D(PIPE_DATA_M1(TRANSCODER_EDP));
MMIO_D(PIPE_DATA_N1(TRANSCODER_EDP));
MMIO_D(PIPE_DATA_M2(TRANSCODER_EDP));
MMIO_D(PIPE_DATA_N2(TRANSCODER_EDP));
MMIO_D(PIPE_LINK_M1(TRANSCODER_EDP));
MMIO_D(PIPE_LINK_N1(TRANSCODER_EDP));
MMIO_D(PIPE_LINK_M2(TRANSCODER_EDP));
MMIO_D(PIPE_LINK_N2(TRANSCODER_EDP));
MMIO_D(PF_CTL(PIPE_A));
MMIO_D(PF_WIN_SZ(PIPE_A));
MMIO_D(PF_WIN_POS(PIPE_A));
MMIO_D(PF_VSCALE(PIPE_A));
MMIO_D(PF_HSCALE(PIPE_A));
MMIO_D(PF_CTL(PIPE_B));
MMIO_D(PF_WIN_SZ(PIPE_B));
MMIO_D(PF_WIN_POS(PIPE_B));
MMIO_D(PF_VSCALE(PIPE_B));
MMIO_D(PF_HSCALE(PIPE_B));
MMIO_D(PF_CTL(PIPE_C));
MMIO_D(PF_WIN_SZ(PIPE_C));
MMIO_D(PF_WIN_POS(PIPE_C));
MMIO_D(PF_VSCALE(PIPE_C));
MMIO_D(PF_HSCALE(PIPE_C));
MMIO_D(WM0_PIPE_ILK(PIPE_A));
MMIO_D(WM0_PIPE_ILK(PIPE_B));
MMIO_D(WM0_PIPE_ILK(PIPE_C));
MMIO_D(WM1_LP_ILK);
MMIO_D(WM2_LP_ILK);
MMIO_D(WM3_LP_ILK);
MMIO_D(WM1S_LP_ILK);
MMIO_D(WM2S_LP_IVB);
MMIO_D(WM3S_LP_IVB);
MMIO_D(BLC_PWM_CPU_CTL2);
MMIO_D(BLC_PWM_CPU_CTL);
MMIO_D(BLC_PWM_PCH_CTL1);
MMIO_D(BLC_PWM_PCH_CTL2);
MMIO_D(_MMIO(0x48268));
MMIO_F(PCH_GMBUS0, 4 * 4);
MMIO_F(PCH_GPIO_BASE, 6 * 4);
MMIO_F(_MMIO(0xe4f00), 0x28);
MMIO_D(_MMIO(_PCH_TRANSACONF));
MMIO_D(_MMIO(_PCH_TRANSBCONF));
MMIO_D(FDI_RX_IIR(PIPE_A));
MMIO_D(FDI_RX_IIR(PIPE_B));
MMIO_D(FDI_RX_IIR(PIPE_C));
MMIO_D(FDI_RX_IMR(PIPE_A));
MMIO_D(FDI_RX_IMR(PIPE_B));
MMIO_D(FDI_RX_IMR(PIPE_C));
MMIO_D(FDI_RX_CTL(PIPE_A));
MMIO_D(FDI_RX_CTL(PIPE_B));
MMIO_D(FDI_RX_CTL(PIPE_C));
MMIO_D(_MMIO(_PCH_TRANS_HTOTAL_A));
MMIO_D(_MMIO(_PCH_TRANS_HBLANK_A));
MMIO_D(_MMIO(_PCH_TRANS_HSYNC_A));
MMIO_D(_MMIO(_PCH_TRANS_VTOTAL_A));
MMIO_D(_MMIO(_PCH_TRANS_VBLANK_A));
MMIO_D(_MMIO(_PCH_TRANS_VSYNC_A));
MMIO_D(_MMIO(_PCH_TRANS_VSYNCSHIFT_A));
MMIO_D(_MMIO(_PCH_TRANS_HTOTAL_B));
MMIO_D(_MMIO(_PCH_TRANS_HBLANK_B));
MMIO_D(_MMIO(_PCH_TRANS_HSYNC_B));
MMIO_D(_MMIO(_PCH_TRANS_VTOTAL_B));
MMIO_D(_MMIO(_PCH_TRANS_VBLANK_B));
MMIO_D(_MMIO(_PCH_TRANS_VSYNC_B));
MMIO_D(_MMIO(_PCH_TRANS_VSYNCSHIFT_B));
MMIO_D(_MMIO(_PCH_TRANSA_DATA_M1));
MMIO_D(_MMIO(_PCH_TRANSA_DATA_N1));
MMIO_D(_MMIO(_PCH_TRANSA_DATA_M2));
MMIO_D(_MMIO(_PCH_TRANSA_DATA_N2));
MMIO_D(_MMIO(_PCH_TRANSA_LINK_M1));
MMIO_D(_MMIO(_PCH_TRANSA_LINK_N1));
MMIO_D(_MMIO(_PCH_TRANSA_LINK_M2));
MMIO_D(_MMIO(_PCH_TRANSA_LINK_N2));
MMIO_D(TRANS_DP_CTL(PIPE_A));
MMIO_D(TRANS_DP_CTL(PIPE_B));
MMIO_D(TRANS_DP_CTL(PIPE_C));
MMIO_D(TVIDEO_DIP_CTL(PIPE_A));
MMIO_D(TVIDEO_DIP_DATA(PIPE_A));
MMIO_D(TVIDEO_DIP_GCP(PIPE_A));
MMIO_D(TVIDEO_DIP_CTL(PIPE_B));
MMIO_D(TVIDEO_DIP_DATA(PIPE_B));
MMIO_D(TVIDEO_DIP_GCP(PIPE_B));
MMIO_D(TVIDEO_DIP_CTL(PIPE_C));
MMIO_D(TVIDEO_DIP_DATA(PIPE_C));
MMIO_D(TVIDEO_DIP_GCP(PIPE_C));
MMIO_D(_MMIO(_FDI_RXA_MISC));
MMIO_D(_MMIO(_FDI_RXB_MISC));
MMIO_D(_MMIO(_FDI_RXA_TUSIZE1));
MMIO_D(_MMIO(_FDI_RXA_TUSIZE2));
MMIO_D(_MMIO(_FDI_RXB_TUSIZE1));
MMIO_D(_MMIO(_FDI_RXB_TUSIZE2));
MMIO_D(PCH_PP_CONTROL);
MMIO_D(PCH_PP_DIVISOR);
MMIO_D(PCH_PP_STATUS);
MMIO_D(PCH_LVDS);
MMIO_D(_MMIO(_PCH_DPLL_A));
MMIO_D(_MMIO(_PCH_DPLL_B));
MMIO_D(_MMIO(_PCH_FPA0));
MMIO_D(_MMIO(_PCH_FPA1));
MMIO_D(_MMIO(_PCH_FPB0));
MMIO_D(_MMIO(_PCH_FPB1));
MMIO_D(PCH_DREF_CONTROL);
MMIO_D(PCH_RAWCLK_FREQ);
MMIO_D(PCH_DPLL_SEL);
MMIO_D(_MMIO(0x61208));
MMIO_D(_MMIO(0x6120c));
MMIO_D(PCH_PP_ON_DELAYS);
MMIO_D(PCH_PP_OFF_DELAYS);
MMIO_D(_MMIO(0xe651c));
MMIO_D(_MMIO(0xe661c));
MMIO_D(_MMIO(0xe671c));
MMIO_D(_MMIO(0xe681c));
MMIO_D(_MMIO(0xe6c04));
MMIO_D(_MMIO(0xe6e1c));
MMIO_D(PCH_PORT_HOTPLUG);
MMIO_D(LCPLL_CTL);
MMIO_D(FUSE_STRAP);
MMIO_D(DIGITAL_PORT_HOTPLUG_CNTRL);
MMIO_D(DISP_ARB_CTL);
MMIO_D(DISP_ARB_CTL2);
MMIO_D(ILK_DISPLAY_CHICKEN1);
MMIO_D(ILK_DISPLAY_CHICKEN2);
MMIO_D(ILK_DSPCLK_GATE_D);
MMIO_D(SOUTH_CHICKEN1);
MMIO_D(SOUTH_CHICKEN2);
MMIO_D(_MMIO(_TRANSA_CHICKEN1));
MMIO_D(_MMIO(_TRANSB_CHICKEN1));
MMIO_D(SOUTH_DSPCLK_GATE_D);
MMIO_D(_MMIO(_TRANSA_CHICKEN2));
MMIO_D(_MMIO(_TRANSB_CHICKEN2));
MMIO_D(ILK_DPFC_CB_BASE(INTEL_FBC_A));
MMIO_D(ILK_DPFC_CONTROL(INTEL_FBC_A));
MMIO_D(ILK_DPFC_RECOMP_CTL(INTEL_FBC_A));
MMIO_D(ILK_DPFC_STATUS(INTEL_FBC_A));
MMIO_D(ILK_DPFC_FENCE_YOFF(INTEL_FBC_A));
MMIO_D(ILK_DPFC_CHICKEN(INTEL_FBC_A));
MMIO_D(ILK_FBC_RT_BASE);
MMIO_D(IPS_CTL);
MMIO_D(PIPE_CSC_COEFF_RY_GY(PIPE_A));
MMIO_D(PIPE_CSC_COEFF_BY(PIPE_A));
MMIO_D(PIPE_CSC_COEFF_RU_GU(PIPE_A));
MMIO_D(PIPE_CSC_COEFF_BU(PIPE_A));
MMIO_D(PIPE_CSC_COEFF_RV_GV(PIPE_A));
MMIO_D(PIPE_CSC_COEFF_BV(PIPE_A));
MMIO_D(PIPE_CSC_MODE(PIPE_A));
MMIO_D(PIPE_CSC_PREOFF_HI(PIPE_A));
MMIO_D(PIPE_CSC_PREOFF_ME(PIPE_A));
MMIO_D(PIPE_CSC_PREOFF_LO(PIPE_A));
MMIO_D(PIPE_CSC_POSTOFF_HI(PIPE_A));
MMIO_D(PIPE_CSC_POSTOFF_ME(PIPE_A));
MMIO_D(PIPE_CSC_POSTOFF_LO(PIPE_A));
MMIO_D(PIPE_CSC_COEFF_RY_GY(PIPE_B));
MMIO_D(PIPE_CSC_COEFF_BY(PIPE_B));
MMIO_D(PIPE_CSC_COEFF_RU_GU(PIPE_B));
MMIO_D(PIPE_CSC_COEFF_BU(PIPE_B));
MMIO_D(PIPE_CSC_COEFF_RV_GV(PIPE_B));
MMIO_D(PIPE_CSC_COEFF_BV(PIPE_B));
MMIO_D(PIPE_CSC_MODE(PIPE_B));
MMIO_D(PIPE_CSC_PREOFF_HI(PIPE_B));
MMIO_D(PIPE_CSC_PREOFF_ME(PIPE_B));
MMIO_D(PIPE_CSC_PREOFF_LO(PIPE_B));
MMIO_D(PIPE_CSC_POSTOFF_HI(PIPE_B));
MMIO_D(PIPE_CSC_POSTOFF_ME(PIPE_B));
MMIO_D(PIPE_CSC_POSTOFF_LO(PIPE_B));
MMIO_D(PIPE_CSC_COEFF_RY_GY(PIPE_C));
MMIO_D(PIPE_CSC_COEFF_BY(PIPE_C));
MMIO_D(PIPE_CSC_COEFF_RU_GU(PIPE_C));
MMIO_D(PIPE_CSC_COEFF_BU(PIPE_C));
MMIO_D(PIPE_CSC_COEFF_RV_GV(PIPE_C));
MMIO_D(PIPE_CSC_COEFF_BV(PIPE_C));
MMIO_D(PIPE_CSC_MODE(PIPE_C));
MMIO_D(PIPE_CSC_PREOFF_HI(PIPE_C));
MMIO_D(PIPE_CSC_PREOFF_ME(PIPE_C));
MMIO_D(PIPE_CSC_PREOFF_LO(PIPE_C));
MMIO_D(PIPE_CSC_POSTOFF_HI(PIPE_C));
MMIO_D(PIPE_CSC_POSTOFF_ME(PIPE_C));
MMIO_D(PIPE_CSC_POSTOFF_LO(PIPE_C));
MMIO_D(PREC_PAL_INDEX(PIPE_A));
MMIO_D(PREC_PAL_DATA(PIPE_A));
MMIO_F(PREC_PAL_GC_MAX(PIPE_A, 0), 4 * 3);
MMIO_D(PREC_PAL_INDEX(PIPE_B));
MMIO_D(PREC_PAL_DATA(PIPE_B));
MMIO_F(PREC_PAL_GC_MAX(PIPE_B, 0), 4 * 3);
MMIO_D(PREC_PAL_INDEX(PIPE_C));
MMIO_D(PREC_PAL_DATA(PIPE_C));
MMIO_F(PREC_PAL_GC_MAX(PIPE_C, 0), 4 * 3);
MMIO_D(_MMIO(0x60110));
MMIO_D(_MMIO(0x61110));
MMIO_F(_MMIO(0x70400), 0x40);
MMIO_F(_MMIO(0x71400), 0x40);
MMIO_F(_MMIO(0x72400), 0x40);
MMIO_D(WM_LINETIME(PIPE_A));
MMIO_D(WM_LINETIME(PIPE_B));
MMIO_D(WM_LINETIME(PIPE_C));
MMIO_D(SPLL_CTL);
MMIO_D(_MMIO(_WRPLL_CTL1));
MMIO_D(_MMIO(_WRPLL_CTL2));
MMIO_D(PORT_CLK_SEL(PORT_A));
MMIO_D(PORT_CLK_SEL(PORT_B));
MMIO_D(PORT_CLK_SEL(PORT_C));
MMIO_D(PORT_CLK_SEL(PORT_D));
MMIO_D(PORT_CLK_SEL(PORT_E));
MMIO_D(TRANS_CLK_SEL(TRANSCODER_A));
MMIO_D(TRANS_CLK_SEL(TRANSCODER_B));
MMIO_D(TRANS_CLK_SEL(TRANSCODER_C));
MMIO_D(HSW_NDE_RSTWRN_OPT);
MMIO_D(_MMIO(0x46508));
MMIO_D(_MMIO(0x49080));
MMIO_D(_MMIO(0x49180));
MMIO_D(_MMIO(0x49280));
MMIO_F(_MMIO(0x49090), 0x14);
MMIO_F(_MMIO(0x49190), 0x14);
MMIO_F(_MMIO(0x49290), 0x14);
MMIO_D(GAMMA_MODE(PIPE_A));
MMIO_D(GAMMA_MODE(PIPE_B));
MMIO_D(GAMMA_MODE(PIPE_C));
MMIO_D(TRANS_MULT(TRANSCODER_A));
MMIO_D(TRANS_MULT(TRANSCODER_B));
MMIO_D(TRANS_MULT(TRANSCODER_C));
MMIO_D(HSW_TVIDEO_DIP_CTL(TRANSCODER_A));
MMIO_D(HSW_TVIDEO_DIP_CTL(TRANSCODER_B));
MMIO_D(HSW_TVIDEO_DIP_CTL(TRANSCODER_C));
MMIO_D(SFUSE_STRAP);
MMIO_D(SBI_ADDR);
MMIO_D(SBI_DATA);
MMIO_D(SBI_CTL_STAT);
MMIO_D(PIXCLK_GATE);
MMIO_F(_MMIO(_DPA_AUX_CH_CTL), 6 * 4);
MMIO_D(DDI_BUF_CTL(PORT_A));
MMIO_D(DDI_BUF_CTL(PORT_B));
MMIO_D(DDI_BUF_CTL(PORT_C));
MMIO_D(DDI_BUF_CTL(PORT_D));
MMIO_D(DDI_BUF_CTL(PORT_E));
MMIO_D(DP_TP_CTL(PORT_A));
MMIO_D(DP_TP_CTL(PORT_B));
MMIO_D(DP_TP_CTL(PORT_C));
MMIO_D(DP_TP_CTL(PORT_D));
MMIO_D(DP_TP_CTL(PORT_E));
MMIO_D(DP_TP_STATUS(PORT_A));
MMIO_D(DP_TP_STATUS(PORT_B));
MMIO_D(DP_TP_STATUS(PORT_C));
MMIO_D(DP_TP_STATUS(PORT_D));
MMIO_D(DP_TP_STATUS(PORT_E));
MMIO_F(_MMIO(_DDI_BUF_TRANS_A), 0x50);
MMIO_F(_MMIO(0x64e60), 0x50);
MMIO_F(_MMIO(0x64eC0), 0x50);
MMIO_F(_MMIO(0x64f20), 0x50);
MMIO_F(_MMIO(0x64f80), 0x50);
MMIO_D(HSW_AUD_CFG(PIPE_A));
MMIO_D(HSW_AUD_PIN_ELD_CP_VLD);
MMIO_D(HSW_AUD_MISC_CTRL(PIPE_A));
MMIO_D(_MMIO(_TRANS_DDI_FUNC_CTL_A));
MMIO_D(_MMIO(_TRANS_DDI_FUNC_CTL_B));
MMIO_D(_MMIO(_TRANS_DDI_FUNC_CTL_C));
MMIO_D(_MMIO(_TRANS_DDI_FUNC_CTL_EDP));
MMIO_D(_MMIO(_TRANSA_MSA_MISC));
MMIO_D(_MMIO(_TRANSB_MSA_MISC));
MMIO_D(_MMIO(_TRANSC_MSA_MISC));
MMIO_D(_MMIO(_TRANS_EDP_MSA_MISC));
MMIO_D(FORCEWAKE);
MMIO_D(FORCEWAKE_ACK);
MMIO_D(GEN6_GT_CORE_STATUS);
MMIO_D(GEN6_GT_THREAD_STATUS_REG);
MMIO_D(GTFIFODBG);
MMIO_D(GTFIFOCTL);
MMIO_D(ECOBUS);
MMIO_D(GEN6_RC_CONTROL);
MMIO_D(GEN6_RC_STATE);
MMIO_D(GEN6_RPNSWREQ);
MMIO_D(GEN6_RC_VIDEO_FREQ);
MMIO_D(GEN6_RP_DOWN_TIMEOUT);
MMIO_D(GEN6_RP_INTERRUPT_LIMITS);
MMIO_D(GEN6_RPSTAT1);
MMIO_D(GEN6_RP_CONTROL);
MMIO_D(GEN6_RP_UP_THRESHOLD);
MMIO_D(GEN6_RP_DOWN_THRESHOLD);
MMIO_D(GEN6_RP_CUR_UP_EI);
MMIO_D(GEN6_RP_CUR_UP);
MMIO_D(GEN6_RP_PREV_UP);
MMIO_D(GEN6_RP_CUR_DOWN_EI);
MMIO_D(GEN6_RP_CUR_DOWN);
MMIO_D(GEN6_RP_PREV_DOWN);
MMIO_D(GEN6_RP_UP_EI);
MMIO_D(GEN6_RP_DOWN_EI);
MMIO_D(GEN6_RP_IDLE_HYSTERSIS);
MMIO_D(GEN6_RC1_WAKE_RATE_LIMIT);
MMIO_D(GEN6_RC6_WAKE_RATE_LIMIT);
MMIO_D(GEN6_RC6pp_WAKE_RATE_LIMIT);
MMIO_D(GEN6_RC_EVALUATION_INTERVAL);
MMIO_D(GEN6_RC_IDLE_HYSTERSIS);
MMIO_D(GEN6_RC_SLEEP);
MMIO_D(GEN6_RC1e_THRESHOLD);
MMIO_D(GEN6_RC6_THRESHOLD);
MMIO_D(GEN6_RC6p_THRESHOLD);
MMIO_D(GEN6_RC6pp_THRESHOLD);
MMIO_D(GEN6_PMINTRMSK);
MMIO_D(RSTDBYCTL);
MMIO_D(GEN6_GDRST);
MMIO_F(FENCE_REG_GEN6_LO(0), 0x80);
MMIO_D(CPU_VGACNTRL);
MMIO_D(TILECTL);
MMIO_D(GEN6_UCGCTL1);
MMIO_D(GEN6_UCGCTL2);
MMIO_F(_MMIO(0x4f000), 0x90);
MMIO_D(GEN6_PCODE_DATA);
MMIO_D(_MMIO(0x13812c));
MMIO_D(GEN7_ERR_INT);
MMIO_D(HSW_EDRAM_CAP);
MMIO_D(HSW_IDICR);
MMIO_D(GFX_FLSH_CNTL_GEN6);
MMIO_D(_MMIO(0x3c));
MMIO_D(_MMIO(0x860));
MMIO_D(ECOSKPD(RENDER_RING_BASE));
MMIO_D(_MMIO(0x121d0));
MMIO_D(ECOSKPD(BLT_RING_BASE));
MMIO_D(_MMIO(0x41d0));
MMIO_D(GAC_ECO_BITS);
MMIO_D(_MMIO(0x6200));
MMIO_D(_MMIO(0x6204));
MMIO_D(_MMIO(0x6208));
MMIO_D(_MMIO(0x7118));
MMIO_D(_MMIO(0x7180));
MMIO_D(_MMIO(0x7408));
MMIO_D(_MMIO(0x7c00));
MMIO_D(GEN6_MBCTL);
MMIO_D(_MMIO(0x911c));
MMIO_D(_MMIO(0x9120));
MMIO_D(GEN7_UCGCTL4);
MMIO_D(GAB_CTL);
MMIO_D(_MMIO(0x48800));
MMIO_D(_MMIO(0xce044));
MMIO_D(_MMIO(0xe6500));
MMIO_D(_MMIO(0xe6504));
MMIO_D(_MMIO(0xe6600));
MMIO_D(_MMIO(0xe6604));
MMIO_D(_MMIO(0xe6700));
MMIO_D(_MMIO(0xe6704));
MMIO_D(_MMIO(0xe6800));
MMIO_D(_MMIO(0xe6804));
MMIO_D(PCH_GMBUS4);
MMIO_D(PCH_GMBUS5);
MMIO_D(_MMIO(0x902c));
MMIO_D(_MMIO(0xec008));
MMIO_D(_MMIO(0xec00c));
MMIO_D(_MMIO(0xec008 + 0x18));
MMIO_D(_MMIO(0xec00c + 0x18));
MMIO_D(_MMIO(0xec008 + 0x18 * 2));
MMIO_D(_MMIO(0xec00c + 0x18 * 2));
MMIO_D(_MMIO(0xec008 + 0x18 * 3));
MMIO_D(_MMIO(0xec00c + 0x18 * 3));
MMIO_D(_MMIO(0xec408));
MMIO_D(_MMIO(0xec40c));
MMIO_D(_MMIO(0xec408 + 0x18));
MMIO_D(_MMIO(0xec40c + 0x18));
MMIO_D(_MMIO(0xec408 + 0x18 * 2));
MMIO_D(_MMIO(0xec40c + 0x18 * 2));
MMIO_D(_MMIO(0xec408 + 0x18 * 3));
MMIO_D(_MMIO(0xec40c + 0x18 * 3));
MMIO_D(_MMIO(0xfc810));
MMIO_D(_MMIO(0xfc81c));
MMIO_D(_MMIO(0xfc828));
MMIO_D(_MMIO(0xfc834));
MMIO_D(_MMIO(0xfcc00));
MMIO_D(_MMIO(0xfcc0c));
MMIO_D(_MMIO(0xfcc18));
MMIO_D(_MMIO(0xfcc24));
MMIO_D(_MMIO(0xfd000));
MMIO_D(_MMIO(0xfd00c));
MMIO_D(_MMIO(0xfd018));
MMIO_D(_MMIO(0xfd024));
MMIO_D(_MMIO(0xfd034));
MMIO_D(FPGA_DBG);
MMIO_D(_MMIO(0x2054));
MMIO_D(_MMIO(0x12054));
MMIO_D(_MMIO(0x22054));
MMIO_D(_MMIO(0x1a054));
MMIO_D(_MMIO(0x44070));
MMIO_D(_MMIO(0x2178));
MMIO_D(_MMIO(0x217c));
MMIO_D(_MMIO(0x12178));
MMIO_D(_MMIO(0x1217c));
MMIO_F(_MMIO(0x5200), 32);
MMIO_F(_MMIO(0x5240), 32);
MMIO_F(_MMIO(0x5280), 16);
MMIO_D(BCS_SWCTRL);
MMIO_F(HS_INVOCATION_COUNT, 8);
MMIO_F(DS_INVOCATION_COUNT, 8);
MMIO_F(IA_VERTICES_COUNT, 8);
MMIO_F(IA_PRIMITIVES_COUNT, 8);
MMIO_F(VS_INVOCATION_COUNT, 8);
MMIO_F(GS_INVOCATION_COUNT, 8);
MMIO_F(GS_PRIMITIVES_COUNT, 8);
MMIO_F(CL_INVOCATION_COUNT, 8);
MMIO_F(CL_PRIMITIVES_COUNT, 8);
MMIO_F(PS_INVOCATION_COUNT, 8);
MMIO_F(PS_DEPTH_COUNT, 8);
MMIO_D(ARB_MODE);
MMIO_RING_D(RING_BBADDR);
MMIO_D(_MMIO(0x2220));
MMIO_D(_MMIO(0x12220));
MMIO_D(_MMIO(0x22220));
MMIO_RING_D(RING_SYNC_1);
MMIO_RING_D(RING_SYNC_0);
MMIO_D(GUC_STATUS);
MMIO_F(_MMIO(MCHBAR_MIRROR_BASE_SNB), 0x40000);
MMIO_F(_MMIO(VGT_PVINFO_PAGE), VGT_PVINFO_SIZE);
MMIO_F(LGC_PALETTE(PIPE_A, 0), 1024);
MMIO_F(LGC_PALETTE(PIPE_B, 0), 1024);
MMIO_F(LGC_PALETTE(PIPE_C, 0), 1024);
return 0;
}
static int iterate_bdw_only_mmio(struct intel_gvt_mmio_table_iter *iter)
{
MMIO_D(HSW_PWR_WELL_CTL1);
MMIO_D(HSW_PWR_WELL_CTL2);
MMIO_D(HSW_PWR_WELL_CTL3);
MMIO_D(HSW_PWR_WELL_CTL4);
MMIO_D(HSW_PWR_WELL_CTL5);
MMIO_D(HSW_PWR_WELL_CTL6);
MMIO_D(WM_MISC);
MMIO_D(_MMIO(_SRD_CTL_EDP));
MMIO_D(_MMIO(0xb1f0));
MMIO_D(_MMIO(0xb1c0));
MMIO_D(_MMIO(0xb100));
MMIO_D(_MMIO(0xb10c));
MMIO_D(_MMIO(0xb110));
MMIO_D(_MMIO(0x83a4));
MMIO_D(_MMIO(0x8430));
MMIO_D(_MMIO(0x2248));
MMIO_D(FORCEWAKE_ACK_HSW);
return 0;
}
static int iterate_bdw_plus_mmio(struct intel_gvt_mmio_table_iter *iter)
{
struct drm_i915_private *dev_priv = iter->i915;
MMIO_D(GEN8_GT_IMR(0));
MMIO_D(GEN8_GT_IER(0));
MMIO_D(GEN8_GT_IIR(0));
MMIO_D(GEN8_GT_ISR(0));
MMIO_D(GEN8_GT_IMR(1));
MMIO_D(GEN8_GT_IER(1));
MMIO_D(GEN8_GT_IIR(1));
MMIO_D(GEN8_GT_ISR(1));
MMIO_D(GEN8_GT_IMR(2));
MMIO_D(GEN8_GT_IER(2));
MMIO_D(GEN8_GT_IIR(2));
MMIO_D(GEN8_GT_ISR(2));
MMIO_D(GEN8_GT_IMR(3));
MMIO_D(GEN8_GT_IER(3));
MMIO_D(GEN8_GT_IIR(3));
MMIO_D(GEN8_GT_ISR(3));
MMIO_D(GEN8_DE_PIPE_IMR(PIPE_A));
MMIO_D(GEN8_DE_PIPE_IER(PIPE_A));
MMIO_D(GEN8_DE_PIPE_IIR(PIPE_A));
MMIO_D(GEN8_DE_PIPE_ISR(PIPE_A));
MMIO_D(GEN8_DE_PIPE_IMR(PIPE_B));
MMIO_D(GEN8_DE_PIPE_IER(PIPE_B));
MMIO_D(GEN8_DE_PIPE_IIR(PIPE_B));
MMIO_D(GEN8_DE_PIPE_ISR(PIPE_B));
MMIO_D(GEN8_DE_PIPE_IMR(PIPE_C));
MMIO_D(GEN8_DE_PIPE_IER(PIPE_C));
MMIO_D(GEN8_DE_PIPE_IIR(PIPE_C));
MMIO_D(GEN8_DE_PIPE_ISR(PIPE_C));
MMIO_D(GEN8_DE_PORT_IMR);
MMIO_D(GEN8_DE_PORT_IER);
MMIO_D(GEN8_DE_PORT_IIR);
MMIO_D(GEN8_DE_PORT_ISR);
MMIO_D(GEN8_DE_MISC_IMR);
MMIO_D(GEN8_DE_MISC_IER);
MMIO_D(GEN8_DE_MISC_IIR);
MMIO_D(GEN8_DE_MISC_ISR);
MMIO_D(GEN8_PCU_IMR);
MMIO_D(GEN8_PCU_IER);
MMIO_D(GEN8_PCU_IIR);
MMIO_D(GEN8_PCU_ISR);
MMIO_D(GEN8_MASTER_IRQ);
MMIO_RING_D(RING_ACTHD_UDW);
#define RING_REG(base) _MMIO((base) + 0xd0)
MMIO_RING_D(RING_REG);
#undef RING_REG
#define RING_REG(base) _MMIO((base) + 0x230)
MMIO_RING_D(RING_REG);
#undef RING_REG
#define RING_REG(base) _MMIO((base) + 0x234)
MMIO_RING_F(RING_REG, 8);
#undef RING_REG
#define RING_REG(base) _MMIO((base) + 0x244)
MMIO_RING_D(RING_REG);
#undef RING_REG
#define RING_REG(base) _MMIO((base) + 0x370)
MMIO_RING_F(RING_REG, 48);
#undef RING_REG
#define RING_REG(base) _MMIO((base) + 0x3a0)
MMIO_RING_D(RING_REG);
#undef RING_REG
MMIO_D(PIPE_MISC(PIPE_A));
MMIO_D(PIPE_MISC(PIPE_B));
MMIO_D(PIPE_MISC(PIPE_C));
MMIO_D(_MMIO(0x1c1d0));
MMIO_D(GEN6_MBCUNIT_SNPCR);
MMIO_D(GEN7_MISCCPCTL);
MMIO_D(_MMIO(0x1c054));
MMIO_D(GEN6_PCODE_MAILBOX);
if (!IS_BROXTON(dev_priv))
MMIO_D(GEN8_PRIVATE_PAT_LO);
MMIO_D(GEN8_PRIVATE_PAT_HI);
MMIO_D(GAMTARBMODE);
#define RING_REG(base) _MMIO((base) + 0x270)
MMIO_RING_F(RING_REG, 32);
#undef RING_REG
MMIO_RING_D(RING_HWS_PGA);
MMIO_D(HDC_CHICKEN0);
MMIO_D(CHICKEN_PIPESL_1(PIPE_A));
MMIO_D(CHICKEN_PIPESL_1(PIPE_B));
MMIO_D(CHICKEN_PIPESL_1(PIPE_C));
MMIO_D(_MMIO(0x6671c));
MMIO_D(_MMIO(0x66c00));
MMIO_D(_MMIO(0x66c04));
MMIO_D(HSW_GTT_CACHE_EN);
MMIO_D(GEN8_EU_DISABLE0);
MMIO_D(GEN8_EU_DISABLE1);
MMIO_D(GEN8_EU_DISABLE2);
MMIO_D(_MMIO(0xfdc));
MMIO_D(GEN8_ROW_CHICKEN);
MMIO_D(GEN7_ROW_CHICKEN2);
MMIO_D(GEN8_UCGCTL6);
MMIO_D(GEN8_L3SQCREG4);
MMIO_D(GEN9_SCRATCH_LNCF1);
MMIO_F(_MMIO(0x24d0), 48);
MMIO_D(_MMIO(0x44484));
MMIO_D(_MMIO(0x4448c));
MMIO_D(GEN8_L3_LRA_1_GPGPU);
MMIO_D(_MMIO(0x110000));
MMIO_D(_MMIO(0x48400));
MMIO_D(_MMIO(0x6e570));
MMIO_D(_MMIO(0x65f10));
MMIO_D(_MMIO(0xe194));
MMIO_D(_MMIO(0xe188));
MMIO_D(HALF_SLICE_CHICKEN2);
MMIO_D(_MMIO(0x2580));
MMIO_D(_MMIO(0xe220));
MMIO_D(_MMIO(0xe230));
MMIO_D(_MMIO(0xe240));
MMIO_D(_MMIO(0xe260));
MMIO_D(_MMIO(0xe270));
MMIO_D(_MMIO(0xe280));
MMIO_D(_MMIO(0xe2a0));
MMIO_D(_MMIO(0xe2b0));
MMIO_D(_MMIO(0xe2c0));
MMIO_D(_MMIO(0x21f0));
MMIO_D(GEN8_GAMW_ECO_DEV_RW_IA);
MMIO_D(_MMIO(0x215c));
MMIO_F(_MMIO(0x2290), 8);
MMIO_D(_MMIO(0x2b00));
MMIO_D(_MMIO(0x2360));
MMIO_D(_MMIO(0x1c17c));
MMIO_D(_MMIO(0x1c178));
MMIO_D(_MMIO(0x4260));
MMIO_D(_MMIO(0x4264));
MMIO_D(_MMIO(0x4268));
MMIO_D(_MMIO(0x426c));
MMIO_D(_MMIO(0x4270));
MMIO_D(_MMIO(0x4094));
MMIO_D(_MMIO(0x22178));
MMIO_D(_MMIO(0x1a178));
MMIO_D(_MMIO(0x1a17c));
MMIO_D(_MMIO(0x2217c));
MMIO_D(EDP_PSR_IMR);
MMIO_D(EDP_PSR_IIR);
MMIO_D(_MMIO(0xe4cc));
MMIO_D(GEN7_SC_INSTDONE);
return 0;
}
static int iterate_pre_skl_mmio(struct intel_gvt_mmio_table_iter *iter)
{
MMIO_D(FORCEWAKE_MT);
MMIO_D(PCH_ADPA);
MMIO_F(_MMIO(_PCH_DPB_AUX_CH_CTL), 6 * 4);
MMIO_F(_MMIO(_PCH_DPC_AUX_CH_CTL), 6 * 4);
MMIO_F(_MMIO(_PCH_DPD_AUX_CH_CTL), 6 * 4);
MMIO_F(_MMIO(0x70440), 0xc);
MMIO_F(_MMIO(0x71440), 0xc);
MMIO_F(_MMIO(0x72440), 0xc);
MMIO_F(_MMIO(0x7044c), 0xc);
MMIO_F(_MMIO(0x7144c), 0xc);
MMIO_F(_MMIO(0x7244c), 0xc);
return 0;
}
static int iterate_skl_plus_mmio(struct intel_gvt_mmio_table_iter *iter)
{
struct drm_i915_private *dev_priv = iter->i915;
MMIO_D(FORCEWAKE_RENDER_GEN9);
MMIO_D(FORCEWAKE_ACK_RENDER_GEN9);
MMIO_D(FORCEWAKE_GT_GEN9);
MMIO_D(FORCEWAKE_ACK_GT_GEN9);
MMIO_D(FORCEWAKE_MEDIA_GEN9);
MMIO_D(FORCEWAKE_ACK_MEDIA_GEN9);
MMIO_F(DP_AUX_CH_CTL(AUX_CH_B), 6 * 4);
MMIO_F(DP_AUX_CH_CTL(AUX_CH_C), 6 * 4);
MMIO_F(DP_AUX_CH_CTL(AUX_CH_D), 6 * 4);
MMIO_D(HSW_PWR_WELL_CTL1);
MMIO_D(HSW_PWR_WELL_CTL2);
MMIO_D(DBUF_CTL_S(0));
MMIO_D(GEN9_PG_ENABLE);
MMIO_D(GEN9_MEDIA_PG_IDLE_HYSTERESIS);
MMIO_D(GEN9_RENDER_PG_IDLE_HYSTERESIS);
MMIO_D(GEN9_GAMT_ECO_REG_RW_IA);
MMIO_D(MMCD_MISC_CTRL);
MMIO_D(CHICKEN_PAR1_1);
MMIO_D(DC_STATE_EN);
MMIO_D(DC_STATE_DEBUG);
MMIO_D(CDCLK_CTL);
MMIO_D(LCPLL1_CTL);
MMIO_D(LCPLL2_CTL);
MMIO_D(_MMIO(_DPLL1_CFGCR1));
MMIO_D(_MMIO(_DPLL2_CFGCR1));
MMIO_D(_MMIO(_DPLL3_CFGCR1));
MMIO_D(_MMIO(_DPLL1_CFGCR2));
MMIO_D(_MMIO(_DPLL2_CFGCR2));
MMIO_D(_MMIO(_DPLL3_CFGCR2));
MMIO_D(DPLL_CTRL1);
MMIO_D(DPLL_CTRL2);
MMIO_D(DPLL_STATUS);
MMIO_D(SKL_PS_WIN_POS(PIPE_A, 0));
MMIO_D(SKL_PS_WIN_POS(PIPE_A, 1));
MMIO_D(SKL_PS_WIN_POS(PIPE_B, 0));
MMIO_D(SKL_PS_WIN_POS(PIPE_B, 1));
MMIO_D(SKL_PS_WIN_POS(PIPE_C, 0));
MMIO_D(SKL_PS_WIN_POS(PIPE_C, 1));
MMIO_D(SKL_PS_WIN_SZ(PIPE_A, 0));
MMIO_D(SKL_PS_WIN_SZ(PIPE_A, 1));
MMIO_D(SKL_PS_WIN_SZ(PIPE_B, 0));
MMIO_D(SKL_PS_WIN_SZ(PIPE_B, 1));
MMIO_D(SKL_PS_WIN_SZ(PIPE_C, 0));
MMIO_D(SKL_PS_WIN_SZ(PIPE_C, 1));
MMIO_D(SKL_PS_CTRL(PIPE_A, 0));
MMIO_D(SKL_PS_CTRL(PIPE_A, 1));
MMIO_D(SKL_PS_CTRL(PIPE_B, 0));
MMIO_D(SKL_PS_CTRL(PIPE_B, 1));
MMIO_D(SKL_PS_CTRL(PIPE_C, 0));
MMIO_D(SKL_PS_CTRL(PIPE_C, 1));
MMIO_D(PLANE_BUF_CFG(PIPE_A, 0));
MMIO_D(PLANE_BUF_CFG(PIPE_A, 1));
MMIO_D(PLANE_BUF_CFG(PIPE_A, 2));
MMIO_D(PLANE_BUF_CFG(PIPE_A, 3));
MMIO_D(PLANE_BUF_CFG(PIPE_B, 0));
MMIO_D(PLANE_BUF_CFG(PIPE_B, 1));
MMIO_D(PLANE_BUF_CFG(PIPE_B, 2));
MMIO_D(PLANE_BUF_CFG(PIPE_B, 3));
MMIO_D(PLANE_BUF_CFG(PIPE_C, 0));
MMIO_D(PLANE_BUF_CFG(PIPE_C, 1));
MMIO_D(PLANE_BUF_CFG(PIPE_C, 2));
MMIO_D(PLANE_BUF_CFG(PIPE_C, 3));
MMIO_D(CUR_BUF_CFG(PIPE_A));
MMIO_D(CUR_BUF_CFG(PIPE_B));
MMIO_D(CUR_BUF_CFG(PIPE_C));
MMIO_F(PLANE_WM(PIPE_A, 0, 0), 4 * 8);
MMIO_F(PLANE_WM(PIPE_A, 1, 0), 4 * 8);
MMIO_F(PLANE_WM(PIPE_A, 2, 0), 4 * 8);
MMIO_F(PLANE_WM(PIPE_B, 0, 0), 4 * 8);
MMIO_F(PLANE_WM(PIPE_B, 1, 0), 4 * 8);
MMIO_F(PLANE_WM(PIPE_B, 2, 0), 4 * 8);
MMIO_F(PLANE_WM(PIPE_C, 0, 0), 4 * 8);
MMIO_F(PLANE_WM(PIPE_C, 1, 0), 4 * 8);
MMIO_F(PLANE_WM(PIPE_C, 2, 0), 4 * 8);
MMIO_F(CUR_WM(PIPE_A, 0), 4 * 8);
MMIO_F(CUR_WM(PIPE_B, 0), 4 * 8);
MMIO_F(CUR_WM(PIPE_C, 0), 4 * 8);
MMIO_D(PLANE_WM_TRANS(PIPE_A, 0));
MMIO_D(PLANE_WM_TRANS(PIPE_A, 1));
MMIO_D(PLANE_WM_TRANS(PIPE_A, 2));
MMIO_D(PLANE_WM_TRANS(PIPE_B, 0));
MMIO_D(PLANE_WM_TRANS(PIPE_B, 1));
MMIO_D(PLANE_WM_TRANS(PIPE_B, 2));
MMIO_D(PLANE_WM_TRANS(PIPE_C, 0));
MMIO_D(PLANE_WM_TRANS(PIPE_C, 1));
MMIO_D(PLANE_WM_TRANS(PIPE_C, 2));
MMIO_D(CUR_WM_TRANS(PIPE_A));
MMIO_D(CUR_WM_TRANS(PIPE_B));
MMIO_D(CUR_WM_TRANS(PIPE_C));
MMIO_D(PLANE_NV12_BUF_CFG(PIPE_A, 0));
MMIO_D(PLANE_NV12_BUF_CFG(PIPE_A, 1));
MMIO_D(PLANE_NV12_BUF_CFG(PIPE_A, 2));
MMIO_D(PLANE_NV12_BUF_CFG(PIPE_A, 3));
MMIO_D(PLANE_NV12_BUF_CFG(PIPE_B, 0));
MMIO_D(PLANE_NV12_BUF_CFG(PIPE_B, 1));
MMIO_D(PLANE_NV12_BUF_CFG(PIPE_B, 2));
MMIO_D(PLANE_NV12_BUF_CFG(PIPE_B, 3));
MMIO_D(PLANE_NV12_BUF_CFG(PIPE_C, 0));
MMIO_D(PLANE_NV12_BUF_CFG(PIPE_C, 1));
MMIO_D(PLANE_NV12_BUF_CFG(PIPE_C, 2));
MMIO_D(PLANE_NV12_BUF_CFG(PIPE_C, 3));
MMIO_D(_MMIO(_REG_701C0(PIPE_A, 1)));
MMIO_D(_MMIO(_REG_701C0(PIPE_A, 2)));
MMIO_D(_MMIO(_REG_701C0(PIPE_A, 3)));
MMIO_D(_MMIO(_REG_701C0(PIPE_A, 4)));
MMIO_D(_MMIO(_REG_701C0(PIPE_B, 1)));
MMIO_D(_MMIO(_REG_701C0(PIPE_B, 2)));
MMIO_D(_MMIO(_REG_701C0(PIPE_B, 3)));
MMIO_D(_MMIO(_REG_701C0(PIPE_B, 4)));
MMIO_D(_MMIO(_REG_701C0(PIPE_C, 1)));
MMIO_D(_MMIO(_REG_701C0(PIPE_C, 2)));
MMIO_D(_MMIO(_REG_701C0(PIPE_C, 3)));
MMIO_D(_MMIO(_REG_701C0(PIPE_C, 4)));
MMIO_D(_MMIO(_REG_701C4(PIPE_A, 1)));
MMIO_D(_MMIO(_REG_701C4(PIPE_A, 2)));
MMIO_D(_MMIO(_REG_701C4(PIPE_A, 3)));
MMIO_D(_MMIO(_REG_701C4(PIPE_A, 4)));
MMIO_D(_MMIO(_REG_701C4(PIPE_B, 1)));
MMIO_D(_MMIO(_REG_701C4(PIPE_B, 2)));
MMIO_D(_MMIO(_REG_701C4(PIPE_B, 3)));
MMIO_D(_MMIO(_REG_701C4(PIPE_B, 4)));
MMIO_D(_MMIO(_REG_701C4(PIPE_C, 1)));
MMIO_D(_MMIO(_REG_701C4(PIPE_C, 2)));
MMIO_D(_MMIO(_REG_701C4(PIPE_C, 3)));
MMIO_D(_MMIO(_REG_701C4(PIPE_C, 4)));
MMIO_D(_MMIO(_PLANE_CTL_3_A));
MMIO_D(_MMIO(_PLANE_CTL_3_B));
MMIO_D(_MMIO(0x72380));
MMIO_D(_MMIO(0x7239c));
MMIO_D(_MMIO(_PLANE_SURF_3_A));
MMIO_D(_MMIO(_PLANE_SURF_3_B));
MMIO_D(DMC_SSP_BASE);
MMIO_D(DMC_HTP_SKL);
MMIO_D(DMC_LAST_WRITE);
MMIO_D(BDW_SCRATCH1);
MMIO_D(SKL_DFSM);
MMIO_D(DISPIO_CR_TX_BMU_CR0);
MMIO_F(GEN9_GFX_MOCS(0), 0x7f8);
MMIO_F(GEN7_L3CNTLREG2, 0x80);
MMIO_D(RPM_CONFIG0);
MMIO_D(_MMIO(0xd08));
MMIO_D(RC6_LOCATION);
MMIO_D(GEN7_FF_SLICE_CS_CHICKEN1);
MMIO_D(GEN9_CS_DEBUG_MODE1);
/* TRTT */
MMIO_D(TRVATTL3PTRDW(0));
MMIO_D(TRVATTL3PTRDW(1));
MMIO_D(TRVATTL3PTRDW(2));
MMIO_D(TRVATTL3PTRDW(3));
MMIO_D(TRVADR);
MMIO_D(TRTTE);
MMIO_D(_MMIO(0x4dfc));
MMIO_D(_MMIO(0x46430));
MMIO_D(_MMIO(0x46520));
MMIO_D(_MMIO(0xc403c));
MMIO_D(GEN8_GARBCNTL);
MMIO_D(DMA_CTRL);
MMIO_D(_MMIO(0x65900));
MMIO_D(GEN6_STOLEN_RESERVED);
MMIO_D(_MMIO(0x4068));
MMIO_D(_MMIO(0x67054));
MMIO_D(_MMIO(0x6e560));
MMIO_D(_MMIO(0x6e554));
MMIO_D(_MMIO(0x2b20));
MMIO_D(_MMIO(0x65f00));
MMIO_D(_MMIO(0x65f08));
MMIO_D(_MMIO(0x320f0));
MMIO_D(_MMIO(0x70034));
MMIO_D(_MMIO(0x71034));
MMIO_D(_MMIO(0x72034));
MMIO_D(_MMIO(_PLANE_KEYVAL_1(PIPE_A)));
MMIO_D(_MMIO(_PLANE_KEYVAL_1(PIPE_B)));
MMIO_D(_MMIO(_PLANE_KEYVAL_1(PIPE_C)));
MMIO_D(_MMIO(_PLANE_KEYMAX_1(PIPE_A)));
MMIO_D(_MMIO(_PLANE_KEYMAX_1(PIPE_B)));
MMIO_D(_MMIO(_PLANE_KEYMAX_1(PIPE_C)));
MMIO_D(_MMIO(_PLANE_KEYMSK_1(PIPE_A)));
MMIO_D(_MMIO(_PLANE_KEYMSK_1(PIPE_B)));
MMIO_D(_MMIO(_PLANE_KEYMSK_1(PIPE_C)));
MMIO_D(_MMIO(0x44500));
#define CSFE_CHICKEN1_REG(base) _MMIO((base) + 0xD4)
MMIO_RING_D(CSFE_CHICKEN1_REG);
#undef CSFE_CHICKEN1_REG
MMIO_D(GEN8_HDC_CHICKEN1);
MMIO_D(GEN9_WM_CHICKEN3);
if (IS_KABYLAKE(dev_priv) ||
IS_COFFEELAKE(dev_priv) || IS_COMETLAKE(dev_priv))
MMIO_D(GAMT_CHKN_BIT_REG);
if (!IS_BROXTON(dev_priv))
MMIO_D(GEN9_CTX_PREEMPT_REG);
MMIO_F(_MMIO(DMC_MMIO_START_RANGE), 0x3000);
return 0;
}
static int iterate_bxt_mmio(struct intel_gvt_mmio_table_iter *iter)
{
struct drm_i915_private *dev_priv = iter->i915;
MMIO_F(_MMIO(0x80000), 0x3000);
MMIO_D(GEN7_SAMPLER_INSTDONE);
MMIO_D(GEN7_ROW_INSTDONE);
MMIO_D(GEN8_FAULT_TLB_DATA0);
MMIO_D(GEN8_FAULT_TLB_DATA1);
MMIO_D(ERROR_GEN6);
MMIO_D(DONE_REG);
MMIO_D(EIR);
MMIO_D(PGTBL_ER);
MMIO_D(_MMIO(0x4194));
MMIO_D(_MMIO(0x4294));
MMIO_D(_MMIO(0x4494));
MMIO_RING_D(RING_PSMI_CTL);
MMIO_RING_D(RING_DMA_FADD);
MMIO_RING_D(RING_DMA_FADD_UDW);
MMIO_RING_D(RING_IPEHR);
MMIO_RING_D(RING_INSTPS);
MMIO_RING_D(RING_BBADDR_UDW);
MMIO_RING_D(RING_BBSTATE);
MMIO_RING_D(RING_IPEIR);
MMIO_F(SOFT_SCRATCH(0), 16 * 4);
MMIO_D(BXT_P_CR_GT_DISP_PWRON);
MMIO_D(BXT_RP_STATE_CAP);
MMIO_D(BXT_PHY_CTL_FAMILY(DPIO_PHY0));
MMIO_D(BXT_PHY_CTL_FAMILY(DPIO_PHY1));
MMIO_D(BXT_PHY_CTL(PORT_A));
MMIO_D(BXT_PHY_CTL(PORT_B));
MMIO_D(BXT_PHY_CTL(PORT_C));
MMIO_D(BXT_PORT_PLL_ENABLE(PORT_A));
MMIO_D(BXT_PORT_PLL_ENABLE(PORT_B));
MMIO_D(BXT_PORT_PLL_ENABLE(PORT_C));
MMIO_D(BXT_PORT_CL1CM_DW0(DPIO_PHY0));
MMIO_D(BXT_PORT_CL1CM_DW9(DPIO_PHY0));
MMIO_D(BXT_PORT_CL1CM_DW10(DPIO_PHY0));
MMIO_D(BXT_PORT_CL1CM_DW28(DPIO_PHY0));
MMIO_D(BXT_PORT_CL1CM_DW30(DPIO_PHY0));
MMIO_D(BXT_PORT_CL2CM_DW6(DPIO_PHY0));
MMIO_D(BXT_PORT_REF_DW3(DPIO_PHY0));
MMIO_D(BXT_PORT_REF_DW6(DPIO_PHY0));
MMIO_D(BXT_PORT_REF_DW8(DPIO_PHY0));
MMIO_D(BXT_PORT_CL1CM_DW0(DPIO_PHY1));
MMIO_D(BXT_PORT_CL1CM_DW9(DPIO_PHY1));
MMIO_D(BXT_PORT_CL1CM_DW10(DPIO_PHY1));
MMIO_D(BXT_PORT_CL1CM_DW28(DPIO_PHY1));
MMIO_D(BXT_PORT_CL1CM_DW30(DPIO_PHY1));
MMIO_D(BXT_PORT_CL2CM_DW6(DPIO_PHY1));
MMIO_D(BXT_PORT_REF_DW3(DPIO_PHY1));
MMIO_D(BXT_PORT_REF_DW6(DPIO_PHY1));
MMIO_D(BXT_PORT_REF_DW8(DPIO_PHY1));
MMIO_D(BXT_PORT_PLL_EBB_0(DPIO_PHY0, DPIO_CH0));
MMIO_D(BXT_PORT_PLL_EBB_4(DPIO_PHY0, DPIO_CH0));
MMIO_D(BXT_PORT_PCS_DW10_LN01(DPIO_PHY0, DPIO_CH0));
MMIO_D(BXT_PORT_PCS_DW10_GRP(DPIO_PHY0, DPIO_CH0));
MMIO_D(BXT_PORT_PCS_DW12_LN01(DPIO_PHY0, DPIO_CH0));
MMIO_D(BXT_PORT_PCS_DW12_LN23(DPIO_PHY0, DPIO_CH0));
MMIO_D(BXT_PORT_PCS_DW12_GRP(DPIO_PHY0, DPIO_CH0));
MMIO_D(BXT_PORT_TX_DW2_LN0(DPIO_PHY0, DPIO_CH0));
MMIO_D(BXT_PORT_TX_DW2_GRP(DPIO_PHY0, DPIO_CH0));
MMIO_D(BXT_PORT_TX_DW3_LN0(DPIO_PHY0, DPIO_CH0));
MMIO_D(BXT_PORT_TX_DW3_GRP(DPIO_PHY0, DPIO_CH0));
MMIO_D(BXT_PORT_TX_DW4_LN0(DPIO_PHY0, DPIO_CH0));
MMIO_D(BXT_PORT_TX_DW4_GRP(DPIO_PHY0, DPIO_CH0));
MMIO_D(BXT_PORT_TX_DW14_LN(DPIO_PHY0, DPIO_CH0, 0));
MMIO_D(BXT_PORT_TX_DW14_LN(DPIO_PHY0, DPIO_CH0, 1));
MMIO_D(BXT_PORT_TX_DW14_LN(DPIO_PHY0, DPIO_CH0, 2));
MMIO_D(BXT_PORT_TX_DW14_LN(DPIO_PHY0, DPIO_CH0, 3));
MMIO_D(BXT_PORT_PLL(DPIO_PHY0, DPIO_CH0, 0));
MMIO_D(BXT_PORT_PLL(DPIO_PHY0, DPIO_CH0, 1));
MMIO_D(BXT_PORT_PLL(DPIO_PHY0, DPIO_CH0, 2));
MMIO_D(BXT_PORT_PLL(DPIO_PHY0, DPIO_CH0, 3));
MMIO_D(BXT_PORT_PLL(DPIO_PHY0, DPIO_CH0, 6));
MMIO_D(BXT_PORT_PLL(DPIO_PHY0, DPIO_CH0, 8));
MMIO_D(BXT_PORT_PLL(DPIO_PHY0, DPIO_CH0, 9));
MMIO_D(BXT_PORT_PLL(DPIO_PHY0, DPIO_CH0, 10));
MMIO_D(BXT_PORT_PLL_EBB_0(DPIO_PHY0, DPIO_CH1));
MMIO_D(BXT_PORT_PLL_EBB_4(DPIO_PHY0, DPIO_CH1));
MMIO_D(BXT_PORT_PCS_DW10_LN01(DPIO_PHY0, DPIO_CH1));
MMIO_D(BXT_PORT_PCS_DW10_GRP(DPIO_PHY0, DPIO_CH1));
MMIO_D(BXT_PORT_PCS_DW12_LN01(DPIO_PHY0, DPIO_CH1));
MMIO_D(BXT_PORT_PCS_DW12_LN23(DPIO_PHY0, DPIO_CH1));
MMIO_D(BXT_PORT_PCS_DW12_GRP(DPIO_PHY0, DPIO_CH1));
MMIO_D(BXT_PORT_TX_DW2_LN0(DPIO_PHY0, DPIO_CH1));
MMIO_D(BXT_PORT_TX_DW2_GRP(DPIO_PHY0, DPIO_CH1));
MMIO_D(BXT_PORT_TX_DW3_LN0(DPIO_PHY0, DPIO_CH1));
MMIO_D(BXT_PORT_TX_DW3_GRP(DPIO_PHY0, DPIO_CH1));
MMIO_D(BXT_PORT_TX_DW4_LN0(DPIO_PHY0, DPIO_CH1));
MMIO_D(BXT_PORT_TX_DW4_GRP(DPIO_PHY0, DPIO_CH1));
MMIO_D(BXT_PORT_TX_DW14_LN(DPIO_PHY0, DPIO_CH1, 0));
MMIO_D(BXT_PORT_TX_DW14_LN(DPIO_PHY0, DPIO_CH1, 1));
MMIO_D(BXT_PORT_TX_DW14_LN(DPIO_PHY0, DPIO_CH1, 2));
MMIO_D(BXT_PORT_TX_DW14_LN(DPIO_PHY0, DPIO_CH1, 3));
MMIO_D(BXT_PORT_PLL(DPIO_PHY0, DPIO_CH1, 0));
MMIO_D(BXT_PORT_PLL(DPIO_PHY0, DPIO_CH1, 1));
MMIO_D(BXT_PORT_PLL(DPIO_PHY0, DPIO_CH1, 2));
MMIO_D(BXT_PORT_PLL(DPIO_PHY0, DPIO_CH1, 3));
MMIO_D(BXT_PORT_PLL(DPIO_PHY0, DPIO_CH1, 6));
MMIO_D(BXT_PORT_PLL(DPIO_PHY0, DPIO_CH1, 8));
MMIO_D(BXT_PORT_PLL(DPIO_PHY0, DPIO_CH1, 9));
MMIO_D(BXT_PORT_PLL(DPIO_PHY0, DPIO_CH1, 10));
MMIO_D(BXT_PORT_PLL_EBB_0(DPIO_PHY1, DPIO_CH0));
MMIO_D(BXT_PORT_PLL_EBB_4(DPIO_PHY1, DPIO_CH0));
MMIO_D(BXT_PORT_PCS_DW10_LN01(DPIO_PHY1, DPIO_CH0));
MMIO_D(BXT_PORT_PCS_DW10_GRP(DPIO_PHY1, DPIO_CH0));
MMIO_D(BXT_PORT_PCS_DW12_LN01(DPIO_PHY1, DPIO_CH0));
MMIO_D(BXT_PORT_PCS_DW12_LN23(DPIO_PHY1, DPIO_CH0));
MMIO_D(BXT_PORT_PCS_DW12_GRP(DPIO_PHY1, DPIO_CH0));
MMIO_D(BXT_PORT_TX_DW2_LN0(DPIO_PHY1, DPIO_CH0));
MMIO_D(BXT_PORT_TX_DW2_GRP(DPIO_PHY1, DPIO_CH0));
MMIO_D(BXT_PORT_TX_DW3_LN0(DPIO_PHY1, DPIO_CH0));
MMIO_D(BXT_PORT_TX_DW3_GRP(DPIO_PHY1, DPIO_CH0));
MMIO_D(BXT_PORT_TX_DW4_LN0(DPIO_PHY1, DPIO_CH0));
MMIO_D(BXT_PORT_TX_DW4_GRP(DPIO_PHY1, DPIO_CH0));
MMIO_D(BXT_PORT_TX_DW14_LN(DPIO_PHY1, DPIO_CH0, 0));
MMIO_D(BXT_PORT_TX_DW14_LN(DPIO_PHY1, DPIO_CH0, 1));
MMIO_D(BXT_PORT_TX_DW14_LN(DPIO_PHY1, DPIO_CH0, 2));
MMIO_D(BXT_PORT_TX_DW14_LN(DPIO_PHY1, DPIO_CH0, 3));
MMIO_D(BXT_PORT_PLL(DPIO_PHY1, DPIO_CH0, 0));
MMIO_D(BXT_PORT_PLL(DPIO_PHY1, DPIO_CH0, 1));
MMIO_D(BXT_PORT_PLL(DPIO_PHY1, DPIO_CH0, 2));
MMIO_D(BXT_PORT_PLL(DPIO_PHY1, DPIO_CH0, 3));
MMIO_D(BXT_PORT_PLL(DPIO_PHY1, DPIO_CH0, 6));
MMIO_D(BXT_PORT_PLL(DPIO_PHY1, DPIO_CH0, 8));
MMIO_D(BXT_PORT_PLL(DPIO_PHY1, DPIO_CH0, 9));
MMIO_D(BXT_PORT_PLL(DPIO_PHY1, DPIO_CH0, 10));
MMIO_D(BXT_DE_PLL_CTL);
MMIO_D(BXT_DE_PLL_ENABLE);
MMIO_D(BXT_DSI_PLL_CTL);
MMIO_D(BXT_DSI_PLL_ENABLE);
MMIO_D(GEN9_CLKGATE_DIS_0);
MMIO_D(GEN9_CLKGATE_DIS_4);
MMIO_D(HSW_TVIDEO_DIP_GCP(TRANSCODER_A));
MMIO_D(HSW_TVIDEO_DIP_GCP(TRANSCODER_B));
MMIO_D(HSW_TVIDEO_DIP_GCP(TRANSCODER_C));
MMIO_D(RC6_CTX_BASE);
MMIO_D(GEN8_PUSHBUS_CONTROL);
MMIO_D(GEN8_PUSHBUS_ENABLE);
MMIO_D(GEN8_PUSHBUS_SHIFT);
MMIO_D(GEN6_GFXPAUSE);
MMIO_D(GEN8_L3SQCREG1);
MMIO_D(GEN8_L3CNTLREG);
MMIO_D(_MMIO(0x20D8));
MMIO_F(GEN8_RING_CS_GPR(RENDER_RING_BASE, 0), 0x40);
MMIO_F(GEN8_RING_CS_GPR(GEN6_BSD_RING_BASE, 0), 0x40);
MMIO_F(GEN8_RING_CS_GPR(BLT_RING_BASE, 0), 0x40);
MMIO_F(GEN8_RING_CS_GPR(VEBOX_RING_BASE, 0), 0x40);
MMIO_D(GEN9_CTX_PREEMPT_REG);
MMIO_D(GEN8_PRIVATE_PAT_LO);
return 0;
}
/**
* intel_gvt_iterate_mmio_table - Iterate the GVT MMIO table
* @iter: the interator
*
* This function is called for iterating the GVT MMIO table when i915 is
* taking the snapshot of the HW and GVT is building MMIO tracking table.
*/
int intel_gvt_iterate_mmio_table(struct intel_gvt_mmio_table_iter *iter)
{
struct drm_i915_private *i915 = iter->i915;
int ret;
ret = iterate_generic_mmio(iter);
if (ret)
goto err;
if (IS_BROADWELL(i915)) {
ret = iterate_bdw_only_mmio(iter);
if (ret)
goto err;
ret = iterate_bdw_plus_mmio(iter);
if (ret)
goto err;
ret = iterate_pre_skl_mmio(iter);
if (ret)
goto err;
} else if (IS_SKYLAKE(i915) ||
IS_KABYLAKE(i915) ||
IS_COFFEELAKE(i915) ||
IS_COMETLAKE(i915)) {
ret = iterate_bdw_plus_mmio(iter);
if (ret)
goto err;
ret = iterate_skl_plus_mmio(iter);
if (ret)
goto err;
} else if (IS_BROXTON(i915)) {
ret = iterate_bdw_plus_mmio(iter);
if (ret)
goto err;
ret = iterate_skl_plus_mmio(iter);
if (ret)
goto err;
ret = iterate_bxt_mmio(iter);
if (ret)
goto err;
}
return 0;
err:
return ret;
}
EXPORT_SYMBOL_NS_GPL(intel_gvt_iterate_mmio_table, I915_GVT);
| linux-master | drivers/gpu/drm/i915/intel_gvt_mmio_table.c |
/* i915_irq.c -- IRQ support for the I915 -*- linux-c -*-
*/
/*
* Copyright 2003 Tungsten Graphics, Inc., Cedar Park, Texas.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
* IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/slab.h>
#include <linux/sysrq.h>
#include <drm/drm_drv.h>
#include "display/intel_display_irq.h"
#include "display/intel_display_types.h"
#include "display/intel_hotplug.h"
#include "display/intel_hotplug_irq.h"
#include "display/intel_lpe_audio.h"
#include "display/intel_psr_regs.h"
#include "gt/intel_breadcrumbs.h"
#include "gt/intel_gt.h"
#include "gt/intel_gt_irq.h"
#include "gt/intel_gt_pm_irq.h"
#include "gt/intel_gt_regs.h"
#include "gt/intel_rps.h"
#include "i915_driver.h"
#include "i915_drv.h"
#include "i915_irq.h"
#include "i915_reg.h"
/**
* DOC: interrupt handling
*
* These functions provide the basic support for enabling and disabling the
* interrupt handling support. There's a lot more functionality in i915_irq.c
* and related files, but that will be described in separate chapters.
*/
/*
* Interrupt statistic for PMU. Increments the counter only if the
* interrupt originated from the GPU so interrupts from a device which
* shares the interrupt line are not accounted.
*/
static inline void pmu_irq_stats(struct drm_i915_private *i915,
irqreturn_t res)
{
if (unlikely(res != IRQ_HANDLED))
return;
/*
* A clever compiler translates that into INC. A not so clever one
* should at least prevent store tearing.
*/
WRITE_ONCE(i915->pmu.irq_count, i915->pmu.irq_count + 1);
}
void gen3_irq_reset(struct intel_uncore *uncore, i915_reg_t imr,
i915_reg_t iir, i915_reg_t ier)
{
intel_uncore_write(uncore, imr, 0xffffffff);
intel_uncore_posting_read(uncore, imr);
intel_uncore_write(uncore, ier, 0);
/* IIR can theoretically queue up two events. Be paranoid. */
intel_uncore_write(uncore, iir, 0xffffffff);
intel_uncore_posting_read(uncore, iir);
intel_uncore_write(uncore, iir, 0xffffffff);
intel_uncore_posting_read(uncore, iir);
}
static void gen2_irq_reset(struct intel_uncore *uncore)
{
intel_uncore_write16(uncore, GEN2_IMR, 0xffff);
intel_uncore_posting_read16(uncore, GEN2_IMR);
intel_uncore_write16(uncore, GEN2_IER, 0);
/* IIR can theoretically queue up two events. Be paranoid. */
intel_uncore_write16(uncore, GEN2_IIR, 0xffff);
intel_uncore_posting_read16(uncore, GEN2_IIR);
intel_uncore_write16(uncore, GEN2_IIR, 0xffff);
intel_uncore_posting_read16(uncore, GEN2_IIR);
}
/*
* We should clear IMR at preinstall/uninstall, and just check at postinstall.
*/
void gen3_assert_iir_is_zero(struct intel_uncore *uncore, i915_reg_t reg)
{
u32 val = intel_uncore_read(uncore, reg);
if (val == 0)
return;
drm_WARN(&uncore->i915->drm, 1,
"Interrupt register 0x%x is not zero: 0x%08x\n",
i915_mmio_reg_offset(reg), val);
intel_uncore_write(uncore, reg, 0xffffffff);
intel_uncore_posting_read(uncore, reg);
intel_uncore_write(uncore, reg, 0xffffffff);
intel_uncore_posting_read(uncore, reg);
}
static void gen2_assert_iir_is_zero(struct intel_uncore *uncore)
{
u16 val = intel_uncore_read16(uncore, GEN2_IIR);
if (val == 0)
return;
drm_WARN(&uncore->i915->drm, 1,
"Interrupt register 0x%x is not zero: 0x%08x\n",
i915_mmio_reg_offset(GEN2_IIR), val);
intel_uncore_write16(uncore, GEN2_IIR, 0xffff);
intel_uncore_posting_read16(uncore, GEN2_IIR);
intel_uncore_write16(uncore, GEN2_IIR, 0xffff);
intel_uncore_posting_read16(uncore, GEN2_IIR);
}
void gen3_irq_init(struct intel_uncore *uncore,
i915_reg_t imr, u32 imr_val,
i915_reg_t ier, u32 ier_val,
i915_reg_t iir)
{
gen3_assert_iir_is_zero(uncore, iir);
intel_uncore_write(uncore, ier, ier_val);
intel_uncore_write(uncore, imr, imr_val);
intel_uncore_posting_read(uncore, imr);
}
static void gen2_irq_init(struct intel_uncore *uncore,
u32 imr_val, u32 ier_val)
{
gen2_assert_iir_is_zero(uncore);
intel_uncore_write16(uncore, GEN2_IER, ier_val);
intel_uncore_write16(uncore, GEN2_IMR, imr_val);
intel_uncore_posting_read16(uncore, GEN2_IMR);
}
/**
* ivb_parity_work - Workqueue called when a parity error interrupt
* occurred.
* @work: workqueue struct
*
* Doesn't actually do anything except notify userspace. As a consequence of
* this event, userspace should try to remap the bad rows since statistically
* it is likely the same row is more likely to go bad again.
*/
static void ivb_parity_work(struct work_struct *work)
{
struct drm_i915_private *dev_priv =
container_of(work, typeof(*dev_priv), l3_parity.error_work);
struct intel_gt *gt = to_gt(dev_priv);
u32 error_status, row, bank, subbank;
char *parity_event[6];
u32 misccpctl;
u8 slice = 0;
/* We must turn off DOP level clock gating to access the L3 registers.
* In order to prevent a get/put style interface, acquire struct mutex
* any time we access those registers.
*/
mutex_lock(&dev_priv->drm.struct_mutex);
/* If we've screwed up tracking, just let the interrupt fire again */
if (drm_WARN_ON(&dev_priv->drm, !dev_priv->l3_parity.which_slice))
goto out;
misccpctl = intel_uncore_rmw(&dev_priv->uncore, GEN7_MISCCPCTL,
GEN7_DOP_CLOCK_GATE_ENABLE, 0);
intel_uncore_posting_read(&dev_priv->uncore, GEN7_MISCCPCTL);
while ((slice = ffs(dev_priv->l3_parity.which_slice)) != 0) {
i915_reg_t reg;
slice--;
if (drm_WARN_ON_ONCE(&dev_priv->drm,
slice >= NUM_L3_SLICES(dev_priv)))
break;
dev_priv->l3_parity.which_slice &= ~(1<<slice);
reg = GEN7_L3CDERRST1(slice);
error_status = intel_uncore_read(&dev_priv->uncore, reg);
row = GEN7_PARITY_ERROR_ROW(error_status);
bank = GEN7_PARITY_ERROR_BANK(error_status);
subbank = GEN7_PARITY_ERROR_SUBBANK(error_status);
intel_uncore_write(&dev_priv->uncore, reg, GEN7_PARITY_ERROR_VALID | GEN7_L3CDERRST1_ENABLE);
intel_uncore_posting_read(&dev_priv->uncore, reg);
parity_event[0] = I915_L3_PARITY_UEVENT "=1";
parity_event[1] = kasprintf(GFP_KERNEL, "ROW=%d", row);
parity_event[2] = kasprintf(GFP_KERNEL, "BANK=%d", bank);
parity_event[3] = kasprintf(GFP_KERNEL, "SUBBANK=%d", subbank);
parity_event[4] = kasprintf(GFP_KERNEL, "SLICE=%d", slice);
parity_event[5] = NULL;
kobject_uevent_env(&dev_priv->drm.primary->kdev->kobj,
KOBJ_CHANGE, parity_event);
drm_dbg(&dev_priv->drm,
"Parity error: Slice = %d, Row = %d, Bank = %d, Sub bank = %d.\n",
slice, row, bank, subbank);
kfree(parity_event[4]);
kfree(parity_event[3]);
kfree(parity_event[2]);
kfree(parity_event[1]);
}
intel_uncore_write(&dev_priv->uncore, GEN7_MISCCPCTL, misccpctl);
out:
drm_WARN_ON(&dev_priv->drm, dev_priv->l3_parity.which_slice);
spin_lock_irq(gt->irq_lock);
gen5_gt_enable_irq(gt, GT_PARITY_ERROR(dev_priv));
spin_unlock_irq(gt->irq_lock);
mutex_unlock(&dev_priv->drm.struct_mutex);
}
static irqreturn_t valleyview_irq_handler(int irq, void *arg)
{
struct drm_i915_private *dev_priv = arg;
irqreturn_t ret = IRQ_NONE;
if (!intel_irqs_enabled(dev_priv))
return IRQ_NONE;
/* IRQs are synced during runtime_suspend, we don't require a wakeref */
disable_rpm_wakeref_asserts(&dev_priv->runtime_pm);
do {
u32 iir, gt_iir, pm_iir;
u32 pipe_stats[I915_MAX_PIPES] = {};
u32 hotplug_status = 0;
u32 ier = 0;
gt_iir = intel_uncore_read(&dev_priv->uncore, GTIIR);
pm_iir = intel_uncore_read(&dev_priv->uncore, GEN6_PMIIR);
iir = intel_uncore_read(&dev_priv->uncore, VLV_IIR);
if (gt_iir == 0 && pm_iir == 0 && iir == 0)
break;
ret = IRQ_HANDLED;
/*
* Theory on interrupt generation, based on empirical evidence:
*
* x = ((VLV_IIR & VLV_IER) ||
* (((GT_IIR & GT_IER) || (GEN6_PMIIR & GEN6_PMIER)) &&
* (VLV_MASTER_IER & MASTER_INTERRUPT_ENABLE)));
*
* A CPU interrupt will only be raised when 'x' has a 0->1 edge.
* Hence we clear MASTER_INTERRUPT_ENABLE and VLV_IER to
* guarantee the CPU interrupt will be raised again even if we
* don't end up clearing all the VLV_IIR, GT_IIR, GEN6_PMIIR
* bits this time around.
*/
intel_uncore_write(&dev_priv->uncore, VLV_MASTER_IER, 0);
ier = intel_uncore_rmw(&dev_priv->uncore, VLV_IER, ~0, 0);
if (gt_iir)
intel_uncore_write(&dev_priv->uncore, GTIIR, gt_iir);
if (pm_iir)
intel_uncore_write(&dev_priv->uncore, GEN6_PMIIR, pm_iir);
if (iir & I915_DISPLAY_PORT_INTERRUPT)
hotplug_status = i9xx_hpd_irq_ack(dev_priv);
/* Call regardless, as some status bits might not be
* signalled in iir */
i9xx_pipestat_irq_ack(dev_priv, iir, pipe_stats);
if (iir & (I915_LPE_PIPE_A_INTERRUPT |
I915_LPE_PIPE_B_INTERRUPT))
intel_lpe_audio_irq_handler(dev_priv);
/*
* VLV_IIR is single buffered, and reflects the level
* from PIPESTAT/PORT_HOTPLUG_STAT, hence clear it last.
*/
if (iir)
intel_uncore_write(&dev_priv->uncore, VLV_IIR, iir);
intel_uncore_write(&dev_priv->uncore, VLV_IER, ier);
intel_uncore_write(&dev_priv->uncore, VLV_MASTER_IER, MASTER_INTERRUPT_ENABLE);
if (gt_iir)
gen6_gt_irq_handler(to_gt(dev_priv), gt_iir);
if (pm_iir)
gen6_rps_irq_handler(&to_gt(dev_priv)->rps, pm_iir);
if (hotplug_status)
i9xx_hpd_irq_handler(dev_priv, hotplug_status);
valleyview_pipestat_irq_handler(dev_priv, pipe_stats);
} while (0);
pmu_irq_stats(dev_priv, ret);
enable_rpm_wakeref_asserts(&dev_priv->runtime_pm);
return ret;
}
static irqreturn_t cherryview_irq_handler(int irq, void *arg)
{
struct drm_i915_private *dev_priv = arg;
irqreturn_t ret = IRQ_NONE;
if (!intel_irqs_enabled(dev_priv))
return IRQ_NONE;
/* IRQs are synced during runtime_suspend, we don't require a wakeref */
disable_rpm_wakeref_asserts(&dev_priv->runtime_pm);
do {
u32 master_ctl, iir;
u32 pipe_stats[I915_MAX_PIPES] = {};
u32 hotplug_status = 0;
u32 ier = 0;
master_ctl = intel_uncore_read(&dev_priv->uncore, GEN8_MASTER_IRQ) & ~GEN8_MASTER_IRQ_CONTROL;
iir = intel_uncore_read(&dev_priv->uncore, VLV_IIR);
if (master_ctl == 0 && iir == 0)
break;
ret = IRQ_HANDLED;
/*
* Theory on interrupt generation, based on empirical evidence:
*
* x = ((VLV_IIR & VLV_IER) ||
* ((GEN8_MASTER_IRQ & ~GEN8_MASTER_IRQ_CONTROL) &&
* (GEN8_MASTER_IRQ & GEN8_MASTER_IRQ_CONTROL)));
*
* A CPU interrupt will only be raised when 'x' has a 0->1 edge.
* Hence we clear GEN8_MASTER_IRQ_CONTROL and VLV_IER to
* guarantee the CPU interrupt will be raised again even if we
* don't end up clearing all the VLV_IIR and GEN8_MASTER_IRQ_CONTROL
* bits this time around.
*/
intel_uncore_write(&dev_priv->uncore, GEN8_MASTER_IRQ, 0);
ier = intel_uncore_rmw(&dev_priv->uncore, VLV_IER, ~0, 0);
gen8_gt_irq_handler(to_gt(dev_priv), master_ctl);
if (iir & I915_DISPLAY_PORT_INTERRUPT)
hotplug_status = i9xx_hpd_irq_ack(dev_priv);
/* Call regardless, as some status bits might not be
* signalled in iir */
i9xx_pipestat_irq_ack(dev_priv, iir, pipe_stats);
if (iir & (I915_LPE_PIPE_A_INTERRUPT |
I915_LPE_PIPE_B_INTERRUPT |
I915_LPE_PIPE_C_INTERRUPT))
intel_lpe_audio_irq_handler(dev_priv);
/*
* VLV_IIR is single buffered, and reflects the level
* from PIPESTAT/PORT_HOTPLUG_STAT, hence clear it last.
*/
if (iir)
intel_uncore_write(&dev_priv->uncore, VLV_IIR, iir);
intel_uncore_write(&dev_priv->uncore, VLV_IER, ier);
intel_uncore_write(&dev_priv->uncore, GEN8_MASTER_IRQ, GEN8_MASTER_IRQ_CONTROL);
if (hotplug_status)
i9xx_hpd_irq_handler(dev_priv, hotplug_status);
valleyview_pipestat_irq_handler(dev_priv, pipe_stats);
} while (0);
pmu_irq_stats(dev_priv, ret);
enable_rpm_wakeref_asserts(&dev_priv->runtime_pm);
return ret;
}
/*
* To handle irqs with the minimum potential races with fresh interrupts, we:
* 1 - Disable Master Interrupt Control.
* 2 - Find the source(s) of the interrupt.
* 3 - Clear the Interrupt Identity bits (IIR).
* 4 - Process the interrupt(s) that had bits set in the IIRs.
* 5 - Re-enable Master Interrupt Control.
*/
static irqreturn_t ilk_irq_handler(int irq, void *arg)
{
struct drm_i915_private *i915 = arg;
void __iomem * const regs = intel_uncore_regs(&i915->uncore);
u32 de_iir, gt_iir, de_ier, sde_ier = 0;
irqreturn_t ret = IRQ_NONE;
if (unlikely(!intel_irqs_enabled(i915)))
return IRQ_NONE;
/* IRQs are synced during runtime_suspend, we don't require a wakeref */
disable_rpm_wakeref_asserts(&i915->runtime_pm);
/* disable master interrupt before clearing iir */
de_ier = raw_reg_read(regs, DEIER);
raw_reg_write(regs, DEIER, de_ier & ~DE_MASTER_IRQ_CONTROL);
/* Disable south interrupts. We'll only write to SDEIIR once, so further
* interrupts will will be stored on its back queue, and then we'll be
* able to process them after we restore SDEIER (as soon as we restore
* it, we'll get an interrupt if SDEIIR still has something to process
* due to its back queue). */
if (!HAS_PCH_NOP(i915)) {
sde_ier = raw_reg_read(regs, SDEIER);
raw_reg_write(regs, SDEIER, 0);
}
/* Find, clear, then process each source of interrupt */
gt_iir = raw_reg_read(regs, GTIIR);
if (gt_iir) {
raw_reg_write(regs, GTIIR, gt_iir);
if (GRAPHICS_VER(i915) >= 6)
gen6_gt_irq_handler(to_gt(i915), gt_iir);
else
gen5_gt_irq_handler(to_gt(i915), gt_iir);
ret = IRQ_HANDLED;
}
de_iir = raw_reg_read(regs, DEIIR);
if (de_iir) {
raw_reg_write(regs, DEIIR, de_iir);
if (DISPLAY_VER(i915) >= 7)
ivb_display_irq_handler(i915, de_iir);
else
ilk_display_irq_handler(i915, de_iir);
ret = IRQ_HANDLED;
}
if (GRAPHICS_VER(i915) >= 6) {
u32 pm_iir = raw_reg_read(regs, GEN6_PMIIR);
if (pm_iir) {
raw_reg_write(regs, GEN6_PMIIR, pm_iir);
gen6_rps_irq_handler(&to_gt(i915)->rps, pm_iir);
ret = IRQ_HANDLED;
}
}
raw_reg_write(regs, DEIER, de_ier);
if (sde_ier)
raw_reg_write(regs, SDEIER, sde_ier);
pmu_irq_stats(i915, ret);
/* IRQs are synced during runtime_suspend, we don't require a wakeref */
enable_rpm_wakeref_asserts(&i915->runtime_pm);
return ret;
}
static inline u32 gen8_master_intr_disable(void __iomem * const regs)
{
raw_reg_write(regs, GEN8_MASTER_IRQ, 0);
/*
* Now with master disabled, get a sample of level indications
* for this interrupt. Indications will be cleared on related acks.
* New indications can and will light up during processing,
* and will generate new interrupt after enabling master.
*/
return raw_reg_read(regs, GEN8_MASTER_IRQ);
}
static inline void gen8_master_intr_enable(void __iomem * const regs)
{
raw_reg_write(regs, GEN8_MASTER_IRQ, GEN8_MASTER_IRQ_CONTROL);
}
static irqreturn_t gen8_irq_handler(int irq, void *arg)
{
struct drm_i915_private *dev_priv = arg;
void __iomem * const regs = intel_uncore_regs(&dev_priv->uncore);
u32 master_ctl;
if (!intel_irqs_enabled(dev_priv))
return IRQ_NONE;
master_ctl = gen8_master_intr_disable(regs);
if (!master_ctl) {
gen8_master_intr_enable(regs);
return IRQ_NONE;
}
/* Find, queue (onto bottom-halves), then clear each source */
gen8_gt_irq_handler(to_gt(dev_priv), master_ctl);
/* IRQs are synced during runtime_suspend, we don't require a wakeref */
if (master_ctl & ~GEN8_GT_IRQS) {
disable_rpm_wakeref_asserts(&dev_priv->runtime_pm);
gen8_de_irq_handler(dev_priv, master_ctl);
enable_rpm_wakeref_asserts(&dev_priv->runtime_pm);
}
gen8_master_intr_enable(regs);
pmu_irq_stats(dev_priv, IRQ_HANDLED);
return IRQ_HANDLED;
}
static inline u32 gen11_master_intr_disable(void __iomem * const regs)
{
raw_reg_write(regs, GEN11_GFX_MSTR_IRQ, 0);
/*
* Now with master disabled, get a sample of level indications
* for this interrupt. Indications will be cleared on related acks.
* New indications can and will light up during processing,
* and will generate new interrupt after enabling master.
*/
return raw_reg_read(regs, GEN11_GFX_MSTR_IRQ);
}
static inline void gen11_master_intr_enable(void __iomem * const regs)
{
raw_reg_write(regs, GEN11_GFX_MSTR_IRQ, GEN11_MASTER_IRQ);
}
static irqreturn_t gen11_irq_handler(int irq, void *arg)
{
struct drm_i915_private *i915 = arg;
void __iomem * const regs = intel_uncore_regs(&i915->uncore);
struct intel_gt *gt = to_gt(i915);
u32 master_ctl;
u32 gu_misc_iir;
if (!intel_irqs_enabled(i915))
return IRQ_NONE;
master_ctl = gen11_master_intr_disable(regs);
if (!master_ctl) {
gen11_master_intr_enable(regs);
return IRQ_NONE;
}
/* Find, queue (onto bottom-halves), then clear each source */
gen11_gt_irq_handler(gt, master_ctl);
/* IRQs are synced during runtime_suspend, we don't require a wakeref */
if (master_ctl & GEN11_DISPLAY_IRQ)
gen11_display_irq_handler(i915);
gu_misc_iir = gen11_gu_misc_irq_ack(i915, master_ctl);
gen11_master_intr_enable(regs);
gen11_gu_misc_irq_handler(i915, gu_misc_iir);
pmu_irq_stats(i915, IRQ_HANDLED);
return IRQ_HANDLED;
}
static inline u32 dg1_master_intr_disable(void __iomem * const regs)
{
u32 val;
/* First disable interrupts */
raw_reg_write(regs, DG1_MSTR_TILE_INTR, 0);
/* Get the indication levels and ack the master unit */
val = raw_reg_read(regs, DG1_MSTR_TILE_INTR);
if (unlikely(!val))
return 0;
raw_reg_write(regs, DG1_MSTR_TILE_INTR, val);
return val;
}
static inline void dg1_master_intr_enable(void __iomem * const regs)
{
raw_reg_write(regs, DG1_MSTR_TILE_INTR, DG1_MSTR_IRQ);
}
static irqreturn_t dg1_irq_handler(int irq, void *arg)
{
struct drm_i915_private * const i915 = arg;
struct intel_gt *gt = to_gt(i915);
void __iomem * const regs = intel_uncore_regs(gt->uncore);
u32 master_tile_ctl, master_ctl;
u32 gu_misc_iir;
if (!intel_irqs_enabled(i915))
return IRQ_NONE;
master_tile_ctl = dg1_master_intr_disable(regs);
if (!master_tile_ctl) {
dg1_master_intr_enable(regs);
return IRQ_NONE;
}
/* FIXME: we only support tile 0 for now. */
if (master_tile_ctl & DG1_MSTR_TILE(0)) {
master_ctl = raw_reg_read(regs, GEN11_GFX_MSTR_IRQ);
raw_reg_write(regs, GEN11_GFX_MSTR_IRQ, master_ctl);
} else {
drm_err(&i915->drm, "Tile not supported: 0x%08x\n",
master_tile_ctl);
dg1_master_intr_enable(regs);
return IRQ_NONE;
}
gen11_gt_irq_handler(gt, master_ctl);
if (master_ctl & GEN11_DISPLAY_IRQ)
gen11_display_irq_handler(i915);
gu_misc_iir = gen11_gu_misc_irq_ack(i915, master_ctl);
dg1_master_intr_enable(regs);
gen11_gu_misc_irq_handler(i915, gu_misc_iir);
pmu_irq_stats(i915, IRQ_HANDLED);
return IRQ_HANDLED;
}
static void ibx_irq_reset(struct drm_i915_private *dev_priv)
{
struct intel_uncore *uncore = &dev_priv->uncore;
if (HAS_PCH_NOP(dev_priv))
return;
GEN3_IRQ_RESET(uncore, SDE);
if (HAS_PCH_CPT(dev_priv) || HAS_PCH_LPT(dev_priv))
intel_uncore_write(&dev_priv->uncore, SERR_INT, 0xffffffff);
}
/* drm_dma.h hooks
*/
static void ilk_irq_reset(struct drm_i915_private *dev_priv)
{
struct intel_uncore *uncore = &dev_priv->uncore;
GEN3_IRQ_RESET(uncore, DE);
dev_priv->irq_mask = ~0u;
if (GRAPHICS_VER(dev_priv) == 7)
intel_uncore_write(uncore, GEN7_ERR_INT, 0xffffffff);
if (IS_HASWELL(dev_priv)) {
intel_uncore_write(uncore, EDP_PSR_IMR, 0xffffffff);
intel_uncore_write(uncore, EDP_PSR_IIR, 0xffffffff);
}
gen5_gt_irq_reset(to_gt(dev_priv));
ibx_irq_reset(dev_priv);
}
static void valleyview_irq_reset(struct drm_i915_private *dev_priv)
{
intel_uncore_write(&dev_priv->uncore, VLV_MASTER_IER, 0);
intel_uncore_posting_read(&dev_priv->uncore, VLV_MASTER_IER);
gen5_gt_irq_reset(to_gt(dev_priv));
spin_lock_irq(&dev_priv->irq_lock);
if (dev_priv->display_irqs_enabled)
vlv_display_irq_reset(dev_priv);
spin_unlock_irq(&dev_priv->irq_lock);
}
static void gen8_irq_reset(struct drm_i915_private *dev_priv)
{
struct intel_uncore *uncore = &dev_priv->uncore;
gen8_master_intr_disable(intel_uncore_regs(uncore));
gen8_gt_irq_reset(to_gt(dev_priv));
gen8_display_irq_reset(dev_priv);
GEN3_IRQ_RESET(uncore, GEN8_PCU_);
if (HAS_PCH_SPLIT(dev_priv))
ibx_irq_reset(dev_priv);
}
static void gen11_irq_reset(struct drm_i915_private *dev_priv)
{
struct intel_gt *gt = to_gt(dev_priv);
struct intel_uncore *uncore = gt->uncore;
gen11_master_intr_disable(intel_uncore_regs(&dev_priv->uncore));
gen11_gt_irq_reset(gt);
gen11_display_irq_reset(dev_priv);
GEN3_IRQ_RESET(uncore, GEN11_GU_MISC_);
GEN3_IRQ_RESET(uncore, GEN8_PCU_);
}
static void dg1_irq_reset(struct drm_i915_private *dev_priv)
{
struct intel_uncore *uncore = &dev_priv->uncore;
struct intel_gt *gt;
unsigned int i;
dg1_master_intr_disable(intel_uncore_regs(&dev_priv->uncore));
for_each_gt(gt, dev_priv, i)
gen11_gt_irq_reset(gt);
gen11_display_irq_reset(dev_priv);
GEN3_IRQ_RESET(uncore, GEN11_GU_MISC_);
GEN3_IRQ_RESET(uncore, GEN8_PCU_);
}
static void cherryview_irq_reset(struct drm_i915_private *dev_priv)
{
struct intel_uncore *uncore = &dev_priv->uncore;
intel_uncore_write(uncore, GEN8_MASTER_IRQ, 0);
intel_uncore_posting_read(&dev_priv->uncore, GEN8_MASTER_IRQ);
gen8_gt_irq_reset(to_gt(dev_priv));
GEN3_IRQ_RESET(uncore, GEN8_PCU_);
spin_lock_irq(&dev_priv->irq_lock);
if (dev_priv->display_irqs_enabled)
vlv_display_irq_reset(dev_priv);
spin_unlock_irq(&dev_priv->irq_lock);
}
static void ilk_irq_postinstall(struct drm_i915_private *dev_priv)
{
gen5_gt_irq_postinstall(to_gt(dev_priv));
ilk_de_irq_postinstall(dev_priv);
}
static void valleyview_irq_postinstall(struct drm_i915_private *dev_priv)
{
gen5_gt_irq_postinstall(to_gt(dev_priv));
spin_lock_irq(&dev_priv->irq_lock);
if (dev_priv->display_irqs_enabled)
vlv_display_irq_postinstall(dev_priv);
spin_unlock_irq(&dev_priv->irq_lock);
intel_uncore_write(&dev_priv->uncore, VLV_MASTER_IER, MASTER_INTERRUPT_ENABLE);
intel_uncore_posting_read(&dev_priv->uncore, VLV_MASTER_IER);
}
static void gen8_irq_postinstall(struct drm_i915_private *dev_priv)
{
gen8_gt_irq_postinstall(to_gt(dev_priv));
gen8_de_irq_postinstall(dev_priv);
gen8_master_intr_enable(intel_uncore_regs(&dev_priv->uncore));
}
static void gen11_irq_postinstall(struct drm_i915_private *dev_priv)
{
struct intel_gt *gt = to_gt(dev_priv);
struct intel_uncore *uncore = gt->uncore;
u32 gu_misc_masked = GEN11_GU_MISC_GSE;
gen11_gt_irq_postinstall(gt);
gen11_de_irq_postinstall(dev_priv);
GEN3_IRQ_INIT(uncore, GEN11_GU_MISC_, ~gu_misc_masked, gu_misc_masked);
gen11_master_intr_enable(intel_uncore_regs(uncore));
intel_uncore_posting_read(&dev_priv->uncore, GEN11_GFX_MSTR_IRQ);
}
static void dg1_irq_postinstall(struct drm_i915_private *dev_priv)
{
struct intel_uncore *uncore = &dev_priv->uncore;
u32 gu_misc_masked = GEN11_GU_MISC_GSE;
struct intel_gt *gt;
unsigned int i;
for_each_gt(gt, dev_priv, i)
gen11_gt_irq_postinstall(gt);
GEN3_IRQ_INIT(uncore, GEN11_GU_MISC_, ~gu_misc_masked, gu_misc_masked);
dg1_de_irq_postinstall(dev_priv);
dg1_master_intr_enable(intel_uncore_regs(uncore));
intel_uncore_posting_read(uncore, DG1_MSTR_TILE_INTR);
}
static void cherryview_irq_postinstall(struct drm_i915_private *dev_priv)
{
gen8_gt_irq_postinstall(to_gt(dev_priv));
spin_lock_irq(&dev_priv->irq_lock);
if (dev_priv->display_irqs_enabled)
vlv_display_irq_postinstall(dev_priv);
spin_unlock_irq(&dev_priv->irq_lock);
intel_uncore_write(&dev_priv->uncore, GEN8_MASTER_IRQ, GEN8_MASTER_IRQ_CONTROL);
intel_uncore_posting_read(&dev_priv->uncore, GEN8_MASTER_IRQ);
}
static void i8xx_irq_reset(struct drm_i915_private *dev_priv)
{
struct intel_uncore *uncore = &dev_priv->uncore;
i9xx_pipestat_irq_reset(dev_priv);
gen2_irq_reset(uncore);
dev_priv->irq_mask = ~0u;
}
static u32 i9xx_error_mask(struct drm_i915_private *i915)
{
/*
* On gen2/3 FBC generates (seemingly spurious)
* display INVALID_GTT/INVALID_GTT_PTE table errors.
*
* Also gen3 bspec has this to say:
* "DISPA_INVALID_GTT_PTE
" [DevNapa] : Reserved. This bit does not reflect the page
" table error for the display plane A."
*
* Unfortunately we can't mask off individual PGTBL_ER bits,
* so we just have to mask off all page table errors via EMR.
*/
if (HAS_FBC(i915))
return ~I915_ERROR_MEMORY_REFRESH;
else
return ~(I915_ERROR_PAGE_TABLE |
I915_ERROR_MEMORY_REFRESH);
}
static void i8xx_irq_postinstall(struct drm_i915_private *dev_priv)
{
struct intel_uncore *uncore = &dev_priv->uncore;
u16 enable_mask;
intel_uncore_write16(uncore, EMR, i9xx_error_mask(dev_priv));
/* Unmask the interrupts that we always want on. */
dev_priv->irq_mask =
~(I915_DISPLAY_PIPE_A_EVENT_INTERRUPT |
I915_DISPLAY_PIPE_B_EVENT_INTERRUPT |
I915_MASTER_ERROR_INTERRUPT);
enable_mask =
I915_DISPLAY_PIPE_A_EVENT_INTERRUPT |
I915_DISPLAY_PIPE_B_EVENT_INTERRUPT |
I915_MASTER_ERROR_INTERRUPT |
I915_USER_INTERRUPT;
gen2_irq_init(uncore, dev_priv->irq_mask, enable_mask);
/* Interrupt setup is already guaranteed to be single-threaded, this is
* just to make the assert_spin_locked check happy. */
spin_lock_irq(&dev_priv->irq_lock);
i915_enable_pipestat(dev_priv, PIPE_A, PIPE_CRC_DONE_INTERRUPT_STATUS);
i915_enable_pipestat(dev_priv, PIPE_B, PIPE_CRC_DONE_INTERRUPT_STATUS);
spin_unlock_irq(&dev_priv->irq_lock);
}
static void i8xx_error_irq_ack(struct drm_i915_private *i915,
u16 *eir, u16 *eir_stuck)
{
struct intel_uncore *uncore = &i915->uncore;
u16 emr;
*eir = intel_uncore_read16(uncore, EIR);
intel_uncore_write16(uncore, EIR, *eir);
*eir_stuck = intel_uncore_read16(uncore, EIR);
if (*eir_stuck == 0)
return;
/*
* Toggle all EMR bits to make sure we get an edge
* in the ISR master error bit if we don't clear
* all the EIR bits. Otherwise the edge triggered
* IIR on i965/g4x wouldn't notice that an interrupt
* is still pending. Also some EIR bits can't be
* cleared except by handling the underlying error
* (or by a GPU reset) so we mask any bit that
* remains set.
*/
emr = intel_uncore_read16(uncore, EMR);
intel_uncore_write16(uncore, EMR, 0xffff);
intel_uncore_write16(uncore, EMR, emr | *eir_stuck);
}
static void i8xx_error_irq_handler(struct drm_i915_private *dev_priv,
u16 eir, u16 eir_stuck)
{
drm_dbg(&dev_priv->drm, "Master Error: EIR 0x%04x\n", eir);
if (eir_stuck)
drm_dbg(&dev_priv->drm, "EIR stuck: 0x%04x, masked\n",
eir_stuck);
drm_dbg(&dev_priv->drm, "PGTBL_ER: 0x%08x\n",
intel_uncore_read(&dev_priv->uncore, PGTBL_ER));
}
static void i9xx_error_irq_ack(struct drm_i915_private *dev_priv,
u32 *eir, u32 *eir_stuck)
{
u32 emr;
*eir = intel_uncore_read(&dev_priv->uncore, EIR);
intel_uncore_write(&dev_priv->uncore, EIR, *eir);
*eir_stuck = intel_uncore_read(&dev_priv->uncore, EIR);
if (*eir_stuck == 0)
return;
/*
* Toggle all EMR bits to make sure we get an edge
* in the ISR master error bit if we don't clear
* all the EIR bits. Otherwise the edge triggered
* IIR on i965/g4x wouldn't notice that an interrupt
* is still pending. Also some EIR bits can't be
* cleared except by handling the underlying error
* (or by a GPU reset) so we mask any bit that
* remains set.
*/
emr = intel_uncore_read(&dev_priv->uncore, EMR);
intel_uncore_write(&dev_priv->uncore, EMR, 0xffffffff);
intel_uncore_write(&dev_priv->uncore, EMR, emr | *eir_stuck);
}
static void i9xx_error_irq_handler(struct drm_i915_private *dev_priv,
u32 eir, u32 eir_stuck)
{
drm_dbg(&dev_priv->drm, "Master Error, EIR 0x%08x\n", eir);
if (eir_stuck)
drm_dbg(&dev_priv->drm, "EIR stuck: 0x%08x, masked\n",
eir_stuck);
drm_dbg(&dev_priv->drm, "PGTBL_ER: 0x%08x\n",
intel_uncore_read(&dev_priv->uncore, PGTBL_ER));
}
static irqreturn_t i8xx_irq_handler(int irq, void *arg)
{
struct drm_i915_private *dev_priv = arg;
irqreturn_t ret = IRQ_NONE;
if (!intel_irqs_enabled(dev_priv))
return IRQ_NONE;
/* IRQs are synced during runtime_suspend, we don't require a wakeref */
disable_rpm_wakeref_asserts(&dev_priv->runtime_pm);
do {
u32 pipe_stats[I915_MAX_PIPES] = {};
u16 eir = 0, eir_stuck = 0;
u16 iir;
iir = intel_uncore_read16(&dev_priv->uncore, GEN2_IIR);
if (iir == 0)
break;
ret = IRQ_HANDLED;
/* Call regardless, as some status bits might not be
* signalled in iir */
i9xx_pipestat_irq_ack(dev_priv, iir, pipe_stats);
if (iir & I915_MASTER_ERROR_INTERRUPT)
i8xx_error_irq_ack(dev_priv, &eir, &eir_stuck);
intel_uncore_write16(&dev_priv->uncore, GEN2_IIR, iir);
if (iir & I915_USER_INTERRUPT)
intel_engine_cs_irq(to_gt(dev_priv)->engine[RCS0], iir);
if (iir & I915_MASTER_ERROR_INTERRUPT)
i8xx_error_irq_handler(dev_priv, eir, eir_stuck);
i8xx_pipestat_irq_handler(dev_priv, iir, pipe_stats);
} while (0);
pmu_irq_stats(dev_priv, ret);
enable_rpm_wakeref_asserts(&dev_priv->runtime_pm);
return ret;
}
static void i915_irq_reset(struct drm_i915_private *dev_priv)
{
struct intel_uncore *uncore = &dev_priv->uncore;
if (I915_HAS_HOTPLUG(dev_priv)) {
i915_hotplug_interrupt_update(dev_priv, 0xffffffff, 0);
intel_uncore_rmw(&dev_priv->uncore, PORT_HOTPLUG_STAT, 0, 0);
}
i9xx_pipestat_irq_reset(dev_priv);
GEN3_IRQ_RESET(uncore, GEN2_);
dev_priv->irq_mask = ~0u;
}
static void i915_irq_postinstall(struct drm_i915_private *dev_priv)
{
struct intel_uncore *uncore = &dev_priv->uncore;
u32 enable_mask;
intel_uncore_write(uncore, EMR, i9xx_error_mask(dev_priv));
/* Unmask the interrupts that we always want on. */
dev_priv->irq_mask =
~(I915_ASLE_INTERRUPT |
I915_DISPLAY_PIPE_A_EVENT_INTERRUPT |
I915_DISPLAY_PIPE_B_EVENT_INTERRUPT |
I915_MASTER_ERROR_INTERRUPT);
enable_mask =
I915_ASLE_INTERRUPT |
I915_DISPLAY_PIPE_A_EVENT_INTERRUPT |
I915_DISPLAY_PIPE_B_EVENT_INTERRUPT |
I915_MASTER_ERROR_INTERRUPT |
I915_USER_INTERRUPT;
if (I915_HAS_HOTPLUG(dev_priv)) {
/* Enable in IER... */
enable_mask |= I915_DISPLAY_PORT_INTERRUPT;
/* and unmask in IMR */
dev_priv->irq_mask &= ~I915_DISPLAY_PORT_INTERRUPT;
}
GEN3_IRQ_INIT(uncore, GEN2_, dev_priv->irq_mask, enable_mask);
/* Interrupt setup is already guaranteed to be single-threaded, this is
* just to make the assert_spin_locked check happy. */
spin_lock_irq(&dev_priv->irq_lock);
i915_enable_pipestat(dev_priv, PIPE_A, PIPE_CRC_DONE_INTERRUPT_STATUS);
i915_enable_pipestat(dev_priv, PIPE_B, PIPE_CRC_DONE_INTERRUPT_STATUS);
spin_unlock_irq(&dev_priv->irq_lock);
i915_enable_asle_pipestat(dev_priv);
}
static irqreturn_t i915_irq_handler(int irq, void *arg)
{
struct drm_i915_private *dev_priv = arg;
irqreturn_t ret = IRQ_NONE;
if (!intel_irqs_enabled(dev_priv))
return IRQ_NONE;
/* IRQs are synced during runtime_suspend, we don't require a wakeref */
disable_rpm_wakeref_asserts(&dev_priv->runtime_pm);
do {
u32 pipe_stats[I915_MAX_PIPES] = {};
u32 eir = 0, eir_stuck = 0;
u32 hotplug_status = 0;
u32 iir;
iir = intel_uncore_read(&dev_priv->uncore, GEN2_IIR);
if (iir == 0)
break;
ret = IRQ_HANDLED;
if (I915_HAS_HOTPLUG(dev_priv) &&
iir & I915_DISPLAY_PORT_INTERRUPT)
hotplug_status = i9xx_hpd_irq_ack(dev_priv);
/* Call regardless, as some status bits might not be
* signalled in iir */
i9xx_pipestat_irq_ack(dev_priv, iir, pipe_stats);
if (iir & I915_MASTER_ERROR_INTERRUPT)
i9xx_error_irq_ack(dev_priv, &eir, &eir_stuck);
intel_uncore_write(&dev_priv->uncore, GEN2_IIR, iir);
if (iir & I915_USER_INTERRUPT)
intel_engine_cs_irq(to_gt(dev_priv)->engine[RCS0], iir);
if (iir & I915_MASTER_ERROR_INTERRUPT)
i9xx_error_irq_handler(dev_priv, eir, eir_stuck);
if (hotplug_status)
i9xx_hpd_irq_handler(dev_priv, hotplug_status);
i915_pipestat_irq_handler(dev_priv, iir, pipe_stats);
} while (0);
pmu_irq_stats(dev_priv, ret);
enable_rpm_wakeref_asserts(&dev_priv->runtime_pm);
return ret;
}
static void i965_irq_reset(struct drm_i915_private *dev_priv)
{
struct intel_uncore *uncore = &dev_priv->uncore;
i915_hotplug_interrupt_update(dev_priv, 0xffffffff, 0);
intel_uncore_rmw(uncore, PORT_HOTPLUG_STAT, 0, 0);
i9xx_pipestat_irq_reset(dev_priv);
GEN3_IRQ_RESET(uncore, GEN2_);
dev_priv->irq_mask = ~0u;
}
static u32 i965_error_mask(struct drm_i915_private *i915)
{
/*
* Enable some error detection, note the instruction error mask
* bit is reserved, so we leave it masked.
*
* i965 FBC no longer generates spurious GTT errors,
* so we can always enable the page table errors.
*/
if (IS_G4X(i915))
return ~(GM45_ERROR_PAGE_TABLE |
GM45_ERROR_MEM_PRIV |
GM45_ERROR_CP_PRIV |
I915_ERROR_MEMORY_REFRESH);
else
return ~(I915_ERROR_PAGE_TABLE |
I915_ERROR_MEMORY_REFRESH);
}
static void i965_irq_postinstall(struct drm_i915_private *dev_priv)
{
struct intel_uncore *uncore = &dev_priv->uncore;
u32 enable_mask;
intel_uncore_write(uncore, EMR, i965_error_mask(dev_priv));
/* Unmask the interrupts that we always want on. */
dev_priv->irq_mask =
~(I915_ASLE_INTERRUPT |
I915_DISPLAY_PORT_INTERRUPT |
I915_DISPLAY_PIPE_A_EVENT_INTERRUPT |
I915_DISPLAY_PIPE_B_EVENT_INTERRUPT |
I915_MASTER_ERROR_INTERRUPT);
enable_mask =
I915_ASLE_INTERRUPT |
I915_DISPLAY_PORT_INTERRUPT |
I915_DISPLAY_PIPE_A_EVENT_INTERRUPT |
I915_DISPLAY_PIPE_B_EVENT_INTERRUPT |
I915_MASTER_ERROR_INTERRUPT |
I915_USER_INTERRUPT;
if (IS_G4X(dev_priv))
enable_mask |= I915_BSD_USER_INTERRUPT;
GEN3_IRQ_INIT(uncore, GEN2_, dev_priv->irq_mask, enable_mask);
/* Interrupt setup is already guaranteed to be single-threaded, this is
* just to make the assert_spin_locked check happy. */
spin_lock_irq(&dev_priv->irq_lock);
i915_enable_pipestat(dev_priv, PIPE_A, PIPE_GMBUS_INTERRUPT_STATUS);
i915_enable_pipestat(dev_priv, PIPE_A, PIPE_CRC_DONE_INTERRUPT_STATUS);
i915_enable_pipestat(dev_priv, PIPE_B, PIPE_CRC_DONE_INTERRUPT_STATUS);
spin_unlock_irq(&dev_priv->irq_lock);
i915_enable_asle_pipestat(dev_priv);
}
static irqreturn_t i965_irq_handler(int irq, void *arg)
{
struct drm_i915_private *dev_priv = arg;
irqreturn_t ret = IRQ_NONE;
if (!intel_irqs_enabled(dev_priv))
return IRQ_NONE;
/* IRQs are synced during runtime_suspend, we don't require a wakeref */
disable_rpm_wakeref_asserts(&dev_priv->runtime_pm);
do {
u32 pipe_stats[I915_MAX_PIPES] = {};
u32 eir = 0, eir_stuck = 0;
u32 hotplug_status = 0;
u32 iir;
iir = intel_uncore_read(&dev_priv->uncore, GEN2_IIR);
if (iir == 0)
break;
ret = IRQ_HANDLED;
if (iir & I915_DISPLAY_PORT_INTERRUPT)
hotplug_status = i9xx_hpd_irq_ack(dev_priv);
/* Call regardless, as some status bits might not be
* signalled in iir */
i9xx_pipestat_irq_ack(dev_priv, iir, pipe_stats);
if (iir & I915_MASTER_ERROR_INTERRUPT)
i9xx_error_irq_ack(dev_priv, &eir, &eir_stuck);
intel_uncore_write(&dev_priv->uncore, GEN2_IIR, iir);
if (iir & I915_USER_INTERRUPT)
intel_engine_cs_irq(to_gt(dev_priv)->engine[RCS0],
iir);
if (iir & I915_BSD_USER_INTERRUPT)
intel_engine_cs_irq(to_gt(dev_priv)->engine[VCS0],
iir >> 25);
if (iir & I915_MASTER_ERROR_INTERRUPT)
i9xx_error_irq_handler(dev_priv, eir, eir_stuck);
if (hotplug_status)
i9xx_hpd_irq_handler(dev_priv, hotplug_status);
i965_pipestat_irq_handler(dev_priv, iir, pipe_stats);
} while (0);
pmu_irq_stats(dev_priv, IRQ_HANDLED);
enable_rpm_wakeref_asserts(&dev_priv->runtime_pm);
return ret;
}
/**
* intel_irq_init - initializes irq support
* @dev_priv: i915 device instance
*
* This function initializes all the irq support including work items, timers
* and all the vtables. It does not setup the interrupt itself though.
*/
void intel_irq_init(struct drm_i915_private *dev_priv)
{
int i;
INIT_WORK(&dev_priv->l3_parity.error_work, ivb_parity_work);
for (i = 0; i < MAX_L3_SLICES; ++i)
dev_priv->l3_parity.remap_info[i] = NULL;
/* pre-gen11 the guc irqs bits are in the upper 16 bits of the pm reg */
if (HAS_GT_UC(dev_priv) && GRAPHICS_VER(dev_priv) < 11)
to_gt(dev_priv)->pm_guc_events = GUC_INTR_GUC2HOST << 16;
}
/**
* intel_irq_fini - deinitializes IRQ support
* @i915: i915 device instance
*
* This function deinitializes all the IRQ support.
*/
void intel_irq_fini(struct drm_i915_private *i915)
{
int i;
for (i = 0; i < MAX_L3_SLICES; ++i)
kfree(i915->l3_parity.remap_info[i]);
}
static irq_handler_t intel_irq_handler(struct drm_i915_private *dev_priv)
{
if (HAS_GMCH(dev_priv)) {
if (IS_CHERRYVIEW(dev_priv))
return cherryview_irq_handler;
else if (IS_VALLEYVIEW(dev_priv))
return valleyview_irq_handler;
else if (GRAPHICS_VER(dev_priv) == 4)
return i965_irq_handler;
else if (GRAPHICS_VER(dev_priv) == 3)
return i915_irq_handler;
else
return i8xx_irq_handler;
} else {
if (GRAPHICS_VER_FULL(dev_priv) >= IP_VER(12, 10))
return dg1_irq_handler;
else if (GRAPHICS_VER(dev_priv) >= 11)
return gen11_irq_handler;
else if (GRAPHICS_VER(dev_priv) >= 8)
return gen8_irq_handler;
else
return ilk_irq_handler;
}
}
static void intel_irq_reset(struct drm_i915_private *dev_priv)
{
if (HAS_GMCH(dev_priv)) {
if (IS_CHERRYVIEW(dev_priv))
cherryview_irq_reset(dev_priv);
else if (IS_VALLEYVIEW(dev_priv))
valleyview_irq_reset(dev_priv);
else if (GRAPHICS_VER(dev_priv) == 4)
i965_irq_reset(dev_priv);
else if (GRAPHICS_VER(dev_priv) == 3)
i915_irq_reset(dev_priv);
else
i8xx_irq_reset(dev_priv);
} else {
if (GRAPHICS_VER_FULL(dev_priv) >= IP_VER(12, 10))
dg1_irq_reset(dev_priv);
else if (GRAPHICS_VER(dev_priv) >= 11)
gen11_irq_reset(dev_priv);
else if (GRAPHICS_VER(dev_priv) >= 8)
gen8_irq_reset(dev_priv);
else
ilk_irq_reset(dev_priv);
}
}
static void intel_irq_postinstall(struct drm_i915_private *dev_priv)
{
if (HAS_GMCH(dev_priv)) {
if (IS_CHERRYVIEW(dev_priv))
cherryview_irq_postinstall(dev_priv);
else if (IS_VALLEYVIEW(dev_priv))
valleyview_irq_postinstall(dev_priv);
else if (GRAPHICS_VER(dev_priv) == 4)
i965_irq_postinstall(dev_priv);
else if (GRAPHICS_VER(dev_priv) == 3)
i915_irq_postinstall(dev_priv);
else
i8xx_irq_postinstall(dev_priv);
} else {
if (GRAPHICS_VER_FULL(dev_priv) >= IP_VER(12, 10))
dg1_irq_postinstall(dev_priv);
else if (GRAPHICS_VER(dev_priv) >= 11)
gen11_irq_postinstall(dev_priv);
else if (GRAPHICS_VER(dev_priv) >= 8)
gen8_irq_postinstall(dev_priv);
else
ilk_irq_postinstall(dev_priv);
}
}
/**
* intel_irq_install - enables the hardware interrupt
* @dev_priv: i915 device instance
*
* This function enables the hardware interrupt handling, but leaves the hotplug
* handling still disabled. It is called after intel_irq_init().
*
* In the driver load and resume code we need working interrupts in a few places
* but don't want to deal with the hassle of concurrent probe and hotplug
* workers. Hence the split into this two-stage approach.
*/
int intel_irq_install(struct drm_i915_private *dev_priv)
{
int irq = to_pci_dev(dev_priv->drm.dev)->irq;
int ret;
/*
* We enable some interrupt sources in our postinstall hooks, so mark
* interrupts as enabled _before_ actually enabling them to avoid
* special cases in our ordering checks.
*/
dev_priv->runtime_pm.irqs_enabled = true;
dev_priv->irq_enabled = true;
intel_irq_reset(dev_priv);
ret = request_irq(irq, intel_irq_handler(dev_priv),
IRQF_SHARED, DRIVER_NAME, dev_priv);
if (ret < 0) {
dev_priv->irq_enabled = false;
return ret;
}
intel_irq_postinstall(dev_priv);
return ret;
}
/**
* intel_irq_uninstall - finilizes all irq handling
* @dev_priv: i915 device instance
*
* This stops interrupt and hotplug handling and unregisters and frees all
* resources acquired in the init functions.
*/
void intel_irq_uninstall(struct drm_i915_private *dev_priv)
{
int irq = to_pci_dev(dev_priv->drm.dev)->irq;
/*
* FIXME we can get called twice during driver probe
* error handling as well as during driver remove due to
* intel_display_driver_remove() calling us out of sequence.
* Would be nice if it didn't do that...
*/
if (!dev_priv->irq_enabled)
return;
dev_priv->irq_enabled = false;
intel_irq_reset(dev_priv);
free_irq(irq, dev_priv);
intel_hpd_cancel_work(dev_priv);
dev_priv->runtime_pm.irqs_enabled = false;
}
/**
* intel_runtime_pm_disable_interrupts - runtime interrupt disabling
* @dev_priv: i915 device instance
*
* This function is used to disable interrupts at runtime, both in the runtime
* pm and the system suspend/resume code.
*/
void intel_runtime_pm_disable_interrupts(struct drm_i915_private *dev_priv)
{
intel_irq_reset(dev_priv);
dev_priv->runtime_pm.irqs_enabled = false;
intel_synchronize_irq(dev_priv);
}
/**
* intel_runtime_pm_enable_interrupts - runtime interrupt enabling
* @dev_priv: i915 device instance
*
* This function is used to enable interrupts at runtime, both in the runtime
* pm and the system suspend/resume code.
*/
void intel_runtime_pm_enable_interrupts(struct drm_i915_private *dev_priv)
{
dev_priv->runtime_pm.irqs_enabled = true;
intel_irq_reset(dev_priv);
intel_irq_postinstall(dev_priv);
}
bool intel_irqs_enabled(struct drm_i915_private *dev_priv)
{
return dev_priv->runtime_pm.irqs_enabled;
}
void intel_synchronize_irq(struct drm_i915_private *i915)
{
synchronize_irq(to_pci_dev(i915->drm.dev)->irq);
}
void intel_synchronize_hardirq(struct drm_i915_private *i915)
{
synchronize_hardirq(to_pci_dev(i915->drm.dev)->irq);
}
| linux-master | drivers/gpu/drm/i915/i915_irq.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2019 Intel Corporation
*/
#include <linux/prandom.h>
#include <uapi/drm/i915_drm.h>
#include "intel_memory_region.h"
#include "i915_drv.h"
#include "i915_ttm_buddy_manager.h"
static const struct {
u16 class;
u16 instance;
} intel_region_map[] = {
[INTEL_REGION_SMEM] = {
.class = INTEL_MEMORY_SYSTEM,
.instance = 0,
},
[INTEL_REGION_LMEM_0] = {
.class = INTEL_MEMORY_LOCAL,
.instance = 0,
},
[INTEL_REGION_STOLEN_SMEM] = {
.class = INTEL_MEMORY_STOLEN_SYSTEM,
.instance = 0,
},
[INTEL_REGION_STOLEN_LMEM] = {
.class = INTEL_MEMORY_STOLEN_LOCAL,
.instance = 0,
},
};
static int __iopagetest(struct intel_memory_region *mem,
u8 __iomem *va, int pagesize,
u8 value, resource_size_t offset,
const void *caller)
{
int byte = get_random_u32_below(pagesize);
u8 result[3];
memset_io(va, value, pagesize); /* or GPF! */
wmb();
result[0] = ioread8(va);
result[1] = ioread8(va + byte);
result[2] = ioread8(va + pagesize - 1);
if (memchr_inv(result, value, sizeof(result))) {
dev_err(mem->i915->drm.dev,
"Failed to read back from memory region:%pR at [%pa + %pa] for %ps; wrote %x, read (%x, %x, %x)\n",
&mem->region, &mem->io_start, &offset, caller,
value, result[0], result[1], result[2]);
return -EINVAL;
}
return 0;
}
static int iopagetest(struct intel_memory_region *mem,
resource_size_t offset,
const void *caller)
{
const u8 val[] = { 0x0, 0xa5, 0xc3, 0xf0 };
void __iomem *va;
int err;
int i;
va = ioremap_wc(mem->io_start + offset, PAGE_SIZE);
if (!va) {
dev_err(mem->i915->drm.dev,
"Failed to ioremap memory region [%pa + %pa] for %ps\n",
&mem->io_start, &offset, caller);
return -EFAULT;
}
for (i = 0; i < ARRAY_SIZE(val); i++) {
err = __iopagetest(mem, va, PAGE_SIZE, val[i], offset, caller);
if (err)
break;
err = __iopagetest(mem, va, PAGE_SIZE, ~val[i], offset, caller);
if (err)
break;
}
iounmap(va);
return err;
}
static resource_size_t random_page(resource_size_t last)
{
/* Limited to low 44b (16TiB), but should suffice for a spot check */
return get_random_u32_below(last >> PAGE_SHIFT) << PAGE_SHIFT;
}
static int iomemtest(struct intel_memory_region *mem,
bool test_all,
const void *caller)
{
resource_size_t last, page;
int err;
if (mem->io_size < PAGE_SIZE)
return 0;
last = mem->io_size - PAGE_SIZE;
/*
* Quick test to check read/write access to the iomap (backing store).
*
* Write a byte, read it back. If the iomapping fails, we expect
* a GPF preventing further execution. If the backing store does not
* exist, the read back will return garbage. We check a couple of pages,
* the first and last of the specified region to confirm the backing
* store + iomap does cover the entire memory region; and we check
* a random offset within as a quick spot check for bad memory.
*/
if (test_all) {
for (page = 0; page <= last; page += PAGE_SIZE) {
err = iopagetest(mem, page, caller);
if (err)
return err;
}
} else {
err = iopagetest(mem, 0, caller);
if (err)
return err;
err = iopagetest(mem, last, caller);
if (err)
return err;
err = iopagetest(mem, random_page(last), caller);
if (err)
return err;
}
return 0;
}
struct intel_memory_region *
intel_memory_region_lookup(struct drm_i915_private *i915,
u16 class, u16 instance)
{
struct intel_memory_region *mr;
int id;
/* XXX: consider maybe converting to an rb tree at some point */
for_each_memory_region(mr, i915, id) {
if (mr->type == class && mr->instance == instance)
return mr;
}
return NULL;
}
struct intel_memory_region *
intel_memory_region_by_type(struct drm_i915_private *i915,
enum intel_memory_type mem_type)
{
struct intel_memory_region *mr;
int id;
for_each_memory_region(mr, i915, id)
if (mr->type == mem_type)
return mr;
return NULL;
}
/**
* intel_memory_region_reserve - Reserve a memory range
* @mem: The region for which we want to reserve a range.
* @offset: Start of the range to reserve.
* @size: The size of the range to reserve.
*
* Return: 0 on success, negative error code on failure.
*/
int intel_memory_region_reserve(struct intel_memory_region *mem,
resource_size_t offset,
resource_size_t size)
{
struct ttm_resource_manager *man = mem->region_private;
GEM_BUG_ON(mem->is_range_manager);
return i915_ttm_buddy_man_reserve(man, offset, size);
}
void intel_memory_region_debug(struct intel_memory_region *mr,
struct drm_printer *printer)
{
drm_printf(printer, "%s: ", mr->name);
if (mr->region_private)
ttm_resource_manager_debug(mr->region_private, printer);
else
drm_printf(printer, "total:%pa bytes\n", &mr->total);
}
static int intel_memory_region_memtest(struct intel_memory_region *mem,
void *caller)
{
struct drm_i915_private *i915 = mem->i915;
int err = 0;
if (!mem->io_start)
return 0;
if (IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM) || i915->params.memtest)
err = iomemtest(mem, i915->params.memtest, caller);
return err;
}
struct intel_memory_region *
intel_memory_region_create(struct drm_i915_private *i915,
resource_size_t start,
resource_size_t size,
resource_size_t min_page_size,
resource_size_t io_start,
resource_size_t io_size,
u16 type,
u16 instance,
const struct intel_memory_region_ops *ops)
{
struct intel_memory_region *mem;
int err;
mem = kzalloc(sizeof(*mem), GFP_KERNEL);
if (!mem)
return ERR_PTR(-ENOMEM);
mem->i915 = i915;
mem->region = DEFINE_RES_MEM(start, size);
mem->io_start = io_start;
mem->io_size = io_size;
mem->min_page_size = min_page_size;
mem->ops = ops;
mem->total = size;
mem->type = type;
mem->instance = instance;
mutex_init(&mem->objects.lock);
INIT_LIST_HEAD(&mem->objects.list);
if (ops->init) {
err = ops->init(mem);
if (err)
goto err_free;
}
err = intel_memory_region_memtest(mem, (void *)_RET_IP_);
if (err)
goto err_release;
return mem;
err_release:
if (mem->ops->release)
mem->ops->release(mem);
err_free:
kfree(mem);
return ERR_PTR(err);
}
void intel_memory_region_set_name(struct intel_memory_region *mem,
const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vsnprintf(mem->name, sizeof(mem->name), fmt, ap);
va_end(ap);
}
void intel_memory_region_avail(struct intel_memory_region *mr,
u64 *avail, u64 *visible_avail)
{
if (mr->type == INTEL_MEMORY_LOCAL) {
i915_ttm_buddy_man_avail(mr->region_private,
avail, visible_avail);
*avail <<= PAGE_SHIFT;
*visible_avail <<= PAGE_SHIFT;
} else {
*avail = mr->total;
*visible_avail = mr->total;
}
}
void intel_memory_region_destroy(struct intel_memory_region *mem)
{
int ret = 0;
if (mem->ops->release)
ret = mem->ops->release(mem);
GEM_WARN_ON(!list_empty_careful(&mem->objects.list));
mutex_destroy(&mem->objects.lock);
if (!ret)
kfree(mem);
}
/* Global memory region registration -- only slight layer inversions! */
int intel_memory_regions_hw_probe(struct drm_i915_private *i915)
{
int err, i;
for (i = 0; i < ARRAY_SIZE(i915->mm.regions); i++) {
struct intel_memory_region *mem = ERR_PTR(-ENODEV);
u16 type, instance;
if (!HAS_REGION(i915, BIT(i)))
continue;
type = intel_region_map[i].class;
instance = intel_region_map[i].instance;
switch (type) {
case INTEL_MEMORY_SYSTEM:
if (IS_DGFX(i915))
mem = i915_gem_ttm_system_setup(i915, type,
instance);
else
mem = i915_gem_shmem_setup(i915, type,
instance);
break;
case INTEL_MEMORY_STOLEN_LOCAL:
mem = i915_gem_stolen_lmem_setup(i915, type, instance);
if (!IS_ERR(mem))
i915->mm.stolen_region = mem;
break;
case INTEL_MEMORY_STOLEN_SYSTEM:
mem = i915_gem_stolen_smem_setup(i915, type, instance);
if (!IS_ERR(mem))
i915->mm.stolen_region = mem;
break;
default:
continue;
}
if (IS_ERR(mem)) {
err = PTR_ERR(mem);
drm_err(&i915->drm,
"Failed to setup region(%d) type=%d\n",
err, type);
goto out_cleanup;
}
mem->id = i;
i915->mm.regions[i] = mem;
}
return 0;
out_cleanup:
intel_memory_regions_driver_release(i915);
return err;
}
void intel_memory_regions_driver_release(struct drm_i915_private *i915)
{
int i;
for (i = 0; i < ARRAY_SIZE(i915->mm.regions); i++) {
struct intel_memory_region *region =
fetch_and_zero(&i915->mm.regions[i]);
if (region)
intel_memory_region_destroy(region);
}
}
#if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
#include "selftests/intel_memory_region.c"
#include "selftests/mock_region.c"
#endif
| linux-master | drivers/gpu/drm/i915/intel_memory_region.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2021 Intel Corporation
*/
#include <linux/dma-fence.h>
#include <linux/slab.h>
#include <drm/ttm/ttm_bo.h>
#include "i915_deps.h"
/**
* DOC: Set of utilities to dynamically collect dependencies into a
* structure which is fed into the GT migration code.
*
* Once we can do async unbinding, this is also needed to coalesce
* the migration fence with the unbind fences if these are coalesced
* post-migration.
*
* While collecting the individual dependencies, we store the refcounted
* struct dma_fence pointers in a realloc-managed pointer array, since
* that can be easily fed into a dma_fence_array. Other options are
* available, like for example an xarray for similarity with drm/sched.
* Can be changed easily if needed.
*
* A struct i915_deps need to be initialized using i915_deps_init().
* If i915_deps_add_dependency() or i915_deps_add_resv() return an
* error code they will internally call i915_deps_fini(), which frees
* all internal references and allocations.
*/
/* Min number of fence pointers in the array when an allocation occurs. */
#define I915_DEPS_MIN_ALLOC_CHUNK 8U
static void i915_deps_reset_fences(struct i915_deps *deps)
{
if (deps->fences != &deps->single)
kfree(deps->fences);
deps->num_deps = 0;
deps->fences_size = 1;
deps->fences = &deps->single;
}
/**
* i915_deps_init - Initialize an i915_deps structure
* @deps: Pointer to the i915_deps structure to initialize.
* @gfp: The allocation mode for subsequenst allocations.
*/
void i915_deps_init(struct i915_deps *deps, gfp_t gfp)
{
deps->fences = NULL;
deps->gfp = gfp;
i915_deps_reset_fences(deps);
}
/**
* i915_deps_fini - Finalize an i915_deps structure
* @deps: Pointer to the i915_deps structure to finalize.
*
* This function drops all fence references taken, conditionally frees and
* then resets the fences array.
*/
void i915_deps_fini(struct i915_deps *deps)
{
unsigned int i;
for (i = 0; i < deps->num_deps; ++i)
dma_fence_put(deps->fences[i]);
if (deps->fences != &deps->single)
kfree(deps->fences);
}
static int i915_deps_grow(struct i915_deps *deps, struct dma_fence *fence,
const struct ttm_operation_ctx *ctx)
{
int ret;
if (deps->num_deps >= deps->fences_size) {
unsigned int new_size = 2 * deps->fences_size;
struct dma_fence **new_fences;
new_size = max(new_size, I915_DEPS_MIN_ALLOC_CHUNK);
new_fences = kmalloc_array(new_size, sizeof(*new_fences), deps->gfp);
if (!new_fences)
goto sync;
memcpy(new_fences, deps->fences,
deps->fences_size * sizeof(*new_fences));
swap(new_fences, deps->fences);
if (new_fences != &deps->single)
kfree(new_fences);
deps->fences_size = new_size;
}
deps->fences[deps->num_deps++] = dma_fence_get(fence);
return 0;
sync:
if (ctx->no_wait_gpu && !dma_fence_is_signaled(fence)) {
ret = -EBUSY;
goto unref;
}
ret = dma_fence_wait(fence, ctx->interruptible);
if (ret)
goto unref;
ret = fence->error;
if (ret)
goto unref;
return 0;
unref:
i915_deps_fini(deps);
return ret;
}
/**
* i915_deps_sync - Wait for all the fences in the dependency collection
* @deps: Pointer to the i915_deps structure the fences of which to wait for.
* @ctx: Pointer to a struct ttm_operation_ctx indicating how the waits
* should be performed.
*
* This function waits for fences in the dependency collection. If it
* encounters an error during the wait or a fence error, the wait for
* further fences is aborted and the error returned.
*
* Return: Zero if successful, Negative error code on error.
*/
int i915_deps_sync(const struct i915_deps *deps, const struct ttm_operation_ctx *ctx)
{
struct dma_fence **fences = deps->fences;
unsigned int i;
int ret = 0;
for (i = 0; i < deps->num_deps; ++i, ++fences) {
if (ctx->no_wait_gpu && !dma_fence_is_signaled(*fences)) {
ret = -EBUSY;
break;
}
ret = dma_fence_wait(*fences, ctx->interruptible);
if (!ret)
ret = (*fences)->error;
if (ret)
break;
}
return ret;
}
/**
* i915_deps_add_dependency - Add a fence to the dependency collection
* @deps: Pointer to the i915_deps structure a fence is to be added to.
* @fence: The fence to add.
* @ctx: Pointer to a struct ttm_operation_ctx indicating how waits are to
* be performed if waiting.
*
* Adds a fence to the dependency collection, and takes a reference on it.
* If the fence context is not zero and there was a later fence from the
* same fence context already added, then the fence is not added to the
* dependency collection. If the fence context is not zero and there was
* an earlier fence already added, then the fence will replace the older
* fence from the same context and the reference on the earlier fence will
* be dropped.
* If there is a failure to allocate memory to accommodate the new fence to
* be added, the new fence will instead be waited for and an error may
* be returned; depending on the value of @ctx, or if there was a fence
* error. If an error was returned, the dependency collection will be
* finalized and all fence reference dropped.
*
* Return: 0 if success. Negative error code on error.
*/
int i915_deps_add_dependency(struct i915_deps *deps,
struct dma_fence *fence,
const struct ttm_operation_ctx *ctx)
{
unsigned int i;
int ret;
if (!fence)
return 0;
if (dma_fence_is_signaled(fence)) {
ret = fence->error;
if (ret)
i915_deps_fini(deps);
return ret;
}
for (i = 0; i < deps->num_deps; ++i) {
struct dma_fence *entry = deps->fences[i];
if (!entry->context || entry->context != fence->context)
continue;
if (dma_fence_is_later(fence, entry)) {
dma_fence_put(entry);
deps->fences[i] = dma_fence_get(fence);
}
return 0;
}
return i915_deps_grow(deps, fence, ctx);
}
/**
* i915_deps_add_resv - Add the fences of a reservation object to a dependency
* collection.
* @deps: Pointer to the i915_deps structure a fence is to be added to.
* @resv: The reservation object, then fences of which to add.
* @ctx: Pointer to a struct ttm_operation_ctx indicating how waits are to
* be performed if waiting.
*
* Calls i915_deps_add_depencency() on the indicated fences of @resv.
*
* Return: Zero on success. Negative error code on error.
*/
int i915_deps_add_resv(struct i915_deps *deps, struct dma_resv *resv,
const struct ttm_operation_ctx *ctx)
{
struct dma_resv_iter iter;
struct dma_fence *fence;
dma_resv_assert_held(resv);
dma_resv_for_each_fence(&iter, resv, dma_resv_usage_rw(true), fence) {
int ret = i915_deps_add_dependency(deps, fence, ctx);
if (ret)
return ret;
}
return 0;
}
| linux-master | drivers/gpu/drm/i915/i915_deps.c |
/*
* Copyright © 2012 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* Authors:
* Ben Widawsky <[email protected]>
*
*/
#include <linux/device.h>
#include <linux/module.h>
#include <linux/stat.h>
#include <linux/sysfs.h>
#include "gt/intel_gt_regs.h"
#include "gt/intel_rc6.h"
#include "gt/intel_rps.h"
#include "gt/sysfs_engines.h"
#include "i915_drv.h"
#include "i915_sysfs.h"
struct drm_i915_private *kdev_minor_to_i915(struct device *kdev)
{
struct drm_minor *minor = dev_get_drvdata(kdev);
return to_i915(minor->dev);
}
static int l3_access_valid(struct drm_i915_private *i915, loff_t offset)
{
if (!HAS_L3_DPF(i915))
return -EPERM;
if (!IS_ALIGNED(offset, sizeof(u32)))
return -EINVAL;
if (offset >= GEN7_L3LOG_SIZE)
return -ENXIO;
return 0;
}
static ssize_t
i915_l3_read(struct file *filp, struct kobject *kobj,
struct bin_attribute *attr, char *buf,
loff_t offset, size_t count)
{
struct device *kdev = kobj_to_dev(kobj);
struct drm_i915_private *i915 = kdev_minor_to_i915(kdev);
int slice = (int)(uintptr_t)attr->private;
int ret;
ret = l3_access_valid(i915, offset);
if (ret)
return ret;
count = round_down(count, sizeof(u32));
count = min_t(size_t, GEN7_L3LOG_SIZE - offset, count);
memset(buf, 0, count);
spin_lock(&i915->gem.contexts.lock);
if (i915->l3_parity.remap_info[slice])
memcpy(buf,
i915->l3_parity.remap_info[slice] + offset / sizeof(u32),
count);
spin_unlock(&i915->gem.contexts.lock);
return count;
}
static ssize_t
i915_l3_write(struct file *filp, struct kobject *kobj,
struct bin_attribute *attr, char *buf,
loff_t offset, size_t count)
{
struct device *kdev = kobj_to_dev(kobj);
struct drm_i915_private *i915 = kdev_minor_to_i915(kdev);
int slice = (int)(uintptr_t)attr->private;
u32 *remap_info, *freeme = NULL;
struct i915_gem_context *ctx;
int ret;
ret = l3_access_valid(i915, offset);
if (ret)
return ret;
if (count < sizeof(u32))
return -EINVAL;
remap_info = kzalloc(GEN7_L3LOG_SIZE, GFP_KERNEL);
if (!remap_info)
return -ENOMEM;
spin_lock(&i915->gem.contexts.lock);
if (i915->l3_parity.remap_info[slice]) {
freeme = remap_info;
remap_info = i915->l3_parity.remap_info[slice];
} else {
i915->l3_parity.remap_info[slice] = remap_info;
}
count = round_down(count, sizeof(u32));
memcpy(remap_info + offset / sizeof(u32), buf, count);
/* NB: We defer the remapping until we switch to the context */
list_for_each_entry(ctx, &i915->gem.contexts.list, link)
ctx->remap_slice |= BIT(slice);
spin_unlock(&i915->gem.contexts.lock);
kfree(freeme);
/*
* TODO: Ideally we really want a GPU reset here to make sure errors
* aren't propagated. Since I cannot find a stable way to reset the GPU
* at this point it is left as a TODO.
*/
return count;
}
static const struct bin_attribute dpf_attrs = {
.attr = {.name = "l3_parity", .mode = (S_IRUSR | S_IWUSR)},
.size = GEN7_L3LOG_SIZE,
.read = i915_l3_read,
.write = i915_l3_write,
.mmap = NULL,
.private = (void *)0
};
static const struct bin_attribute dpf_attrs_1 = {
.attr = {.name = "l3_parity_slice_1", .mode = (S_IRUSR | S_IWUSR)},
.size = GEN7_L3LOG_SIZE,
.read = i915_l3_read,
.write = i915_l3_write,
.mmap = NULL,
.private = (void *)1
};
#if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
static ssize_t error_state_read(struct file *filp, struct kobject *kobj,
struct bin_attribute *attr, char *buf,
loff_t off, size_t count)
{
struct device *kdev = kobj_to_dev(kobj);
struct drm_i915_private *i915 = kdev_minor_to_i915(kdev);
struct i915_gpu_coredump *gpu;
ssize_t ret = 0;
/*
* FIXME: Concurrent clients triggering resets and reading + clearing
* dumps can cause inconsistent sysfs reads when a user calls in with a
* non-zero offset to complete a prior partial read but the
* gpu_coredump has been cleared or replaced.
*/
gpu = i915_first_error_state(i915);
if (IS_ERR(gpu)) {
ret = PTR_ERR(gpu);
} else if (gpu) {
ret = i915_gpu_coredump_copy_to_buffer(gpu, buf, off, count);
i915_gpu_coredump_put(gpu);
} else {
const char *str = "No error state collected\n";
size_t len = strlen(str);
if (off < len) {
ret = min_t(size_t, count, len - off);
memcpy(buf, str + off, ret);
}
}
return ret;
}
static ssize_t error_state_write(struct file *file, struct kobject *kobj,
struct bin_attribute *attr, char *buf,
loff_t off, size_t count)
{
struct device *kdev = kobj_to_dev(kobj);
struct drm_i915_private *dev_priv = kdev_minor_to_i915(kdev);
drm_dbg(&dev_priv->drm, "Resetting error state\n");
i915_reset_error_state(dev_priv);
return count;
}
static const struct bin_attribute error_state_attr = {
.attr.name = "error",
.attr.mode = S_IRUSR | S_IWUSR,
.size = 0,
.read = error_state_read,
.write = error_state_write,
};
static void i915_setup_error_capture(struct device *kdev)
{
if (sysfs_create_bin_file(&kdev->kobj, &error_state_attr))
drm_err(&kdev_minor_to_i915(kdev)->drm,
"error_state sysfs setup failed\n");
}
static void i915_teardown_error_capture(struct device *kdev)
{
sysfs_remove_bin_file(&kdev->kobj, &error_state_attr);
}
#else
static void i915_setup_error_capture(struct device *kdev) {}
static void i915_teardown_error_capture(struct device *kdev) {}
#endif
void i915_setup_sysfs(struct drm_i915_private *dev_priv)
{
struct device *kdev = dev_priv->drm.primary->kdev;
int ret;
if (HAS_L3_DPF(dev_priv)) {
ret = device_create_bin_file(kdev, &dpf_attrs);
if (ret)
drm_err(&dev_priv->drm,
"l3 parity sysfs setup failed\n");
if (NUM_L3_SLICES(dev_priv) > 1) {
ret = device_create_bin_file(kdev,
&dpf_attrs_1);
if (ret)
drm_err(&dev_priv->drm,
"l3 parity slice 1 setup failed\n");
}
}
dev_priv->sysfs_gt = kobject_create_and_add("gt", &kdev->kobj);
if (!dev_priv->sysfs_gt)
drm_warn(&dev_priv->drm,
"failed to register GT sysfs directory\n");
i915_setup_error_capture(kdev);
intel_engines_add_sysfs(dev_priv);
}
void i915_teardown_sysfs(struct drm_i915_private *dev_priv)
{
struct device *kdev = dev_priv->drm.primary->kdev;
i915_teardown_error_capture(kdev);
device_remove_bin_file(kdev, &dpf_attrs_1);
device_remove_bin_file(kdev, &dpf_attrs);
kobject_put(dev_priv->sysfs_gt);
}
| linux-master | drivers/gpu/drm/i915/i915_sysfs.c |
/*
* Copyright © 2014 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <linux/string_helpers.h>
#include <drm/drm_print.h>
#include "i915_params.h"
#include "i915_drv.h"
DECLARE_DYNDBG_CLASSMAP(drm_debug_classes, DD_CLASS_TYPE_DISJOINT_BITS, 0,
"DRM_UT_CORE",
"DRM_UT_DRIVER",
"DRM_UT_KMS",
"DRM_UT_PRIME",
"DRM_UT_ATOMIC",
"DRM_UT_VBL",
"DRM_UT_STATE",
"DRM_UT_LEASE",
"DRM_UT_DP",
"DRM_UT_DRMRES");
#define i915_param_named(name, T, perm, desc) \
module_param_named(name, i915_modparams.name, T, perm); \
MODULE_PARM_DESC(name, desc)
#define i915_param_named_unsafe(name, T, perm, desc) \
module_param_named_unsafe(name, i915_modparams.name, T, perm); \
MODULE_PARM_DESC(name, desc)
struct i915_params i915_modparams __read_mostly = {
#define MEMBER(T, member, value, ...) .member = (value),
I915_PARAMS_FOR_EACH(MEMBER)
#undef MEMBER
};
/*
* Note: As a rule, keep module parameter sysfs permissions read-only
* 0400. Runtime changes are only supported through i915 debugfs.
*
* For any exceptions requiring write access and runtime changes through module
* parameter sysfs, prevent debugfs file creation by setting the parameter's
* debugfs mode to 0.
*/
i915_param_named(modeset, int, 0400,
"Use kernel modesetting [KMS] (0=disable, "
"1=on, -1=force vga console preference [default])");
i915_param_named_unsafe(enable_dc, int, 0400,
"Enable power-saving display C-states. "
"(-1=auto [default]; 0=disable; 1=up to DC5; 2=up to DC6; "
"3=up to DC5 with DC3CO; 4=up to DC6 with DC3CO)");
i915_param_named_unsafe(enable_fbc, int, 0400,
"Enable frame buffer compression for power savings "
"(default: -1 (use per-chip default))");
i915_param_named_unsafe(lvds_channel_mode, int, 0400,
"Specify LVDS channel mode "
"(0=probe BIOS [default], 1=single-channel, 2=dual-channel)");
i915_param_named_unsafe(panel_use_ssc, int, 0400,
"Use Spread Spectrum Clock with panels [LVDS/eDP] "
"(default: auto from VBT)");
i915_param_named_unsafe(vbt_sdvo_panel_type, int, 0400,
"Override/Ignore selection of SDVO panel mode in the VBT "
"(-2=ignore, -1=auto [default], index in VBT BIOS table)");
i915_param_named_unsafe(reset, uint, 0400,
"Attempt GPU resets (0=disabled, 1=full gpu reset, 2=engine reset [default])");
i915_param_named_unsafe(vbt_firmware, charp, 0400,
"Load VBT from specified file under /lib/firmware");
#if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
i915_param_named(error_capture, bool, 0400,
"Record the GPU state following a hang. "
"This information in /sys/class/drm/card<N>/error is vital for "
"triaging and debugging hangs.");
#endif
i915_param_named_unsafe(enable_hangcheck, bool, 0400,
"Periodically check GPU activity for detecting hangs. "
"WARNING: Disabling this can cause system wide hangs. "
"(default: true)");
i915_param_named_unsafe(enable_psr, int, 0400,
"Enable PSR "
"(0=disabled, 1=enable up to PSR1, 2=enable up to PSR2) "
"Default: -1 (use per-chip default)");
i915_param_named(psr_safest_params, bool, 0400,
"Replace PSR VBT parameters by the safest and not optimal ones. This "
"is helpful to detect if PSR issues are related to bad values set in "
" VBT. (0=use VBT parameters, 1=use safest parameters)");
i915_param_named_unsafe(enable_psr2_sel_fetch, bool, 0400,
"Enable PSR2 selective fetch "
"(0=disabled, 1=enabled) "
"Default: 0");
i915_param_named_unsafe(enable_sagv, bool, 0600,
"Enable system agent voltage/frequency scaling (SAGV) (default: true)");
i915_param_named_unsafe(force_probe, charp, 0400,
"Force probe options for specified supported devices. "
"See CONFIG_DRM_I915_FORCE_PROBE for details.");
i915_param_named_unsafe(disable_power_well, int, 0400,
"Disable display power wells when possible "
"(-1=auto [default], 0=power wells always on, 1=power wells disabled when possible)");
i915_param_named_unsafe(enable_ips, int, 0400, "Enable IPS (default: true)");
i915_param_named_unsafe(enable_dpt, bool, 0400,
"Enable display page table (DPT) (default: true)");
i915_param_named(fastboot, int, 0400,
"Try to skip unnecessary mode sets at boot time "
"(0=disabled, 1=enabled) "
"Default: -1 (use per-chip default)");
i915_param_named_unsafe(load_detect_test, bool, 0400,
"Force-enable the VGA load detect code for testing (default:false). "
"For developers only.");
i915_param_named_unsafe(force_reset_modeset_test, bool, 0400,
"Force a modeset during gpu reset for testing (default:false). "
"For developers only.");
i915_param_named_unsafe(invert_brightness, int, 0400,
"Invert backlight brightness "
"(-1 force normal, 0 machine defaults, 1 force inversion), please "
"report PCI device ID, subsystem vendor and subsystem device ID "
"to [email protected], if your machine needs it. "
"It will then be included in an upcoming module version.");
i915_param_named(disable_display, bool, 0400,
"Disable display (default: false)");
i915_param_named(memtest, bool, 0400,
"Perform a read/write test of all device memory on module load (default: off)");
i915_param_named(mmio_debug, int, 0400,
"Enable the MMIO debug code for the first N failures (default: off). "
"This may negatively affect performance.");
/* Special case writable file */
i915_param_named(verbose_state_checks, bool, 0600,
"Enable verbose logs (ie. WARN_ON()) in case of unexpected hw state conditions.");
i915_param_named_unsafe(nuclear_pageflip, bool, 0400,
"Force enable atomic functionality on platforms that don't have full support yet.");
/* WA to get away with the default setting in VBT for early platforms.Will be removed */
i915_param_named_unsafe(edp_vswing, int, 0400,
"Ignore/Override vswing pre-emph table selection from VBT "
"(0=use value from vbt [default], 1=low power swing(200mV),"
"2=default swing(400mV))");
i915_param_named_unsafe(enable_guc, int, 0400,
"Enable GuC load for GuC submission and/or HuC load. "
"Required functionality can be selected using bitmask values. "
"(-1=auto [default], 0=disable, 1=GuC submission, 2=HuC load)");
i915_param_named(guc_log_level, int, 0400,
"GuC firmware logging level. Requires GuC to be loaded. "
"(-1=auto [default], 0=disable, 1..4=enable with verbosity min..max)");
i915_param_named_unsafe(guc_firmware_path, charp, 0400,
"GuC firmware path to use instead of the default one");
i915_param_named_unsafe(huc_firmware_path, charp, 0400,
"HuC firmware path to use instead of the default one");
i915_param_named_unsafe(dmc_firmware_path, charp, 0400,
"DMC firmware path to use instead of the default one");
i915_param_named_unsafe(gsc_firmware_path, charp, 0400,
"GSC firmware path to use instead of the default one");
i915_param_named_unsafe(enable_dp_mst, bool, 0400,
"Enable multi-stream transport (MST) for new DisplayPort sinks. (default: true)");
#if IS_ENABLED(CONFIG_DRM_I915_DEBUG)
i915_param_named_unsafe(inject_probe_failure, uint, 0400,
"Force an error after a number of failure check points (0:disabled (default), N:force failure at the Nth failure check point)");
#endif
i915_param_named(enable_dpcd_backlight, int, 0400,
"Enable support for DPCD backlight control"
"(-1=use per-VBT LFP backlight type setting [default], 0=disabled, 1=enable, 2=force VESA interface, 3=force Intel interface)");
#if IS_ENABLED(CONFIG_DRM_I915_GVT)
i915_param_named(enable_gvt, bool, 0400,
"Enable support for Intel GVT-g graphics virtualization host support(default:false)");
#endif
#if CONFIG_DRM_I915_REQUEST_TIMEOUT
i915_param_named_unsafe(request_timeout_ms, uint, 0600,
"Default request/fence/batch buffer expiration timeout.");
#endif
i915_param_named_unsafe(lmem_size, uint, 0400,
"Set the lmem size(in MiB) for each region. (default: 0, all memory)");
i915_param_named_unsafe(lmem_bar_size, uint, 0400,
"Set the lmem bar size(in MiB).");
static void _param_print_bool(struct drm_printer *p, const char *name,
bool val)
{
drm_printf(p, "i915.%s=%s\n", name, str_yes_no(val));
}
static void _param_print_int(struct drm_printer *p, const char *name,
int val)
{
drm_printf(p, "i915.%s=%d\n", name, val);
}
static void _param_print_uint(struct drm_printer *p, const char *name,
unsigned int val)
{
drm_printf(p, "i915.%s=%u\n", name, val);
}
static void _param_print_ulong(struct drm_printer *p, const char *name,
unsigned long val)
{
drm_printf(p, "i915.%s=%lu\n", name, val);
}
static void _param_print_charp(struct drm_printer *p, const char *name,
const char *val)
{
drm_printf(p, "i915.%s=%s\n", name, val);
}
#define _param_print(p, name, val) \
_Generic(val, \
bool: _param_print_bool, \
int: _param_print_int, \
unsigned int: _param_print_uint, \
unsigned long: _param_print_ulong, \
char *: _param_print_charp)(p, name, val)
/**
* i915_params_dump - dump i915 modparams
* @params: i915 modparams
* @p: the &drm_printer
*
* Pretty printer for i915 modparams.
*/
void i915_params_dump(const struct i915_params *params, struct drm_printer *p)
{
#define PRINT(T, x, ...) _param_print(p, #x, params->x);
I915_PARAMS_FOR_EACH(PRINT);
#undef PRINT
}
static void _param_dup_charp(char **valp)
{
*valp = kstrdup(*valp, GFP_ATOMIC);
}
static void _param_nop(void *valp)
{
}
#define _param_dup(valp) \
_Generic(valp, \
char **: _param_dup_charp, \
default: _param_nop)(valp)
void i915_params_copy(struct i915_params *dest, const struct i915_params *src)
{
*dest = *src;
#define DUP(T, x, ...) _param_dup(&dest->x);
I915_PARAMS_FOR_EACH(DUP);
#undef DUP
}
static void _param_free_charp(char **valp)
{
kfree(*valp);
*valp = NULL;
}
#define _param_free(valp) \
_Generic(valp, \
char **: _param_free_charp, \
default: _param_nop)(valp)
/* free the allocated members, *not* the passed in params itself */
void i915_params_free(struct i915_params *params)
{
#define FREE(T, x, ...) _param_free(¶ms->x);
I915_PARAMS_FOR_EACH(FREE);
#undef FREE
}
| linux-master | drivers/gpu/drm/i915/i915_params.c |
/*
* 32-bit ioctl compatibility routines for the i915 DRM.
*
* Copyright (C) Paul Mackerras 2005
* Copyright (C) Alan Hourihane 2005
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* Author: Alan Hourihane <[email protected]>
*/
#include <linux/compat.h>
#include <drm/drm_ioctl.h>
#include "i915_drv.h"
#include "i915_getparam.h"
#include "i915_ioc32.h"
struct drm_i915_getparam32 {
s32 param;
/*
* We screwed up the generic ioctl struct here and used a variable-sized
* pointer. Use u32 in the compat struct to match the 32bit pointer
* userspace expects.
*/
u32 value;
};
static int compat_i915_getparam(struct file *file, unsigned int cmd,
unsigned long arg)
{
struct drm_i915_getparam32 req32;
struct drm_i915_getparam req;
if (copy_from_user(&req32, (void __user *)arg, sizeof(req32)))
return -EFAULT;
req.param = req32.param;
req.value = compat_ptr(req32.value);
return drm_ioctl_kernel(file, i915_getparam_ioctl, &req,
DRM_RENDER_ALLOW);
}
static drm_ioctl_compat_t *i915_compat_ioctls[] = {
[DRM_I915_GETPARAM] = compat_i915_getparam,
};
/**
* i915_ioc32_compat_ioctl - handle the mistakes of the past
* @filp: the file pointer
* @cmd: the ioctl command (and encoded flags)
* @arg: the ioctl argument (from userspace)
*
* Called whenever a 32-bit process running under a 64-bit kernel
* performs an ioctl on /dev/dri/card<n>.
*/
long i915_ioc32_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
unsigned int nr = DRM_IOCTL_NR(cmd);
drm_ioctl_compat_t *fn = NULL;
int ret;
if (nr < DRM_COMMAND_BASE || nr >= DRM_COMMAND_END)
return drm_compat_ioctl(filp, cmd, arg);
if (nr < DRM_COMMAND_BASE + ARRAY_SIZE(i915_compat_ioctls))
fn = i915_compat_ioctls[nr - DRM_COMMAND_BASE];
if (fn != NULL)
ret = (*fn) (filp, cmd, arg);
else
ret = drm_ioctl(filp, cmd, arg);
return ret;
}
| linux-master | drivers/gpu/drm/i915/i915_ioc32.c |
/*
* Copyright © 2016 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
#include <linux/string_helpers.h>
#include <drm/drm_print.h>
#include <drm/i915_pciids.h>
#include "display/intel_display_device.h"
#include "gt/intel_gt_regs.h"
#include "i915_drv.h"
#include "i915_reg.h"
#include "i915_utils.h"
#include "intel_device_info.h"
#define PLATFORM_NAME(x) [INTEL_##x] = #x
static const char * const platform_names[] = {
PLATFORM_NAME(I830),
PLATFORM_NAME(I845G),
PLATFORM_NAME(I85X),
PLATFORM_NAME(I865G),
PLATFORM_NAME(I915G),
PLATFORM_NAME(I915GM),
PLATFORM_NAME(I945G),
PLATFORM_NAME(I945GM),
PLATFORM_NAME(G33),
PLATFORM_NAME(PINEVIEW),
PLATFORM_NAME(I965G),
PLATFORM_NAME(I965GM),
PLATFORM_NAME(G45),
PLATFORM_NAME(GM45),
PLATFORM_NAME(IRONLAKE),
PLATFORM_NAME(SANDYBRIDGE),
PLATFORM_NAME(IVYBRIDGE),
PLATFORM_NAME(VALLEYVIEW),
PLATFORM_NAME(HASWELL),
PLATFORM_NAME(BROADWELL),
PLATFORM_NAME(CHERRYVIEW),
PLATFORM_NAME(SKYLAKE),
PLATFORM_NAME(BROXTON),
PLATFORM_NAME(KABYLAKE),
PLATFORM_NAME(GEMINILAKE),
PLATFORM_NAME(COFFEELAKE),
PLATFORM_NAME(COMETLAKE),
PLATFORM_NAME(ICELAKE),
PLATFORM_NAME(ELKHARTLAKE),
PLATFORM_NAME(JASPERLAKE),
PLATFORM_NAME(TIGERLAKE),
PLATFORM_NAME(ROCKETLAKE),
PLATFORM_NAME(DG1),
PLATFORM_NAME(ALDERLAKE_S),
PLATFORM_NAME(ALDERLAKE_P),
PLATFORM_NAME(XEHPSDV),
PLATFORM_NAME(DG2),
PLATFORM_NAME(PONTEVECCHIO),
PLATFORM_NAME(METEORLAKE),
};
#undef PLATFORM_NAME
const char *intel_platform_name(enum intel_platform platform)
{
BUILD_BUG_ON(ARRAY_SIZE(platform_names) != INTEL_MAX_PLATFORMS);
if (WARN_ON_ONCE(platform >= ARRAY_SIZE(platform_names) ||
platform_names[platform] == NULL))
return "<unknown>";
return platform_names[platform];
}
void intel_device_info_print(const struct intel_device_info *info,
const struct intel_runtime_info *runtime,
struct drm_printer *p)
{
if (runtime->graphics.ip.rel)
drm_printf(p, "graphics version: %u.%02u\n",
runtime->graphics.ip.ver,
runtime->graphics.ip.rel);
else
drm_printf(p, "graphics version: %u\n",
runtime->graphics.ip.ver);
if (runtime->media.ip.rel)
drm_printf(p, "media version: %u.%02u\n",
runtime->media.ip.ver,
runtime->media.ip.rel);
else
drm_printf(p, "media version: %u\n",
runtime->media.ip.ver);
drm_printf(p, "graphics stepping: %s\n", intel_step_name(runtime->step.graphics_step));
drm_printf(p, "media stepping: %s\n", intel_step_name(runtime->step.media_step));
drm_printf(p, "display stepping: %s\n", intel_step_name(runtime->step.display_step));
drm_printf(p, "base die stepping: %s\n", intel_step_name(runtime->step.basedie_step));
drm_printf(p, "gt: %d\n", info->gt);
drm_printf(p, "memory-regions: 0x%x\n", info->memory_regions);
drm_printf(p, "page-sizes: 0x%x\n", runtime->page_sizes);
drm_printf(p, "platform: %s\n", intel_platform_name(info->platform));
drm_printf(p, "ppgtt-size: %d\n", runtime->ppgtt_size);
drm_printf(p, "ppgtt-type: %d\n", runtime->ppgtt_type);
drm_printf(p, "dma_mask_size: %u\n", info->dma_mask_size);
#define PRINT_FLAG(name) drm_printf(p, "%s: %s\n", #name, str_yes_no(info->name))
DEV_INFO_FOR_EACH_FLAG(PRINT_FLAG);
#undef PRINT_FLAG
drm_printf(p, "has_pooled_eu: %s\n", str_yes_no(runtime->has_pooled_eu));
drm_printf(p, "rawclk rate: %u kHz\n", runtime->rawclk_freq);
}
#undef INTEL_VGA_DEVICE
#define INTEL_VGA_DEVICE(id, info) (id)
static const u16 subplatform_ult_ids[] = {
INTEL_HSW_ULT_GT1_IDS(0),
INTEL_HSW_ULT_GT2_IDS(0),
INTEL_HSW_ULT_GT3_IDS(0),
INTEL_BDW_ULT_GT1_IDS(0),
INTEL_BDW_ULT_GT2_IDS(0),
INTEL_BDW_ULT_GT3_IDS(0),
INTEL_BDW_ULT_RSVD_IDS(0),
INTEL_SKL_ULT_GT1_IDS(0),
INTEL_SKL_ULT_GT2_IDS(0),
INTEL_SKL_ULT_GT3_IDS(0),
INTEL_KBL_ULT_GT1_IDS(0),
INTEL_KBL_ULT_GT2_IDS(0),
INTEL_KBL_ULT_GT3_IDS(0),
INTEL_CFL_U_GT2_IDS(0),
INTEL_CFL_U_GT3_IDS(0),
INTEL_WHL_U_GT1_IDS(0),
INTEL_WHL_U_GT2_IDS(0),
INTEL_WHL_U_GT3_IDS(0),
INTEL_CML_U_GT1_IDS(0),
INTEL_CML_U_GT2_IDS(0),
};
static const u16 subplatform_ulx_ids[] = {
INTEL_HSW_ULX_GT1_IDS(0),
INTEL_HSW_ULX_GT2_IDS(0),
INTEL_BDW_ULX_GT1_IDS(0),
INTEL_BDW_ULX_GT2_IDS(0),
INTEL_BDW_ULX_GT3_IDS(0),
INTEL_BDW_ULX_RSVD_IDS(0),
INTEL_SKL_ULX_GT1_IDS(0),
INTEL_SKL_ULX_GT2_IDS(0),
INTEL_KBL_ULX_GT1_IDS(0),
INTEL_KBL_ULX_GT2_IDS(0),
INTEL_AML_KBL_GT2_IDS(0),
INTEL_AML_CFL_GT2_IDS(0),
};
static const u16 subplatform_portf_ids[] = {
INTEL_ICL_PORT_F_IDS(0),
};
static const u16 subplatform_uy_ids[] = {
INTEL_TGL_12_GT2_IDS(0),
};
static const u16 subplatform_n_ids[] = {
INTEL_ADLN_IDS(0),
};
static const u16 subplatform_rpl_ids[] = {
INTEL_RPLS_IDS(0),
INTEL_RPLP_IDS(0),
};
static const u16 subplatform_rplu_ids[] = {
INTEL_RPLU_IDS(0),
};
static const u16 subplatform_g10_ids[] = {
INTEL_DG2_G10_IDS(0),
INTEL_ATS_M150_IDS(0),
};
static const u16 subplatform_g11_ids[] = {
INTEL_DG2_G11_IDS(0),
INTEL_ATS_M75_IDS(0),
};
static const u16 subplatform_g12_ids[] = {
INTEL_DG2_G12_IDS(0),
};
static const u16 subplatform_m_ids[] = {
INTEL_MTL_M_IDS(0),
};
static const u16 subplatform_p_ids[] = {
INTEL_MTL_P_IDS(0),
};
static bool find_devid(u16 id, const u16 *p, unsigned int num)
{
for (; num; num--, p++) {
if (*p == id)
return true;
}
return false;
}
static void intel_device_info_subplatform_init(struct drm_i915_private *i915)
{
const struct intel_device_info *info = INTEL_INFO(i915);
const struct intel_runtime_info *rinfo = RUNTIME_INFO(i915);
const unsigned int pi = __platform_mask_index(rinfo, info->platform);
const unsigned int pb = __platform_mask_bit(rinfo, info->platform);
u16 devid = INTEL_DEVID(i915);
u32 mask = 0;
/* Make sure IS_<platform> checks are working. */
RUNTIME_INFO(i915)->platform_mask[pi] = BIT(pb);
/* Find and mark subplatform bits based on the PCI device id. */
if (find_devid(devid, subplatform_ult_ids,
ARRAY_SIZE(subplatform_ult_ids))) {
mask = BIT(INTEL_SUBPLATFORM_ULT);
if (IS_HASWELL(i915) || IS_BROADWELL(i915))
DISPLAY_RUNTIME_INFO(i915)->port_mask &= ~BIT(PORT_D);
} else if (find_devid(devid, subplatform_ulx_ids,
ARRAY_SIZE(subplatform_ulx_ids))) {
mask = BIT(INTEL_SUBPLATFORM_ULX);
if (IS_HASWELL(i915) || IS_BROADWELL(i915)) {
/* ULX machines are also considered ULT. */
mask |= BIT(INTEL_SUBPLATFORM_ULT);
DISPLAY_RUNTIME_INFO(i915)->port_mask &= ~BIT(PORT_D);
}
} else if (find_devid(devid, subplatform_portf_ids,
ARRAY_SIZE(subplatform_portf_ids))) {
DISPLAY_RUNTIME_INFO(i915)->port_mask |= BIT(PORT_F);
mask = BIT(INTEL_SUBPLATFORM_PORTF);
} else if (find_devid(devid, subplatform_uy_ids,
ARRAY_SIZE(subplatform_uy_ids))) {
mask = BIT(INTEL_SUBPLATFORM_UY);
} else if (find_devid(devid, subplatform_n_ids,
ARRAY_SIZE(subplatform_n_ids))) {
mask = BIT(INTEL_SUBPLATFORM_N);
} else if (find_devid(devid, subplatform_rpl_ids,
ARRAY_SIZE(subplatform_rpl_ids))) {
mask = BIT(INTEL_SUBPLATFORM_RPL);
if (find_devid(devid, subplatform_rplu_ids,
ARRAY_SIZE(subplatform_rplu_ids)))
mask |= BIT(INTEL_SUBPLATFORM_RPLU);
} else if (find_devid(devid, subplatform_g10_ids,
ARRAY_SIZE(subplatform_g10_ids))) {
mask = BIT(INTEL_SUBPLATFORM_G10);
} else if (find_devid(devid, subplatform_g11_ids,
ARRAY_SIZE(subplatform_g11_ids))) {
mask = BIT(INTEL_SUBPLATFORM_G11);
} else if (find_devid(devid, subplatform_g12_ids,
ARRAY_SIZE(subplatform_g12_ids))) {
mask = BIT(INTEL_SUBPLATFORM_G12);
} else if (find_devid(devid, subplatform_m_ids,
ARRAY_SIZE(subplatform_m_ids))) {
mask = BIT(INTEL_SUBPLATFORM_M);
} else if (find_devid(devid, subplatform_p_ids,
ARRAY_SIZE(subplatform_p_ids))) {
mask = BIT(INTEL_SUBPLATFORM_P);
}
GEM_BUG_ON(mask & ~INTEL_SUBPLATFORM_MASK);
RUNTIME_INFO(i915)->platform_mask[pi] |= mask;
}
static void ip_ver_read(struct drm_i915_private *i915, u32 offset, struct intel_ip_version *ip)
{
struct pci_dev *pdev = to_pci_dev(i915->drm.dev);
void __iomem *addr;
u32 val;
u8 expected_ver = ip->ver;
u8 expected_rel = ip->rel;
addr = pci_iomap_range(pdev, 0, offset, sizeof(u32));
if (drm_WARN_ON(&i915->drm, !addr))
return;
val = ioread32(addr);
pci_iounmap(pdev, addr);
ip->ver = REG_FIELD_GET(GMD_ID_ARCH_MASK, val);
ip->rel = REG_FIELD_GET(GMD_ID_RELEASE_MASK, val);
ip->step = REG_FIELD_GET(GMD_ID_STEP, val);
/* Sanity check against expected versions from device info */
if (IP_VER(ip->ver, ip->rel) < IP_VER(expected_ver, expected_rel))
drm_dbg(&i915->drm,
"Hardware reports GMD IP version %u.%u (REG[0x%x] = 0x%08x) but minimum expected is %u.%u\n",
ip->ver, ip->rel, offset, val, expected_ver, expected_rel);
}
/*
* Setup the graphics version for the current device. This must be done before
* any code that performs checks on GRAPHICS_VER or DISPLAY_VER, so this
* function should be called very early in the driver initialization sequence.
*
* Regular MMIO access is not yet setup at the point this function is called so
* we peek at the appropriate MMIO offset directly. The GMD_ID register is
* part of an 'always on' power well by design, so we don't need to worry about
* forcewake while reading it.
*/
static void intel_ipver_early_init(struct drm_i915_private *i915)
{
struct intel_runtime_info *runtime = RUNTIME_INFO(i915);
if (!HAS_GMD_ID(i915)) {
drm_WARN_ON(&i915->drm, RUNTIME_INFO(i915)->graphics.ip.ver > 12);
/*
* On older platforms, graphics and media share the same ip
* version and release.
*/
RUNTIME_INFO(i915)->media.ip =
RUNTIME_INFO(i915)->graphics.ip;
return;
}
ip_ver_read(i915, i915_mmio_reg_offset(GMD_ID_GRAPHICS),
&runtime->graphics.ip);
/* Wa_22012778468 */
if (runtime->graphics.ip.ver == 0x0 &&
INTEL_INFO(i915)->platform == INTEL_METEORLAKE) {
RUNTIME_INFO(i915)->graphics.ip.ver = 12;
RUNTIME_INFO(i915)->graphics.ip.rel = 70;
}
ip_ver_read(i915, i915_mmio_reg_offset(GMD_ID_MEDIA),
&runtime->media.ip);
}
/**
* intel_device_info_runtime_init_early - initialize early runtime info
* @i915: the i915 device
*
* Determine early intel_device_info fields at runtime. This function needs
* to be called before the MMIO has been setup.
*/
void intel_device_info_runtime_init_early(struct drm_i915_private *i915)
{
intel_ipver_early_init(i915);
intel_device_info_subplatform_init(i915);
}
static const struct intel_display_device_info no_display = {};
/**
* intel_device_info_runtime_init - initialize runtime info
* @dev_priv: the i915 device
*
* Determine various intel_device_info fields at runtime.
*
* Use it when either:
* - it's judged too laborious to fill n static structures with the limit
* when a simple if statement does the job,
* - run-time checks (eg read fuse/strap registers) are needed.
*
* This function needs to be called:
* - after the MMIO has been setup as we are reading registers,
* - after the PCH has been detected,
* - before the first usage of the fields it can tweak.
*/
void intel_device_info_runtime_init(struct drm_i915_private *dev_priv)
{
struct intel_runtime_info *runtime = RUNTIME_INFO(dev_priv);
if (HAS_DISPLAY(dev_priv))
intel_display_device_info_runtime_init(dev_priv);
/* Display may have been disabled by runtime init */
if (!HAS_DISPLAY(dev_priv)) {
dev_priv->drm.driver_features &= ~(DRIVER_MODESET |
DRIVER_ATOMIC);
dev_priv->display.info.__device_info = &no_display;
}
/* Disable nuclear pageflip by default on pre-g4x */
if (!dev_priv->params.nuclear_pageflip &&
DISPLAY_VER(dev_priv) < 5 && !IS_G4X(dev_priv))
dev_priv->drm.driver_features &= ~DRIVER_ATOMIC;
BUILD_BUG_ON(BITS_PER_TYPE(intel_engine_mask_t) < I915_NUM_ENGINES);
if (GRAPHICS_VER(dev_priv) == 6 && i915_vtd_active(dev_priv)) {
drm_info(&dev_priv->drm,
"Disabling ppGTT for VT-d support\n");
runtime->ppgtt_type = INTEL_PPGTT_NONE;
}
runtime->rawclk_freq = intel_read_rawclk(dev_priv);
drm_dbg(&dev_priv->drm, "rawclk rate: %d kHz\n", runtime->rawclk_freq);
}
/*
* Set up device info and initial runtime info at driver create.
*
* Note: i915 is only an allocated blob of memory at this point.
*/
void intel_device_info_driver_create(struct drm_i915_private *i915,
u16 device_id,
const struct intel_device_info *match_info)
{
struct intel_runtime_info *runtime;
u16 ver, rel, step;
/* Setup INTEL_INFO() */
i915->__info = match_info;
/* Initialize initial runtime info from static const data and pdev. */
runtime = RUNTIME_INFO(i915);
memcpy(runtime, &INTEL_INFO(i915)->__runtime, sizeof(*runtime));
/* Probe display support */
i915->display.info.__device_info = intel_display_device_probe(i915, HAS_GMD_ID(i915),
&ver, &rel, &step);
memcpy(DISPLAY_RUNTIME_INFO(i915),
&DISPLAY_INFO(i915)->__runtime_defaults,
sizeof(*DISPLAY_RUNTIME_INFO(i915)));
if (HAS_GMD_ID(i915)) {
DISPLAY_RUNTIME_INFO(i915)->ip.ver = ver;
DISPLAY_RUNTIME_INFO(i915)->ip.rel = rel;
DISPLAY_RUNTIME_INFO(i915)->ip.step = step;
}
runtime->device_id = device_id;
}
void intel_driver_caps_print(const struct intel_driver_caps *caps,
struct drm_printer *p)
{
drm_printf(p, "Has logical contexts? %s\n",
str_yes_no(caps->has_logical_contexts));
drm_printf(p, "scheduler: 0x%x\n", caps->scheduler);
}
| linux-master | drivers/gpu/drm/i915/intel_device_info.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2020 Intel Corporation
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <uapi/drm/i915_drm.h>
#include <drm/drm_print.h>
#include "gem/i915_gem_context.h"
#include "i915_drm_client.h"
#include "i915_file_private.h"
#include "i915_gem.h"
#include "i915_utils.h"
struct i915_drm_client *i915_drm_client_alloc(void)
{
struct i915_drm_client *client;
client = kzalloc(sizeof(*client), GFP_KERNEL);
if (!client)
return NULL;
kref_init(&client->kref);
spin_lock_init(&client->ctx_lock);
INIT_LIST_HEAD(&client->ctx_list);
return client;
}
void __i915_drm_client_free(struct kref *kref)
{
struct i915_drm_client *client =
container_of(kref, typeof(*client), kref);
kfree(client);
}
#ifdef CONFIG_PROC_FS
static const char * const uabi_class_names[] = {
[I915_ENGINE_CLASS_RENDER] = "render",
[I915_ENGINE_CLASS_COPY] = "copy",
[I915_ENGINE_CLASS_VIDEO] = "video",
[I915_ENGINE_CLASS_VIDEO_ENHANCE] = "video-enhance",
[I915_ENGINE_CLASS_COMPUTE] = "compute",
};
static u64 busy_add(struct i915_gem_context *ctx, unsigned int class)
{
struct i915_gem_engines_iter it;
struct intel_context *ce;
u64 total = 0;
for_each_gem_engine(ce, rcu_dereference(ctx->engines), it) {
if (ce->engine->uabi_class != class)
continue;
total += intel_context_get_total_runtime_ns(ce);
}
return total;
}
static void
show_client_class(struct drm_printer *p,
struct drm_i915_private *i915,
struct i915_drm_client *client,
unsigned int class)
{
const unsigned int capacity = i915->engine_uabi_class_count[class];
u64 total = atomic64_read(&client->past_runtime[class]);
struct i915_gem_context *ctx;
rcu_read_lock();
list_for_each_entry_rcu(ctx, &client->ctx_list, client_link)
total += busy_add(ctx, class);
rcu_read_unlock();
if (capacity)
drm_printf(p, "drm-engine-%s:\t%llu ns\n",
uabi_class_names[class], total);
if (capacity > 1)
drm_printf(p, "drm-engine-capacity-%s:\t%u\n",
uabi_class_names[class],
capacity);
}
void i915_drm_client_fdinfo(struct drm_printer *p, struct drm_file *file)
{
struct drm_i915_file_private *file_priv = file->driver_priv;
struct drm_i915_private *i915 = file_priv->i915;
unsigned int i;
/*
* ******************************************************************
* For text output format description please see drm-usage-stats.rst!
* ******************************************************************
*/
if (GRAPHICS_VER(i915) < 8)
return;
for (i = 0; i < ARRAY_SIZE(uabi_class_names); i++)
show_client_class(p, i915, file_priv->client, i);
}
#endif
| linux-master | drivers/gpu/drm/i915/i915_drm_client.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2020 Intel Corporation
*/
#include <linux/kernel.h>
#include "i915_config.h"
#include "i915_utils.h"
unsigned long
i915_fence_context_timeout(const struct drm_i915_private *i915, u64 context)
{
if (CONFIG_DRM_I915_FENCE_TIMEOUT && context)
return msecs_to_jiffies_timeout(CONFIG_DRM_I915_FENCE_TIMEOUT);
return 0;
}
| linux-master | drivers/gpu/drm/i915/i915_config.c |
/*
* SPDX-License-Identifier: MIT
*/
#include "gem/i915_gem_mman.h"
#include "gt/intel_engine_user.h"
#include "pxp/intel_pxp.h"
#include "i915_cmd_parser.h"
#include "i915_drv.h"
#include "i915_getparam.h"
#include "i915_perf.h"
int i915_getparam_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_i915_private *i915 = to_i915(dev);
struct pci_dev *pdev = to_pci_dev(dev->dev);
const struct sseu_dev_info *sseu = &to_gt(i915)->info.sseu;
drm_i915_getparam_t *param = data;
int value = 0;
switch (param->param) {
case I915_PARAM_IRQ_ACTIVE:
case I915_PARAM_ALLOW_BATCHBUFFER:
case I915_PARAM_LAST_DISPATCH:
case I915_PARAM_HAS_EXEC_CONSTANTS:
/* Reject all old ums/dri params. */
return -ENODEV;
case I915_PARAM_CHIPSET_ID:
value = pdev->device;
break;
case I915_PARAM_REVISION:
value = pdev->revision;
break;
case I915_PARAM_NUM_FENCES_AVAIL:
value = to_gt(i915)->ggtt->num_fences;
break;
case I915_PARAM_HAS_OVERLAY:
value = !!i915->display.overlay;
break;
case I915_PARAM_HAS_BSD:
value = !!intel_engine_lookup_user(i915,
I915_ENGINE_CLASS_VIDEO, 0);
break;
case I915_PARAM_HAS_BLT:
value = !!intel_engine_lookup_user(i915,
I915_ENGINE_CLASS_COPY, 0);
break;
case I915_PARAM_HAS_VEBOX:
value = !!intel_engine_lookup_user(i915,
I915_ENGINE_CLASS_VIDEO_ENHANCE, 0);
break;
case I915_PARAM_HAS_BSD2:
value = !!intel_engine_lookup_user(i915,
I915_ENGINE_CLASS_VIDEO, 1);
break;
case I915_PARAM_HAS_LLC:
value = HAS_LLC(i915);
break;
case I915_PARAM_HAS_WT:
value = HAS_WT(i915);
break;
case I915_PARAM_HAS_ALIASING_PPGTT:
value = INTEL_PPGTT(i915);
break;
case I915_PARAM_HAS_SEMAPHORES:
value = !!(i915->caps.scheduler & I915_SCHEDULER_CAP_SEMAPHORES);
break;
case I915_PARAM_HAS_SECURE_BATCHES:
value = HAS_SECURE_BATCHES(i915) && capable(CAP_SYS_ADMIN);
break;
case I915_PARAM_CMD_PARSER_VERSION:
value = i915_cmd_parser_get_version(i915);
break;
case I915_PARAM_SUBSLICE_TOTAL:
value = intel_sseu_subslice_total(sseu);
if (!value)
return -ENODEV;
break;
case I915_PARAM_EU_TOTAL:
value = sseu->eu_total;
if (!value)
return -ENODEV;
break;
case I915_PARAM_HAS_GPU_RESET:
value = i915->params.enable_hangcheck &&
intel_has_gpu_reset(to_gt(i915));
if (value && intel_has_reset_engine(to_gt(i915)))
value = 2;
break;
case I915_PARAM_HAS_RESOURCE_STREAMER:
value = 0;
break;
case I915_PARAM_HAS_POOLED_EU:
value = HAS_POOLED_EU(i915);
break;
case I915_PARAM_MIN_EU_IN_POOL:
value = sseu->min_eu_in_pool;
break;
case I915_PARAM_HUC_STATUS:
/* On platform with a media GT, the HuC is on that GT */
if (i915->media_gt)
value = intel_huc_check_status(&i915->media_gt->uc.huc);
else
value = intel_huc_check_status(&to_gt(i915)->uc.huc);
if (value < 0)
return value;
break;
case I915_PARAM_PXP_STATUS:
value = intel_pxp_get_readiness_status(i915->pxp);
if (value < 0)
return value;
break;
case I915_PARAM_MMAP_GTT_VERSION:
/* Though we've started our numbering from 1, and so class all
* earlier versions as 0, in effect their value is undefined as
* the ioctl will report EINVAL for the unknown param!
*/
value = i915_gem_mmap_gtt_version();
break;
case I915_PARAM_HAS_SCHEDULER:
value = i915->caps.scheduler;
break;
case I915_PARAM_MMAP_VERSION:
/* Remember to bump this if the version changes! */
case I915_PARAM_HAS_GEM:
case I915_PARAM_HAS_PAGEFLIPPING:
case I915_PARAM_HAS_EXECBUF2: /* depends on GEM */
case I915_PARAM_HAS_RELAXED_FENCING:
case I915_PARAM_HAS_COHERENT_RINGS:
case I915_PARAM_HAS_RELAXED_DELTA:
case I915_PARAM_HAS_GEN7_SOL_RESET:
case I915_PARAM_HAS_WAIT_TIMEOUT:
case I915_PARAM_HAS_PRIME_VMAP_FLUSH:
case I915_PARAM_HAS_PINNED_BATCHES:
case I915_PARAM_HAS_EXEC_NO_RELOC:
case I915_PARAM_HAS_EXEC_HANDLE_LUT:
case I915_PARAM_HAS_COHERENT_PHYS_GTT:
case I915_PARAM_HAS_EXEC_SOFTPIN:
case I915_PARAM_HAS_EXEC_ASYNC:
case I915_PARAM_HAS_EXEC_FENCE:
case I915_PARAM_HAS_EXEC_CAPTURE:
case I915_PARAM_HAS_EXEC_BATCH_FIRST:
case I915_PARAM_HAS_EXEC_FENCE_ARRAY:
case I915_PARAM_HAS_EXEC_SUBMIT_FENCE:
case I915_PARAM_HAS_EXEC_TIMELINE_FENCES:
case I915_PARAM_HAS_USERPTR_PROBE:
/* For the time being all of these are always true;
* if some supported hardware does not have one of these
* features this value needs to be provided from
* INTEL_INFO(), a feature macro, or similar.
*/
value = 1;
break;
case I915_PARAM_HAS_CONTEXT_ISOLATION:
value = intel_engines_has_context_isolation(i915);
break;
case I915_PARAM_SLICE_MASK:
/* Not supported from Xe_HP onward; use topology queries */
if (GRAPHICS_VER_FULL(i915) >= IP_VER(12, 50))
return -EINVAL;
value = sseu->slice_mask;
if (!value)
return -ENODEV;
break;
case I915_PARAM_SUBSLICE_MASK:
/* Not supported from Xe_HP onward; use topology queries */
if (GRAPHICS_VER_FULL(i915) >= IP_VER(12, 50))
return -EINVAL;
/* Only copy bits from the first slice */
value = intel_sseu_get_hsw_subslices(sseu, 0);
if (!value)
return -ENODEV;
break;
case I915_PARAM_CS_TIMESTAMP_FREQUENCY:
value = to_gt(i915)->clock_frequency;
break;
case I915_PARAM_MMAP_GTT_COHERENT:
value = INTEL_INFO(i915)->has_coherent_ggtt;
break;
case I915_PARAM_PERF_REVISION:
value = i915_perf_ioctl_version(i915);
break;
case I915_PARAM_OA_TIMESTAMP_FREQUENCY:
value = i915_perf_oa_timestamp_frequency(i915);
break;
default:
drm_dbg(&i915->drm, "Unknown parameter %d\n", param->param);
return -EINVAL;
}
if (put_user(value, param->value))
return -EFAULT;
return 0;
}
| linux-master | drivers/gpu/drm/i915/i915_getparam.c |
/*
* Copyright (c) 2008 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* Authors:
* Eric Anholt <[email protected]>
* Keith Packard <[email protected]>
* Mika Kuoppala <[email protected]>
*
*/
#include <linux/ascii85.h>
#include <linux/highmem.h>
#include <linux/nmi.h>
#include <linux/pagevec.h>
#include <linux/scatterlist.h>
#include <linux/string_helpers.h>
#include <linux/utsname.h>
#include <linux/zlib.h>
#include <drm/drm_cache.h>
#include <drm/drm_print.h>
#include "display/intel_dmc.h"
#include "display/intel_overlay.h"
#include "gem/i915_gem_context.h"
#include "gem/i915_gem_lmem.h"
#include "gt/intel_engine_regs.h"
#include "gt/intel_gt.h"
#include "gt/intel_gt_mcr.h"
#include "gt/intel_gt_pm.h"
#include "gt/intel_gt_regs.h"
#include "gt/uc/intel_guc_capture.h"
#include "i915_driver.h"
#include "i915_drv.h"
#include "i915_gpu_error.h"
#include "i915_memcpy.h"
#include "i915_reg.h"
#include "i915_scatterlist.h"
#include "i915_utils.h"
#define ALLOW_FAIL (__GFP_KSWAPD_RECLAIM | __GFP_RETRY_MAYFAIL | __GFP_NOWARN)
#define ATOMIC_MAYFAIL (GFP_ATOMIC | __GFP_NOWARN)
static void __sg_set_buf(struct scatterlist *sg,
void *addr, unsigned int len, loff_t it)
{
sg->page_link = (unsigned long)virt_to_page(addr);
sg->offset = offset_in_page(addr);
sg->length = len;
sg->dma_address = it;
}
static bool __i915_error_grow(struct drm_i915_error_state_buf *e, size_t len)
{
if (!len)
return false;
if (e->bytes + len + 1 <= e->size)
return true;
if (e->bytes) {
__sg_set_buf(e->cur++, e->buf, e->bytes, e->iter);
e->iter += e->bytes;
e->buf = NULL;
e->bytes = 0;
}
if (e->cur == e->end) {
struct scatterlist *sgl;
sgl = (typeof(sgl))__get_free_page(ALLOW_FAIL);
if (!sgl) {
e->err = -ENOMEM;
return false;
}
if (e->cur) {
e->cur->offset = 0;
e->cur->length = 0;
e->cur->page_link =
(unsigned long)sgl | SG_CHAIN;
} else {
e->sgl = sgl;
}
e->cur = sgl;
e->end = sgl + SG_MAX_SINGLE_ALLOC - 1;
}
e->size = ALIGN(len + 1, SZ_64K);
e->buf = kmalloc(e->size, ALLOW_FAIL);
if (!e->buf) {
e->size = PAGE_ALIGN(len + 1);
e->buf = kmalloc(e->size, GFP_KERNEL);
}
if (!e->buf) {
e->err = -ENOMEM;
return false;
}
return true;
}
__printf(2, 0)
static void i915_error_vprintf(struct drm_i915_error_state_buf *e,
const char *fmt, va_list args)
{
va_list ap;
int len;
if (e->err)
return;
va_copy(ap, args);
len = vsnprintf(NULL, 0, fmt, ap);
va_end(ap);
if (len <= 0) {
e->err = len;
return;
}
if (!__i915_error_grow(e, len))
return;
GEM_BUG_ON(e->bytes >= e->size);
len = vscnprintf(e->buf + e->bytes, e->size - e->bytes, fmt, args);
if (len < 0) {
e->err = len;
return;
}
e->bytes += len;
}
static void i915_error_puts(struct drm_i915_error_state_buf *e, const char *str)
{
unsigned len;
if (e->err || !str)
return;
len = strlen(str);
if (!__i915_error_grow(e, len))
return;
GEM_BUG_ON(e->bytes + len > e->size);
memcpy(e->buf + e->bytes, str, len);
e->bytes += len;
}
#define err_printf(e, ...) i915_error_printf(e, __VA_ARGS__)
#define err_puts(e, s) i915_error_puts(e, s)
static void __i915_printfn_error(struct drm_printer *p, struct va_format *vaf)
{
i915_error_vprintf(p->arg, vaf->fmt, *vaf->va);
}
static inline struct drm_printer
i915_error_printer(struct drm_i915_error_state_buf *e)
{
struct drm_printer p = {
.printfn = __i915_printfn_error,
.arg = e,
};
return p;
}
/* single threaded page allocator with a reserved stash for emergencies */
static void pool_fini(struct folio_batch *fbatch)
{
folio_batch_release(fbatch);
}
static int pool_refill(struct folio_batch *fbatch, gfp_t gfp)
{
while (folio_batch_space(fbatch)) {
struct folio *folio;
folio = folio_alloc(gfp, 0);
if (!folio)
return -ENOMEM;
folio_batch_add(fbatch, folio);
}
return 0;
}
static int pool_init(struct folio_batch *fbatch, gfp_t gfp)
{
int err;
folio_batch_init(fbatch);
err = pool_refill(fbatch, gfp);
if (err)
pool_fini(fbatch);
return err;
}
static void *pool_alloc(struct folio_batch *fbatch, gfp_t gfp)
{
struct folio *folio;
folio = folio_alloc(gfp, 0);
if (!folio && folio_batch_count(fbatch))
folio = fbatch->folios[--fbatch->nr];
return folio ? folio_address(folio) : NULL;
}
static void pool_free(struct folio_batch *fbatch, void *addr)
{
struct folio *folio = virt_to_folio(addr);
if (folio_batch_space(fbatch))
folio_batch_add(fbatch, folio);
else
folio_put(folio);
}
#ifdef CONFIG_DRM_I915_COMPRESS_ERROR
struct i915_vma_compress {
struct folio_batch pool;
struct z_stream_s zstream;
void *tmp;
};
static bool compress_init(struct i915_vma_compress *c)
{
struct z_stream_s *zstream = &c->zstream;
if (pool_init(&c->pool, ALLOW_FAIL))
return false;
zstream->workspace =
kmalloc(zlib_deflate_workspacesize(MAX_WBITS, MAX_MEM_LEVEL),
ALLOW_FAIL);
if (!zstream->workspace) {
pool_fini(&c->pool);
return false;
}
c->tmp = NULL;
if (i915_has_memcpy_from_wc())
c->tmp = pool_alloc(&c->pool, ALLOW_FAIL);
return true;
}
static bool compress_start(struct i915_vma_compress *c)
{
struct z_stream_s *zstream = &c->zstream;
void *workspace = zstream->workspace;
memset(zstream, 0, sizeof(*zstream));
zstream->workspace = workspace;
return zlib_deflateInit(zstream, Z_DEFAULT_COMPRESSION) == Z_OK;
}
static void *compress_next_page(struct i915_vma_compress *c,
struct i915_vma_coredump *dst)
{
void *page_addr;
struct page *page;
page_addr = pool_alloc(&c->pool, ALLOW_FAIL);
if (!page_addr)
return ERR_PTR(-ENOMEM);
page = virt_to_page(page_addr);
list_add_tail(&page->lru, &dst->page_list);
return page_addr;
}
static int compress_page(struct i915_vma_compress *c,
void *src,
struct i915_vma_coredump *dst,
bool wc)
{
struct z_stream_s *zstream = &c->zstream;
zstream->next_in = src;
if (wc && c->tmp && i915_memcpy_from_wc(c->tmp, src, PAGE_SIZE))
zstream->next_in = c->tmp;
zstream->avail_in = PAGE_SIZE;
do {
if (zstream->avail_out == 0) {
zstream->next_out = compress_next_page(c, dst);
if (IS_ERR(zstream->next_out))
return PTR_ERR(zstream->next_out);
zstream->avail_out = PAGE_SIZE;
}
if (zlib_deflate(zstream, Z_NO_FLUSH) != Z_OK)
return -EIO;
cond_resched();
} while (zstream->avail_in);
/* Fallback to uncompressed if we increase size? */
if (0 && zstream->total_out > zstream->total_in)
return -E2BIG;
return 0;
}
static int compress_flush(struct i915_vma_compress *c,
struct i915_vma_coredump *dst)
{
struct z_stream_s *zstream = &c->zstream;
do {
switch (zlib_deflate(zstream, Z_FINISH)) {
case Z_OK: /* more space requested */
zstream->next_out = compress_next_page(c, dst);
if (IS_ERR(zstream->next_out))
return PTR_ERR(zstream->next_out);
zstream->avail_out = PAGE_SIZE;
break;
case Z_STREAM_END:
goto end;
default: /* any error */
return -EIO;
}
} while (1);
end:
memset(zstream->next_out, 0, zstream->avail_out);
dst->unused = zstream->avail_out;
return 0;
}
static void compress_finish(struct i915_vma_compress *c)
{
zlib_deflateEnd(&c->zstream);
}
static void compress_fini(struct i915_vma_compress *c)
{
kfree(c->zstream.workspace);
if (c->tmp)
pool_free(&c->pool, c->tmp);
pool_fini(&c->pool);
}
static void err_compression_marker(struct drm_i915_error_state_buf *m)
{
err_puts(m, ":");
}
#else
struct i915_vma_compress {
struct folio_batch pool;
};
static bool compress_init(struct i915_vma_compress *c)
{
return pool_init(&c->pool, ALLOW_FAIL) == 0;
}
static bool compress_start(struct i915_vma_compress *c)
{
return true;
}
static int compress_page(struct i915_vma_compress *c,
void *src,
struct i915_vma_coredump *dst,
bool wc)
{
void *ptr;
ptr = pool_alloc(&c->pool, ALLOW_FAIL);
if (!ptr)
return -ENOMEM;
if (!(wc && i915_memcpy_from_wc(ptr, src, PAGE_SIZE)))
memcpy(ptr, src, PAGE_SIZE);
list_add_tail(&virt_to_page(ptr)->lru, &dst->page_list);
cond_resched();
return 0;
}
static int compress_flush(struct i915_vma_compress *c,
struct i915_vma_coredump *dst)
{
return 0;
}
static void compress_finish(struct i915_vma_compress *c)
{
}
static void compress_fini(struct i915_vma_compress *c)
{
pool_fini(&c->pool);
}
static void err_compression_marker(struct drm_i915_error_state_buf *m)
{
err_puts(m, "~");
}
#endif
static void error_print_instdone(struct drm_i915_error_state_buf *m,
const struct intel_engine_coredump *ee)
{
int slice;
int subslice;
int iter;
err_printf(m, " INSTDONE: 0x%08x\n",
ee->instdone.instdone);
if (ee->engine->class != RENDER_CLASS || GRAPHICS_VER(m->i915) <= 3)
return;
err_printf(m, " SC_INSTDONE: 0x%08x\n",
ee->instdone.slice_common);
if (GRAPHICS_VER(m->i915) <= 6)
return;
for_each_ss_steering(iter, ee->engine->gt, slice, subslice)
err_printf(m, " SAMPLER_INSTDONE[%d][%d]: 0x%08x\n",
slice, subslice,
ee->instdone.sampler[slice][subslice]);
for_each_ss_steering(iter, ee->engine->gt, slice, subslice)
err_printf(m, " ROW_INSTDONE[%d][%d]: 0x%08x\n",
slice, subslice,
ee->instdone.row[slice][subslice]);
if (GRAPHICS_VER(m->i915) < 12)
return;
if (GRAPHICS_VER_FULL(m->i915) >= IP_VER(12, 55)) {
for_each_ss_steering(iter, ee->engine->gt, slice, subslice)
err_printf(m, " GEOM_SVGUNIT_INSTDONE[%d][%d]: 0x%08x\n",
slice, subslice,
ee->instdone.geom_svg[slice][subslice]);
}
err_printf(m, " SC_INSTDONE_EXTRA: 0x%08x\n",
ee->instdone.slice_common_extra[0]);
err_printf(m, " SC_INSTDONE_EXTRA2: 0x%08x\n",
ee->instdone.slice_common_extra[1]);
}
static void error_print_request(struct drm_i915_error_state_buf *m,
const char *prefix,
const struct i915_request_coredump *erq)
{
if (!erq->seqno)
return;
err_printf(m, "%s pid %d, seqno %8x:%08x%s%s, prio %d, head %08x, tail %08x\n",
prefix, erq->pid, erq->context, erq->seqno,
test_bit(DMA_FENCE_FLAG_SIGNALED_BIT,
&erq->flags) ? "!" : "",
test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
&erq->flags) ? "+" : "",
erq->sched_attr.priority,
erq->head, erq->tail);
}
static void error_print_context(struct drm_i915_error_state_buf *m,
const char *header,
const struct i915_gem_context_coredump *ctx)
{
err_printf(m, "%s%s[%d] prio %d, guilty %d active %d, runtime total %lluns, avg %lluns\n",
header, ctx->comm, ctx->pid, ctx->sched_attr.priority,
ctx->guilty, ctx->active,
ctx->total_runtime, ctx->avg_runtime);
err_printf(m, " context timeline seqno %u\n", ctx->hwsp_seqno);
}
static struct i915_vma_coredump *
__find_vma(struct i915_vma_coredump *vma, const char *name)
{
while (vma) {
if (strcmp(vma->name, name) == 0)
return vma;
vma = vma->next;
}
return NULL;
}
struct i915_vma_coredump *
intel_gpu_error_find_batch(const struct intel_engine_coredump *ee)
{
return __find_vma(ee->vma, "batch");
}
static void error_print_engine(struct drm_i915_error_state_buf *m,
const struct intel_engine_coredump *ee)
{
struct i915_vma_coredump *batch;
int n;
err_printf(m, "%s command stream:\n", ee->engine->name);
err_printf(m, " CCID: 0x%08x\n", ee->ccid);
err_printf(m, " START: 0x%08x\n", ee->start);
err_printf(m, " HEAD: 0x%08x [0x%08x]\n", ee->head, ee->rq_head);
err_printf(m, " TAIL: 0x%08x [0x%08x, 0x%08x]\n",
ee->tail, ee->rq_post, ee->rq_tail);
err_printf(m, " CTL: 0x%08x\n", ee->ctl);
err_printf(m, " MODE: 0x%08x\n", ee->mode);
err_printf(m, " HWS: 0x%08x\n", ee->hws);
err_printf(m, " ACTHD: 0x%08x %08x\n",
(u32)(ee->acthd>>32), (u32)ee->acthd);
err_printf(m, " IPEIR: 0x%08x\n", ee->ipeir);
err_printf(m, " IPEHR: 0x%08x\n", ee->ipehr);
err_printf(m, " ESR: 0x%08x\n", ee->esr);
error_print_instdone(m, ee);
batch = intel_gpu_error_find_batch(ee);
if (batch) {
u64 start = batch->gtt_offset;
u64 end = start + batch->gtt_size;
err_printf(m, " batch: [0x%08x_%08x, 0x%08x_%08x]\n",
upper_32_bits(start), lower_32_bits(start),
upper_32_bits(end), lower_32_bits(end));
}
if (GRAPHICS_VER(m->i915) >= 4) {
err_printf(m, " BBADDR: 0x%08x_%08x\n",
(u32)(ee->bbaddr>>32), (u32)ee->bbaddr);
err_printf(m, " BB_STATE: 0x%08x\n", ee->bbstate);
err_printf(m, " INSTPS: 0x%08x\n", ee->instps);
}
err_printf(m, " INSTPM: 0x%08x\n", ee->instpm);
err_printf(m, " FADDR: 0x%08x %08x\n", upper_32_bits(ee->faddr),
lower_32_bits(ee->faddr));
if (GRAPHICS_VER(m->i915) >= 6) {
err_printf(m, " RC PSMI: 0x%08x\n", ee->rc_psmi);
err_printf(m, " FAULT_REG: 0x%08x\n", ee->fault_reg);
}
if (GRAPHICS_VER(m->i915) >= 11) {
err_printf(m, " NOPID: 0x%08x\n", ee->nopid);
err_printf(m, " EXCC: 0x%08x\n", ee->excc);
err_printf(m, " CMD_CCTL: 0x%08x\n", ee->cmd_cctl);
err_printf(m, " CSCMDOP: 0x%08x\n", ee->cscmdop);
err_printf(m, " CTX_SR_CTL: 0x%08x\n", ee->ctx_sr_ctl);
err_printf(m, " DMA_FADDR_HI: 0x%08x\n", ee->dma_faddr_hi);
err_printf(m, " DMA_FADDR_LO: 0x%08x\n", ee->dma_faddr_lo);
}
if (HAS_PPGTT(m->i915)) {
err_printf(m, " GFX_MODE: 0x%08x\n", ee->vm_info.gfx_mode);
if (GRAPHICS_VER(m->i915) >= 8) {
int i;
for (i = 0; i < 4; i++)
err_printf(m, " PDP%d: 0x%016llx\n",
i, ee->vm_info.pdp[i]);
} else {
err_printf(m, " PP_DIR_BASE: 0x%08x\n",
ee->vm_info.pp_dir_base);
}
}
for (n = 0; n < ee->num_ports; n++) {
err_printf(m, " ELSP[%d]:", n);
error_print_request(m, " ", &ee->execlist[n]);
}
}
void i915_error_printf(struct drm_i915_error_state_buf *e, const char *f, ...)
{
va_list args;
va_start(args, f);
i915_error_vprintf(e, f, args);
va_end(args);
}
void intel_gpu_error_print_vma(struct drm_i915_error_state_buf *m,
const struct intel_engine_cs *engine,
const struct i915_vma_coredump *vma)
{
char out[ASCII85_BUFSZ];
struct page *page;
if (!vma)
return;
err_printf(m, "%s --- %s = 0x%08x %08x\n",
engine ? engine->name : "global", vma->name,
upper_32_bits(vma->gtt_offset),
lower_32_bits(vma->gtt_offset));
if (vma->gtt_page_sizes > I915_GTT_PAGE_SIZE_4K)
err_printf(m, "gtt_page_sizes = 0x%08x\n", vma->gtt_page_sizes);
err_compression_marker(m);
list_for_each_entry(page, &vma->page_list, lru) {
int i, len;
const u32 *addr = page_address(page);
len = PAGE_SIZE;
if (page == list_last_entry(&vma->page_list, typeof(*page), lru))
len -= vma->unused;
len = ascii85_encode_len(len);
for (i = 0; i < len; i++)
err_puts(m, ascii85_encode(addr[i], out));
}
err_puts(m, "\n");
}
static void err_print_capabilities(struct drm_i915_error_state_buf *m,
struct i915_gpu_coredump *error)
{
struct drm_printer p = i915_error_printer(m);
intel_device_info_print(&error->device_info, &error->runtime_info, &p);
intel_display_device_info_print(&error->display_device_info,
&error->display_runtime_info, &p);
intel_driver_caps_print(&error->driver_caps, &p);
}
static void err_print_params(struct drm_i915_error_state_buf *m,
const struct i915_params *params)
{
struct drm_printer p = i915_error_printer(m);
i915_params_dump(params, &p);
}
static void err_print_pciid(struct drm_i915_error_state_buf *m,
struct drm_i915_private *i915)
{
struct pci_dev *pdev = to_pci_dev(i915->drm.dev);
err_printf(m, "PCI ID: 0x%04x\n", pdev->device);
err_printf(m, "PCI Revision: 0x%02x\n", pdev->revision);
err_printf(m, "PCI Subsystem: %04x:%04x\n",
pdev->subsystem_vendor,
pdev->subsystem_device);
}
static void err_print_guc_ctb(struct drm_i915_error_state_buf *m,
const char *name,
const struct intel_ctb_coredump *ctb)
{
if (!ctb->size)
return;
err_printf(m, "GuC %s CTB: raw: 0x%08X, 0x%08X/%08X, cached: 0x%08X/%08X, desc = 0x%08X, buf = 0x%08X x 0x%08X\n",
name, ctb->raw_status, ctb->raw_head, ctb->raw_tail,
ctb->head, ctb->tail, ctb->desc_offset, ctb->cmds_offset, ctb->size);
}
static void err_print_uc(struct drm_i915_error_state_buf *m,
const struct intel_uc_coredump *error_uc)
{
struct drm_printer p = i915_error_printer(m);
intel_uc_fw_dump(&error_uc->guc_fw, &p);
intel_uc_fw_dump(&error_uc->huc_fw, &p);
err_printf(m, "GuC timestamp: 0x%08x\n", error_uc->guc.timestamp);
intel_gpu_error_print_vma(m, NULL, error_uc->guc.vma_log);
err_printf(m, "GuC CTB fence: %d\n", error_uc->guc.last_fence);
err_print_guc_ctb(m, "Send", error_uc->guc.ctb + 0);
err_print_guc_ctb(m, "Recv", error_uc->guc.ctb + 1);
intel_gpu_error_print_vma(m, NULL, error_uc->guc.vma_ctb);
}
static void err_free_sgl(struct scatterlist *sgl)
{
while (sgl) {
struct scatterlist *sg;
for (sg = sgl; !sg_is_chain(sg); sg++) {
kfree(sg_virt(sg));
if (sg_is_last(sg))
break;
}
sg = sg_is_last(sg) ? NULL : sg_chain_ptr(sg);
free_page((unsigned long)sgl);
sgl = sg;
}
}
static void err_print_gt_info(struct drm_i915_error_state_buf *m,
struct intel_gt_coredump *gt)
{
struct drm_printer p = i915_error_printer(m);
intel_gt_info_print(>->info, &p);
intel_sseu_print_topology(gt->_gt->i915, >->info.sseu, &p);
}
static void err_print_gt_display(struct drm_i915_error_state_buf *m,
struct intel_gt_coredump *gt)
{
err_printf(m, "IER: 0x%08x\n", gt->ier);
err_printf(m, "DERRMR: 0x%08x\n", gt->derrmr);
}
static void err_print_gt_global_nonguc(struct drm_i915_error_state_buf *m,
struct intel_gt_coredump *gt)
{
int i;
err_printf(m, "GT awake: %s\n", str_yes_no(gt->awake));
err_printf(m, "CS timestamp frequency: %u Hz, %d ns\n",
gt->clock_frequency, gt->clock_period_ns);
err_printf(m, "EIR: 0x%08x\n", gt->eir);
err_printf(m, "PGTBL_ER: 0x%08x\n", gt->pgtbl_er);
for (i = 0; i < gt->ngtier; i++)
err_printf(m, "GTIER[%d]: 0x%08x\n", i, gt->gtier[i]);
}
static void err_print_gt_global(struct drm_i915_error_state_buf *m,
struct intel_gt_coredump *gt)
{
err_printf(m, "FORCEWAKE: 0x%08x\n", gt->forcewake);
if (IS_GRAPHICS_VER(m->i915, 6, 11)) {
err_printf(m, "ERROR: 0x%08x\n", gt->error);
err_printf(m, "DONE_REG: 0x%08x\n", gt->done_reg);
}
if (GRAPHICS_VER(m->i915) >= 8)
err_printf(m, "FAULT_TLB_DATA: 0x%08x 0x%08x\n",
gt->fault_data1, gt->fault_data0);
if (GRAPHICS_VER(m->i915) == 7)
err_printf(m, "ERR_INT: 0x%08x\n", gt->err_int);
if (IS_GRAPHICS_VER(m->i915, 8, 11))
err_printf(m, "GTT_CACHE_EN: 0x%08x\n", gt->gtt_cache);
if (GRAPHICS_VER(m->i915) == 12)
err_printf(m, "AUX_ERR_DBG: 0x%08x\n", gt->aux_err);
if (GRAPHICS_VER(m->i915) >= 12) {
int i;
for (i = 0; i < I915_MAX_SFC; i++) {
/*
* SFC_DONE resides in the VD forcewake domain, so it
* only exists if the corresponding VCS engine is
* present.
*/
if ((gt->_gt->info.sfc_mask & BIT(i)) == 0 ||
!HAS_ENGINE(gt->_gt, _VCS(i * 2)))
continue;
err_printf(m, " SFC_DONE[%d]: 0x%08x\n", i,
gt->sfc_done[i]);
}
err_printf(m, " GAM_DONE: 0x%08x\n", gt->gam_done);
}
}
static void err_print_gt_fences(struct drm_i915_error_state_buf *m,
struct intel_gt_coredump *gt)
{
int i;
for (i = 0; i < gt->nfence; i++)
err_printf(m, " fence[%d] = %08llx\n", i, gt->fence[i]);
}
static void err_print_gt_engines(struct drm_i915_error_state_buf *m,
struct intel_gt_coredump *gt)
{
const struct intel_engine_coredump *ee;
for (ee = gt->engine; ee; ee = ee->next) {
const struct i915_vma_coredump *vma;
if (gt->uc && gt->uc->guc.is_guc_capture) {
if (ee->guc_capture_node)
intel_guc_capture_print_engine_node(m, ee);
else
err_printf(m, " Missing GuC capture node for %s\n",
ee->engine->name);
} else {
error_print_engine(m, ee);
}
err_printf(m, " hung: %u\n", ee->hung);
err_printf(m, " engine reset count: %u\n", ee->reset_count);
error_print_context(m, " Active context: ", &ee->context);
for (vma = ee->vma; vma; vma = vma->next)
intel_gpu_error_print_vma(m, ee->engine, vma);
}
}
static void __err_print_to_sgl(struct drm_i915_error_state_buf *m,
struct i915_gpu_coredump *error)
{
const struct intel_engine_coredump *ee;
struct timespec64 ts;
if (*error->error_msg)
err_printf(m, "%s\n", error->error_msg);
err_printf(m, "Kernel: %s %s\n",
init_utsname()->release,
init_utsname()->machine);
err_printf(m, "Driver: %s\n", DRIVER_DATE);
ts = ktime_to_timespec64(error->time);
err_printf(m, "Time: %lld s %ld us\n",
(s64)ts.tv_sec, ts.tv_nsec / NSEC_PER_USEC);
ts = ktime_to_timespec64(error->boottime);
err_printf(m, "Boottime: %lld s %ld us\n",
(s64)ts.tv_sec, ts.tv_nsec / NSEC_PER_USEC);
ts = ktime_to_timespec64(error->uptime);
err_printf(m, "Uptime: %lld s %ld us\n",
(s64)ts.tv_sec, ts.tv_nsec / NSEC_PER_USEC);
err_printf(m, "Capture: %lu jiffies; %d ms ago\n",
error->capture, jiffies_to_msecs(jiffies - error->capture));
for (ee = error->gt ? error->gt->engine : NULL; ee; ee = ee->next)
err_printf(m, "Active process (on ring %s): %s [%d]\n",
ee->engine->name,
ee->context.comm,
ee->context.pid);
err_printf(m, "Reset count: %u\n", error->reset_count);
err_printf(m, "Suspend count: %u\n", error->suspend_count);
err_printf(m, "Platform: %s\n", intel_platform_name(error->device_info.platform));
err_printf(m, "Subplatform: 0x%x\n",
intel_subplatform(&error->runtime_info,
error->device_info.platform));
err_print_pciid(m, m->i915);
err_printf(m, "IOMMU enabled?: %d\n", error->iommu);
intel_dmc_print_error_state(m, m->i915);
err_printf(m, "RPM wakelock: %s\n", str_yes_no(error->wakelock));
err_printf(m, "PM suspended: %s\n", str_yes_no(error->suspended));
if (error->gt) {
bool print_guc_capture = false;
if (error->gt->uc && error->gt->uc->guc.is_guc_capture)
print_guc_capture = true;
err_print_gt_display(m, error->gt);
err_print_gt_global_nonguc(m, error->gt);
err_print_gt_fences(m, error->gt);
/*
* GuC dumped global, eng-class and eng-instance registers together
* as part of engine state dump so we print in err_print_gt_engines
*/
if (!print_guc_capture)
err_print_gt_global(m, error->gt);
err_print_gt_engines(m, error->gt);
if (error->gt->uc)
err_print_uc(m, error->gt->uc);
err_print_gt_info(m, error->gt);
}
if (error->overlay)
intel_overlay_print_error_state(m, error->overlay);
err_print_capabilities(m, error);
err_print_params(m, &error->params);
}
static int err_print_to_sgl(struct i915_gpu_coredump *error)
{
struct drm_i915_error_state_buf m;
if (IS_ERR(error))
return PTR_ERR(error);
if (READ_ONCE(error->sgl))
return 0;
memset(&m, 0, sizeof(m));
m.i915 = error->i915;
__err_print_to_sgl(&m, error);
if (m.buf) {
__sg_set_buf(m.cur++, m.buf, m.bytes, m.iter);
m.bytes = 0;
m.buf = NULL;
}
if (m.cur) {
GEM_BUG_ON(m.end < m.cur);
sg_mark_end(m.cur - 1);
}
GEM_BUG_ON(m.sgl && !m.cur);
if (m.err) {
err_free_sgl(m.sgl);
return m.err;
}
if (cmpxchg(&error->sgl, NULL, m.sgl))
err_free_sgl(m.sgl);
return 0;
}
ssize_t i915_gpu_coredump_copy_to_buffer(struct i915_gpu_coredump *error,
char *buf, loff_t off, size_t rem)
{
struct scatterlist *sg;
size_t count;
loff_t pos;
int err;
if (!error || !rem)
return 0;
err = err_print_to_sgl(error);
if (err)
return err;
sg = READ_ONCE(error->fit);
if (!sg || off < sg->dma_address)
sg = error->sgl;
if (!sg)
return 0;
pos = sg->dma_address;
count = 0;
do {
size_t len, start;
if (sg_is_chain(sg)) {
sg = sg_chain_ptr(sg);
GEM_BUG_ON(sg_is_chain(sg));
}
len = sg->length;
if (pos + len <= off) {
pos += len;
continue;
}
start = sg->offset;
if (pos < off) {
GEM_BUG_ON(off - pos > len);
len -= off - pos;
start += off - pos;
pos = off;
}
len = min(len, rem);
GEM_BUG_ON(!len || len > sg->length);
memcpy(buf, page_address(sg_page(sg)) + start, len);
count += len;
pos += len;
buf += len;
rem -= len;
if (!rem) {
WRITE_ONCE(error->fit, sg);
break;
}
} while (!sg_is_last(sg++));
return count;
}
static void i915_vma_coredump_free(struct i915_vma_coredump *vma)
{
while (vma) {
struct i915_vma_coredump *next = vma->next;
struct page *page, *n;
list_for_each_entry_safe(page, n, &vma->page_list, lru) {
list_del_init(&page->lru);
__free_page(page);
}
kfree(vma);
vma = next;
}
}
static void cleanup_params(struct i915_gpu_coredump *error)
{
i915_params_free(&error->params);
}
static void cleanup_uc(struct intel_uc_coredump *uc)
{
kfree(uc->guc_fw.file_selected.path);
kfree(uc->huc_fw.file_selected.path);
kfree(uc->guc_fw.file_wanted.path);
kfree(uc->huc_fw.file_wanted.path);
i915_vma_coredump_free(uc->guc.vma_log);
i915_vma_coredump_free(uc->guc.vma_ctb);
kfree(uc);
}
static void cleanup_gt(struct intel_gt_coredump *gt)
{
while (gt->engine) {
struct intel_engine_coredump *ee = gt->engine;
gt->engine = ee->next;
i915_vma_coredump_free(ee->vma);
intel_guc_capture_free_node(ee);
kfree(ee);
}
if (gt->uc)
cleanup_uc(gt->uc);
kfree(gt);
}
void __i915_gpu_coredump_free(struct kref *error_ref)
{
struct i915_gpu_coredump *error =
container_of(error_ref, typeof(*error), ref);
while (error->gt) {
struct intel_gt_coredump *gt = error->gt;
error->gt = gt->next;
cleanup_gt(gt);
}
kfree(error->overlay);
cleanup_params(error);
err_free_sgl(error->sgl);
kfree(error);
}
static struct i915_vma_coredump *
i915_vma_coredump_create(const struct intel_gt *gt,
const struct i915_vma_resource *vma_res,
struct i915_vma_compress *compress,
const char *name)
{
struct i915_ggtt *ggtt = gt->ggtt;
const u64 slot = ggtt->error_capture.start;
struct i915_vma_coredump *dst;
struct sgt_iter iter;
int ret;
might_sleep();
if (!vma_res || !vma_res->bi.pages || !compress)
return NULL;
dst = kmalloc(sizeof(*dst), ALLOW_FAIL);
if (!dst)
return NULL;
if (!compress_start(compress)) {
kfree(dst);
return NULL;
}
INIT_LIST_HEAD(&dst->page_list);
strcpy(dst->name, name);
dst->next = NULL;
dst->gtt_offset = vma_res->start;
dst->gtt_size = vma_res->node_size;
dst->gtt_page_sizes = vma_res->page_sizes_gtt;
dst->unused = 0;
ret = -EINVAL;
if (drm_mm_node_allocated(&ggtt->error_capture)) {
void __iomem *s;
dma_addr_t dma;
for_each_sgt_daddr(dma, iter, vma_res->bi.pages) {
mutex_lock(&ggtt->error_mutex);
if (ggtt->vm.raw_insert_page)
ggtt->vm.raw_insert_page(&ggtt->vm, dma, slot,
i915_gem_get_pat_index(gt->i915,
I915_CACHE_NONE),
0);
else
ggtt->vm.insert_page(&ggtt->vm, dma, slot,
i915_gem_get_pat_index(gt->i915,
I915_CACHE_NONE),
0);
mb();
s = io_mapping_map_wc(&ggtt->iomap, slot, PAGE_SIZE);
ret = compress_page(compress,
(void __force *)s, dst,
true);
io_mapping_unmap(s);
mb();
ggtt->vm.clear_range(&ggtt->vm, slot, PAGE_SIZE);
mutex_unlock(&ggtt->error_mutex);
if (ret)
break;
}
} else if (vma_res->bi.lmem) {
struct intel_memory_region *mem = vma_res->mr;
dma_addr_t dma;
for_each_sgt_daddr(dma, iter, vma_res->bi.pages) {
dma_addr_t offset = dma - mem->region.start;
void __iomem *s;
if (offset + PAGE_SIZE > mem->io_size) {
ret = -EINVAL;
break;
}
s = io_mapping_map_wc(&mem->iomap, offset, PAGE_SIZE);
ret = compress_page(compress,
(void __force *)s, dst,
true);
io_mapping_unmap(s);
if (ret)
break;
}
} else {
struct page *page;
for_each_sgt_page(page, iter, vma_res->bi.pages) {
void *s;
drm_clflush_pages(&page, 1);
s = kmap_local_page(page);
ret = compress_page(compress, s, dst, false);
kunmap_local(s);
drm_clflush_pages(&page, 1);
if (ret)
break;
}
}
if (ret || compress_flush(compress, dst)) {
struct page *page, *n;
list_for_each_entry_safe_reverse(page, n, &dst->page_list, lru) {
list_del_init(&page->lru);
pool_free(&compress->pool, page_address(page));
}
kfree(dst);
dst = NULL;
}
compress_finish(compress);
return dst;
}
static void gt_record_fences(struct intel_gt_coredump *gt)
{
struct i915_ggtt *ggtt = gt->_gt->ggtt;
struct intel_uncore *uncore = gt->_gt->uncore;
int i;
if (GRAPHICS_VER(uncore->i915) >= 6) {
for (i = 0; i < ggtt->num_fences; i++)
gt->fence[i] =
intel_uncore_read64(uncore,
FENCE_REG_GEN6_LO(i));
} else if (GRAPHICS_VER(uncore->i915) >= 4) {
for (i = 0; i < ggtt->num_fences; i++)
gt->fence[i] =
intel_uncore_read64(uncore,
FENCE_REG_965_LO(i));
} else {
for (i = 0; i < ggtt->num_fences; i++)
gt->fence[i] =
intel_uncore_read(uncore, FENCE_REG(i));
}
gt->nfence = i;
}
static void engine_record_registers(struct intel_engine_coredump *ee)
{
const struct intel_engine_cs *engine = ee->engine;
struct drm_i915_private *i915 = engine->i915;
if (GRAPHICS_VER(i915) >= 6) {
ee->rc_psmi = ENGINE_READ(engine, RING_PSMI_CTL);
if (GRAPHICS_VER_FULL(i915) >= IP_VER(12, 50))
ee->fault_reg = intel_gt_mcr_read_any(engine->gt,
XEHP_RING_FAULT_REG);
else if (GRAPHICS_VER(i915) >= 12)
ee->fault_reg = intel_uncore_read(engine->uncore,
GEN12_RING_FAULT_REG);
else if (GRAPHICS_VER(i915) >= 8)
ee->fault_reg = intel_uncore_read(engine->uncore,
GEN8_RING_FAULT_REG);
else
ee->fault_reg = GEN6_RING_FAULT_REG_READ(engine);
}
if (GRAPHICS_VER(i915) >= 4) {
ee->esr = ENGINE_READ(engine, RING_ESR);
ee->faddr = ENGINE_READ(engine, RING_DMA_FADD);
ee->ipeir = ENGINE_READ(engine, RING_IPEIR);
ee->ipehr = ENGINE_READ(engine, RING_IPEHR);
ee->instps = ENGINE_READ(engine, RING_INSTPS);
ee->bbaddr = ENGINE_READ(engine, RING_BBADDR);
ee->ccid = ENGINE_READ(engine, CCID);
if (GRAPHICS_VER(i915) >= 8) {
ee->faddr |= (u64)ENGINE_READ(engine, RING_DMA_FADD_UDW) << 32;
ee->bbaddr |= (u64)ENGINE_READ(engine, RING_BBADDR_UDW) << 32;
}
ee->bbstate = ENGINE_READ(engine, RING_BBSTATE);
} else {
ee->faddr = ENGINE_READ(engine, DMA_FADD_I8XX);
ee->ipeir = ENGINE_READ(engine, IPEIR);
ee->ipehr = ENGINE_READ(engine, IPEHR);
}
if (GRAPHICS_VER(i915) >= 11) {
ee->cmd_cctl = ENGINE_READ(engine, RING_CMD_CCTL);
ee->cscmdop = ENGINE_READ(engine, RING_CSCMDOP);
ee->ctx_sr_ctl = ENGINE_READ(engine, RING_CTX_SR_CTL);
ee->dma_faddr_hi = ENGINE_READ(engine, RING_DMA_FADD_UDW);
ee->dma_faddr_lo = ENGINE_READ(engine, RING_DMA_FADD);
ee->nopid = ENGINE_READ(engine, RING_NOPID);
ee->excc = ENGINE_READ(engine, RING_EXCC);
}
intel_engine_get_instdone(engine, &ee->instdone);
ee->instpm = ENGINE_READ(engine, RING_INSTPM);
ee->acthd = intel_engine_get_active_head(engine);
ee->start = ENGINE_READ(engine, RING_START);
ee->head = ENGINE_READ(engine, RING_HEAD);
ee->tail = ENGINE_READ(engine, RING_TAIL);
ee->ctl = ENGINE_READ(engine, RING_CTL);
if (GRAPHICS_VER(i915) > 2)
ee->mode = ENGINE_READ(engine, RING_MI_MODE);
if (!HWS_NEEDS_PHYSICAL(i915)) {
i915_reg_t mmio;
if (GRAPHICS_VER(i915) == 7) {
switch (engine->id) {
default:
MISSING_CASE(engine->id);
fallthrough;
case RCS0:
mmio = RENDER_HWS_PGA_GEN7;
break;
case BCS0:
mmio = BLT_HWS_PGA_GEN7;
break;
case VCS0:
mmio = BSD_HWS_PGA_GEN7;
break;
case VECS0:
mmio = VEBOX_HWS_PGA_GEN7;
break;
}
} else if (GRAPHICS_VER(engine->i915) == 6) {
mmio = RING_HWS_PGA_GEN6(engine->mmio_base);
} else {
/* XXX: gen8 returns to sanity */
mmio = RING_HWS_PGA(engine->mmio_base);
}
ee->hws = intel_uncore_read(engine->uncore, mmio);
}
ee->reset_count = i915_reset_engine_count(&i915->gpu_error, engine);
if (HAS_PPGTT(i915)) {
int i;
ee->vm_info.gfx_mode = ENGINE_READ(engine, RING_MODE_GEN7);
if (GRAPHICS_VER(i915) == 6) {
ee->vm_info.pp_dir_base =
ENGINE_READ(engine, RING_PP_DIR_BASE_READ);
} else if (GRAPHICS_VER(i915) == 7) {
ee->vm_info.pp_dir_base =
ENGINE_READ(engine, RING_PP_DIR_BASE);
} else if (GRAPHICS_VER(i915) >= 8) {
u32 base = engine->mmio_base;
for (i = 0; i < 4; i++) {
ee->vm_info.pdp[i] =
intel_uncore_read(engine->uncore,
GEN8_RING_PDP_UDW(base, i));
ee->vm_info.pdp[i] <<= 32;
ee->vm_info.pdp[i] |=
intel_uncore_read(engine->uncore,
GEN8_RING_PDP_LDW(base, i));
}
}
}
}
static void record_request(const struct i915_request *request,
struct i915_request_coredump *erq)
{
erq->flags = request->fence.flags;
erq->context = request->fence.context;
erq->seqno = request->fence.seqno;
erq->sched_attr = request->sched.attr;
erq->head = request->head;
erq->tail = request->tail;
erq->pid = 0;
rcu_read_lock();
if (!intel_context_is_closed(request->context)) {
const struct i915_gem_context *ctx;
ctx = rcu_dereference(request->context->gem_context);
if (ctx)
erq->pid = pid_nr(ctx->pid);
}
rcu_read_unlock();
}
static void engine_record_execlists(struct intel_engine_coredump *ee)
{
const struct intel_engine_execlists * const el = &ee->engine->execlists;
struct i915_request * const *port = el->active;
unsigned int n = 0;
while (*port)
record_request(*port++, &ee->execlist[n++]);
ee->num_ports = n;
}
static bool record_context(struct i915_gem_context_coredump *e,
struct intel_context *ce)
{
struct i915_gem_context *ctx;
struct task_struct *task;
bool simulated;
rcu_read_lock();
ctx = rcu_dereference(ce->gem_context);
if (ctx && !kref_get_unless_zero(&ctx->ref))
ctx = NULL;
rcu_read_unlock();
if (!ctx)
return true;
rcu_read_lock();
task = pid_task(ctx->pid, PIDTYPE_PID);
if (task) {
strcpy(e->comm, task->comm);
e->pid = task->pid;
}
rcu_read_unlock();
e->sched_attr = ctx->sched;
e->guilty = atomic_read(&ctx->guilty_count);
e->active = atomic_read(&ctx->active_count);
e->hwsp_seqno = (ce->timeline && ce->timeline->hwsp_seqno) ?
*ce->timeline->hwsp_seqno : ~0U;
e->total_runtime = intel_context_get_total_runtime_ns(ce);
e->avg_runtime = intel_context_get_avg_runtime_ns(ce);
simulated = i915_gem_context_no_error_capture(ctx);
i915_gem_context_put(ctx);
return simulated;
}
struct intel_engine_capture_vma {
struct intel_engine_capture_vma *next;
struct i915_vma_resource *vma_res;
char name[16];
bool lockdep_cookie;
};
static struct intel_engine_capture_vma *
capture_vma_snapshot(struct intel_engine_capture_vma *next,
struct i915_vma_resource *vma_res,
gfp_t gfp, const char *name)
{
struct intel_engine_capture_vma *c;
if (!vma_res)
return next;
c = kmalloc(sizeof(*c), gfp);
if (!c)
return next;
if (!i915_vma_resource_hold(vma_res, &c->lockdep_cookie)) {
kfree(c);
return next;
}
strcpy(c->name, name);
c->vma_res = i915_vma_resource_get(vma_res);
c->next = next;
return c;
}
static struct intel_engine_capture_vma *
capture_vma(struct intel_engine_capture_vma *next,
struct i915_vma *vma,
const char *name,
gfp_t gfp)
{
if (!vma)
return next;
/*
* If the vma isn't pinned, then the vma should be snapshotted
* to a struct i915_vma_snapshot at command submission time.
* Not here.
*/
if (GEM_WARN_ON(!i915_vma_is_pinned(vma)))
return next;
next = capture_vma_snapshot(next, vma->resource, gfp, name);
return next;
}
static struct intel_engine_capture_vma *
capture_user(struct intel_engine_capture_vma *capture,
const struct i915_request *rq,
gfp_t gfp)
{
struct i915_capture_list *c;
for (c = rq->capture_list; c; c = c->next)
capture = capture_vma_snapshot(capture, c->vma_res, gfp,
"user");
return capture;
}
static void add_vma(struct intel_engine_coredump *ee,
struct i915_vma_coredump *vma)
{
if (vma) {
vma->next = ee->vma;
ee->vma = vma;
}
}
static struct i915_vma_coredump *
create_vma_coredump(const struct intel_gt *gt, struct i915_vma *vma,
const char *name, struct i915_vma_compress *compress)
{
struct i915_vma_coredump *ret = NULL;
struct i915_vma_resource *vma_res;
bool lockdep_cookie;
if (!vma)
return NULL;
vma_res = vma->resource;
if (i915_vma_resource_hold(vma_res, &lockdep_cookie)) {
ret = i915_vma_coredump_create(gt, vma_res, compress, name);
i915_vma_resource_unhold(vma_res, lockdep_cookie);
}
return ret;
}
static void add_vma_coredump(struct intel_engine_coredump *ee,
const struct intel_gt *gt,
struct i915_vma *vma,
const char *name,
struct i915_vma_compress *compress)
{
add_vma(ee, create_vma_coredump(gt, vma, name, compress));
}
struct intel_engine_coredump *
intel_engine_coredump_alloc(struct intel_engine_cs *engine, gfp_t gfp, u32 dump_flags)
{
struct intel_engine_coredump *ee;
ee = kzalloc(sizeof(*ee), gfp);
if (!ee)
return NULL;
ee->engine = engine;
if (!(dump_flags & CORE_DUMP_FLAG_IS_GUC_CAPTURE)) {
engine_record_registers(ee);
engine_record_execlists(ee);
}
return ee;
}
static struct intel_engine_capture_vma *
engine_coredump_add_context(struct intel_engine_coredump *ee,
struct intel_context *ce,
gfp_t gfp)
{
struct intel_engine_capture_vma *vma = NULL;
ee->simulated |= record_context(&ee->context, ce);
if (ee->simulated)
return NULL;
/*
* We need to copy these to an anonymous buffer
* as the simplest method to avoid being overwritten
* by userspace.
*/
vma = capture_vma(vma, ce->ring->vma, "ring", gfp);
vma = capture_vma(vma, ce->state, "HW context", gfp);
return vma;
}
struct intel_engine_capture_vma *
intel_engine_coredump_add_request(struct intel_engine_coredump *ee,
struct i915_request *rq,
gfp_t gfp)
{
struct intel_engine_capture_vma *vma;
vma = engine_coredump_add_context(ee, rq->context, gfp);
if (!vma)
return NULL;
/*
* We need to copy these to an anonymous buffer
* as the simplest method to avoid being overwritten
* by userspace.
*/
vma = capture_vma_snapshot(vma, rq->batch_res, gfp, "batch");
vma = capture_user(vma, rq, gfp);
ee->rq_head = rq->head;
ee->rq_post = rq->postfix;
ee->rq_tail = rq->tail;
return vma;
}
void
intel_engine_coredump_add_vma(struct intel_engine_coredump *ee,
struct intel_engine_capture_vma *capture,
struct i915_vma_compress *compress)
{
const struct intel_engine_cs *engine = ee->engine;
while (capture) {
struct intel_engine_capture_vma *this = capture;
struct i915_vma_resource *vma_res = this->vma_res;
add_vma(ee,
i915_vma_coredump_create(engine->gt, vma_res,
compress, this->name));
i915_vma_resource_unhold(vma_res, this->lockdep_cookie);
i915_vma_resource_put(vma_res);
capture = this->next;
kfree(this);
}
add_vma_coredump(ee, engine->gt, engine->status_page.vma,
"HW Status", compress);
add_vma_coredump(ee, engine->gt, engine->wa_ctx.vma,
"WA context", compress);
}
static struct intel_engine_coredump *
capture_engine(struct intel_engine_cs *engine,
struct i915_vma_compress *compress,
u32 dump_flags)
{
struct intel_engine_capture_vma *capture = NULL;
struct intel_engine_coredump *ee;
struct intel_context *ce = NULL;
struct i915_request *rq = NULL;
ee = intel_engine_coredump_alloc(engine, ALLOW_FAIL, dump_flags);
if (!ee)
return NULL;
intel_engine_get_hung_entity(engine, &ce, &rq);
if (rq && !i915_request_started(rq))
drm_info(&engine->gt->i915->drm, "Got hung context on %s with active request %lld:%lld [0x%04X] not yet started\n",
engine->name, rq->fence.context, rq->fence.seqno, ce->guc_id.id);
if (rq) {
capture = intel_engine_coredump_add_request(ee, rq, ATOMIC_MAYFAIL);
i915_request_put(rq);
} else if (ce) {
capture = engine_coredump_add_context(ee, ce, ATOMIC_MAYFAIL);
}
if (capture) {
intel_engine_coredump_add_vma(ee, capture, compress);
if (dump_flags & CORE_DUMP_FLAG_IS_GUC_CAPTURE)
intel_guc_capture_get_matching_node(engine->gt, ee, ce);
} else {
kfree(ee);
ee = NULL;
}
return ee;
}
static void
gt_record_engines(struct intel_gt_coredump *gt,
intel_engine_mask_t engine_mask,
struct i915_vma_compress *compress,
u32 dump_flags)
{
struct intel_engine_cs *engine;
enum intel_engine_id id;
for_each_engine(engine, gt->_gt, id) {
struct intel_engine_coredump *ee;
/* Refill our page pool before entering atomic section */
pool_refill(&compress->pool, ALLOW_FAIL);
ee = capture_engine(engine, compress, dump_flags);
if (!ee)
continue;
ee->hung = engine->mask & engine_mask;
gt->simulated |= ee->simulated;
if (ee->simulated) {
if (dump_flags & CORE_DUMP_FLAG_IS_GUC_CAPTURE)
intel_guc_capture_free_node(ee);
kfree(ee);
continue;
}
ee->next = gt->engine;
gt->engine = ee;
}
}
static void gt_record_guc_ctb(struct intel_ctb_coredump *saved,
const struct intel_guc_ct_buffer *ctb,
const void *blob_ptr, struct intel_guc *guc)
{
if (!ctb || !ctb->desc)
return;
saved->raw_status = ctb->desc->status;
saved->raw_head = ctb->desc->head;
saved->raw_tail = ctb->desc->tail;
saved->head = ctb->head;
saved->tail = ctb->tail;
saved->size = ctb->size;
saved->desc_offset = ((void *)ctb->desc) - blob_ptr;
saved->cmds_offset = ((void *)ctb->cmds) - blob_ptr;
}
static struct intel_uc_coredump *
gt_record_uc(struct intel_gt_coredump *gt,
struct i915_vma_compress *compress)
{
const struct intel_uc *uc = >->_gt->uc;
struct intel_uc_coredump *error_uc;
error_uc = kzalloc(sizeof(*error_uc), ALLOW_FAIL);
if (!error_uc)
return NULL;
memcpy(&error_uc->guc_fw, &uc->guc.fw, sizeof(uc->guc.fw));
memcpy(&error_uc->huc_fw, &uc->huc.fw, sizeof(uc->huc.fw));
error_uc->guc_fw.file_selected.path = kstrdup(uc->guc.fw.file_selected.path, ALLOW_FAIL);
error_uc->huc_fw.file_selected.path = kstrdup(uc->huc.fw.file_selected.path, ALLOW_FAIL);
error_uc->guc_fw.file_wanted.path = kstrdup(uc->guc.fw.file_wanted.path, ALLOW_FAIL);
error_uc->huc_fw.file_wanted.path = kstrdup(uc->huc.fw.file_wanted.path, ALLOW_FAIL);
/*
* Save the GuC log and include a timestamp reference for converting the
* log times to system times (in conjunction with the error->boottime and
* gt->clock_frequency fields saved elsewhere).
*/
error_uc->guc.timestamp = intel_uncore_read(gt->_gt->uncore, GUCPMTIMESTAMP);
error_uc->guc.vma_log = create_vma_coredump(gt->_gt, uc->guc.log.vma,
"GuC log buffer", compress);
error_uc->guc.vma_ctb = create_vma_coredump(gt->_gt, uc->guc.ct.vma,
"GuC CT buffer", compress);
error_uc->guc.last_fence = uc->guc.ct.requests.last_fence;
gt_record_guc_ctb(error_uc->guc.ctb + 0, &uc->guc.ct.ctbs.send,
uc->guc.ct.ctbs.send.desc, (struct intel_guc *)&uc->guc);
gt_record_guc_ctb(error_uc->guc.ctb + 1, &uc->guc.ct.ctbs.recv,
uc->guc.ct.ctbs.send.desc, (struct intel_guc *)&uc->guc);
return error_uc;
}
/* Capture display registers. */
static void gt_record_display_regs(struct intel_gt_coredump *gt)
{
struct intel_uncore *uncore = gt->_gt->uncore;
struct drm_i915_private *i915 = uncore->i915;
if (GRAPHICS_VER(i915) >= 6)
gt->derrmr = intel_uncore_read(uncore, DERRMR);
if (GRAPHICS_VER(i915) >= 8)
gt->ier = intel_uncore_read(uncore, GEN8_DE_MISC_IER);
else if (IS_VALLEYVIEW(i915))
gt->ier = intel_uncore_read(uncore, VLV_IER);
else if (HAS_PCH_SPLIT(i915))
gt->ier = intel_uncore_read(uncore, DEIER);
else if (GRAPHICS_VER(i915) == 2)
gt->ier = intel_uncore_read16(uncore, GEN2_IER);
else
gt->ier = intel_uncore_read(uncore, GEN2_IER);
}
/* Capture all other registers that GuC doesn't capture. */
static void gt_record_global_nonguc_regs(struct intel_gt_coredump *gt)
{
struct intel_uncore *uncore = gt->_gt->uncore;
struct drm_i915_private *i915 = uncore->i915;
int i;
if (IS_VALLEYVIEW(i915)) {
gt->gtier[0] = intel_uncore_read(uncore, GTIER);
gt->ngtier = 1;
} else if (GRAPHICS_VER(i915) >= 11) {
gt->gtier[0] =
intel_uncore_read(uncore,
GEN11_RENDER_COPY_INTR_ENABLE);
gt->gtier[1] =
intel_uncore_read(uncore, GEN11_VCS_VECS_INTR_ENABLE);
gt->gtier[2] =
intel_uncore_read(uncore, GEN11_GUC_SG_INTR_ENABLE);
gt->gtier[3] =
intel_uncore_read(uncore,
GEN11_GPM_WGBOXPERF_INTR_ENABLE);
gt->gtier[4] =
intel_uncore_read(uncore,
GEN11_CRYPTO_RSVD_INTR_ENABLE);
gt->gtier[5] =
intel_uncore_read(uncore,
GEN11_GUNIT_CSME_INTR_ENABLE);
gt->ngtier = 6;
} else if (GRAPHICS_VER(i915) >= 8) {
for (i = 0; i < 4; i++)
gt->gtier[i] =
intel_uncore_read(uncore, GEN8_GT_IER(i));
gt->ngtier = 4;
} else if (HAS_PCH_SPLIT(i915)) {
gt->gtier[0] = intel_uncore_read(uncore, GTIER);
gt->ngtier = 1;
}
gt->eir = intel_uncore_read(uncore, EIR);
gt->pgtbl_er = intel_uncore_read(uncore, PGTBL_ER);
}
/*
* Capture all registers that relate to workload submission.
* NOTE: In GuC submission, when GuC resets an engine, it can dump these for us
*/
static void gt_record_global_regs(struct intel_gt_coredump *gt)
{
struct intel_uncore *uncore = gt->_gt->uncore;
struct drm_i915_private *i915 = uncore->i915;
int i;
/*
* General organization
* 1. Registers specific to a single generation
* 2. Registers which belong to multiple generations
* 3. Feature specific registers.
* 4. Everything else
* Please try to follow the order.
*/
/* 1: Registers specific to a single generation */
if (IS_VALLEYVIEW(i915))
gt->forcewake = intel_uncore_read_fw(uncore, FORCEWAKE_VLV);
if (GRAPHICS_VER(i915) == 7)
gt->err_int = intel_uncore_read(uncore, GEN7_ERR_INT);
if (GRAPHICS_VER_FULL(i915) >= IP_VER(12, 50)) {
gt->fault_data0 = intel_gt_mcr_read_any((struct intel_gt *)gt->_gt,
XEHP_FAULT_TLB_DATA0);
gt->fault_data1 = intel_gt_mcr_read_any((struct intel_gt *)gt->_gt,
XEHP_FAULT_TLB_DATA1);
} else if (GRAPHICS_VER(i915) >= 12) {
gt->fault_data0 = intel_uncore_read(uncore,
GEN12_FAULT_TLB_DATA0);
gt->fault_data1 = intel_uncore_read(uncore,
GEN12_FAULT_TLB_DATA1);
} else if (GRAPHICS_VER(i915) >= 8) {
gt->fault_data0 = intel_uncore_read(uncore,
GEN8_FAULT_TLB_DATA0);
gt->fault_data1 = intel_uncore_read(uncore,
GEN8_FAULT_TLB_DATA1);
}
if (GRAPHICS_VER(i915) == 6) {
gt->forcewake = intel_uncore_read_fw(uncore, FORCEWAKE);
gt->gab_ctl = intel_uncore_read(uncore, GAB_CTL);
gt->gfx_mode = intel_uncore_read(uncore, GFX_MODE);
}
/* 2: Registers which belong to multiple generations */
if (GRAPHICS_VER(i915) >= 7)
gt->forcewake = intel_uncore_read_fw(uncore, FORCEWAKE_MT);
if (GRAPHICS_VER(i915) >= 6) {
if (GRAPHICS_VER(i915) < 12) {
gt->error = intel_uncore_read(uncore, ERROR_GEN6);
gt->done_reg = intel_uncore_read(uncore, DONE_REG);
}
}
/* 3: Feature specific registers */
if (IS_GRAPHICS_VER(i915, 6, 7)) {
gt->gam_ecochk = intel_uncore_read(uncore, GAM_ECOCHK);
gt->gac_eco = intel_uncore_read(uncore, GAC_ECO_BITS);
}
if (IS_GRAPHICS_VER(i915, 8, 11))
gt->gtt_cache = intel_uncore_read(uncore, HSW_GTT_CACHE_EN);
if (GRAPHICS_VER(i915) == 12)
gt->aux_err = intel_uncore_read(uncore, GEN12_AUX_ERR_DBG);
if (GRAPHICS_VER(i915) >= 12) {
for (i = 0; i < I915_MAX_SFC; i++) {
/*
* SFC_DONE resides in the VD forcewake domain, so it
* only exists if the corresponding VCS engine is
* present.
*/
if ((gt->_gt->info.sfc_mask & BIT(i)) == 0 ||
!HAS_ENGINE(gt->_gt, _VCS(i * 2)))
continue;
gt->sfc_done[i] =
intel_uncore_read(uncore, GEN12_SFC_DONE(i));
}
gt->gam_done = intel_uncore_read(uncore, GEN12_GAM_DONE);
}
}
static void gt_record_info(struct intel_gt_coredump *gt)
{
memcpy(>->info, >->_gt->info, sizeof(struct intel_gt_info));
gt->clock_frequency = gt->_gt->clock_frequency;
gt->clock_period_ns = gt->_gt->clock_period_ns;
}
/*
* Generate a semi-unique error code. The code is not meant to have meaning, The
* code's only purpose is to try to prevent false duplicated bug reports by
* grossly estimating a GPU error state.
*
* TODO Ideally, hashing the batchbuffer would be a very nice way to determine
* the hang if we could strip the GTT offset information from it.
*
* It's only a small step better than a random number in its current form.
*/
static u32 generate_ecode(const struct intel_engine_coredump *ee)
{
/*
* IPEHR would be an ideal way to detect errors, as it's the gross
* measure of "the command that hung." However, has some very common
* synchronization commands which almost always appear in the case
* strictly a client bug. Use instdone to differentiate those some.
*/
return ee ? ee->ipehr ^ ee->instdone.instdone : 0;
}
static const char *error_msg(struct i915_gpu_coredump *error)
{
struct intel_engine_coredump *first = NULL;
unsigned int hung_classes = 0;
struct intel_gt_coredump *gt;
int len;
for (gt = error->gt; gt; gt = gt->next) {
struct intel_engine_coredump *cs;
for (cs = gt->engine; cs; cs = cs->next) {
if (cs->hung) {
hung_classes |= BIT(cs->engine->uabi_class);
if (!first)
first = cs;
}
}
}
len = scnprintf(error->error_msg, sizeof(error->error_msg),
"GPU HANG: ecode %d:%x:%08x",
GRAPHICS_VER(error->i915), hung_classes,
generate_ecode(first));
if (first && first->context.pid) {
/* Just show the first executing process, more is confusing */
len += scnprintf(error->error_msg + len,
sizeof(error->error_msg) - len,
", in %s [%d]",
first->context.comm, first->context.pid);
}
return error->error_msg;
}
static void capture_gen(struct i915_gpu_coredump *error)
{
struct drm_i915_private *i915 = error->i915;
error->wakelock = atomic_read(&i915->runtime_pm.wakeref_count);
error->suspended = i915->runtime_pm.suspended;
error->iommu = i915_vtd_active(i915);
error->reset_count = i915_reset_count(&i915->gpu_error);
error->suspend_count = i915->suspend_count;
i915_params_copy(&error->params, &i915->params);
memcpy(&error->device_info,
INTEL_INFO(i915),
sizeof(error->device_info));
memcpy(&error->runtime_info,
RUNTIME_INFO(i915),
sizeof(error->runtime_info));
memcpy(&error->display_device_info, DISPLAY_INFO(i915),
sizeof(error->display_device_info));
memcpy(&error->display_runtime_info, DISPLAY_RUNTIME_INFO(i915),
sizeof(error->display_runtime_info));
error->driver_caps = i915->caps;
}
struct i915_gpu_coredump *
i915_gpu_coredump_alloc(struct drm_i915_private *i915, gfp_t gfp)
{
struct i915_gpu_coredump *error;
if (!i915->params.error_capture)
return NULL;
error = kzalloc(sizeof(*error), gfp);
if (!error)
return NULL;
kref_init(&error->ref);
error->i915 = i915;
error->time = ktime_get_real();
error->boottime = ktime_get_boottime();
error->uptime = ktime_sub(ktime_get(), to_gt(i915)->last_init_time);
error->capture = jiffies;
capture_gen(error);
return error;
}
#define DAY_AS_SECONDS(x) (24 * 60 * 60 * (x))
struct intel_gt_coredump *
intel_gt_coredump_alloc(struct intel_gt *gt, gfp_t gfp, u32 dump_flags)
{
struct intel_gt_coredump *gc;
gc = kzalloc(sizeof(*gc), gfp);
if (!gc)
return NULL;
gc->_gt = gt;
gc->awake = intel_gt_pm_is_awake(gt);
gt_record_display_regs(gc);
gt_record_global_nonguc_regs(gc);
/*
* GuC dumps global, eng-class and eng-instance registers
* (that can change as part of engine state during execution)
* before an engine is reset due to a hung context.
* GuC captures and reports all three groups of registers
* together as a single set before the engine is reset.
* Thus, if GuC triggered the context reset we retrieve
* the register values as part of gt_record_engines.
*/
if (!(dump_flags & CORE_DUMP_FLAG_IS_GUC_CAPTURE))
gt_record_global_regs(gc);
gt_record_fences(gc);
return gc;
}
struct i915_vma_compress *
i915_vma_capture_prepare(struct intel_gt_coredump *gt)
{
struct i915_vma_compress *compress;
compress = kmalloc(sizeof(*compress), ALLOW_FAIL);
if (!compress)
return NULL;
if (!compress_init(compress)) {
kfree(compress);
return NULL;
}
return compress;
}
void i915_vma_capture_finish(struct intel_gt_coredump *gt,
struct i915_vma_compress *compress)
{
if (!compress)
return;
compress_fini(compress);
kfree(compress);
}
static struct i915_gpu_coredump *
__i915_gpu_coredump(struct intel_gt *gt, intel_engine_mask_t engine_mask, u32 dump_flags)
{
struct drm_i915_private *i915 = gt->i915;
struct i915_gpu_coredump *error;
/* Check if GPU capture has been disabled */
error = READ_ONCE(i915->gpu_error.first_error);
if (IS_ERR(error))
return error;
error = i915_gpu_coredump_alloc(i915, ALLOW_FAIL);
if (!error)
return ERR_PTR(-ENOMEM);
error->gt = intel_gt_coredump_alloc(gt, ALLOW_FAIL, dump_flags);
if (error->gt) {
struct i915_vma_compress *compress;
compress = i915_vma_capture_prepare(error->gt);
if (!compress) {
kfree(error->gt);
kfree(error);
return ERR_PTR(-ENOMEM);
}
if (INTEL_INFO(i915)->has_gt_uc) {
error->gt->uc = gt_record_uc(error->gt, compress);
if (error->gt->uc) {
if (dump_flags & CORE_DUMP_FLAG_IS_GUC_CAPTURE)
error->gt->uc->guc.is_guc_capture = true;
else
GEM_BUG_ON(error->gt->uc->guc.is_guc_capture);
}
}
gt_record_info(error->gt);
gt_record_engines(error->gt, engine_mask, compress, dump_flags);
i915_vma_capture_finish(error->gt, compress);
error->simulated |= error->gt->simulated;
}
error->overlay = intel_overlay_capture_error_state(i915);
return error;
}
struct i915_gpu_coredump *
i915_gpu_coredump(struct intel_gt *gt, intel_engine_mask_t engine_mask, u32 dump_flags)
{
static DEFINE_MUTEX(capture_mutex);
int ret = mutex_lock_interruptible(&capture_mutex);
struct i915_gpu_coredump *dump;
if (ret)
return ERR_PTR(ret);
dump = __i915_gpu_coredump(gt, engine_mask, dump_flags);
mutex_unlock(&capture_mutex);
return dump;
}
void i915_error_state_store(struct i915_gpu_coredump *error)
{
struct drm_i915_private *i915;
static bool warned;
if (IS_ERR_OR_NULL(error))
return;
i915 = error->i915;
drm_info(&i915->drm, "%s\n", error_msg(error));
if (error->simulated ||
cmpxchg(&i915->gpu_error.first_error, NULL, error))
return;
i915_gpu_coredump_get(error);
if (!xchg(&warned, true) &&
ktime_get_real_seconds() - DRIVER_TIMESTAMP < DAY_AS_SECONDS(180)) {
pr_info("GPU hangs can indicate a bug anywhere in the entire gfx stack, including userspace.\n");
pr_info("Please file a _new_ bug report at https://gitlab.freedesktop.org/drm/intel/issues/new.\n");
pr_info("Please see https://gitlab.freedesktop.org/drm/intel/-/wikis/How-to-file-i915-bugs for details.\n");
pr_info("drm/i915 developers can then reassign to the right component if it's not a kernel issue.\n");
pr_info("The GPU crash dump is required to analyze GPU hangs, so please always attach it.\n");
pr_info("GPU crash dump saved to /sys/class/drm/card%d/error\n",
i915->drm.primary->index);
}
}
/**
* i915_capture_error_state - capture an error record for later analysis
* @gt: intel_gt which originated the hang
* @engine_mask: hung engines
* @dump_flags: dump flags
*
* Should be called when an error is detected (either a hang or an error
* interrupt) to capture error state from the time of the error. Fills
* out a structure which becomes available in debugfs for user level tools
* to pick up.
*/
void i915_capture_error_state(struct intel_gt *gt,
intel_engine_mask_t engine_mask, u32 dump_flags)
{
struct i915_gpu_coredump *error;
error = i915_gpu_coredump(gt, engine_mask, dump_flags);
if (IS_ERR(error)) {
cmpxchg(>->i915->gpu_error.first_error, NULL, error);
return;
}
i915_error_state_store(error);
i915_gpu_coredump_put(error);
}
struct i915_gpu_coredump *
i915_first_error_state(struct drm_i915_private *i915)
{
struct i915_gpu_coredump *error;
spin_lock_irq(&i915->gpu_error.lock);
error = i915->gpu_error.first_error;
if (!IS_ERR_OR_NULL(error))
i915_gpu_coredump_get(error);
spin_unlock_irq(&i915->gpu_error.lock);
return error;
}
void i915_reset_error_state(struct drm_i915_private *i915)
{
struct i915_gpu_coredump *error;
spin_lock_irq(&i915->gpu_error.lock);
error = i915->gpu_error.first_error;
if (error != ERR_PTR(-ENODEV)) /* if disabled, always disabled */
i915->gpu_error.first_error = NULL;
spin_unlock_irq(&i915->gpu_error.lock);
if (!IS_ERR_OR_NULL(error))
i915_gpu_coredump_put(error);
}
void i915_disable_error_state(struct drm_i915_private *i915, int err)
{
spin_lock_irq(&i915->gpu_error.lock);
if (!i915->gpu_error.first_error)
i915->gpu_error.first_error = ERR_PTR(err);
spin_unlock_irq(&i915->gpu_error.lock);
}
#if IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM)
void intel_klog_error_capture(struct intel_gt *gt,
intel_engine_mask_t engine_mask)
{
static int g_count;
struct drm_i915_private *i915 = gt->i915;
struct i915_gpu_coredump *error;
intel_wakeref_t wakeref;
size_t buf_size = PAGE_SIZE * 128;
size_t pos_err;
char *buf, *ptr, *next;
int l_count = g_count++;
int line = 0;
/* Can't allocate memory during a reset */
if (test_bit(I915_RESET_BACKOFF, >->reset.flags)) {
drm_err(>->i915->drm, "[Capture/%d.%d] Inside GT reset, skipping error capture :(\n",
l_count, line++);
return;
}
error = READ_ONCE(i915->gpu_error.first_error);
if (error) {
drm_err(&i915->drm, "[Capture/%d.%d] Clearing existing error capture first...\n",
l_count, line++);
i915_reset_error_state(i915);
}
with_intel_runtime_pm(&i915->runtime_pm, wakeref)
error = i915_gpu_coredump(gt, engine_mask, CORE_DUMP_FLAG_NONE);
if (IS_ERR(error)) {
drm_err(&i915->drm, "[Capture/%d.%d] Failed to capture error capture: %ld!\n",
l_count, line++, PTR_ERR(error));
return;
}
buf = kvmalloc(buf_size, GFP_KERNEL);
if (!buf) {
drm_err(&i915->drm, "[Capture/%d.%d] Failed to allocate buffer for error capture!\n",
l_count, line++);
i915_gpu_coredump_put(error);
return;
}
drm_info(&i915->drm, "[Capture/%d.%d] Dumping i915 error capture for %ps...\n",
l_count, line++, __builtin_return_address(0));
/* Largest string length safe to print via dmesg */
# define MAX_CHUNK 800
pos_err = 0;
while (1) {
ssize_t got = i915_gpu_coredump_copy_to_buffer(error, buf, pos_err, buf_size - 1);
if (got <= 0)
break;
buf[got] = 0;
pos_err += got;
ptr = buf;
while (got > 0) {
size_t count;
char tag[2];
next = strnchr(ptr, got, '\n');
if (next) {
count = next - ptr;
*next = 0;
tag[0] = '>';
tag[1] = '<';
} else {
count = got;
tag[0] = '}';
tag[1] = '{';
}
if (count > MAX_CHUNK) {
size_t pos;
char *ptr2 = ptr;
for (pos = MAX_CHUNK; pos < count; pos += MAX_CHUNK) {
char chr = ptr[pos];
ptr[pos] = 0;
drm_info(&i915->drm, "[Capture/%d.%d] }%s{\n",
l_count, line++, ptr2);
ptr[pos] = chr;
ptr2 = ptr + pos;
/*
* If spewing large amounts of data via a serial console,
* this can be a very slow process. So be friendly and try
* not to cause 'softlockup on CPU' problems.
*/
cond_resched();
}
if (ptr2 < (ptr + count))
drm_info(&i915->drm, "[Capture/%d.%d] %c%s%c\n",
l_count, line++, tag[0], ptr2, tag[1]);
else if (tag[0] == '>')
drm_info(&i915->drm, "[Capture/%d.%d] ><\n",
l_count, line++);
} else {
drm_info(&i915->drm, "[Capture/%d.%d] %c%s%c\n",
l_count, line++, tag[0], ptr, tag[1]);
}
ptr = next;
got -= count;
if (next) {
ptr++;
got--;
}
/* As above. */
cond_resched();
}
if (got)
drm_info(&i915->drm, "[Capture/%d.%d] Got %zd bytes remaining!\n",
l_count, line++, got);
}
kvfree(buf);
drm_info(&i915->drm, "[Capture/%d.%d] Dumped %zd bytes\n", l_count, line++, pos_err);
}
#endif
| linux-master | drivers/gpu/drm/i915/i915_gpu_error.c |
/*
* Copyright © 2008-2015 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* Authors:
* Eric Anholt <[email protected]>
*
*/
#include <linux/dma-fence-array.h>
#include <linux/kthread.h>
#include <linux/dma-resv.h>
#include <linux/shmem_fs.h>
#include <linux/slab.h>
#include <linux/stop_machine.h>
#include <linux/swap.h>
#include <linux/pci.h>
#include <linux/dma-buf.h>
#include <linux/mman.h>
#include <drm/drm_cache.h>
#include <drm/drm_vma_manager.h>
#include "display/intel_display.h"
#include "display/intel_frontbuffer.h"
#include "gem/i915_gem_clflush.h"
#include "gem/i915_gem_context.h"
#include "gem/i915_gem_ioctls.h"
#include "gem/i915_gem_mman.h"
#include "gem/i915_gem_pm.h"
#include "gem/i915_gem_region.h"
#include "gem/i915_gem_userptr.h"
#include "gt/intel_engine_user.h"
#include "gt/intel_gt.h"
#include "gt/intel_gt_pm.h"
#include "gt/intel_workarounds.h"
#include "i915_drv.h"
#include "i915_file_private.h"
#include "i915_trace.h"
#include "i915_vgpu.h"
#include "intel_clock_gating.h"
static int
insert_mappable_node(struct i915_ggtt *ggtt, struct drm_mm_node *node, u32 size)
{
int err;
err = mutex_lock_interruptible(&ggtt->vm.mutex);
if (err)
return err;
memset(node, 0, sizeof(*node));
err = drm_mm_insert_node_in_range(&ggtt->vm.mm, node,
size, 0, I915_COLOR_UNEVICTABLE,
0, ggtt->mappable_end,
DRM_MM_INSERT_LOW);
mutex_unlock(&ggtt->vm.mutex);
return err;
}
static void
remove_mappable_node(struct i915_ggtt *ggtt, struct drm_mm_node *node)
{
mutex_lock(&ggtt->vm.mutex);
drm_mm_remove_node(node);
mutex_unlock(&ggtt->vm.mutex);
}
int
i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
struct drm_file *file)
{
struct drm_i915_private *i915 = to_i915(dev);
struct i915_ggtt *ggtt = to_gt(i915)->ggtt;
struct drm_i915_gem_get_aperture *args = data;
struct i915_vma *vma;
u64 pinned;
if (mutex_lock_interruptible(&ggtt->vm.mutex))
return -EINTR;
pinned = ggtt->vm.reserved;
list_for_each_entry(vma, &ggtt->vm.bound_list, vm_link)
if (i915_vma_is_pinned(vma))
pinned += vma->node.size;
mutex_unlock(&ggtt->vm.mutex);
args->aper_size = ggtt->vm.total;
args->aper_available_size = args->aper_size - pinned;
return 0;
}
int i915_gem_object_unbind(struct drm_i915_gem_object *obj,
unsigned long flags)
{
struct intel_runtime_pm *rpm = &to_i915(obj->base.dev)->runtime_pm;
bool vm_trylock = !!(flags & I915_GEM_OBJECT_UNBIND_VM_TRYLOCK);
LIST_HEAD(still_in_list);
intel_wakeref_t wakeref;
struct i915_vma *vma;
int ret;
assert_object_held(obj);
if (list_empty(&obj->vma.list))
return 0;
/*
* As some machines use ACPI to handle runtime-resume callbacks, and
* ACPI is quite kmalloc happy, we cannot resume beneath the vm->mutex
* as they are required by the shrinker. Ergo, we wake the device up
* first just in case.
*/
wakeref = intel_runtime_pm_get(rpm);
try_again:
ret = 0;
spin_lock(&obj->vma.lock);
while (!ret && (vma = list_first_entry_or_null(&obj->vma.list,
struct i915_vma,
obj_link))) {
list_move_tail(&vma->obj_link, &still_in_list);
if (!i915_vma_is_bound(vma, I915_VMA_BIND_MASK))
continue;
if (flags & I915_GEM_OBJECT_UNBIND_TEST) {
ret = -EBUSY;
break;
}
/*
* Requiring the vm destructor to take the object lock
* before destroying a vma would help us eliminate the
* i915_vm_tryget() here, AND thus also the barrier stuff
* at the end. That's an easy fix, but sleeping locks in
* a kthread should generally be avoided.
*/
ret = -EAGAIN;
if (!i915_vm_tryget(vma->vm))
break;
spin_unlock(&obj->vma.lock);
/*
* Since i915_vma_parked() takes the object lock
* before vma destruction, it won't race us here,
* and destroy the vma from under us.
*/
ret = -EBUSY;
if (flags & I915_GEM_OBJECT_UNBIND_ASYNC) {
assert_object_held(vma->obj);
ret = i915_vma_unbind_async(vma, vm_trylock);
}
if (ret == -EBUSY && (flags & I915_GEM_OBJECT_UNBIND_ACTIVE ||
!i915_vma_is_active(vma))) {
if (vm_trylock) {
if (mutex_trylock(&vma->vm->mutex)) {
ret = __i915_vma_unbind(vma);
mutex_unlock(&vma->vm->mutex);
}
} else {
ret = i915_vma_unbind(vma);
}
}
i915_vm_put(vma->vm);
spin_lock(&obj->vma.lock);
}
list_splice_init(&still_in_list, &obj->vma.list);
spin_unlock(&obj->vma.lock);
if (ret == -EAGAIN && flags & I915_GEM_OBJECT_UNBIND_BARRIER) {
rcu_barrier(); /* flush the i915_vm_release() */
goto try_again;
}
intel_runtime_pm_put(rpm, wakeref);
return ret;
}
static int
shmem_pread(struct page *page, int offset, int len, char __user *user_data,
bool needs_clflush)
{
char *vaddr;
int ret;
vaddr = kmap(page);
if (needs_clflush)
drm_clflush_virt_range(vaddr + offset, len);
ret = __copy_to_user(user_data, vaddr + offset, len);
kunmap(page);
return ret ? -EFAULT : 0;
}
static int
i915_gem_shmem_pread(struct drm_i915_gem_object *obj,
struct drm_i915_gem_pread *args)
{
unsigned int needs_clflush;
char __user *user_data;
unsigned long offset;
pgoff_t idx;
u64 remain;
int ret;
ret = i915_gem_object_lock_interruptible(obj, NULL);
if (ret)
return ret;
ret = i915_gem_object_pin_pages(obj);
if (ret)
goto err_unlock;
ret = i915_gem_object_prepare_read(obj, &needs_clflush);
if (ret)
goto err_unpin;
i915_gem_object_finish_access(obj);
i915_gem_object_unlock(obj);
remain = args->size;
user_data = u64_to_user_ptr(args->data_ptr);
offset = offset_in_page(args->offset);
for (idx = args->offset >> PAGE_SHIFT; remain; idx++) {
struct page *page = i915_gem_object_get_page(obj, idx);
unsigned int length = min_t(u64, remain, PAGE_SIZE - offset);
ret = shmem_pread(page, offset, length, user_data,
needs_clflush);
if (ret)
break;
remain -= length;
user_data += length;
offset = 0;
}
i915_gem_object_unpin_pages(obj);
return ret;
err_unpin:
i915_gem_object_unpin_pages(obj);
err_unlock:
i915_gem_object_unlock(obj);
return ret;
}
static inline bool
gtt_user_read(struct io_mapping *mapping,
loff_t base, int offset,
char __user *user_data, int length)
{
void __iomem *vaddr;
unsigned long unwritten;
/* We can use the cpu mem copy function because this is X86. */
vaddr = io_mapping_map_atomic_wc(mapping, base);
unwritten = __copy_to_user_inatomic(user_data,
(void __force *)vaddr + offset,
length);
io_mapping_unmap_atomic(vaddr);
if (unwritten) {
vaddr = io_mapping_map_wc(mapping, base, PAGE_SIZE);
unwritten = copy_to_user(user_data,
(void __force *)vaddr + offset,
length);
io_mapping_unmap(vaddr);
}
return unwritten;
}
static struct i915_vma *i915_gem_gtt_prepare(struct drm_i915_gem_object *obj,
struct drm_mm_node *node,
bool write)
{
struct drm_i915_private *i915 = to_i915(obj->base.dev);
struct i915_ggtt *ggtt = to_gt(i915)->ggtt;
struct i915_vma *vma;
struct i915_gem_ww_ctx ww;
int ret;
i915_gem_ww_ctx_init(&ww, true);
retry:
vma = ERR_PTR(-ENODEV);
ret = i915_gem_object_lock(obj, &ww);
if (ret)
goto err_ww;
ret = i915_gem_object_set_to_gtt_domain(obj, write);
if (ret)
goto err_ww;
if (!i915_gem_object_is_tiled(obj))
vma = i915_gem_object_ggtt_pin_ww(obj, &ww, NULL, 0, 0,
PIN_MAPPABLE |
PIN_NONBLOCK /* NOWARN */ |
PIN_NOEVICT);
if (vma == ERR_PTR(-EDEADLK)) {
ret = -EDEADLK;
goto err_ww;
} else if (!IS_ERR(vma)) {
node->start = i915_ggtt_offset(vma);
node->flags = 0;
} else {
ret = insert_mappable_node(ggtt, node, PAGE_SIZE);
if (ret)
goto err_ww;
GEM_BUG_ON(!drm_mm_node_allocated(node));
vma = NULL;
}
ret = i915_gem_object_pin_pages(obj);
if (ret) {
if (drm_mm_node_allocated(node)) {
ggtt->vm.clear_range(&ggtt->vm, node->start, node->size);
remove_mappable_node(ggtt, node);
} else {
i915_vma_unpin(vma);
}
}
err_ww:
if (ret == -EDEADLK) {
ret = i915_gem_ww_ctx_backoff(&ww);
if (!ret)
goto retry;
}
i915_gem_ww_ctx_fini(&ww);
return ret ? ERR_PTR(ret) : vma;
}
static void i915_gem_gtt_cleanup(struct drm_i915_gem_object *obj,
struct drm_mm_node *node,
struct i915_vma *vma)
{
struct drm_i915_private *i915 = to_i915(obj->base.dev);
struct i915_ggtt *ggtt = to_gt(i915)->ggtt;
i915_gem_object_unpin_pages(obj);
if (drm_mm_node_allocated(node)) {
ggtt->vm.clear_range(&ggtt->vm, node->start, node->size);
remove_mappable_node(ggtt, node);
} else {
i915_vma_unpin(vma);
}
}
static int
i915_gem_gtt_pread(struct drm_i915_gem_object *obj,
const struct drm_i915_gem_pread *args)
{
struct drm_i915_private *i915 = to_i915(obj->base.dev);
struct i915_ggtt *ggtt = to_gt(i915)->ggtt;
unsigned long remain, offset;
intel_wakeref_t wakeref;
struct drm_mm_node node;
void __user *user_data;
struct i915_vma *vma;
int ret = 0;
if (overflows_type(args->size, remain) ||
overflows_type(args->offset, offset))
return -EINVAL;
wakeref = intel_runtime_pm_get(&i915->runtime_pm);
vma = i915_gem_gtt_prepare(obj, &node, false);
if (IS_ERR(vma)) {
ret = PTR_ERR(vma);
goto out_rpm;
}
user_data = u64_to_user_ptr(args->data_ptr);
remain = args->size;
offset = args->offset;
while (remain > 0) {
/* Operation in this page
*
* page_base = page offset within aperture
* page_offset = offset within page
* page_length = bytes to copy for this page
*/
u32 page_base = node.start;
unsigned page_offset = offset_in_page(offset);
unsigned page_length = PAGE_SIZE - page_offset;
page_length = remain < page_length ? remain : page_length;
if (drm_mm_node_allocated(&node)) {
ggtt->vm.insert_page(&ggtt->vm,
i915_gem_object_get_dma_address(obj,
offset >> PAGE_SHIFT),
node.start,
i915_gem_get_pat_index(i915,
I915_CACHE_NONE), 0);
} else {
page_base += offset & PAGE_MASK;
}
if (gtt_user_read(&ggtt->iomap, page_base, page_offset,
user_data, page_length)) {
ret = -EFAULT;
break;
}
remain -= page_length;
user_data += page_length;
offset += page_length;
}
i915_gem_gtt_cleanup(obj, &node, vma);
out_rpm:
intel_runtime_pm_put(&i915->runtime_pm, wakeref);
return ret;
}
/**
* i915_gem_pread_ioctl - Reads data from the object referenced by handle.
* @dev: drm device pointer
* @data: ioctl data blob
* @file: drm file pointer
*
* On error, the contents of *data are undefined.
*/
int
i915_gem_pread_ioctl(struct drm_device *dev, void *data,
struct drm_file *file)
{
struct drm_i915_private *i915 = to_i915(dev);
struct drm_i915_gem_pread *args = data;
struct drm_i915_gem_object *obj;
int ret;
/* PREAD is disallowed for all platforms after TGL-LP. This also
* covers all platforms with local memory.
*/
if (GRAPHICS_VER(i915) >= 12 && !IS_TIGERLAKE(i915))
return -EOPNOTSUPP;
if (args->size == 0)
return 0;
if (!access_ok(u64_to_user_ptr(args->data_ptr),
args->size))
return -EFAULT;
obj = i915_gem_object_lookup(file, args->handle);
if (!obj)
return -ENOENT;
/* Bounds check source. */
if (range_overflows_t(u64, args->offset, args->size, obj->base.size)) {
ret = -EINVAL;
goto out;
}
trace_i915_gem_object_pread(obj, args->offset, args->size);
ret = -ENODEV;
if (obj->ops->pread)
ret = obj->ops->pread(obj, args);
if (ret != -ENODEV)
goto out;
ret = i915_gem_object_wait(obj,
I915_WAIT_INTERRUPTIBLE,
MAX_SCHEDULE_TIMEOUT);
if (ret)
goto out;
ret = i915_gem_shmem_pread(obj, args);
if (ret == -EFAULT || ret == -ENODEV)
ret = i915_gem_gtt_pread(obj, args);
out:
i915_gem_object_put(obj);
return ret;
}
/* This is the fast write path which cannot handle
* page faults in the source data
*/
static inline bool
ggtt_write(struct io_mapping *mapping,
loff_t base, int offset,
char __user *user_data, int length)
{
void __iomem *vaddr;
unsigned long unwritten;
/* We can use the cpu mem copy function because this is X86. */
vaddr = io_mapping_map_atomic_wc(mapping, base);
unwritten = __copy_from_user_inatomic_nocache((void __force *)vaddr + offset,
user_data, length);
io_mapping_unmap_atomic(vaddr);
if (unwritten) {
vaddr = io_mapping_map_wc(mapping, base, PAGE_SIZE);
unwritten = copy_from_user((void __force *)vaddr + offset,
user_data, length);
io_mapping_unmap(vaddr);
}
return unwritten;
}
/**
* i915_gem_gtt_pwrite_fast - This is the fast pwrite path, where we copy the data directly from the
* user into the GTT, uncached.
* @obj: i915 GEM object
* @args: pwrite arguments structure
*/
static int
i915_gem_gtt_pwrite_fast(struct drm_i915_gem_object *obj,
const struct drm_i915_gem_pwrite *args)
{
struct drm_i915_private *i915 = to_i915(obj->base.dev);
struct i915_ggtt *ggtt = to_gt(i915)->ggtt;
struct intel_runtime_pm *rpm = &i915->runtime_pm;
unsigned long remain, offset;
intel_wakeref_t wakeref;
struct drm_mm_node node;
struct i915_vma *vma;
void __user *user_data;
int ret = 0;
if (overflows_type(args->size, remain) ||
overflows_type(args->offset, offset))
return -EINVAL;
if (i915_gem_object_has_struct_page(obj)) {
/*
* Avoid waking the device up if we can fallback, as
* waking/resuming is very slow (worst-case 10-100 ms
* depending on PCI sleeps and our own resume time).
* This easily dwarfs any performance advantage from
* using the cache bypass of indirect GGTT access.
*/
wakeref = intel_runtime_pm_get_if_in_use(rpm);
if (!wakeref)
return -EFAULT;
} else {
/* No backing pages, no fallback, we must force GGTT access */
wakeref = intel_runtime_pm_get(rpm);
}
vma = i915_gem_gtt_prepare(obj, &node, true);
if (IS_ERR(vma)) {
ret = PTR_ERR(vma);
goto out_rpm;
}
i915_gem_object_invalidate_frontbuffer(obj, ORIGIN_CPU);
user_data = u64_to_user_ptr(args->data_ptr);
offset = args->offset;
remain = args->size;
while (remain) {
/* Operation in this page
*
* page_base = page offset within aperture
* page_offset = offset within page
* page_length = bytes to copy for this page
*/
u32 page_base = node.start;
unsigned int page_offset = offset_in_page(offset);
unsigned int page_length = PAGE_SIZE - page_offset;
page_length = remain < page_length ? remain : page_length;
if (drm_mm_node_allocated(&node)) {
/* flush the write before we modify the GGTT */
intel_gt_flush_ggtt_writes(ggtt->vm.gt);
ggtt->vm.insert_page(&ggtt->vm,
i915_gem_object_get_dma_address(obj,
offset >> PAGE_SHIFT),
node.start,
i915_gem_get_pat_index(i915,
I915_CACHE_NONE), 0);
wmb(); /* flush modifications to the GGTT (insert_page) */
} else {
page_base += offset & PAGE_MASK;
}
/* If we get a fault while copying data, then (presumably) our
* source page isn't available. Return the error and we'll
* retry in the slow path.
* If the object is non-shmem backed, we retry again with the
* path that handles page fault.
*/
if (ggtt_write(&ggtt->iomap, page_base, page_offset,
user_data, page_length)) {
ret = -EFAULT;
break;
}
remain -= page_length;
user_data += page_length;
offset += page_length;
}
intel_gt_flush_ggtt_writes(ggtt->vm.gt);
i915_gem_object_flush_frontbuffer(obj, ORIGIN_CPU);
i915_gem_gtt_cleanup(obj, &node, vma);
out_rpm:
intel_runtime_pm_put(rpm, wakeref);
return ret;
}
/* Per-page copy function for the shmem pwrite fastpath.
* Flushes invalid cachelines before writing to the target if
* needs_clflush_before is set and flushes out any written cachelines after
* writing if needs_clflush is set.
*/
static int
shmem_pwrite(struct page *page, int offset, int len, char __user *user_data,
bool needs_clflush_before,
bool needs_clflush_after)
{
char *vaddr;
int ret;
vaddr = kmap(page);
if (needs_clflush_before)
drm_clflush_virt_range(vaddr + offset, len);
ret = __copy_from_user(vaddr + offset, user_data, len);
if (!ret && needs_clflush_after)
drm_clflush_virt_range(vaddr + offset, len);
kunmap(page);
return ret ? -EFAULT : 0;
}
static int
i915_gem_shmem_pwrite(struct drm_i915_gem_object *obj,
const struct drm_i915_gem_pwrite *args)
{
unsigned int partial_cacheline_write;
unsigned int needs_clflush;
void __user *user_data;
unsigned long offset;
pgoff_t idx;
u64 remain;
int ret;
ret = i915_gem_object_lock_interruptible(obj, NULL);
if (ret)
return ret;
ret = i915_gem_object_pin_pages(obj);
if (ret)
goto err_unlock;
ret = i915_gem_object_prepare_write(obj, &needs_clflush);
if (ret)
goto err_unpin;
i915_gem_object_finish_access(obj);
i915_gem_object_unlock(obj);
/* If we don't overwrite a cacheline completely we need to be
* careful to have up-to-date data by first clflushing. Don't
* overcomplicate things and flush the entire patch.
*/
partial_cacheline_write = 0;
if (needs_clflush & CLFLUSH_BEFORE)
partial_cacheline_write = boot_cpu_data.x86_clflush_size - 1;
user_data = u64_to_user_ptr(args->data_ptr);
remain = args->size;
offset = offset_in_page(args->offset);
for (idx = args->offset >> PAGE_SHIFT; remain; idx++) {
struct page *page = i915_gem_object_get_page(obj, idx);
unsigned int length = min_t(u64, remain, PAGE_SIZE - offset);
ret = shmem_pwrite(page, offset, length, user_data,
(offset | length) & partial_cacheline_write,
needs_clflush & CLFLUSH_AFTER);
if (ret)
break;
remain -= length;
user_data += length;
offset = 0;
}
i915_gem_object_flush_frontbuffer(obj, ORIGIN_CPU);
i915_gem_object_unpin_pages(obj);
return ret;
err_unpin:
i915_gem_object_unpin_pages(obj);
err_unlock:
i915_gem_object_unlock(obj);
return ret;
}
/**
* i915_gem_pwrite_ioctl - Writes data to the object referenced by handle.
* @dev: drm device
* @data: ioctl data blob
* @file: drm file
*
* On error, the contents of the buffer that were to be modified are undefined.
*/
int
i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
struct drm_file *file)
{
struct drm_i915_private *i915 = to_i915(dev);
struct drm_i915_gem_pwrite *args = data;
struct drm_i915_gem_object *obj;
int ret;
/* PWRITE is disallowed for all platforms after TGL-LP. This also
* covers all platforms with local memory.
*/
if (GRAPHICS_VER(i915) >= 12 && !IS_TIGERLAKE(i915))
return -EOPNOTSUPP;
if (args->size == 0)
return 0;
if (!access_ok(u64_to_user_ptr(args->data_ptr), args->size))
return -EFAULT;
obj = i915_gem_object_lookup(file, args->handle);
if (!obj)
return -ENOENT;
/* Bounds check destination. */
if (range_overflows_t(u64, args->offset, args->size, obj->base.size)) {
ret = -EINVAL;
goto err;
}
/* Writes not allowed into this read-only object */
if (i915_gem_object_is_readonly(obj)) {
ret = -EINVAL;
goto err;
}
trace_i915_gem_object_pwrite(obj, args->offset, args->size);
ret = -ENODEV;
if (obj->ops->pwrite)
ret = obj->ops->pwrite(obj, args);
if (ret != -ENODEV)
goto err;
ret = i915_gem_object_wait(obj,
I915_WAIT_INTERRUPTIBLE |
I915_WAIT_ALL,
MAX_SCHEDULE_TIMEOUT);
if (ret)
goto err;
ret = -EFAULT;
/* We can only do the GTT pwrite on untiled buffers, as otherwise
* it would end up going through the fenced access, and we'll get
* different detiling behavior between reading and writing.
* pread/pwrite currently are reading and writing from the CPU
* perspective, requiring manual detiling by the client.
*/
if (!i915_gem_object_has_struct_page(obj) ||
i915_gem_cpu_write_needs_clflush(obj))
/* Note that the gtt paths might fail with non-page-backed user
* pointers (e.g. gtt mappings when moving data between
* textures). Fallback to the shmem path in that case.
*/
ret = i915_gem_gtt_pwrite_fast(obj, args);
if (ret == -EFAULT || ret == -ENOSPC) {
if (i915_gem_object_has_struct_page(obj))
ret = i915_gem_shmem_pwrite(obj, args);
}
err:
i915_gem_object_put(obj);
return ret;
}
/**
* i915_gem_sw_finish_ioctl - Called when user space has done writes to this buffer
* @dev: drm device
* @data: ioctl data blob
* @file: drm file
*/
int
i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
struct drm_file *file)
{
struct drm_i915_gem_sw_finish *args = data;
struct drm_i915_gem_object *obj;
obj = i915_gem_object_lookup(file, args->handle);
if (!obj)
return -ENOENT;
/*
* Proxy objects are barred from CPU access, so there is no
* need to ban sw_finish as it is a nop.
*/
/* Pinned buffers may be scanout, so flush the cache */
i915_gem_object_flush_if_display(obj);
i915_gem_object_put(obj);
return 0;
}
void i915_gem_runtime_suspend(struct drm_i915_private *i915)
{
struct drm_i915_gem_object *obj, *on;
int i;
/*
* Only called during RPM suspend. All users of the userfault_list
* must be holding an RPM wakeref to ensure that this can not
* run concurrently with themselves (and use the struct_mutex for
* protection between themselves).
*/
list_for_each_entry_safe(obj, on,
&to_gt(i915)->ggtt->userfault_list, userfault_link)
__i915_gem_object_release_mmap_gtt(obj);
list_for_each_entry_safe(obj, on,
&i915->runtime_pm.lmem_userfault_list, userfault_link)
i915_gem_object_runtime_pm_release_mmap_offset(obj);
/*
* The fence will be lost when the device powers down. If any were
* in use by hardware (i.e. they are pinned), we should not be powering
* down! All other fences will be reacquired by the user upon waking.
*/
for (i = 0; i < to_gt(i915)->ggtt->num_fences; i++) {
struct i915_fence_reg *reg = &to_gt(i915)->ggtt->fence_regs[i];
/*
* Ideally we want to assert that the fence register is not
* live at this point (i.e. that no piece of code will be
* trying to write through fence + GTT, as that both violates
* our tracking of activity and associated locking/barriers,
* but also is illegal given that the hw is powered down).
*
* Previously we used reg->pin_count as a "liveness" indicator.
* That is not sufficient, and we need a more fine-grained
* tool if we want to have a sanity check here.
*/
if (!reg->vma)
continue;
GEM_BUG_ON(i915_vma_has_userfault(reg->vma));
reg->dirty = true;
}
}
static void discard_ggtt_vma(struct i915_vma *vma)
{
struct drm_i915_gem_object *obj = vma->obj;
spin_lock(&obj->vma.lock);
if (!RB_EMPTY_NODE(&vma->obj_node)) {
rb_erase(&vma->obj_node, &obj->vma.tree);
RB_CLEAR_NODE(&vma->obj_node);
}
spin_unlock(&obj->vma.lock);
}
struct i915_vma *
i915_gem_object_ggtt_pin_ww(struct drm_i915_gem_object *obj,
struct i915_gem_ww_ctx *ww,
const struct i915_gtt_view *view,
u64 size, u64 alignment, u64 flags)
{
struct drm_i915_private *i915 = to_i915(obj->base.dev);
struct i915_ggtt *ggtt = to_gt(i915)->ggtt;
struct i915_vma *vma;
int ret;
GEM_WARN_ON(!ww);
if (flags & PIN_MAPPABLE &&
(!view || view->type == I915_GTT_VIEW_NORMAL)) {
/*
* If the required space is larger than the available
* aperture, we will not able to find a slot for the
* object and unbinding the object now will be in
* vain. Worse, doing so may cause us to ping-pong
* the object in and out of the Global GTT and
* waste a lot of cycles under the mutex.
*/
if (obj->base.size > ggtt->mappable_end)
return ERR_PTR(-E2BIG);
/*
* If NONBLOCK is set the caller is optimistically
* trying to cache the full object within the mappable
* aperture, and *must* have a fallback in place for
* situations where we cannot bind the object. We
* can be a little more lax here and use the fallback
* more often to avoid costly migrations of ourselves
* and other objects within the aperture.
*
* Half-the-aperture is used as a simple heuristic.
* More interesting would to do search for a free
* block prior to making the commitment to unbind.
* That caters for the self-harm case, and with a
* little more heuristics (e.g. NOFAULT, NOEVICT)
* we could try to minimise harm to others.
*/
if (flags & PIN_NONBLOCK &&
obj->base.size > ggtt->mappable_end / 2)
return ERR_PTR(-ENOSPC);
}
new_vma:
vma = i915_vma_instance(obj, &ggtt->vm, view);
if (IS_ERR(vma))
return vma;
if (i915_vma_misplaced(vma, size, alignment, flags)) {
if (flags & PIN_NONBLOCK) {
if (i915_vma_is_pinned(vma) || i915_vma_is_active(vma))
return ERR_PTR(-ENOSPC);
/*
* If this misplaced vma is too big (i.e, at-least
* half the size of aperture) or hasn't been pinned
* mappable before, we ignore the misplacement when
* PIN_NONBLOCK is set in order to avoid the ping-pong
* issue described above. In other words, we try to
* avoid the costly operation of unbinding this vma
* from the GGTT and rebinding it back because there
* may not be enough space for this vma in the aperture.
*/
if (flags & PIN_MAPPABLE &&
(vma->fence_size > ggtt->mappable_end / 2 ||
!i915_vma_is_map_and_fenceable(vma)))
return ERR_PTR(-ENOSPC);
}
if (i915_vma_is_pinned(vma) || i915_vma_is_active(vma)) {
discard_ggtt_vma(vma);
goto new_vma;
}
ret = i915_vma_unbind(vma);
if (ret)
return ERR_PTR(ret);
}
ret = i915_vma_pin_ww(vma, ww, size, alignment, flags | PIN_GLOBAL);
if (ret)
return ERR_PTR(ret);
if (vma->fence && !i915_gem_object_is_tiled(obj)) {
mutex_lock(&ggtt->vm.mutex);
i915_vma_revoke_fence(vma);
mutex_unlock(&ggtt->vm.mutex);
}
ret = i915_vma_wait_for_bind(vma);
if (ret) {
i915_vma_unpin(vma);
return ERR_PTR(ret);
}
return vma;
}
struct i915_vma * __must_check
i915_gem_object_ggtt_pin(struct drm_i915_gem_object *obj,
const struct i915_gtt_view *view,
u64 size, u64 alignment, u64 flags)
{
struct i915_gem_ww_ctx ww;
struct i915_vma *ret;
int err;
for_i915_gem_ww(&ww, err, true) {
err = i915_gem_object_lock(obj, &ww);
if (err)
continue;
ret = i915_gem_object_ggtt_pin_ww(obj, &ww, view, size,
alignment, flags);
if (IS_ERR(ret))
err = PTR_ERR(ret);
}
return err ? ERR_PTR(err) : ret;
}
int
i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_i915_private *i915 = to_i915(dev);
struct drm_i915_gem_madvise *args = data;
struct drm_i915_gem_object *obj;
int err;
switch (args->madv) {
case I915_MADV_DONTNEED:
case I915_MADV_WILLNEED:
break;
default:
return -EINVAL;
}
obj = i915_gem_object_lookup(file_priv, args->handle);
if (!obj)
return -ENOENT;
err = i915_gem_object_lock_interruptible(obj, NULL);
if (err)
goto out;
if (i915_gem_object_has_pages(obj) &&
i915_gem_object_is_tiled(obj) &&
i915->gem_quirks & GEM_QUIRK_PIN_SWIZZLED_PAGES) {
if (obj->mm.madv == I915_MADV_WILLNEED) {
GEM_BUG_ON(!i915_gem_object_has_tiling_quirk(obj));
i915_gem_object_clear_tiling_quirk(obj);
i915_gem_object_make_shrinkable(obj);
}
if (args->madv == I915_MADV_WILLNEED) {
GEM_BUG_ON(i915_gem_object_has_tiling_quirk(obj));
i915_gem_object_make_unshrinkable(obj);
i915_gem_object_set_tiling_quirk(obj);
}
}
if (obj->mm.madv != __I915_MADV_PURGED) {
obj->mm.madv = args->madv;
if (obj->ops->adjust_lru)
obj->ops->adjust_lru(obj);
}
if (i915_gem_object_has_pages(obj) ||
i915_gem_object_has_self_managed_shrink_list(obj)) {
unsigned long flags;
spin_lock_irqsave(&i915->mm.obj_lock, flags);
if (!list_empty(&obj->mm.link)) {
struct list_head *list;
if (obj->mm.madv != I915_MADV_WILLNEED)
list = &i915->mm.purge_list;
else
list = &i915->mm.shrink_list;
list_move_tail(&obj->mm.link, list);
}
spin_unlock_irqrestore(&i915->mm.obj_lock, flags);
}
/* if the object is no longer attached, discard its backing storage */
if (obj->mm.madv == I915_MADV_DONTNEED &&
!i915_gem_object_has_pages(obj))
i915_gem_object_truncate(obj);
args->retained = obj->mm.madv != __I915_MADV_PURGED;
i915_gem_object_unlock(obj);
out:
i915_gem_object_put(obj);
return err;
}
/*
* A single pass should suffice to release all the freed objects (along most
* call paths), but be a little more paranoid in that freeing the objects does
* take a little amount of time, during which the rcu callbacks could have added
* new objects into the freed list, and armed the work again.
*/
void i915_gem_drain_freed_objects(struct drm_i915_private *i915)
{
while (atomic_read(&i915->mm.free_count)) {
flush_work(&i915->mm.free_work);
drain_workqueue(i915->bdev.wq);
rcu_barrier();
}
}
/*
* Similar to objects above (see i915_gem_drain_freed-objects), in general we
* have workers that are armed by RCU and then rearm themselves in their
* callbacks. To be paranoid, we need to drain the workqueue a second time after
* waiting for the RCU grace period so that we catch work queued via RCU from
* the first pass. As neither drain_workqueue() nor flush_workqueue() report a
* result, we make an assumption that we only don't require more than 3 passes
* to catch all _recursive_ RCU delayed work.
*/
void i915_gem_drain_workqueue(struct drm_i915_private *i915)
{
int i;
for (i = 0; i < 3; i++) {
flush_workqueue(i915->wq);
rcu_barrier();
i915_gem_drain_freed_objects(i915);
}
drain_workqueue(i915->wq);
}
int i915_gem_init(struct drm_i915_private *dev_priv)
{
struct intel_gt *gt;
unsigned int i;
int ret;
/*
* In the proccess of replacing cache_level with pat_index a tricky
* dependency is created on the definition of the enum i915_cache_level.
* in case this enum is changed, PTE encode would be broken.
* Add a WARNING here. And remove when we completely quit using this
* enum
*/
BUILD_BUG_ON(I915_CACHE_NONE != 0 ||
I915_CACHE_LLC != 1 ||
I915_CACHE_L3_LLC != 2 ||
I915_CACHE_WT != 3 ||
I915_MAX_CACHE_LEVEL != 4);
/* We need to fallback to 4K pages if host doesn't support huge gtt. */
if (intel_vgpu_active(dev_priv) && !intel_vgpu_has_huge_gtt(dev_priv))
RUNTIME_INFO(dev_priv)->page_sizes = I915_GTT_PAGE_SIZE_4K;
ret = i915_gem_init_userptr(dev_priv);
if (ret)
return ret;
for_each_gt(gt, dev_priv, i) {
intel_uc_fetch_firmwares(>->uc);
intel_wopcm_init(>->wopcm);
if (GRAPHICS_VER(dev_priv) >= 8)
setup_private_pat(gt);
}
ret = i915_init_ggtt(dev_priv);
if (ret) {
GEM_BUG_ON(ret == -EIO);
goto err_unlock;
}
/*
* Despite its name intel_clock_gating_init applies both display
* clock gating workarounds; GT mmio workarounds and the occasional
* GT power context workaround. Worse, sometimes it includes a context
* register workaround which we need to apply before we record the
* default HW state for all contexts.
*
* FIXME: break up the workarounds and apply them at the right time!
*/
intel_clock_gating_init(dev_priv);
for_each_gt(gt, dev_priv, i) {
ret = intel_gt_init(gt);
if (ret)
goto err_unlock;
}
return 0;
/*
* Unwinding is complicated by that we want to handle -EIO to mean
* disable GPU submission but keep KMS alive. We want to mark the
* HW as irrevisibly wedged, but keep enough state around that the
* driver doesn't explode during runtime.
*/
err_unlock:
i915_gem_drain_workqueue(dev_priv);
if (ret != -EIO) {
for_each_gt(gt, dev_priv, i) {
intel_gt_driver_remove(gt);
intel_gt_driver_release(gt);
intel_uc_cleanup_firmwares(>->uc);
}
}
if (ret == -EIO) {
/*
* Allow engines or uC initialisation to fail by marking the GPU
* as wedged. But we only want to do this when the GPU is angry,
* for all other failure, such as an allocation failure, bail.
*/
for_each_gt(gt, dev_priv, i) {
if (!intel_gt_is_wedged(gt)) {
i915_probe_error(dev_priv,
"Failed to initialize GPU, declaring it wedged!\n");
intel_gt_set_wedged(gt);
}
}
/* Minimal basic recovery for KMS */
ret = i915_ggtt_enable_hw(dev_priv);
i915_ggtt_resume(to_gt(dev_priv)->ggtt);
intel_clock_gating_init(dev_priv);
}
i915_gem_drain_freed_objects(dev_priv);
return ret;
}
void i915_gem_driver_register(struct drm_i915_private *i915)
{
i915_gem_driver_register__shrinker(i915);
intel_engines_driver_register(i915);
}
void i915_gem_driver_unregister(struct drm_i915_private *i915)
{
i915_gem_driver_unregister__shrinker(i915);
}
void i915_gem_driver_remove(struct drm_i915_private *dev_priv)
{
struct intel_gt *gt;
unsigned int i;
i915_gem_suspend_late(dev_priv);
for_each_gt(gt, dev_priv, i)
intel_gt_driver_remove(gt);
dev_priv->uabi_engines = RB_ROOT;
/* Flush any outstanding unpin_work. */
i915_gem_drain_workqueue(dev_priv);
}
void i915_gem_driver_release(struct drm_i915_private *dev_priv)
{
struct intel_gt *gt;
unsigned int i;
for_each_gt(gt, dev_priv, i) {
intel_gt_driver_release(gt);
intel_uc_cleanup_firmwares(>->uc);
}
/* Flush any outstanding work, including i915_gem_context.release_work. */
i915_gem_drain_workqueue(dev_priv);
drm_WARN_ON(&dev_priv->drm, !list_empty(&dev_priv->gem.contexts.list));
}
static void i915_gem_init__mm(struct drm_i915_private *i915)
{
spin_lock_init(&i915->mm.obj_lock);
init_llist_head(&i915->mm.free_list);
INIT_LIST_HEAD(&i915->mm.purge_list);
INIT_LIST_HEAD(&i915->mm.shrink_list);
i915_gem_init__objects(i915);
}
void i915_gem_init_early(struct drm_i915_private *dev_priv)
{
i915_gem_init__mm(dev_priv);
i915_gem_init__contexts(dev_priv);
spin_lock_init(&dev_priv->display.fb_tracking.lock);
}
void i915_gem_cleanup_early(struct drm_i915_private *dev_priv)
{
i915_gem_drain_workqueue(dev_priv);
GEM_BUG_ON(!llist_empty(&dev_priv->mm.free_list));
GEM_BUG_ON(atomic_read(&dev_priv->mm.free_count));
drm_WARN_ON(&dev_priv->drm, dev_priv->mm.shrink_count);
}
int i915_gem_open(struct drm_i915_private *i915, struct drm_file *file)
{
struct drm_i915_file_private *file_priv;
struct i915_drm_client *client;
int ret = -ENOMEM;
drm_dbg(&i915->drm, "\n");
file_priv = kzalloc(sizeof(*file_priv), GFP_KERNEL);
if (!file_priv)
goto err_alloc;
client = i915_drm_client_alloc();
if (!client)
goto err_client;
file->driver_priv = file_priv;
file_priv->i915 = i915;
file_priv->file = file;
file_priv->client = client;
file_priv->bsd_engine = -1;
file_priv->hang_timestamp = jiffies;
ret = i915_gem_context_open(i915, file);
if (ret)
goto err_context;
return 0;
err_context:
i915_drm_client_put(client);
err_client:
kfree(file_priv);
err_alloc:
return ret;
}
#if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
#include "selftests/mock_gem_device.c"
#include "selftests/i915_gem.c"
#endif
| linux-master | drivers/gpu/drm/i915/i915_gem.c |
/* i915_drv.c -- i830,i845,i855,i865,i915 driver -*- linux-c -*-
*/
/*
*
* Copyright 2003 Tungsten Graphics, Inc., Cedar Park, Texas.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
* IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include <linux/acpi.h>
#include <linux/device.h>
#include <linux/module.h>
#include <linux/oom.h>
#include <linux/pci.h>
#include <linux/pm.h>
#include <linux/pm_runtime.h>
#include <linux/slab.h>
#include <linux/string_helpers.h>
#include <linux/vga_switcheroo.h>
#include <linux/vt.h>
#include <drm/drm_aperture.h>
#include <drm/drm_atomic_helper.h>
#include <drm/drm_ioctl.h>
#include <drm/drm_managed.h>
#include <drm/drm_probe_helper.h>
#include "display/intel_acpi.h"
#include "display/intel_bw.h"
#include "display/intel_cdclk.h"
#include "display/intel_display_driver.h"
#include "display/intel_display_types.h"
#include "display/intel_dmc.h"
#include "display/intel_dp.h"
#include "display/intel_dpt.h"
#include "display/intel_fbdev.h"
#include "display/intel_hotplug.h"
#include "display/intel_overlay.h"
#include "display/intel_pch_refclk.h"
#include "display/intel_pipe_crc.h"
#include "display/intel_pps.h"
#include "display/intel_sprite.h"
#include "display/intel_vga.h"
#include "display/skl_watermark.h"
#include "gem/i915_gem_context.h"
#include "gem/i915_gem_create.h"
#include "gem/i915_gem_dmabuf.h"
#include "gem/i915_gem_ioctls.h"
#include "gem/i915_gem_mman.h"
#include "gem/i915_gem_pm.h"
#include "gt/intel_gt.h"
#include "gt/intel_gt_pm.h"
#include "gt/intel_rc6.h"
#include "pxp/intel_pxp.h"
#include "pxp/intel_pxp_debugfs.h"
#include "pxp/intel_pxp_pm.h"
#include "soc/intel_dram.h"
#include "soc/intel_gmch.h"
#include "i915_debugfs.h"
#include "i915_driver.h"
#include "i915_drm_client.h"
#include "i915_drv.h"
#include "i915_file_private.h"
#include "i915_getparam.h"
#include "i915_hwmon.h"
#include "i915_ioc32.h"
#include "i915_ioctl.h"
#include "i915_irq.h"
#include "i915_memcpy.h"
#include "i915_perf.h"
#include "i915_query.h"
#include "i915_suspend.h"
#include "i915_switcheroo.h"
#include "i915_sysfs.h"
#include "i915_utils.h"
#include "i915_vgpu.h"
#include "intel_clock_gating.h"
#include "intel_gvt.h"
#include "intel_memory_region.h"
#include "intel_pci_config.h"
#include "intel_pcode.h"
#include "intel_region_ttm.h"
#include "vlv_suspend.h"
static const struct drm_driver i915_drm_driver;
static int i915_workqueues_init(struct drm_i915_private *dev_priv)
{
/*
* The i915 workqueue is primarily used for batched retirement of
* requests (and thus managing bo) once the task has been completed
* by the GPU. i915_retire_requests() is called directly when we
* need high-priority retirement, such as waiting for an explicit
* bo.
*
* It is also used for periodic low-priority events, such as
* idle-timers and recording error state.
*
* All tasks on the workqueue are expected to acquire the dev mutex
* so there is no point in running more than one instance of the
* workqueue at any time. Use an ordered one.
*/
dev_priv->wq = alloc_ordered_workqueue("i915", 0);
if (dev_priv->wq == NULL)
goto out_err;
dev_priv->display.hotplug.dp_wq = alloc_ordered_workqueue("i915-dp", 0);
if (dev_priv->display.hotplug.dp_wq == NULL)
goto out_free_wq;
/*
* The unordered i915 workqueue should be used for all work
* scheduling that do not require running in order, which used
* to be scheduled on the system_wq before moving to a driver
* instance due deprecation of flush_scheduled_work().
*/
dev_priv->unordered_wq = alloc_workqueue("i915-unordered", 0, 0);
if (dev_priv->unordered_wq == NULL)
goto out_free_dp_wq;
return 0;
out_free_dp_wq:
destroy_workqueue(dev_priv->display.hotplug.dp_wq);
out_free_wq:
destroy_workqueue(dev_priv->wq);
out_err:
drm_err(&dev_priv->drm, "Failed to allocate workqueues.\n");
return -ENOMEM;
}
static void i915_workqueues_cleanup(struct drm_i915_private *dev_priv)
{
destroy_workqueue(dev_priv->unordered_wq);
destroy_workqueue(dev_priv->display.hotplug.dp_wq);
destroy_workqueue(dev_priv->wq);
}
/*
* We don't keep the workarounds for pre-production hardware, so we expect our
* driver to fail on these machines in one way or another. A little warning on
* dmesg may help both the user and the bug triagers.
*
* Our policy for removing pre-production workarounds is to keep the
* current gen workarounds as a guide to the bring-up of the next gen
* (workarounds have a habit of persisting!). Anything older than that
* should be removed along with the complications they introduce.
*/
static void intel_detect_preproduction_hw(struct drm_i915_private *dev_priv)
{
bool pre = false;
pre |= IS_HASWELL_EARLY_SDV(dev_priv);
pre |= IS_SKYLAKE(dev_priv) && INTEL_REVID(dev_priv) < 0x6;
pre |= IS_BROXTON(dev_priv) && INTEL_REVID(dev_priv) < 0xA;
pre |= IS_KABYLAKE(dev_priv) && INTEL_REVID(dev_priv) < 0x1;
pre |= IS_GEMINILAKE(dev_priv) && INTEL_REVID(dev_priv) < 0x3;
pre |= IS_ICELAKE(dev_priv) && INTEL_REVID(dev_priv) < 0x7;
pre |= IS_TIGERLAKE(dev_priv) && INTEL_REVID(dev_priv) < 0x1;
pre |= IS_DG1(dev_priv) && INTEL_REVID(dev_priv) < 0x1;
if (pre) {
drm_err(&dev_priv->drm, "This is a pre-production stepping. "
"It may not be fully functional.\n");
add_taint(TAINT_MACHINE_CHECK, LOCKDEP_STILL_OK);
}
}
static void sanitize_gpu(struct drm_i915_private *i915)
{
if (!INTEL_INFO(i915)->gpu_reset_clobbers_display) {
struct intel_gt *gt;
unsigned int i;
for_each_gt(gt, i915, i)
__intel_gt_reset(gt, ALL_ENGINES);
}
}
/**
* i915_driver_early_probe - setup state not requiring device access
* @dev_priv: device private
*
* Initialize everything that is a "SW-only" state, that is state not
* requiring accessing the device or exposing the driver via kernel internal
* or userspace interfaces. Example steps belonging here: lock initialization,
* system memory allocation, setting up device specific attributes and
* function hooks not requiring accessing the device.
*/
static int i915_driver_early_probe(struct drm_i915_private *dev_priv)
{
int ret = 0;
if (i915_inject_probe_failure(dev_priv))
return -ENODEV;
intel_device_info_runtime_init_early(dev_priv);
intel_step_init(dev_priv);
intel_uncore_mmio_debug_init_early(dev_priv);
spin_lock_init(&dev_priv->irq_lock);
spin_lock_init(&dev_priv->gpu_error.lock);
mutex_init(&dev_priv->display.backlight.lock);
mutex_init(&dev_priv->sb_lock);
cpu_latency_qos_add_request(&dev_priv->sb_qos, PM_QOS_DEFAULT_VALUE);
mutex_init(&dev_priv->display.audio.mutex);
mutex_init(&dev_priv->display.wm.wm_mutex);
mutex_init(&dev_priv->display.pps.mutex);
mutex_init(&dev_priv->display.hdcp.hdcp_mutex);
i915_memcpy_init_early(dev_priv);
intel_runtime_pm_init_early(&dev_priv->runtime_pm);
ret = i915_workqueues_init(dev_priv);
if (ret < 0)
return ret;
ret = vlv_suspend_init(dev_priv);
if (ret < 0)
goto err_workqueues;
ret = intel_region_ttm_device_init(dev_priv);
if (ret)
goto err_ttm;
ret = intel_root_gt_init_early(dev_priv);
if (ret < 0)
goto err_rootgt;
i915_gem_init_early(dev_priv);
/* This must be called before any calls to HAS_PCH_* */
intel_detect_pch(dev_priv);
intel_irq_init(dev_priv);
intel_display_driver_early_probe(dev_priv);
intel_clock_gating_hooks_init(dev_priv);
intel_detect_preproduction_hw(dev_priv);
return 0;
err_rootgt:
intel_region_ttm_device_fini(dev_priv);
err_ttm:
vlv_suspend_cleanup(dev_priv);
err_workqueues:
i915_workqueues_cleanup(dev_priv);
return ret;
}
/**
* i915_driver_late_release - cleanup the setup done in
* i915_driver_early_probe()
* @dev_priv: device private
*/
static void i915_driver_late_release(struct drm_i915_private *dev_priv)
{
intel_irq_fini(dev_priv);
intel_power_domains_cleanup(dev_priv);
i915_gem_cleanup_early(dev_priv);
intel_gt_driver_late_release_all(dev_priv);
intel_region_ttm_device_fini(dev_priv);
vlv_suspend_cleanup(dev_priv);
i915_workqueues_cleanup(dev_priv);
cpu_latency_qos_remove_request(&dev_priv->sb_qos);
mutex_destroy(&dev_priv->sb_lock);
i915_params_free(&dev_priv->params);
}
/**
* i915_driver_mmio_probe - setup device MMIO
* @dev_priv: device private
*
* Setup minimal device state necessary for MMIO accesses later in the
* initialization sequence. The setup here should avoid any other device-wide
* side effects or exposing the driver via kernel internal or user space
* interfaces.
*/
static int i915_driver_mmio_probe(struct drm_i915_private *dev_priv)
{
struct intel_gt *gt;
int ret, i;
if (i915_inject_probe_failure(dev_priv))
return -ENODEV;
ret = intel_gmch_bridge_setup(dev_priv);
if (ret < 0)
return ret;
for_each_gt(gt, dev_priv, i) {
ret = intel_uncore_init_mmio(gt->uncore);
if (ret)
return ret;
ret = drmm_add_action_or_reset(&dev_priv->drm,
intel_uncore_fini_mmio,
gt->uncore);
if (ret)
return ret;
}
/* Try to make sure MCHBAR is enabled before poking at it */
intel_gmch_bar_setup(dev_priv);
intel_device_info_runtime_init(dev_priv);
for_each_gt(gt, dev_priv, i) {
ret = intel_gt_init_mmio(gt);
if (ret)
goto err_uncore;
}
/* As early as possible, scrub existing GPU state before clobbering */
sanitize_gpu(dev_priv);
return 0;
err_uncore:
intel_gmch_bar_teardown(dev_priv);
return ret;
}
/**
* i915_driver_mmio_release - cleanup the setup done in i915_driver_mmio_probe()
* @dev_priv: device private
*/
static void i915_driver_mmio_release(struct drm_i915_private *dev_priv)
{
intel_gmch_bar_teardown(dev_priv);
}
/**
* i915_set_dma_info - set all relevant PCI dma info as configured for the
* platform
* @i915: valid i915 instance
*
* Set the dma max segment size, device and coherent masks. The dma mask set
* needs to occur before i915_ggtt_probe_hw.
*
* A couple of platforms have special needs. Address them as well.
*
*/
static int i915_set_dma_info(struct drm_i915_private *i915)
{
unsigned int mask_size = INTEL_INFO(i915)->dma_mask_size;
int ret;
GEM_BUG_ON(!mask_size);
/*
* We don't have a max segment size, so set it to the max so sg's
* debugging layer doesn't complain
*/
dma_set_max_seg_size(i915->drm.dev, UINT_MAX);
ret = dma_set_mask(i915->drm.dev, DMA_BIT_MASK(mask_size));
if (ret)
goto mask_err;
/* overlay on gen2 is broken and can't address above 1G */
if (GRAPHICS_VER(i915) == 2)
mask_size = 30;
/*
* 965GM sometimes incorrectly writes to hardware status page (HWS)
* using 32bit addressing, overwriting memory if HWS is located
* above 4GB.
*
* The documentation also mentions an issue with undefined
* behaviour if any general state is accessed within a page above 4GB,
* which also needs to be handled carefully.
*/
if (IS_I965G(i915) || IS_I965GM(i915))
mask_size = 32;
ret = dma_set_coherent_mask(i915->drm.dev, DMA_BIT_MASK(mask_size));
if (ret)
goto mask_err;
return 0;
mask_err:
drm_err(&i915->drm, "Can't set DMA mask/consistent mask (%d)\n", ret);
return ret;
}
static int i915_pcode_init(struct drm_i915_private *i915)
{
struct intel_gt *gt;
int id, ret;
for_each_gt(gt, i915, id) {
ret = intel_pcode_init(gt->uncore);
if (ret) {
drm_err(>->i915->drm, "gt%d: intel_pcode_init failed %d\n", id, ret);
return ret;
}
}
return 0;
}
/**
* i915_driver_hw_probe - setup state requiring device access
* @dev_priv: device private
*
* Setup state that requires accessing the device, but doesn't require
* exposing the driver via kernel internal or userspace interfaces.
*/
static int i915_driver_hw_probe(struct drm_i915_private *dev_priv)
{
struct pci_dev *pdev = to_pci_dev(dev_priv->drm.dev);
int ret;
if (i915_inject_probe_failure(dev_priv))
return -ENODEV;
if (HAS_PPGTT(dev_priv)) {
if (intel_vgpu_active(dev_priv) &&
!intel_vgpu_has_full_ppgtt(dev_priv)) {
i915_report_error(dev_priv,
"incompatible vGPU found, support for isolated ppGTT required\n");
return -ENXIO;
}
}
if (HAS_EXECLISTS(dev_priv)) {
/*
* Older GVT emulation depends upon intercepting CSB mmio,
* which we no longer use, preferring to use the HWSP cache
* instead.
*/
if (intel_vgpu_active(dev_priv) &&
!intel_vgpu_has_hwsp_emulation(dev_priv)) {
i915_report_error(dev_priv,
"old vGPU host found, support for HWSP emulation required\n");
return -ENXIO;
}
}
/* needs to be done before ggtt probe */
intel_dram_edram_detect(dev_priv);
ret = i915_set_dma_info(dev_priv);
if (ret)
return ret;
ret = i915_perf_init(dev_priv);
if (ret)
return ret;
ret = i915_ggtt_probe_hw(dev_priv);
if (ret)
goto err_perf;
ret = drm_aperture_remove_conflicting_pci_framebuffers(pdev, dev_priv->drm.driver);
if (ret)
goto err_ggtt;
ret = i915_ggtt_init_hw(dev_priv);
if (ret)
goto err_ggtt;
/*
* Make sure we probe lmem before we probe stolen-lmem. The BAR size
* might be different due to bar resizing.
*/
ret = intel_gt_tiles_init(dev_priv);
if (ret)
goto err_ggtt;
ret = intel_memory_regions_hw_probe(dev_priv);
if (ret)
goto err_ggtt;
ret = i915_ggtt_enable_hw(dev_priv);
if (ret) {
drm_err(&dev_priv->drm, "failed to enable GGTT\n");
goto err_mem_regions;
}
pci_set_master(pdev);
/* On the 945G/GM, the chipset reports the MSI capability on the
* integrated graphics even though the support isn't actually there
* according to the published specs. It doesn't appear to function
* correctly in testing on 945G.
* This may be a side effect of MSI having been made available for PEG
* and the registers being closely associated.
*
* According to chipset errata, on the 965GM, MSI interrupts may
* be lost or delayed, and was defeatured. MSI interrupts seem to
* get lost on g4x as well, and interrupt delivery seems to stay
* properly dead afterwards. So we'll just disable them for all
* pre-gen5 chipsets.
*
* dp aux and gmbus irq on gen4 seems to be able to generate legacy
* interrupts even when in MSI mode. This results in spurious
* interrupt warnings if the legacy irq no. is shared with another
* device. The kernel then disables that interrupt source and so
* prevents the other device from working properly.
*/
if (GRAPHICS_VER(dev_priv) >= 5) {
if (pci_enable_msi(pdev) < 0)
drm_dbg(&dev_priv->drm, "can't enable MSI");
}
ret = intel_gvt_init(dev_priv);
if (ret)
goto err_msi;
intel_opregion_setup(dev_priv);
ret = i915_pcode_init(dev_priv);
if (ret)
goto err_opregion;
/*
* Fill the dram structure to get the system dram info. This will be
* used for memory latency calculation.
*/
intel_dram_detect(dev_priv);
intel_bw_init_hw(dev_priv);
return 0;
err_opregion:
intel_opregion_cleanup(dev_priv);
err_msi:
if (pdev->msi_enabled)
pci_disable_msi(pdev);
err_mem_regions:
intel_memory_regions_driver_release(dev_priv);
err_ggtt:
i915_ggtt_driver_release(dev_priv);
i915_gem_drain_freed_objects(dev_priv);
i915_ggtt_driver_late_release(dev_priv);
err_perf:
i915_perf_fini(dev_priv);
return ret;
}
/**
* i915_driver_hw_remove - cleanup the setup done in i915_driver_hw_probe()
* @dev_priv: device private
*/
static void i915_driver_hw_remove(struct drm_i915_private *dev_priv)
{
struct pci_dev *pdev = to_pci_dev(dev_priv->drm.dev);
i915_perf_fini(dev_priv);
intel_opregion_cleanup(dev_priv);
if (pdev->msi_enabled)
pci_disable_msi(pdev);
}
/**
* i915_driver_register - register the driver with the rest of the system
* @dev_priv: device private
*
* Perform any steps necessary to make the driver available via kernel
* internal or userspace interfaces.
*/
static void i915_driver_register(struct drm_i915_private *dev_priv)
{
struct intel_gt *gt;
unsigned int i;
i915_gem_driver_register(dev_priv);
i915_pmu_register(dev_priv);
intel_vgpu_register(dev_priv);
/* Reveal our presence to userspace */
if (drm_dev_register(&dev_priv->drm, 0)) {
drm_err(&dev_priv->drm,
"Failed to register driver for userspace access!\n");
return;
}
i915_debugfs_register(dev_priv);
i915_setup_sysfs(dev_priv);
/* Depends on sysfs having been initialized */
i915_perf_register(dev_priv);
for_each_gt(gt, dev_priv, i)
intel_gt_driver_register(gt);
intel_pxp_debugfs_register(dev_priv->pxp);
i915_hwmon_register(dev_priv);
intel_display_driver_register(dev_priv);
intel_power_domains_enable(dev_priv);
intel_runtime_pm_enable(&dev_priv->runtime_pm);
intel_register_dsm_handler();
if (i915_switcheroo_register(dev_priv))
drm_err(&dev_priv->drm, "Failed to register vga switcheroo!\n");
}
/**
* i915_driver_unregister - cleanup the registration done in i915_driver_regiser()
* @dev_priv: device private
*/
static void i915_driver_unregister(struct drm_i915_private *dev_priv)
{
struct intel_gt *gt;
unsigned int i;
i915_switcheroo_unregister(dev_priv);
intel_unregister_dsm_handler();
intel_runtime_pm_disable(&dev_priv->runtime_pm);
intel_power_domains_disable(dev_priv);
intel_display_driver_unregister(dev_priv);
intel_pxp_fini(dev_priv);
for_each_gt(gt, dev_priv, i)
intel_gt_driver_unregister(gt);
i915_hwmon_unregister(dev_priv);
i915_perf_unregister(dev_priv);
i915_pmu_unregister(dev_priv);
i915_teardown_sysfs(dev_priv);
drm_dev_unplug(&dev_priv->drm);
i915_gem_driver_unregister(dev_priv);
}
void
i915_print_iommu_status(struct drm_i915_private *i915, struct drm_printer *p)
{
drm_printf(p, "iommu: %s\n",
str_enabled_disabled(i915_vtd_active(i915)));
}
static void i915_welcome_messages(struct drm_i915_private *dev_priv)
{
if (drm_debug_enabled(DRM_UT_DRIVER)) {
struct drm_printer p = drm_debug_printer("i915 device info:");
struct intel_gt *gt;
unsigned int i;
drm_printf(&p, "pciid=0x%04x rev=0x%02x platform=%s (subplatform=0x%x) gen=%i\n",
INTEL_DEVID(dev_priv),
INTEL_REVID(dev_priv),
intel_platform_name(INTEL_INFO(dev_priv)->platform),
intel_subplatform(RUNTIME_INFO(dev_priv),
INTEL_INFO(dev_priv)->platform),
GRAPHICS_VER(dev_priv));
intel_device_info_print(INTEL_INFO(dev_priv),
RUNTIME_INFO(dev_priv), &p);
intel_display_device_info_print(DISPLAY_INFO(dev_priv),
DISPLAY_RUNTIME_INFO(dev_priv), &p);
i915_print_iommu_status(dev_priv, &p);
for_each_gt(gt, dev_priv, i)
intel_gt_info_print(>->info, &p);
}
if (IS_ENABLED(CONFIG_DRM_I915_DEBUG))
drm_info(&dev_priv->drm, "DRM_I915_DEBUG enabled\n");
if (IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM))
drm_info(&dev_priv->drm, "DRM_I915_DEBUG_GEM enabled\n");
if (IS_ENABLED(CONFIG_DRM_I915_DEBUG_RUNTIME_PM))
drm_info(&dev_priv->drm,
"DRM_I915_DEBUG_RUNTIME_PM enabled\n");
}
static struct drm_i915_private *
i915_driver_create(struct pci_dev *pdev, const struct pci_device_id *ent)
{
const struct intel_device_info *match_info =
(struct intel_device_info *)ent->driver_data;
struct drm_i915_private *i915;
i915 = devm_drm_dev_alloc(&pdev->dev, &i915_drm_driver,
struct drm_i915_private, drm);
if (IS_ERR(i915))
return i915;
pci_set_drvdata(pdev, i915);
/* Device parameters start as a copy of module parameters. */
i915_params_copy(&i915->params, &i915_modparams);
/* Set up device info and initial runtime info. */
intel_device_info_driver_create(i915, pdev->device, match_info);
return i915;
}
/**
* i915_driver_probe - setup chip and create an initial config
* @pdev: PCI device
* @ent: matching PCI ID entry
*
* The driver probe routine has to do several things:
* - drive output discovery via intel_display_driver_probe()
* - initialize the memory manager
* - allocate initial config memory
* - setup the DRM framebuffer with the allocated memory
*/
int i915_driver_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
struct drm_i915_private *i915;
int ret;
ret = pci_enable_device(pdev);
if (ret) {
pr_err("Failed to enable graphics device: %pe\n", ERR_PTR(ret));
return ret;
}
i915 = i915_driver_create(pdev, ent);
if (IS_ERR(i915)) {
pci_disable_device(pdev);
return PTR_ERR(i915);
}
ret = i915_driver_early_probe(i915);
if (ret < 0)
goto out_pci_disable;
disable_rpm_wakeref_asserts(&i915->runtime_pm);
intel_vgpu_detect(i915);
ret = intel_gt_probe_all(i915);
if (ret < 0)
goto out_runtime_pm_put;
ret = i915_driver_mmio_probe(i915);
if (ret < 0)
goto out_tiles_cleanup;
ret = i915_driver_hw_probe(i915);
if (ret < 0)
goto out_cleanup_mmio;
ret = intel_display_driver_probe_noirq(i915);
if (ret < 0)
goto out_cleanup_hw;
ret = intel_irq_install(i915);
if (ret)
goto out_cleanup_modeset;
ret = intel_display_driver_probe_nogem(i915);
if (ret)
goto out_cleanup_irq;
ret = i915_gem_init(i915);
if (ret)
goto out_cleanup_modeset2;
intel_pxp_init(i915);
ret = intel_display_driver_probe(i915);
if (ret)
goto out_cleanup_gem;
i915_driver_register(i915);
enable_rpm_wakeref_asserts(&i915->runtime_pm);
i915_welcome_messages(i915);
i915->do_release = true;
return 0;
out_cleanup_gem:
i915_gem_suspend(i915);
i915_gem_driver_remove(i915);
i915_gem_driver_release(i915);
out_cleanup_modeset2:
/* FIXME clean up the error path */
intel_display_driver_remove(i915);
intel_irq_uninstall(i915);
intel_display_driver_remove_noirq(i915);
goto out_cleanup_modeset;
out_cleanup_irq:
intel_irq_uninstall(i915);
out_cleanup_modeset:
intel_display_driver_remove_nogem(i915);
out_cleanup_hw:
i915_driver_hw_remove(i915);
intel_memory_regions_driver_release(i915);
i915_ggtt_driver_release(i915);
i915_gem_drain_freed_objects(i915);
i915_ggtt_driver_late_release(i915);
out_cleanup_mmio:
i915_driver_mmio_release(i915);
out_tiles_cleanup:
intel_gt_release_all(i915);
out_runtime_pm_put:
enable_rpm_wakeref_asserts(&i915->runtime_pm);
i915_driver_late_release(i915);
out_pci_disable:
pci_disable_device(pdev);
i915_probe_error(i915, "Device initialization failed (%d)\n", ret);
return ret;
}
void i915_driver_remove(struct drm_i915_private *i915)
{
intel_wakeref_t wakeref;
wakeref = intel_runtime_pm_get(&i915->runtime_pm);
i915_driver_unregister(i915);
/* Flush any external code that still may be under the RCU lock */
synchronize_rcu();
i915_gem_suspend(i915);
intel_gvt_driver_remove(i915);
intel_display_driver_remove(i915);
intel_irq_uninstall(i915);
intel_display_driver_remove_noirq(i915);
i915_reset_error_state(i915);
i915_gem_driver_remove(i915);
intel_display_driver_remove_nogem(i915);
i915_driver_hw_remove(i915);
intel_runtime_pm_put(&i915->runtime_pm, wakeref);
}
static void i915_driver_release(struct drm_device *dev)
{
struct drm_i915_private *dev_priv = to_i915(dev);
struct intel_runtime_pm *rpm = &dev_priv->runtime_pm;
intel_wakeref_t wakeref;
if (!dev_priv->do_release)
return;
wakeref = intel_runtime_pm_get(rpm);
i915_gem_driver_release(dev_priv);
intel_memory_regions_driver_release(dev_priv);
i915_ggtt_driver_release(dev_priv);
i915_gem_drain_freed_objects(dev_priv);
i915_ggtt_driver_late_release(dev_priv);
i915_driver_mmio_release(dev_priv);
intel_runtime_pm_put(rpm, wakeref);
intel_runtime_pm_driver_release(rpm);
i915_driver_late_release(dev_priv);
}
static int i915_driver_open(struct drm_device *dev, struct drm_file *file)
{
struct drm_i915_private *i915 = to_i915(dev);
int ret;
ret = i915_gem_open(i915, file);
if (ret)
return ret;
return 0;
}
/**
* i915_driver_lastclose - clean up after all DRM clients have exited
* @dev: DRM device
*
* Take care of cleaning up after all DRM clients have exited. In the
* mode setting case, we want to restore the kernel's initial mode (just
* in case the last client left us in a bad state).
*
* Additionally, in the non-mode setting case, we'll tear down the GTT
* and DMA structures, since the kernel won't be using them, and clea
* up any GEM state.
*/
static void i915_driver_lastclose(struct drm_device *dev)
{
struct drm_i915_private *i915 = to_i915(dev);
intel_fbdev_restore_mode(i915);
vga_switcheroo_process_delayed_switch();
}
static void i915_driver_postclose(struct drm_device *dev, struct drm_file *file)
{
struct drm_i915_file_private *file_priv = file->driver_priv;
i915_gem_context_close(file);
i915_drm_client_put(file_priv->client);
kfree_rcu(file_priv, rcu);
/* Catch up with all the deferred frees from "this" client */
i915_gem_flush_free_objects(to_i915(dev));
}
static void intel_suspend_encoders(struct drm_i915_private *dev_priv)
{
struct intel_encoder *encoder;
if (!HAS_DISPLAY(dev_priv))
return;
/*
* TODO: check and remove holding the modeset locks if none of
* the encoders depends on this.
*/
drm_modeset_lock_all(&dev_priv->drm);
for_each_intel_encoder(&dev_priv->drm, encoder)
if (encoder->suspend)
encoder->suspend(encoder);
drm_modeset_unlock_all(&dev_priv->drm);
for_each_intel_encoder(&dev_priv->drm, encoder)
if (encoder->suspend_complete)
encoder->suspend_complete(encoder);
}
static void intel_shutdown_encoders(struct drm_i915_private *dev_priv)
{
struct intel_encoder *encoder;
if (!HAS_DISPLAY(dev_priv))
return;
/*
* TODO: check and remove holding the modeset locks if none of
* the encoders depends on this.
*/
drm_modeset_lock_all(&dev_priv->drm);
for_each_intel_encoder(&dev_priv->drm, encoder)
if (encoder->shutdown)
encoder->shutdown(encoder);
drm_modeset_unlock_all(&dev_priv->drm);
for_each_intel_encoder(&dev_priv->drm, encoder)
if (encoder->shutdown_complete)
encoder->shutdown_complete(encoder);
}
void i915_driver_shutdown(struct drm_i915_private *i915)
{
disable_rpm_wakeref_asserts(&i915->runtime_pm);
intel_runtime_pm_disable(&i915->runtime_pm);
intel_power_domains_disable(i915);
if (HAS_DISPLAY(i915)) {
drm_kms_helper_poll_disable(&i915->drm);
drm_atomic_helper_shutdown(&i915->drm);
}
intel_dp_mst_suspend(i915);
intel_runtime_pm_disable_interrupts(i915);
intel_hpd_cancel_work(i915);
intel_suspend_encoders(i915);
intel_shutdown_encoders(i915);
intel_dmc_suspend(i915);
i915_gem_suspend(i915);
/*
* The only requirement is to reboot with display DC states disabled,
* for now leaving all display power wells in the INIT power domain
* enabled.
*
* TODO:
* - unify the pci_driver::shutdown sequence here with the
* pci_driver.driver.pm.poweroff,poweroff_late sequence.
* - unify the driver remove and system/runtime suspend sequences with
* the above unified shutdown/poweroff sequence.
*/
intel_power_domains_driver_remove(i915);
enable_rpm_wakeref_asserts(&i915->runtime_pm);
intel_runtime_pm_driver_release(&i915->runtime_pm);
}
static bool suspend_to_idle(struct drm_i915_private *dev_priv)
{
#if IS_ENABLED(CONFIG_ACPI_SLEEP)
if (acpi_target_system_state() < ACPI_STATE_S3)
return true;
#endif
return false;
}
static void i915_drm_complete(struct drm_device *dev)
{
struct drm_i915_private *i915 = to_i915(dev);
intel_pxp_resume_complete(i915->pxp);
}
static int i915_drm_prepare(struct drm_device *dev)
{
struct drm_i915_private *i915 = to_i915(dev);
intel_pxp_suspend_prepare(i915->pxp);
/*
* NB intel_display_driver_suspend() may issue new requests after we've
* ostensibly marked the GPU as ready-to-sleep here. We need to
* split out that work and pull it forward so that after point,
* the GPU is not woken again.
*/
return i915_gem_backup_suspend(i915);
}
static int i915_drm_suspend(struct drm_device *dev)
{
struct drm_i915_private *dev_priv = to_i915(dev);
struct pci_dev *pdev = to_pci_dev(dev_priv->drm.dev);
pci_power_t opregion_target_state;
disable_rpm_wakeref_asserts(&dev_priv->runtime_pm);
/* We do a lot of poking in a lot of registers, make sure they work
* properly. */
intel_power_domains_disable(dev_priv);
if (HAS_DISPLAY(dev_priv))
drm_kms_helper_poll_disable(dev);
pci_save_state(pdev);
intel_display_driver_suspend(dev_priv);
intel_dp_mst_suspend(dev_priv);
intel_runtime_pm_disable_interrupts(dev_priv);
intel_hpd_cancel_work(dev_priv);
intel_suspend_encoders(dev_priv);
/* Must be called before GGTT is suspended. */
intel_dpt_suspend(dev_priv);
i915_ggtt_suspend(to_gt(dev_priv)->ggtt);
i915_save_display(dev_priv);
opregion_target_state = suspend_to_idle(dev_priv) ? PCI_D1 : PCI_D3cold;
intel_opregion_suspend(dev_priv, opregion_target_state);
intel_fbdev_set_suspend(dev, FBINFO_STATE_SUSPENDED, true);
dev_priv->suspend_count++;
intel_dmc_suspend(dev_priv);
enable_rpm_wakeref_asserts(&dev_priv->runtime_pm);
i915_gem_drain_freed_objects(dev_priv);
return 0;
}
static int i915_drm_suspend_late(struct drm_device *dev, bool hibernation)
{
struct drm_i915_private *dev_priv = to_i915(dev);
struct pci_dev *pdev = to_pci_dev(dev_priv->drm.dev);
struct intel_runtime_pm *rpm = &dev_priv->runtime_pm;
struct intel_gt *gt;
int ret, i;
bool s2idle = !hibernation && suspend_to_idle(dev_priv);
disable_rpm_wakeref_asserts(rpm);
intel_pxp_suspend(dev_priv->pxp);
i915_gem_suspend_late(dev_priv);
for_each_gt(gt, dev_priv, i)
intel_uncore_suspend(gt->uncore);
intel_power_domains_suspend(dev_priv, s2idle);
intel_display_power_suspend_late(dev_priv);
ret = vlv_suspend_complete(dev_priv);
if (ret) {
drm_err(&dev_priv->drm, "Suspend complete failed: %d\n", ret);
intel_power_domains_resume(dev_priv);
goto out;
}
pci_disable_device(pdev);
/*
* During hibernation on some platforms the BIOS may try to access
* the device even though it's already in D3 and hang the machine. So
* leave the device in D0 on those platforms and hope the BIOS will
* power down the device properly. The issue was seen on multiple old
* GENs with different BIOS vendors, so having an explicit blacklist
* is inpractical; apply the workaround on everything pre GEN6. The
* platforms where the issue was seen:
* Lenovo Thinkpad X301, X61s, X60, T60, X41
* Fujitsu FSC S7110
* Acer Aspire 1830T
*/
if (!(hibernation && GRAPHICS_VER(dev_priv) < 6))
pci_set_power_state(pdev, PCI_D3hot);
out:
enable_rpm_wakeref_asserts(rpm);
if (!dev_priv->uncore.user_forcewake_count)
intel_runtime_pm_driver_release(rpm);
return ret;
}
int i915_driver_suspend_switcheroo(struct drm_i915_private *i915,
pm_message_t state)
{
int error;
if (drm_WARN_ON_ONCE(&i915->drm, state.event != PM_EVENT_SUSPEND &&
state.event != PM_EVENT_FREEZE))
return -EINVAL;
if (i915->drm.switch_power_state == DRM_SWITCH_POWER_OFF)
return 0;
error = i915_drm_suspend(&i915->drm);
if (error)
return error;
return i915_drm_suspend_late(&i915->drm, false);
}
static int i915_drm_resume(struct drm_device *dev)
{
struct drm_i915_private *dev_priv = to_i915(dev);
struct intel_gt *gt;
int ret, i;
disable_rpm_wakeref_asserts(&dev_priv->runtime_pm);
ret = i915_pcode_init(dev_priv);
if (ret)
return ret;
sanitize_gpu(dev_priv);
ret = i915_ggtt_enable_hw(dev_priv);
if (ret)
drm_err(&dev_priv->drm, "failed to re-enable GGTT\n");
i915_ggtt_resume(to_gt(dev_priv)->ggtt);
for_each_gt(gt, dev_priv, i)
if (GRAPHICS_VER(gt->i915) >= 8)
setup_private_pat(gt);
/* Must be called after GGTT is resumed. */
intel_dpt_resume(dev_priv);
intel_dmc_resume(dev_priv);
i915_restore_display(dev_priv);
intel_pps_unlock_regs_wa(dev_priv);
intel_init_pch_refclk(dev_priv);
/*
* Interrupts have to be enabled before any batches are run. If not the
* GPU will hang. i915_gem_init_hw() will initiate batches to
* update/restore the context.
*
* drm_mode_config_reset() needs AUX interrupts.
*
* Modeset enabling in intel_display_driver_init_hw() also needs working
* interrupts.
*/
intel_runtime_pm_enable_interrupts(dev_priv);
if (HAS_DISPLAY(dev_priv))
drm_mode_config_reset(dev);
i915_gem_resume(dev_priv);
intel_display_driver_init_hw(dev_priv);
intel_clock_gating_init(dev_priv);
intel_hpd_init(dev_priv);
/* MST sideband requires HPD interrupts enabled */
intel_dp_mst_resume(dev_priv);
intel_display_driver_resume(dev_priv);
intel_hpd_poll_disable(dev_priv);
if (HAS_DISPLAY(dev_priv))
drm_kms_helper_poll_enable(dev);
intel_opregion_resume(dev_priv);
intel_fbdev_set_suspend(dev, FBINFO_STATE_RUNNING, false);
intel_power_domains_enable(dev_priv);
intel_gvt_resume(dev_priv);
enable_rpm_wakeref_asserts(&dev_priv->runtime_pm);
return 0;
}
static int i915_drm_resume_early(struct drm_device *dev)
{
struct drm_i915_private *dev_priv = to_i915(dev);
struct pci_dev *pdev = to_pci_dev(dev_priv->drm.dev);
struct intel_gt *gt;
int ret, i;
/*
* We have a resume ordering issue with the snd-hda driver also
* requiring our device to be power up. Due to the lack of a
* parent/child relationship we currently solve this with an early
* resume hook.
*
* FIXME: This should be solved with a special hdmi sink device or
* similar so that power domains can be employed.
*/
/*
* Note that we need to set the power state explicitly, since we
* powered off the device during freeze and the PCI core won't power
* it back up for us during thaw. Powering off the device during
* freeze is not a hard requirement though, and during the
* suspend/resume phases the PCI core makes sure we get here with the
* device powered on. So in case we change our freeze logic and keep
* the device powered we can also remove the following set power state
* call.
*/
ret = pci_set_power_state(pdev, PCI_D0);
if (ret) {
drm_err(&dev_priv->drm,
"failed to set PCI D0 power state (%d)\n", ret);
return ret;
}
/*
* Note that pci_enable_device() first enables any parent bridge
* device and only then sets the power state for this device. The
* bridge enabling is a nop though, since bridge devices are resumed
* first. The order of enabling power and enabling the device is
* imposed by the PCI core as described above, so here we preserve the
* same order for the freeze/thaw phases.
*
* TODO: eventually we should remove pci_disable_device() /
* pci_enable_enable_device() from suspend/resume. Due to how they
* depend on the device enable refcount we can't anyway depend on them
* disabling/enabling the device.
*/
if (pci_enable_device(pdev))
return -EIO;
pci_set_master(pdev);
disable_rpm_wakeref_asserts(&dev_priv->runtime_pm);
ret = vlv_resume_prepare(dev_priv, false);
if (ret)
drm_err(&dev_priv->drm,
"Resume prepare failed: %d, continuing anyway\n", ret);
for_each_gt(gt, dev_priv, i) {
intel_uncore_resume_early(gt->uncore);
intel_gt_check_and_clear_faults(gt);
}
intel_display_power_resume_early(dev_priv);
intel_power_domains_resume(dev_priv);
enable_rpm_wakeref_asserts(&dev_priv->runtime_pm);
return ret;
}
int i915_driver_resume_switcheroo(struct drm_i915_private *i915)
{
int ret;
if (i915->drm.switch_power_state == DRM_SWITCH_POWER_OFF)
return 0;
ret = i915_drm_resume_early(&i915->drm);
if (ret)
return ret;
return i915_drm_resume(&i915->drm);
}
static int i915_pm_prepare(struct device *kdev)
{
struct drm_i915_private *i915 = kdev_to_i915(kdev);
if (!i915) {
dev_err(kdev, "DRM not initialized, aborting suspend.\n");
return -ENODEV;
}
if (i915->drm.switch_power_state == DRM_SWITCH_POWER_OFF)
return 0;
return i915_drm_prepare(&i915->drm);
}
static int i915_pm_suspend(struct device *kdev)
{
struct drm_i915_private *i915 = kdev_to_i915(kdev);
if (!i915) {
dev_err(kdev, "DRM not initialized, aborting suspend.\n");
return -ENODEV;
}
if (i915->drm.switch_power_state == DRM_SWITCH_POWER_OFF)
return 0;
return i915_drm_suspend(&i915->drm);
}
static int i915_pm_suspend_late(struct device *kdev)
{
struct drm_i915_private *i915 = kdev_to_i915(kdev);
/*
* We have a suspend ordering issue with the snd-hda driver also
* requiring our device to be power up. Due to the lack of a
* parent/child relationship we currently solve this with an late
* suspend hook.
*
* FIXME: This should be solved with a special hdmi sink device or
* similar so that power domains can be employed.
*/
if (i915->drm.switch_power_state == DRM_SWITCH_POWER_OFF)
return 0;
return i915_drm_suspend_late(&i915->drm, false);
}
static int i915_pm_poweroff_late(struct device *kdev)
{
struct drm_i915_private *i915 = kdev_to_i915(kdev);
if (i915->drm.switch_power_state == DRM_SWITCH_POWER_OFF)
return 0;
return i915_drm_suspend_late(&i915->drm, true);
}
static int i915_pm_resume_early(struct device *kdev)
{
struct drm_i915_private *i915 = kdev_to_i915(kdev);
if (i915->drm.switch_power_state == DRM_SWITCH_POWER_OFF)
return 0;
return i915_drm_resume_early(&i915->drm);
}
static int i915_pm_resume(struct device *kdev)
{
struct drm_i915_private *i915 = kdev_to_i915(kdev);
if (i915->drm.switch_power_state == DRM_SWITCH_POWER_OFF)
return 0;
return i915_drm_resume(&i915->drm);
}
static void i915_pm_complete(struct device *kdev)
{
struct drm_i915_private *i915 = kdev_to_i915(kdev);
if (i915->drm.switch_power_state == DRM_SWITCH_POWER_OFF)
return;
i915_drm_complete(&i915->drm);
}
/* freeze: before creating the hibernation_image */
static int i915_pm_freeze(struct device *kdev)
{
struct drm_i915_private *i915 = kdev_to_i915(kdev);
int ret;
if (i915->drm.switch_power_state != DRM_SWITCH_POWER_OFF) {
ret = i915_drm_suspend(&i915->drm);
if (ret)
return ret;
}
ret = i915_gem_freeze(i915);
if (ret)
return ret;
return 0;
}
static int i915_pm_freeze_late(struct device *kdev)
{
struct drm_i915_private *i915 = kdev_to_i915(kdev);
int ret;
if (i915->drm.switch_power_state != DRM_SWITCH_POWER_OFF) {
ret = i915_drm_suspend_late(&i915->drm, true);
if (ret)
return ret;
}
ret = i915_gem_freeze_late(i915);
if (ret)
return ret;
return 0;
}
/* thaw: called after creating the hibernation image, but before turning off. */
static int i915_pm_thaw_early(struct device *kdev)
{
return i915_pm_resume_early(kdev);
}
static int i915_pm_thaw(struct device *kdev)
{
return i915_pm_resume(kdev);
}
/* restore: called after loading the hibernation image. */
static int i915_pm_restore_early(struct device *kdev)
{
return i915_pm_resume_early(kdev);
}
static int i915_pm_restore(struct device *kdev)
{
return i915_pm_resume(kdev);
}
static int intel_runtime_suspend(struct device *kdev)
{
struct drm_i915_private *dev_priv = kdev_to_i915(kdev);
struct intel_runtime_pm *rpm = &dev_priv->runtime_pm;
struct pci_dev *pdev = to_pci_dev(dev_priv->drm.dev);
struct pci_dev *root_pdev;
struct intel_gt *gt;
int ret, i;
if (drm_WARN_ON_ONCE(&dev_priv->drm, !HAS_RUNTIME_PM(dev_priv)))
return -ENODEV;
drm_dbg(&dev_priv->drm, "Suspending device\n");
disable_rpm_wakeref_asserts(rpm);
/*
* We are safe here against re-faults, since the fault handler takes
* an RPM reference.
*/
i915_gem_runtime_suspend(dev_priv);
intel_pxp_runtime_suspend(dev_priv->pxp);
for_each_gt(gt, dev_priv, i)
intel_gt_runtime_suspend(gt);
intel_runtime_pm_disable_interrupts(dev_priv);
for_each_gt(gt, dev_priv, i)
intel_uncore_suspend(gt->uncore);
intel_display_power_suspend(dev_priv);
ret = vlv_suspend_complete(dev_priv);
if (ret) {
drm_err(&dev_priv->drm,
"Runtime suspend failed, disabling it (%d)\n", ret);
intel_uncore_runtime_resume(&dev_priv->uncore);
intel_runtime_pm_enable_interrupts(dev_priv);
for_each_gt(gt, dev_priv, i)
intel_gt_runtime_resume(gt);
enable_rpm_wakeref_asserts(rpm);
return ret;
}
enable_rpm_wakeref_asserts(rpm);
intel_runtime_pm_driver_release(rpm);
if (intel_uncore_arm_unclaimed_mmio_detection(&dev_priv->uncore))
drm_err(&dev_priv->drm,
"Unclaimed access detected prior to suspending\n");
/*
* FIXME: Temporary hammer to avoid freezing the machine on our DGFX
* This should be totally removed when we handle the pci states properly
* on runtime PM.
*/
root_pdev = pcie_find_root_port(pdev);
if (root_pdev)
pci_d3cold_disable(root_pdev);
rpm->suspended = true;
/*
* FIXME: We really should find a document that references the arguments
* used below!
*/
if (IS_BROADWELL(dev_priv)) {
/*
* On Broadwell, if we use PCI_D1 the PCH DDI ports will stop
* being detected, and the call we do at intel_runtime_resume()
* won't be able to restore them. Since PCI_D3hot matches the
* actual specification and appears to be working, use it.
*/
intel_opregion_notify_adapter(dev_priv, PCI_D3hot);
} else {
/*
* current versions of firmware which depend on this opregion
* notification have repurposed the D1 definition to mean
* "runtime suspended" vs. what you would normally expect (D3)
* to distinguish it from notifications that might be sent via
* the suspend path.
*/
intel_opregion_notify_adapter(dev_priv, PCI_D1);
}
assert_forcewakes_inactive(&dev_priv->uncore);
if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv))
intel_hpd_poll_enable(dev_priv);
drm_dbg(&dev_priv->drm, "Device suspended\n");
return 0;
}
static int intel_runtime_resume(struct device *kdev)
{
struct drm_i915_private *dev_priv = kdev_to_i915(kdev);
struct intel_runtime_pm *rpm = &dev_priv->runtime_pm;
struct pci_dev *pdev = to_pci_dev(dev_priv->drm.dev);
struct pci_dev *root_pdev;
struct intel_gt *gt;
int ret, i;
if (drm_WARN_ON_ONCE(&dev_priv->drm, !HAS_RUNTIME_PM(dev_priv)))
return -ENODEV;
drm_dbg(&dev_priv->drm, "Resuming device\n");
drm_WARN_ON_ONCE(&dev_priv->drm, atomic_read(&rpm->wakeref_count));
disable_rpm_wakeref_asserts(rpm);
intel_opregion_notify_adapter(dev_priv, PCI_D0);
rpm->suspended = false;
root_pdev = pcie_find_root_port(pdev);
if (root_pdev)
pci_d3cold_enable(root_pdev);
if (intel_uncore_unclaimed_mmio(&dev_priv->uncore))
drm_dbg(&dev_priv->drm,
"Unclaimed access during suspend, bios?\n");
intel_display_power_resume(dev_priv);
ret = vlv_resume_prepare(dev_priv, true);
for_each_gt(gt, dev_priv, i)
intel_uncore_runtime_resume(gt->uncore);
intel_runtime_pm_enable_interrupts(dev_priv);
/*
* No point of rolling back things in case of an error, as the best
* we can do is to hope that things will still work (and disable RPM).
*/
for_each_gt(gt, dev_priv, i)
intel_gt_runtime_resume(gt);
intel_pxp_runtime_resume(dev_priv->pxp);
/*
* On VLV/CHV display interrupts are part of the display
* power well, so hpd is reinitialized from there. For
* everyone else do it here.
*/
if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv)) {
intel_hpd_init(dev_priv);
intel_hpd_poll_disable(dev_priv);
}
skl_watermark_ipc_update(dev_priv);
enable_rpm_wakeref_asserts(rpm);
if (ret)
drm_err(&dev_priv->drm,
"Runtime resume failed, disabling it (%d)\n", ret);
else
drm_dbg(&dev_priv->drm, "Device resumed\n");
return ret;
}
const struct dev_pm_ops i915_pm_ops = {
/*
* S0ix (via system suspend) and S3 event handlers [PMSG_SUSPEND,
* PMSG_RESUME]
*/
.prepare = i915_pm_prepare,
.suspend = i915_pm_suspend,
.suspend_late = i915_pm_suspend_late,
.resume_early = i915_pm_resume_early,
.resume = i915_pm_resume,
.complete = i915_pm_complete,
/*
* S4 event handlers
* @freeze, @freeze_late : called (1) before creating the
* hibernation image [PMSG_FREEZE] and
* (2) after rebooting, before restoring
* the image [PMSG_QUIESCE]
* @thaw, @thaw_early : called (1) after creating the hibernation
* image, before writing it [PMSG_THAW]
* and (2) after failing to create or
* restore the image [PMSG_RECOVER]
* @poweroff, @poweroff_late: called after writing the hibernation
* image, before rebooting [PMSG_HIBERNATE]
* @restore, @restore_early : called after rebooting and restoring the
* hibernation image [PMSG_RESTORE]
*/
.freeze = i915_pm_freeze,
.freeze_late = i915_pm_freeze_late,
.thaw_early = i915_pm_thaw_early,
.thaw = i915_pm_thaw,
.poweroff = i915_pm_suspend,
.poweroff_late = i915_pm_poweroff_late,
.restore_early = i915_pm_restore_early,
.restore = i915_pm_restore,
/* S0ix (via runtime suspend) event handlers */
.runtime_suspend = intel_runtime_suspend,
.runtime_resume = intel_runtime_resume,
};
static const struct file_operations i915_driver_fops = {
.owner = THIS_MODULE,
.open = drm_open,
.release = drm_release_noglobal,
.unlocked_ioctl = drm_ioctl,
.mmap = i915_gem_mmap,
.poll = drm_poll,
.read = drm_read,
.compat_ioctl = i915_ioc32_compat_ioctl,
.llseek = noop_llseek,
#ifdef CONFIG_PROC_FS
.show_fdinfo = drm_show_fdinfo,
#endif
};
static int
i915_gem_reject_pin_ioctl(struct drm_device *dev, void *data,
struct drm_file *file)
{
return -ENODEV;
}
static const struct drm_ioctl_desc i915_ioctls[] = {
DRM_IOCTL_DEF_DRV(I915_INIT, drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
DRM_IOCTL_DEF_DRV(I915_FLUSH, drm_noop, DRM_AUTH),
DRM_IOCTL_DEF_DRV(I915_FLIP, drm_noop, DRM_AUTH),
DRM_IOCTL_DEF_DRV(I915_BATCHBUFFER, drm_noop, DRM_AUTH),
DRM_IOCTL_DEF_DRV(I915_IRQ_EMIT, drm_noop, DRM_AUTH),
DRM_IOCTL_DEF_DRV(I915_IRQ_WAIT, drm_noop, DRM_AUTH),
DRM_IOCTL_DEF_DRV(I915_GETPARAM, i915_getparam_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_SETPARAM, drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
DRM_IOCTL_DEF_DRV(I915_ALLOC, drm_noop, DRM_AUTH),
DRM_IOCTL_DEF_DRV(I915_FREE, drm_noop, DRM_AUTH),
DRM_IOCTL_DEF_DRV(I915_INIT_HEAP, drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
DRM_IOCTL_DEF_DRV(I915_CMDBUFFER, drm_noop, DRM_AUTH),
DRM_IOCTL_DEF_DRV(I915_DESTROY_HEAP, drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
DRM_IOCTL_DEF_DRV(I915_SET_VBLANK_PIPE, drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
DRM_IOCTL_DEF_DRV(I915_GET_VBLANK_PIPE, drm_noop, DRM_AUTH),
DRM_IOCTL_DEF_DRV(I915_VBLANK_SWAP, drm_noop, DRM_AUTH),
DRM_IOCTL_DEF_DRV(I915_HWS_ADDR, drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
DRM_IOCTL_DEF_DRV(I915_GEM_INIT, drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
DRM_IOCTL_DEF_DRV(I915_GEM_EXECBUFFER, drm_invalid_op, DRM_AUTH),
DRM_IOCTL_DEF_DRV(I915_GEM_EXECBUFFER2_WR, i915_gem_execbuffer2_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GEM_PIN, i915_gem_reject_pin_ioctl, DRM_AUTH|DRM_ROOT_ONLY),
DRM_IOCTL_DEF_DRV(I915_GEM_UNPIN, i915_gem_reject_pin_ioctl, DRM_AUTH|DRM_ROOT_ONLY),
DRM_IOCTL_DEF_DRV(I915_GEM_BUSY, i915_gem_busy_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GEM_SET_CACHING, i915_gem_set_caching_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GEM_GET_CACHING, i915_gem_get_caching_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GEM_THROTTLE, i915_gem_throttle_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GEM_ENTERVT, drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
DRM_IOCTL_DEF_DRV(I915_GEM_LEAVEVT, drm_noop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
DRM_IOCTL_DEF_DRV(I915_GEM_CREATE, i915_gem_create_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GEM_CREATE_EXT, i915_gem_create_ext_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GEM_PREAD, i915_gem_pread_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GEM_PWRITE, i915_gem_pwrite_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GEM_MMAP, i915_gem_mmap_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GEM_MMAP_OFFSET, i915_gem_mmap_offset_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GEM_SET_DOMAIN, i915_gem_set_domain_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GEM_SW_FINISH, i915_gem_sw_finish_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GEM_SET_TILING, i915_gem_set_tiling_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GEM_GET_TILING, i915_gem_get_tiling_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GEM_GET_APERTURE, i915_gem_get_aperture_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GET_PIPE_FROM_CRTC_ID, intel_get_pipe_from_crtc_id_ioctl, 0),
DRM_IOCTL_DEF_DRV(I915_GEM_MADVISE, i915_gem_madvise_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_OVERLAY_PUT_IMAGE, intel_overlay_put_image_ioctl, DRM_MASTER),
DRM_IOCTL_DEF_DRV(I915_OVERLAY_ATTRS, intel_overlay_attrs_ioctl, DRM_MASTER),
DRM_IOCTL_DEF_DRV(I915_SET_SPRITE_COLORKEY, intel_sprite_set_colorkey_ioctl, DRM_MASTER),
DRM_IOCTL_DEF_DRV(I915_GET_SPRITE_COLORKEY, drm_noop, DRM_MASTER),
DRM_IOCTL_DEF_DRV(I915_GEM_WAIT, i915_gem_wait_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GEM_CONTEXT_CREATE_EXT, i915_gem_context_create_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GEM_CONTEXT_DESTROY, i915_gem_context_destroy_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_REG_READ, i915_reg_read_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GET_RESET_STATS, i915_gem_context_reset_stats_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GEM_USERPTR, i915_gem_userptr_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GEM_CONTEXT_GETPARAM, i915_gem_context_getparam_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GEM_CONTEXT_SETPARAM, i915_gem_context_setparam_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_PERF_OPEN, i915_perf_open_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_PERF_ADD_CONFIG, i915_perf_add_config_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_PERF_REMOVE_CONFIG, i915_perf_remove_config_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_QUERY, i915_query_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GEM_VM_CREATE, i915_gem_vm_create_ioctl, DRM_RENDER_ALLOW),
DRM_IOCTL_DEF_DRV(I915_GEM_VM_DESTROY, i915_gem_vm_destroy_ioctl, DRM_RENDER_ALLOW),
};
/*
* Interface history:
*
* 1.1: Original.
* 1.2: Add Power Management
* 1.3: Add vblank support
* 1.4: Fix cmdbuffer path, add heap destroy
* 1.5: Add vblank pipe configuration
* 1.6: - New ioctl for scheduling buffer swaps on vertical blank
* - Support vertical blank on secondary display pipe
*/
#define DRIVER_MAJOR 1
#define DRIVER_MINOR 6
#define DRIVER_PATCHLEVEL 0
static const struct drm_driver i915_drm_driver = {
/* Don't use MTRRs here; the Xserver or userspace app should
* deal with them for Intel hardware.
*/
.driver_features =
DRIVER_GEM |
DRIVER_RENDER | DRIVER_MODESET | DRIVER_ATOMIC | DRIVER_SYNCOBJ |
DRIVER_SYNCOBJ_TIMELINE,
.release = i915_driver_release,
.open = i915_driver_open,
.lastclose = i915_driver_lastclose,
.postclose = i915_driver_postclose,
.show_fdinfo = PTR_IF(IS_ENABLED(CONFIG_PROC_FS), i915_drm_client_fdinfo),
.gem_prime_import = i915_gem_prime_import,
.dumb_create = i915_gem_dumb_create,
.dumb_map_offset = i915_gem_dumb_mmap_offset,
.ioctls = i915_ioctls,
.num_ioctls = ARRAY_SIZE(i915_ioctls),
.fops = &i915_driver_fops,
.name = DRIVER_NAME,
.desc = DRIVER_DESC,
.date = DRIVER_DATE,
.major = DRIVER_MAJOR,
.minor = DRIVER_MINOR,
.patchlevel = DRIVER_PATCHLEVEL,
};
| linux-master | drivers/gpu/drm/i915/i915_driver.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2022 Intel Corporation
*/
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/types.h>
#include "i915_drv.h"
#include "i915_hwmon.h"
#include "i915_reg.h"
#include "intel_mchbar_regs.h"
#include "intel_pcode.h"
#include "gt/intel_gt.h"
#include "gt/intel_gt_regs.h"
/*
* SF_* - scale factors for particular quantities according to hwmon spec.
* - voltage - millivolts
* - power - microwatts
* - curr - milliamperes
* - energy - microjoules
* - time - milliseconds
*/
#define SF_VOLTAGE 1000
#define SF_POWER 1000000
#define SF_CURR 1000
#define SF_ENERGY 1000000
#define SF_TIME 1000
struct hwm_reg {
i915_reg_t gt_perf_status;
i915_reg_t pkg_power_sku_unit;
i915_reg_t pkg_power_sku;
i915_reg_t pkg_rapl_limit;
i915_reg_t energy_status_all;
i915_reg_t energy_status_tile;
};
struct hwm_energy_info {
u32 reg_val_prev;
long accum_energy; /* Accumulated energy for energy1_input */
};
struct hwm_drvdata {
struct i915_hwmon *hwmon;
struct intel_uncore *uncore;
struct device *hwmon_dev;
struct hwm_energy_info ei; /* Energy info for energy1_input */
char name[12];
int gt_n;
bool reset_in_progress;
wait_queue_head_t waitq;
};
struct i915_hwmon {
struct hwm_drvdata ddat;
struct hwm_drvdata ddat_gt[I915_MAX_GT];
struct mutex hwmon_lock; /* counter overflow logic and rmw */
struct hwm_reg rg;
int scl_shift_power;
int scl_shift_energy;
int scl_shift_time;
};
static void
hwm_locked_with_pm_intel_uncore_rmw(struct hwm_drvdata *ddat,
i915_reg_t reg, u32 clear, u32 set)
{
struct i915_hwmon *hwmon = ddat->hwmon;
struct intel_uncore *uncore = ddat->uncore;
intel_wakeref_t wakeref;
mutex_lock(&hwmon->hwmon_lock);
with_intel_runtime_pm(uncore->rpm, wakeref)
intel_uncore_rmw(uncore, reg, clear, set);
mutex_unlock(&hwmon->hwmon_lock);
}
/*
* This function's return type of u64 allows for the case where the scaling
* of the field taken from the 32-bit register value might cause a result to
* exceed 32 bits.
*/
static u64
hwm_field_read_and_scale(struct hwm_drvdata *ddat, i915_reg_t rgadr,
u32 field_msk, int nshift, u32 scale_factor)
{
struct intel_uncore *uncore = ddat->uncore;
intel_wakeref_t wakeref;
u32 reg_value;
with_intel_runtime_pm(uncore->rpm, wakeref)
reg_value = intel_uncore_read(uncore, rgadr);
reg_value = REG_FIELD_GET(field_msk, reg_value);
return mul_u64_u32_shr(reg_value, scale_factor, nshift);
}
/*
* hwm_energy - Obtain energy value
*
* The underlying energy hardware register is 32-bits and is subject to
* overflow. How long before overflow? For example, with an example
* scaling bit shift of 14 bits (see register *PACKAGE_POWER_SKU_UNIT) and
* a power draw of 1000 watts, the 32-bit counter will overflow in
* approximately 4.36 minutes.
*
* Examples:
* 1 watt: (2^32 >> 14) / 1 W / (60 * 60 * 24) secs/day -> 3 days
* 1000 watts: (2^32 >> 14) / 1000 W / 60 secs/min -> 4.36 minutes
*
* The function significantly increases overflow duration (from 4.36
* minutes) by accumulating the energy register into a 'long' as allowed by
* the hwmon API. Using x86_64 128 bit arithmetic (see mul_u64_u32_shr()),
* a 'long' of 63 bits, SF_ENERGY of 1e6 (~20 bits) and
* hwmon->scl_shift_energy of 14 bits we have 57 (63 - 20 + 14) bits before
* energy1_input overflows. This at 1000 W is an overflow duration of 278 years.
*/
static void
hwm_energy(struct hwm_drvdata *ddat, long *energy)
{
struct intel_uncore *uncore = ddat->uncore;
struct i915_hwmon *hwmon = ddat->hwmon;
struct hwm_energy_info *ei = &ddat->ei;
intel_wakeref_t wakeref;
i915_reg_t rgaddr;
u32 reg_val;
if (ddat->gt_n >= 0)
rgaddr = hwmon->rg.energy_status_tile;
else
rgaddr = hwmon->rg.energy_status_all;
mutex_lock(&hwmon->hwmon_lock);
with_intel_runtime_pm(uncore->rpm, wakeref)
reg_val = intel_uncore_read(uncore, rgaddr);
if (reg_val >= ei->reg_val_prev)
ei->accum_energy += reg_val - ei->reg_val_prev;
else
ei->accum_energy += UINT_MAX - ei->reg_val_prev + reg_val;
ei->reg_val_prev = reg_val;
*energy = mul_u64_u32_shr(ei->accum_energy, SF_ENERGY,
hwmon->scl_shift_energy);
mutex_unlock(&hwmon->hwmon_lock);
}
static ssize_t
hwm_power1_max_interval_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct hwm_drvdata *ddat = dev_get_drvdata(dev);
struct i915_hwmon *hwmon = ddat->hwmon;
intel_wakeref_t wakeref;
u32 r, x, y, x_w = 2; /* 2 bits */
u64 tau4, out;
with_intel_runtime_pm(ddat->uncore->rpm, wakeref)
r = intel_uncore_read(ddat->uncore, hwmon->rg.pkg_rapl_limit);
x = REG_FIELD_GET(PKG_PWR_LIM_1_TIME_X, r);
y = REG_FIELD_GET(PKG_PWR_LIM_1_TIME_Y, r);
/*
* tau = 1.x * power(2,y), x = bits(23:22), y = bits(21:17)
* = (4 | x) << (y - 2)
* where (y - 2) ensures a 1.x fixed point representation of 1.x
* However because y can be < 2, we compute
* tau4 = (4 | x) << y
* but add 2 when doing the final right shift to account for units
*/
tau4 = ((1 << x_w) | x) << y;
/* val in hwmon interface units (millisec) */
out = mul_u64_u32_shr(tau4, SF_TIME, hwmon->scl_shift_time + x_w);
return sysfs_emit(buf, "%llu\n", out);
}
static ssize_t
hwm_power1_max_interval_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct hwm_drvdata *ddat = dev_get_drvdata(dev);
struct i915_hwmon *hwmon = ddat->hwmon;
u32 x, y, rxy, x_w = 2; /* 2 bits */
u64 tau4, r, max_win;
unsigned long val;
int ret;
ret = kstrtoul(buf, 0, &val);
if (ret)
return ret;
/*
* Max HW supported tau in '1.x * power(2,y)' format, x = 0, y = 0x12
* The hwmon->scl_shift_time default of 0xa results in a max tau of 256 seconds
*/
#define PKG_MAX_WIN_DEFAULT 0x12ull
/*
* val must be < max in hwmon interface units. The steps below are
* explained in i915_power1_max_interval_show()
*/
r = FIELD_PREP(PKG_MAX_WIN, PKG_MAX_WIN_DEFAULT);
x = REG_FIELD_GET(PKG_MAX_WIN_X, r);
y = REG_FIELD_GET(PKG_MAX_WIN_Y, r);
tau4 = ((1 << x_w) | x) << y;
max_win = mul_u64_u32_shr(tau4, SF_TIME, hwmon->scl_shift_time + x_w);
if (val > max_win)
return -EINVAL;
/* val in hw units */
val = DIV_ROUND_CLOSEST_ULL((u64)val << hwmon->scl_shift_time, SF_TIME);
/* Convert to 1.x * power(2,y) */
if (!val) {
/* Avoid ilog2(0) */
y = 0;
x = 0;
} else {
y = ilog2(val);
/* x = (val - (1 << y)) >> (y - 2); */
x = (val - (1ul << y)) << x_w >> y;
}
rxy = REG_FIELD_PREP(PKG_PWR_LIM_1_TIME_X, x) | REG_FIELD_PREP(PKG_PWR_LIM_1_TIME_Y, y);
hwm_locked_with_pm_intel_uncore_rmw(ddat, hwmon->rg.pkg_rapl_limit,
PKG_PWR_LIM_1_TIME, rxy);
return count;
}
static SENSOR_DEVICE_ATTR(power1_max_interval, 0664,
hwm_power1_max_interval_show,
hwm_power1_max_interval_store, 0);
static struct attribute *hwm_attributes[] = {
&sensor_dev_attr_power1_max_interval.dev_attr.attr,
NULL
};
static umode_t hwm_attributes_visible(struct kobject *kobj,
struct attribute *attr, int index)
{
struct device *dev = kobj_to_dev(kobj);
struct hwm_drvdata *ddat = dev_get_drvdata(dev);
struct i915_hwmon *hwmon = ddat->hwmon;
if (attr == &sensor_dev_attr_power1_max_interval.dev_attr.attr)
return i915_mmio_reg_valid(hwmon->rg.pkg_rapl_limit) ? attr->mode : 0;
return 0;
}
static const struct attribute_group hwm_attrgroup = {
.attrs = hwm_attributes,
.is_visible = hwm_attributes_visible,
};
static const struct attribute_group *hwm_groups[] = {
&hwm_attrgroup,
NULL
};
static const struct hwmon_channel_info * const hwm_info[] = {
HWMON_CHANNEL_INFO(in, HWMON_I_INPUT),
HWMON_CHANNEL_INFO(power, HWMON_P_MAX | HWMON_P_RATED_MAX | HWMON_P_CRIT),
HWMON_CHANNEL_INFO(energy, HWMON_E_INPUT),
HWMON_CHANNEL_INFO(curr, HWMON_C_CRIT),
NULL
};
static const struct hwmon_channel_info * const hwm_gt_info[] = {
HWMON_CHANNEL_INFO(energy, HWMON_E_INPUT),
NULL
};
/* I1 is exposed as power_crit or as curr_crit depending on bit 31 */
static int hwm_pcode_read_i1(struct drm_i915_private *i915, u32 *uval)
{
/* Avoid ILLEGAL_SUBCOMMAND "mailbox access failed" warning in snb_pcode_read */
if (IS_DG1(i915) || IS_DG2(i915))
return -ENXIO;
return snb_pcode_read_p(&i915->uncore, PCODE_POWER_SETUP,
POWER_SETUP_SUBCOMMAND_READ_I1, 0, uval);
}
static int hwm_pcode_write_i1(struct drm_i915_private *i915, u32 uval)
{
return snb_pcode_write_p(&i915->uncore, PCODE_POWER_SETUP,
POWER_SETUP_SUBCOMMAND_WRITE_I1, 0, uval);
}
static umode_t
hwm_in_is_visible(const struct hwm_drvdata *ddat, u32 attr)
{
struct drm_i915_private *i915 = ddat->uncore->i915;
switch (attr) {
case hwmon_in_input:
return IS_DG1(i915) || IS_DG2(i915) ? 0444 : 0;
default:
return 0;
}
}
static int
hwm_in_read(struct hwm_drvdata *ddat, u32 attr, long *val)
{
struct i915_hwmon *hwmon = ddat->hwmon;
intel_wakeref_t wakeref;
u32 reg_value;
switch (attr) {
case hwmon_in_input:
with_intel_runtime_pm(ddat->uncore->rpm, wakeref)
reg_value = intel_uncore_read(ddat->uncore, hwmon->rg.gt_perf_status);
/* HW register value in units of 2.5 millivolt */
*val = DIV_ROUND_CLOSEST(REG_FIELD_GET(GEN12_VOLTAGE_MASK, reg_value) * 25, 10);
return 0;
default:
return -EOPNOTSUPP;
}
}
static umode_t
hwm_power_is_visible(const struct hwm_drvdata *ddat, u32 attr, int chan)
{
struct drm_i915_private *i915 = ddat->uncore->i915;
struct i915_hwmon *hwmon = ddat->hwmon;
u32 uval;
switch (attr) {
case hwmon_power_max:
return i915_mmio_reg_valid(hwmon->rg.pkg_rapl_limit) ? 0664 : 0;
case hwmon_power_rated_max:
return i915_mmio_reg_valid(hwmon->rg.pkg_power_sku) ? 0444 : 0;
case hwmon_power_crit:
return (hwm_pcode_read_i1(i915, &uval) ||
!(uval & POWER_SETUP_I1_WATTS)) ? 0 : 0644;
default:
return 0;
}
}
#define PL1_DISABLE 0
/*
* HW allows arbitrary PL1 limits to be set but silently clamps these values to
* "typical but not guaranteed" min/max values in rg.pkg_power_sku. Follow the
* same pattern for sysfs, allow arbitrary PL1 limits to be set but display
* clamped values when read. Write/read I1 also follows the same pattern.
*/
static int
hwm_power_max_read(struct hwm_drvdata *ddat, long *val)
{
struct i915_hwmon *hwmon = ddat->hwmon;
intel_wakeref_t wakeref;
u64 r, min, max;
/* Check if PL1 limit is disabled */
with_intel_runtime_pm(ddat->uncore->rpm, wakeref)
r = intel_uncore_read(ddat->uncore, hwmon->rg.pkg_rapl_limit);
if (!(r & PKG_PWR_LIM_1_EN)) {
*val = PL1_DISABLE;
return 0;
}
*val = hwm_field_read_and_scale(ddat,
hwmon->rg.pkg_rapl_limit,
PKG_PWR_LIM_1,
hwmon->scl_shift_power,
SF_POWER);
with_intel_runtime_pm(ddat->uncore->rpm, wakeref)
r = intel_uncore_read64(ddat->uncore, hwmon->rg.pkg_power_sku);
min = REG_FIELD_GET(PKG_MIN_PWR, r);
min = mul_u64_u32_shr(min, SF_POWER, hwmon->scl_shift_power);
max = REG_FIELD_GET(PKG_MAX_PWR, r);
max = mul_u64_u32_shr(max, SF_POWER, hwmon->scl_shift_power);
if (min && max)
*val = clamp_t(u64, *val, min, max);
return 0;
}
static int
hwm_power_max_write(struct hwm_drvdata *ddat, long val)
{
struct i915_hwmon *hwmon = ddat->hwmon;
intel_wakeref_t wakeref;
DEFINE_WAIT(wait);
int ret = 0;
u32 nval;
/* Block waiting for GuC reset to complete when needed */
for (;;) {
mutex_lock(&hwmon->hwmon_lock);
prepare_to_wait(&ddat->waitq, &wait, TASK_INTERRUPTIBLE);
if (!hwmon->ddat.reset_in_progress)
break;
if (signal_pending(current)) {
ret = -EINTR;
break;
}
mutex_unlock(&hwmon->hwmon_lock);
schedule();
}
finish_wait(&ddat->waitq, &wait);
if (ret)
goto unlock;
wakeref = intel_runtime_pm_get(ddat->uncore->rpm);
/* Disable PL1 limit and verify, because the limit cannot be disabled on all platforms */
if (val == PL1_DISABLE) {
intel_uncore_rmw(ddat->uncore, hwmon->rg.pkg_rapl_limit,
PKG_PWR_LIM_1_EN, 0);
nval = intel_uncore_read(ddat->uncore, hwmon->rg.pkg_rapl_limit);
if (nval & PKG_PWR_LIM_1_EN)
ret = -ENODEV;
goto exit;
}
/* Computation in 64-bits to avoid overflow. Round to nearest. */
nval = DIV_ROUND_CLOSEST_ULL((u64)val << hwmon->scl_shift_power, SF_POWER);
nval = PKG_PWR_LIM_1_EN | REG_FIELD_PREP(PKG_PWR_LIM_1, nval);
intel_uncore_rmw(ddat->uncore, hwmon->rg.pkg_rapl_limit,
PKG_PWR_LIM_1_EN | PKG_PWR_LIM_1, nval);
exit:
intel_runtime_pm_put(ddat->uncore->rpm, wakeref);
unlock:
mutex_unlock(&hwmon->hwmon_lock);
return ret;
}
static int
hwm_power_read(struct hwm_drvdata *ddat, u32 attr, int chan, long *val)
{
struct i915_hwmon *hwmon = ddat->hwmon;
int ret;
u32 uval;
switch (attr) {
case hwmon_power_max:
return hwm_power_max_read(ddat, val);
case hwmon_power_rated_max:
*val = hwm_field_read_and_scale(ddat,
hwmon->rg.pkg_power_sku,
PKG_PKG_TDP,
hwmon->scl_shift_power,
SF_POWER);
return 0;
case hwmon_power_crit:
ret = hwm_pcode_read_i1(ddat->uncore->i915, &uval);
if (ret)
return ret;
if (!(uval & POWER_SETUP_I1_WATTS))
return -ENODEV;
*val = mul_u64_u32_shr(REG_FIELD_GET(POWER_SETUP_I1_DATA_MASK, uval),
SF_POWER, POWER_SETUP_I1_SHIFT);
return 0;
default:
return -EOPNOTSUPP;
}
}
static int
hwm_power_write(struct hwm_drvdata *ddat, u32 attr, int chan, long val)
{
u32 uval;
switch (attr) {
case hwmon_power_max:
return hwm_power_max_write(ddat, val);
case hwmon_power_crit:
uval = DIV_ROUND_CLOSEST_ULL(val << POWER_SETUP_I1_SHIFT, SF_POWER);
return hwm_pcode_write_i1(ddat->uncore->i915, uval);
default:
return -EOPNOTSUPP;
}
}
void i915_hwmon_power_max_disable(struct drm_i915_private *i915, bool *old)
{
struct i915_hwmon *hwmon = i915->hwmon;
u32 r;
if (!hwmon || !i915_mmio_reg_valid(hwmon->rg.pkg_rapl_limit))
return;
mutex_lock(&hwmon->hwmon_lock);
hwmon->ddat.reset_in_progress = true;
r = intel_uncore_rmw(hwmon->ddat.uncore, hwmon->rg.pkg_rapl_limit,
PKG_PWR_LIM_1_EN, 0);
*old = !!(r & PKG_PWR_LIM_1_EN);
mutex_unlock(&hwmon->hwmon_lock);
}
void i915_hwmon_power_max_restore(struct drm_i915_private *i915, bool old)
{
struct i915_hwmon *hwmon = i915->hwmon;
if (!hwmon || !i915_mmio_reg_valid(hwmon->rg.pkg_rapl_limit))
return;
mutex_lock(&hwmon->hwmon_lock);
intel_uncore_rmw(hwmon->ddat.uncore, hwmon->rg.pkg_rapl_limit,
PKG_PWR_LIM_1_EN, old ? PKG_PWR_LIM_1_EN : 0);
hwmon->ddat.reset_in_progress = false;
wake_up_all(&hwmon->ddat.waitq);
mutex_unlock(&hwmon->hwmon_lock);
}
static umode_t
hwm_energy_is_visible(const struct hwm_drvdata *ddat, u32 attr)
{
struct i915_hwmon *hwmon = ddat->hwmon;
i915_reg_t rgaddr;
switch (attr) {
case hwmon_energy_input:
if (ddat->gt_n >= 0)
rgaddr = hwmon->rg.energy_status_tile;
else
rgaddr = hwmon->rg.energy_status_all;
return i915_mmio_reg_valid(rgaddr) ? 0444 : 0;
default:
return 0;
}
}
static int
hwm_energy_read(struct hwm_drvdata *ddat, u32 attr, long *val)
{
switch (attr) {
case hwmon_energy_input:
hwm_energy(ddat, val);
return 0;
default:
return -EOPNOTSUPP;
}
}
static umode_t
hwm_curr_is_visible(const struct hwm_drvdata *ddat, u32 attr)
{
struct drm_i915_private *i915 = ddat->uncore->i915;
u32 uval;
switch (attr) {
case hwmon_curr_crit:
return (hwm_pcode_read_i1(i915, &uval) ||
(uval & POWER_SETUP_I1_WATTS)) ? 0 : 0644;
default:
return 0;
}
}
static int
hwm_curr_read(struct hwm_drvdata *ddat, u32 attr, long *val)
{
int ret;
u32 uval;
switch (attr) {
case hwmon_curr_crit:
ret = hwm_pcode_read_i1(ddat->uncore->i915, &uval);
if (ret)
return ret;
if (uval & POWER_SETUP_I1_WATTS)
return -ENODEV;
*val = mul_u64_u32_shr(REG_FIELD_GET(POWER_SETUP_I1_DATA_MASK, uval),
SF_CURR, POWER_SETUP_I1_SHIFT);
return 0;
default:
return -EOPNOTSUPP;
}
}
static int
hwm_curr_write(struct hwm_drvdata *ddat, u32 attr, long val)
{
u32 uval;
switch (attr) {
case hwmon_curr_crit:
uval = DIV_ROUND_CLOSEST_ULL(val << POWER_SETUP_I1_SHIFT, SF_CURR);
return hwm_pcode_write_i1(ddat->uncore->i915, uval);
default:
return -EOPNOTSUPP;
}
}
static umode_t
hwm_is_visible(const void *drvdata, enum hwmon_sensor_types type,
u32 attr, int channel)
{
struct hwm_drvdata *ddat = (struct hwm_drvdata *)drvdata;
switch (type) {
case hwmon_in:
return hwm_in_is_visible(ddat, attr);
case hwmon_power:
return hwm_power_is_visible(ddat, attr, channel);
case hwmon_energy:
return hwm_energy_is_visible(ddat, attr);
case hwmon_curr:
return hwm_curr_is_visible(ddat, attr);
default:
return 0;
}
}
static int
hwm_read(struct device *dev, enum hwmon_sensor_types type, u32 attr,
int channel, long *val)
{
struct hwm_drvdata *ddat = dev_get_drvdata(dev);
switch (type) {
case hwmon_in:
return hwm_in_read(ddat, attr, val);
case hwmon_power:
return hwm_power_read(ddat, attr, channel, val);
case hwmon_energy:
return hwm_energy_read(ddat, attr, val);
case hwmon_curr:
return hwm_curr_read(ddat, attr, val);
default:
return -EOPNOTSUPP;
}
}
static int
hwm_write(struct device *dev, enum hwmon_sensor_types type, u32 attr,
int channel, long val)
{
struct hwm_drvdata *ddat = dev_get_drvdata(dev);
switch (type) {
case hwmon_power:
return hwm_power_write(ddat, attr, channel, val);
case hwmon_curr:
return hwm_curr_write(ddat, attr, val);
default:
return -EOPNOTSUPP;
}
}
static const struct hwmon_ops hwm_ops = {
.is_visible = hwm_is_visible,
.read = hwm_read,
.write = hwm_write,
};
static const struct hwmon_chip_info hwm_chip_info = {
.ops = &hwm_ops,
.info = hwm_info,
};
static umode_t
hwm_gt_is_visible(const void *drvdata, enum hwmon_sensor_types type,
u32 attr, int channel)
{
struct hwm_drvdata *ddat = (struct hwm_drvdata *)drvdata;
switch (type) {
case hwmon_energy:
return hwm_energy_is_visible(ddat, attr);
default:
return 0;
}
}
static int
hwm_gt_read(struct device *dev, enum hwmon_sensor_types type, u32 attr,
int channel, long *val)
{
struct hwm_drvdata *ddat = dev_get_drvdata(dev);
switch (type) {
case hwmon_energy:
return hwm_energy_read(ddat, attr, val);
default:
return -EOPNOTSUPP;
}
}
static const struct hwmon_ops hwm_gt_ops = {
.is_visible = hwm_gt_is_visible,
.read = hwm_gt_read,
};
static const struct hwmon_chip_info hwm_gt_chip_info = {
.ops = &hwm_gt_ops,
.info = hwm_gt_info,
};
static void
hwm_get_preregistration_info(struct drm_i915_private *i915)
{
struct i915_hwmon *hwmon = i915->hwmon;
struct intel_uncore *uncore = &i915->uncore;
struct hwm_drvdata *ddat = &hwmon->ddat;
intel_wakeref_t wakeref;
u32 val_sku_unit = 0;
struct intel_gt *gt;
long energy;
int i;
/* Available for all Gen12+/dGfx */
hwmon->rg.gt_perf_status = GEN12_RPSTAT1;
if (IS_DG1(i915) || IS_DG2(i915)) {
hwmon->rg.pkg_power_sku_unit = PCU_PACKAGE_POWER_SKU_UNIT;
hwmon->rg.pkg_power_sku = PCU_PACKAGE_POWER_SKU;
hwmon->rg.pkg_rapl_limit = PCU_PACKAGE_RAPL_LIMIT;
hwmon->rg.energy_status_all = PCU_PACKAGE_ENERGY_STATUS;
hwmon->rg.energy_status_tile = INVALID_MMIO_REG;
} else if (IS_XEHPSDV(i915)) {
hwmon->rg.pkg_power_sku_unit = GT0_PACKAGE_POWER_SKU_UNIT;
hwmon->rg.pkg_power_sku = INVALID_MMIO_REG;
hwmon->rg.pkg_rapl_limit = GT0_PACKAGE_RAPL_LIMIT;
hwmon->rg.energy_status_all = GT0_PLATFORM_ENERGY_STATUS;
hwmon->rg.energy_status_tile = GT0_PACKAGE_ENERGY_STATUS;
} else {
hwmon->rg.pkg_power_sku_unit = INVALID_MMIO_REG;
hwmon->rg.pkg_power_sku = INVALID_MMIO_REG;
hwmon->rg.pkg_rapl_limit = INVALID_MMIO_REG;
hwmon->rg.energy_status_all = INVALID_MMIO_REG;
hwmon->rg.energy_status_tile = INVALID_MMIO_REG;
}
with_intel_runtime_pm(uncore->rpm, wakeref) {
/*
* The contents of register hwmon->rg.pkg_power_sku_unit do not change,
* so read it once and store the shift values.
*/
if (i915_mmio_reg_valid(hwmon->rg.pkg_power_sku_unit))
val_sku_unit = intel_uncore_read(uncore,
hwmon->rg.pkg_power_sku_unit);
}
hwmon->scl_shift_power = REG_FIELD_GET(PKG_PWR_UNIT, val_sku_unit);
hwmon->scl_shift_energy = REG_FIELD_GET(PKG_ENERGY_UNIT, val_sku_unit);
hwmon->scl_shift_time = REG_FIELD_GET(PKG_TIME_UNIT, val_sku_unit);
/*
* Initialize 'struct hwm_energy_info', i.e. set fields to the
* first value of the energy register read
*/
if (i915_mmio_reg_valid(hwmon->rg.energy_status_all))
hwm_energy(ddat, &energy);
if (i915_mmio_reg_valid(hwmon->rg.energy_status_tile)) {
for_each_gt(gt, i915, i)
hwm_energy(&hwmon->ddat_gt[i], &energy);
}
}
void i915_hwmon_register(struct drm_i915_private *i915)
{
struct device *dev = i915->drm.dev;
struct i915_hwmon *hwmon;
struct device *hwmon_dev;
struct hwm_drvdata *ddat;
struct hwm_drvdata *ddat_gt;
struct intel_gt *gt;
int i;
/* hwmon is available only for dGfx */
if (!IS_DGFX(i915))
return;
hwmon = devm_kzalloc(dev, sizeof(*hwmon), GFP_KERNEL);
if (!hwmon)
return;
i915->hwmon = hwmon;
mutex_init(&hwmon->hwmon_lock);
ddat = &hwmon->ddat;
ddat->hwmon = hwmon;
ddat->uncore = &i915->uncore;
snprintf(ddat->name, sizeof(ddat->name), "i915");
ddat->gt_n = -1;
init_waitqueue_head(&ddat->waitq);
for_each_gt(gt, i915, i) {
ddat_gt = hwmon->ddat_gt + i;
ddat_gt->hwmon = hwmon;
ddat_gt->uncore = gt->uncore;
snprintf(ddat_gt->name, sizeof(ddat_gt->name), "i915_gt%u", i);
ddat_gt->gt_n = i;
}
hwm_get_preregistration_info(i915);
/* hwmon_dev points to device hwmon<i> */
hwmon_dev = devm_hwmon_device_register_with_info(dev, ddat->name,
ddat,
&hwm_chip_info,
hwm_groups);
if (IS_ERR(hwmon_dev)) {
i915->hwmon = NULL;
return;
}
ddat->hwmon_dev = hwmon_dev;
for_each_gt(gt, i915, i) {
ddat_gt = hwmon->ddat_gt + i;
/*
* Create per-gt directories only if a per-gt attribute is
* visible. Currently this is only energy
*/
if (!hwm_gt_is_visible(ddat_gt, hwmon_energy, hwmon_energy_input, 0))
continue;
hwmon_dev = devm_hwmon_device_register_with_info(dev, ddat_gt->name,
ddat_gt,
&hwm_gt_chip_info,
NULL);
if (!IS_ERR(hwmon_dev))
ddat_gt->hwmon_dev = hwmon_dev;
}
}
void i915_hwmon_unregister(struct drm_i915_private *i915)
{
fetch_and_zero(&i915->hwmon);
}
| linux-master | drivers/gpu/drm/i915/i915_hwmon.c |
/*
* Copyright © 2014 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
#include <linux/mm.h>
#include <linux/io-mapping.h>
#include "i915_drv.h"
#include "i915_mm.h"
struct remap_pfn {
struct mm_struct *mm;
unsigned long pfn;
pgprot_t prot;
struct sgt_iter sgt;
resource_size_t iobase;
};
#define use_dma(io) ((io) != -1)
static inline unsigned long sgt_pfn(const struct remap_pfn *r)
{
if (use_dma(r->iobase))
return (r->sgt.dma + r->sgt.curr + r->iobase) >> PAGE_SHIFT;
else
return r->sgt.pfn + (r->sgt.curr >> PAGE_SHIFT);
}
static int remap_sg(pte_t *pte, unsigned long addr, void *data)
{
struct remap_pfn *r = data;
if (GEM_WARN_ON(!r->sgt.sgp))
return -EINVAL;
/* Special PTE are not associated with any struct page */
set_pte_at(r->mm, addr, pte,
pte_mkspecial(pfn_pte(sgt_pfn(r), r->prot)));
r->pfn++; /* track insertions in case we need to unwind later */
r->sgt.curr += PAGE_SIZE;
if (r->sgt.curr >= r->sgt.max)
r->sgt = __sgt_iter(__sg_next(r->sgt.sgp), use_dma(r->iobase));
return 0;
}
#define EXPECTED_FLAGS (VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP)
#if IS_ENABLED(CONFIG_X86)
static int remap_pfn(pte_t *pte, unsigned long addr, void *data)
{
struct remap_pfn *r = data;
/* Special PTE are not associated with any struct page */
set_pte_at(r->mm, addr, pte, pte_mkspecial(pfn_pte(r->pfn, r->prot)));
r->pfn++;
return 0;
}
/**
* remap_io_mapping - remap an IO mapping to userspace
* @vma: user vma to map to
* @addr: target user address to start at
* @pfn: physical address of kernel memory
* @size: size of map area
* @iomap: the source io_mapping
*
* Note: this is only safe if the mm semaphore is held when called.
*/
int remap_io_mapping(struct vm_area_struct *vma,
unsigned long addr, unsigned long pfn, unsigned long size,
struct io_mapping *iomap)
{
struct remap_pfn r;
int err;
GEM_BUG_ON((vma->vm_flags & EXPECTED_FLAGS) != EXPECTED_FLAGS);
/* We rely on prevalidation of the io-mapping to skip track_pfn(). */
r.mm = vma->vm_mm;
r.pfn = pfn;
r.prot = __pgprot((pgprot_val(iomap->prot) & _PAGE_CACHE_MASK) |
(pgprot_val(vma->vm_page_prot) & ~_PAGE_CACHE_MASK));
err = apply_to_page_range(r.mm, addr, size, remap_pfn, &r);
if (unlikely(err)) {
zap_vma_ptes(vma, addr, (r.pfn - pfn) << PAGE_SHIFT);
return err;
}
return 0;
}
#endif
/**
* remap_io_sg - remap an IO mapping to userspace
* @vma: user vma to map to
* @addr: target user address to start at
* @size: size of map area
* @sgl: Start sg entry
* @iobase: Use stored dma address offset by this address or pfn if -1
*
* Note: this is only safe if the mm semaphore is held when called.
*/
int remap_io_sg(struct vm_area_struct *vma,
unsigned long addr, unsigned long size,
struct scatterlist *sgl, resource_size_t iobase)
{
struct remap_pfn r = {
.mm = vma->vm_mm,
.prot = vma->vm_page_prot,
.sgt = __sgt_iter(sgl, use_dma(iobase)),
.iobase = iobase,
};
int err;
/* We rely on prevalidation of the io-mapping to skip track_pfn(). */
GEM_BUG_ON((vma->vm_flags & EXPECTED_FLAGS) != EXPECTED_FLAGS);
if (!use_dma(iobase))
flush_cache_range(vma, addr, size);
err = apply_to_page_range(r.mm, addr, size, remap_sg, &r);
if (unlikely(err)) {
zap_vma_ptes(vma, addr, r.pfn << PAGE_SHIFT);
return err;
}
return 0;
}
| linux-master | drivers/gpu/drm/i915/i915_mm.c |
/*
* Copyright © 2016 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
#include <linux/sched/mm.h>
#include <linux/dma-fence-array.h>
#include <drm/drm_gem.h>
#include "display/intel_display.h"
#include "display/intel_frontbuffer.h"
#include "gem/i915_gem_lmem.h"
#include "gem/i915_gem_tiling.h"
#include "gt/intel_engine.h"
#include "gt/intel_engine_heartbeat.h"
#include "gt/intel_gt.h"
#include "gt/intel_gt_requests.h"
#include "gt/intel_tlb.h"
#include "i915_drv.h"
#include "i915_gem_evict.h"
#include "i915_sw_fence_work.h"
#include "i915_trace.h"
#include "i915_vma.h"
#include "i915_vma_resource.h"
static inline void assert_vma_held_evict(const struct i915_vma *vma)
{
/*
* We may be forced to unbind when the vm is dead, to clean it up.
* This is the only exception to the requirement of the object lock
* being held.
*/
if (kref_read(&vma->vm->ref))
assert_object_held_shared(vma->obj);
}
static struct kmem_cache *slab_vmas;
static struct i915_vma *i915_vma_alloc(void)
{
return kmem_cache_zalloc(slab_vmas, GFP_KERNEL);
}
static void i915_vma_free(struct i915_vma *vma)
{
return kmem_cache_free(slab_vmas, vma);
}
#if IS_ENABLED(CONFIG_DRM_I915_ERRLOG_GEM) && IS_ENABLED(CONFIG_DRM_DEBUG_MM)
#include <linux/stackdepot.h>
static void vma_print_allocator(struct i915_vma *vma, const char *reason)
{
char buf[512];
if (!vma->node.stack) {
drm_dbg(vma->obj->base.dev,
"vma.node [%08llx + %08llx] %s: unknown owner\n",
vma->node.start, vma->node.size, reason);
return;
}
stack_depot_snprint(vma->node.stack, buf, sizeof(buf), 0);
drm_dbg(vma->obj->base.dev,
"vma.node [%08llx + %08llx] %s: inserted at %s\n",
vma->node.start, vma->node.size, reason, buf);
}
#else
static void vma_print_allocator(struct i915_vma *vma, const char *reason)
{
}
#endif
static inline struct i915_vma *active_to_vma(struct i915_active *ref)
{
return container_of(ref, typeof(struct i915_vma), active);
}
static int __i915_vma_active(struct i915_active *ref)
{
return i915_vma_tryget(active_to_vma(ref)) ? 0 : -ENOENT;
}
static void __i915_vma_retire(struct i915_active *ref)
{
i915_vma_put(active_to_vma(ref));
}
static struct i915_vma *
vma_create(struct drm_i915_gem_object *obj,
struct i915_address_space *vm,
const struct i915_gtt_view *view)
{
struct i915_vma *pos = ERR_PTR(-E2BIG);
struct i915_vma *vma;
struct rb_node *rb, **p;
int err;
/* The aliasing_ppgtt should never be used directly! */
GEM_BUG_ON(vm == &vm->gt->ggtt->alias->vm);
vma = i915_vma_alloc();
if (vma == NULL)
return ERR_PTR(-ENOMEM);
vma->ops = &vm->vma_ops;
vma->obj = obj;
vma->size = obj->base.size;
vma->display_alignment = I915_GTT_MIN_ALIGNMENT;
i915_active_init(&vma->active, __i915_vma_active, __i915_vma_retire, 0);
/* Declare ourselves safe for use inside shrinkers */
if (IS_ENABLED(CONFIG_LOCKDEP)) {
fs_reclaim_acquire(GFP_KERNEL);
might_lock(&vma->active.mutex);
fs_reclaim_release(GFP_KERNEL);
}
INIT_LIST_HEAD(&vma->closed_link);
INIT_LIST_HEAD(&vma->obj_link);
RB_CLEAR_NODE(&vma->obj_node);
if (view && view->type != I915_GTT_VIEW_NORMAL) {
vma->gtt_view = *view;
if (view->type == I915_GTT_VIEW_PARTIAL) {
GEM_BUG_ON(range_overflows_t(u64,
view->partial.offset,
view->partial.size,
obj->base.size >> PAGE_SHIFT));
vma->size = view->partial.size;
vma->size <<= PAGE_SHIFT;
GEM_BUG_ON(vma->size > obj->base.size);
} else if (view->type == I915_GTT_VIEW_ROTATED) {
vma->size = intel_rotation_info_size(&view->rotated);
vma->size <<= PAGE_SHIFT;
} else if (view->type == I915_GTT_VIEW_REMAPPED) {
vma->size = intel_remapped_info_size(&view->remapped);
vma->size <<= PAGE_SHIFT;
}
}
if (unlikely(vma->size > vm->total))
goto err_vma;
GEM_BUG_ON(!IS_ALIGNED(vma->size, I915_GTT_PAGE_SIZE));
err = mutex_lock_interruptible(&vm->mutex);
if (err) {
pos = ERR_PTR(err);
goto err_vma;
}
vma->vm = vm;
list_add_tail(&vma->vm_link, &vm->unbound_list);
spin_lock(&obj->vma.lock);
if (i915_is_ggtt(vm)) {
if (unlikely(overflows_type(vma->size, u32)))
goto err_unlock;
vma->fence_size = i915_gem_fence_size(vm->i915, vma->size,
i915_gem_object_get_tiling(obj),
i915_gem_object_get_stride(obj));
if (unlikely(vma->fence_size < vma->size || /* overflow */
vma->fence_size > vm->total))
goto err_unlock;
GEM_BUG_ON(!IS_ALIGNED(vma->fence_size, I915_GTT_MIN_ALIGNMENT));
vma->fence_alignment = i915_gem_fence_alignment(vm->i915, vma->size,
i915_gem_object_get_tiling(obj),
i915_gem_object_get_stride(obj));
GEM_BUG_ON(!is_power_of_2(vma->fence_alignment));
__set_bit(I915_VMA_GGTT_BIT, __i915_vma_flags(vma));
}
rb = NULL;
p = &obj->vma.tree.rb_node;
while (*p) {
long cmp;
rb = *p;
pos = rb_entry(rb, struct i915_vma, obj_node);
/*
* If the view already exists in the tree, another thread
* already created a matching vma, so return the older instance
* and dispose of ours.
*/
cmp = i915_vma_compare(pos, vm, view);
if (cmp < 0)
p = &rb->rb_right;
else if (cmp > 0)
p = &rb->rb_left;
else
goto err_unlock;
}
rb_link_node(&vma->obj_node, rb, p);
rb_insert_color(&vma->obj_node, &obj->vma.tree);
if (i915_vma_is_ggtt(vma))
/*
* We put the GGTT vma at the start of the vma-list, followed
* by the ppGGTT vma. This allows us to break early when
* iterating over only the GGTT vma for an object, see
* for_each_ggtt_vma()
*/
list_add(&vma->obj_link, &obj->vma.list);
else
list_add_tail(&vma->obj_link, &obj->vma.list);
spin_unlock(&obj->vma.lock);
mutex_unlock(&vm->mutex);
return vma;
err_unlock:
spin_unlock(&obj->vma.lock);
list_del_init(&vma->vm_link);
mutex_unlock(&vm->mutex);
err_vma:
i915_vma_free(vma);
return pos;
}
static struct i915_vma *
i915_vma_lookup(struct drm_i915_gem_object *obj,
struct i915_address_space *vm,
const struct i915_gtt_view *view)
{
struct rb_node *rb;
rb = obj->vma.tree.rb_node;
while (rb) {
struct i915_vma *vma = rb_entry(rb, struct i915_vma, obj_node);
long cmp;
cmp = i915_vma_compare(vma, vm, view);
if (cmp == 0)
return vma;
if (cmp < 0)
rb = rb->rb_right;
else
rb = rb->rb_left;
}
return NULL;
}
/**
* i915_vma_instance - return the singleton instance of the VMA
* @obj: parent &struct drm_i915_gem_object to be mapped
* @vm: address space in which the mapping is located
* @view: additional mapping requirements
*
* i915_vma_instance() looks up an existing VMA of the @obj in the @vm with
* the same @view characteristics. If a match is not found, one is created.
* Once created, the VMA is kept until either the object is freed, or the
* address space is closed.
*
* Returns the vma, or an error pointer.
*/
struct i915_vma *
i915_vma_instance(struct drm_i915_gem_object *obj,
struct i915_address_space *vm,
const struct i915_gtt_view *view)
{
struct i915_vma *vma;
GEM_BUG_ON(view && !i915_is_ggtt_or_dpt(vm));
GEM_BUG_ON(!kref_read(&vm->ref));
spin_lock(&obj->vma.lock);
vma = i915_vma_lookup(obj, vm, view);
spin_unlock(&obj->vma.lock);
/* vma_create() will resolve the race if another creates the vma */
if (unlikely(!vma))
vma = vma_create(obj, vm, view);
GEM_BUG_ON(!IS_ERR(vma) && i915_vma_compare(vma, vm, view));
return vma;
}
struct i915_vma_work {
struct dma_fence_work base;
struct i915_address_space *vm;
struct i915_vm_pt_stash stash;
struct i915_vma_resource *vma_res;
struct drm_i915_gem_object *obj;
struct i915_sw_dma_fence_cb cb;
unsigned int pat_index;
unsigned int flags;
};
static void __vma_bind(struct dma_fence_work *work)
{
struct i915_vma_work *vw = container_of(work, typeof(*vw), base);
struct i915_vma_resource *vma_res = vw->vma_res;
/*
* We are about the bind the object, which must mean we have already
* signaled the work to potentially clear/move the pages underneath. If
* something went wrong at that stage then the object should have
* unknown_state set, in which case we need to skip the bind.
*/
if (i915_gem_object_has_unknown_state(vw->obj))
return;
vma_res->ops->bind_vma(vma_res->vm, &vw->stash,
vma_res, vw->pat_index, vw->flags);
}
static void __vma_release(struct dma_fence_work *work)
{
struct i915_vma_work *vw = container_of(work, typeof(*vw), base);
if (vw->obj)
i915_gem_object_put(vw->obj);
i915_vm_free_pt_stash(vw->vm, &vw->stash);
if (vw->vma_res)
i915_vma_resource_put(vw->vma_res);
}
static const struct dma_fence_work_ops bind_ops = {
.name = "bind",
.work = __vma_bind,
.release = __vma_release,
};
struct i915_vma_work *i915_vma_work(void)
{
struct i915_vma_work *vw;
vw = kzalloc(sizeof(*vw), GFP_KERNEL);
if (!vw)
return NULL;
dma_fence_work_init(&vw->base, &bind_ops);
vw->base.dma.error = -EAGAIN; /* disable the worker by default */
return vw;
}
int i915_vma_wait_for_bind(struct i915_vma *vma)
{
int err = 0;
if (rcu_access_pointer(vma->active.excl.fence)) {
struct dma_fence *fence;
rcu_read_lock();
fence = dma_fence_get_rcu_safe(&vma->active.excl.fence);
rcu_read_unlock();
if (fence) {
err = dma_fence_wait(fence, true);
dma_fence_put(fence);
}
}
return err;
}
#if IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM)
static int i915_vma_verify_bind_complete(struct i915_vma *vma)
{
struct dma_fence *fence = i915_active_fence_get(&vma->active.excl);
int err;
if (!fence)
return 0;
if (dma_fence_is_signaled(fence))
err = fence->error;
else
err = -EBUSY;
dma_fence_put(fence);
return err;
}
#else
#define i915_vma_verify_bind_complete(_vma) 0
#endif
I915_SELFTEST_EXPORT void
i915_vma_resource_init_from_vma(struct i915_vma_resource *vma_res,
struct i915_vma *vma)
{
struct drm_i915_gem_object *obj = vma->obj;
i915_vma_resource_init(vma_res, vma->vm, vma->pages, &vma->page_sizes,
obj->mm.rsgt, i915_gem_object_is_readonly(obj),
i915_gem_object_is_lmem(obj), obj->mm.region,
vma->ops, vma->private, __i915_vma_offset(vma),
__i915_vma_size(vma), vma->size, vma->guard);
}
/**
* i915_vma_bind - Sets up PTEs for an VMA in it's corresponding address space.
* @vma: VMA to map
* @pat_index: PAT index to set in PTE
* @flags: flags like global or local mapping
* @work: preallocated worker for allocating and binding the PTE
* @vma_res: pointer to a preallocated vma resource. The resource is either
* consumed or freed.
*
* DMA addresses are taken from the scatter-gather table of this object (or of
* this VMA in case of non-default GGTT views) and PTE entries set up.
* Note that DMA addresses are also the only part of the SG table we care about.
*/
int i915_vma_bind(struct i915_vma *vma,
unsigned int pat_index,
u32 flags,
struct i915_vma_work *work,
struct i915_vma_resource *vma_res)
{
u32 bind_flags;
u32 vma_flags;
int ret;
lockdep_assert_held(&vma->vm->mutex);
GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
GEM_BUG_ON(vma->size > i915_vma_size(vma));
if (GEM_DEBUG_WARN_ON(range_overflows(vma->node.start,
vma->node.size,
vma->vm->total))) {
i915_vma_resource_free(vma_res);
return -ENODEV;
}
if (GEM_DEBUG_WARN_ON(!flags)) {
i915_vma_resource_free(vma_res);
return -EINVAL;
}
bind_flags = flags;
bind_flags &= I915_VMA_GLOBAL_BIND | I915_VMA_LOCAL_BIND;
vma_flags = atomic_read(&vma->flags);
vma_flags &= I915_VMA_GLOBAL_BIND | I915_VMA_LOCAL_BIND;
bind_flags &= ~vma_flags;
if (bind_flags == 0) {
i915_vma_resource_free(vma_res);
return 0;
}
GEM_BUG_ON(!atomic_read(&vma->pages_count));
/* Wait for or await async unbinds touching our range */
if (work && bind_flags & vma->vm->bind_async_flags)
ret = i915_vma_resource_bind_dep_await(vma->vm,
&work->base.chain,
vma->node.start,
vma->node.size,
true,
GFP_NOWAIT |
__GFP_RETRY_MAYFAIL |
__GFP_NOWARN);
else
ret = i915_vma_resource_bind_dep_sync(vma->vm, vma->node.start,
vma->node.size, true);
if (ret) {
i915_vma_resource_free(vma_res);
return ret;
}
if (vma->resource || !vma_res) {
/* Rebinding with an additional I915_VMA_*_BIND */
GEM_WARN_ON(!vma_flags);
i915_vma_resource_free(vma_res);
} else {
i915_vma_resource_init_from_vma(vma_res, vma);
vma->resource = vma_res;
}
trace_i915_vma_bind(vma, bind_flags);
if (work && bind_flags & vma->vm->bind_async_flags) {
struct dma_fence *prev;
work->vma_res = i915_vma_resource_get(vma->resource);
work->pat_index = pat_index;
work->flags = bind_flags;
/*
* Note we only want to chain up to the migration fence on
* the pages (not the object itself). As we don't track that,
* yet, we have to use the exclusive fence instead.
*
* Also note that we do not want to track the async vma as
* part of the obj->resv->excl_fence as it only affects
* execution and not content or object's backing store lifetime.
*/
prev = i915_active_set_exclusive(&vma->active, &work->base.dma);
if (prev) {
__i915_sw_fence_await_dma_fence(&work->base.chain,
prev,
&work->cb);
dma_fence_put(prev);
}
work->base.dma.error = 0; /* enable the queue_work() */
work->obj = i915_gem_object_get(vma->obj);
} else {
ret = i915_gem_object_wait_moving_fence(vma->obj, true);
if (ret) {
i915_vma_resource_free(vma->resource);
vma->resource = NULL;
return ret;
}
vma->ops->bind_vma(vma->vm, NULL, vma->resource, pat_index,
bind_flags);
}
atomic_or(bind_flags, &vma->flags);
return 0;
}
void __iomem *i915_vma_pin_iomap(struct i915_vma *vma)
{
void __iomem *ptr;
int err;
if (WARN_ON_ONCE(vma->obj->flags & I915_BO_ALLOC_GPU_ONLY))
return IOMEM_ERR_PTR(-EINVAL);
GEM_BUG_ON(!i915_vma_is_ggtt(vma));
GEM_BUG_ON(!i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND));
GEM_BUG_ON(i915_vma_verify_bind_complete(vma));
ptr = READ_ONCE(vma->iomap);
if (ptr == NULL) {
/*
* TODO: consider just using i915_gem_object_pin_map() for lmem
* instead, which already supports mapping non-contiguous chunks
* of pages, that way we can also drop the
* I915_BO_ALLOC_CONTIGUOUS when allocating the object.
*/
if (i915_gem_object_is_lmem(vma->obj)) {
ptr = i915_gem_object_lmem_io_map(vma->obj, 0,
vma->obj->base.size);
} else if (i915_vma_is_map_and_fenceable(vma)) {
ptr = io_mapping_map_wc(&i915_vm_to_ggtt(vma->vm)->iomap,
i915_vma_offset(vma),
i915_vma_size(vma));
} else {
ptr = (void __iomem *)
i915_gem_object_pin_map(vma->obj, I915_MAP_WC);
if (IS_ERR(ptr)) {
err = PTR_ERR(ptr);
goto err;
}
ptr = page_pack_bits(ptr, 1);
}
if (ptr == NULL) {
err = -ENOMEM;
goto err;
}
if (unlikely(cmpxchg(&vma->iomap, NULL, ptr))) {
if (page_unmask_bits(ptr))
__i915_gem_object_release_map(vma->obj);
else
io_mapping_unmap(ptr);
ptr = vma->iomap;
}
}
__i915_vma_pin(vma);
err = i915_vma_pin_fence(vma);
if (err)
goto err_unpin;
i915_vma_set_ggtt_write(vma);
/* NB Access through the GTT requires the device to be awake. */
return page_mask_bits(ptr);
err_unpin:
__i915_vma_unpin(vma);
err:
return IOMEM_ERR_PTR(err);
}
void i915_vma_flush_writes(struct i915_vma *vma)
{
if (i915_vma_unset_ggtt_write(vma))
intel_gt_flush_ggtt_writes(vma->vm->gt);
}
void i915_vma_unpin_iomap(struct i915_vma *vma)
{
GEM_BUG_ON(vma->iomap == NULL);
/* XXX We keep the mapping until __i915_vma_unbind()/evict() */
i915_vma_flush_writes(vma);
i915_vma_unpin_fence(vma);
i915_vma_unpin(vma);
}
void i915_vma_unpin_and_release(struct i915_vma **p_vma, unsigned int flags)
{
struct i915_vma *vma;
struct drm_i915_gem_object *obj;
vma = fetch_and_zero(p_vma);
if (!vma)
return;
obj = vma->obj;
GEM_BUG_ON(!obj);
i915_vma_unpin(vma);
if (flags & I915_VMA_RELEASE_MAP)
i915_gem_object_unpin_map(obj);
i915_gem_object_put(obj);
}
bool i915_vma_misplaced(const struct i915_vma *vma,
u64 size, u64 alignment, u64 flags)
{
if (!drm_mm_node_allocated(&vma->node))
return false;
if (test_bit(I915_VMA_ERROR_BIT, __i915_vma_flags(vma)))
return true;
if (i915_vma_size(vma) < size)
return true;
GEM_BUG_ON(alignment && !is_power_of_2(alignment));
if (alignment && !IS_ALIGNED(i915_vma_offset(vma), alignment))
return true;
if (flags & PIN_MAPPABLE && !i915_vma_is_map_and_fenceable(vma))
return true;
if (flags & PIN_OFFSET_BIAS &&
i915_vma_offset(vma) < (flags & PIN_OFFSET_MASK))
return true;
if (flags & PIN_OFFSET_FIXED &&
i915_vma_offset(vma) != (flags & PIN_OFFSET_MASK))
return true;
if (flags & PIN_OFFSET_GUARD &&
vma->guard < (flags & PIN_OFFSET_MASK))
return true;
return false;
}
void __i915_vma_set_map_and_fenceable(struct i915_vma *vma)
{
bool mappable, fenceable;
GEM_BUG_ON(!i915_vma_is_ggtt(vma));
GEM_BUG_ON(!vma->fence_size);
fenceable = (i915_vma_size(vma) >= vma->fence_size &&
IS_ALIGNED(i915_vma_offset(vma), vma->fence_alignment));
mappable = i915_ggtt_offset(vma) + vma->fence_size <=
i915_vm_to_ggtt(vma->vm)->mappable_end;
if (mappable && fenceable)
set_bit(I915_VMA_CAN_FENCE_BIT, __i915_vma_flags(vma));
else
clear_bit(I915_VMA_CAN_FENCE_BIT, __i915_vma_flags(vma));
}
bool i915_gem_valid_gtt_space(struct i915_vma *vma, unsigned long color)
{
struct drm_mm_node *node = &vma->node;
struct drm_mm_node *other;
/*
* On some machines we have to be careful when putting differing types
* of snoopable memory together to avoid the prefetcher crossing memory
* domains and dying. During vm initialisation, we decide whether or not
* these constraints apply and set the drm_mm.color_adjust
* appropriately.
*/
if (!i915_vm_has_cache_coloring(vma->vm))
return true;
/* Only valid to be called on an already inserted vma */
GEM_BUG_ON(!drm_mm_node_allocated(node));
GEM_BUG_ON(list_empty(&node->node_list));
other = list_prev_entry(node, node_list);
if (i915_node_color_differs(other, color) &&
!drm_mm_hole_follows(other))
return false;
other = list_next_entry(node, node_list);
if (i915_node_color_differs(other, color) &&
!drm_mm_hole_follows(node))
return false;
return true;
}
/**
* i915_vma_insert - finds a slot for the vma in its address space
* @vma: the vma
* @ww: An optional struct i915_gem_ww_ctx
* @size: requested size in bytes (can be larger than the VMA)
* @alignment: required alignment
* @flags: mask of PIN_* flags to use
*
* First we try to allocate some free space that meets the requirements for
* the VMA. Failiing that, if the flags permit, it will evict an old VMA,
* preferrably the oldest idle entry to make room for the new VMA.
*
* Returns:
* 0 on success, negative error code otherwise.
*/
static int
i915_vma_insert(struct i915_vma *vma, struct i915_gem_ww_ctx *ww,
u64 size, u64 alignment, u64 flags)
{
unsigned long color, guard;
u64 start, end;
int ret;
GEM_BUG_ON(i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND | I915_VMA_LOCAL_BIND));
GEM_BUG_ON(drm_mm_node_allocated(&vma->node));
GEM_BUG_ON(hweight64(flags & (PIN_OFFSET_GUARD | PIN_OFFSET_FIXED | PIN_OFFSET_BIAS)) > 1);
size = max(size, vma->size);
alignment = max_t(typeof(alignment), alignment, vma->display_alignment);
if (flags & PIN_MAPPABLE) {
size = max_t(typeof(size), size, vma->fence_size);
alignment = max_t(typeof(alignment),
alignment, vma->fence_alignment);
}
GEM_BUG_ON(!IS_ALIGNED(size, I915_GTT_PAGE_SIZE));
GEM_BUG_ON(!IS_ALIGNED(alignment, I915_GTT_MIN_ALIGNMENT));
GEM_BUG_ON(!is_power_of_2(alignment));
guard = vma->guard; /* retain guard across rebinds */
if (flags & PIN_OFFSET_GUARD) {
GEM_BUG_ON(overflows_type(flags & PIN_OFFSET_MASK, u32));
guard = max_t(u32, guard, flags & PIN_OFFSET_MASK);
}
/*
* As we align the node upon insertion, but the hardware gets
* node.start + guard, the easiest way to make that work is
* to make the guard a multiple of the alignment size.
*/
guard = ALIGN(guard, alignment);
start = flags & PIN_OFFSET_BIAS ? flags & PIN_OFFSET_MASK : 0;
GEM_BUG_ON(!IS_ALIGNED(start, I915_GTT_PAGE_SIZE));
end = vma->vm->total;
if (flags & PIN_MAPPABLE)
end = min_t(u64, end, i915_vm_to_ggtt(vma->vm)->mappable_end);
if (flags & PIN_ZONE_4G)
end = min_t(u64, end, (1ULL << 32) - I915_GTT_PAGE_SIZE);
GEM_BUG_ON(!IS_ALIGNED(end, I915_GTT_PAGE_SIZE));
alignment = max(alignment, i915_vm_obj_min_alignment(vma->vm, vma->obj));
/*
* If binding the object/GGTT view requires more space than the entire
* aperture has, reject it early before evicting everything in a vain
* attempt to find space.
*/
if (size > end - 2 * guard) {
drm_dbg(vma->obj->base.dev,
"Attempting to bind an object larger than the aperture: request=%llu > %s aperture=%llu\n",
size, flags & PIN_MAPPABLE ? "mappable" : "total", end);
return -ENOSPC;
}
color = 0;
if (i915_vm_has_cache_coloring(vma->vm))
color = vma->obj->pat_index;
if (flags & PIN_OFFSET_FIXED) {
u64 offset = flags & PIN_OFFSET_MASK;
if (!IS_ALIGNED(offset, alignment) ||
range_overflows(offset, size, end))
return -EINVAL;
/*
* The caller knows not of the guard added by others and
* requests for the offset of the start of its buffer
* to be fixed, which may not be the same as the position
* of the vma->node due to the guard pages.
*/
if (offset < guard || offset + size > end - guard)
return -ENOSPC;
ret = i915_gem_gtt_reserve(vma->vm, ww, &vma->node,
size + 2 * guard,
offset - guard,
color, flags);
if (ret)
return ret;
} else {
size += 2 * guard;
/*
* We only support huge gtt pages through the 48b PPGTT,
* however we also don't want to force any alignment for
* objects which need to be tightly packed into the low 32bits.
*
* Note that we assume that GGTT are limited to 4GiB for the
* forseeable future. See also i915_ggtt_offset().
*/
if (upper_32_bits(end - 1) &&
vma->page_sizes.sg > I915_GTT_PAGE_SIZE &&
!HAS_64K_PAGES(vma->vm->i915)) {
/*
* We can't mix 64K and 4K PTEs in the same page-table
* (2M block), and so to avoid the ugliness and
* complexity of coloring we opt for just aligning 64K
* objects to 2M.
*/
u64 page_alignment =
rounddown_pow_of_two(vma->page_sizes.sg |
I915_GTT_PAGE_SIZE_2M);
/*
* Check we don't expand for the limited Global GTT
* (mappable aperture is even more precious!). This
* also checks that we exclude the aliasing-ppgtt.
*/
GEM_BUG_ON(i915_vma_is_ggtt(vma));
alignment = max(alignment, page_alignment);
if (vma->page_sizes.sg & I915_GTT_PAGE_SIZE_64K)
size = round_up(size, I915_GTT_PAGE_SIZE_2M);
}
ret = i915_gem_gtt_insert(vma->vm, ww, &vma->node,
size, alignment, color,
start, end, flags);
if (ret)
return ret;
GEM_BUG_ON(vma->node.start < start);
GEM_BUG_ON(vma->node.start + vma->node.size > end);
}
GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
GEM_BUG_ON(!i915_gem_valid_gtt_space(vma, color));
list_move_tail(&vma->vm_link, &vma->vm->bound_list);
vma->guard = guard;
return 0;
}
static void
i915_vma_detach(struct i915_vma *vma)
{
GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
GEM_BUG_ON(i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND | I915_VMA_LOCAL_BIND));
/*
* And finally now the object is completely decoupled from this
* vma, we can drop its hold on the backing storage and allow
* it to be reaped by the shrinker.
*/
list_move_tail(&vma->vm_link, &vma->vm->unbound_list);
}
static bool try_qad_pin(struct i915_vma *vma, unsigned int flags)
{
unsigned int bound;
bound = atomic_read(&vma->flags);
if (flags & PIN_VALIDATE) {
flags &= I915_VMA_BIND_MASK;
return (flags & bound) == flags;
}
/* with the lock mandatory for unbind, we don't race here */
flags &= I915_VMA_BIND_MASK;
do {
if (unlikely(flags & ~bound))
return false;
if (unlikely(bound & (I915_VMA_OVERFLOW | I915_VMA_ERROR)))
return false;
GEM_BUG_ON(((bound + 1) & I915_VMA_PIN_MASK) == 0);
} while (!atomic_try_cmpxchg(&vma->flags, &bound, bound + 1));
return true;
}
static struct scatterlist *
rotate_pages(struct drm_i915_gem_object *obj, unsigned int offset,
unsigned int width, unsigned int height,
unsigned int src_stride, unsigned int dst_stride,
struct sg_table *st, struct scatterlist *sg)
{
unsigned int column, row;
pgoff_t src_idx;
for (column = 0; column < width; column++) {
unsigned int left;
src_idx = src_stride * (height - 1) + column + offset;
for (row = 0; row < height; row++) {
st->nents++;
/*
* We don't need the pages, but need to initialize
* the entries so the sg list can be happily traversed.
* The only thing we need are DMA addresses.
*/
sg_set_page(sg, NULL, I915_GTT_PAGE_SIZE, 0);
sg_dma_address(sg) =
i915_gem_object_get_dma_address(obj, src_idx);
sg_dma_len(sg) = I915_GTT_PAGE_SIZE;
sg = sg_next(sg);
src_idx -= src_stride;
}
left = (dst_stride - height) * I915_GTT_PAGE_SIZE;
if (!left)
continue;
st->nents++;
/*
* The DE ignores the PTEs for the padding tiles, the sg entry
* here is just a conenience to indicate how many padding PTEs
* to insert at this spot.
*/
sg_set_page(sg, NULL, left, 0);
sg_dma_address(sg) = 0;
sg_dma_len(sg) = left;
sg = sg_next(sg);
}
return sg;
}
static noinline struct sg_table *
intel_rotate_pages(struct intel_rotation_info *rot_info,
struct drm_i915_gem_object *obj)
{
unsigned int size = intel_rotation_info_size(rot_info);
struct drm_i915_private *i915 = to_i915(obj->base.dev);
struct sg_table *st;
struct scatterlist *sg;
int ret = -ENOMEM;
int i;
/* Allocate target SG list. */
st = kmalloc(sizeof(*st), GFP_KERNEL);
if (!st)
goto err_st_alloc;
ret = sg_alloc_table(st, size, GFP_KERNEL);
if (ret)
goto err_sg_alloc;
st->nents = 0;
sg = st->sgl;
for (i = 0 ; i < ARRAY_SIZE(rot_info->plane); i++)
sg = rotate_pages(obj, rot_info->plane[i].offset,
rot_info->plane[i].width, rot_info->plane[i].height,
rot_info->plane[i].src_stride,
rot_info->plane[i].dst_stride,
st, sg);
return st;
err_sg_alloc:
kfree(st);
err_st_alloc:
drm_dbg(&i915->drm, "Failed to create rotated mapping for object size %zu! (%ux%u tiles, %u pages)\n",
obj->base.size, rot_info->plane[0].width,
rot_info->plane[0].height, size);
return ERR_PTR(ret);
}
static struct scatterlist *
add_padding_pages(unsigned int count,
struct sg_table *st, struct scatterlist *sg)
{
st->nents++;
/*
* The DE ignores the PTEs for the padding tiles, the sg entry
* here is just a convenience to indicate how many padding PTEs
* to insert at this spot.
*/
sg_set_page(sg, NULL, count * I915_GTT_PAGE_SIZE, 0);
sg_dma_address(sg) = 0;
sg_dma_len(sg) = count * I915_GTT_PAGE_SIZE;
sg = sg_next(sg);
return sg;
}
static struct scatterlist *
remap_tiled_color_plane_pages(struct drm_i915_gem_object *obj,
unsigned long offset, unsigned int alignment_pad,
unsigned int width, unsigned int height,
unsigned int src_stride, unsigned int dst_stride,
struct sg_table *st, struct scatterlist *sg,
unsigned int *gtt_offset)
{
unsigned int row;
if (!width || !height)
return sg;
if (alignment_pad)
sg = add_padding_pages(alignment_pad, st, sg);
for (row = 0; row < height; row++) {
unsigned int left = width * I915_GTT_PAGE_SIZE;
while (left) {
dma_addr_t addr;
unsigned int length;
/*
* We don't need the pages, but need to initialize
* the entries so the sg list can be happily traversed.
* The only thing we need are DMA addresses.
*/
addr = i915_gem_object_get_dma_address_len(obj, offset, &length);
length = min(left, length);
st->nents++;
sg_set_page(sg, NULL, length, 0);
sg_dma_address(sg) = addr;
sg_dma_len(sg) = length;
sg = sg_next(sg);
offset += length / I915_GTT_PAGE_SIZE;
left -= length;
}
offset += src_stride - width;
left = (dst_stride - width) * I915_GTT_PAGE_SIZE;
if (!left)
continue;
sg = add_padding_pages(left >> PAGE_SHIFT, st, sg);
}
*gtt_offset += alignment_pad + dst_stride * height;
return sg;
}
static struct scatterlist *
remap_contiguous_pages(struct drm_i915_gem_object *obj,
pgoff_t obj_offset,
unsigned int count,
struct sg_table *st, struct scatterlist *sg)
{
struct scatterlist *iter;
unsigned int offset;
iter = i915_gem_object_get_sg_dma(obj, obj_offset, &offset);
GEM_BUG_ON(!iter);
do {
unsigned int len;
len = min(sg_dma_len(iter) - (offset << PAGE_SHIFT),
count << PAGE_SHIFT);
sg_set_page(sg, NULL, len, 0);
sg_dma_address(sg) =
sg_dma_address(iter) + (offset << PAGE_SHIFT);
sg_dma_len(sg) = len;
st->nents++;
count -= len >> PAGE_SHIFT;
if (count == 0)
return sg;
sg = __sg_next(sg);
iter = __sg_next(iter);
offset = 0;
} while (1);
}
static struct scatterlist *
remap_linear_color_plane_pages(struct drm_i915_gem_object *obj,
pgoff_t obj_offset, unsigned int alignment_pad,
unsigned int size,
struct sg_table *st, struct scatterlist *sg,
unsigned int *gtt_offset)
{
if (!size)
return sg;
if (alignment_pad)
sg = add_padding_pages(alignment_pad, st, sg);
sg = remap_contiguous_pages(obj, obj_offset, size, st, sg);
sg = sg_next(sg);
*gtt_offset += alignment_pad + size;
return sg;
}
static struct scatterlist *
remap_color_plane_pages(const struct intel_remapped_info *rem_info,
struct drm_i915_gem_object *obj,
int color_plane,
struct sg_table *st, struct scatterlist *sg,
unsigned int *gtt_offset)
{
unsigned int alignment_pad = 0;
if (rem_info->plane_alignment)
alignment_pad = ALIGN(*gtt_offset, rem_info->plane_alignment) - *gtt_offset;
if (rem_info->plane[color_plane].linear)
sg = remap_linear_color_plane_pages(obj,
rem_info->plane[color_plane].offset,
alignment_pad,
rem_info->plane[color_plane].size,
st, sg,
gtt_offset);
else
sg = remap_tiled_color_plane_pages(obj,
rem_info->plane[color_plane].offset,
alignment_pad,
rem_info->plane[color_plane].width,
rem_info->plane[color_plane].height,
rem_info->plane[color_plane].src_stride,
rem_info->plane[color_plane].dst_stride,
st, sg,
gtt_offset);
return sg;
}
static noinline struct sg_table *
intel_remap_pages(struct intel_remapped_info *rem_info,
struct drm_i915_gem_object *obj)
{
unsigned int size = intel_remapped_info_size(rem_info);
struct drm_i915_private *i915 = to_i915(obj->base.dev);
struct sg_table *st;
struct scatterlist *sg;
unsigned int gtt_offset = 0;
int ret = -ENOMEM;
int i;
/* Allocate target SG list. */
st = kmalloc(sizeof(*st), GFP_KERNEL);
if (!st)
goto err_st_alloc;
ret = sg_alloc_table(st, size, GFP_KERNEL);
if (ret)
goto err_sg_alloc;
st->nents = 0;
sg = st->sgl;
for (i = 0 ; i < ARRAY_SIZE(rem_info->plane); i++)
sg = remap_color_plane_pages(rem_info, obj, i, st, sg, >t_offset);
i915_sg_trim(st);
return st;
err_sg_alloc:
kfree(st);
err_st_alloc:
drm_dbg(&i915->drm, "Failed to create remapped mapping for object size %zu! (%ux%u tiles, %u pages)\n",
obj->base.size, rem_info->plane[0].width,
rem_info->plane[0].height, size);
return ERR_PTR(ret);
}
static noinline struct sg_table *
intel_partial_pages(const struct i915_gtt_view *view,
struct drm_i915_gem_object *obj)
{
struct sg_table *st;
struct scatterlist *sg;
unsigned int count = view->partial.size;
int ret = -ENOMEM;
st = kmalloc(sizeof(*st), GFP_KERNEL);
if (!st)
goto err_st_alloc;
ret = sg_alloc_table(st, count, GFP_KERNEL);
if (ret)
goto err_sg_alloc;
st->nents = 0;
sg = remap_contiguous_pages(obj, view->partial.offset, count, st, st->sgl);
sg_mark_end(sg);
i915_sg_trim(st); /* Drop any unused tail entries. */
return st;
err_sg_alloc:
kfree(st);
err_st_alloc:
return ERR_PTR(ret);
}
static int
__i915_vma_get_pages(struct i915_vma *vma)
{
struct sg_table *pages;
/*
* The vma->pages are only valid within the lifespan of the borrowed
* obj->mm.pages. When the obj->mm.pages sg_table is regenerated, so
* must be the vma->pages. A simple rule is that vma->pages must only
* be accessed when the obj->mm.pages are pinned.
*/
GEM_BUG_ON(!i915_gem_object_has_pinned_pages(vma->obj));
switch (vma->gtt_view.type) {
default:
GEM_BUG_ON(vma->gtt_view.type);
fallthrough;
case I915_GTT_VIEW_NORMAL:
pages = vma->obj->mm.pages;
break;
case I915_GTT_VIEW_ROTATED:
pages =
intel_rotate_pages(&vma->gtt_view.rotated, vma->obj);
break;
case I915_GTT_VIEW_REMAPPED:
pages =
intel_remap_pages(&vma->gtt_view.remapped, vma->obj);
break;
case I915_GTT_VIEW_PARTIAL:
pages = intel_partial_pages(&vma->gtt_view, vma->obj);
break;
}
if (IS_ERR(pages)) {
drm_err(&vma->vm->i915->drm,
"Failed to get pages for VMA view type %u (%ld)!\n",
vma->gtt_view.type, PTR_ERR(pages));
return PTR_ERR(pages);
}
vma->pages = pages;
return 0;
}
I915_SELFTEST_EXPORT int i915_vma_get_pages(struct i915_vma *vma)
{
int err;
if (atomic_add_unless(&vma->pages_count, 1, 0))
return 0;
err = i915_gem_object_pin_pages(vma->obj);
if (err)
return err;
err = __i915_vma_get_pages(vma);
if (err)
goto err_unpin;
vma->page_sizes = vma->obj->mm.page_sizes;
atomic_inc(&vma->pages_count);
return 0;
err_unpin:
__i915_gem_object_unpin_pages(vma->obj);
return err;
}
void vma_invalidate_tlb(struct i915_address_space *vm, u32 *tlb)
{
struct intel_gt *gt;
int id;
if (!tlb)
return;
/*
* Before we release the pages that were bound by this vma, we
* must invalidate all the TLBs that may still have a reference
* back to our physical address. It only needs to be done once,
* so after updating the PTE to point away from the pages, record
* the most recent TLB invalidation seqno, and if we have not yet
* flushed the TLBs upon release, perform a full invalidation.
*/
for_each_gt(gt, vm->i915, id)
WRITE_ONCE(tlb[id],
intel_gt_next_invalidate_tlb_full(gt));
}
static void __vma_put_pages(struct i915_vma *vma, unsigned int count)
{
/* We allocate under vma_get_pages, so beware the shrinker */
GEM_BUG_ON(atomic_read(&vma->pages_count) < count);
if (atomic_sub_return(count, &vma->pages_count) == 0) {
if (vma->pages != vma->obj->mm.pages) {
sg_free_table(vma->pages);
kfree(vma->pages);
}
vma->pages = NULL;
i915_gem_object_unpin_pages(vma->obj);
}
}
I915_SELFTEST_EXPORT void i915_vma_put_pages(struct i915_vma *vma)
{
if (atomic_add_unless(&vma->pages_count, -1, 1))
return;
__vma_put_pages(vma, 1);
}
static void vma_unbind_pages(struct i915_vma *vma)
{
unsigned int count;
lockdep_assert_held(&vma->vm->mutex);
/* The upper portion of pages_count is the number of bindings */
count = atomic_read(&vma->pages_count);
count >>= I915_VMA_PAGES_BIAS;
GEM_BUG_ON(!count);
__vma_put_pages(vma, count | count << I915_VMA_PAGES_BIAS);
}
int i915_vma_pin_ww(struct i915_vma *vma, struct i915_gem_ww_ctx *ww,
u64 size, u64 alignment, u64 flags)
{
struct i915_vma_work *work = NULL;
struct dma_fence *moving = NULL;
struct i915_vma_resource *vma_res = NULL;
intel_wakeref_t wakeref = 0;
unsigned int bound;
int err;
assert_vma_held(vma);
GEM_BUG_ON(!ww);
BUILD_BUG_ON(PIN_GLOBAL != I915_VMA_GLOBAL_BIND);
BUILD_BUG_ON(PIN_USER != I915_VMA_LOCAL_BIND);
GEM_BUG_ON(!(flags & (PIN_USER | PIN_GLOBAL)));
/* First try and grab the pin without rebinding the vma */
if (try_qad_pin(vma, flags))
return 0;
err = i915_vma_get_pages(vma);
if (err)
return err;
if (flags & PIN_GLOBAL)
wakeref = intel_runtime_pm_get(&vma->vm->i915->runtime_pm);
if (flags & vma->vm->bind_async_flags) {
/* lock VM */
err = i915_vm_lock_objects(vma->vm, ww);
if (err)
goto err_rpm;
work = i915_vma_work();
if (!work) {
err = -ENOMEM;
goto err_rpm;
}
work->vm = vma->vm;
err = i915_gem_object_get_moving_fence(vma->obj, &moving);
if (err)
goto err_rpm;
dma_fence_work_chain(&work->base, moving);
/* Allocate enough page directories to used PTE */
if (vma->vm->allocate_va_range) {
err = i915_vm_alloc_pt_stash(vma->vm,
&work->stash,
vma->size);
if (err)
goto err_fence;
err = i915_vm_map_pt_stash(vma->vm, &work->stash);
if (err)
goto err_fence;
}
}
vma_res = i915_vma_resource_alloc();
if (IS_ERR(vma_res)) {
err = PTR_ERR(vma_res);
goto err_fence;
}
/*
* Differentiate between user/kernel vma inside the aliasing-ppgtt.
*
* We conflate the Global GTT with the user's vma when using the
* aliasing-ppgtt, but it is still vitally important to try and
* keep the use cases distinct. For example, userptr objects are
* not allowed inside the Global GTT as that will cause lock
* inversions when we have to evict them the mmu_notifier callbacks -
* but they are allowed to be part of the user ppGTT which can never
* be mapped. As such we try to give the distinct users of the same
* mutex, distinct lockclasses [equivalent to how we keep i915_ggtt
* and i915_ppgtt separate].
*
* NB this may cause us to mask real lock inversions -- while the
* code is safe today, lockdep may not be able to spot future
* transgressions.
*/
err = mutex_lock_interruptible_nested(&vma->vm->mutex,
!(flags & PIN_GLOBAL));
if (err)
goto err_vma_res;
/* No more allocations allowed now we hold vm->mutex */
if (unlikely(i915_vma_is_closed(vma))) {
err = -ENOENT;
goto err_unlock;
}
bound = atomic_read(&vma->flags);
if (unlikely(bound & I915_VMA_ERROR)) {
err = -ENOMEM;
goto err_unlock;
}
if (unlikely(!((bound + 1) & I915_VMA_PIN_MASK))) {
err = -EAGAIN; /* pins are meant to be fairly temporary */
goto err_unlock;
}
if (unlikely(!(flags & ~bound & I915_VMA_BIND_MASK))) {
if (!(flags & PIN_VALIDATE))
__i915_vma_pin(vma);
goto err_unlock;
}
err = i915_active_acquire(&vma->active);
if (err)
goto err_unlock;
if (!(bound & I915_VMA_BIND_MASK)) {
err = i915_vma_insert(vma, ww, size, alignment, flags);
if (err)
goto err_active;
if (i915_is_ggtt(vma->vm))
__i915_vma_set_map_and_fenceable(vma);
}
GEM_BUG_ON(!vma->pages);
err = i915_vma_bind(vma,
vma->obj->pat_index,
flags, work, vma_res);
vma_res = NULL;
if (err)
goto err_remove;
/* There should only be at most 2 active bindings (user, global) */
GEM_BUG_ON(bound + I915_VMA_PAGES_ACTIVE < bound);
atomic_add(I915_VMA_PAGES_ACTIVE, &vma->pages_count);
list_move_tail(&vma->vm_link, &vma->vm->bound_list);
if (!(flags & PIN_VALIDATE)) {
__i915_vma_pin(vma);
GEM_BUG_ON(!i915_vma_is_pinned(vma));
}
GEM_BUG_ON(!i915_vma_is_bound(vma, flags));
GEM_BUG_ON(i915_vma_misplaced(vma, size, alignment, flags));
err_remove:
if (!i915_vma_is_bound(vma, I915_VMA_BIND_MASK)) {
i915_vma_detach(vma);
drm_mm_remove_node(&vma->node);
}
err_active:
i915_active_release(&vma->active);
err_unlock:
mutex_unlock(&vma->vm->mutex);
err_vma_res:
i915_vma_resource_free(vma_res);
err_fence:
if (work)
dma_fence_work_commit_imm(&work->base);
err_rpm:
if (wakeref)
intel_runtime_pm_put(&vma->vm->i915->runtime_pm, wakeref);
if (moving)
dma_fence_put(moving);
i915_vma_put_pages(vma);
return err;
}
static void flush_idle_contexts(struct intel_gt *gt)
{
struct intel_engine_cs *engine;
enum intel_engine_id id;
for_each_engine(engine, gt, id)
intel_engine_flush_barriers(engine);
intel_gt_wait_for_idle(gt, MAX_SCHEDULE_TIMEOUT);
}
static int __i915_ggtt_pin(struct i915_vma *vma, struct i915_gem_ww_ctx *ww,
u32 align, unsigned int flags)
{
struct i915_address_space *vm = vma->vm;
struct intel_gt *gt;
struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
int err;
do {
err = i915_vma_pin_ww(vma, ww, 0, align, flags | PIN_GLOBAL);
if (err != -ENOSPC) {
if (!err) {
err = i915_vma_wait_for_bind(vma);
if (err)
i915_vma_unpin(vma);
}
return err;
}
/* Unlike i915_vma_pin, we don't take no for an answer! */
list_for_each_entry(gt, &ggtt->gt_list, ggtt_link)
flush_idle_contexts(gt);
if (mutex_lock_interruptible(&vm->mutex) == 0) {
/*
* We pass NULL ww here, as we don't want to unbind
* locked objects when called from execbuf when pinning
* is removed. This would probably regress badly.
*/
i915_gem_evict_vm(vm, NULL, NULL);
mutex_unlock(&vm->mutex);
}
} while (1);
}
int i915_ggtt_pin(struct i915_vma *vma, struct i915_gem_ww_ctx *ww,
u32 align, unsigned int flags)
{
struct i915_gem_ww_ctx _ww;
int err;
GEM_BUG_ON(!i915_vma_is_ggtt(vma));
if (ww)
return __i915_ggtt_pin(vma, ww, align, flags);
lockdep_assert_not_held(&vma->obj->base.resv->lock.base);
for_i915_gem_ww(&_ww, err, true) {
err = i915_gem_object_lock(vma->obj, &_ww);
if (!err)
err = __i915_ggtt_pin(vma, &_ww, align, flags);
}
return err;
}
/**
* i915_ggtt_clear_scanout - Clear scanout flag for all objects ggtt vmas
* @obj: i915 GEM object
* This function clears scanout flags for objects ggtt vmas. These flags are set
* when object is pinned for display use and this function to clear them all is
* targeted to be called by frontbuffer tracking code when the frontbuffer is
* about to be released.
*/
void i915_ggtt_clear_scanout(struct drm_i915_gem_object *obj)
{
struct i915_vma *vma;
spin_lock(&obj->vma.lock);
for_each_ggtt_vma(vma, obj) {
i915_vma_clear_scanout(vma);
vma->display_alignment = I915_GTT_MIN_ALIGNMENT;
}
spin_unlock(&obj->vma.lock);
}
static void __vma_close(struct i915_vma *vma, struct intel_gt *gt)
{
/*
* We defer actually closing, unbinding and destroying the VMA until
* the next idle point, or if the object is freed in the meantime. By
* postponing the unbind, we allow for it to be resurrected by the
* client, avoiding the work required to rebind the VMA. This is
* advantageous for DRI, where the client/server pass objects
* between themselves, temporarily opening a local VMA to the
* object, and then closing it again. The same object is then reused
* on the next frame (or two, depending on the depth of the swap queue)
* causing us to rebind the VMA once more. This ends up being a lot
* of wasted work for the steady state.
*/
GEM_BUG_ON(i915_vma_is_closed(vma));
list_add(&vma->closed_link, >->closed_vma);
}
void i915_vma_close(struct i915_vma *vma)
{
struct intel_gt *gt = vma->vm->gt;
unsigned long flags;
if (i915_vma_is_ggtt(vma))
return;
GEM_BUG_ON(!atomic_read(&vma->open_count));
if (atomic_dec_and_lock_irqsave(&vma->open_count,
>->closed_lock,
flags)) {
__vma_close(vma, gt);
spin_unlock_irqrestore(>->closed_lock, flags);
}
}
static void __i915_vma_remove_closed(struct i915_vma *vma)
{
list_del_init(&vma->closed_link);
}
void i915_vma_reopen(struct i915_vma *vma)
{
struct intel_gt *gt = vma->vm->gt;
spin_lock_irq(>->closed_lock);
if (i915_vma_is_closed(vma))
__i915_vma_remove_closed(vma);
spin_unlock_irq(>->closed_lock);
}
static void force_unbind(struct i915_vma *vma)
{
if (!drm_mm_node_allocated(&vma->node))
return;
atomic_and(~I915_VMA_PIN_MASK, &vma->flags);
WARN_ON(__i915_vma_unbind(vma));
GEM_BUG_ON(drm_mm_node_allocated(&vma->node));
}
static void release_references(struct i915_vma *vma, struct intel_gt *gt,
bool vm_ddestroy)
{
struct drm_i915_gem_object *obj = vma->obj;
GEM_BUG_ON(i915_vma_is_active(vma));
spin_lock(&obj->vma.lock);
list_del(&vma->obj_link);
if (!RB_EMPTY_NODE(&vma->obj_node))
rb_erase(&vma->obj_node, &obj->vma.tree);
spin_unlock(&obj->vma.lock);
spin_lock_irq(>->closed_lock);
__i915_vma_remove_closed(vma);
spin_unlock_irq(>->closed_lock);
if (vm_ddestroy)
i915_vm_resv_put(vma->vm);
/* Wait for async active retire */
i915_active_wait(&vma->active);
i915_active_fini(&vma->active);
GEM_WARN_ON(vma->resource);
i915_vma_free(vma);
}
/*
* i915_vma_destroy_locked - Remove all weak reference to the vma and put
* the initial reference.
*
* This function should be called when it's decided the vma isn't needed
* anymore. The caller must assure that it doesn't race with another lookup
* plus destroy, typically by taking an appropriate reference.
*
* Current callsites are
* - __i915_gem_object_pages_fini()
* - __i915_vm_close() - Blocks the above function by taking a reference on
* the object.
* - __i915_vma_parked() - Blocks the above functions by taking a reference
* on the vm and a reference on the object. Also takes the object lock so
* destruction from __i915_vma_parked() can be blocked by holding the
* object lock. Since the object lock is only allowed from within i915 with
* an object refcount, holding the object lock also implicitly blocks the
* vma freeing from __i915_gem_object_pages_fini().
*
* Because of locks taken during destruction, a vma is also guaranteed to
* stay alive while the following locks are held if it was looked up while
* holding one of the locks:
* - vm->mutex
* - obj->vma.lock
* - gt->closed_lock
*/
void i915_vma_destroy_locked(struct i915_vma *vma)
{
lockdep_assert_held(&vma->vm->mutex);
force_unbind(vma);
list_del_init(&vma->vm_link);
release_references(vma, vma->vm->gt, false);
}
void i915_vma_destroy(struct i915_vma *vma)
{
struct intel_gt *gt;
bool vm_ddestroy;
mutex_lock(&vma->vm->mutex);
force_unbind(vma);
list_del_init(&vma->vm_link);
vm_ddestroy = vma->vm_ddestroy;
vma->vm_ddestroy = false;
/* vma->vm may be freed when releasing vma->vm->mutex. */
gt = vma->vm->gt;
mutex_unlock(&vma->vm->mutex);
release_references(vma, gt, vm_ddestroy);
}
void i915_vma_parked(struct intel_gt *gt)
{
struct i915_vma *vma, *next;
LIST_HEAD(closed);
spin_lock_irq(>->closed_lock);
list_for_each_entry_safe(vma, next, >->closed_vma, closed_link) {
struct drm_i915_gem_object *obj = vma->obj;
struct i915_address_space *vm = vma->vm;
/* XXX All to avoid keeping a reference on i915_vma itself */
if (!kref_get_unless_zero(&obj->base.refcount))
continue;
if (!i915_vm_tryget(vm)) {
i915_gem_object_put(obj);
continue;
}
list_move(&vma->closed_link, &closed);
}
spin_unlock_irq(>->closed_lock);
/* As the GT is held idle, no vma can be reopened as we destroy them */
list_for_each_entry_safe(vma, next, &closed, closed_link) {
struct drm_i915_gem_object *obj = vma->obj;
struct i915_address_space *vm = vma->vm;
if (i915_gem_object_trylock(obj, NULL)) {
INIT_LIST_HEAD(&vma->closed_link);
i915_vma_destroy(vma);
i915_gem_object_unlock(obj);
} else {
/* back you go.. */
spin_lock_irq(>->closed_lock);
list_add(&vma->closed_link, >->closed_vma);
spin_unlock_irq(>->closed_lock);
}
i915_gem_object_put(obj);
i915_vm_put(vm);
}
}
static void __i915_vma_iounmap(struct i915_vma *vma)
{
GEM_BUG_ON(i915_vma_is_pinned(vma));
if (vma->iomap == NULL)
return;
if (page_unmask_bits(vma->iomap))
__i915_gem_object_release_map(vma->obj);
else
io_mapping_unmap(vma->iomap);
vma->iomap = NULL;
}
void i915_vma_revoke_mmap(struct i915_vma *vma)
{
struct drm_vma_offset_node *node;
u64 vma_offset;
if (!i915_vma_has_userfault(vma))
return;
GEM_BUG_ON(!i915_vma_is_map_and_fenceable(vma));
GEM_BUG_ON(!vma->obj->userfault_count);
node = &vma->mmo->vma_node;
vma_offset = vma->gtt_view.partial.offset << PAGE_SHIFT;
unmap_mapping_range(vma->vm->i915->drm.anon_inode->i_mapping,
drm_vma_node_offset_addr(node) + vma_offset,
vma->size,
1);
i915_vma_unset_userfault(vma);
if (!--vma->obj->userfault_count)
list_del(&vma->obj->userfault_link);
}
static int
__i915_request_await_bind(struct i915_request *rq, struct i915_vma *vma)
{
return __i915_request_await_exclusive(rq, &vma->active);
}
static int __i915_vma_move_to_active(struct i915_vma *vma, struct i915_request *rq)
{
int err;
/* Wait for the vma to be bound before we start! */
err = __i915_request_await_bind(rq, vma);
if (err)
return err;
return i915_active_add_request(&vma->active, rq);
}
int _i915_vma_move_to_active(struct i915_vma *vma,
struct i915_request *rq,
struct dma_fence *fence,
unsigned int flags)
{
struct drm_i915_gem_object *obj = vma->obj;
int err;
assert_object_held(obj);
GEM_BUG_ON(!vma->pages);
if (!(flags & __EXEC_OBJECT_NO_REQUEST_AWAIT)) {
err = i915_request_await_object(rq, vma->obj, flags & EXEC_OBJECT_WRITE);
if (unlikely(err))
return err;
}
err = __i915_vma_move_to_active(vma, rq);
if (unlikely(err))
return err;
/*
* Reserve fences slot early to prevent an allocation after preparing
* the workload and associating fences with dma_resv.
*/
if (fence && !(flags & __EXEC_OBJECT_NO_RESERVE)) {
struct dma_fence *curr;
int idx;
dma_fence_array_for_each(curr, idx, fence)
;
err = dma_resv_reserve_fences(vma->obj->base.resv, idx);
if (unlikely(err))
return err;
}
if (flags & EXEC_OBJECT_WRITE) {
struct intel_frontbuffer *front;
front = i915_gem_object_get_frontbuffer(obj);
if (unlikely(front)) {
if (intel_frontbuffer_invalidate(front, ORIGIN_CS))
i915_active_add_request(&front->write, rq);
intel_frontbuffer_put(front);
}
}
if (fence) {
struct dma_fence *curr;
enum dma_resv_usage usage;
int idx;
if (flags & EXEC_OBJECT_WRITE) {
usage = DMA_RESV_USAGE_WRITE;
obj->write_domain = I915_GEM_DOMAIN_RENDER;
obj->read_domains = 0;
} else {
usage = DMA_RESV_USAGE_READ;
obj->write_domain = 0;
}
dma_fence_array_for_each(curr, idx, fence)
dma_resv_add_fence(vma->obj->base.resv, curr, usage);
}
if (flags & EXEC_OBJECT_NEEDS_FENCE && vma->fence)
i915_active_add_request(&vma->fence->active, rq);
obj->read_domains |= I915_GEM_GPU_DOMAINS;
obj->mm.dirty = true;
GEM_BUG_ON(!i915_vma_is_active(vma));
return 0;
}
struct dma_fence *__i915_vma_evict(struct i915_vma *vma, bool async)
{
struct i915_vma_resource *vma_res = vma->resource;
struct dma_fence *unbind_fence;
GEM_BUG_ON(i915_vma_is_pinned(vma));
assert_vma_held_evict(vma);
if (i915_vma_is_map_and_fenceable(vma)) {
/* Force a pagefault for domain tracking on next user access */
i915_vma_revoke_mmap(vma);
/*
* Check that we have flushed all writes through the GGTT
* before the unbind, other due to non-strict nature of those
* indirect writes they may end up referencing the GGTT PTE
* after the unbind.
*
* Note that we may be concurrently poking at the GGTT_WRITE
* bit from set-domain, as we mark all GGTT vma associated
* with an object. We know this is for another vma, as we
* are currently unbinding this one -- so if this vma will be
* reused, it will be refaulted and have its dirty bit set
* before the next write.
*/
i915_vma_flush_writes(vma);
/* release the fence reg _after_ flushing */
i915_vma_revoke_fence(vma);
clear_bit(I915_VMA_CAN_FENCE_BIT, __i915_vma_flags(vma));
}
__i915_vma_iounmap(vma);
GEM_BUG_ON(vma->fence);
GEM_BUG_ON(i915_vma_has_userfault(vma));
/* Object backend must be async capable. */
GEM_WARN_ON(async && !vma->resource->bi.pages_rsgt);
/* If vm is not open, unbind is a nop. */
vma_res->needs_wakeref = i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND) &&
kref_read(&vma->vm->ref);
vma_res->skip_pte_rewrite = !kref_read(&vma->vm->ref) ||
vma->vm->skip_pte_rewrite;
trace_i915_vma_unbind(vma);
if (async)
unbind_fence = i915_vma_resource_unbind(vma_res,
vma->obj->mm.tlb);
else
unbind_fence = i915_vma_resource_unbind(vma_res, NULL);
vma->resource = NULL;
atomic_and(~(I915_VMA_BIND_MASK | I915_VMA_ERROR | I915_VMA_GGTT_WRITE),
&vma->flags);
i915_vma_detach(vma);
if (!async) {
if (unbind_fence) {
dma_fence_wait(unbind_fence, false);
dma_fence_put(unbind_fence);
unbind_fence = NULL;
}
vma_invalidate_tlb(vma->vm, vma->obj->mm.tlb);
}
/*
* Binding itself may not have completed until the unbind fence signals,
* so don't drop the pages until that happens, unless the resource is
* async_capable.
*/
vma_unbind_pages(vma);
return unbind_fence;
}
int __i915_vma_unbind(struct i915_vma *vma)
{
int ret;
lockdep_assert_held(&vma->vm->mutex);
assert_vma_held_evict(vma);
if (!drm_mm_node_allocated(&vma->node))
return 0;
if (i915_vma_is_pinned(vma)) {
vma_print_allocator(vma, "is pinned");
return -EAGAIN;
}
/*
* After confirming that no one else is pinning this vma, wait for
* any laggards who may have crept in during the wait (through
* a residual pin skipping the vm->mutex) to complete.
*/
ret = i915_vma_sync(vma);
if (ret)
return ret;
GEM_BUG_ON(i915_vma_is_active(vma));
__i915_vma_evict(vma, false);
drm_mm_remove_node(&vma->node); /* pairs with i915_vma_release() */
return 0;
}
static struct dma_fence *__i915_vma_unbind_async(struct i915_vma *vma)
{
struct dma_fence *fence;
lockdep_assert_held(&vma->vm->mutex);
if (!drm_mm_node_allocated(&vma->node))
return NULL;
if (i915_vma_is_pinned(vma) ||
&vma->obj->mm.rsgt->table != vma->resource->bi.pages)
return ERR_PTR(-EAGAIN);
/*
* We probably need to replace this with awaiting the fences of the
* object's dma_resv when the vma active goes away. When doing that
* we need to be careful to not add the vma_resource unbind fence
* immediately to the object's dma_resv, because then unbinding
* the next vma from the object, in case there are many, will
* actually await the unbinding of the previous vmas, which is
* undesirable.
*/
if (i915_sw_fence_await_active(&vma->resource->chain, &vma->active,
I915_ACTIVE_AWAIT_EXCL |
I915_ACTIVE_AWAIT_ACTIVE) < 0) {
return ERR_PTR(-EBUSY);
}
fence = __i915_vma_evict(vma, true);
drm_mm_remove_node(&vma->node); /* pairs with i915_vma_release() */
return fence;
}
int i915_vma_unbind(struct i915_vma *vma)
{
struct i915_address_space *vm = vma->vm;
intel_wakeref_t wakeref = 0;
int err;
assert_object_held_shared(vma->obj);
/* Optimistic wait before taking the mutex */
err = i915_vma_sync(vma);
if (err)
return err;
if (!drm_mm_node_allocated(&vma->node))
return 0;
if (i915_vma_is_pinned(vma)) {
vma_print_allocator(vma, "is pinned");
return -EAGAIN;
}
if (i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND))
/* XXX not always required: nop_clear_range */
wakeref = intel_runtime_pm_get(&vm->i915->runtime_pm);
err = mutex_lock_interruptible_nested(&vma->vm->mutex, !wakeref);
if (err)
goto out_rpm;
err = __i915_vma_unbind(vma);
mutex_unlock(&vm->mutex);
out_rpm:
if (wakeref)
intel_runtime_pm_put(&vm->i915->runtime_pm, wakeref);
return err;
}
int i915_vma_unbind_async(struct i915_vma *vma, bool trylock_vm)
{
struct drm_i915_gem_object *obj = vma->obj;
struct i915_address_space *vm = vma->vm;
intel_wakeref_t wakeref = 0;
struct dma_fence *fence;
int err;
/*
* We need the dma-resv lock since we add the
* unbind fence to the dma-resv object.
*/
assert_object_held(obj);
if (!drm_mm_node_allocated(&vma->node))
return 0;
if (i915_vma_is_pinned(vma)) {
vma_print_allocator(vma, "is pinned");
return -EAGAIN;
}
if (!obj->mm.rsgt)
return -EBUSY;
err = dma_resv_reserve_fences(obj->base.resv, 2);
if (err)
return -EBUSY;
/*
* It would be great if we could grab this wakeref from the
* async unbind work if needed, but we can't because it uses
* kmalloc and it's in the dma-fence signalling critical path.
*/
if (i915_vma_is_bound(vma, I915_VMA_GLOBAL_BIND))
wakeref = intel_runtime_pm_get(&vm->i915->runtime_pm);
if (trylock_vm && !mutex_trylock(&vm->mutex)) {
err = -EBUSY;
goto out_rpm;
} else if (!trylock_vm) {
err = mutex_lock_interruptible_nested(&vm->mutex, !wakeref);
if (err)
goto out_rpm;
}
fence = __i915_vma_unbind_async(vma);
mutex_unlock(&vm->mutex);
if (IS_ERR_OR_NULL(fence)) {
err = PTR_ERR_OR_ZERO(fence);
goto out_rpm;
}
dma_resv_add_fence(obj->base.resv, fence, DMA_RESV_USAGE_READ);
dma_fence_put(fence);
out_rpm:
if (wakeref)
intel_runtime_pm_put(&vm->i915->runtime_pm, wakeref);
return err;
}
int i915_vma_unbind_unlocked(struct i915_vma *vma)
{
int err;
i915_gem_object_lock(vma->obj, NULL);
err = i915_vma_unbind(vma);
i915_gem_object_unlock(vma->obj);
return err;
}
struct i915_vma *i915_vma_make_unshrinkable(struct i915_vma *vma)
{
i915_gem_object_make_unshrinkable(vma->obj);
return vma;
}
void i915_vma_make_shrinkable(struct i915_vma *vma)
{
i915_gem_object_make_shrinkable(vma->obj);
}
void i915_vma_make_purgeable(struct i915_vma *vma)
{
i915_gem_object_make_purgeable(vma->obj);
}
#if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
#include "selftests/i915_vma.c"
#endif
void i915_vma_module_exit(void)
{
kmem_cache_destroy(slab_vmas);
}
int __init i915_vma_module_init(void)
{
slab_vmas = KMEM_CACHE(i915_vma, SLAB_HWCACHE_ALIGN);
if (!slab_vmas)
return -ENOMEM;
return 0;
}
| linux-master | drivers/gpu/drm/i915/i915_vma.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2021 Intel Corporation
*/
#include <drm/ttm/ttm_device.h>
#include <drm/ttm/ttm_range_manager.h>
#include "i915_drv.h"
#include "i915_scatterlist.h"
#include "i915_ttm_buddy_manager.h"
#include "intel_region_ttm.h"
#include "gem/i915_gem_region.h"
#include "gem/i915_gem_ttm.h" /* For the funcs/ops export only */
/**
* DOC: TTM support structure
*
* The code in this file deals with setting up memory managers for TTM
* LMEM and MOCK regions and converting the output from
* the managers to struct sg_table, Basically providing the mapping from
* i915 GEM regions to TTM memory types and resource managers.
*/
/**
* intel_region_ttm_device_init - Initialize a TTM device
* @dev_priv: Pointer to an i915 device private structure.
*
* Return: 0 on success, negative error code on failure.
*/
int intel_region_ttm_device_init(struct drm_i915_private *dev_priv)
{
struct drm_device *drm = &dev_priv->drm;
return ttm_device_init(&dev_priv->bdev, i915_ttm_driver(),
drm->dev, drm->anon_inode->i_mapping,
drm->vma_offset_manager, false, false);
}
/**
* intel_region_ttm_device_fini - Finalize a TTM device
* @dev_priv: Pointer to an i915 device private structure.
*/
void intel_region_ttm_device_fini(struct drm_i915_private *dev_priv)
{
ttm_device_fini(&dev_priv->bdev);
}
/*
* Map the i915 memory regions to TTM memory types. We use the
* driver-private types for now, reserving TTM_PL_VRAM for stolen
* memory and TTM_PL_TT for GGTT use if decided to implement this.
*/
int intel_region_to_ttm_type(const struct intel_memory_region *mem)
{
int type;
GEM_BUG_ON(mem->type != INTEL_MEMORY_LOCAL &&
mem->type != INTEL_MEMORY_MOCK &&
mem->type != INTEL_MEMORY_SYSTEM);
if (mem->type == INTEL_MEMORY_SYSTEM)
return TTM_PL_SYSTEM;
type = mem->instance + TTM_PL_PRIV;
GEM_BUG_ON(type >= TTM_NUM_MEM_TYPES);
return type;
}
/**
* intel_region_ttm_init - Initialize a memory region for TTM.
* @mem: The region to initialize.
*
* This function initializes a suitable TTM resource manager for the
* region, and if it's a LMEM region type, attaches it to the TTM
* device. MOCK regions are NOT attached to the TTM device, since we don't
* have one for the mock selftests.
*
* Return: 0 on success, negative error code on failure.
*/
int intel_region_ttm_init(struct intel_memory_region *mem)
{
struct ttm_device *bdev = &mem->i915->bdev;
int mem_type = intel_region_to_ttm_type(mem);
int ret;
ret = i915_ttm_buddy_man_init(bdev, mem_type, false,
resource_size(&mem->region),
mem->io_size,
mem->min_page_size, PAGE_SIZE);
if (ret)
return ret;
mem->region_private = ttm_manager_type(bdev, mem_type);
return 0;
}
/**
* intel_region_ttm_fini - Finalize a TTM region.
* @mem: The memory region
*
* This functions takes down the TTM resource manager associated with the
* memory region, and if it was registered with the TTM device,
* removes that registration.
*/
int intel_region_ttm_fini(struct intel_memory_region *mem)
{
struct ttm_resource_manager *man = mem->region_private;
int ret = -EBUSY;
int count;
/*
* Put the region's move fences. This releases requests that
* may hold on to contexts and vms that may hold on to buffer
* objects placed in this region.
*/
if (man)
ttm_resource_manager_cleanup(man);
/* Flush objects from region. */
for (count = 0; count < 10; ++count) {
i915_gem_flush_free_objects(mem->i915);
mutex_lock(&mem->objects.lock);
if (list_empty(&mem->objects.list))
ret = 0;
mutex_unlock(&mem->objects.lock);
if (!ret)
break;
msleep(20);
drain_workqueue(mem->i915->bdev.wq);
}
/* If we leaked objects, Don't free the region causing use after free */
if (ret || !man)
return ret;
ret = i915_ttm_buddy_man_fini(&mem->i915->bdev,
intel_region_to_ttm_type(mem));
GEM_WARN_ON(ret);
mem->region_private = NULL;
return ret;
}
/**
* intel_region_ttm_resource_to_rsgt -
* Convert an opaque TTM resource manager resource to a refcounted sg_table.
* @mem: The memory region.
* @res: The resource manager resource obtained from the TTM resource manager.
* @page_alignment: Required page alignment for each sg entry. Power of two.
*
* The gem backends typically use sg-tables for operations on the underlying
* io_memory. So provide a way for the backends to translate the
* nodes they are handed from TTM to sg-tables.
*
* Return: A malloced sg_table on success, an error pointer on failure.
*/
struct i915_refct_sgt *
intel_region_ttm_resource_to_rsgt(struct intel_memory_region *mem,
struct ttm_resource *res,
u32 page_alignment)
{
if (mem->is_range_manager) {
struct ttm_range_mgr_node *range_node =
to_ttm_range_mgr_node(res);
return i915_rsgt_from_mm_node(&range_node->mm_nodes[0],
mem->region.start,
page_alignment);
} else {
return i915_rsgt_from_buddy_resource(res, mem->region.start,
page_alignment);
}
}
#ifdef CONFIG_DRM_I915_SELFTEST
/**
* intel_region_ttm_resource_alloc - Allocate memory resources from a region
* @mem: The memory region,
* @offset: BO offset
* @size: The requested size in bytes
* @flags: Allocation flags
*
* This functionality is provided only for callers that need to allocate
* memory from standalone TTM range managers, without the TTM eviction
* functionality. Don't use if you are not completely sure that's the
* case. The returned opaque node can be converted to an sg_table using
* intel_region_ttm_resource_to_st(), and can be freed using
* intel_region_ttm_resource_free().
*
* Return: A valid pointer on success, an error pointer on failure.
*/
struct ttm_resource *
intel_region_ttm_resource_alloc(struct intel_memory_region *mem,
resource_size_t offset,
resource_size_t size,
unsigned int flags)
{
struct ttm_resource_manager *man = mem->region_private;
struct ttm_place place = {};
struct ttm_buffer_object mock_bo = {};
struct ttm_resource *res;
int ret;
if (flags & I915_BO_ALLOC_CONTIGUOUS)
place.flags |= TTM_PL_FLAG_CONTIGUOUS;
if (offset != I915_BO_INVALID_OFFSET) {
if (WARN_ON(overflows_type(offset >> PAGE_SHIFT, place.fpfn))) {
ret = -E2BIG;
goto out;
}
place.fpfn = offset >> PAGE_SHIFT;
if (WARN_ON(overflows_type(place.fpfn + (size >> PAGE_SHIFT), place.lpfn))) {
ret = -E2BIG;
goto out;
}
place.lpfn = place.fpfn + (size >> PAGE_SHIFT);
} else if (mem->io_size && mem->io_size < mem->total) {
if (flags & I915_BO_ALLOC_GPU_ONLY) {
place.flags |= TTM_PL_FLAG_TOPDOWN;
} else {
place.fpfn = 0;
if (WARN_ON(overflows_type(mem->io_size >> PAGE_SHIFT, place.lpfn))) {
ret = -E2BIG;
goto out;
}
place.lpfn = mem->io_size >> PAGE_SHIFT;
}
}
mock_bo.base.size = size;
mock_bo.bdev = &mem->i915->bdev;
ret = man->func->alloc(man, &mock_bo, &place, &res);
out:
if (ret == -ENOSPC)
ret = -ENXIO;
if (!ret)
res->bo = NULL; /* Rather blow up, then some uaf */
return ret ? ERR_PTR(ret) : res;
}
#endif
/**
* intel_region_ttm_resource_free - Free a resource allocated from a resource manager
* @mem: The region the resource was allocated from.
* @res: The opaque resource representing an allocation.
*/
void intel_region_ttm_resource_free(struct intel_memory_region *mem,
struct ttm_resource *res)
{
struct ttm_resource_manager *man = mem->region_private;
struct ttm_buffer_object mock_bo = {};
mock_bo.base.size = res->size;
mock_bo.bdev = &mem->i915->bdev;
res->bo = &mock_bo;
man->func->free(man, res);
}
| linux-master | drivers/gpu/drm/i915/intel_region_ttm.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2019 Intel Corporation
*/
#include <linux/vga_switcheroo.h>
#include "i915_driver.h"
#include "i915_drv.h"
#include "i915_switcheroo.h"
static void i915_switcheroo_set_state(struct pci_dev *pdev,
enum vga_switcheroo_state state)
{
struct drm_i915_private *i915 = pdev_to_i915(pdev);
pm_message_t pmm = { .event = PM_EVENT_SUSPEND };
if (!i915) {
dev_err(&pdev->dev, "DRM not initialized, aborting switch.\n");
return;
}
if (!HAS_DISPLAY(i915)) {
dev_err(&pdev->dev, "Device state not initialized, aborting switch.\n");
return;
}
if (state == VGA_SWITCHEROO_ON) {
drm_info(&i915->drm, "switched on\n");
i915->drm.switch_power_state = DRM_SWITCH_POWER_CHANGING;
/* i915 resume handler doesn't set to D0 */
pci_set_power_state(pdev, PCI_D0);
i915_driver_resume_switcheroo(i915);
i915->drm.switch_power_state = DRM_SWITCH_POWER_ON;
} else {
drm_info(&i915->drm, "switched off\n");
i915->drm.switch_power_state = DRM_SWITCH_POWER_CHANGING;
i915_driver_suspend_switcheroo(i915, pmm);
i915->drm.switch_power_state = DRM_SWITCH_POWER_OFF;
}
}
static bool i915_switcheroo_can_switch(struct pci_dev *pdev)
{
struct drm_i915_private *i915 = pdev_to_i915(pdev);
/*
* FIXME: open_count is protected by drm_global_mutex but that would lead to
* locking inversion with the driver load path. And the access here is
* completely racy anyway. So don't bother with locking for now.
*/
return i915 && HAS_DISPLAY(i915) && atomic_read(&i915->drm.open_count) == 0;
}
static const struct vga_switcheroo_client_ops i915_switcheroo_ops = {
.set_gpu_state = i915_switcheroo_set_state,
.reprobe = NULL,
.can_switch = i915_switcheroo_can_switch,
};
int i915_switcheroo_register(struct drm_i915_private *i915)
{
struct pci_dev *pdev = to_pci_dev(i915->drm.dev);
return vga_switcheroo_register_client(pdev, &i915_switcheroo_ops, false);
}
void i915_switcheroo_unregister(struct drm_i915_private *i915)
{
struct pci_dev *pdev = to_pci_dev(i915->drm.dev);
vga_switcheroo_unregister_client(pdev);
}
| linux-master | drivers/gpu/drm/i915/i915_switcheroo.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2020,2021 Intel Corporation
*/
#include "i915_drv.h"
#include "intel_step.h"
/*
* Some platforms have unusual ways of mapping PCI revision ID to GT/display
* steppings. E.g., in some cases a higher PCI revision may translate to a
* lower stepping of the GT and/or display IP. This file provides lookup
* tables to map the PCI revision into a standard set of stepping values that
* can be compared numerically.
*
* Also note that some revisions/steppings may have been set aside as
* placeholders but never materialized in real hardware; in those cases there
* may be jumps in the revision IDs or stepping values in the tables below.
*/
/*
* Some platforms always have the same stepping value for GT and display;
* use a macro to define these to make it easier to identify the platforms
* where the two steppings can deviate.
*/
#define COMMON_STEP(x) .graphics_step = STEP_##x, .display_step = STEP_##x, .media_step = STEP_##x
#define COMMON_GT_MEDIA_STEP(x) .graphics_step = STEP_##x, .media_step = STEP_##x
static const struct intel_step_info skl_revids[] = {
[0x6] = { COMMON_STEP(G0) },
[0x7] = { COMMON_STEP(H0) },
[0x9] = { COMMON_STEP(J0) },
[0xA] = { COMMON_STEP(I1) },
};
static const struct intel_step_info kbl_revids[] = {
[1] = { COMMON_GT_MEDIA_STEP(B0), .display_step = STEP_B0 },
[2] = { COMMON_GT_MEDIA_STEP(C0), .display_step = STEP_B0 },
[3] = { COMMON_GT_MEDIA_STEP(D0), .display_step = STEP_B0 },
[4] = { COMMON_GT_MEDIA_STEP(F0), .display_step = STEP_C0 },
[5] = { COMMON_GT_MEDIA_STEP(C0), .display_step = STEP_B1 },
[6] = { COMMON_GT_MEDIA_STEP(D1), .display_step = STEP_B1 },
[7] = { COMMON_GT_MEDIA_STEP(G0), .display_step = STEP_C0 },
};
static const struct intel_step_info bxt_revids[] = {
[0xA] = { COMMON_STEP(C0) },
[0xB] = { COMMON_STEP(C0) },
[0xC] = { COMMON_STEP(D0) },
[0xD] = { COMMON_STEP(E0) },
};
static const struct intel_step_info glk_revids[] = {
[3] = { COMMON_STEP(B0) },
};
static const struct intel_step_info icl_revids[] = {
[7] = { COMMON_STEP(D0) },
};
static const struct intel_step_info jsl_ehl_revids[] = {
[0] = { COMMON_STEP(A0) },
[1] = { COMMON_STEP(B0) },
};
static const struct intel_step_info tgl_uy_revids[] = {
[0] = { COMMON_GT_MEDIA_STEP(A0), .display_step = STEP_A0 },
[1] = { COMMON_GT_MEDIA_STEP(B0), .display_step = STEP_C0 },
[2] = { COMMON_GT_MEDIA_STEP(B1), .display_step = STEP_C0 },
[3] = { COMMON_GT_MEDIA_STEP(C0), .display_step = STEP_D0 },
};
/* Same GT stepping between tgl_uy_revids and tgl_revids don't mean the same HW */
static const struct intel_step_info tgl_revids[] = {
[0] = { COMMON_GT_MEDIA_STEP(A0), .display_step = STEP_B0 },
[1] = { COMMON_GT_MEDIA_STEP(B0), .display_step = STEP_D0 },
};
static const struct intel_step_info rkl_revids[] = {
[0] = { COMMON_STEP(A0) },
[1] = { COMMON_STEP(B0) },
[4] = { COMMON_STEP(C0) },
};
static const struct intel_step_info dg1_revids[] = {
[0] = { COMMON_STEP(A0) },
[1] = { COMMON_STEP(B0) },
};
static const struct intel_step_info adls_revids[] = {
[0x0] = { COMMON_GT_MEDIA_STEP(A0), .display_step = STEP_A0 },
[0x1] = { COMMON_GT_MEDIA_STEP(A0), .display_step = STEP_A2 },
[0x4] = { COMMON_GT_MEDIA_STEP(B0), .display_step = STEP_B0 },
[0x8] = { COMMON_GT_MEDIA_STEP(C0), .display_step = STEP_B0 },
[0xC] = { COMMON_GT_MEDIA_STEP(D0), .display_step = STEP_C0 },
};
static const struct intel_step_info adlp_revids[] = {
[0x0] = { COMMON_GT_MEDIA_STEP(A0), .display_step = STEP_A0 },
[0x4] = { COMMON_GT_MEDIA_STEP(B0), .display_step = STEP_B0 },
[0x8] = { COMMON_GT_MEDIA_STEP(C0), .display_step = STEP_C0 },
[0xC] = { COMMON_GT_MEDIA_STEP(C0), .display_step = STEP_D0 },
};
static const struct intel_step_info xehpsdv_revids[] = {
[0x0] = { COMMON_GT_MEDIA_STEP(A0) },
[0x1] = { COMMON_GT_MEDIA_STEP(A1) },
[0x4] = { COMMON_GT_MEDIA_STEP(B0) },
[0x8] = { COMMON_GT_MEDIA_STEP(C0) },
};
static const struct intel_step_info dg2_g10_revid_step_tbl[] = {
[0x0] = { COMMON_GT_MEDIA_STEP(A0), .display_step = STEP_A0 },
[0x1] = { COMMON_GT_MEDIA_STEP(A1), .display_step = STEP_A0 },
[0x4] = { COMMON_GT_MEDIA_STEP(B0), .display_step = STEP_B0 },
[0x8] = { COMMON_GT_MEDIA_STEP(C0), .display_step = STEP_C0 },
};
static const struct intel_step_info dg2_g11_revid_step_tbl[] = {
[0x0] = { COMMON_GT_MEDIA_STEP(A0), .display_step = STEP_B0 },
[0x4] = { COMMON_GT_MEDIA_STEP(B0), .display_step = STEP_C0 },
[0x5] = { COMMON_GT_MEDIA_STEP(B1), .display_step = STEP_C0 },
};
static const struct intel_step_info dg2_g12_revid_step_tbl[] = {
[0x0] = { COMMON_GT_MEDIA_STEP(A0), .display_step = STEP_C0 },
};
static const struct intel_step_info adls_rpls_revids[] = {
[0x4] = { COMMON_GT_MEDIA_STEP(D0), .display_step = STEP_D0 },
[0xC] = { COMMON_GT_MEDIA_STEP(D0), .display_step = STEP_C0 },
};
static const struct intel_step_info adlp_rplp_revids[] = {
[0x4] = { COMMON_GT_MEDIA_STEP(C0), .display_step = STEP_E0 },
};
static const struct intel_step_info adlp_n_revids[] = {
[0x0] = { COMMON_GT_MEDIA_STEP(A0), .display_step = STEP_D0 },
};
static u8 gmd_to_intel_step(struct drm_i915_private *i915,
struct intel_ip_version *gmd)
{
u8 step = gmd->step + STEP_A0;
if (step >= STEP_FUTURE) {
drm_dbg(&i915->drm, "Using future steppings\n");
return STEP_FUTURE;
}
return step;
}
static void pvc_step_init(struct drm_i915_private *i915, int pci_revid);
void intel_step_init(struct drm_i915_private *i915)
{
const struct intel_step_info *revids = NULL;
int size = 0;
int revid = INTEL_REVID(i915);
struct intel_step_info step = {};
if (HAS_GMD_ID(i915)) {
step.graphics_step = gmd_to_intel_step(i915,
&RUNTIME_INFO(i915)->graphics.ip);
step.media_step = gmd_to_intel_step(i915,
&RUNTIME_INFO(i915)->media.ip);
step.display_step = STEP_A0 + DISPLAY_RUNTIME_INFO(i915)->ip.step;
if (step.display_step >= STEP_FUTURE) {
drm_dbg(&i915->drm, "Using future display steppings\n");
step.display_step = STEP_FUTURE;
}
RUNTIME_INFO(i915)->step = step;
return;
}
if (IS_PONTEVECCHIO(i915)) {
pvc_step_init(i915, revid);
return;
} else if (IS_DG2_G10(i915)) {
revids = dg2_g10_revid_step_tbl;
size = ARRAY_SIZE(dg2_g10_revid_step_tbl);
} else if (IS_DG2_G11(i915)) {
revids = dg2_g11_revid_step_tbl;
size = ARRAY_SIZE(dg2_g11_revid_step_tbl);
} else if (IS_DG2_G12(i915)) {
revids = dg2_g12_revid_step_tbl;
size = ARRAY_SIZE(dg2_g12_revid_step_tbl);
} else if (IS_XEHPSDV(i915)) {
revids = xehpsdv_revids;
size = ARRAY_SIZE(xehpsdv_revids);
} else if (IS_ALDERLAKE_P_N(i915)) {
revids = adlp_n_revids;
size = ARRAY_SIZE(adlp_n_revids);
} else if (IS_RAPTORLAKE_P(i915)) {
revids = adlp_rplp_revids;
size = ARRAY_SIZE(adlp_rplp_revids);
} else if (IS_ALDERLAKE_P(i915)) {
revids = adlp_revids;
size = ARRAY_SIZE(adlp_revids);
} else if (IS_RAPTORLAKE_S(i915)) {
revids = adls_rpls_revids;
size = ARRAY_SIZE(adls_rpls_revids);
} else if (IS_ALDERLAKE_S(i915)) {
revids = adls_revids;
size = ARRAY_SIZE(adls_revids);
} else if (IS_DG1(i915)) {
revids = dg1_revids;
size = ARRAY_SIZE(dg1_revids);
} else if (IS_ROCKETLAKE(i915)) {
revids = rkl_revids;
size = ARRAY_SIZE(rkl_revids);
} else if (IS_TIGERLAKE_UY(i915)) {
revids = tgl_uy_revids;
size = ARRAY_SIZE(tgl_uy_revids);
} else if (IS_TIGERLAKE(i915)) {
revids = tgl_revids;
size = ARRAY_SIZE(tgl_revids);
} else if (IS_JASPERLAKE(i915) || IS_ELKHARTLAKE(i915)) {
revids = jsl_ehl_revids;
size = ARRAY_SIZE(jsl_ehl_revids);
} else if (IS_ICELAKE(i915)) {
revids = icl_revids;
size = ARRAY_SIZE(icl_revids);
} else if (IS_GEMINILAKE(i915)) {
revids = glk_revids;
size = ARRAY_SIZE(glk_revids);
} else if (IS_BROXTON(i915)) {
revids = bxt_revids;
size = ARRAY_SIZE(bxt_revids);
} else if (IS_KABYLAKE(i915)) {
revids = kbl_revids;
size = ARRAY_SIZE(kbl_revids);
} else if (IS_SKYLAKE(i915)) {
revids = skl_revids;
size = ARRAY_SIZE(skl_revids);
}
/* Not using the stepping scheme for the platform yet. */
if (!revids)
return;
if (revid < size && revids[revid].graphics_step != STEP_NONE) {
step = revids[revid];
} else {
drm_warn(&i915->drm, "Unknown revid 0x%02x\n", revid);
/*
* If we hit a gap in the revid array, use the information for
* the next revid.
*
* This may be wrong in all sorts of ways, especially if the
* steppings in the array are not monotonically increasing, but
* it's better than defaulting to 0.
*/
while (revid < size && revids[revid].graphics_step == STEP_NONE)
revid++;
if (revid < size) {
drm_dbg(&i915->drm, "Using steppings for revid 0x%02x\n",
revid);
step = revids[revid];
} else {
drm_dbg(&i915->drm, "Using future steppings\n");
step.graphics_step = STEP_FUTURE;
step.display_step = STEP_FUTURE;
}
}
if (drm_WARN_ON(&i915->drm, step.graphics_step == STEP_NONE))
return;
RUNTIME_INFO(i915)->step = step;
}
#define PVC_BD_REVID GENMASK(5, 3)
#define PVC_CT_REVID GENMASK(2, 0)
static const int pvc_bd_subids[] = {
[0x0] = STEP_A0,
[0x3] = STEP_B0,
[0x4] = STEP_B1,
[0x5] = STEP_B3,
};
static const int pvc_ct_subids[] = {
[0x3] = STEP_A0,
[0x5] = STEP_B0,
[0x6] = STEP_B1,
[0x7] = STEP_C0,
};
static int
pvc_step_lookup(struct drm_i915_private *i915, const char *type,
const int *table, int size, int subid)
{
if (subid < size && table[subid] != STEP_NONE)
return table[subid];
drm_warn(&i915->drm, "Unknown %s id 0x%02x\n", type, subid);
/*
* As on other platforms, try to use the next higher ID if we land on a
* gap in the table.
*/
while (subid < size && table[subid] == STEP_NONE)
subid++;
if (subid < size) {
drm_dbg(&i915->drm, "Using steppings for %s id 0x%02x\n",
type, subid);
return table[subid];
}
drm_dbg(&i915->drm, "Using future steppings\n");
return STEP_FUTURE;
}
/*
* PVC needs special handling since we don't lookup the
* revid in a table, but rather specific bitfields within
* the revid for various components.
*/
static void pvc_step_init(struct drm_i915_private *i915, int pci_revid)
{
int ct_subid, bd_subid;
bd_subid = FIELD_GET(PVC_BD_REVID, pci_revid);
ct_subid = FIELD_GET(PVC_CT_REVID, pci_revid);
RUNTIME_INFO(i915)->step.basedie_step =
pvc_step_lookup(i915, "Base Die", pvc_bd_subids,
ARRAY_SIZE(pvc_bd_subids), bd_subid);
RUNTIME_INFO(i915)->step.graphics_step =
pvc_step_lookup(i915, "Compute Tile", pvc_ct_subids,
ARRAY_SIZE(pvc_ct_subids), ct_subid);
}
#define STEP_NAME_CASE(name) \
case STEP_##name: \
return #name;
const char *intel_step_name(enum intel_step step)
{
switch (step) {
STEP_NAME_LIST(STEP_NAME_CASE);
default:
return "**";
}
}
| linux-master | drivers/gpu/drm/i915/intel_step.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2021 Intel Corporation
*/
#include <linux/interval_tree_generic.h>
#include <linux/sched/mm.h>
#include "i915_sw_fence.h"
#include "i915_vma_resource.h"
#include "i915_drv.h"
#include "intel_memory_region.h"
#include "gt/intel_gtt.h"
static struct kmem_cache *slab_vma_resources;
/**
* DOC:
* We use a per-vm interval tree to keep track of vma_resources
* scheduled for unbind but not yet unbound. The tree is protected by
* the vm mutex, and nodes are removed just after the unbind fence signals.
* The removal takes the vm mutex from a kernel thread which we need to
* keep in mind so that we don't grab the mutex and try to wait for all
* pending unbinds to complete, because that will temporaryily block many
* of the workqueue threads, and people will get angry.
*
* We should consider using a single ordered fence per VM instead but that
* requires ordering the unbinds and might introduce unnecessary waiting
* for unrelated unbinds. Amount of code will probably be roughly the same
* due to the simplicity of using the interval tree interface.
*
* Another drawback of this interval tree is that the complexity of insertion
* and removal of fences increases as O(ln(pending_unbinds)) instead of
* O(1) for a single fence without interval tree.
*/
#define VMA_RES_START(_node) ((_node)->start - (_node)->guard)
#define VMA_RES_LAST(_node) ((_node)->start + (_node)->node_size + (_node)->guard - 1)
INTERVAL_TREE_DEFINE(struct i915_vma_resource, rb,
u64, __subtree_last,
VMA_RES_START, VMA_RES_LAST, static, vma_res_itree);
/* Callbacks for the unbind dma-fence. */
/**
* i915_vma_resource_alloc - Allocate a vma resource
*
* Return: A pointer to a cleared struct i915_vma_resource or
* a -ENOMEM error pointer if allocation fails.
*/
struct i915_vma_resource *i915_vma_resource_alloc(void)
{
struct i915_vma_resource *vma_res =
kmem_cache_zalloc(slab_vma_resources, GFP_KERNEL);
return vma_res ? vma_res : ERR_PTR(-ENOMEM);
}
/**
* i915_vma_resource_free - Free a vma resource
* @vma_res: The vma resource to free.
*/
void i915_vma_resource_free(struct i915_vma_resource *vma_res)
{
if (vma_res)
kmem_cache_free(slab_vma_resources, vma_res);
}
static const char *get_driver_name(struct dma_fence *fence)
{
return "vma unbind fence";
}
static const char *get_timeline_name(struct dma_fence *fence)
{
return "unbound";
}
static void unbind_fence_free_rcu(struct rcu_head *head)
{
struct i915_vma_resource *vma_res =
container_of(head, typeof(*vma_res), unbind_fence.rcu);
i915_vma_resource_free(vma_res);
}
static void unbind_fence_release(struct dma_fence *fence)
{
struct i915_vma_resource *vma_res =
container_of(fence, typeof(*vma_res), unbind_fence);
i915_sw_fence_fini(&vma_res->chain);
call_rcu(&fence->rcu, unbind_fence_free_rcu);
}
static struct dma_fence_ops unbind_fence_ops = {
.get_driver_name = get_driver_name,
.get_timeline_name = get_timeline_name,
.release = unbind_fence_release,
};
static void __i915_vma_resource_unhold(struct i915_vma_resource *vma_res)
{
struct i915_address_space *vm;
if (!refcount_dec_and_test(&vma_res->hold_count))
return;
dma_fence_signal(&vma_res->unbind_fence);
vm = vma_res->vm;
if (vma_res->wakeref)
intel_runtime_pm_put(&vm->i915->runtime_pm, vma_res->wakeref);
vma_res->vm = NULL;
if (!RB_EMPTY_NODE(&vma_res->rb)) {
mutex_lock(&vm->mutex);
vma_res_itree_remove(vma_res, &vm->pending_unbind);
mutex_unlock(&vm->mutex);
}
if (vma_res->bi.pages_rsgt)
i915_refct_sgt_put(vma_res->bi.pages_rsgt);
}
/**
* i915_vma_resource_unhold - Unhold the signaling of the vma resource unbind
* fence.
* @vma_res: The vma resource.
* @lockdep_cookie: The lockdep cookie returned from i915_vma_resource_hold.
*
* The function may leave a dma_fence critical section.
*/
void i915_vma_resource_unhold(struct i915_vma_resource *vma_res,
bool lockdep_cookie)
{
dma_fence_end_signalling(lockdep_cookie);
if (IS_ENABLED(CONFIG_PROVE_LOCKING)) {
unsigned long irq_flags;
/* Inefficient open-coded might_lock_irqsave() */
spin_lock_irqsave(&vma_res->lock, irq_flags);
spin_unlock_irqrestore(&vma_res->lock, irq_flags);
}
__i915_vma_resource_unhold(vma_res);
}
/**
* i915_vma_resource_hold - Hold the signaling of the vma resource unbind fence.
* @vma_res: The vma resource.
* @lockdep_cookie: Pointer to a bool serving as a lockdep cooke that should
* be given as an argument to the pairing i915_vma_resource_unhold.
*
* If returning true, the function enters a dma_fence signalling critical
* section if not in one already.
*
* Return: true if holding successful, false if not.
*/
bool i915_vma_resource_hold(struct i915_vma_resource *vma_res,
bool *lockdep_cookie)
{
bool held = refcount_inc_not_zero(&vma_res->hold_count);
if (held)
*lockdep_cookie = dma_fence_begin_signalling();
return held;
}
static void i915_vma_resource_unbind_work(struct work_struct *work)
{
struct i915_vma_resource *vma_res =
container_of(work, typeof(*vma_res), work);
struct i915_address_space *vm = vma_res->vm;
bool lockdep_cookie;
lockdep_cookie = dma_fence_begin_signalling();
if (likely(!vma_res->skip_pte_rewrite))
vma_res->ops->unbind_vma(vm, vma_res);
dma_fence_end_signalling(lockdep_cookie);
__i915_vma_resource_unhold(vma_res);
i915_vma_resource_put(vma_res);
}
static int
i915_vma_resource_fence_notify(struct i915_sw_fence *fence,
enum i915_sw_fence_notify state)
{
struct i915_vma_resource *vma_res =
container_of(fence, typeof(*vma_res), chain);
struct dma_fence *unbind_fence =
&vma_res->unbind_fence;
switch (state) {
case FENCE_COMPLETE:
dma_fence_get(unbind_fence);
if (vma_res->immediate_unbind) {
i915_vma_resource_unbind_work(&vma_res->work);
} else {
INIT_WORK(&vma_res->work, i915_vma_resource_unbind_work);
queue_work(system_unbound_wq, &vma_res->work);
}
break;
case FENCE_FREE:
i915_vma_resource_put(vma_res);
break;
}
return NOTIFY_DONE;
}
/**
* i915_vma_resource_unbind - Unbind a vma resource
* @vma_res: The vma resource to unbind.
* @tlb: pointer to vma->obj->mm.tlb associated with the resource
* to be stored at vma_res->tlb. When not-NULL, it will be used
* to do TLB cache invalidation before freeing a VMA resource.
* Used only for async unbind.
*
* At this point this function does little more than publish a fence that
* signals immediately unless signaling is held back.
*
* Return: A refcounted pointer to a dma-fence that signals when unbinding is
* complete.
*/
struct dma_fence *i915_vma_resource_unbind(struct i915_vma_resource *vma_res,
u32 *tlb)
{
struct i915_address_space *vm = vma_res->vm;
vma_res->tlb = tlb;
/* Reference for the sw fence */
i915_vma_resource_get(vma_res);
/* Caller must already have a wakeref in this case. */
if (vma_res->needs_wakeref)
vma_res->wakeref = intel_runtime_pm_get_if_in_use(&vm->i915->runtime_pm);
if (atomic_read(&vma_res->chain.pending) <= 1) {
RB_CLEAR_NODE(&vma_res->rb);
vma_res->immediate_unbind = 1;
} else {
vma_res_itree_insert(vma_res, &vma_res->vm->pending_unbind);
}
i915_sw_fence_commit(&vma_res->chain);
return &vma_res->unbind_fence;
}
/**
* __i915_vma_resource_init - Initialize a vma resource.
* @vma_res: The vma resource to initialize
*
* Initializes the private members of a vma resource.
*/
void __i915_vma_resource_init(struct i915_vma_resource *vma_res)
{
spin_lock_init(&vma_res->lock);
dma_fence_init(&vma_res->unbind_fence, &unbind_fence_ops,
&vma_res->lock, 0, 0);
refcount_set(&vma_res->hold_count, 1);
i915_sw_fence_init(&vma_res->chain, i915_vma_resource_fence_notify);
}
static void
i915_vma_resource_color_adjust_range(struct i915_address_space *vm,
u64 *start,
u64 *end)
{
if (i915_vm_has_cache_coloring(vm)) {
if (*start)
*start -= I915_GTT_PAGE_SIZE;
*end += I915_GTT_PAGE_SIZE;
}
}
/**
* i915_vma_resource_bind_dep_sync - Wait for / sync all unbinds touching a
* certain vm range.
* @vm: The vm to look at.
* @offset: The range start.
* @size: The range size.
* @intr: Whether to wait interrubtible.
*
* The function needs to be called with the vm lock held.
*
* Return: Zero on success, -ERESTARTSYS if interrupted and @intr==true
*/
int i915_vma_resource_bind_dep_sync(struct i915_address_space *vm,
u64 offset,
u64 size,
bool intr)
{
struct i915_vma_resource *node;
u64 last = offset + size - 1;
lockdep_assert_held(&vm->mutex);
might_sleep();
i915_vma_resource_color_adjust_range(vm, &offset, &last);
node = vma_res_itree_iter_first(&vm->pending_unbind, offset, last);
while (node) {
int ret = dma_fence_wait(&node->unbind_fence, intr);
if (ret)
return ret;
node = vma_res_itree_iter_next(node, offset, last);
}
return 0;
}
/**
* i915_vma_resource_bind_dep_sync_all - Wait for / sync all unbinds of a vm,
* releasing the vm lock while waiting.
* @vm: The vm to look at.
*
* The function may not be called with the vm lock held.
* Typically this is called at vm destruction to finish any pending
* unbind operations. The vm mutex is released while waiting to avoid
* stalling kernel workqueues trying to grab the mutex.
*/
void i915_vma_resource_bind_dep_sync_all(struct i915_address_space *vm)
{
struct i915_vma_resource *node;
struct dma_fence *fence;
do {
fence = NULL;
mutex_lock(&vm->mutex);
node = vma_res_itree_iter_first(&vm->pending_unbind, 0,
U64_MAX);
if (node)
fence = dma_fence_get_rcu(&node->unbind_fence);
mutex_unlock(&vm->mutex);
if (fence) {
/*
* The wait makes sure the node eventually removes
* itself from the tree.
*/
dma_fence_wait(fence, false);
dma_fence_put(fence);
}
} while (node);
}
/**
* i915_vma_resource_bind_dep_await - Have a struct i915_sw_fence await all
* pending unbinds in a certain range of a vm.
* @vm: The vm to look at.
* @sw_fence: The struct i915_sw_fence that will be awaiting the unbinds.
* @offset: The range start.
* @size: The range size.
* @intr: Whether to wait interrubtible.
* @gfp: Allocation mode for memory allocations.
*
* The function makes @sw_fence await all pending unbinds in a certain
* vm range before calling the complete notifier. To be able to await
* each individual unbind, the function needs to allocate memory using
* the @gpf allocation mode. If that fails, the function will instead
* wait for the unbind fence to signal, using @intr to judge whether to
* wait interruptible or not. Note that @gfp should ideally be selected so
* as to avoid any expensive memory allocation stalls and rather fail and
* synchronize itself. For now the vm mutex is required when calling this
* function with means that @gfp can't call into direct reclaim. In reality
* this means that during heavy memory pressure, we will sync in this
* function.
*
* Return: Zero on success, -ERESTARTSYS if interrupted and @intr==true
*/
int i915_vma_resource_bind_dep_await(struct i915_address_space *vm,
struct i915_sw_fence *sw_fence,
u64 offset,
u64 size,
bool intr,
gfp_t gfp)
{
struct i915_vma_resource *node;
u64 last = offset + size - 1;
lockdep_assert_held(&vm->mutex);
might_alloc(gfp);
might_sleep();
i915_vma_resource_color_adjust_range(vm, &offset, &last);
node = vma_res_itree_iter_first(&vm->pending_unbind, offset, last);
while (node) {
int ret;
ret = i915_sw_fence_await_dma_fence(sw_fence,
&node->unbind_fence,
0, gfp);
if (ret < 0) {
ret = dma_fence_wait(&node->unbind_fence, intr);
if (ret)
return ret;
}
node = vma_res_itree_iter_next(node, offset, last);
}
return 0;
}
void i915_vma_resource_module_exit(void)
{
kmem_cache_destroy(slab_vma_resources);
}
int __init i915_vma_resource_module_init(void)
{
slab_vma_resources = KMEM_CACHE(i915_vma_resource, SLAB_HWCACHE_ALIGN);
if (!slab_vma_resources)
return -ENOMEM;
return 0;
}
| linux-master | drivers/gpu/drm/i915/i915_vma_resource.c |
/*
* Copyright © 2017 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
#include <linux/completion.h>
#include <linux/delay.h>
#include <linux/prime_numbers.h>
#include "../i915_selftest.h"
static int
fence_notify(struct i915_sw_fence *fence, enum i915_sw_fence_notify state)
{
switch (state) {
case FENCE_COMPLETE:
break;
case FENCE_FREE:
/* Leave the fence for the caller to free it after testing */
break;
}
return NOTIFY_DONE;
}
static struct i915_sw_fence *alloc_fence(void)
{
struct i915_sw_fence *fence;
fence = kmalloc(sizeof(*fence), GFP_KERNEL);
if (!fence)
return NULL;
i915_sw_fence_init(fence, fence_notify);
return fence;
}
static void free_fence(struct i915_sw_fence *fence)
{
i915_sw_fence_fini(fence);
kfree(fence);
}
static int __test_self(struct i915_sw_fence *fence)
{
if (i915_sw_fence_done(fence))
return -EINVAL;
i915_sw_fence_commit(fence);
if (!i915_sw_fence_done(fence))
return -EINVAL;
i915_sw_fence_wait(fence);
if (!i915_sw_fence_done(fence))
return -EINVAL;
return 0;
}
static int test_self(void *arg)
{
struct i915_sw_fence *fence;
int ret;
/* Test i915_sw_fence signaling and completion testing */
fence = alloc_fence();
if (!fence)
return -ENOMEM;
ret = __test_self(fence);
free_fence(fence);
return ret;
}
static int test_dag(void *arg)
{
struct i915_sw_fence *A, *B, *C;
int ret = -EINVAL;
/* Test detection of cycles within the i915_sw_fence graphs */
if (!IS_ENABLED(CONFIG_DRM_I915_SW_FENCE_CHECK_DAG))
return 0;
A = alloc_fence();
if (!A)
return -ENOMEM;
if (i915_sw_fence_await_sw_fence_gfp(A, A, GFP_KERNEL) != -EINVAL) {
pr_err("recursive cycle not detected (AA)\n");
goto err_A;
}
B = alloc_fence();
if (!B) {
ret = -ENOMEM;
goto err_A;
}
i915_sw_fence_await_sw_fence_gfp(A, B, GFP_KERNEL);
if (i915_sw_fence_await_sw_fence_gfp(B, A, GFP_KERNEL) != -EINVAL) {
pr_err("single depth cycle not detected (BAB)\n");
goto err_B;
}
C = alloc_fence();
if (!C) {
ret = -ENOMEM;
goto err_B;
}
if (i915_sw_fence_await_sw_fence_gfp(B, C, GFP_KERNEL) == -EINVAL) {
pr_err("invalid cycle detected\n");
goto err_C;
}
if (i915_sw_fence_await_sw_fence_gfp(C, B, GFP_KERNEL) != -EINVAL) {
pr_err("single depth cycle not detected (CBC)\n");
goto err_C;
}
if (i915_sw_fence_await_sw_fence_gfp(C, A, GFP_KERNEL) != -EINVAL) {
pr_err("cycle not detected (BA, CB, AC)\n");
goto err_C;
}
if (i915_sw_fence_await_sw_fence_gfp(A, C, GFP_KERNEL) == -EINVAL) {
pr_err("invalid cycle detected\n");
goto err_C;
}
i915_sw_fence_commit(A);
i915_sw_fence_commit(B);
i915_sw_fence_commit(C);
ret = 0;
if (!i915_sw_fence_done(C)) {
pr_err("fence C not done\n");
ret = -EINVAL;
}
if (!i915_sw_fence_done(B)) {
pr_err("fence B not done\n");
ret = -EINVAL;
}
if (!i915_sw_fence_done(A)) {
pr_err("fence A not done\n");
ret = -EINVAL;
}
err_C:
free_fence(C);
err_B:
free_fence(B);
err_A:
free_fence(A);
return ret;
}
static int test_AB(void *arg)
{
struct i915_sw_fence *A, *B;
int ret;
/* Test i915_sw_fence (A) waiting on an event source (B) */
A = alloc_fence();
if (!A)
return -ENOMEM;
B = alloc_fence();
if (!B) {
ret = -ENOMEM;
goto err_A;
}
ret = i915_sw_fence_await_sw_fence_gfp(A, B, GFP_KERNEL);
if (ret < 0)
goto err_B;
if (ret == 0) {
pr_err("Incorrectly reported fence A was complete before await\n");
ret = -EINVAL;
goto err_B;
}
ret = -EINVAL;
i915_sw_fence_commit(A);
if (i915_sw_fence_done(A))
goto err_B;
i915_sw_fence_commit(B);
if (!i915_sw_fence_done(B)) {
pr_err("Fence B is not done\n");
goto err_B;
}
if (!i915_sw_fence_done(A)) {
pr_err("Fence A is not done\n");
goto err_B;
}
ret = 0;
err_B:
free_fence(B);
err_A:
free_fence(A);
return ret;
}
static int test_ABC(void *arg)
{
struct i915_sw_fence *A, *B, *C;
int ret;
/* Test a chain of fences, A waits on B who waits on C */
A = alloc_fence();
if (!A)
return -ENOMEM;
B = alloc_fence();
if (!B) {
ret = -ENOMEM;
goto err_A;
}
C = alloc_fence();
if (!C) {
ret = -ENOMEM;
goto err_B;
}
ret = i915_sw_fence_await_sw_fence_gfp(A, B, GFP_KERNEL);
if (ret < 0)
goto err_C;
if (ret == 0) {
pr_err("Incorrectly reported fence B was complete before await\n");
goto err_C;
}
ret = i915_sw_fence_await_sw_fence_gfp(B, C, GFP_KERNEL);
if (ret < 0)
goto err_C;
if (ret == 0) {
pr_err("Incorrectly reported fence C was complete before await\n");
goto err_C;
}
ret = -EINVAL;
i915_sw_fence_commit(A);
if (i915_sw_fence_done(A)) {
pr_err("Fence A completed early\n");
goto err_C;
}
i915_sw_fence_commit(B);
if (i915_sw_fence_done(B)) {
pr_err("Fence B completed early\n");
goto err_C;
}
if (i915_sw_fence_done(A)) {
pr_err("Fence A completed early (after signaling B)\n");
goto err_C;
}
i915_sw_fence_commit(C);
ret = 0;
if (!i915_sw_fence_done(C)) {
pr_err("Fence C not done\n");
ret = -EINVAL;
}
if (!i915_sw_fence_done(B)) {
pr_err("Fence B not done\n");
ret = -EINVAL;
}
if (!i915_sw_fence_done(A)) {
pr_err("Fence A not done\n");
ret = -EINVAL;
}
err_C:
free_fence(C);
err_B:
free_fence(B);
err_A:
free_fence(A);
return ret;
}
static int test_AB_C(void *arg)
{
struct i915_sw_fence *A, *B, *C;
int ret = -EINVAL;
/* Test multiple fences (AB) waiting on a single event (C) */
A = alloc_fence();
if (!A)
return -ENOMEM;
B = alloc_fence();
if (!B) {
ret = -ENOMEM;
goto err_A;
}
C = alloc_fence();
if (!C) {
ret = -ENOMEM;
goto err_B;
}
ret = i915_sw_fence_await_sw_fence_gfp(A, C, GFP_KERNEL);
if (ret < 0)
goto err_C;
if (ret == 0) {
ret = -EINVAL;
goto err_C;
}
ret = i915_sw_fence_await_sw_fence_gfp(B, C, GFP_KERNEL);
if (ret < 0)
goto err_C;
if (ret == 0) {
ret = -EINVAL;
goto err_C;
}
i915_sw_fence_commit(A);
i915_sw_fence_commit(B);
ret = 0;
if (i915_sw_fence_done(A)) {
pr_err("Fence A completed early\n");
ret = -EINVAL;
}
if (i915_sw_fence_done(B)) {
pr_err("Fence B completed early\n");
ret = -EINVAL;
}
i915_sw_fence_commit(C);
if (!i915_sw_fence_done(C)) {
pr_err("Fence C not done\n");
ret = -EINVAL;
}
if (!i915_sw_fence_done(B)) {
pr_err("Fence B not done\n");
ret = -EINVAL;
}
if (!i915_sw_fence_done(A)) {
pr_err("Fence A not done\n");
ret = -EINVAL;
}
err_C:
free_fence(C);
err_B:
free_fence(B);
err_A:
free_fence(A);
return ret;
}
static int test_C_AB(void *arg)
{
struct i915_sw_fence *A, *B, *C;
int ret;
/* Test multiple event sources (A,B) for a single fence (C) */
A = alloc_fence();
if (!A)
return -ENOMEM;
B = alloc_fence();
if (!B) {
ret = -ENOMEM;
goto err_A;
}
C = alloc_fence();
if (!C) {
ret = -ENOMEM;
goto err_B;
}
ret = i915_sw_fence_await_sw_fence_gfp(C, A, GFP_KERNEL);
if (ret < 0)
goto err_C;
if (ret == 0) {
ret = -EINVAL;
goto err_C;
}
ret = i915_sw_fence_await_sw_fence_gfp(C, B, GFP_KERNEL);
if (ret < 0)
goto err_C;
if (ret == 0) {
ret = -EINVAL;
goto err_C;
}
ret = 0;
i915_sw_fence_commit(C);
if (i915_sw_fence_done(C))
ret = -EINVAL;
i915_sw_fence_commit(A);
i915_sw_fence_commit(B);
if (!i915_sw_fence_done(A)) {
pr_err("Fence A not done\n");
ret = -EINVAL;
}
if (!i915_sw_fence_done(B)) {
pr_err("Fence B not done\n");
ret = -EINVAL;
}
if (!i915_sw_fence_done(C)) {
pr_err("Fence C not done\n");
ret = -EINVAL;
}
err_C:
free_fence(C);
err_B:
free_fence(B);
err_A:
free_fence(A);
return ret;
}
static int test_chain(void *arg)
{
int nfences = 4096;
struct i915_sw_fence **fences;
int ret, i;
/* Test a long chain of fences */
fences = kmalloc_array(nfences, sizeof(*fences), GFP_KERNEL);
if (!fences)
return -ENOMEM;
for (i = 0; i < nfences; i++) {
fences[i] = alloc_fence();
if (!fences[i]) {
nfences = i;
ret = -ENOMEM;
goto err;
}
if (i > 0) {
ret = i915_sw_fence_await_sw_fence_gfp(fences[i],
fences[i - 1],
GFP_KERNEL);
if (ret < 0) {
nfences = i + 1;
goto err;
}
i915_sw_fence_commit(fences[i]);
}
}
ret = 0;
for (i = nfences; --i; ) {
if (i915_sw_fence_done(fences[i])) {
if (ret == 0)
pr_err("Fence[%d] completed early\n", i);
ret = -EINVAL;
}
}
i915_sw_fence_commit(fences[0]);
for (i = 0; ret == 0 && i < nfences; i++) {
if (!i915_sw_fence_done(fences[i])) {
pr_err("Fence[%d] is not done\n", i);
ret = -EINVAL;
}
}
err:
for (i = 0; i < nfences; i++)
free_fence(fences[i]);
kfree(fences);
return ret;
}
struct task_ipc {
struct work_struct work;
struct completion started;
struct i915_sw_fence *in, *out;
int value;
};
static void task_ipc(struct work_struct *work)
{
struct task_ipc *ipc = container_of(work, typeof(*ipc), work);
complete(&ipc->started);
i915_sw_fence_wait(ipc->in);
smp_store_mb(ipc->value, 1);
i915_sw_fence_commit(ipc->out);
}
static int test_ipc(void *arg)
{
struct task_ipc ipc;
struct workqueue_struct *wq;
int ret = 0;
wq = alloc_workqueue("i1915-selftest", 0, 0);
if (wq == NULL)
return -ENOMEM;
/* Test use of i915_sw_fence as an interprocess signaling mechanism */
ipc.in = alloc_fence();
if (!ipc.in) {
ret = -ENOMEM;
goto err_work;
}
ipc.out = alloc_fence();
if (!ipc.out) {
ret = -ENOMEM;
goto err_in;
}
/* use a completion to avoid chicken-and-egg testing */
init_completion(&ipc.started);
ipc.value = 0;
INIT_WORK_ONSTACK(&ipc.work, task_ipc);
queue_work(wq, &ipc.work);
wait_for_completion(&ipc.started);
usleep_range(1000, 2000);
if (READ_ONCE(ipc.value)) {
pr_err("worker updated value before i915_sw_fence was signaled\n");
ret = -EINVAL;
}
i915_sw_fence_commit(ipc.in);
i915_sw_fence_wait(ipc.out);
if (!READ_ONCE(ipc.value)) {
pr_err("worker signaled i915_sw_fence before value was posted\n");
ret = -EINVAL;
}
flush_work(&ipc.work);
destroy_work_on_stack(&ipc.work);
free_fence(ipc.out);
err_in:
free_fence(ipc.in);
err_work:
destroy_workqueue(wq);
return ret;
}
static int test_timer(void *arg)
{
unsigned long target, delay;
struct timed_fence tf;
preempt_disable();
timed_fence_init(&tf, target = jiffies);
if (!i915_sw_fence_done(&tf.fence)) {
pr_err("Fence with immediate expiration not signaled\n");
goto err;
}
preempt_enable();
timed_fence_fini(&tf);
for_each_prime_number(delay, i915_selftest.timeout_jiffies/2) {
preempt_disable();
timed_fence_init(&tf, target = jiffies + delay);
if (i915_sw_fence_done(&tf.fence)) {
pr_err("Fence with future expiration (%lu jiffies) already signaled\n", delay);
goto err;
}
preempt_enable();
i915_sw_fence_wait(&tf.fence);
preempt_disable();
if (!i915_sw_fence_done(&tf.fence)) {
pr_err("Fence not signaled after wait\n");
goto err;
}
if (time_before(jiffies, target)) {
pr_err("Fence signaled too early, target=%lu, now=%lu\n",
target, jiffies);
goto err;
}
preempt_enable();
timed_fence_fini(&tf);
}
return 0;
err:
preempt_enable();
timed_fence_fini(&tf);
return -EINVAL;
}
static const char *mock_name(struct dma_fence *fence)
{
return "mock";
}
static const struct dma_fence_ops mock_fence_ops = {
.get_driver_name = mock_name,
.get_timeline_name = mock_name,
};
static DEFINE_SPINLOCK(mock_fence_lock);
static struct dma_fence *alloc_dma_fence(void)
{
struct dma_fence *dma;
dma = kmalloc(sizeof(*dma), GFP_KERNEL);
if (dma)
dma_fence_init(dma, &mock_fence_ops, &mock_fence_lock, 0, 0);
return dma;
}
static struct i915_sw_fence *
wrap_dma_fence(struct dma_fence *dma, unsigned long delay)
{
struct i915_sw_fence *fence;
int err;
fence = alloc_fence();
if (!fence)
return ERR_PTR(-ENOMEM);
err = i915_sw_fence_await_dma_fence(fence, dma, delay, GFP_NOWAIT);
i915_sw_fence_commit(fence);
if (err < 0) {
free_fence(fence);
return ERR_PTR(err);
}
return fence;
}
static int test_dma_fence(void *arg)
{
struct i915_sw_fence *timeout = NULL, *not = NULL;
unsigned long delay = i915_selftest.timeout_jiffies;
unsigned long end, sleep;
struct dma_fence *dma;
int err;
dma = alloc_dma_fence();
if (!dma)
return -ENOMEM;
timeout = wrap_dma_fence(dma, delay);
if (IS_ERR(timeout)) {
err = PTR_ERR(timeout);
goto err;
}
not = wrap_dma_fence(dma, 0);
if (IS_ERR(not)) {
err = PTR_ERR(not);
goto err;
}
err = -EINVAL;
if (i915_sw_fence_done(timeout) || i915_sw_fence_done(not)) {
pr_err("Fences immediately signaled\n");
goto err;
}
/* We round the timeout for the fence up to the next second */
end = round_jiffies_up(jiffies + delay);
sleep = jiffies_to_usecs(delay) / 3;
usleep_range(sleep, 2 * sleep);
if (time_after(jiffies, end)) {
pr_debug("Slept too long, delay=%lu, (target=%lu, now=%lu) skipping\n",
delay, end, jiffies);
goto skip;
}
if (i915_sw_fence_done(timeout) || i915_sw_fence_done(not)) {
pr_err("Fences signaled too early\n");
goto err;
}
if (!wait_event_timeout(timeout->wait,
i915_sw_fence_done(timeout),
2 * (end - jiffies) + 1)) {
pr_err("Timeout fence unsignaled!\n");
goto err;
}
if (i915_sw_fence_done(not)) {
pr_err("No timeout fence signaled!\n");
goto err;
}
skip:
dma_fence_signal(dma);
if (!i915_sw_fence_done(timeout) || !i915_sw_fence_done(not)) {
pr_err("Fences unsignaled\n");
goto err;
}
free_fence(not);
free_fence(timeout);
dma_fence_put(dma);
return 0;
err:
dma_fence_signal(dma);
if (!IS_ERR_OR_NULL(timeout))
free_fence(timeout);
if (!IS_ERR_OR_NULL(not))
free_fence(not);
dma_fence_put(dma);
return err;
}
int i915_sw_fence_mock_selftests(void)
{
static const struct i915_subtest tests[] = {
SUBTEST(test_self),
SUBTEST(test_dag),
SUBTEST(test_AB),
SUBTEST(test_ABC),
SUBTEST(test_AB_C),
SUBTEST(test_C_AB),
SUBTEST(test_chain),
SUBTEST(test_ipc),
SUBTEST(test_timer),
SUBTEST(test_dma_fence),
};
return i915_subtests(tests, NULL);
}
| linux-master | drivers/gpu/drm/i915/selftests/i915_sw_fence.c |
/*
* SPDX-License-Identifier: MIT
*
* Copyright © 2018 Intel Corporation
*/
#include <linux/kref.h>
#include <linux/string_helpers.h>
#include "gem/i915_gem_pm.h"
#include "gt/intel_gt.h"
#include "i915_selftest.h"
#include "igt_flush_test.h"
#include "lib_sw_fence.h"
struct live_active {
struct i915_active base;
struct kref ref;
bool retired;
};
static void __live_get(struct live_active *active)
{
kref_get(&active->ref);
}
static void __live_free(struct live_active *active)
{
i915_active_fini(&active->base);
kfree(active);
}
static void __live_release(struct kref *ref)
{
struct live_active *active = container_of(ref, typeof(*active), ref);
__live_free(active);
}
static void __live_put(struct live_active *active)
{
kref_put(&active->ref, __live_release);
}
static int __live_active(struct i915_active *base)
{
struct live_active *active = container_of(base, typeof(*active), base);
__live_get(active);
return 0;
}
static void __live_retire(struct i915_active *base)
{
struct live_active *active = container_of(base, typeof(*active), base);
active->retired = true;
__live_put(active);
}
static struct live_active *__live_alloc(struct drm_i915_private *i915)
{
struct live_active *active;
active = kzalloc(sizeof(*active), GFP_KERNEL);
if (!active)
return NULL;
kref_init(&active->ref);
i915_active_init(&active->base, __live_active, __live_retire, 0);
return active;
}
static struct live_active *
__live_active_setup(struct drm_i915_private *i915)
{
struct intel_engine_cs *engine;
struct i915_sw_fence *submit;
struct live_active *active;
unsigned int count = 0;
int err = 0;
active = __live_alloc(i915);
if (!active)
return ERR_PTR(-ENOMEM);
submit = heap_fence_create(GFP_KERNEL);
if (!submit) {
kfree(active);
return ERR_PTR(-ENOMEM);
}
err = i915_active_acquire(&active->base);
if (err)
goto out;
for_each_uabi_engine(engine, i915) {
struct i915_request *rq;
rq = intel_engine_create_kernel_request(engine);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
break;
}
err = i915_sw_fence_await_sw_fence_gfp(&rq->submit,
submit,
GFP_KERNEL);
if (err >= 0)
err = i915_active_add_request(&active->base, rq);
i915_request_add(rq);
if (err) {
pr_err("Failed to track active ref!\n");
break;
}
count++;
}
i915_active_release(&active->base);
if (READ_ONCE(active->retired) && count) {
pr_err("i915_active retired before submission!\n");
err = -EINVAL;
}
if (atomic_read(&active->base.count) != count) {
pr_err("i915_active not tracking all requests, found %d, expected %d\n",
atomic_read(&active->base.count), count);
err = -EINVAL;
}
out:
i915_sw_fence_commit(submit);
heap_fence_put(submit);
if (err) {
__live_put(active);
active = ERR_PTR(err);
}
return active;
}
static int live_active_wait(void *arg)
{
struct drm_i915_private *i915 = arg;
struct live_active *active;
int err = 0;
/* Check that we get a callback when requests retire upon waiting */
active = __live_active_setup(i915);
if (IS_ERR(active))
return PTR_ERR(active);
__i915_active_wait(&active->base, TASK_UNINTERRUPTIBLE);
if (!READ_ONCE(active->retired)) {
struct drm_printer p = drm_err_printer(__func__);
pr_err("i915_active not retired after waiting!\n");
i915_active_print(&active->base, &p);
err = -EINVAL;
}
__live_put(active);
if (igt_flush_test(i915))
err = -EIO;
return err;
}
static int live_active_retire(void *arg)
{
struct drm_i915_private *i915 = arg;
struct live_active *active;
int err = 0;
/* Check that we get a callback when requests are indirectly retired */
active = __live_active_setup(i915);
if (IS_ERR(active))
return PTR_ERR(active);
/* waits for & retires all requests */
if (igt_flush_test(i915))
err = -EIO;
if (!READ_ONCE(active->retired)) {
struct drm_printer p = drm_err_printer(__func__);
pr_err("i915_active not retired after flushing!\n");
i915_active_print(&active->base, &p);
err = -EINVAL;
}
__live_put(active);
return err;
}
static int live_active_barrier(void *arg)
{
struct drm_i915_private *i915 = arg;
struct intel_engine_cs *engine;
struct live_active *active;
int err = 0;
/* Check that we get a callback when requests retire upon waiting */
active = __live_alloc(i915);
if (!active)
return -ENOMEM;
err = i915_active_acquire(&active->base);
if (err)
goto out;
for_each_uabi_engine(engine, i915) {
err = i915_active_acquire_preallocate_barrier(&active->base,
engine);
if (err)
break;
i915_active_acquire_barrier(&active->base);
}
i915_active_release(&active->base);
if (err)
goto out;
__i915_active_wait(&active->base, TASK_UNINTERRUPTIBLE);
if (!READ_ONCE(active->retired)) {
pr_err("i915_active not retired after flushing barriers!\n");
err = -EINVAL;
}
out:
__live_put(active);
if (igt_flush_test(i915))
err = -EIO;
return err;
}
int i915_active_live_selftests(struct drm_i915_private *i915)
{
static const struct i915_subtest tests[] = {
SUBTEST(live_active_wait),
SUBTEST(live_active_retire),
SUBTEST(live_active_barrier),
};
if (intel_gt_is_wedged(to_gt(i915)))
return 0;
return i915_subtests(tests, i915);
}
static struct intel_engine_cs *node_to_barrier(struct active_node *it)
{
struct intel_engine_cs *engine;
if (!is_barrier(&it->base))
return NULL;
engine = __barrier_to_engine(it);
smp_rmb(); /* serialise with add_active_barriers */
if (!is_barrier(&it->base))
return NULL;
return engine;
}
void i915_active_print(struct i915_active *ref, struct drm_printer *m)
{
drm_printf(m, "active %ps:%ps\n", ref->active, ref->retire);
drm_printf(m, "\tcount: %d\n", atomic_read(&ref->count));
drm_printf(m, "\tpreallocated barriers? %s\n",
str_yes_no(!llist_empty(&ref->preallocated_barriers)));
if (i915_active_acquire_if_busy(ref)) {
struct active_node *it, *n;
rbtree_postorder_for_each_entry_safe(it, n, &ref->tree, node) {
struct intel_engine_cs *engine;
engine = node_to_barrier(it);
if (engine) {
drm_printf(m, "\tbarrier: %s\n", engine->name);
continue;
}
if (i915_active_fence_isset(&it->base)) {
drm_printf(m,
"\ttimeline: %llx\n", it->timeline);
continue;
}
}
i915_active_release(ref);
}
}
static void spin_unlock_wait(spinlock_t *lock)
{
spin_lock_irq(lock);
spin_unlock_irq(lock);
}
static void active_flush(struct i915_active *ref,
struct i915_active_fence *active)
{
struct dma_fence *fence;
fence = xchg(__active_fence_slot(active), NULL);
if (!fence)
return;
spin_lock_irq(fence->lock);
__list_del_entry(&active->cb.node);
spin_unlock_irq(fence->lock); /* serialise with fence->cb_list */
atomic_dec(&ref->count);
GEM_BUG_ON(!test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags));
}
void i915_active_unlock_wait(struct i915_active *ref)
{
if (i915_active_acquire_if_busy(ref)) {
struct active_node *it, *n;
/* Wait for all active callbacks */
rcu_read_lock();
active_flush(ref, &ref->excl);
rbtree_postorder_for_each_entry_safe(it, n, &ref->tree, node)
active_flush(ref, &it->base);
rcu_read_unlock();
i915_active_release(ref);
}
/* And wait for the retire callback */
spin_unlock_wait(&ref->tree_lock);
/* ... which may have been on a thread instead */
flush_work(&ref->work);
}
| linux-master | drivers/gpu/drm/i915/selftests/i915_active.c |
/*
* SPDX-License-Identifier: MIT
*
* Copyright © 2018 Intel Corporation
*/
#include "gt/intel_gt.h"
#include "gt/intel_gt_requests.h"
#include "i915_drv.h"
#include "i915_selftest.h"
#include "igt_flush_test.h"
int igt_flush_test(struct drm_i915_private *i915)
{
struct intel_gt *gt;
unsigned int i;
int ret = 0;
for_each_gt(gt, i915, i) {
if (intel_gt_is_wedged(gt))
ret = -EIO;
cond_resched();
if (intel_gt_wait_for_idle(gt, HZ * 3) == -ETIME) {
pr_err("%pS timed out, cancelling all further testing.\n",
__builtin_return_address(0));
GEM_TRACE("%pS timed out.\n",
__builtin_return_address(0));
GEM_TRACE_DUMP();
intel_gt_set_wedged(gt);
ret = -EIO;
}
}
return ret;
}
| linux-master | drivers/gpu/drm/i915/selftests/igt_flush_test.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2020 Intel Corporation
*/
#include <asm/msr.h>
#include "i915_drv.h"
#include "librapl.h"
bool librapl_supported(const struct drm_i915_private *i915)
{
/* Discrete cards require hwmon integration */
if (IS_DGFX(i915))
return false;
return librapl_energy_uJ();
}
u64 librapl_energy_uJ(void)
{
unsigned long long power;
u32 units;
if (rdmsrl_safe(MSR_RAPL_POWER_UNIT, &power))
return 0;
units = (power & 0x1f00) >> 8;
if (rdmsrl_safe(MSR_PP1_ENERGY_STATUS, &power))
return 0;
return (1000000 * power) >> units; /* convert to uJ */
}
| linux-master | drivers/gpu/drm/i915/selftests/librapl.c |
/*
* SPDX-License-Identifier: MIT
*
* Copyright © 2019 Intel Corporation
*/
#include <linux/kref.h>
#include "gem/i915_gem_pm.h"
#include "gt/intel_gt.h"
#include "i915_selftest.h"
#include "igt_flush_test.h"
#include "lib_sw_fence.h"
#define TEST_OA_CONFIG_UUID "12345678-1234-1234-1234-1234567890ab"
static int
alloc_empty_config(struct i915_perf *perf)
{
struct i915_oa_config *oa_config;
oa_config = kzalloc(sizeof(*oa_config), GFP_KERNEL);
if (!oa_config)
return -ENOMEM;
oa_config->perf = perf;
kref_init(&oa_config->ref);
strscpy(oa_config->uuid, TEST_OA_CONFIG_UUID, sizeof(oa_config->uuid));
mutex_lock(&perf->metrics_lock);
oa_config->id = idr_alloc(&perf->metrics_idr, oa_config, 2, 0, GFP_KERNEL);
if (oa_config->id < 0) {
mutex_unlock(&perf->metrics_lock);
i915_oa_config_put(oa_config);
return -ENOMEM;
}
mutex_unlock(&perf->metrics_lock);
return 0;
}
static void
destroy_empty_config(struct i915_perf *perf)
{
struct i915_oa_config *oa_config = NULL, *tmp;
int id;
mutex_lock(&perf->metrics_lock);
idr_for_each_entry(&perf->metrics_idr, tmp, id) {
if (!strcmp(tmp->uuid, TEST_OA_CONFIG_UUID)) {
oa_config = tmp;
break;
}
}
if (oa_config)
idr_remove(&perf->metrics_idr, oa_config->id);
mutex_unlock(&perf->metrics_lock);
if (oa_config)
i915_oa_config_put(oa_config);
}
static struct i915_oa_config *
get_empty_config(struct i915_perf *perf)
{
struct i915_oa_config *oa_config = NULL, *tmp;
int id;
mutex_lock(&perf->metrics_lock);
idr_for_each_entry(&perf->metrics_idr, tmp, id) {
if (!strcmp(tmp->uuid, TEST_OA_CONFIG_UUID)) {
oa_config = i915_oa_config_get(tmp);
break;
}
}
mutex_unlock(&perf->metrics_lock);
return oa_config;
}
static struct i915_perf_stream *
test_stream(struct i915_perf *perf)
{
struct drm_i915_perf_open_param param = {};
struct i915_oa_config *oa_config = get_empty_config(perf);
struct perf_open_properties props = {
.engine = intel_engine_lookup_user(perf->i915,
I915_ENGINE_CLASS_RENDER,
0),
.sample_flags = SAMPLE_OA_REPORT,
.oa_format = GRAPHICS_VER(perf->i915) == 12 ?
I915_OA_FORMAT_A32u40_A4u32_B8_C8 : I915_OA_FORMAT_C4_B8,
};
struct i915_perf_stream *stream;
struct intel_gt *gt;
if (!props.engine)
return NULL;
gt = props.engine->gt;
if (!oa_config)
return NULL;
props.metrics_set = oa_config->id;
stream = kzalloc(sizeof(*stream), GFP_KERNEL);
if (!stream) {
i915_oa_config_put(oa_config);
return NULL;
}
stream->perf = perf;
mutex_lock(>->perf.lock);
if (i915_oa_stream_init(stream, ¶m, &props)) {
kfree(stream);
stream = NULL;
}
mutex_unlock(>->perf.lock);
i915_oa_config_put(oa_config);
return stream;
}
static void stream_destroy(struct i915_perf_stream *stream)
{
struct intel_gt *gt = stream->engine->gt;
mutex_lock(>->perf.lock);
i915_perf_destroy_locked(stream);
mutex_unlock(>->perf.lock);
}
static int live_sanitycheck(void *arg)
{
struct drm_i915_private *i915 = arg;
struct i915_perf_stream *stream;
/* Quick check we can create a perf stream */
stream = test_stream(&i915->perf);
if (!stream)
return -EINVAL;
stream_destroy(stream);
return 0;
}
static int write_timestamp(struct i915_request *rq, int slot)
{
u32 *cs;
int len;
cs = intel_ring_begin(rq, 6);
if (IS_ERR(cs))
return PTR_ERR(cs);
len = 5;
if (GRAPHICS_VER(rq->i915) >= 8)
len++;
*cs++ = GFX_OP_PIPE_CONTROL(len);
*cs++ = PIPE_CONTROL_GLOBAL_GTT_IVB |
PIPE_CONTROL_STORE_DATA_INDEX |
PIPE_CONTROL_WRITE_TIMESTAMP;
*cs++ = slot * sizeof(u32);
*cs++ = 0;
*cs++ = 0;
*cs++ = 0;
intel_ring_advance(rq, cs);
return 0;
}
static ktime_t poll_status(struct i915_request *rq, int slot)
{
while (!intel_read_status_page(rq->engine, slot) &&
!i915_request_completed(rq))
cpu_relax();
return ktime_get();
}
static int live_noa_delay(void *arg)
{
struct drm_i915_private *i915 = arg;
struct i915_perf_stream *stream;
struct i915_request *rq;
ktime_t t0, t1;
u64 expected;
u32 delay;
int err;
int i;
/* Check that the GPU delays matches expectations */
stream = test_stream(&i915->perf);
if (!stream)
return -ENOMEM;
expected = atomic64_read(&stream->perf->noa_programming_delay);
if (stream->engine->class != RENDER_CLASS) {
err = -ENODEV;
goto out;
}
for (i = 0; i < 4; i++)
intel_write_status_page(stream->engine, 0x100 + i, 0);
rq = intel_engine_create_kernel_request(stream->engine);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
goto out;
}
if (rq->engine->emit_init_breadcrumb) {
err = rq->engine->emit_init_breadcrumb(rq);
if (err) {
i915_request_add(rq);
goto out;
}
}
err = write_timestamp(rq, 0x100);
if (err) {
i915_request_add(rq);
goto out;
}
err = rq->engine->emit_bb_start(rq,
i915_ggtt_offset(stream->noa_wait), 0,
I915_DISPATCH_SECURE);
if (err) {
i915_request_add(rq);
goto out;
}
err = write_timestamp(rq, 0x102);
if (err) {
i915_request_add(rq);
goto out;
}
i915_request_get(rq);
i915_request_add(rq);
preempt_disable();
t0 = poll_status(rq, 0x100);
t1 = poll_status(rq, 0x102);
preempt_enable();
pr_info("CPU delay: %lluns, expected %lluns\n",
ktime_sub(t1, t0), expected);
delay = intel_read_status_page(stream->engine, 0x102);
delay -= intel_read_status_page(stream->engine, 0x100);
delay = intel_gt_clock_interval_to_ns(stream->engine->gt, delay);
pr_info("GPU delay: %uns, expected %lluns\n",
delay, expected);
if (4 * delay < 3 * expected || 2 * delay > 3 * expected) {
pr_err("GPU delay [%uus] outside of expected threshold! [%lluus, %lluus]\n",
delay / 1000,
div_u64(3 * expected, 4000),
div_u64(3 * expected, 2000));
err = -EINVAL;
}
i915_request_put(rq);
out:
stream_destroy(stream);
return err;
}
static int live_noa_gpr(void *arg)
{
struct drm_i915_private *i915 = arg;
struct i915_perf_stream *stream;
struct intel_context *ce;
struct i915_request *rq;
u32 *cs, *store;
void *scratch;
u32 gpr0;
int err;
int i;
/* Check that the delay does not clobber user context state (GPR) */
stream = test_stream(&i915->perf);
if (!stream)
return -ENOMEM;
gpr0 = i915_mmio_reg_offset(GEN8_RING_CS_GPR(stream->engine->mmio_base, 0));
ce = intel_context_create(stream->engine);
if (IS_ERR(ce)) {
err = PTR_ERR(ce);
goto out;
}
/* Poison the ce->vm so we detect writes not to the GGTT gt->scratch */
scratch = __px_vaddr(ce->vm->scratch[0]);
memset(scratch, POISON_FREE, PAGE_SIZE);
rq = intel_context_create_request(ce);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
goto out_ce;
}
i915_request_get(rq);
if (rq->engine->emit_init_breadcrumb) {
err = rq->engine->emit_init_breadcrumb(rq);
if (err) {
i915_request_add(rq);
goto out_rq;
}
}
/* Fill the 16 qword [32 dword] GPR with a known unlikely value */
cs = intel_ring_begin(rq, 2 * 32 + 2);
if (IS_ERR(cs)) {
err = PTR_ERR(cs);
i915_request_add(rq);
goto out_rq;
}
*cs++ = MI_LOAD_REGISTER_IMM(32);
for (i = 0; i < 32; i++) {
*cs++ = gpr0 + i * sizeof(u32);
*cs++ = STACK_MAGIC;
}
*cs++ = MI_NOOP;
intel_ring_advance(rq, cs);
/* Execute the GPU delay */
err = rq->engine->emit_bb_start(rq,
i915_ggtt_offset(stream->noa_wait), 0,
I915_DISPATCH_SECURE);
if (err) {
i915_request_add(rq);
goto out_rq;
}
/* Read the GPR back, using the pinned global HWSP for convenience */
store = memset32(rq->engine->status_page.addr + 512, 0, 32);
for (i = 0; i < 32; i++) {
u32 cmd;
cs = intel_ring_begin(rq, 4);
if (IS_ERR(cs)) {
err = PTR_ERR(cs);
i915_request_add(rq);
goto out_rq;
}
cmd = MI_STORE_REGISTER_MEM;
if (GRAPHICS_VER(i915) >= 8)
cmd++;
cmd |= MI_USE_GGTT;
*cs++ = cmd;
*cs++ = gpr0 + i * sizeof(u32);
*cs++ = i915_ggtt_offset(rq->engine->status_page.vma) +
offset_in_page(store) +
i * sizeof(u32);
*cs++ = 0;
intel_ring_advance(rq, cs);
}
i915_request_add(rq);
if (i915_request_wait(rq, I915_WAIT_INTERRUPTIBLE, HZ / 2) < 0) {
pr_err("noa_wait timed out\n");
intel_gt_set_wedged(stream->engine->gt);
err = -EIO;
goto out_rq;
}
/* Verify that the GPR contain our expected values */
for (i = 0; i < 32; i++) {
if (store[i] == STACK_MAGIC)
continue;
pr_err("GPR[%d] lost, found:%08x, expected:%08x!\n",
i, store[i], STACK_MAGIC);
err = -EINVAL;
}
/* Verify that the user's scratch page was not used for GPR storage */
if (memchr_inv(scratch, POISON_FREE, PAGE_SIZE)) {
pr_err("Scratch page overwritten!\n");
igt_hexdump(scratch, 4096);
err = -EINVAL;
}
out_rq:
i915_request_put(rq);
out_ce:
intel_context_put(ce);
out:
stream_destroy(stream);
return err;
}
int i915_perf_live_selftests(struct drm_i915_private *i915)
{
static const struct i915_subtest tests[] = {
SUBTEST(live_sanitycheck),
SUBTEST(live_noa_delay),
SUBTEST(live_noa_gpr),
};
struct i915_perf *perf = &i915->perf;
int err;
if (!perf->metrics_kobj || !perf->ops.enable_metric_set)
return 0;
if (intel_gt_is_wedged(to_gt(i915)))
return 0;
err = alloc_empty_config(&i915->perf);
if (err)
return err;
err = i915_live_subtests(tests, i915);
destroy_empty_config(&i915->perf);
return err;
}
| linux-master | drivers/gpu/drm/i915/selftests/i915_perf.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2019-2021 Intel Corporation
*/
#include <drm/ttm/ttm_placement.h>
#include <linux/scatterlist.h>
#include "gem/i915_gem_region.h"
#include "intel_memory_region.h"
#include "intel_region_ttm.h"
#include "mock_region.h"
static void mock_region_put_pages(struct drm_i915_gem_object *obj,
struct sg_table *pages)
{
i915_refct_sgt_put(obj->mm.rsgt);
obj->mm.rsgt = NULL;
intel_region_ttm_resource_free(obj->mm.region, obj->mm.res);
}
static int mock_region_get_pages(struct drm_i915_gem_object *obj)
{
struct sg_table *pages;
int err;
obj->mm.res = intel_region_ttm_resource_alloc(obj->mm.region,
obj->bo_offset,
obj->base.size,
obj->flags);
if (IS_ERR(obj->mm.res))
return PTR_ERR(obj->mm.res);
obj->mm.rsgt = intel_region_ttm_resource_to_rsgt(obj->mm.region,
obj->mm.res,
obj->mm.region->min_page_size);
if (IS_ERR(obj->mm.rsgt)) {
err = PTR_ERR(obj->mm.rsgt);
goto err_free_resource;
}
pages = &obj->mm.rsgt->table;
__i915_gem_object_set_pages(obj, pages);
return 0;
err_free_resource:
intel_region_ttm_resource_free(obj->mm.region, obj->mm.res);
return err;
}
static const struct drm_i915_gem_object_ops mock_region_obj_ops = {
.name = "mock-region",
.get_pages = mock_region_get_pages,
.put_pages = mock_region_put_pages,
.release = i915_gem_object_release_memory_region,
};
static int mock_object_init(struct intel_memory_region *mem,
struct drm_i915_gem_object *obj,
resource_size_t offset,
resource_size_t size,
resource_size_t page_size,
unsigned int flags)
{
static struct lock_class_key lock_class;
struct drm_i915_private *i915 = mem->i915;
if (size > resource_size(&mem->region))
return -E2BIG;
drm_gem_private_object_init(&i915->drm, &obj->base, size);
i915_gem_object_init(obj, &mock_region_obj_ops, &lock_class, flags);
obj->bo_offset = offset;
obj->read_domains = I915_GEM_DOMAIN_CPU | I915_GEM_DOMAIN_GTT;
i915_gem_object_set_cache_coherency(obj, I915_CACHE_NONE);
i915_gem_object_init_memory_region(obj, mem);
return 0;
}
static int mock_region_fini(struct intel_memory_region *mem)
{
struct drm_i915_private *i915 = mem->i915;
int instance = mem->instance;
int ret;
ret = intel_region_ttm_fini(mem);
ida_free(&i915->selftest.mock_region_instances, instance);
return ret;
}
static const struct intel_memory_region_ops mock_region_ops = {
.init = intel_region_ttm_init,
.release = mock_region_fini,
.init_object = mock_object_init,
};
struct intel_memory_region *
mock_region_create(struct drm_i915_private *i915,
resource_size_t start,
resource_size_t size,
resource_size_t min_page_size,
resource_size_t io_start,
resource_size_t io_size)
{
int instance = ida_alloc_max(&i915->selftest.mock_region_instances,
TTM_NUM_MEM_TYPES - TTM_PL_PRIV - 1,
GFP_KERNEL);
if (instance < 0)
return ERR_PTR(instance);
return intel_memory_region_create(i915, start, size, min_page_size,
io_start, io_size,
INTEL_MEMORY_MOCK, instance,
&mock_region_ops);
}
| linux-master | drivers/gpu/drm/i915/selftests/mock_region.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2018 Intel Corporation
*/
#include <linux/preempt.h>
#include <linux/bottom_half.h>
#include <linux/irqflags.h>
#include "igt_atomic.h"
static void __preempt_begin(void)
{
preempt_disable();
}
static void __preempt_end(void)
{
preempt_enable();
}
static void __softirq_begin(void)
{
local_bh_disable();
}
static void __softirq_end(void)
{
local_bh_enable();
}
static void __hardirq_begin(void)
{
local_irq_disable();
}
static void __hardirq_end(void)
{
local_irq_enable();
}
const struct igt_atomic_section igt_atomic_phases[] = {
{ "preempt", __preempt_begin, __preempt_end },
{ "softirq", __softirq_begin, __softirq_end },
{ "hardirq", __hardirq_begin, __hardirq_end },
{ }
};
| linux-master | drivers/gpu/drm/i915/selftests/igt_atomic.c |
/*
* Copyright © 2017 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
#include "mock_uncore.h"
#define __nop_write(x) \
static void \
nop_write##x(struct intel_uncore *uncore, i915_reg_t reg, u##x val, bool trace) { }
__nop_write(8)
__nop_write(16)
__nop_write(32)
#define __nop_read(x) \
static u##x \
nop_read##x(struct intel_uncore *uncore, i915_reg_t reg, bool trace) { return 0; }
__nop_read(8)
__nop_read(16)
__nop_read(32)
__nop_read(64)
void mock_uncore_init(struct intel_uncore *uncore,
struct drm_i915_private *i915)
{
intel_uncore_init_early(uncore, to_gt(i915));
ASSIGN_RAW_WRITE_MMIO_VFUNCS(uncore, nop);
ASSIGN_RAW_READ_MMIO_VFUNCS(uncore, nop);
}
| linux-master | drivers/gpu/drm/i915/selftests/mock_uncore.c |
/*
* Copyright © 2016 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
#include "gem/i915_gem_internal.h"
#include "gem/i915_gem_pm.h"
#include "gem/selftests/igt_gem_utils.h"
#include "gem/selftests/mock_context.h"
#include "gt/intel_gt.h"
#include "gt/intel_gt_print.h"
#include "i915_selftest.h"
#include "igt_flush_test.h"
#include "lib_sw_fence.h"
#include "mock_drm.h"
#include "mock_gem_device.h"
static void quirk_add(struct drm_i915_gem_object *obj,
struct list_head *objects)
{
/* quirk is only for live tiled objects, use it to declare ownership */
GEM_BUG_ON(i915_gem_object_has_tiling_quirk(obj));
i915_gem_object_set_tiling_quirk(obj);
list_add(&obj->st_link, objects);
}
static int populate_ggtt(struct i915_ggtt *ggtt, struct list_head *objects)
{
struct drm_i915_gem_object *obj;
unsigned long count;
count = 0;
do {
struct i915_vma *vma;
obj = i915_gem_object_create_internal(ggtt->vm.i915,
I915_GTT_PAGE_SIZE);
if (IS_ERR(obj))
return PTR_ERR(obj);
vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0, 0);
if (IS_ERR(vma)) {
i915_gem_object_put(obj);
if (vma == ERR_PTR(-ENOSPC))
break;
return PTR_ERR(vma);
}
quirk_add(obj, objects);
count++;
} while (1);
pr_debug("Filled GGTT with %lu pages [%llu total]\n",
count, ggtt->vm.total / PAGE_SIZE);
if (list_empty(&ggtt->vm.bound_list)) {
pr_err("No objects on the GGTT inactive list!\n");
return -EINVAL;
}
return 0;
}
static void unpin_ggtt(struct i915_ggtt *ggtt)
{
struct i915_vma *vma;
list_for_each_entry(vma, &ggtt->vm.bound_list, vm_link)
if (i915_gem_object_has_tiling_quirk(vma->obj))
i915_vma_unpin(vma);
}
static void cleanup_objects(struct i915_ggtt *ggtt, struct list_head *list)
{
struct drm_i915_gem_object *obj, *on;
list_for_each_entry_safe(obj, on, list, st_link) {
GEM_BUG_ON(!i915_gem_object_has_tiling_quirk(obj));
i915_gem_object_set_tiling_quirk(obj);
i915_gem_object_put(obj);
}
i915_gem_drain_freed_objects(ggtt->vm.i915);
}
static int igt_evict_something(void *arg)
{
struct intel_gt *gt = arg;
struct i915_ggtt *ggtt = gt->ggtt;
LIST_HEAD(objects);
int err;
/* Fill the GGTT with pinned objects and try to evict one. */
err = populate_ggtt(ggtt, &objects);
if (err)
goto cleanup;
/* Everything is pinned, nothing should happen */
mutex_lock(&ggtt->vm.mutex);
err = i915_gem_evict_something(&ggtt->vm, NULL,
I915_GTT_PAGE_SIZE, 0, 0,
0, U64_MAX,
0);
mutex_unlock(&ggtt->vm.mutex);
if (err != -ENOSPC) {
pr_err("i915_gem_evict_something failed on a full GGTT with err=%d\n",
err);
goto cleanup;
}
unpin_ggtt(ggtt);
/* Everything is unpinned, we should be able to evict something */
mutex_lock(&ggtt->vm.mutex);
err = i915_gem_evict_something(&ggtt->vm, NULL,
I915_GTT_PAGE_SIZE, 0, 0,
0, U64_MAX,
0);
mutex_unlock(&ggtt->vm.mutex);
if (err) {
pr_err("i915_gem_evict_something failed on a full GGTT with err=%d\n",
err);
goto cleanup;
}
cleanup:
cleanup_objects(ggtt, &objects);
return err;
}
static int igt_overcommit(void *arg)
{
struct intel_gt *gt = arg;
struct i915_ggtt *ggtt = gt->ggtt;
struct drm_i915_gem_object *obj;
struct i915_vma *vma;
LIST_HEAD(objects);
int err;
/* Fill the GGTT with pinned objects and then try to pin one more.
* We expect it to fail.
*/
err = populate_ggtt(ggtt, &objects);
if (err)
goto cleanup;
obj = i915_gem_object_create_internal(gt->i915, I915_GTT_PAGE_SIZE);
if (IS_ERR(obj)) {
err = PTR_ERR(obj);
goto cleanup;
}
quirk_add(obj, &objects);
vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0, 0);
if (vma != ERR_PTR(-ENOSPC)) {
pr_err("Failed to evict+insert, i915_gem_object_ggtt_pin returned err=%d\n", (int)PTR_ERR_OR_ZERO(vma));
err = -EINVAL;
goto cleanup;
}
cleanup:
cleanup_objects(ggtt, &objects);
return err;
}
static int igt_evict_for_vma(void *arg)
{
struct intel_gt *gt = arg;
struct i915_ggtt *ggtt = gt->ggtt;
struct drm_mm_node target = {
.start = 0,
.size = 4096,
};
LIST_HEAD(objects);
int err;
/* Fill the GGTT with pinned objects and try to evict a range. */
err = populate_ggtt(ggtt, &objects);
if (err)
goto cleanup;
/* Everything is pinned, nothing should happen */
mutex_lock(&ggtt->vm.mutex);
err = i915_gem_evict_for_node(&ggtt->vm, NULL, &target, 0);
mutex_unlock(&ggtt->vm.mutex);
if (err != -ENOSPC) {
pr_err("i915_gem_evict_for_node on a full GGTT returned err=%d\n",
err);
goto cleanup;
}
unpin_ggtt(ggtt);
/* Everything is unpinned, we should be able to evict the node */
mutex_lock(&ggtt->vm.mutex);
err = i915_gem_evict_for_node(&ggtt->vm, NULL, &target, 0);
mutex_unlock(&ggtt->vm.mutex);
if (err) {
pr_err("i915_gem_evict_for_node returned err=%d\n",
err);
goto cleanup;
}
cleanup:
cleanup_objects(ggtt, &objects);
return err;
}
static void mock_color_adjust(const struct drm_mm_node *node,
unsigned long color,
u64 *start,
u64 *end)
{
}
static int igt_evict_for_cache_color(void *arg)
{
struct intel_gt *gt = arg;
struct i915_ggtt *ggtt = gt->ggtt;
const unsigned long flags = PIN_OFFSET_FIXED;
struct drm_mm_node target = {
.start = I915_GTT_PAGE_SIZE * 2,
.size = I915_GTT_PAGE_SIZE,
.color = i915_gem_get_pat_index(gt->i915, I915_CACHE_LLC),
};
struct drm_i915_gem_object *obj;
struct i915_vma *vma;
LIST_HEAD(objects);
int err;
/*
* Currently the use of color_adjust for the GGTT is limited to cache
* coloring and guard pages, and so the presence of mm.color_adjust for
* the GGTT is assumed to be i915_ggtt_color_adjust, hence using a mock
* color adjust will work just fine for our purposes.
*/
ggtt->vm.mm.color_adjust = mock_color_adjust;
GEM_BUG_ON(!i915_vm_has_cache_coloring(&ggtt->vm));
obj = i915_gem_object_create_internal(gt->i915, I915_GTT_PAGE_SIZE);
if (IS_ERR(obj)) {
err = PTR_ERR(obj);
goto cleanup;
}
i915_gem_object_set_cache_coherency(obj, I915_CACHE_LLC);
quirk_add(obj, &objects);
vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
I915_GTT_PAGE_SIZE | flags);
if (IS_ERR(vma)) {
pr_err("[0]i915_gem_object_ggtt_pin failed\n");
err = PTR_ERR(vma);
goto cleanup;
}
obj = i915_gem_object_create_internal(gt->i915, I915_GTT_PAGE_SIZE);
if (IS_ERR(obj)) {
err = PTR_ERR(obj);
goto cleanup;
}
i915_gem_object_set_cache_coherency(obj, I915_CACHE_LLC);
quirk_add(obj, &objects);
/* Neighbouring; same colour - should fit */
vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
(I915_GTT_PAGE_SIZE * 2) | flags);
if (IS_ERR(vma)) {
pr_err("[1]i915_gem_object_ggtt_pin failed\n");
err = PTR_ERR(vma);
goto cleanup;
}
i915_vma_unpin(vma);
/* Remove just the second vma */
mutex_lock(&ggtt->vm.mutex);
err = i915_gem_evict_for_node(&ggtt->vm, NULL, &target, 0);
mutex_unlock(&ggtt->vm.mutex);
if (err) {
pr_err("[0]i915_gem_evict_for_node returned err=%d\n", err);
goto cleanup;
}
/* Attempt to remove the first *pinned* vma, by removing the (empty)
* neighbour -- this should fail.
*/
target.color = i915_gem_get_pat_index(gt->i915, I915_CACHE_L3_LLC);
mutex_lock(&ggtt->vm.mutex);
err = i915_gem_evict_for_node(&ggtt->vm, NULL, &target, 0);
mutex_unlock(&ggtt->vm.mutex);
if (!err) {
pr_err("[1]i915_gem_evict_for_node returned err=%d\n", err);
err = -EINVAL;
goto cleanup;
}
err = 0;
cleanup:
unpin_ggtt(ggtt);
cleanup_objects(ggtt, &objects);
ggtt->vm.mm.color_adjust = NULL;
return err;
}
static int igt_evict_vm(void *arg)
{
struct intel_gt *gt = arg;
struct i915_ggtt *ggtt = gt->ggtt;
struct i915_gem_ww_ctx ww;
LIST_HEAD(objects);
int err;
/* Fill the GGTT with pinned objects and try to evict everything. */
err = populate_ggtt(ggtt, &objects);
if (err)
goto cleanup;
/* Everything is pinned, nothing should happen */
mutex_lock(&ggtt->vm.mutex);
err = i915_gem_evict_vm(&ggtt->vm, NULL, NULL);
mutex_unlock(&ggtt->vm.mutex);
if (err) {
pr_err("i915_gem_evict_vm on a full GGTT returned err=%d]\n",
err);
goto cleanup;
}
unpin_ggtt(ggtt);
for_i915_gem_ww(&ww, err, false) {
mutex_lock(&ggtt->vm.mutex);
err = i915_gem_evict_vm(&ggtt->vm, &ww, NULL);
mutex_unlock(&ggtt->vm.mutex);
}
if (err) {
pr_err("i915_gem_evict_vm on a full GGTT returned err=%d]\n",
err);
goto cleanup;
}
cleanup:
cleanup_objects(ggtt, &objects);
return err;
}
static int igt_evict_contexts(void *arg)
{
const u64 PRETEND_GGTT_SIZE = 16ull << 20;
struct intel_gt *gt = arg;
struct i915_ggtt *ggtt = gt->ggtt;
struct drm_i915_private *i915 = gt->i915;
struct intel_engine_cs *engine;
enum intel_engine_id id;
struct reserved {
struct drm_mm_node node;
struct reserved *next;
} *reserved = NULL;
intel_wakeref_t wakeref;
struct drm_mm_node hole;
unsigned long count;
int err;
/*
* The purpose of this test is to verify that we will trigger an
* eviction in the GGTT when constructing a request that requires
* additional space in the GGTT for pinning the context. This space
* is not directly tied to the request so reclaiming it requires
* extra work.
*
* As such this test is only meaningful for full-ppgtt environments
* where the GTT space of the request is separate from the GGTT
* allocation required to build the request.
*/
if (!HAS_FULL_PPGTT(i915))
return 0;
wakeref = intel_runtime_pm_get(&i915->runtime_pm);
/* Reserve a block so that we know we have enough to fit a few rq */
memset(&hole, 0, sizeof(hole));
mutex_lock(&ggtt->vm.mutex);
err = i915_gem_gtt_insert(&ggtt->vm, NULL, &hole,
PRETEND_GGTT_SIZE, 0, I915_COLOR_UNEVICTABLE,
0, ggtt->vm.total,
PIN_NOEVICT);
if (err)
goto out_locked;
/* Make the GGTT appear small by filling it with unevictable nodes */
count = 0;
do {
struct reserved *r;
mutex_unlock(&ggtt->vm.mutex);
r = kcalloc(1, sizeof(*r), GFP_KERNEL);
mutex_lock(&ggtt->vm.mutex);
if (!r) {
err = -ENOMEM;
goto out_locked;
}
if (i915_gem_gtt_insert(&ggtt->vm, NULL, &r->node,
1ul << 20, 0, I915_COLOR_UNEVICTABLE,
0, ggtt->vm.total,
PIN_NOEVICT)) {
kfree(r);
break;
}
r->next = reserved;
reserved = r;
count++;
} while (1);
drm_mm_remove_node(&hole);
mutex_unlock(&ggtt->vm.mutex);
pr_info("Filled GGTT with %lu 1MiB nodes\n", count);
/* Overfill the GGTT with context objects and so try to evict one. */
for_each_engine(engine, gt, id) {
struct i915_sw_fence fence;
struct i915_request *last = NULL;
count = 0;
onstack_fence_init(&fence);
do {
struct intel_context *ce;
struct i915_request *rq;
ce = intel_context_create(engine);
if (IS_ERR(ce))
break;
/* We will need some GGTT space for the rq's context */
igt_evict_ctl.fail_if_busy = true;
rq = intel_context_create_request(ce);
igt_evict_ctl.fail_if_busy = false;
intel_context_put(ce);
if (IS_ERR(rq)) {
/* When full, fail_if_busy will trigger EBUSY */
if (PTR_ERR(rq) != -EBUSY) {
pr_err("Unexpected error from request alloc (on %s): %d\n",
engine->name,
(int)PTR_ERR(rq));
err = PTR_ERR(rq);
}
break;
}
/* Keep every request/ctx pinned until we are full */
err = i915_sw_fence_await_sw_fence_gfp(&rq->submit,
&fence,
GFP_KERNEL);
if (err < 0)
break;
i915_request_add(rq);
count++;
if (last)
i915_request_put(last);
last = i915_request_get(rq);
err = 0;
} while(1);
onstack_fence_fini(&fence);
pr_info("Submitted %lu contexts/requests on %s\n",
count, engine->name);
if (err)
break;
if (last) {
if (i915_request_wait(last, 0, HZ) < 0) {
err = -EIO;
i915_request_put(last);
pr_err("Failed waiting for last request (on %s)",
engine->name);
break;
}
i915_request_put(last);
}
err = intel_gt_wait_for_idle(engine->gt, HZ * 3);
if (err) {
gt_err(engine->gt, "Failed to idle GT (on %s)",
engine->name);
break;
}
}
mutex_lock(&ggtt->vm.mutex);
out_locked:
if (igt_flush_test(i915))
err = -EIO;
while (reserved) {
struct reserved *next = reserved->next;
drm_mm_remove_node(&reserved->node);
kfree(reserved);
reserved = next;
}
if (drm_mm_node_allocated(&hole))
drm_mm_remove_node(&hole);
mutex_unlock(&ggtt->vm.mutex);
intel_runtime_pm_put(&i915->runtime_pm, wakeref);
return err;
}
int i915_gem_evict_mock_selftests(void)
{
static const struct i915_subtest tests[] = {
SUBTEST(igt_evict_something),
SUBTEST(igt_evict_for_vma),
SUBTEST(igt_evict_for_cache_color),
SUBTEST(igt_evict_vm),
SUBTEST(igt_overcommit),
};
struct drm_i915_private *i915;
intel_wakeref_t wakeref;
int err = 0;
i915 = mock_gem_device();
if (!i915)
return -ENOMEM;
with_intel_runtime_pm(&i915->runtime_pm, wakeref)
err = i915_subtests(tests, to_gt(i915));
mock_destroy_device(i915);
return err;
}
int i915_gem_evict_live_selftests(struct drm_i915_private *i915)
{
static const struct i915_subtest tests[] = {
SUBTEST(igt_evict_contexts),
};
if (intel_gt_is_wedged(to_gt(i915)))
return 0;
return intel_gt_live_subtests(tests, to_gt(i915));
}
| linux-master | drivers/gpu/drm/i915/selftests/i915_gem_evict.c |
/*
* Copyright © 2016 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
#include "../i915_selftest.h"
static int intel_fw_table_check(const struct intel_forcewake_range *ranges,
unsigned int num_ranges,
bool is_watertight)
{
unsigned int i;
s32 prev;
for (i = 0, prev = -1; i < num_ranges; i++, ranges++) {
/* Check that the table is watertight */
if (is_watertight && (prev + 1) != (s32)ranges->start) {
pr_err("%s: entry[%d]:(%x, %x) is not watertight to previous (%x)\n",
__func__, i, ranges->start, ranges->end, prev);
return -EINVAL;
}
/* Check that the table never goes backwards */
if (prev >= (s32)ranges->start) {
pr_err("%s: entry[%d]:(%x, %x) is less than the previous (%x)\n",
__func__, i, ranges->start, ranges->end, prev);
return -EINVAL;
}
/* Check that the entry is valid */
if (ranges->start >= ranges->end) {
pr_err("%s: entry[%d]:(%x, %x) has negative length\n",
__func__, i, ranges->start, ranges->end);
return -EINVAL;
}
prev = ranges->end;
}
return 0;
}
static int intel_shadow_table_check(void)
{
struct {
const struct i915_range *regs;
unsigned int size;
} range_lists[] = {
{ gen8_shadowed_regs, ARRAY_SIZE(gen8_shadowed_regs) },
{ gen11_shadowed_regs, ARRAY_SIZE(gen11_shadowed_regs) },
{ gen12_shadowed_regs, ARRAY_SIZE(gen12_shadowed_regs) },
{ dg2_shadowed_regs, ARRAY_SIZE(dg2_shadowed_regs) },
{ pvc_shadowed_regs, ARRAY_SIZE(pvc_shadowed_regs) },
{ mtl_shadowed_regs, ARRAY_SIZE(mtl_shadowed_regs) },
{ xelpmp_shadowed_regs, ARRAY_SIZE(xelpmp_shadowed_regs) },
};
const struct i915_range *range;
unsigned int i, j;
s32 prev;
for (j = 0; j < ARRAY_SIZE(range_lists); ++j) {
range = range_lists[j].regs;
for (i = 0, prev = -1; i < range_lists[j].size; i++, range++) {
if (range->end < range->start) {
pr_err("%s: range[%d]:(%06x-%06x) has end before start\n",
__func__, i, range->start, range->end);
return -EINVAL;
}
if (prev >= (s32)range->start) {
pr_err("%s: range[%d]:(%06x-%06x) is before end of previous (%06x)\n",
__func__, i, range->start, range->end, prev);
return -EINVAL;
}
if (range->start % 4) {
pr_err("%s: range[%d]:(%06x-%06x) has non-dword-aligned start\n",
__func__, i, range->start, range->end);
return -EINVAL;
}
prev = range->end;
}
}
return 0;
}
int intel_uncore_mock_selftests(void)
{
struct {
const struct intel_forcewake_range *ranges;
unsigned int num_ranges;
bool is_watertight;
} fw[] = {
{ __vlv_fw_ranges, ARRAY_SIZE(__vlv_fw_ranges), false },
{ __chv_fw_ranges, ARRAY_SIZE(__chv_fw_ranges), false },
{ __gen9_fw_ranges, ARRAY_SIZE(__gen9_fw_ranges), true },
{ __gen11_fw_ranges, ARRAY_SIZE(__gen11_fw_ranges), true },
{ __gen12_fw_ranges, ARRAY_SIZE(__gen12_fw_ranges), true },
{ __xehp_fw_ranges, ARRAY_SIZE(__xehp_fw_ranges), true },
{ __pvc_fw_ranges, ARRAY_SIZE(__pvc_fw_ranges), true },
{ __mtl_fw_ranges, ARRAY_SIZE(__mtl_fw_ranges), true },
{ __xelpmp_fw_ranges, ARRAY_SIZE(__xelpmp_fw_ranges), true },
};
int err, i;
for (i = 0; i < ARRAY_SIZE(fw); i++) {
err = intel_fw_table_check(fw[i].ranges,
fw[i].num_ranges,
fw[i].is_watertight);
if (err)
return err;
}
err = intel_shadow_table_check();
if (err)
return err;
return 0;
}
static int live_forcewake_ops(void *arg)
{
static const struct reg {
const char *name;
u8 min_graphics_ver;
u8 max_graphics_ver;
unsigned long platforms;
unsigned int offset;
} registers[] = {
{
"RING_START",
6, 7,
0x38,
},
{
"RING_MI_MODE",
8, U8_MAX,
0x9c,
}
};
const struct reg *r;
struct intel_gt *gt = arg;
struct intel_uncore_forcewake_domain *domain;
struct intel_uncore *uncore = gt->uncore;
struct intel_engine_cs *engine;
enum intel_engine_id id;
intel_wakeref_t wakeref;
unsigned int tmp;
int err = 0;
GEM_BUG_ON(gt->awake);
/* vlv/chv with their pcu behave differently wrt reads */
if (IS_VALLEYVIEW(gt->i915) || IS_CHERRYVIEW(gt->i915)) {
pr_debug("PCU fakes forcewake badly; skipping\n");
return 0;
}
/*
* Not quite as reliable across the gen as one would hope.
*
* Either our theory of operation is incorrect, or there remain
* external parties interfering with the powerwells.
*
* https://bugs.freedesktop.org/show_bug.cgi?id=110210
*/
if (!IS_ENABLED(CONFIG_DRM_I915_SELFTEST_BROKEN))
return 0;
/* We have to pick carefully to get the exact behaviour we need */
for (r = registers; r->name; r++)
if (IS_GRAPHICS_VER(gt->i915, r->min_graphics_ver, r->max_graphics_ver))
break;
if (!r->name) {
pr_debug("Forcewaked register not known for %s; skipping\n",
intel_platform_name(INTEL_INFO(gt->i915)->platform));
return 0;
}
wakeref = intel_runtime_pm_get(uncore->rpm);
for_each_fw_domain(domain, uncore, tmp) {
smp_store_mb(domain->active, false);
if (!hrtimer_cancel(&domain->timer))
continue;
intel_uncore_fw_release_timer(&domain->timer);
}
for_each_engine(engine, gt, id) {
i915_reg_t mmio = _MMIO(engine->mmio_base + r->offset);
u32 __iomem *reg = intel_uncore_regs(uncore) + engine->mmio_base + r->offset;
enum forcewake_domains fw_domains;
u32 val;
if (!engine->default_state)
continue;
fw_domains = intel_uncore_forcewake_for_reg(uncore, mmio,
FW_REG_READ);
if (!fw_domains)
continue;
for_each_fw_domain_masked(domain, fw_domains, uncore, tmp) {
if (!domain->wake_count)
continue;
pr_err("fw_domain %s still active, aborting test!\n",
intel_uncore_forcewake_domain_to_str(domain->id));
err = -EINVAL;
goto out_rpm;
}
intel_uncore_forcewake_get(uncore, fw_domains);
val = readl(reg);
intel_uncore_forcewake_put(uncore, fw_domains);
/* Flush the forcewake release (delayed onto a timer) */
for_each_fw_domain_masked(domain, fw_domains, uncore, tmp) {
smp_store_mb(domain->active, false);
if (hrtimer_cancel(&domain->timer))
intel_uncore_fw_release_timer(&domain->timer);
preempt_disable();
err = wait_ack_clear(domain, FORCEWAKE_KERNEL);
preempt_enable();
if (err) {
pr_err("Failed to clear fw_domain %s\n",
intel_uncore_forcewake_domain_to_str(domain->id));
goto out_rpm;
}
}
if (!val) {
pr_err("%s:%s was zero while fw was held!\n",
engine->name, r->name);
err = -EINVAL;
goto out_rpm;
}
/* We then expect the read to return 0 outside of the fw */
if (wait_for(readl(reg) == 0, 100)) {
pr_err("%s:%s=%0x, fw_domains 0x%x still up after 100ms!\n",
engine->name, r->name, readl(reg), fw_domains);
err = -ETIMEDOUT;
goto out_rpm;
}
}
out_rpm:
intel_runtime_pm_put(uncore->rpm, wakeref);
return err;
}
static int live_forcewake_domains(void *arg)
{
#define FW_RANGE 0x40000
struct intel_gt *gt = arg;
struct intel_uncore *uncore = gt->uncore;
unsigned long *valid;
u32 offset;
int err;
if (!HAS_FPGA_DBG_UNCLAIMED(gt->i915) &&
!IS_VALLEYVIEW(gt->i915) &&
!IS_CHERRYVIEW(gt->i915))
return 0;
/*
* This test may lockup the machine or cause GPU hangs afterwards.
*/
if (!IS_ENABLED(CONFIG_DRM_I915_SELFTEST_BROKEN))
return 0;
valid = bitmap_zalloc(FW_RANGE, GFP_KERNEL);
if (!valid)
return -ENOMEM;
intel_uncore_forcewake_get(uncore, FORCEWAKE_ALL);
check_for_unclaimed_mmio(uncore);
for (offset = 0; offset < FW_RANGE; offset += 4) {
i915_reg_t reg = { offset };
intel_uncore_posting_read_fw(uncore, reg);
if (!check_for_unclaimed_mmio(uncore))
set_bit(offset, valid);
}
intel_uncore_forcewake_put(uncore, FORCEWAKE_ALL);
err = 0;
for_each_set_bit(offset, valid, FW_RANGE) {
i915_reg_t reg = { offset };
iosf_mbi_punit_acquire();
intel_uncore_forcewake_reset(uncore);
iosf_mbi_punit_release();
check_for_unclaimed_mmio(uncore);
intel_uncore_posting_read_fw(uncore, reg);
if (check_for_unclaimed_mmio(uncore)) {
pr_err("Unclaimed mmio read to register 0x%04x\n",
offset);
err = -EINVAL;
}
}
bitmap_free(valid);
return err;
}
static int live_fw_table(void *arg)
{
struct intel_gt *gt = arg;
/* Confirm the table we load is still valid */
return intel_fw_table_check(gt->uncore->fw_domains_table,
gt->uncore->fw_domains_table_entries,
GRAPHICS_VER(gt->i915) >= 9);
}
int intel_uncore_live_selftests(struct drm_i915_private *i915)
{
static const struct i915_subtest tests[] = {
SUBTEST(live_fw_table),
SUBTEST(live_forcewake_ops),
SUBTEST(live_forcewake_domains),
};
return intel_gt_live_subtests(tests, to_gt(i915));
}
| linux-master | drivers/gpu/drm/i915/selftests/intel_uncore.c |
/*
* Copyright © 2016 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
#include <linux/list_sort.h>
#include <linux/prime_numbers.h>
#include "gem/i915_gem_context.h"
#include "gem/i915_gem_internal.h"
#include "gem/i915_gem_lmem.h"
#include "gem/i915_gem_region.h"
#include "gem/selftests/mock_context.h"
#include "gt/intel_context.h"
#include "gt/intel_gpu_commands.h"
#include "gt/intel_gtt.h"
#include "i915_random.h"
#include "i915_selftest.h"
#include "i915_vma_resource.h"
#include "mock_drm.h"
#include "mock_gem_device.h"
#include "mock_gtt.h"
#include "igt_flush_test.h"
static void cleanup_freed_objects(struct drm_i915_private *i915)
{
i915_gem_drain_freed_objects(i915);
}
static void fake_free_pages(struct drm_i915_gem_object *obj,
struct sg_table *pages)
{
sg_free_table(pages);
kfree(pages);
}
static int fake_get_pages(struct drm_i915_gem_object *obj)
{
#define GFP (GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY)
#define PFN_BIAS 0x1000
struct sg_table *pages;
struct scatterlist *sg;
typeof(obj->base.size) rem;
pages = kmalloc(sizeof(*pages), GFP);
if (!pages)
return -ENOMEM;
rem = round_up(obj->base.size, BIT(31)) >> 31;
/* restricted by sg_alloc_table */
if (overflows_type(rem, unsigned int)) {
kfree(pages);
return -E2BIG;
}
if (sg_alloc_table(pages, rem, GFP)) {
kfree(pages);
return -ENOMEM;
}
rem = obj->base.size;
for (sg = pages->sgl; sg; sg = sg_next(sg)) {
unsigned long len = min_t(typeof(rem), rem, BIT(31));
GEM_BUG_ON(!len);
sg_set_page(sg, pfn_to_page(PFN_BIAS), len, 0);
sg_dma_address(sg) = page_to_phys(sg_page(sg));
sg_dma_len(sg) = len;
rem -= len;
}
GEM_BUG_ON(rem);
__i915_gem_object_set_pages(obj, pages);
return 0;
#undef GFP
}
static void fake_put_pages(struct drm_i915_gem_object *obj,
struct sg_table *pages)
{
fake_free_pages(obj, pages);
obj->mm.dirty = false;
}
static const struct drm_i915_gem_object_ops fake_ops = {
.name = "fake-gem",
.flags = I915_GEM_OBJECT_IS_SHRINKABLE,
.get_pages = fake_get_pages,
.put_pages = fake_put_pages,
};
static struct drm_i915_gem_object *
fake_dma_object(struct drm_i915_private *i915, u64 size)
{
static struct lock_class_key lock_class;
struct drm_i915_gem_object *obj;
GEM_BUG_ON(!size);
GEM_BUG_ON(!IS_ALIGNED(size, I915_GTT_PAGE_SIZE));
if (overflows_type(size, obj->base.size))
return ERR_PTR(-E2BIG);
obj = i915_gem_object_alloc();
if (!obj)
goto err;
drm_gem_private_object_init(&i915->drm, &obj->base, size);
i915_gem_object_init(obj, &fake_ops, &lock_class, 0);
i915_gem_object_set_volatile(obj);
obj->write_domain = I915_GEM_DOMAIN_CPU;
obj->read_domains = I915_GEM_DOMAIN_CPU;
obj->pat_index = i915_gem_get_pat_index(i915, I915_CACHE_NONE);
/* Preallocate the "backing storage" */
if (i915_gem_object_pin_pages_unlocked(obj))
goto err_obj;
i915_gem_object_unpin_pages(obj);
return obj;
err_obj:
i915_gem_object_put(obj);
err:
return ERR_PTR(-ENOMEM);
}
static int igt_ppgtt_alloc(void *arg)
{
struct drm_i915_private *dev_priv = arg;
struct i915_ppgtt *ppgtt;
struct i915_gem_ww_ctx ww;
u64 size, last, limit;
int err = 0;
/* Allocate a ppggt and try to fill the entire range */
if (!HAS_PPGTT(dev_priv))
return 0;
ppgtt = i915_ppgtt_create(to_gt(dev_priv), 0);
if (IS_ERR(ppgtt))
return PTR_ERR(ppgtt);
if (!ppgtt->vm.allocate_va_range)
goto err_ppgtt_cleanup;
/*
* While we only allocate the page tables here and so we could
* address a much larger GTT than we could actually fit into
* RAM, a practical limit is the amount of physical pages in the system.
* This should ensure that we do not run into the oomkiller during
* the test and take down the machine wilfully.
*/
limit = totalram_pages() << PAGE_SHIFT;
limit = min(ppgtt->vm.total, limit);
i915_gem_ww_ctx_init(&ww, false);
retry:
err = i915_vm_lock_objects(&ppgtt->vm, &ww);
if (err)
goto err_ppgtt_cleanup;
/* Check we can allocate the entire range */
for (size = 4096; size <= limit; size <<= 2) {
struct i915_vm_pt_stash stash = {};
err = i915_vm_alloc_pt_stash(&ppgtt->vm, &stash, size);
if (err)
goto err_ppgtt_cleanup;
err = i915_vm_map_pt_stash(&ppgtt->vm, &stash);
if (err) {
i915_vm_free_pt_stash(&ppgtt->vm, &stash);
goto err_ppgtt_cleanup;
}
ppgtt->vm.allocate_va_range(&ppgtt->vm, &stash, 0, size);
cond_resched();
ppgtt->vm.clear_range(&ppgtt->vm, 0, size);
i915_vm_free_pt_stash(&ppgtt->vm, &stash);
}
/* Check we can incrementally allocate the entire range */
for (last = 0, size = 4096; size <= limit; last = size, size <<= 2) {
struct i915_vm_pt_stash stash = {};
err = i915_vm_alloc_pt_stash(&ppgtt->vm, &stash, size - last);
if (err)
goto err_ppgtt_cleanup;
err = i915_vm_map_pt_stash(&ppgtt->vm, &stash);
if (err) {
i915_vm_free_pt_stash(&ppgtt->vm, &stash);
goto err_ppgtt_cleanup;
}
ppgtt->vm.allocate_va_range(&ppgtt->vm, &stash,
last, size - last);
cond_resched();
i915_vm_free_pt_stash(&ppgtt->vm, &stash);
}
err_ppgtt_cleanup:
if (err == -EDEADLK) {
err = i915_gem_ww_ctx_backoff(&ww);
if (!err)
goto retry;
}
i915_gem_ww_ctx_fini(&ww);
i915_vm_put(&ppgtt->vm);
return err;
}
static int lowlevel_hole(struct i915_address_space *vm,
u64 hole_start, u64 hole_end,
unsigned long end_time)
{
const unsigned int min_alignment =
i915_vm_min_alignment(vm, INTEL_MEMORY_SYSTEM);
I915_RND_STATE(seed_prng);
struct i915_vma_resource *mock_vma_res;
unsigned int size;
mock_vma_res = kzalloc(sizeof(*mock_vma_res), GFP_KERNEL);
if (!mock_vma_res)
return -ENOMEM;
/* Keep creating larger objects until one cannot fit into the hole */
for (size = 12; (hole_end - hole_start) >> size; size++) {
I915_RND_SUBSTATE(prng, seed_prng);
struct drm_i915_gem_object *obj;
unsigned int *order, count, n;
u64 hole_size, aligned_size;
aligned_size = max_t(u32, ilog2(min_alignment), size);
hole_size = (hole_end - hole_start) >> aligned_size;
if (hole_size > KMALLOC_MAX_SIZE / sizeof(u32))
hole_size = KMALLOC_MAX_SIZE / sizeof(u32);
count = hole_size >> 1;
if (!count) {
pr_debug("%s: hole is too small [%llx - %llx] >> %d: %lld\n",
__func__, hole_start, hole_end, size, hole_size);
break;
}
do {
order = i915_random_order(count, &prng);
if (order)
break;
} while (count >>= 1);
if (!count) {
kfree(mock_vma_res);
return -ENOMEM;
}
GEM_BUG_ON(!order);
GEM_BUG_ON(count * BIT_ULL(aligned_size) > vm->total);
GEM_BUG_ON(hole_start + count * BIT_ULL(aligned_size) > hole_end);
/* Ignore allocation failures (i.e. don't report them as
* a test failure) as we are purposefully allocating very
* large objects without checking that we have sufficient
* memory. We expect to hit -ENOMEM.
*/
obj = fake_dma_object(vm->i915, BIT_ULL(size));
if (IS_ERR(obj)) {
kfree(order);
break;
}
GEM_BUG_ON(obj->base.size != BIT_ULL(size));
if (i915_gem_object_pin_pages_unlocked(obj)) {
i915_gem_object_put(obj);
kfree(order);
break;
}
for (n = 0; n < count; n++) {
u64 addr = hole_start + order[n] * BIT_ULL(aligned_size);
intel_wakeref_t wakeref;
GEM_BUG_ON(addr + BIT_ULL(aligned_size) > vm->total);
if (igt_timeout(end_time,
"%s timed out before %d/%d\n",
__func__, n, count)) {
hole_end = hole_start; /* quit */
break;
}
if (vm->allocate_va_range) {
struct i915_vm_pt_stash stash = {};
struct i915_gem_ww_ctx ww;
int err;
i915_gem_ww_ctx_init(&ww, false);
retry:
err = i915_vm_lock_objects(vm, &ww);
if (err)
goto alloc_vm_end;
err = -ENOMEM;
if (i915_vm_alloc_pt_stash(vm, &stash,
BIT_ULL(size)))
goto alloc_vm_end;
err = i915_vm_map_pt_stash(vm, &stash);
if (!err)
vm->allocate_va_range(vm, &stash,
addr, BIT_ULL(size));
i915_vm_free_pt_stash(vm, &stash);
alloc_vm_end:
if (err == -EDEADLK) {
err = i915_gem_ww_ctx_backoff(&ww);
if (!err)
goto retry;
}
i915_gem_ww_ctx_fini(&ww);
if (err)
break;
}
mock_vma_res->bi.pages = obj->mm.pages;
mock_vma_res->node_size = BIT_ULL(aligned_size);
mock_vma_res->start = addr;
with_intel_runtime_pm(vm->gt->uncore->rpm, wakeref)
vm->insert_entries(vm, mock_vma_res,
i915_gem_get_pat_index(vm->i915,
I915_CACHE_NONE),
0);
}
count = n;
i915_random_reorder(order, count, &prng);
for (n = 0; n < count; n++) {
u64 addr = hole_start + order[n] * BIT_ULL(aligned_size);
intel_wakeref_t wakeref;
GEM_BUG_ON(addr + BIT_ULL(size) > vm->total);
with_intel_runtime_pm(vm->gt->uncore->rpm, wakeref)
vm->clear_range(vm, addr, BIT_ULL(size));
}
i915_gem_object_unpin_pages(obj);
i915_gem_object_put(obj);
kfree(order);
cleanup_freed_objects(vm->i915);
}
kfree(mock_vma_res);
return 0;
}
static void close_object_list(struct list_head *objects,
struct i915_address_space *vm)
{
struct drm_i915_gem_object *obj, *on;
int __maybe_unused ignored;
list_for_each_entry_safe(obj, on, objects, st_link) {
struct i915_vma *vma;
vma = i915_vma_instance(obj, vm, NULL);
if (!IS_ERR(vma))
ignored = i915_vma_unbind_unlocked(vma);
list_del(&obj->st_link);
i915_gem_object_put(obj);
}
}
static int fill_hole(struct i915_address_space *vm,
u64 hole_start, u64 hole_end,
unsigned long end_time)
{
const u64 hole_size = hole_end - hole_start;
struct drm_i915_gem_object *obj;
const unsigned int min_alignment =
i915_vm_min_alignment(vm, INTEL_MEMORY_SYSTEM);
const unsigned long max_pages =
min_t(u64, ULONG_MAX - 1, (hole_size / 2) >> ilog2(min_alignment));
const unsigned long max_step = max(int_sqrt(max_pages), 2UL);
unsigned long npages, prime, flags;
struct i915_vma *vma;
LIST_HEAD(objects);
int err;
/* Try binding many VMA working inwards from either edge */
flags = PIN_OFFSET_FIXED | PIN_USER;
if (i915_is_ggtt(vm))
flags |= PIN_GLOBAL;
for_each_prime_number_from(prime, 2, max_step) {
for (npages = 1; npages <= max_pages; npages *= prime) {
const u64 full_size = npages << PAGE_SHIFT;
const struct {
const char *name;
u64 offset;
int step;
} phases[] = {
{ "top-down", hole_end, -1, },
{ "bottom-up", hole_start, 1, },
{ }
}, *p;
obj = fake_dma_object(vm->i915, full_size);
if (IS_ERR(obj))
break;
list_add(&obj->st_link, &objects);
/* Align differing sized objects against the edges, and
* check we don't walk off into the void when binding
* them into the GTT.
*/
for (p = phases; p->name; p++) {
u64 offset;
offset = p->offset;
list_for_each_entry(obj, &objects, st_link) {
u64 aligned_size = round_up(obj->base.size,
min_alignment);
vma = i915_vma_instance(obj, vm, NULL);
if (IS_ERR(vma))
continue;
if (p->step < 0) {
if (offset < hole_start + aligned_size)
break;
offset -= aligned_size;
}
err = i915_vma_pin(vma, 0, 0, offset | flags);
if (err) {
pr_err("%s(%s) pin (forward) failed with err=%d on size=%lu pages (prime=%lu), offset=%llx\n",
__func__, p->name, err, npages, prime, offset);
goto err;
}
if (!drm_mm_node_allocated(&vma->node) ||
i915_vma_misplaced(vma, 0, 0, offset | flags)) {
pr_err("%s(%s) (forward) insert failed: vma.node=%llx + %llx [allocated? %d], expected offset %llx\n",
__func__, p->name, vma->node.start, vma->node.size, drm_mm_node_allocated(&vma->node),
offset);
err = -EINVAL;
goto err;
}
i915_vma_unpin(vma);
if (p->step > 0) {
if (offset + aligned_size > hole_end)
break;
offset += aligned_size;
}
}
offset = p->offset;
list_for_each_entry(obj, &objects, st_link) {
u64 aligned_size = round_up(obj->base.size,
min_alignment);
vma = i915_vma_instance(obj, vm, NULL);
if (IS_ERR(vma))
continue;
if (p->step < 0) {
if (offset < hole_start + aligned_size)
break;
offset -= aligned_size;
}
if (!drm_mm_node_allocated(&vma->node) ||
i915_vma_misplaced(vma, 0, 0, offset | flags)) {
pr_err("%s(%s) (forward) moved vma.node=%llx + %llx, expected offset %llx\n",
__func__, p->name, vma->node.start, vma->node.size,
offset);
err = -EINVAL;
goto err;
}
err = i915_vma_unbind_unlocked(vma);
if (err) {
pr_err("%s(%s) (forward) unbind of vma.node=%llx + %llx failed with err=%d\n",
__func__, p->name, vma->node.start, vma->node.size,
err);
goto err;
}
if (p->step > 0) {
if (offset + aligned_size > hole_end)
break;
offset += aligned_size;
}
}
offset = p->offset;
list_for_each_entry_reverse(obj, &objects, st_link) {
u64 aligned_size = round_up(obj->base.size,
min_alignment);
vma = i915_vma_instance(obj, vm, NULL);
if (IS_ERR(vma))
continue;
if (p->step < 0) {
if (offset < hole_start + aligned_size)
break;
offset -= aligned_size;
}
err = i915_vma_pin(vma, 0, 0, offset | flags);
if (err) {
pr_err("%s(%s) pin (backward) failed with err=%d on size=%lu pages (prime=%lu), offset=%llx\n",
__func__, p->name, err, npages, prime, offset);
goto err;
}
if (!drm_mm_node_allocated(&vma->node) ||
i915_vma_misplaced(vma, 0, 0, offset | flags)) {
pr_err("%s(%s) (backward) insert failed: vma.node=%llx + %llx [allocated? %d], expected offset %llx\n",
__func__, p->name, vma->node.start, vma->node.size, drm_mm_node_allocated(&vma->node),
offset);
err = -EINVAL;
goto err;
}
i915_vma_unpin(vma);
if (p->step > 0) {
if (offset + aligned_size > hole_end)
break;
offset += aligned_size;
}
}
offset = p->offset;
list_for_each_entry_reverse(obj, &objects, st_link) {
u64 aligned_size = round_up(obj->base.size,
min_alignment);
vma = i915_vma_instance(obj, vm, NULL);
if (IS_ERR(vma))
continue;
if (p->step < 0) {
if (offset < hole_start + aligned_size)
break;
offset -= aligned_size;
}
if (!drm_mm_node_allocated(&vma->node) ||
i915_vma_misplaced(vma, 0, 0, offset | flags)) {
pr_err("%s(%s) (backward) moved vma.node=%llx + %llx [allocated? %d], expected offset %llx\n",
__func__, p->name, vma->node.start, vma->node.size, drm_mm_node_allocated(&vma->node),
offset);
err = -EINVAL;
goto err;
}
err = i915_vma_unbind_unlocked(vma);
if (err) {
pr_err("%s(%s) (backward) unbind of vma.node=%llx + %llx failed with err=%d\n",
__func__, p->name, vma->node.start, vma->node.size,
err);
goto err;
}
if (p->step > 0) {
if (offset + aligned_size > hole_end)
break;
offset += aligned_size;
}
}
}
if (igt_timeout(end_time, "%s timed out (npages=%lu, prime=%lu)\n",
__func__, npages, prime)) {
err = -EINTR;
goto err;
}
}
close_object_list(&objects, vm);
cleanup_freed_objects(vm->i915);
}
return 0;
err:
close_object_list(&objects, vm);
return err;
}
static int walk_hole(struct i915_address_space *vm,
u64 hole_start, u64 hole_end,
unsigned long end_time)
{
const u64 hole_size = hole_end - hole_start;
const unsigned long max_pages =
min_t(u64, ULONG_MAX - 1, hole_size >> PAGE_SHIFT);
unsigned long min_alignment;
unsigned long flags;
u64 size;
/* Try binding a single VMA in different positions within the hole */
flags = PIN_OFFSET_FIXED | PIN_USER;
if (i915_is_ggtt(vm))
flags |= PIN_GLOBAL;
min_alignment = i915_vm_min_alignment(vm, INTEL_MEMORY_SYSTEM);
for_each_prime_number_from(size, 1, max_pages) {
struct drm_i915_gem_object *obj;
struct i915_vma *vma;
u64 addr;
int err = 0;
obj = fake_dma_object(vm->i915, size << PAGE_SHIFT);
if (IS_ERR(obj))
break;
vma = i915_vma_instance(obj, vm, NULL);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto err_put;
}
for (addr = hole_start;
addr + obj->base.size < hole_end;
addr += round_up(obj->base.size, min_alignment)) {
err = i915_vma_pin(vma, 0, 0, addr | flags);
if (err) {
pr_err("%s bind failed at %llx + %llx [hole %llx- %llx] with err=%d\n",
__func__, addr, vma->size,
hole_start, hole_end, err);
goto err_put;
}
i915_vma_unpin(vma);
if (!drm_mm_node_allocated(&vma->node) ||
i915_vma_misplaced(vma, 0, 0, addr | flags)) {
pr_err("%s incorrect at %llx + %llx\n",
__func__, addr, vma->size);
err = -EINVAL;
goto err_put;
}
err = i915_vma_unbind_unlocked(vma);
if (err) {
pr_err("%s unbind failed at %llx + %llx with err=%d\n",
__func__, addr, vma->size, err);
goto err_put;
}
GEM_BUG_ON(drm_mm_node_allocated(&vma->node));
if (igt_timeout(end_time,
"%s timed out at %llx\n",
__func__, addr)) {
err = -EINTR;
goto err_put;
}
}
err_put:
i915_gem_object_put(obj);
if (err)
return err;
cleanup_freed_objects(vm->i915);
}
return 0;
}
static int pot_hole(struct i915_address_space *vm,
u64 hole_start, u64 hole_end,
unsigned long end_time)
{
struct drm_i915_gem_object *obj;
struct i915_vma *vma;
unsigned int min_alignment;
unsigned long flags;
unsigned int pot;
int err = 0;
flags = PIN_OFFSET_FIXED | PIN_USER;
if (i915_is_ggtt(vm))
flags |= PIN_GLOBAL;
min_alignment = i915_vm_min_alignment(vm, INTEL_MEMORY_SYSTEM);
obj = i915_gem_object_create_internal(vm->i915, 2 * I915_GTT_PAGE_SIZE);
if (IS_ERR(obj))
return PTR_ERR(obj);
vma = i915_vma_instance(obj, vm, NULL);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto err_obj;
}
/* Insert a pair of pages across every pot boundary within the hole */
for (pot = fls64(hole_end - 1) - 1;
pot > ilog2(2 * min_alignment);
pot--) {
u64 step = BIT_ULL(pot);
u64 addr;
for (addr = round_up(hole_start + min_alignment, step) - min_alignment;
hole_end > addr && hole_end - addr >= 2 * min_alignment;
addr += step) {
err = i915_vma_pin(vma, 0, 0, addr | flags);
if (err) {
pr_err("%s failed to pin object at %llx in hole [%llx - %llx], with err=%d\n",
__func__,
addr,
hole_start, hole_end,
err);
goto err_obj;
}
if (!drm_mm_node_allocated(&vma->node) ||
i915_vma_misplaced(vma, 0, 0, addr | flags)) {
pr_err("%s incorrect at %llx + %llx\n",
__func__, addr, vma->size);
i915_vma_unpin(vma);
err = i915_vma_unbind_unlocked(vma);
err = -EINVAL;
goto err_obj;
}
i915_vma_unpin(vma);
err = i915_vma_unbind_unlocked(vma);
GEM_BUG_ON(err);
}
if (igt_timeout(end_time,
"%s timed out after %d/%d\n",
__func__, pot, fls64(hole_end - 1) - 1)) {
err = -EINTR;
goto err_obj;
}
}
err_obj:
i915_gem_object_put(obj);
return err;
}
static int drunk_hole(struct i915_address_space *vm,
u64 hole_start, u64 hole_end,
unsigned long end_time)
{
I915_RND_STATE(prng);
unsigned int min_alignment;
unsigned int size;
unsigned long flags;
flags = PIN_OFFSET_FIXED | PIN_USER;
if (i915_is_ggtt(vm))
flags |= PIN_GLOBAL;
min_alignment = i915_vm_min_alignment(vm, INTEL_MEMORY_SYSTEM);
/* Keep creating larger objects until one cannot fit into the hole */
for (size = 12; (hole_end - hole_start) >> size; size++) {
struct drm_i915_gem_object *obj;
unsigned int *order, count, n;
struct i915_vma *vma;
u64 hole_size, aligned_size;
int err = -ENODEV;
aligned_size = max_t(u32, ilog2(min_alignment), size);
hole_size = (hole_end - hole_start) >> aligned_size;
if (hole_size > KMALLOC_MAX_SIZE / sizeof(u32))
hole_size = KMALLOC_MAX_SIZE / sizeof(u32);
count = hole_size >> 1;
if (!count) {
pr_debug("%s: hole is too small [%llx - %llx] >> %d: %lld\n",
__func__, hole_start, hole_end, size, hole_size);
break;
}
do {
order = i915_random_order(count, &prng);
if (order)
break;
} while (count >>= 1);
if (!count)
return -ENOMEM;
GEM_BUG_ON(!order);
/* Ignore allocation failures (i.e. don't report them as
* a test failure) as we are purposefully allocating very
* large objects without checking that we have sufficient
* memory. We expect to hit -ENOMEM.
*/
obj = fake_dma_object(vm->i915, BIT_ULL(size));
if (IS_ERR(obj)) {
kfree(order);
break;
}
vma = i915_vma_instance(obj, vm, NULL);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto err_obj;
}
GEM_BUG_ON(vma->size != BIT_ULL(size));
for (n = 0; n < count; n++) {
u64 addr = hole_start + order[n] * BIT_ULL(aligned_size);
err = i915_vma_pin(vma, 0, 0, addr | flags);
if (err) {
pr_err("%s failed to pin object at %llx + %llx in hole [%llx - %llx], with err=%d\n",
__func__,
addr, BIT_ULL(size),
hole_start, hole_end,
err);
goto err_obj;
}
if (!drm_mm_node_allocated(&vma->node) ||
i915_vma_misplaced(vma, 0, 0, addr | flags)) {
pr_err("%s incorrect at %llx + %llx\n",
__func__, addr, BIT_ULL(size));
i915_vma_unpin(vma);
err = i915_vma_unbind_unlocked(vma);
err = -EINVAL;
goto err_obj;
}
i915_vma_unpin(vma);
err = i915_vma_unbind_unlocked(vma);
GEM_BUG_ON(err);
if (igt_timeout(end_time,
"%s timed out after %d/%d\n",
__func__, n, count)) {
err = -EINTR;
goto err_obj;
}
}
err_obj:
i915_gem_object_put(obj);
kfree(order);
if (err)
return err;
cleanup_freed_objects(vm->i915);
}
return 0;
}
static int __shrink_hole(struct i915_address_space *vm,
u64 hole_start, u64 hole_end,
unsigned long end_time)
{
struct drm_i915_gem_object *obj;
unsigned long flags = PIN_OFFSET_FIXED | PIN_USER;
unsigned int min_alignment;
unsigned int order = 12;
LIST_HEAD(objects);
int err = 0;
u64 addr;
min_alignment = i915_vm_min_alignment(vm, INTEL_MEMORY_SYSTEM);
/* Keep creating larger objects until one cannot fit into the hole */
for (addr = hole_start; addr < hole_end; ) {
struct i915_vma *vma;
u64 size = BIT_ULL(order++);
size = min(size, hole_end - addr);
obj = fake_dma_object(vm->i915, size);
if (IS_ERR(obj)) {
err = PTR_ERR(obj);
break;
}
list_add(&obj->st_link, &objects);
vma = i915_vma_instance(obj, vm, NULL);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
break;
}
GEM_BUG_ON(vma->size != size);
err = i915_vma_pin(vma, 0, 0, addr | flags);
if (err) {
pr_err("%s failed to pin object at %llx + %llx in hole [%llx - %llx], with err=%d\n",
__func__, addr, size, hole_start, hole_end, err);
break;
}
if (!drm_mm_node_allocated(&vma->node) ||
i915_vma_misplaced(vma, 0, 0, addr | flags)) {
pr_err("%s incorrect at %llx + %llx\n",
__func__, addr, size);
i915_vma_unpin(vma);
err = i915_vma_unbind_unlocked(vma);
err = -EINVAL;
break;
}
i915_vma_unpin(vma);
addr += round_up(size, min_alignment);
/*
* Since we are injecting allocation faults at random intervals,
* wait for this allocation to complete before we change the
* faultinjection.
*/
err = i915_vma_sync(vma);
if (err)
break;
if (igt_timeout(end_time,
"%s timed out at ofset %llx [%llx - %llx]\n",
__func__, addr, hole_start, hole_end)) {
err = -EINTR;
break;
}
}
close_object_list(&objects, vm);
cleanup_freed_objects(vm->i915);
return err;
}
static int shrink_hole(struct i915_address_space *vm,
u64 hole_start, u64 hole_end,
unsigned long end_time)
{
unsigned long prime;
int err;
vm->fault_attr.probability = 999;
atomic_set(&vm->fault_attr.times, -1);
for_each_prime_number_from(prime, 0, ULONG_MAX - 1) {
vm->fault_attr.interval = prime;
err = __shrink_hole(vm, hole_start, hole_end, end_time);
if (err)
break;
}
memset(&vm->fault_attr, 0, sizeof(vm->fault_attr));
return err;
}
static int shrink_boom(struct i915_address_space *vm,
u64 hole_start, u64 hole_end,
unsigned long end_time)
{
unsigned int sizes[] = { SZ_2M, SZ_1G };
struct drm_i915_gem_object *purge;
struct drm_i915_gem_object *explode;
int err;
int i;
/*
* Catch the case which shrink_hole seems to miss. The setup here
* requires invoking the shrinker as we do the alloc_pt/alloc_pd, while
* ensuring that all vma assiocated with the respective pd/pdp are
* unpinned at the time.
*/
for (i = 0; i < ARRAY_SIZE(sizes); ++i) {
unsigned int flags = PIN_USER | PIN_OFFSET_FIXED;
unsigned int size = sizes[i];
struct i915_vma *vma;
purge = fake_dma_object(vm->i915, size);
if (IS_ERR(purge))
return PTR_ERR(purge);
vma = i915_vma_instance(purge, vm, NULL);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto err_purge;
}
err = i915_vma_pin(vma, 0, 0, flags);
if (err)
goto err_purge;
/* Should now be ripe for purging */
i915_vma_unpin(vma);
explode = fake_dma_object(vm->i915, size);
if (IS_ERR(explode)) {
err = PTR_ERR(explode);
goto err_purge;
}
vm->fault_attr.probability = 100;
vm->fault_attr.interval = 1;
atomic_set(&vm->fault_attr.times, -1);
vma = i915_vma_instance(explode, vm, NULL);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto err_explode;
}
err = i915_vma_pin(vma, 0, 0, flags | size);
if (err)
goto err_explode;
i915_vma_unpin(vma);
i915_gem_object_put(purge);
i915_gem_object_put(explode);
memset(&vm->fault_attr, 0, sizeof(vm->fault_attr));
cleanup_freed_objects(vm->i915);
}
return 0;
err_explode:
i915_gem_object_put(explode);
err_purge:
i915_gem_object_put(purge);
memset(&vm->fault_attr, 0, sizeof(vm->fault_attr));
return err;
}
static int misaligned_case(struct i915_address_space *vm, struct intel_memory_region *mr,
u64 addr, u64 size, unsigned long flags)
{
struct drm_i915_gem_object *obj;
struct i915_vma *vma;
int err = 0;
u64 expected_vma_size, expected_node_size;
bool is_stolen = mr->type == INTEL_MEMORY_STOLEN_SYSTEM ||
mr->type == INTEL_MEMORY_STOLEN_LOCAL;
obj = i915_gem_object_create_region(mr, size, 0, I915_BO_ALLOC_GPU_ONLY);
if (IS_ERR(obj)) {
/* if iGVT-g or DMAR is active, stolen mem will be uninitialized */
if (PTR_ERR(obj) == -ENODEV && is_stolen)
return 0;
return PTR_ERR(obj);
}
vma = i915_vma_instance(obj, vm, NULL);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto err_put;
}
err = i915_vma_pin(vma, 0, 0, addr | flags);
if (err)
goto err_put;
i915_vma_unpin(vma);
if (!drm_mm_node_allocated(&vma->node)) {
err = -EINVAL;
goto err_put;
}
if (i915_vma_misplaced(vma, 0, 0, addr | flags)) {
err = -EINVAL;
goto err_put;
}
expected_vma_size = round_up(size, 1 << (ffs(vma->resource->page_sizes_gtt) - 1));
expected_node_size = expected_vma_size;
if (HAS_64K_PAGES(vm->i915) && i915_gem_object_is_lmem(obj)) {
expected_vma_size = round_up(size, I915_GTT_PAGE_SIZE_64K);
expected_node_size = round_up(size, I915_GTT_PAGE_SIZE_64K);
}
if (vma->size != expected_vma_size || vma->node.size != expected_node_size) {
err = i915_vma_unbind_unlocked(vma);
err = -EBADSLT;
goto err_put;
}
err = i915_vma_unbind_unlocked(vma);
if (err)
goto err_put;
GEM_BUG_ON(drm_mm_node_allocated(&vma->node));
err_put:
i915_gem_object_put(obj);
cleanup_freed_objects(vm->i915);
return err;
}
static int misaligned_pin(struct i915_address_space *vm,
u64 hole_start, u64 hole_end,
unsigned long end_time)
{
struct intel_memory_region *mr;
enum intel_region_id id;
unsigned long flags = PIN_OFFSET_FIXED | PIN_USER;
int err = 0;
u64 hole_size = hole_end - hole_start;
if (i915_is_ggtt(vm))
flags |= PIN_GLOBAL;
for_each_memory_region(mr, vm->i915, id) {
u64 min_alignment = i915_vm_min_alignment(vm, mr->type);
u64 size = min_alignment;
u64 addr = round_down(hole_start + (hole_size / 2), min_alignment);
/* avoid -ENOSPC on very small hole setups */
if (hole_size < 3 * min_alignment)
continue;
/* we can't test < 4k alignment due to flags being encoded in lower bits */
if (min_alignment != I915_GTT_PAGE_SIZE_4K) {
err = misaligned_case(vm, mr, addr + (min_alignment / 2), size, flags);
/* misaligned should error with -EINVAL*/
if (!err)
err = -EBADSLT;
if (err != -EINVAL)
return err;
}
/* test for vma->size expansion to min page size */
err = misaligned_case(vm, mr, addr, PAGE_SIZE, flags);
if (err)
return err;
/* test for intermediate size not expanding vma->size for large alignments */
err = misaligned_case(vm, mr, addr, size / 2, flags);
if (err)
return err;
}
return 0;
}
static int exercise_ppgtt(struct drm_i915_private *dev_priv,
int (*func)(struct i915_address_space *vm,
u64 hole_start, u64 hole_end,
unsigned long end_time))
{
struct i915_ppgtt *ppgtt;
IGT_TIMEOUT(end_time);
struct file *file;
int err;
if (!HAS_FULL_PPGTT(dev_priv))
return 0;
file = mock_file(dev_priv);
if (IS_ERR(file))
return PTR_ERR(file);
ppgtt = i915_ppgtt_create(to_gt(dev_priv), 0);
if (IS_ERR(ppgtt)) {
err = PTR_ERR(ppgtt);
goto out_free;
}
GEM_BUG_ON(offset_in_page(ppgtt->vm.total));
assert_vm_alive(&ppgtt->vm);
err = func(&ppgtt->vm, 0, ppgtt->vm.total, end_time);
i915_vm_put(&ppgtt->vm);
out_free:
fput(file);
return err;
}
static int igt_ppgtt_fill(void *arg)
{
return exercise_ppgtt(arg, fill_hole);
}
static int igt_ppgtt_walk(void *arg)
{
return exercise_ppgtt(arg, walk_hole);
}
static int igt_ppgtt_pot(void *arg)
{
return exercise_ppgtt(arg, pot_hole);
}
static int igt_ppgtt_drunk(void *arg)
{
return exercise_ppgtt(arg, drunk_hole);
}
static int igt_ppgtt_lowlevel(void *arg)
{
return exercise_ppgtt(arg, lowlevel_hole);
}
static int igt_ppgtt_shrink(void *arg)
{
return exercise_ppgtt(arg, shrink_hole);
}
static int igt_ppgtt_shrink_boom(void *arg)
{
return exercise_ppgtt(arg, shrink_boom);
}
static int igt_ppgtt_misaligned_pin(void *arg)
{
return exercise_ppgtt(arg, misaligned_pin);
}
static int sort_holes(void *priv, const struct list_head *A,
const struct list_head *B)
{
struct drm_mm_node *a = list_entry(A, typeof(*a), hole_stack);
struct drm_mm_node *b = list_entry(B, typeof(*b), hole_stack);
if (a->start < b->start)
return -1;
else
return 1;
}
static int exercise_ggtt(struct drm_i915_private *i915,
int (*func)(struct i915_address_space *vm,
u64 hole_start, u64 hole_end,
unsigned long end_time))
{
struct i915_ggtt *ggtt = to_gt(i915)->ggtt;
u64 hole_start, hole_end, last = 0;
struct drm_mm_node *node;
IGT_TIMEOUT(end_time);
int err = 0;
restart:
list_sort(NULL, &ggtt->vm.mm.hole_stack, sort_holes);
drm_mm_for_each_hole(node, &ggtt->vm.mm, hole_start, hole_end) {
if (hole_start < last)
continue;
if (ggtt->vm.mm.color_adjust)
ggtt->vm.mm.color_adjust(node, 0,
&hole_start, &hole_end);
if (hole_start >= hole_end)
continue;
err = func(&ggtt->vm, hole_start, hole_end, end_time);
if (err)
break;
/* As we have manipulated the drm_mm, the list may be corrupt */
last = hole_end;
goto restart;
}
return err;
}
static int igt_ggtt_fill(void *arg)
{
return exercise_ggtt(arg, fill_hole);
}
static int igt_ggtt_walk(void *arg)
{
return exercise_ggtt(arg, walk_hole);
}
static int igt_ggtt_pot(void *arg)
{
return exercise_ggtt(arg, pot_hole);
}
static int igt_ggtt_drunk(void *arg)
{
return exercise_ggtt(arg, drunk_hole);
}
static int igt_ggtt_lowlevel(void *arg)
{
return exercise_ggtt(arg, lowlevel_hole);
}
static int igt_ggtt_misaligned_pin(void *arg)
{
return exercise_ggtt(arg, misaligned_pin);
}
static int igt_ggtt_page(void *arg)
{
const unsigned int count = PAGE_SIZE/sizeof(u32);
I915_RND_STATE(prng);
struct drm_i915_private *i915 = arg;
struct i915_ggtt *ggtt = to_gt(i915)->ggtt;
struct drm_i915_gem_object *obj;
intel_wakeref_t wakeref;
struct drm_mm_node tmp;
unsigned int *order, n;
int err;
if (!i915_ggtt_has_aperture(ggtt))
return 0;
obj = i915_gem_object_create_internal(i915, PAGE_SIZE);
if (IS_ERR(obj))
return PTR_ERR(obj);
err = i915_gem_object_pin_pages_unlocked(obj);
if (err)
goto out_free;
memset(&tmp, 0, sizeof(tmp));
mutex_lock(&ggtt->vm.mutex);
err = drm_mm_insert_node_in_range(&ggtt->vm.mm, &tmp,
count * PAGE_SIZE, 0,
I915_COLOR_UNEVICTABLE,
0, ggtt->mappable_end,
DRM_MM_INSERT_LOW);
mutex_unlock(&ggtt->vm.mutex);
if (err)
goto out_unpin;
wakeref = intel_runtime_pm_get(&i915->runtime_pm);
for (n = 0; n < count; n++) {
u64 offset = tmp.start + n * PAGE_SIZE;
ggtt->vm.insert_page(&ggtt->vm,
i915_gem_object_get_dma_address(obj, 0),
offset,
i915_gem_get_pat_index(i915,
I915_CACHE_NONE),
0);
}
order = i915_random_order(count, &prng);
if (!order) {
err = -ENOMEM;
goto out_remove;
}
for (n = 0; n < count; n++) {
u64 offset = tmp.start + order[n] * PAGE_SIZE;
u32 __iomem *vaddr;
vaddr = io_mapping_map_atomic_wc(&ggtt->iomap, offset);
iowrite32(n, vaddr + n);
io_mapping_unmap_atomic(vaddr);
}
intel_gt_flush_ggtt_writes(ggtt->vm.gt);
i915_random_reorder(order, count, &prng);
for (n = 0; n < count; n++) {
u64 offset = tmp.start + order[n] * PAGE_SIZE;
u32 __iomem *vaddr;
u32 val;
vaddr = io_mapping_map_atomic_wc(&ggtt->iomap, offset);
val = ioread32(vaddr + n);
io_mapping_unmap_atomic(vaddr);
if (val != n) {
pr_err("insert page failed: found %d, expected %d\n",
val, n);
err = -EINVAL;
break;
}
}
kfree(order);
out_remove:
ggtt->vm.clear_range(&ggtt->vm, tmp.start, tmp.size);
intel_runtime_pm_put(&i915->runtime_pm, wakeref);
mutex_lock(&ggtt->vm.mutex);
drm_mm_remove_node(&tmp);
mutex_unlock(&ggtt->vm.mutex);
out_unpin:
i915_gem_object_unpin_pages(obj);
out_free:
i915_gem_object_put(obj);
return err;
}
static void track_vma_bind(struct i915_vma *vma)
{
struct drm_i915_gem_object *obj = vma->obj;
__i915_gem_object_pin_pages(obj);
GEM_BUG_ON(atomic_read(&vma->pages_count));
atomic_set(&vma->pages_count, I915_VMA_PAGES_ACTIVE);
__i915_gem_object_pin_pages(obj);
vma->pages = obj->mm.pages;
vma->resource->bi.pages = vma->pages;
mutex_lock(&vma->vm->mutex);
list_move_tail(&vma->vm_link, &vma->vm->bound_list);
mutex_unlock(&vma->vm->mutex);
}
static int exercise_mock(struct drm_i915_private *i915,
int (*func)(struct i915_address_space *vm,
u64 hole_start, u64 hole_end,
unsigned long end_time))
{
const u64 limit = totalram_pages() << PAGE_SHIFT;
struct i915_address_space *vm;
struct i915_gem_context *ctx;
IGT_TIMEOUT(end_time);
int err;
ctx = mock_context(i915, "mock");
if (!ctx)
return -ENOMEM;
vm = i915_gem_context_get_eb_vm(ctx);
err = func(vm, 0, min(vm->total, limit), end_time);
i915_vm_put(vm);
mock_context_close(ctx);
return err;
}
static int igt_mock_fill(void *arg)
{
struct i915_ggtt *ggtt = arg;
return exercise_mock(ggtt->vm.i915, fill_hole);
}
static int igt_mock_walk(void *arg)
{
struct i915_ggtt *ggtt = arg;
return exercise_mock(ggtt->vm.i915, walk_hole);
}
static int igt_mock_pot(void *arg)
{
struct i915_ggtt *ggtt = arg;
return exercise_mock(ggtt->vm.i915, pot_hole);
}
static int igt_mock_drunk(void *arg)
{
struct i915_ggtt *ggtt = arg;
return exercise_mock(ggtt->vm.i915, drunk_hole);
}
static int reserve_gtt_with_resource(struct i915_vma *vma, u64 offset)
{
struct i915_address_space *vm = vma->vm;
struct i915_vma_resource *vma_res;
struct drm_i915_gem_object *obj = vma->obj;
int err;
vma_res = i915_vma_resource_alloc();
if (IS_ERR(vma_res))
return PTR_ERR(vma_res);
mutex_lock(&vm->mutex);
err = i915_gem_gtt_reserve(vm, NULL, &vma->node, obj->base.size,
offset,
obj->pat_index,
0);
if (!err) {
i915_vma_resource_init_from_vma(vma_res, vma);
vma->resource = vma_res;
} else {
kfree(vma_res);
}
mutex_unlock(&vm->mutex);
return err;
}
static int igt_gtt_reserve(void *arg)
{
struct i915_ggtt *ggtt = arg;
struct drm_i915_gem_object *obj, *on;
I915_RND_STATE(prng);
LIST_HEAD(objects);
u64 total;
int err = -ENODEV;
/* i915_gem_gtt_reserve() tries to reserve the precise range
* for the node, and evicts if it has to. So our test checks that
* it can give us the requsted space and prevent overlaps.
*/
/* Start by filling the GGTT */
for (total = 0;
total + 2 * I915_GTT_PAGE_SIZE <= ggtt->vm.total;
total += 2 * I915_GTT_PAGE_SIZE) {
struct i915_vma *vma;
obj = i915_gem_object_create_internal(ggtt->vm.i915,
2 * PAGE_SIZE);
if (IS_ERR(obj)) {
err = PTR_ERR(obj);
goto out;
}
err = i915_gem_object_pin_pages_unlocked(obj);
if (err) {
i915_gem_object_put(obj);
goto out;
}
list_add(&obj->st_link, &objects);
vma = i915_vma_instance(obj, &ggtt->vm, NULL);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto out;
}
err = reserve_gtt_with_resource(vma, total);
if (err) {
pr_err("i915_gem_gtt_reserve (pass 1) failed at %llu/%llu with err=%d\n",
total, ggtt->vm.total, err);
goto out;
}
track_vma_bind(vma);
GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
if (vma->node.start != total ||
vma->node.size != 2*I915_GTT_PAGE_SIZE) {
pr_err("i915_gem_gtt_reserve (pass 1) placement failed, found (%llx + %llx), expected (%llx + %llx)\n",
vma->node.start, vma->node.size,
total, 2*I915_GTT_PAGE_SIZE);
err = -EINVAL;
goto out;
}
}
/* Now we start forcing evictions */
for (total = I915_GTT_PAGE_SIZE;
total + 2 * I915_GTT_PAGE_SIZE <= ggtt->vm.total;
total += 2 * I915_GTT_PAGE_SIZE) {
struct i915_vma *vma;
obj = i915_gem_object_create_internal(ggtt->vm.i915,
2 * PAGE_SIZE);
if (IS_ERR(obj)) {
err = PTR_ERR(obj);
goto out;
}
err = i915_gem_object_pin_pages_unlocked(obj);
if (err) {
i915_gem_object_put(obj);
goto out;
}
list_add(&obj->st_link, &objects);
vma = i915_vma_instance(obj, &ggtt->vm, NULL);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto out;
}
err = reserve_gtt_with_resource(vma, total);
if (err) {
pr_err("i915_gem_gtt_reserve (pass 2) failed at %llu/%llu with err=%d\n",
total, ggtt->vm.total, err);
goto out;
}
track_vma_bind(vma);
GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
if (vma->node.start != total ||
vma->node.size != 2*I915_GTT_PAGE_SIZE) {
pr_err("i915_gem_gtt_reserve (pass 2) placement failed, found (%llx + %llx), expected (%llx + %llx)\n",
vma->node.start, vma->node.size,
total, 2*I915_GTT_PAGE_SIZE);
err = -EINVAL;
goto out;
}
}
/* And then try at random */
list_for_each_entry_safe(obj, on, &objects, st_link) {
struct i915_vma *vma;
u64 offset;
vma = i915_vma_instance(obj, &ggtt->vm, NULL);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto out;
}
err = i915_vma_unbind_unlocked(vma);
if (err) {
pr_err("i915_vma_unbind failed with err=%d!\n", err);
goto out;
}
offset = igt_random_offset(&prng,
0, ggtt->vm.total,
2 * I915_GTT_PAGE_SIZE,
I915_GTT_MIN_ALIGNMENT);
err = reserve_gtt_with_resource(vma, offset);
if (err) {
pr_err("i915_gem_gtt_reserve (pass 3) failed at %llu/%llu with err=%d\n",
total, ggtt->vm.total, err);
goto out;
}
track_vma_bind(vma);
GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
if (vma->node.start != offset ||
vma->node.size != 2*I915_GTT_PAGE_SIZE) {
pr_err("i915_gem_gtt_reserve (pass 3) placement failed, found (%llx + %llx), expected (%llx + %llx)\n",
vma->node.start, vma->node.size,
offset, 2*I915_GTT_PAGE_SIZE);
err = -EINVAL;
goto out;
}
}
out:
list_for_each_entry_safe(obj, on, &objects, st_link) {
i915_gem_object_unpin_pages(obj);
i915_gem_object_put(obj);
}
return err;
}
static int insert_gtt_with_resource(struct i915_vma *vma)
{
struct i915_address_space *vm = vma->vm;
struct i915_vma_resource *vma_res;
struct drm_i915_gem_object *obj = vma->obj;
int err;
vma_res = i915_vma_resource_alloc();
if (IS_ERR(vma_res))
return PTR_ERR(vma_res);
mutex_lock(&vm->mutex);
err = i915_gem_gtt_insert(vm, NULL, &vma->node, obj->base.size, 0,
obj->pat_index, 0, vm->total, 0);
if (!err) {
i915_vma_resource_init_from_vma(vma_res, vma);
vma->resource = vma_res;
} else {
kfree(vma_res);
}
mutex_unlock(&vm->mutex);
return err;
}
static int igt_gtt_insert(void *arg)
{
struct i915_ggtt *ggtt = arg;
struct drm_i915_gem_object *obj, *on;
struct drm_mm_node tmp = {};
const struct invalid_insert {
u64 size;
u64 alignment;
u64 start, end;
} invalid_insert[] = {
{
ggtt->vm.total + I915_GTT_PAGE_SIZE, 0,
0, ggtt->vm.total,
},
{
2*I915_GTT_PAGE_SIZE, 0,
0, I915_GTT_PAGE_SIZE,
},
{
-(u64)I915_GTT_PAGE_SIZE, 0,
0, 4*I915_GTT_PAGE_SIZE,
},
{
-(u64)2*I915_GTT_PAGE_SIZE, 2*I915_GTT_PAGE_SIZE,
0, 4*I915_GTT_PAGE_SIZE,
},
{
I915_GTT_PAGE_SIZE, I915_GTT_MIN_ALIGNMENT << 1,
I915_GTT_MIN_ALIGNMENT, I915_GTT_MIN_ALIGNMENT << 1,
},
{}
}, *ii;
LIST_HEAD(objects);
u64 total;
int err = -ENODEV;
/* i915_gem_gtt_insert() tries to allocate some free space in the GTT
* to the node, evicting if required.
*/
/* Check a couple of obviously invalid requests */
for (ii = invalid_insert; ii->size; ii++) {
mutex_lock(&ggtt->vm.mutex);
err = i915_gem_gtt_insert(&ggtt->vm, NULL, &tmp,
ii->size, ii->alignment,
I915_COLOR_UNEVICTABLE,
ii->start, ii->end,
0);
mutex_unlock(&ggtt->vm.mutex);
if (err != -ENOSPC) {
pr_err("Invalid i915_gem_gtt_insert(.size=%llx, .alignment=%llx, .start=%llx, .end=%llx) succeeded (err=%d)\n",
ii->size, ii->alignment, ii->start, ii->end,
err);
return -EINVAL;
}
}
/* Start by filling the GGTT */
for (total = 0;
total + I915_GTT_PAGE_SIZE <= ggtt->vm.total;
total += I915_GTT_PAGE_SIZE) {
struct i915_vma *vma;
obj = i915_gem_object_create_internal(ggtt->vm.i915,
I915_GTT_PAGE_SIZE);
if (IS_ERR(obj)) {
err = PTR_ERR(obj);
goto out;
}
err = i915_gem_object_pin_pages_unlocked(obj);
if (err) {
i915_gem_object_put(obj);
goto out;
}
list_add(&obj->st_link, &objects);
vma = i915_vma_instance(obj, &ggtt->vm, NULL);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto out;
}
err = insert_gtt_with_resource(vma);
if (err == -ENOSPC) {
/* maxed out the GGTT space */
i915_gem_object_put(obj);
break;
}
if (err) {
pr_err("i915_gem_gtt_insert (pass 1) failed at %llu/%llu with err=%d\n",
total, ggtt->vm.total, err);
goto out;
}
track_vma_bind(vma);
__i915_vma_pin(vma);
GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
}
list_for_each_entry(obj, &objects, st_link) {
struct i915_vma *vma;
vma = i915_vma_instance(obj, &ggtt->vm, NULL);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto out;
}
if (!drm_mm_node_allocated(&vma->node)) {
pr_err("VMA was unexpectedly evicted!\n");
err = -EINVAL;
goto out;
}
__i915_vma_unpin(vma);
}
/* If we then reinsert, we should find the same hole */
list_for_each_entry_safe(obj, on, &objects, st_link) {
struct i915_vma *vma;
u64 offset;
vma = i915_vma_instance(obj, &ggtt->vm, NULL);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto out;
}
GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
offset = vma->node.start;
err = i915_vma_unbind_unlocked(vma);
if (err) {
pr_err("i915_vma_unbind failed with err=%d!\n", err);
goto out;
}
err = insert_gtt_with_resource(vma);
if (err) {
pr_err("i915_gem_gtt_insert (pass 2) failed at %llu/%llu with err=%d\n",
total, ggtt->vm.total, err);
goto out;
}
track_vma_bind(vma);
GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
if (vma->node.start != offset) {
pr_err("i915_gem_gtt_insert did not return node to its previous location (the only hole), expected address %llx, found %llx\n",
offset, vma->node.start);
err = -EINVAL;
goto out;
}
}
/* And then force evictions */
for (total = 0;
total + 2 * I915_GTT_PAGE_SIZE <= ggtt->vm.total;
total += 2 * I915_GTT_PAGE_SIZE) {
struct i915_vma *vma;
obj = i915_gem_object_create_internal(ggtt->vm.i915,
2 * I915_GTT_PAGE_SIZE);
if (IS_ERR(obj)) {
err = PTR_ERR(obj);
goto out;
}
err = i915_gem_object_pin_pages_unlocked(obj);
if (err) {
i915_gem_object_put(obj);
goto out;
}
list_add(&obj->st_link, &objects);
vma = i915_vma_instance(obj, &ggtt->vm, NULL);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto out;
}
err = insert_gtt_with_resource(vma);
if (err) {
pr_err("i915_gem_gtt_insert (pass 3) failed at %llu/%llu with err=%d\n",
total, ggtt->vm.total, err);
goto out;
}
track_vma_bind(vma);
GEM_BUG_ON(!drm_mm_node_allocated(&vma->node));
}
out:
list_for_each_entry_safe(obj, on, &objects, st_link) {
i915_gem_object_unpin_pages(obj);
i915_gem_object_put(obj);
}
return err;
}
int i915_gem_gtt_mock_selftests(void)
{
static const struct i915_subtest tests[] = {
SUBTEST(igt_mock_drunk),
SUBTEST(igt_mock_walk),
SUBTEST(igt_mock_pot),
SUBTEST(igt_mock_fill),
SUBTEST(igt_gtt_reserve),
SUBTEST(igt_gtt_insert),
};
struct drm_i915_private *i915;
struct intel_gt *gt;
int err;
i915 = mock_gem_device();
if (!i915)
return -ENOMEM;
/* allocate the ggtt */
err = intel_gt_assign_ggtt(to_gt(i915));
if (err)
goto out_put;
gt = to_gt(i915);
mock_init_ggtt(gt);
err = i915_subtests(tests, gt->ggtt);
mock_device_flush(i915);
i915_gem_drain_freed_objects(i915);
mock_fini_ggtt(gt->ggtt);
out_put:
mock_destroy_device(i915);
return err;
}
int i915_gem_gtt_live_selftests(struct drm_i915_private *i915)
{
static const struct i915_subtest tests[] = {
SUBTEST(igt_ppgtt_alloc),
SUBTEST(igt_ppgtt_lowlevel),
SUBTEST(igt_ppgtt_drunk),
SUBTEST(igt_ppgtt_walk),
SUBTEST(igt_ppgtt_pot),
SUBTEST(igt_ppgtt_fill),
SUBTEST(igt_ppgtt_shrink),
SUBTEST(igt_ppgtt_shrink_boom),
SUBTEST(igt_ppgtt_misaligned_pin),
SUBTEST(igt_ggtt_lowlevel),
SUBTEST(igt_ggtt_drunk),
SUBTEST(igt_ggtt_walk),
SUBTEST(igt_ggtt_pot),
SUBTEST(igt_ggtt_fill),
SUBTEST(igt_ggtt_page),
SUBTEST(igt_ggtt_misaligned_pin),
};
GEM_BUG_ON(offset_in_page(to_gt(i915)->ggtt->vm.total));
return i915_live_subtests(tests, i915);
}
| linux-master | drivers/gpu/drm/i915/selftests/i915_gem_gtt.c |
/*
* Copyright © 2016 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
#include <linux/pm_domain.h>
#include <linux/pm_runtime.h>
#include <linux/iommu.h>
#include <drm/drm_managed.h>
#include "gt/intel_gt.h"
#include "gt/intel_gt_requests.h"
#include "gt/mock_engine.h"
#include "intel_memory_region.h"
#include "intel_region_ttm.h"
#include "mock_request.h"
#include "mock_gem_device.h"
#include "mock_gtt.h"
#include "mock_uncore.h"
#include "mock_region.h"
#include "gem/selftests/mock_context.h"
#include "gem/selftests/mock_gem_object.h"
void mock_device_flush(struct drm_i915_private *i915)
{
struct intel_gt *gt = to_gt(i915);
struct intel_engine_cs *engine;
enum intel_engine_id id;
do {
for_each_engine(engine, gt, id)
mock_engine_flush(engine);
} while (intel_gt_retire_requests_timeout(gt, MAX_SCHEDULE_TIMEOUT,
NULL));
}
static void mock_device_release(struct drm_device *dev)
{
struct drm_i915_private *i915 = to_i915(dev);
if (!i915->do_release)
goto out;
mock_device_flush(i915);
intel_gt_driver_remove(to_gt(i915));
i915_gem_drain_workqueue(i915);
mock_fini_ggtt(to_gt(i915)->ggtt);
destroy_workqueue(i915->unordered_wq);
destroy_workqueue(i915->wq);
intel_region_ttm_device_fini(i915);
intel_gt_driver_late_release_all(i915);
intel_memory_regions_driver_release(i915);
drm_mode_config_cleanup(&i915->drm);
out:
i915_params_free(&i915->params);
}
static const struct drm_driver mock_driver = {
.name = "mock",
.driver_features = DRIVER_GEM,
.release = mock_device_release,
};
static void release_dev(struct device *dev)
{
struct pci_dev *pdev = to_pci_dev(dev);
kfree(pdev);
}
static int pm_domain_resume(struct device *dev)
{
return pm_generic_runtime_resume(dev);
}
static int pm_domain_suspend(struct device *dev)
{
return pm_generic_runtime_suspend(dev);
}
static struct dev_pm_domain pm_domain = {
.ops = {
.runtime_suspend = pm_domain_suspend,
.runtime_resume = pm_domain_resume,
},
};
static void mock_gt_probe(struct drm_i915_private *i915)
{
i915->gt[0] = to_gt(i915);
i915->gt[0]->name = "Mock GT";
}
static const struct intel_device_info mock_info = {
.__runtime.graphics.ip.ver = -1,
.__runtime.page_sizes = (I915_GTT_PAGE_SIZE_4K |
I915_GTT_PAGE_SIZE_64K |
I915_GTT_PAGE_SIZE_2M),
.memory_regions = REGION_SMEM,
.platform_engine_mask = BIT(0),
/* simply use legacy cache level for mock device */
.max_pat_index = 3,
.cachelevel_to_pat = {
[I915_CACHE_NONE] = 0,
[I915_CACHE_LLC] = 1,
[I915_CACHE_L3_LLC] = 2,
[I915_CACHE_WT] = 3,
},
};
struct drm_i915_private *mock_gem_device(void)
{
#if IS_ENABLED(CONFIG_IOMMU_API) && defined(CONFIG_INTEL_IOMMU)
static struct dev_iommu fake_iommu = { .priv = (void *)-1 };
#endif
struct drm_i915_private *i915;
struct pci_dev *pdev;
int ret;
pdev = kzalloc(sizeof(*pdev), GFP_KERNEL);
if (!pdev)
return NULL;
device_initialize(&pdev->dev);
pdev->class = PCI_BASE_CLASS_DISPLAY << 16;
pdev->dev.release = release_dev;
dev_set_name(&pdev->dev, "mock");
dma_coerce_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
#if IS_ENABLED(CONFIG_IOMMU_API) && defined(CONFIG_INTEL_IOMMU)
/* HACK to disable iommu for the fake device; force identity mapping */
pdev->dev.iommu = &fake_iommu;
#endif
if (!devres_open_group(&pdev->dev, NULL, GFP_KERNEL)) {
put_device(&pdev->dev);
return NULL;
}
i915 = devm_drm_dev_alloc(&pdev->dev, &mock_driver,
struct drm_i915_private, drm);
if (IS_ERR(i915)) {
pr_err("Failed to allocate mock GEM device: err=%ld\n", PTR_ERR(i915));
devres_release_group(&pdev->dev, NULL);
put_device(&pdev->dev);
return NULL;
}
pci_set_drvdata(pdev, i915);
/* Device parameters start as a copy of module parameters. */
i915_params_copy(&i915->params, &i915_modparams);
/* Set up device info and initial runtime info. */
intel_device_info_driver_create(i915, pdev->device, &mock_info);
dev_pm_domain_set(&pdev->dev, &pm_domain);
pm_runtime_enable(&pdev->dev);
pm_runtime_dont_use_autosuspend(&pdev->dev);
if (pm_runtime_enabled(&pdev->dev))
WARN_ON(pm_runtime_get_sync(&pdev->dev));
intel_runtime_pm_init_early(&i915->runtime_pm);
/* wakeref tracking has significant overhead */
i915->runtime_pm.no_wakeref_tracking = true;
/* Using the global GTT may ask questions about KMS users, so prepare */
drm_mode_config_init(&i915->drm);
intel_memory_regions_hw_probe(i915);
spin_lock_init(&i915->gpu_error.lock);
i915_gem_init__mm(i915);
intel_root_gt_init_early(i915);
mock_uncore_init(&i915->uncore, i915);
atomic_inc(&to_gt(i915)->wakeref.count); /* disable; no hw support */
to_gt(i915)->awake = -ENODEV;
mock_gt_probe(i915);
ret = intel_region_ttm_device_init(i915);
if (ret)
goto err_ttm;
i915->wq = alloc_ordered_workqueue("mock", 0);
if (!i915->wq)
goto err_drv;
i915->unordered_wq = alloc_workqueue("mock-unordered", 0, 0);
if (!i915->unordered_wq)
goto err_wq;
mock_init_contexts(i915);
/* allocate the ggtt */
ret = intel_gt_assign_ggtt(to_gt(i915));
if (ret)
goto err_unlock;
mock_init_ggtt(to_gt(i915));
to_gt(i915)->vm = i915_vm_get(&to_gt(i915)->ggtt->vm);
to_gt(i915)->info.engine_mask = BIT(0);
to_gt(i915)->engine[RCS0] = mock_engine(i915, "mock", RCS0);
if (!to_gt(i915)->engine[RCS0])
goto err_unlock;
if (mock_engine_init(to_gt(i915)->engine[RCS0]))
goto err_context;
__clear_bit(I915_WEDGED, &to_gt(i915)->reset.flags);
intel_engines_driver_register(i915);
i915->do_release = true;
ida_init(&i915->selftest.mock_region_instances);
return i915;
err_context:
intel_gt_driver_remove(to_gt(i915));
err_unlock:
destroy_workqueue(i915->unordered_wq);
err_wq:
destroy_workqueue(i915->wq);
err_drv:
intel_region_ttm_device_fini(i915);
err_ttm:
intel_gt_driver_late_release_all(i915);
intel_memory_regions_driver_release(i915);
drm_mode_config_cleanup(&i915->drm);
mock_destroy_device(i915);
return NULL;
}
void mock_destroy_device(struct drm_i915_private *i915)
{
struct device *dev = i915->drm.dev;
devres_release_group(dev, NULL);
put_device(dev);
}
| linux-master | drivers/gpu/drm/i915/selftests/mock_gem_device.c |
/*
* SPDX-License-Identifier: MIT
*
* Copyright © 2018 Intel Corporation
*/
#include "gt/intel_gpu_commands.h"
#include "gt/intel_gt.h"
#include "gem/i915_gem_internal.h"
#include "gem/selftests/igt_gem_utils.h"
#include "igt_spinner.h"
int igt_spinner_init(struct igt_spinner *spin, struct intel_gt *gt)
{
int err;
memset(spin, 0, sizeof(*spin));
spin->gt = gt;
spin->hws = i915_gem_object_create_internal(gt->i915, PAGE_SIZE);
if (IS_ERR(spin->hws)) {
err = PTR_ERR(spin->hws);
goto err;
}
i915_gem_object_set_cache_coherency(spin->hws, I915_CACHE_LLC);
spin->obj = i915_gem_object_create_internal(gt->i915, PAGE_SIZE);
if (IS_ERR(spin->obj)) {
err = PTR_ERR(spin->obj);
goto err_hws;
}
return 0;
err_hws:
i915_gem_object_put(spin->hws);
err:
return err;
}
static void *igt_spinner_pin_obj(struct intel_context *ce,
struct i915_gem_ww_ctx *ww,
struct drm_i915_gem_object *obj,
unsigned int mode, struct i915_vma **vma)
{
void *vaddr;
int ret;
*vma = i915_vma_instance(obj, ce->vm, NULL);
if (IS_ERR(*vma))
return ERR_CAST(*vma);
ret = i915_gem_object_lock(obj, ww);
if (ret)
return ERR_PTR(ret);
vaddr = i915_gem_object_pin_map(obj, mode);
if (!ww)
i915_gem_object_unlock(obj);
if (IS_ERR(vaddr))
return vaddr;
if (ww)
ret = i915_vma_pin_ww(*vma, ww, 0, 0, PIN_USER);
else
ret = i915_vma_pin(*vma, 0, 0, PIN_USER);
if (ret) {
i915_gem_object_unpin_map(obj);
return ERR_PTR(ret);
}
return vaddr;
}
int igt_spinner_pin(struct igt_spinner *spin,
struct intel_context *ce,
struct i915_gem_ww_ctx *ww)
{
void *vaddr;
if (spin->ce && WARN_ON(spin->ce != ce))
return -ENODEV;
spin->ce = ce;
if (!spin->seqno) {
vaddr = igt_spinner_pin_obj(ce, ww, spin->hws, I915_MAP_WB, &spin->hws_vma);
if (IS_ERR(vaddr))
return PTR_ERR(vaddr);
spin->seqno = memset(vaddr, 0xff, PAGE_SIZE);
}
if (!spin->batch) {
unsigned int mode;
mode = intel_gt_coherent_map_type(spin->gt, spin->obj, false);
vaddr = igt_spinner_pin_obj(ce, ww, spin->obj, mode, &spin->batch_vma);
if (IS_ERR(vaddr))
return PTR_ERR(vaddr);
spin->batch = vaddr;
}
return 0;
}
static unsigned int seqno_offset(u64 fence)
{
return offset_in_page(sizeof(u32) * fence);
}
static u64 hws_address(const struct i915_vma *hws,
const struct i915_request *rq)
{
return i915_vma_offset(hws) + seqno_offset(rq->fence.context);
}
struct i915_request *
igt_spinner_create_request(struct igt_spinner *spin,
struct intel_context *ce,
u32 arbitration_command)
{
struct intel_engine_cs *engine = ce->engine;
struct i915_request *rq = NULL;
struct i915_vma *hws, *vma;
unsigned int flags;
u32 *batch;
int err;
GEM_BUG_ON(spin->gt != ce->vm->gt);
if (!intel_engine_can_store_dword(ce->engine))
return ERR_PTR(-ENODEV);
if (!spin->batch) {
err = igt_spinner_pin(spin, ce, NULL);
if (err)
return ERR_PTR(err);
}
hws = spin->hws_vma;
vma = spin->batch_vma;
rq = intel_context_create_request(ce);
if (IS_ERR(rq))
return ERR_CAST(rq);
err = igt_vma_move_to_active_unlocked(vma, rq, 0);
if (err)
goto cancel_rq;
err = igt_vma_move_to_active_unlocked(hws, rq, 0);
if (err)
goto cancel_rq;
batch = spin->batch;
if (GRAPHICS_VER(rq->i915) >= 8) {
*batch++ = MI_STORE_DWORD_IMM_GEN4;
*batch++ = lower_32_bits(hws_address(hws, rq));
*batch++ = upper_32_bits(hws_address(hws, rq));
} else if (GRAPHICS_VER(rq->i915) >= 6) {
*batch++ = MI_STORE_DWORD_IMM_GEN4;
*batch++ = 0;
*batch++ = hws_address(hws, rq);
} else if (GRAPHICS_VER(rq->i915) >= 4) {
*batch++ = MI_STORE_DWORD_IMM_GEN4 | MI_USE_GGTT;
*batch++ = 0;
*batch++ = hws_address(hws, rq);
} else {
*batch++ = MI_STORE_DWORD_IMM | MI_MEM_VIRTUAL;
*batch++ = hws_address(hws, rq);
}
*batch++ = rq->fence.seqno;
*batch++ = arbitration_command;
if (GRAPHICS_VER(rq->i915) >= 8)
*batch++ = MI_BATCH_BUFFER_START | BIT(8) | 1;
else if (IS_HASWELL(rq->i915))
*batch++ = MI_BATCH_BUFFER_START | MI_BATCH_PPGTT_HSW;
else if (GRAPHICS_VER(rq->i915) >= 6)
*batch++ = MI_BATCH_BUFFER_START;
else
*batch++ = MI_BATCH_BUFFER_START | MI_BATCH_GTT;
*batch++ = lower_32_bits(i915_vma_offset(vma));
*batch++ = upper_32_bits(i915_vma_offset(vma));
*batch++ = MI_BATCH_BUFFER_END; /* not reached */
intel_gt_chipset_flush(engine->gt);
if (engine->emit_init_breadcrumb) {
err = engine->emit_init_breadcrumb(rq);
if (err)
goto cancel_rq;
}
flags = 0;
if (GRAPHICS_VER(rq->i915) <= 5)
flags |= I915_DISPATCH_SECURE;
err = engine->emit_bb_start(rq, i915_vma_offset(vma), PAGE_SIZE, flags);
cancel_rq:
if (err) {
i915_request_set_error_once(rq, err);
i915_request_add(rq);
}
return err ? ERR_PTR(err) : rq;
}
static u32
hws_seqno(const struct igt_spinner *spin, const struct i915_request *rq)
{
u32 *seqno = spin->seqno + seqno_offset(rq->fence.context);
return READ_ONCE(*seqno);
}
void igt_spinner_end(struct igt_spinner *spin)
{
if (!spin->batch)
return;
*spin->batch = MI_BATCH_BUFFER_END;
intel_gt_chipset_flush(spin->gt);
}
void igt_spinner_fini(struct igt_spinner *spin)
{
igt_spinner_end(spin);
if (spin->batch) {
i915_vma_unpin(spin->batch_vma);
i915_gem_object_unpin_map(spin->obj);
}
i915_gem_object_put(spin->obj);
if (spin->seqno) {
i915_vma_unpin(spin->hws_vma);
i915_gem_object_unpin_map(spin->hws);
}
i915_gem_object_put(spin->hws);
}
bool igt_wait_for_spinner(struct igt_spinner *spin, struct i915_request *rq)
{
if (i915_request_is_ready(rq))
intel_engine_flush_submission(rq->engine);
return !(wait_for_us(i915_seqno_passed(hws_seqno(spin, rq),
rq->fence.seqno),
100) &&
wait_for(i915_seqno_passed(hws_seqno(spin, rq),
rq->fence.seqno),
50));
}
| linux-master | drivers/gpu/drm/i915/selftests/igt_spinner.c |
/*
* Copyright © 2016 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
#include <linux/prime_numbers.h>
#include <linux/pm_qos.h>
#include <linux/sort.h>
#include "gem/i915_gem_internal.h"
#include "gem/i915_gem_pm.h"
#include "gem/selftests/mock_context.h"
#include "gt/intel_engine_heartbeat.h"
#include "gt/intel_engine_pm.h"
#include "gt/intel_engine_user.h"
#include "gt/intel_gt.h"
#include "gt/intel_gt_clock_utils.h"
#include "gt/intel_gt_requests.h"
#include "gt/selftest_engine_heartbeat.h"
#include "i915_random.h"
#include "i915_selftest.h"
#include "igt_flush_test.h"
#include "igt_live_test.h"
#include "igt_spinner.h"
#include "lib_sw_fence.h"
#include "mock_drm.h"
#include "mock_gem_device.h"
static unsigned int num_uabi_engines(struct drm_i915_private *i915)
{
struct intel_engine_cs *engine;
unsigned int count;
count = 0;
for_each_uabi_engine(engine, i915)
count++;
return count;
}
static struct intel_engine_cs *rcs0(struct drm_i915_private *i915)
{
return intel_engine_lookup_user(i915, I915_ENGINE_CLASS_RENDER, 0);
}
static int igt_add_request(void *arg)
{
struct drm_i915_private *i915 = arg;
struct i915_request *request;
/* Basic preliminary test to create a request and let it loose! */
request = mock_request(rcs0(i915)->kernel_context, HZ / 10);
if (!request)
return -ENOMEM;
i915_request_add(request);
return 0;
}
static int igt_wait_request(void *arg)
{
const long T = HZ / 4;
struct drm_i915_private *i915 = arg;
struct i915_request *request;
int err = -EINVAL;
/* Submit a request, then wait upon it */
request = mock_request(rcs0(i915)->kernel_context, T);
if (!request)
return -ENOMEM;
i915_request_get(request);
if (i915_request_wait(request, 0, 0) != -ETIME) {
pr_err("request wait (busy query) succeeded (expected timeout before submit!)\n");
goto out_request;
}
if (i915_request_wait(request, 0, T) != -ETIME) {
pr_err("request wait succeeded (expected timeout before submit!)\n");
goto out_request;
}
if (i915_request_completed(request)) {
pr_err("request completed before submit!!\n");
goto out_request;
}
i915_request_add(request);
if (i915_request_wait(request, 0, 0) != -ETIME) {
pr_err("request wait (busy query) succeeded (expected timeout after submit!)\n");
goto out_request;
}
if (i915_request_completed(request)) {
pr_err("request completed immediately!\n");
goto out_request;
}
if (i915_request_wait(request, 0, T / 2) != -ETIME) {
pr_err("request wait succeeded (expected timeout!)\n");
goto out_request;
}
if (i915_request_wait(request, 0, T) == -ETIME) {
pr_err("request wait timed out!\n");
goto out_request;
}
if (!i915_request_completed(request)) {
pr_err("request not complete after waiting!\n");
goto out_request;
}
if (i915_request_wait(request, 0, T) == -ETIME) {
pr_err("request wait timed out when already complete!\n");
goto out_request;
}
err = 0;
out_request:
i915_request_put(request);
mock_device_flush(i915);
return err;
}
static int igt_fence_wait(void *arg)
{
const long T = HZ / 4;
struct drm_i915_private *i915 = arg;
struct i915_request *request;
int err = -EINVAL;
/* Submit a request, treat it as a fence and wait upon it */
request = mock_request(rcs0(i915)->kernel_context, T);
if (!request)
return -ENOMEM;
if (dma_fence_wait_timeout(&request->fence, false, T) != -ETIME) {
pr_err("fence wait success before submit (expected timeout)!\n");
goto out;
}
i915_request_add(request);
if (dma_fence_is_signaled(&request->fence)) {
pr_err("fence signaled immediately!\n");
goto out;
}
if (dma_fence_wait_timeout(&request->fence, false, T / 2) != -ETIME) {
pr_err("fence wait success after submit (expected timeout)!\n");
goto out;
}
if (dma_fence_wait_timeout(&request->fence, false, T) <= 0) {
pr_err("fence wait timed out (expected success)!\n");
goto out;
}
if (!dma_fence_is_signaled(&request->fence)) {
pr_err("fence unsignaled after waiting!\n");
goto out;
}
if (dma_fence_wait_timeout(&request->fence, false, T) <= 0) {
pr_err("fence wait timed out when complete (expected success)!\n");
goto out;
}
err = 0;
out:
mock_device_flush(i915);
return err;
}
static int igt_request_rewind(void *arg)
{
struct drm_i915_private *i915 = arg;
struct i915_request *request, *vip;
struct i915_gem_context *ctx[2];
struct intel_context *ce;
int err = -EINVAL;
ctx[0] = mock_context(i915, "A");
if (!ctx[0]) {
err = -ENOMEM;
goto err_ctx_0;
}
ce = i915_gem_context_get_engine(ctx[0], RCS0);
GEM_BUG_ON(IS_ERR(ce));
request = mock_request(ce, 2 * HZ);
intel_context_put(ce);
if (!request) {
err = -ENOMEM;
goto err_context_0;
}
i915_request_get(request);
i915_request_add(request);
ctx[1] = mock_context(i915, "B");
if (!ctx[1]) {
err = -ENOMEM;
goto err_ctx_1;
}
ce = i915_gem_context_get_engine(ctx[1], RCS0);
GEM_BUG_ON(IS_ERR(ce));
vip = mock_request(ce, 0);
intel_context_put(ce);
if (!vip) {
err = -ENOMEM;
goto err_context_1;
}
/* Simulate preemption by manual reordering */
if (!mock_cancel_request(request)) {
pr_err("failed to cancel request (already executed)!\n");
i915_request_add(vip);
goto err_context_1;
}
i915_request_get(vip);
i915_request_add(vip);
rcu_read_lock();
request->engine->submit_request(request);
rcu_read_unlock();
if (i915_request_wait(vip, 0, HZ) == -ETIME) {
pr_err("timed out waiting for high priority request\n");
goto err;
}
if (i915_request_completed(request)) {
pr_err("low priority request already completed\n");
goto err;
}
err = 0;
err:
i915_request_put(vip);
err_context_1:
mock_context_close(ctx[1]);
err_ctx_1:
i915_request_put(request);
err_context_0:
mock_context_close(ctx[0]);
err_ctx_0:
mock_device_flush(i915);
return err;
}
struct smoketest {
struct intel_engine_cs *engine;
struct i915_gem_context **contexts;
atomic_long_t num_waits, num_fences;
int ncontexts, max_batch;
struct i915_request *(*request_alloc)(struct intel_context *ce);
};
static struct i915_request *
__mock_request_alloc(struct intel_context *ce)
{
return mock_request(ce, 0);
}
static struct i915_request *
__live_request_alloc(struct intel_context *ce)
{
return intel_context_create_request(ce);
}
struct smoke_thread {
struct kthread_worker *worker;
struct kthread_work work;
struct smoketest *t;
bool stop;
int result;
};
static void __igt_breadcrumbs_smoketest(struct kthread_work *work)
{
struct smoke_thread *thread = container_of(work, typeof(*thread), work);
struct smoketest *t = thread->t;
const unsigned int max_batch = min(t->ncontexts, t->max_batch) - 1;
const unsigned int total = 4 * t->ncontexts + 1;
unsigned int num_waits = 0, num_fences = 0;
struct i915_request **requests;
I915_RND_STATE(prng);
unsigned int *order;
int err = 0;
/*
* A very simple test to catch the most egregious of list handling bugs.
*
* At its heart, we simply create oodles of requests running across
* multiple kthreads and enable signaling on them, for the sole purpose
* of stressing our breadcrumb handling. The only inspection we do is
* that the fences were marked as signaled.
*/
requests = kcalloc(total, sizeof(*requests), GFP_KERNEL);
if (!requests) {
thread->result = -ENOMEM;
return;
}
order = i915_random_order(total, &prng);
if (!order) {
err = -ENOMEM;
goto out_requests;
}
while (!READ_ONCE(thread->stop)) {
struct i915_sw_fence *submit, *wait;
unsigned int n, count;
submit = heap_fence_create(GFP_KERNEL);
if (!submit) {
err = -ENOMEM;
break;
}
wait = heap_fence_create(GFP_KERNEL);
if (!wait) {
i915_sw_fence_commit(submit);
heap_fence_put(submit);
err = -ENOMEM;
break;
}
i915_random_reorder(order, total, &prng);
count = 1 + i915_prandom_u32_max_state(max_batch, &prng);
for (n = 0; n < count; n++) {
struct i915_gem_context *ctx =
t->contexts[order[n] % t->ncontexts];
struct i915_request *rq;
struct intel_context *ce;
ce = i915_gem_context_get_engine(ctx, t->engine->legacy_idx);
GEM_BUG_ON(IS_ERR(ce));
rq = t->request_alloc(ce);
intel_context_put(ce);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
count = n;
break;
}
err = i915_sw_fence_await_sw_fence_gfp(&rq->submit,
submit,
GFP_KERNEL);
requests[n] = i915_request_get(rq);
i915_request_add(rq);
if (err >= 0)
err = i915_sw_fence_await_dma_fence(wait,
&rq->fence,
0,
GFP_KERNEL);
if (err < 0) {
i915_request_put(rq);
count = n;
break;
}
}
i915_sw_fence_commit(submit);
i915_sw_fence_commit(wait);
if (!wait_event_timeout(wait->wait,
i915_sw_fence_done(wait),
5 * HZ)) {
struct i915_request *rq = requests[count - 1];
pr_err("waiting for %d/%d fences (last %llx:%lld) on %s timed out!\n",
atomic_read(&wait->pending), count,
rq->fence.context, rq->fence.seqno,
t->engine->name);
GEM_TRACE_DUMP();
intel_gt_set_wedged(t->engine->gt);
GEM_BUG_ON(!i915_request_completed(rq));
i915_sw_fence_wait(wait);
err = -EIO;
}
for (n = 0; n < count; n++) {
struct i915_request *rq = requests[n];
if (!test_bit(DMA_FENCE_FLAG_SIGNALED_BIT,
&rq->fence.flags)) {
pr_err("%llu:%llu was not signaled!\n",
rq->fence.context, rq->fence.seqno);
err = -EINVAL;
}
i915_request_put(rq);
}
heap_fence_put(wait);
heap_fence_put(submit);
if (err < 0)
break;
num_fences += count;
num_waits++;
cond_resched();
}
atomic_long_add(num_fences, &t->num_fences);
atomic_long_add(num_waits, &t->num_waits);
kfree(order);
out_requests:
kfree(requests);
thread->result = err;
}
static int mock_breadcrumbs_smoketest(void *arg)
{
struct drm_i915_private *i915 = arg;
struct smoketest t = {
.engine = rcs0(i915),
.ncontexts = 1024,
.max_batch = 1024,
.request_alloc = __mock_request_alloc
};
unsigned int ncpus = num_online_cpus();
struct smoke_thread *threads;
unsigned int n;
int ret = 0;
/*
* Smoketest our breadcrumb/signal handling for requests across multiple
* threads. A very simple test to only catch the most egregious of bugs.
* See __igt_breadcrumbs_smoketest();
*/
threads = kcalloc(ncpus, sizeof(*threads), GFP_KERNEL);
if (!threads)
return -ENOMEM;
t.contexts = kcalloc(t.ncontexts, sizeof(*t.contexts), GFP_KERNEL);
if (!t.contexts) {
ret = -ENOMEM;
goto out_threads;
}
for (n = 0; n < t.ncontexts; n++) {
t.contexts[n] = mock_context(t.engine->i915, "mock");
if (!t.contexts[n]) {
ret = -ENOMEM;
goto out_contexts;
}
}
for (n = 0; n < ncpus; n++) {
struct kthread_worker *worker;
worker = kthread_create_worker(0, "igt/%d", n);
if (IS_ERR(worker)) {
ret = PTR_ERR(worker);
ncpus = n;
break;
}
threads[n].worker = worker;
threads[n].t = &t;
threads[n].stop = false;
threads[n].result = 0;
kthread_init_work(&threads[n].work,
__igt_breadcrumbs_smoketest);
kthread_queue_work(worker, &threads[n].work);
}
msleep(jiffies_to_msecs(i915_selftest.timeout_jiffies));
for (n = 0; n < ncpus; n++) {
int err;
WRITE_ONCE(threads[n].stop, true);
kthread_flush_work(&threads[n].work);
err = READ_ONCE(threads[n].result);
if (err < 0 && !ret)
ret = err;
kthread_destroy_worker(threads[n].worker);
}
pr_info("Completed %lu waits for %lu fence across %d cpus\n",
atomic_long_read(&t.num_waits),
atomic_long_read(&t.num_fences),
ncpus);
out_contexts:
for (n = 0; n < t.ncontexts; n++) {
if (!t.contexts[n])
break;
mock_context_close(t.contexts[n]);
}
kfree(t.contexts);
out_threads:
kfree(threads);
return ret;
}
int i915_request_mock_selftests(void)
{
static const struct i915_subtest tests[] = {
SUBTEST(igt_add_request),
SUBTEST(igt_wait_request),
SUBTEST(igt_fence_wait),
SUBTEST(igt_request_rewind),
SUBTEST(mock_breadcrumbs_smoketest),
};
struct drm_i915_private *i915;
intel_wakeref_t wakeref;
int err = 0;
i915 = mock_gem_device();
if (!i915)
return -ENOMEM;
with_intel_runtime_pm(&i915->runtime_pm, wakeref)
err = i915_subtests(tests, i915);
mock_destroy_device(i915);
return err;
}
static int live_nop_request(void *arg)
{
struct drm_i915_private *i915 = arg;
struct intel_engine_cs *engine;
struct igt_live_test t;
int err = -ENODEV;
/*
* Submit various sized batches of empty requests, to each engine
* (individually), and wait for the batch to complete. We can check
* the overhead of submitting requests to the hardware.
*/
for_each_uabi_engine(engine, i915) {
unsigned long n, prime;
IGT_TIMEOUT(end_time);
ktime_t times[2] = {};
err = igt_live_test_begin(&t, i915, __func__, engine->name);
if (err)
return err;
intel_engine_pm_get(engine);
for_each_prime_number_from(prime, 1, 8192) {
struct i915_request *request = NULL;
times[1] = ktime_get_raw();
for (n = 0; n < prime; n++) {
i915_request_put(request);
request = i915_request_create(engine->kernel_context);
if (IS_ERR(request))
return PTR_ERR(request);
/*
* This space is left intentionally blank.
*
* We do not actually want to perform any
* action with this request, we just want
* to measure the latency in allocation
* and submission of our breadcrumbs -
* ensuring that the bare request is sufficient
* for the system to work (i.e. proper HEAD
* tracking of the rings, interrupt handling,
* etc). It also gives us the lowest bounds
* for latency.
*/
i915_request_get(request);
i915_request_add(request);
}
i915_request_wait(request, 0, MAX_SCHEDULE_TIMEOUT);
i915_request_put(request);
times[1] = ktime_sub(ktime_get_raw(), times[1]);
if (prime == 1)
times[0] = times[1];
if (__igt_timeout(end_time, NULL))
break;
}
intel_engine_pm_put(engine);
err = igt_live_test_end(&t);
if (err)
return err;
pr_info("Request latencies on %s: 1 = %lluns, %lu = %lluns\n",
engine->name,
ktime_to_ns(times[0]),
prime, div64_u64(ktime_to_ns(times[1]), prime));
}
return err;
}
static int __cancel_inactive(struct intel_engine_cs *engine)
{
struct intel_context *ce;
struct igt_spinner spin;
struct i915_request *rq;
int err = 0;
if (igt_spinner_init(&spin, engine->gt))
return -ENOMEM;
ce = intel_context_create(engine);
if (IS_ERR(ce)) {
err = PTR_ERR(ce);
goto out_spin;
}
rq = igt_spinner_create_request(&spin, ce, MI_ARB_CHECK);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
goto out_ce;
}
pr_debug("%s: Cancelling inactive request\n", engine->name);
i915_request_cancel(rq, -EINTR);
i915_request_get(rq);
i915_request_add(rq);
if (i915_request_wait(rq, 0, HZ / 5) < 0) {
struct drm_printer p = drm_info_printer(engine->i915->drm.dev);
pr_err("%s: Failed to cancel inactive request\n", engine->name);
intel_engine_dump(engine, &p, "%s\n", engine->name);
err = -ETIME;
goto out_rq;
}
if (rq->fence.error != -EINTR) {
pr_err("%s: fence not cancelled (%u)\n",
engine->name, rq->fence.error);
err = -EINVAL;
}
out_rq:
i915_request_put(rq);
out_ce:
intel_context_put(ce);
out_spin:
igt_spinner_fini(&spin);
if (err)
pr_err("%s: %s error %d\n", __func__, engine->name, err);
return err;
}
static int __cancel_active(struct intel_engine_cs *engine)
{
struct intel_context *ce;
struct igt_spinner spin;
struct i915_request *rq;
int err = 0;
if (igt_spinner_init(&spin, engine->gt))
return -ENOMEM;
ce = intel_context_create(engine);
if (IS_ERR(ce)) {
err = PTR_ERR(ce);
goto out_spin;
}
rq = igt_spinner_create_request(&spin, ce, MI_ARB_CHECK);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
goto out_ce;
}
pr_debug("%s: Cancelling active request\n", engine->name);
i915_request_get(rq);
i915_request_add(rq);
if (!igt_wait_for_spinner(&spin, rq)) {
struct drm_printer p = drm_info_printer(engine->i915->drm.dev);
pr_err("Failed to start spinner on %s\n", engine->name);
intel_engine_dump(engine, &p, "%s\n", engine->name);
err = -ETIME;
goto out_rq;
}
i915_request_cancel(rq, -EINTR);
if (i915_request_wait(rq, 0, HZ / 5) < 0) {
struct drm_printer p = drm_info_printer(engine->i915->drm.dev);
pr_err("%s: Failed to cancel active request\n", engine->name);
intel_engine_dump(engine, &p, "%s\n", engine->name);
err = -ETIME;
goto out_rq;
}
if (rq->fence.error != -EINTR) {
pr_err("%s: fence not cancelled (%u)\n",
engine->name, rq->fence.error);
err = -EINVAL;
}
out_rq:
i915_request_put(rq);
out_ce:
intel_context_put(ce);
out_spin:
igt_spinner_fini(&spin);
if (err)
pr_err("%s: %s error %d\n", __func__, engine->name, err);
return err;
}
static int __cancel_completed(struct intel_engine_cs *engine)
{
struct intel_context *ce;
struct igt_spinner spin;
struct i915_request *rq;
int err = 0;
if (igt_spinner_init(&spin, engine->gt))
return -ENOMEM;
ce = intel_context_create(engine);
if (IS_ERR(ce)) {
err = PTR_ERR(ce);
goto out_spin;
}
rq = igt_spinner_create_request(&spin, ce, MI_ARB_CHECK);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
goto out_ce;
}
igt_spinner_end(&spin);
i915_request_get(rq);
i915_request_add(rq);
if (i915_request_wait(rq, 0, HZ / 5) < 0) {
err = -ETIME;
goto out_rq;
}
pr_debug("%s: Cancelling completed request\n", engine->name);
i915_request_cancel(rq, -EINTR);
if (rq->fence.error) {
pr_err("%s: fence not cancelled (%u)\n",
engine->name, rq->fence.error);
err = -EINVAL;
}
out_rq:
i915_request_put(rq);
out_ce:
intel_context_put(ce);
out_spin:
igt_spinner_fini(&spin);
if (err)
pr_err("%s: %s error %d\n", __func__, engine->name, err);
return err;
}
/*
* Test to prove a non-preemptable request can be cancelled and a subsequent
* request on the same context can successfully complete after cancellation.
*
* Testing methodology is to create a non-preemptible request and submit it,
* wait for spinner to start, create a NOP request and submit it, cancel the
* spinner, wait for spinner to complete and verify it failed with an error,
* finally wait for NOP request to complete verify it succeeded without an
* error. Preemption timeout also reduced / restored so test runs in a timely
* maner.
*/
static int __cancel_reset(struct drm_i915_private *i915,
struct intel_engine_cs *engine)
{
struct intel_context *ce;
struct igt_spinner spin;
struct i915_request *rq, *nop;
unsigned long preempt_timeout_ms;
int err = 0;
if (!CONFIG_DRM_I915_PREEMPT_TIMEOUT ||
!intel_has_reset_engine(engine->gt))
return 0;
preempt_timeout_ms = engine->props.preempt_timeout_ms;
engine->props.preempt_timeout_ms = 100;
if (igt_spinner_init(&spin, engine->gt))
goto out_restore;
ce = intel_context_create(engine);
if (IS_ERR(ce)) {
err = PTR_ERR(ce);
goto out_spin;
}
rq = igt_spinner_create_request(&spin, ce, MI_NOOP);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
goto out_ce;
}
pr_debug("%s: Cancelling active non-preemptable request\n",
engine->name);
i915_request_get(rq);
i915_request_add(rq);
if (!igt_wait_for_spinner(&spin, rq)) {
struct drm_printer p = drm_info_printer(engine->i915->drm.dev);
pr_err("Failed to start spinner on %s\n", engine->name);
intel_engine_dump(engine, &p, "%s\n", engine->name);
err = -ETIME;
goto out_rq;
}
nop = intel_context_create_request(ce);
if (IS_ERR(nop))
goto out_rq;
i915_request_get(nop);
i915_request_add(nop);
i915_request_cancel(rq, -EINTR);
if (i915_request_wait(rq, 0, HZ) < 0) {
struct drm_printer p = drm_info_printer(engine->i915->drm.dev);
pr_err("%s: Failed to cancel hung request\n", engine->name);
intel_engine_dump(engine, &p, "%s\n", engine->name);
err = -ETIME;
goto out_nop;
}
if (rq->fence.error != -EINTR) {
pr_err("%s: fence not cancelled (%u)\n",
engine->name, rq->fence.error);
err = -EINVAL;
goto out_nop;
}
if (i915_request_wait(nop, 0, HZ) < 0) {
struct drm_printer p = drm_info_printer(engine->i915->drm.dev);
pr_err("%s: Failed to complete nop request\n", engine->name);
intel_engine_dump(engine, &p, "%s\n", engine->name);
err = -ETIME;
goto out_nop;
}
if (nop->fence.error != 0) {
pr_err("%s: Nop request errored (%u)\n",
engine->name, nop->fence.error);
err = -EINVAL;
}
out_nop:
i915_request_put(nop);
out_rq:
i915_request_put(rq);
out_ce:
intel_context_put(ce);
out_spin:
igt_spinner_fini(&spin);
out_restore:
engine->props.preempt_timeout_ms = preempt_timeout_ms;
if (err)
pr_err("%s: %s error %d\n", __func__, engine->name, err);
return err;
}
static int live_cancel_request(void *arg)
{
struct drm_i915_private *i915 = arg;
struct intel_engine_cs *engine;
/*
* Check cancellation of requests. We expect to be able to immediately
* cancel active requests, even if they are currently on the GPU.
*/
for_each_uabi_engine(engine, i915) {
struct igt_live_test t;
int err, err2;
if (!intel_engine_has_preemption(engine))
continue;
err = igt_live_test_begin(&t, i915, __func__, engine->name);
if (err)
return err;
err = __cancel_inactive(engine);
if (err == 0)
err = __cancel_active(engine);
if (err == 0)
err = __cancel_completed(engine);
err2 = igt_live_test_end(&t);
if (err)
return err;
if (err2)
return err2;
/* Expects reset so call outside of igt_live_test_* */
err = __cancel_reset(i915, engine);
if (err)
return err;
if (igt_flush_test(i915))
return -EIO;
}
return 0;
}
static struct i915_vma *empty_batch(struct intel_gt *gt)
{
struct drm_i915_gem_object *obj;
struct i915_vma *vma;
u32 *cmd;
int err;
obj = i915_gem_object_create_internal(gt->i915, PAGE_SIZE);
if (IS_ERR(obj))
return ERR_CAST(obj);
cmd = i915_gem_object_pin_map_unlocked(obj, I915_MAP_WC);
if (IS_ERR(cmd)) {
err = PTR_ERR(cmd);
goto err;
}
*cmd = MI_BATCH_BUFFER_END;
__i915_gem_object_flush_map(obj, 0, 64);
i915_gem_object_unpin_map(obj);
intel_gt_chipset_flush(gt);
vma = i915_vma_instance(obj, gt->vm, NULL);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto err;
}
err = i915_vma_pin(vma, 0, 0, PIN_USER);
if (err)
goto err;
/* Force the wait now to avoid including it in the benchmark */
err = i915_vma_sync(vma);
if (err)
goto err_pin;
return vma;
err_pin:
i915_vma_unpin(vma);
err:
i915_gem_object_put(obj);
return ERR_PTR(err);
}
static int emit_bb_start(struct i915_request *rq, struct i915_vma *batch)
{
return rq->engine->emit_bb_start(rq,
i915_vma_offset(batch),
i915_vma_size(batch),
0);
}
static struct i915_request *
empty_request(struct intel_engine_cs *engine,
struct i915_vma *batch)
{
struct i915_request *request;
int err;
request = i915_request_create(engine->kernel_context);
if (IS_ERR(request))
return request;
err = emit_bb_start(request, batch);
if (err)
goto out_request;
i915_request_get(request);
out_request:
i915_request_add(request);
return err ? ERR_PTR(err) : request;
}
static int live_empty_request(void *arg)
{
struct drm_i915_private *i915 = arg;
struct intel_engine_cs *engine;
struct igt_live_test t;
int err;
/*
* Submit various sized batches of empty requests, to each engine
* (individually), and wait for the batch to complete. We can check
* the overhead of submitting requests to the hardware.
*/
for_each_uabi_engine(engine, i915) {
IGT_TIMEOUT(end_time);
struct i915_request *request;
struct i915_vma *batch;
unsigned long n, prime;
ktime_t times[2] = {};
batch = empty_batch(engine->gt);
if (IS_ERR(batch))
return PTR_ERR(batch);
err = igt_live_test_begin(&t, i915, __func__, engine->name);
if (err)
goto out_batch;
intel_engine_pm_get(engine);
/* Warmup / preload */
request = empty_request(engine, batch);
if (IS_ERR(request)) {
err = PTR_ERR(request);
intel_engine_pm_put(engine);
goto out_batch;
}
i915_request_wait(request, 0, MAX_SCHEDULE_TIMEOUT);
for_each_prime_number_from(prime, 1, 8192) {
times[1] = ktime_get_raw();
for (n = 0; n < prime; n++) {
i915_request_put(request);
request = empty_request(engine, batch);
if (IS_ERR(request)) {
err = PTR_ERR(request);
intel_engine_pm_put(engine);
goto out_batch;
}
}
i915_request_wait(request, 0, MAX_SCHEDULE_TIMEOUT);
times[1] = ktime_sub(ktime_get_raw(), times[1]);
if (prime == 1)
times[0] = times[1];
if (__igt_timeout(end_time, NULL))
break;
}
i915_request_put(request);
intel_engine_pm_put(engine);
err = igt_live_test_end(&t);
if (err)
goto out_batch;
pr_info("Batch latencies on %s: 1 = %lluns, %lu = %lluns\n",
engine->name,
ktime_to_ns(times[0]),
prime, div64_u64(ktime_to_ns(times[1]), prime));
out_batch:
i915_vma_unpin(batch);
i915_vma_put(batch);
if (err)
break;
}
return err;
}
static struct i915_vma *recursive_batch(struct intel_gt *gt)
{
struct drm_i915_gem_object *obj;
const int ver = GRAPHICS_VER(gt->i915);
struct i915_vma *vma;
u32 *cmd;
int err;
obj = i915_gem_object_create_internal(gt->i915, PAGE_SIZE);
if (IS_ERR(obj))
return ERR_CAST(obj);
vma = i915_vma_instance(obj, gt->vm, NULL);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto err;
}
err = i915_vma_pin(vma, 0, 0, PIN_USER);
if (err)
goto err;
cmd = i915_gem_object_pin_map_unlocked(obj, I915_MAP_WC);
if (IS_ERR(cmd)) {
err = PTR_ERR(cmd);
goto err;
}
if (ver >= 8) {
*cmd++ = MI_BATCH_BUFFER_START | 1 << 8 | 1;
*cmd++ = lower_32_bits(i915_vma_offset(vma));
*cmd++ = upper_32_bits(i915_vma_offset(vma));
} else if (ver >= 6) {
*cmd++ = MI_BATCH_BUFFER_START | 1 << 8;
*cmd++ = lower_32_bits(i915_vma_offset(vma));
} else {
*cmd++ = MI_BATCH_BUFFER_START | MI_BATCH_GTT;
*cmd++ = lower_32_bits(i915_vma_offset(vma));
}
*cmd++ = MI_BATCH_BUFFER_END; /* terminate early in case of error */
__i915_gem_object_flush_map(obj, 0, 64);
i915_gem_object_unpin_map(obj);
intel_gt_chipset_flush(gt);
return vma;
err:
i915_gem_object_put(obj);
return ERR_PTR(err);
}
static int recursive_batch_resolve(struct i915_vma *batch)
{
u32 *cmd;
cmd = i915_gem_object_pin_map_unlocked(batch->obj, I915_MAP_WC);
if (IS_ERR(cmd))
return PTR_ERR(cmd);
*cmd = MI_BATCH_BUFFER_END;
__i915_gem_object_flush_map(batch->obj, 0, sizeof(*cmd));
i915_gem_object_unpin_map(batch->obj);
intel_gt_chipset_flush(batch->vm->gt);
return 0;
}
static int live_all_engines(void *arg)
{
struct drm_i915_private *i915 = arg;
const unsigned int nengines = num_uabi_engines(i915);
struct intel_engine_cs *engine;
struct i915_request **request;
struct igt_live_test t;
unsigned int idx;
int err;
/*
* Check we can submit requests to all engines simultaneously. We
* send a recursive batch to each engine - checking that we don't
* block doing so, and that they don't complete too soon.
*/
request = kcalloc(nengines, sizeof(*request), GFP_KERNEL);
if (!request)
return -ENOMEM;
err = igt_live_test_begin(&t, i915, __func__, "");
if (err)
goto out_free;
idx = 0;
for_each_uabi_engine(engine, i915) {
struct i915_vma *batch;
batch = recursive_batch(engine->gt);
if (IS_ERR(batch)) {
err = PTR_ERR(batch);
pr_err("%s: Unable to create batch, err=%d\n",
__func__, err);
goto out_free;
}
i915_vma_lock(batch);
request[idx] = intel_engine_create_kernel_request(engine);
if (IS_ERR(request[idx])) {
err = PTR_ERR(request[idx]);
pr_err("%s: Request allocation failed with err=%d\n",
__func__, err);
goto out_unlock;
}
GEM_BUG_ON(request[idx]->context->vm != batch->vm);
err = i915_vma_move_to_active(batch, request[idx], 0);
GEM_BUG_ON(err);
err = emit_bb_start(request[idx], batch);
GEM_BUG_ON(err);
request[idx]->batch = batch;
i915_request_get(request[idx]);
i915_request_add(request[idx]);
idx++;
out_unlock:
i915_vma_unlock(batch);
if (err)
goto out_request;
}
idx = 0;
for_each_uabi_engine(engine, i915) {
if (i915_request_completed(request[idx])) {
pr_err("%s(%s): request completed too early!\n",
__func__, engine->name);
err = -EINVAL;
goto out_request;
}
idx++;
}
idx = 0;
for_each_uabi_engine(engine, i915) {
err = recursive_batch_resolve(request[idx]->batch);
if (err) {
pr_err("%s: failed to resolve batch, err=%d\n",
__func__, err);
goto out_request;
}
idx++;
}
idx = 0;
for_each_uabi_engine(engine, i915) {
struct i915_request *rq = request[idx];
long timeout;
timeout = i915_request_wait(rq, 0,
MAX_SCHEDULE_TIMEOUT);
if (timeout < 0) {
err = timeout;
pr_err("%s: error waiting for request on %s, err=%d\n",
__func__, engine->name, err);
goto out_request;
}
GEM_BUG_ON(!i915_request_completed(rq));
i915_vma_unpin(rq->batch);
i915_vma_put(rq->batch);
i915_request_put(rq);
request[idx] = NULL;
idx++;
}
err = igt_live_test_end(&t);
out_request:
idx = 0;
for_each_uabi_engine(engine, i915) {
struct i915_request *rq = request[idx];
if (!rq)
continue;
if (rq->batch) {
i915_vma_unpin(rq->batch);
i915_vma_put(rq->batch);
}
i915_request_put(rq);
idx++;
}
out_free:
kfree(request);
return err;
}
static int live_sequential_engines(void *arg)
{
struct drm_i915_private *i915 = arg;
const unsigned int nengines = num_uabi_engines(i915);
struct i915_request **request;
struct i915_request *prev = NULL;
struct intel_engine_cs *engine;
struct igt_live_test t;
unsigned int idx;
int err;
/*
* Check we can submit requests to all engines sequentially, such
* that each successive request waits for the earlier ones. This
* tests that we don't execute requests out of order, even though
* they are running on independent engines.
*/
request = kcalloc(nengines, sizeof(*request), GFP_KERNEL);
if (!request)
return -ENOMEM;
err = igt_live_test_begin(&t, i915, __func__, "");
if (err)
goto out_free;
idx = 0;
for_each_uabi_engine(engine, i915) {
struct i915_vma *batch;
batch = recursive_batch(engine->gt);
if (IS_ERR(batch)) {
err = PTR_ERR(batch);
pr_err("%s: Unable to create batch for %s, err=%d\n",
__func__, engine->name, err);
goto out_free;
}
i915_vma_lock(batch);
request[idx] = intel_engine_create_kernel_request(engine);
if (IS_ERR(request[idx])) {
err = PTR_ERR(request[idx]);
pr_err("%s: Request allocation failed for %s with err=%d\n",
__func__, engine->name, err);
goto out_unlock;
}
GEM_BUG_ON(request[idx]->context->vm != batch->vm);
if (prev) {
err = i915_request_await_dma_fence(request[idx],
&prev->fence);
if (err) {
i915_request_add(request[idx]);
pr_err("%s: Request await failed for %s with err=%d\n",
__func__, engine->name, err);
goto out_unlock;
}
}
err = i915_vma_move_to_active(batch, request[idx], 0);
GEM_BUG_ON(err);
err = emit_bb_start(request[idx], batch);
GEM_BUG_ON(err);
request[idx]->batch = batch;
i915_request_get(request[idx]);
i915_request_add(request[idx]);
prev = request[idx];
idx++;
out_unlock:
i915_vma_unlock(batch);
if (err)
goto out_request;
}
idx = 0;
for_each_uabi_engine(engine, i915) {
long timeout;
if (i915_request_completed(request[idx])) {
pr_err("%s(%s): request completed too early!\n",
__func__, engine->name);
err = -EINVAL;
goto out_request;
}
err = recursive_batch_resolve(request[idx]->batch);
if (err) {
pr_err("%s: failed to resolve batch, err=%d\n",
__func__, err);
goto out_request;
}
timeout = i915_request_wait(request[idx], 0,
MAX_SCHEDULE_TIMEOUT);
if (timeout < 0) {
err = timeout;
pr_err("%s: error waiting for request on %s, err=%d\n",
__func__, engine->name, err);
goto out_request;
}
GEM_BUG_ON(!i915_request_completed(request[idx]));
idx++;
}
err = igt_live_test_end(&t);
out_request:
idx = 0;
for_each_uabi_engine(engine, i915) {
u32 *cmd;
if (!request[idx])
break;
cmd = i915_gem_object_pin_map_unlocked(request[idx]->batch->obj,
I915_MAP_WC);
if (!IS_ERR(cmd)) {
*cmd = MI_BATCH_BUFFER_END;
__i915_gem_object_flush_map(request[idx]->batch->obj,
0, sizeof(*cmd));
i915_gem_object_unpin_map(request[idx]->batch->obj);
intel_gt_chipset_flush(engine->gt);
}
i915_vma_put(request[idx]->batch);
i915_request_put(request[idx]);
idx++;
}
out_free:
kfree(request);
return err;
}
struct parallel_thread {
struct kthread_worker *worker;
struct kthread_work work;
struct intel_engine_cs *engine;
int result;
};
static void __live_parallel_engine1(struct kthread_work *work)
{
struct parallel_thread *thread =
container_of(work, typeof(*thread), work);
struct intel_engine_cs *engine = thread->engine;
IGT_TIMEOUT(end_time);
unsigned long count;
int err = 0;
count = 0;
intel_engine_pm_get(engine);
do {
struct i915_request *rq;
rq = i915_request_create(engine->kernel_context);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
break;
}
i915_request_get(rq);
i915_request_add(rq);
err = 0;
if (i915_request_wait(rq, 0, HZ) < 0)
err = -ETIME;
i915_request_put(rq);
if (err)
break;
count++;
} while (!__igt_timeout(end_time, NULL));
intel_engine_pm_put(engine);
pr_info("%s: %lu request + sync\n", engine->name, count);
thread->result = err;
}
static void __live_parallel_engineN(struct kthread_work *work)
{
struct parallel_thread *thread =
container_of(work, typeof(*thread), work);
struct intel_engine_cs *engine = thread->engine;
IGT_TIMEOUT(end_time);
unsigned long count;
int err = 0;
count = 0;
intel_engine_pm_get(engine);
do {
struct i915_request *rq;
rq = i915_request_create(engine->kernel_context);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
break;
}
i915_request_add(rq);
count++;
} while (!__igt_timeout(end_time, NULL));
intel_engine_pm_put(engine);
pr_info("%s: %lu requests\n", engine->name, count);
thread->result = err;
}
static bool wake_all(struct drm_i915_private *i915)
{
if (atomic_dec_and_test(&i915->selftest.counter)) {
wake_up_var(&i915->selftest.counter);
return true;
}
return false;
}
static int wait_for_all(struct drm_i915_private *i915)
{
if (wake_all(i915))
return 0;
if (wait_var_event_timeout(&i915->selftest.counter,
!atomic_read(&i915->selftest.counter),
i915_selftest.timeout_jiffies))
return 0;
return -ETIME;
}
static void __live_parallel_spin(struct kthread_work *work)
{
struct parallel_thread *thread =
container_of(work, typeof(*thread), work);
struct intel_engine_cs *engine = thread->engine;
struct igt_spinner spin;
struct i915_request *rq;
int err = 0;
/*
* Create a spinner running for eternity on each engine. If a second
* spinner is incorrectly placed on the same engine, it will not be
* able to start in time.
*/
if (igt_spinner_init(&spin, engine->gt)) {
wake_all(engine->i915);
thread->result = -ENOMEM;
return;
}
intel_engine_pm_get(engine);
rq = igt_spinner_create_request(&spin,
engine->kernel_context,
MI_NOOP); /* no preemption */
intel_engine_pm_put(engine);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
if (err == -ENODEV)
err = 0;
wake_all(engine->i915);
goto out_spin;
}
i915_request_get(rq);
i915_request_add(rq);
if (igt_wait_for_spinner(&spin, rq)) {
/* Occupy this engine for the whole test */
err = wait_for_all(engine->i915);
} else {
pr_err("Failed to start spinner on %s\n", engine->name);
err = -EINVAL;
}
igt_spinner_end(&spin);
if (err == 0 && i915_request_wait(rq, 0, HZ) < 0)
err = -EIO;
i915_request_put(rq);
out_spin:
igt_spinner_fini(&spin);
thread->result = err;
}
static int live_parallel_engines(void *arg)
{
struct drm_i915_private *i915 = arg;
static void (* const func[])(struct kthread_work *) = {
__live_parallel_engine1,
__live_parallel_engineN,
__live_parallel_spin,
NULL,
};
const unsigned int nengines = num_uabi_engines(i915);
struct parallel_thread *threads;
struct intel_engine_cs *engine;
void (* const *fn)(struct kthread_work *);
int err = 0;
/*
* Check we can submit requests to all engines concurrently. This
* tests that we load up the system maximally.
*/
threads = kcalloc(nengines, sizeof(*threads), GFP_KERNEL);
if (!threads)
return -ENOMEM;
for (fn = func; !err && *fn; fn++) {
char name[KSYM_NAME_LEN];
struct igt_live_test t;
unsigned int idx;
snprintf(name, sizeof(name), "%ps", *fn);
err = igt_live_test_begin(&t, i915, __func__, name);
if (err)
break;
atomic_set(&i915->selftest.counter, nengines);
idx = 0;
for_each_uabi_engine(engine, i915) {
struct kthread_worker *worker;
worker = kthread_create_worker(0, "igt/parallel:%s",
engine->name);
if (IS_ERR(worker)) {
err = PTR_ERR(worker);
break;
}
threads[idx].worker = worker;
threads[idx].result = 0;
threads[idx].engine = engine;
kthread_init_work(&threads[idx].work, *fn);
kthread_queue_work(worker, &threads[idx].work);
idx++;
}
idx = 0;
for_each_uabi_engine(engine, i915) {
int status;
if (!threads[idx].worker)
break;
kthread_flush_work(&threads[idx].work);
status = READ_ONCE(threads[idx].result);
if (status && !err)
err = status;
kthread_destroy_worker(threads[idx++].worker);
}
if (igt_live_test_end(&t))
err = -EIO;
}
kfree(threads);
return err;
}
static int
max_batches(struct i915_gem_context *ctx, struct intel_engine_cs *engine)
{
struct i915_request *rq;
int ret;
/*
* Before execlists, all contexts share the same ringbuffer. With
* execlists, each context/engine has a separate ringbuffer and
* for the purposes of this test, inexhaustible.
*
* For the global ringbuffer though, we have to be very careful
* that we do not wrap while preventing the execution of requests
* with a unsignaled fence.
*/
if (HAS_EXECLISTS(ctx->i915))
return INT_MAX;
rq = igt_request_alloc(ctx, engine);
if (IS_ERR(rq)) {
ret = PTR_ERR(rq);
} else {
int sz;
ret = rq->ring->size - rq->reserved_space;
i915_request_add(rq);
sz = rq->ring->emit - rq->head;
if (sz < 0)
sz += rq->ring->size;
ret /= sz;
ret /= 2; /* leave half spare, in case of emergency! */
}
return ret;
}
static int live_breadcrumbs_smoketest(void *arg)
{
struct drm_i915_private *i915 = arg;
const unsigned int nengines = num_uabi_engines(i915);
const unsigned int ncpus = /* saturate with nengines * ncpus */
max_t(int, 2, DIV_ROUND_UP(num_online_cpus(), nengines));
unsigned long num_waits, num_fences;
struct intel_engine_cs *engine;
struct smoke_thread *threads;
struct igt_live_test live;
intel_wakeref_t wakeref;
struct smoketest *smoke;
unsigned int n, idx;
struct file *file;
int ret = 0;
/*
* Smoketest our breadcrumb/signal handling for requests across multiple
* threads. A very simple test to only catch the most egregious of bugs.
* See __igt_breadcrumbs_smoketest();
*
* On real hardware this time.
*/
wakeref = intel_runtime_pm_get(&i915->runtime_pm);
file = mock_file(i915);
if (IS_ERR(file)) {
ret = PTR_ERR(file);
goto out_rpm;
}
smoke = kcalloc(nengines, sizeof(*smoke), GFP_KERNEL);
if (!smoke) {
ret = -ENOMEM;
goto out_file;
}
threads = kcalloc(ncpus * nengines, sizeof(*threads), GFP_KERNEL);
if (!threads) {
ret = -ENOMEM;
goto out_smoke;
}
smoke[0].request_alloc = __live_request_alloc;
smoke[0].ncontexts = 64;
smoke[0].contexts = kcalloc(smoke[0].ncontexts,
sizeof(*smoke[0].contexts),
GFP_KERNEL);
if (!smoke[0].contexts) {
ret = -ENOMEM;
goto out_threads;
}
for (n = 0; n < smoke[0].ncontexts; n++) {
smoke[0].contexts[n] = live_context(i915, file);
if (IS_ERR(smoke[0].contexts[n])) {
ret = PTR_ERR(smoke[0].contexts[n]);
goto out_contexts;
}
}
ret = igt_live_test_begin(&live, i915, __func__, "");
if (ret)
goto out_contexts;
idx = 0;
for_each_uabi_engine(engine, i915) {
smoke[idx] = smoke[0];
smoke[idx].engine = engine;
smoke[idx].max_batch =
max_batches(smoke[0].contexts[0], engine);
if (smoke[idx].max_batch < 0) {
ret = smoke[idx].max_batch;
goto out_flush;
}
/* One ring interleaved between requests from all cpus */
smoke[idx].max_batch /= ncpus + 1;
pr_debug("Limiting batches to %d requests on %s\n",
smoke[idx].max_batch, engine->name);
for (n = 0; n < ncpus; n++) {
unsigned int i = idx * ncpus + n;
struct kthread_worker *worker;
worker = kthread_create_worker(0, "igt/%d.%d", idx, n);
if (IS_ERR(worker)) {
ret = PTR_ERR(worker);
goto out_flush;
}
threads[i].worker = worker;
threads[i].t = &smoke[idx];
kthread_init_work(&threads[i].work,
__igt_breadcrumbs_smoketest);
kthread_queue_work(worker, &threads[i].work);
}
idx++;
}
msleep(jiffies_to_msecs(i915_selftest.timeout_jiffies));
out_flush:
idx = 0;
num_waits = 0;
num_fences = 0;
for_each_uabi_engine(engine, i915) {
for (n = 0; n < ncpus; n++) {
unsigned int i = idx * ncpus + n;
int err;
if (!threads[i].worker)
continue;
WRITE_ONCE(threads[i].stop, true);
kthread_flush_work(&threads[i].work);
err = READ_ONCE(threads[i].result);
if (err < 0 && !ret)
ret = err;
kthread_destroy_worker(threads[i].worker);
}
num_waits += atomic_long_read(&smoke[idx].num_waits);
num_fences += atomic_long_read(&smoke[idx].num_fences);
idx++;
}
pr_info("Completed %lu waits for %lu fences across %d engines and %d cpus\n",
num_waits, num_fences, idx, ncpus);
ret = igt_live_test_end(&live) ?: ret;
out_contexts:
kfree(smoke[0].contexts);
out_threads:
kfree(threads);
out_smoke:
kfree(smoke);
out_file:
fput(file);
out_rpm:
intel_runtime_pm_put(&i915->runtime_pm, wakeref);
return ret;
}
int i915_request_live_selftests(struct drm_i915_private *i915)
{
static const struct i915_subtest tests[] = {
SUBTEST(live_nop_request),
SUBTEST(live_all_engines),
SUBTEST(live_sequential_engines),
SUBTEST(live_parallel_engines),
SUBTEST(live_empty_request),
SUBTEST(live_cancel_request),
SUBTEST(live_breadcrumbs_smoketest),
};
if (intel_gt_is_wedged(to_gt(i915)))
return 0;
return i915_live_subtests(tests, i915);
}
static int switch_to_kernel_sync(struct intel_context *ce, int err)
{
struct i915_request *rq;
struct dma_fence *fence;
rq = intel_engine_create_kernel_request(ce->engine);
if (IS_ERR(rq))
return PTR_ERR(rq);
fence = i915_active_fence_get(&ce->timeline->last_request);
if (fence) {
i915_request_await_dma_fence(rq, fence);
dma_fence_put(fence);
}
rq = i915_request_get(rq);
i915_request_add(rq);
if (i915_request_wait(rq, 0, HZ / 2) < 0 && !err)
err = -ETIME;
i915_request_put(rq);
while (!err && !intel_engine_is_idle(ce->engine))
intel_engine_flush_submission(ce->engine);
return err;
}
struct perf_stats {
struct intel_engine_cs *engine;
unsigned long count;
ktime_t time;
ktime_t busy;
u64 runtime;
};
struct perf_series {
struct drm_i915_private *i915;
unsigned int nengines;
struct intel_context *ce[];
};
static int cmp_u32(const void *A, const void *B)
{
const u32 *a = A, *b = B;
return *a - *b;
}
static u32 trifilter(u32 *a)
{
u64 sum;
#define TF_COUNT 5
sort(a, TF_COUNT, sizeof(*a), cmp_u32, NULL);
sum = mul_u32_u32(a[2], 2);
sum += a[1];
sum += a[3];
GEM_BUG_ON(sum > U32_MAX);
return sum;
#define TF_BIAS 2
}
static u64 cycles_to_ns(struct intel_engine_cs *engine, u32 cycles)
{
u64 ns = intel_gt_clock_interval_to_ns(engine->gt, cycles);
return DIV_ROUND_CLOSEST(ns, 1 << TF_BIAS);
}
static u32 *emit_timestamp_store(u32 *cs, struct intel_context *ce, u32 offset)
{
*cs++ = MI_STORE_REGISTER_MEM_GEN8 | MI_USE_GGTT;
*cs++ = i915_mmio_reg_offset(RING_TIMESTAMP((ce->engine->mmio_base)));
*cs++ = offset;
*cs++ = 0;
return cs;
}
static u32 *emit_store_dw(u32 *cs, u32 offset, u32 value)
{
*cs++ = MI_STORE_DWORD_IMM_GEN4 | MI_USE_GGTT;
*cs++ = offset;
*cs++ = 0;
*cs++ = value;
return cs;
}
static u32 *emit_semaphore_poll(u32 *cs, u32 mode, u32 value, u32 offset)
{
*cs++ = MI_SEMAPHORE_WAIT |
MI_SEMAPHORE_GLOBAL_GTT |
MI_SEMAPHORE_POLL |
mode;
*cs++ = value;
*cs++ = offset;
*cs++ = 0;
return cs;
}
static u32 *emit_semaphore_poll_until(u32 *cs, u32 offset, u32 value)
{
return emit_semaphore_poll(cs, MI_SEMAPHORE_SAD_EQ_SDD, value, offset);
}
static void semaphore_set(u32 *sema, u32 value)
{
WRITE_ONCE(*sema, value);
wmb(); /* flush the update to the cache, and beyond */
}
static u32 *hwsp_scratch(const struct intel_context *ce)
{
return memset32(ce->engine->status_page.addr + 1000, 0, 21);
}
static u32 hwsp_offset(const struct intel_context *ce, u32 *dw)
{
return (i915_ggtt_offset(ce->engine->status_page.vma) +
offset_in_page(dw));
}
static int measure_semaphore_response(struct intel_context *ce)
{
u32 *sema = hwsp_scratch(ce);
const u32 offset = hwsp_offset(ce, sema);
u32 elapsed[TF_COUNT], cycles;
struct i915_request *rq;
u32 *cs;
int err;
int i;
/*
* Measure how many cycles it takes for the HW to detect the change
* in a semaphore value.
*
* A: read CS_TIMESTAMP from CPU
* poke semaphore
* B: read CS_TIMESTAMP on GPU
*
* Semaphore latency: B - A
*/
semaphore_set(sema, -1);
rq = i915_request_create(ce);
if (IS_ERR(rq))
return PTR_ERR(rq);
cs = intel_ring_begin(rq, 4 + 12 * ARRAY_SIZE(elapsed));
if (IS_ERR(cs)) {
i915_request_add(rq);
err = PTR_ERR(cs);
goto err;
}
cs = emit_store_dw(cs, offset, 0);
for (i = 1; i <= ARRAY_SIZE(elapsed); i++) {
cs = emit_semaphore_poll_until(cs, offset, i);
cs = emit_timestamp_store(cs, ce, offset + i * sizeof(u32));
cs = emit_store_dw(cs, offset, 0);
}
intel_ring_advance(rq, cs);
i915_request_add(rq);
if (wait_for(READ_ONCE(*sema) == 0, 50)) {
err = -EIO;
goto err;
}
for (i = 1; i <= ARRAY_SIZE(elapsed); i++) {
preempt_disable();
cycles = ENGINE_READ_FW(ce->engine, RING_TIMESTAMP);
semaphore_set(sema, i);
preempt_enable();
if (wait_for(READ_ONCE(*sema) == 0, 50)) {
err = -EIO;
goto err;
}
elapsed[i - 1] = sema[i] - cycles;
}
cycles = trifilter(elapsed);
pr_info("%s: semaphore response %d cycles, %lluns\n",
ce->engine->name, cycles >> TF_BIAS,
cycles_to_ns(ce->engine, cycles));
return intel_gt_wait_for_idle(ce->engine->gt, HZ);
err:
intel_gt_set_wedged(ce->engine->gt);
return err;
}
static int measure_idle_dispatch(struct intel_context *ce)
{
u32 *sema = hwsp_scratch(ce);
const u32 offset = hwsp_offset(ce, sema);
u32 elapsed[TF_COUNT], cycles;
u32 *cs;
int err;
int i;
/*
* Measure how long it takes for us to submit a request while the
* engine is idle, but is resting in our context.
*
* A: read CS_TIMESTAMP from CPU
* submit request
* B: read CS_TIMESTAMP on GPU
*
* Submission latency: B - A
*/
for (i = 0; i < ARRAY_SIZE(elapsed); i++) {
struct i915_request *rq;
err = intel_gt_wait_for_idle(ce->engine->gt, HZ / 2);
if (err)
return err;
rq = i915_request_create(ce);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
goto err;
}
cs = intel_ring_begin(rq, 4);
if (IS_ERR(cs)) {
i915_request_add(rq);
err = PTR_ERR(cs);
goto err;
}
cs = emit_timestamp_store(cs, ce, offset + i * sizeof(u32));
intel_ring_advance(rq, cs);
preempt_disable();
local_bh_disable();
elapsed[i] = ENGINE_READ_FW(ce->engine, RING_TIMESTAMP);
i915_request_add(rq);
local_bh_enable();
preempt_enable();
}
err = intel_gt_wait_for_idle(ce->engine->gt, HZ / 2);
if (err)
goto err;
for (i = 0; i < ARRAY_SIZE(elapsed); i++)
elapsed[i] = sema[i] - elapsed[i];
cycles = trifilter(elapsed);
pr_info("%s: idle dispatch latency %d cycles, %lluns\n",
ce->engine->name, cycles >> TF_BIAS,
cycles_to_ns(ce->engine, cycles));
return intel_gt_wait_for_idle(ce->engine->gt, HZ);
err:
intel_gt_set_wedged(ce->engine->gt);
return err;
}
static int measure_busy_dispatch(struct intel_context *ce)
{
u32 *sema = hwsp_scratch(ce);
const u32 offset = hwsp_offset(ce, sema);
u32 elapsed[TF_COUNT + 1], cycles;
u32 *cs;
int err;
int i;
/*
* Measure how long it takes for us to submit a request while the
* engine is busy, polling on a semaphore in our context. With
* direct submission, this will include the cost of a lite restore.
*
* A: read CS_TIMESTAMP from CPU
* submit request
* B: read CS_TIMESTAMP on GPU
*
* Submission latency: B - A
*/
for (i = 1; i <= ARRAY_SIZE(elapsed); i++) {
struct i915_request *rq;
rq = i915_request_create(ce);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
goto err;
}
cs = intel_ring_begin(rq, 12);
if (IS_ERR(cs)) {
i915_request_add(rq);
err = PTR_ERR(cs);
goto err;
}
cs = emit_store_dw(cs, offset + i * sizeof(u32), -1);
cs = emit_semaphore_poll_until(cs, offset, i);
cs = emit_timestamp_store(cs, ce, offset + i * sizeof(u32));
intel_ring_advance(rq, cs);
if (i > 1 && wait_for(READ_ONCE(sema[i - 1]), 500)) {
err = -EIO;
goto err;
}
preempt_disable();
local_bh_disable();
elapsed[i - 1] = ENGINE_READ_FW(ce->engine, RING_TIMESTAMP);
i915_request_add(rq);
local_bh_enable();
semaphore_set(sema, i - 1);
preempt_enable();
}
wait_for(READ_ONCE(sema[i - 1]), 500);
semaphore_set(sema, i - 1);
for (i = 1; i <= TF_COUNT; i++) {
GEM_BUG_ON(sema[i] == -1);
elapsed[i - 1] = sema[i] - elapsed[i];
}
cycles = trifilter(elapsed);
pr_info("%s: busy dispatch latency %d cycles, %lluns\n",
ce->engine->name, cycles >> TF_BIAS,
cycles_to_ns(ce->engine, cycles));
return intel_gt_wait_for_idle(ce->engine->gt, HZ);
err:
intel_gt_set_wedged(ce->engine->gt);
return err;
}
static int plug(struct intel_engine_cs *engine, u32 *sema, u32 mode, int value)
{
const u32 offset =
i915_ggtt_offset(engine->status_page.vma) +
offset_in_page(sema);
struct i915_request *rq;
u32 *cs;
rq = i915_request_create(engine->kernel_context);
if (IS_ERR(rq))
return PTR_ERR(rq);
cs = intel_ring_begin(rq, 4);
if (IS_ERR(cs)) {
i915_request_add(rq);
return PTR_ERR(cs);
}
cs = emit_semaphore_poll(cs, mode, value, offset);
intel_ring_advance(rq, cs);
i915_request_add(rq);
return 0;
}
static int measure_inter_request(struct intel_context *ce)
{
u32 *sema = hwsp_scratch(ce);
const u32 offset = hwsp_offset(ce, sema);
u32 elapsed[TF_COUNT + 1], cycles;
struct i915_sw_fence *submit;
int i, err;
/*
* Measure how long it takes to advance from one request into the
* next. Between each request we flush the GPU caches to memory,
* update the breadcrumbs, and then invalidate those caches.
* We queue up all the requests to be submitted in one batch so
* it should be one set of contiguous measurements.
*
* A: read CS_TIMESTAMP on GPU
* advance request
* B: read CS_TIMESTAMP on GPU
*
* Request latency: B - A
*/
err = plug(ce->engine, sema, MI_SEMAPHORE_SAD_NEQ_SDD, 0);
if (err)
return err;
submit = heap_fence_create(GFP_KERNEL);
if (!submit) {
semaphore_set(sema, 1);
return -ENOMEM;
}
intel_engine_flush_submission(ce->engine);
for (i = 1; i <= ARRAY_SIZE(elapsed); i++) {
struct i915_request *rq;
u32 *cs;
rq = i915_request_create(ce);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
goto err_submit;
}
err = i915_sw_fence_await_sw_fence_gfp(&rq->submit,
submit,
GFP_KERNEL);
if (err < 0) {
i915_request_add(rq);
goto err_submit;
}
cs = intel_ring_begin(rq, 4);
if (IS_ERR(cs)) {
i915_request_add(rq);
err = PTR_ERR(cs);
goto err_submit;
}
cs = emit_timestamp_store(cs, ce, offset + i * sizeof(u32));
intel_ring_advance(rq, cs);
i915_request_add(rq);
}
i915_sw_fence_commit(submit);
intel_engine_flush_submission(ce->engine);
heap_fence_put(submit);
semaphore_set(sema, 1);
err = intel_gt_wait_for_idle(ce->engine->gt, HZ / 2);
if (err)
goto err;
for (i = 1; i <= TF_COUNT; i++)
elapsed[i - 1] = sema[i + 1] - sema[i];
cycles = trifilter(elapsed);
pr_info("%s: inter-request latency %d cycles, %lluns\n",
ce->engine->name, cycles >> TF_BIAS,
cycles_to_ns(ce->engine, cycles));
return intel_gt_wait_for_idle(ce->engine->gt, HZ);
err_submit:
i915_sw_fence_commit(submit);
heap_fence_put(submit);
semaphore_set(sema, 1);
err:
intel_gt_set_wedged(ce->engine->gt);
return err;
}
static int measure_context_switch(struct intel_context *ce)
{
u32 *sema = hwsp_scratch(ce);
const u32 offset = hwsp_offset(ce, sema);
struct i915_request *fence = NULL;
u32 elapsed[TF_COUNT + 1], cycles;
int i, j, err;
u32 *cs;
/*
* Measure how long it takes to advance from one request in one
* context to a request in another context. This allows us to
* measure how long the context save/restore take, along with all
* the inter-context setup we require.
*
* A: read CS_TIMESTAMP on GPU
* switch context
* B: read CS_TIMESTAMP on GPU
*
* Context switch latency: B - A
*/
err = plug(ce->engine, sema, MI_SEMAPHORE_SAD_NEQ_SDD, 0);
if (err)
return err;
for (i = 1; i <= ARRAY_SIZE(elapsed); i++) {
struct intel_context *arr[] = {
ce, ce->engine->kernel_context
};
u32 addr = offset + ARRAY_SIZE(arr) * i * sizeof(u32);
for (j = 0; j < ARRAY_SIZE(arr); j++) {
struct i915_request *rq;
rq = i915_request_create(arr[j]);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
goto err_fence;
}
if (fence) {
err = i915_request_await_dma_fence(rq,
&fence->fence);
if (err) {
i915_request_add(rq);
goto err_fence;
}
}
cs = intel_ring_begin(rq, 4);
if (IS_ERR(cs)) {
i915_request_add(rq);
err = PTR_ERR(cs);
goto err_fence;
}
cs = emit_timestamp_store(cs, ce, addr);
addr += sizeof(u32);
intel_ring_advance(rq, cs);
i915_request_put(fence);
fence = i915_request_get(rq);
i915_request_add(rq);
}
}
i915_request_put(fence);
intel_engine_flush_submission(ce->engine);
semaphore_set(sema, 1);
err = intel_gt_wait_for_idle(ce->engine->gt, HZ / 2);
if (err)
goto err;
for (i = 1; i <= TF_COUNT; i++)
elapsed[i - 1] = sema[2 * i + 2] - sema[2 * i + 1];
cycles = trifilter(elapsed);
pr_info("%s: context switch latency %d cycles, %lluns\n",
ce->engine->name, cycles >> TF_BIAS,
cycles_to_ns(ce->engine, cycles));
return intel_gt_wait_for_idle(ce->engine->gt, HZ);
err_fence:
i915_request_put(fence);
semaphore_set(sema, 1);
err:
intel_gt_set_wedged(ce->engine->gt);
return err;
}
static int measure_preemption(struct intel_context *ce)
{
u32 *sema = hwsp_scratch(ce);
const u32 offset = hwsp_offset(ce, sema);
u32 elapsed[TF_COUNT], cycles;
u32 *cs;
int err;
int i;
/*
* We measure two latencies while triggering preemption. The first
* latency is how long it takes for us to submit a preempting request.
* The second latency is how it takes for us to return from the
* preemption back to the original context.
*
* A: read CS_TIMESTAMP from CPU
* submit preemption
* B: read CS_TIMESTAMP on GPU (in preempting context)
* context switch
* C: read CS_TIMESTAMP on GPU (in original context)
*
* Preemption dispatch latency: B - A
* Preemption switch latency: C - B
*/
if (!intel_engine_has_preemption(ce->engine))
return 0;
for (i = 1; i <= ARRAY_SIZE(elapsed); i++) {
u32 addr = offset + 2 * i * sizeof(u32);
struct i915_request *rq;
rq = i915_request_create(ce);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
goto err;
}
cs = intel_ring_begin(rq, 12);
if (IS_ERR(cs)) {
i915_request_add(rq);
err = PTR_ERR(cs);
goto err;
}
cs = emit_store_dw(cs, addr, -1);
cs = emit_semaphore_poll_until(cs, offset, i);
cs = emit_timestamp_store(cs, ce, addr + sizeof(u32));
intel_ring_advance(rq, cs);
i915_request_add(rq);
if (wait_for(READ_ONCE(sema[2 * i]) == -1, 500)) {
err = -EIO;
goto err;
}
rq = i915_request_create(ce->engine->kernel_context);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
goto err;
}
cs = intel_ring_begin(rq, 8);
if (IS_ERR(cs)) {
i915_request_add(rq);
err = PTR_ERR(cs);
goto err;
}
cs = emit_timestamp_store(cs, ce, addr);
cs = emit_store_dw(cs, offset, i);
intel_ring_advance(rq, cs);
rq->sched.attr.priority = I915_PRIORITY_BARRIER;
elapsed[i - 1] = ENGINE_READ_FW(ce->engine, RING_TIMESTAMP);
i915_request_add(rq);
}
if (wait_for(READ_ONCE(sema[2 * i - 2]) != -1, 500)) {
err = -EIO;
goto err;
}
for (i = 1; i <= TF_COUNT; i++)
elapsed[i - 1] = sema[2 * i + 0] - elapsed[i - 1];
cycles = trifilter(elapsed);
pr_info("%s: preemption dispatch latency %d cycles, %lluns\n",
ce->engine->name, cycles >> TF_BIAS,
cycles_to_ns(ce->engine, cycles));
for (i = 1; i <= TF_COUNT; i++)
elapsed[i - 1] = sema[2 * i + 1] - sema[2 * i + 0];
cycles = trifilter(elapsed);
pr_info("%s: preemption switch latency %d cycles, %lluns\n",
ce->engine->name, cycles >> TF_BIAS,
cycles_to_ns(ce->engine, cycles));
return intel_gt_wait_for_idle(ce->engine->gt, HZ);
err:
intel_gt_set_wedged(ce->engine->gt);
return err;
}
struct signal_cb {
struct dma_fence_cb base;
bool seen;
};
static void signal_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
{
struct signal_cb *s = container_of(cb, typeof(*s), base);
smp_store_mb(s->seen, true); /* be safe, be strong */
}
static int measure_completion(struct intel_context *ce)
{
u32 *sema = hwsp_scratch(ce);
const u32 offset = hwsp_offset(ce, sema);
u32 elapsed[TF_COUNT], cycles;
u32 *cs;
int err;
int i;
/*
* Measure how long it takes for the signal (interrupt) to be
* sent from the GPU to be processed by the CPU.
*
* A: read CS_TIMESTAMP on GPU
* signal
* B: read CS_TIMESTAMP from CPU
*
* Completion latency: B - A
*/
for (i = 1; i <= ARRAY_SIZE(elapsed); i++) {
struct signal_cb cb = { .seen = false };
struct i915_request *rq;
rq = i915_request_create(ce);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
goto err;
}
cs = intel_ring_begin(rq, 12);
if (IS_ERR(cs)) {
i915_request_add(rq);
err = PTR_ERR(cs);
goto err;
}
cs = emit_store_dw(cs, offset + i * sizeof(u32), -1);
cs = emit_semaphore_poll_until(cs, offset, i);
cs = emit_timestamp_store(cs, ce, offset + i * sizeof(u32));
intel_ring_advance(rq, cs);
dma_fence_add_callback(&rq->fence, &cb.base, signal_cb);
i915_request_add(rq);
intel_engine_flush_submission(ce->engine);
if (wait_for(READ_ONCE(sema[i]) == -1, 50)) {
err = -EIO;
goto err;
}
preempt_disable();
semaphore_set(sema, i);
while (!READ_ONCE(cb.seen))
cpu_relax();
elapsed[i - 1] = ENGINE_READ_FW(ce->engine, RING_TIMESTAMP);
preempt_enable();
}
err = intel_gt_wait_for_idle(ce->engine->gt, HZ / 2);
if (err)
goto err;
for (i = 0; i < ARRAY_SIZE(elapsed); i++) {
GEM_BUG_ON(sema[i + 1] == -1);
elapsed[i] = elapsed[i] - sema[i + 1];
}
cycles = trifilter(elapsed);
pr_info("%s: completion latency %d cycles, %lluns\n",
ce->engine->name, cycles >> TF_BIAS,
cycles_to_ns(ce->engine, cycles));
return intel_gt_wait_for_idle(ce->engine->gt, HZ);
err:
intel_gt_set_wedged(ce->engine->gt);
return err;
}
static void rps_pin(struct intel_gt *gt)
{
/* Pin the frequency to max */
atomic_inc(>->rps.num_waiters);
intel_uncore_forcewake_get(gt->uncore, FORCEWAKE_ALL);
mutex_lock(>->rps.lock);
intel_rps_set(>->rps, gt->rps.max_freq);
mutex_unlock(>->rps.lock);
}
static void rps_unpin(struct intel_gt *gt)
{
intel_uncore_forcewake_put(gt->uncore, FORCEWAKE_ALL);
atomic_dec(>->rps.num_waiters);
}
static int perf_request_latency(void *arg)
{
struct drm_i915_private *i915 = arg;
struct intel_engine_cs *engine;
struct pm_qos_request qos;
int err = 0;
if (GRAPHICS_VER(i915) < 8) /* per-engine CS timestamp, semaphores */
return 0;
cpu_latency_qos_add_request(&qos, 0); /* disable cstates */
for_each_uabi_engine(engine, i915) {
struct intel_context *ce;
ce = intel_context_create(engine);
if (IS_ERR(ce)) {
err = PTR_ERR(ce);
goto out;
}
err = intel_context_pin(ce);
if (err) {
intel_context_put(ce);
goto out;
}
st_engine_heartbeat_disable(engine);
rps_pin(engine->gt);
if (err == 0)
err = measure_semaphore_response(ce);
if (err == 0)
err = measure_idle_dispatch(ce);
if (err == 0)
err = measure_busy_dispatch(ce);
if (err == 0)
err = measure_inter_request(ce);
if (err == 0)
err = measure_context_switch(ce);
if (err == 0)
err = measure_preemption(ce);
if (err == 0)
err = measure_completion(ce);
rps_unpin(engine->gt);
st_engine_heartbeat_enable(engine);
intel_context_unpin(ce);
intel_context_put(ce);
if (err)
goto out;
}
out:
if (igt_flush_test(i915))
err = -EIO;
cpu_latency_qos_remove_request(&qos);
return err;
}
static int s_sync0(void *arg)
{
struct perf_series *ps = arg;
IGT_TIMEOUT(end_time);
unsigned int idx = 0;
int err = 0;
GEM_BUG_ON(!ps->nengines);
do {
struct i915_request *rq;
rq = i915_request_create(ps->ce[idx]);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
break;
}
i915_request_get(rq);
i915_request_add(rq);
if (i915_request_wait(rq, 0, HZ / 5) < 0)
err = -ETIME;
i915_request_put(rq);
if (err)
break;
if (++idx == ps->nengines)
idx = 0;
} while (!__igt_timeout(end_time, NULL));
return err;
}
static int s_sync1(void *arg)
{
struct perf_series *ps = arg;
struct i915_request *prev = NULL;
IGT_TIMEOUT(end_time);
unsigned int idx = 0;
int err = 0;
GEM_BUG_ON(!ps->nengines);
do {
struct i915_request *rq;
rq = i915_request_create(ps->ce[idx]);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
break;
}
i915_request_get(rq);
i915_request_add(rq);
if (prev && i915_request_wait(prev, 0, HZ / 5) < 0)
err = -ETIME;
i915_request_put(prev);
prev = rq;
if (err)
break;
if (++idx == ps->nengines)
idx = 0;
} while (!__igt_timeout(end_time, NULL));
i915_request_put(prev);
return err;
}
static int s_many(void *arg)
{
struct perf_series *ps = arg;
IGT_TIMEOUT(end_time);
unsigned int idx = 0;
GEM_BUG_ON(!ps->nengines);
do {
struct i915_request *rq;
rq = i915_request_create(ps->ce[idx]);
if (IS_ERR(rq))
return PTR_ERR(rq);
i915_request_add(rq);
if (++idx == ps->nengines)
idx = 0;
} while (!__igt_timeout(end_time, NULL));
return 0;
}
static int perf_series_engines(void *arg)
{
struct drm_i915_private *i915 = arg;
static int (* const func[])(void *arg) = {
s_sync0,
s_sync1,
s_many,
NULL,
};
const unsigned int nengines = num_uabi_engines(i915);
struct intel_engine_cs *engine;
int (* const *fn)(void *arg);
struct pm_qos_request qos;
struct perf_stats *stats;
struct perf_series *ps;
unsigned int idx;
int err = 0;
stats = kcalloc(nengines, sizeof(*stats), GFP_KERNEL);
if (!stats)
return -ENOMEM;
ps = kzalloc(struct_size(ps, ce, nengines), GFP_KERNEL);
if (!ps) {
kfree(stats);
return -ENOMEM;
}
cpu_latency_qos_add_request(&qos, 0); /* disable cstates */
ps->i915 = i915;
ps->nengines = nengines;
idx = 0;
for_each_uabi_engine(engine, i915) {
struct intel_context *ce;
ce = intel_context_create(engine);
if (IS_ERR(ce)) {
err = PTR_ERR(ce);
goto out;
}
err = intel_context_pin(ce);
if (err) {
intel_context_put(ce);
goto out;
}
ps->ce[idx++] = ce;
}
GEM_BUG_ON(idx != ps->nengines);
for (fn = func; *fn && !err; fn++) {
char name[KSYM_NAME_LEN];
struct igt_live_test t;
snprintf(name, sizeof(name), "%ps", *fn);
err = igt_live_test_begin(&t, i915, __func__, name);
if (err)
break;
for (idx = 0; idx < nengines; idx++) {
struct perf_stats *p =
memset(&stats[idx], 0, sizeof(stats[idx]));
struct intel_context *ce = ps->ce[idx];
p->engine = ps->ce[idx]->engine;
intel_engine_pm_get(p->engine);
if (intel_engine_supports_stats(p->engine))
p->busy = intel_engine_get_busy_time(p->engine,
&p->time) + 1;
else
p->time = ktime_get();
p->runtime = -intel_context_get_total_runtime_ns(ce);
}
err = (*fn)(ps);
if (igt_live_test_end(&t))
err = -EIO;
for (idx = 0; idx < nengines; idx++) {
struct perf_stats *p = &stats[idx];
struct intel_context *ce = ps->ce[idx];
int integer, decimal;
u64 busy, dt, now;
if (p->busy)
p->busy = ktime_sub(intel_engine_get_busy_time(p->engine,
&now),
p->busy - 1);
else
now = ktime_get();
p->time = ktime_sub(now, p->time);
err = switch_to_kernel_sync(ce, err);
p->runtime += intel_context_get_total_runtime_ns(ce);
intel_engine_pm_put(p->engine);
busy = 100 * ktime_to_ns(p->busy);
dt = ktime_to_ns(p->time);
if (dt) {
integer = div64_u64(busy, dt);
busy -= integer * dt;
decimal = div64_u64(100 * busy, dt);
} else {
integer = 0;
decimal = 0;
}
pr_info("%s %5s: { seqno:%d, busy:%d.%02d%%, runtime:%lldms, walltime:%lldms }\n",
name, p->engine->name, ce->timeline->seqno,
integer, decimal,
div_u64(p->runtime, 1000 * 1000),
div_u64(ktime_to_ns(p->time), 1000 * 1000));
}
}
out:
for (idx = 0; idx < nengines; idx++) {
if (IS_ERR_OR_NULL(ps->ce[idx]))
break;
intel_context_unpin(ps->ce[idx]);
intel_context_put(ps->ce[idx]);
}
kfree(ps);
cpu_latency_qos_remove_request(&qos);
kfree(stats);
return err;
}
struct p_thread {
struct perf_stats p;
struct kthread_worker *worker;
struct kthread_work work;
struct intel_engine_cs *engine;
int result;
};
static void p_sync0(struct kthread_work *work)
{
struct p_thread *thread = container_of(work, typeof(*thread), work);
struct perf_stats *p = &thread->p;
struct intel_engine_cs *engine = p->engine;
struct intel_context *ce;
IGT_TIMEOUT(end_time);
unsigned long count;
bool busy;
int err = 0;
ce = intel_context_create(engine);
if (IS_ERR(ce)) {
thread->result = PTR_ERR(ce);
return;
}
err = intel_context_pin(ce);
if (err) {
intel_context_put(ce);
thread->result = err;
return;
}
if (intel_engine_supports_stats(engine)) {
p->busy = intel_engine_get_busy_time(engine, &p->time);
busy = true;
} else {
p->time = ktime_get();
busy = false;
}
count = 0;
do {
struct i915_request *rq;
rq = i915_request_create(ce);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
break;
}
i915_request_get(rq);
i915_request_add(rq);
err = 0;
if (i915_request_wait(rq, 0, HZ) < 0)
err = -ETIME;
i915_request_put(rq);
if (err)
break;
count++;
} while (!__igt_timeout(end_time, NULL));
if (busy) {
ktime_t now;
p->busy = ktime_sub(intel_engine_get_busy_time(engine, &now),
p->busy);
p->time = ktime_sub(now, p->time);
} else {
p->time = ktime_sub(ktime_get(), p->time);
}
err = switch_to_kernel_sync(ce, err);
p->runtime = intel_context_get_total_runtime_ns(ce);
p->count = count;
intel_context_unpin(ce);
intel_context_put(ce);
thread->result = err;
}
static void p_sync1(struct kthread_work *work)
{
struct p_thread *thread = container_of(work, typeof(*thread), work);
struct perf_stats *p = &thread->p;
struct intel_engine_cs *engine = p->engine;
struct i915_request *prev = NULL;
struct intel_context *ce;
IGT_TIMEOUT(end_time);
unsigned long count;
bool busy;
int err = 0;
ce = intel_context_create(engine);
if (IS_ERR(ce)) {
thread->result = PTR_ERR(ce);
return;
}
err = intel_context_pin(ce);
if (err) {
intel_context_put(ce);
thread->result = err;
return;
}
if (intel_engine_supports_stats(engine)) {
p->busy = intel_engine_get_busy_time(engine, &p->time);
busy = true;
} else {
p->time = ktime_get();
busy = false;
}
count = 0;
do {
struct i915_request *rq;
rq = i915_request_create(ce);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
break;
}
i915_request_get(rq);
i915_request_add(rq);
err = 0;
if (prev && i915_request_wait(prev, 0, HZ) < 0)
err = -ETIME;
i915_request_put(prev);
prev = rq;
if (err)
break;
count++;
} while (!__igt_timeout(end_time, NULL));
i915_request_put(prev);
if (busy) {
ktime_t now;
p->busy = ktime_sub(intel_engine_get_busy_time(engine, &now),
p->busy);
p->time = ktime_sub(now, p->time);
} else {
p->time = ktime_sub(ktime_get(), p->time);
}
err = switch_to_kernel_sync(ce, err);
p->runtime = intel_context_get_total_runtime_ns(ce);
p->count = count;
intel_context_unpin(ce);
intel_context_put(ce);
thread->result = err;
}
static void p_many(struct kthread_work *work)
{
struct p_thread *thread = container_of(work, typeof(*thread), work);
struct perf_stats *p = &thread->p;
struct intel_engine_cs *engine = p->engine;
struct intel_context *ce;
IGT_TIMEOUT(end_time);
unsigned long count;
int err = 0;
bool busy;
ce = intel_context_create(engine);
if (IS_ERR(ce)) {
thread->result = PTR_ERR(ce);
return;
}
err = intel_context_pin(ce);
if (err) {
intel_context_put(ce);
thread->result = err;
return;
}
if (intel_engine_supports_stats(engine)) {
p->busy = intel_engine_get_busy_time(engine, &p->time);
busy = true;
} else {
p->time = ktime_get();
busy = false;
}
count = 0;
do {
struct i915_request *rq;
rq = i915_request_create(ce);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
break;
}
i915_request_add(rq);
count++;
} while (!__igt_timeout(end_time, NULL));
if (busy) {
ktime_t now;
p->busy = ktime_sub(intel_engine_get_busy_time(engine, &now),
p->busy);
p->time = ktime_sub(now, p->time);
} else {
p->time = ktime_sub(ktime_get(), p->time);
}
err = switch_to_kernel_sync(ce, err);
p->runtime = intel_context_get_total_runtime_ns(ce);
p->count = count;
intel_context_unpin(ce);
intel_context_put(ce);
thread->result = err;
}
static int perf_parallel_engines(void *arg)
{
struct drm_i915_private *i915 = arg;
static void (* const func[])(struct kthread_work *) = {
p_sync0,
p_sync1,
p_many,
NULL,
};
const unsigned int nengines = num_uabi_engines(i915);
void (* const *fn)(struct kthread_work *);
struct intel_engine_cs *engine;
struct pm_qos_request qos;
struct p_thread *engines;
int err = 0;
engines = kcalloc(nengines, sizeof(*engines), GFP_KERNEL);
if (!engines)
return -ENOMEM;
cpu_latency_qos_add_request(&qos, 0);
for (fn = func; *fn; fn++) {
char name[KSYM_NAME_LEN];
struct igt_live_test t;
unsigned int idx;
snprintf(name, sizeof(name), "%ps", *fn);
err = igt_live_test_begin(&t, i915, __func__, name);
if (err)
break;
atomic_set(&i915->selftest.counter, nengines);
idx = 0;
for_each_uabi_engine(engine, i915) {
struct kthread_worker *worker;
intel_engine_pm_get(engine);
memset(&engines[idx].p, 0, sizeof(engines[idx].p));
worker = kthread_create_worker(0, "igt:%s",
engine->name);
if (IS_ERR(worker)) {
err = PTR_ERR(worker);
intel_engine_pm_put(engine);
break;
}
engines[idx].worker = worker;
engines[idx].result = 0;
engines[idx].p.engine = engine;
engines[idx].engine = engine;
kthread_init_work(&engines[idx].work, *fn);
kthread_queue_work(worker, &engines[idx].work);
idx++;
}
idx = 0;
for_each_uabi_engine(engine, i915) {
int status;
if (!engines[idx].worker)
break;
kthread_flush_work(&engines[idx].work);
status = READ_ONCE(engines[idx].result);
if (status && !err)
err = status;
intel_engine_pm_put(engine);
kthread_destroy_worker(engines[idx].worker);
idx++;
}
if (igt_live_test_end(&t))
err = -EIO;
if (err)
break;
idx = 0;
for_each_uabi_engine(engine, i915) {
struct perf_stats *p = &engines[idx].p;
u64 busy = 100 * ktime_to_ns(p->busy);
u64 dt = ktime_to_ns(p->time);
int integer, decimal;
if (dt) {
integer = div64_u64(busy, dt);
busy -= integer * dt;
decimal = div64_u64(100 * busy, dt);
} else {
integer = 0;
decimal = 0;
}
GEM_BUG_ON(engine != p->engine);
pr_info("%s %5s: { count:%lu, busy:%d.%02d%%, runtime:%lldms, walltime:%lldms }\n",
name, engine->name, p->count, integer, decimal,
div_u64(p->runtime, 1000 * 1000),
div_u64(ktime_to_ns(p->time), 1000 * 1000));
idx++;
}
}
cpu_latency_qos_remove_request(&qos);
kfree(engines);
return err;
}
int i915_request_perf_selftests(struct drm_i915_private *i915)
{
static const struct i915_subtest tests[] = {
SUBTEST(perf_request_latency),
SUBTEST(perf_series_engines),
SUBTEST(perf_parallel_engines),
};
if (intel_gt_is_wedged(to_gt(i915)))
return 0;
return i915_subtests(tests, i915);
}
| linux-master | drivers/gpu/drm/i915/selftests/i915_request.c |
/*
* Copyright © 2017 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
#include "../i915_selftest.h"
#include "i915_random.h"
static char *
__sync_print(struct i915_syncmap *p,
char *buf, unsigned long *sz,
unsigned int depth,
unsigned int last,
unsigned int idx)
{
unsigned long len;
unsigned int i, X;
if (depth) {
unsigned int d;
for (d = 0; d < depth - 1; d++) {
if (last & BIT(depth - d - 1))
len = scnprintf(buf, *sz, "| ");
else
len = scnprintf(buf, *sz, " ");
buf += len;
*sz -= len;
}
len = scnprintf(buf, *sz, "%x-> ", idx);
buf += len;
*sz -= len;
}
/* We mark bits after the prefix as "X" */
len = scnprintf(buf, *sz, "0x%016llx", p->prefix << p->height << SHIFT);
buf += len;
*sz -= len;
X = (p->height + SHIFT) / 4;
scnprintf(buf - X, *sz + X, "%*s", X, "XXXXXXXXXXXXXXXXX");
if (!p->height) {
for_each_set_bit(i, (unsigned long *)&p->bitmap, KSYNCMAP) {
len = scnprintf(buf, *sz, " %x:%x,",
i, __sync_seqno(p)[i]);
buf += len;
*sz -= len;
}
buf -= 1;
*sz += 1;
}
len = scnprintf(buf, *sz, "\n");
buf += len;
*sz -= len;
if (p->height) {
for_each_set_bit(i, (unsigned long *)&p->bitmap, KSYNCMAP) {
buf = __sync_print(__sync_child(p)[i], buf, sz,
depth + 1,
last << 1 | !!(p->bitmap >> (i + 1)),
i);
}
}
return buf;
}
static bool
i915_syncmap_print_to_buf(struct i915_syncmap *p, char *buf, unsigned long sz)
{
if (!p)
return false;
while (p->parent)
p = p->parent;
__sync_print(p, buf, &sz, 0, 1, 0);
return true;
}
static int check_syncmap_free(struct i915_syncmap **sync)
{
i915_syncmap_free(sync);
if (*sync) {
pr_err("sync not cleared after free\n");
return -EINVAL;
}
return 0;
}
static int dump_syncmap(struct i915_syncmap *sync, int err)
{
char *buf;
if (!err)
return check_syncmap_free(&sync);
buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
if (!buf)
goto skip;
if (i915_syncmap_print_to_buf(sync, buf, PAGE_SIZE))
pr_err("%s", buf);
kfree(buf);
skip:
i915_syncmap_free(&sync);
return err;
}
static int igt_syncmap_init(void *arg)
{
struct i915_syncmap *sync = (void *)~0ul;
/*
* Cursory check that we can initialise a random pointer and transform
* it into the root pointer of a syncmap.
*/
i915_syncmap_init(&sync);
return check_syncmap_free(&sync);
}
static int check_seqno(struct i915_syncmap *leaf, unsigned int idx, u32 seqno)
{
if (leaf->height) {
pr_err("%s: not a leaf, height is %d\n",
__func__, leaf->height);
return -EINVAL;
}
if (__sync_seqno(leaf)[idx] != seqno) {
pr_err("%s: seqno[%d], found %x, expected %x\n",
__func__, idx, __sync_seqno(leaf)[idx], seqno);
return -EINVAL;
}
return 0;
}
static int check_one(struct i915_syncmap **sync, u64 context, u32 seqno)
{
int err;
err = i915_syncmap_set(sync, context, seqno);
if (err)
return err;
if ((*sync)->height) {
pr_err("Inserting first context=%llx did not return leaf (height=%d, prefix=%llx\n",
context, (*sync)->height, (*sync)->prefix);
return -EINVAL;
}
if ((*sync)->parent) {
pr_err("Inserting first context=%llx created branches!\n",
context);
return -EINVAL;
}
if (hweight32((*sync)->bitmap) != 1) {
pr_err("First bitmap does not contain a single entry, found %x (count=%d)!\n",
(*sync)->bitmap, hweight32((*sync)->bitmap));
return -EINVAL;
}
err = check_seqno((*sync), ilog2((*sync)->bitmap), seqno);
if (err)
return err;
if (!i915_syncmap_is_later(sync, context, seqno)) {
pr_err("Lookup of first context=%llx/seqno=%x failed!\n",
context, seqno);
return -EINVAL;
}
return 0;
}
static int igt_syncmap_one(void *arg)
{
I915_RND_STATE(prng);
IGT_TIMEOUT(end_time);
struct i915_syncmap *sync;
unsigned long max = 1;
int err;
/*
* Check that inserting a new id, creates a leaf and only that leaf.
*/
i915_syncmap_init(&sync);
do {
u64 context = i915_prandom_u64_state(&prng);
unsigned long loop;
err = check_syncmap_free(&sync);
if (err)
goto out;
for (loop = 0; loop <= max; loop++) {
err = check_one(&sync, context,
prandom_u32_state(&prng));
if (err)
goto out;
}
max++;
} while (!__igt_timeout(end_time, NULL));
pr_debug("%s: Completed %lu single insertions\n",
__func__, max * (max - 1) / 2);
out:
return dump_syncmap(sync, err);
}
static int check_leaf(struct i915_syncmap **sync, u64 context, u32 seqno)
{
int err;
err = i915_syncmap_set(sync, context, seqno);
if (err)
return err;
if ((*sync)->height) {
pr_err("Inserting context=%llx did not return leaf (height=%d, prefix=%llx\n",
context, (*sync)->height, (*sync)->prefix);
return -EINVAL;
}
if (hweight32((*sync)->bitmap) != 1) {
pr_err("First entry into leaf (context=%llx) does not contain a single entry, found %x (count=%d)!\n",
context, (*sync)->bitmap, hweight32((*sync)->bitmap));
return -EINVAL;
}
err = check_seqno((*sync), ilog2((*sync)->bitmap), seqno);
if (err)
return err;
if (!i915_syncmap_is_later(sync, context, seqno)) {
pr_err("Lookup of first entry context=%llx/seqno=%x failed!\n",
context, seqno);
return -EINVAL;
}
return 0;
}
static int igt_syncmap_join_above(void *arg)
{
struct i915_syncmap *sync;
unsigned int pass, order;
int err;
i915_syncmap_init(&sync);
/*
* When we have a new id that doesn't fit inside the existing tree,
* we need to add a new layer above.
*
* 1: 0x00000001
* 2: 0x00000010
* 3: 0x00000100
* 4: 0x00001000
* ...
* Each pass the common prefix shrinks and we have to insert a join.
* Each join will only contain two branches, the latest of which
* is always a leaf.
*
* If we then reuse the same set of contexts, we expect to build an
* identical tree.
*/
for (pass = 0; pass < 3; pass++) {
for (order = 0; order < 64; order += SHIFT) {
u64 context = BIT_ULL(order);
struct i915_syncmap *join;
err = check_leaf(&sync, context, 0);
if (err)
goto out;
join = sync->parent;
if (!join) /* very first insert will have no parents */
continue;
if (!join->height) {
pr_err("Parent with no height!\n");
err = -EINVAL;
goto out;
}
if (hweight32(join->bitmap) != 2) {
pr_err("Join does not have 2 children: %x (%d)\n",
join->bitmap, hweight32(join->bitmap));
err = -EINVAL;
goto out;
}
if (__sync_child(join)[__sync_branch_idx(join, context)] != sync) {
pr_err("Leaf misplaced in parent!\n");
err = -EINVAL;
goto out;
}
}
}
out:
return dump_syncmap(sync, err);
}
static int igt_syncmap_join_below(void *arg)
{
struct i915_syncmap *sync;
unsigned int step, order, idx;
int err = -ENODEV;
i915_syncmap_init(&sync);
/*
* Check that we can split a compacted branch by replacing it with
* a join.
*/
for (step = 0; step < KSYNCMAP; step++) {
for (order = 64 - SHIFT; order > 0; order -= SHIFT) {
u64 context = step * BIT_ULL(order);
err = i915_syncmap_set(&sync, context, 0);
if (err)
goto out;
if (sync->height) {
pr_err("Inserting context=%llx (order=%d, step=%d) did not return leaf (height=%d, prefix=%llx\n",
context, order, step, sync->height, sync->prefix);
err = -EINVAL;
goto out;
}
}
}
for (step = 0; step < KSYNCMAP; step++) {
for (order = SHIFT; order < 64; order += SHIFT) {
u64 context = step * BIT_ULL(order);
if (!i915_syncmap_is_later(&sync, context, 0)) {
pr_err("1: context %llx (order=%d, step=%d) not found\n",
context, order, step);
err = -EINVAL;
goto out;
}
for (idx = 1; idx < KSYNCMAP; idx++) {
if (i915_syncmap_is_later(&sync, context + idx, 0)) {
pr_err("1: context %llx (order=%d, step=%d) should not exist\n",
context + idx, order, step);
err = -EINVAL;
goto out;
}
}
}
}
for (order = SHIFT; order < 64; order += SHIFT) {
for (step = 0; step < KSYNCMAP; step++) {
u64 context = step * BIT_ULL(order);
if (!i915_syncmap_is_later(&sync, context, 0)) {
pr_err("2: context %llx (order=%d, step=%d) not found\n",
context, order, step);
err = -EINVAL;
goto out;
}
}
}
out:
return dump_syncmap(sync, err);
}
static int igt_syncmap_neighbours(void *arg)
{
I915_RND_STATE(prng);
IGT_TIMEOUT(end_time);
struct i915_syncmap *sync;
int err = -ENODEV;
/*
* Each leaf holds KSYNCMAP seqno. Check that when we create KSYNCMAP
* neighbouring ids, they all fit into the same leaf.
*/
i915_syncmap_init(&sync);
do {
u64 context = i915_prandom_u64_state(&prng) & ~MASK;
unsigned int idx;
if (i915_syncmap_is_later(&sync, context, 0)) /* Skip repeats */
continue;
for (idx = 0; idx < KSYNCMAP; idx++) {
err = i915_syncmap_set(&sync, context + idx, 0);
if (err)
goto out;
if (sync->height) {
pr_err("Inserting context=%llx did not return leaf (height=%d, prefix=%llx\n",
context, sync->height, sync->prefix);
err = -EINVAL;
goto out;
}
if (sync->bitmap != BIT(idx + 1) - 1) {
pr_err("Inserting neighbouring context=0x%llx+%d, did not fit into the same leaf bitmap=%x (%d), expected %lx (%d)\n",
context, idx,
sync->bitmap, hweight32(sync->bitmap),
BIT(idx + 1) - 1, idx + 1);
err = -EINVAL;
goto out;
}
}
} while (!__igt_timeout(end_time, NULL));
out:
return dump_syncmap(sync, err);
}
static int igt_syncmap_compact(void *arg)
{
struct i915_syncmap *sync;
unsigned int idx, order;
int err = -ENODEV;
i915_syncmap_init(&sync);
/*
* The syncmap are "space efficient" compressed radix trees - any
* branch with only one child is skipped and replaced by the child.
*
* If we construct a tree with ids that are neighbouring at a non-zero
* height, we form a join but each child of that join is directly a
* leaf holding the single id.
*/
for (order = SHIFT; order < 64; order += SHIFT) {
err = check_syncmap_free(&sync);
if (err)
goto out;
/* Create neighbours in the parent */
for (idx = 0; idx < KSYNCMAP; idx++) {
u64 context = idx * BIT_ULL(order) + idx;
err = i915_syncmap_set(&sync, context, 0);
if (err)
goto out;
if (sync->height) {
pr_err("Inserting context=%llx (order=%d, idx=%d) did not return leaf (height=%d, prefix=%llx\n",
context, order, idx,
sync->height, sync->prefix);
err = -EINVAL;
goto out;
}
}
sync = sync->parent;
if (sync->parent) {
pr_err("Parent (join) of last leaf was not the sync!\n");
err = -EINVAL;
goto out;
}
if (sync->height != order) {
pr_err("Join does not have the expected height, found %d, expected %d\n",
sync->height, order);
err = -EINVAL;
goto out;
}
if (sync->bitmap != BIT(KSYNCMAP) - 1) {
pr_err("Join is not full!, found %x (%d) expected %lx (%d)\n",
sync->bitmap, hweight32(sync->bitmap),
BIT(KSYNCMAP) - 1, KSYNCMAP);
err = -EINVAL;
goto out;
}
/* Each of our children should be a leaf */
for (idx = 0; idx < KSYNCMAP; idx++) {
struct i915_syncmap *leaf = __sync_child(sync)[idx];
if (leaf->height) {
pr_err("Child %d is a not leaf!\n", idx);
err = -EINVAL;
goto out;
}
if (leaf->parent != sync) {
pr_err("Child %d is not attached to us!\n",
idx);
err = -EINVAL;
goto out;
}
if (!is_power_of_2(leaf->bitmap)) {
pr_err("Child %d holds more than one id, found %x (%d)\n",
idx, leaf->bitmap, hweight32(leaf->bitmap));
err = -EINVAL;
goto out;
}
if (leaf->bitmap != BIT(idx)) {
pr_err("Child %d has wrong seqno idx, found %d, expected %d\n",
idx, ilog2(leaf->bitmap), idx);
err = -EINVAL;
goto out;
}
}
}
out:
return dump_syncmap(sync, err);
}
static int igt_syncmap_random(void *arg)
{
I915_RND_STATE(prng);
IGT_TIMEOUT(end_time);
struct i915_syncmap *sync;
unsigned long count, phase, i;
u32 seqno;
int err;
i915_syncmap_init(&sync);
/*
* Having tried to test the individual operations within i915_syncmap,
* run a smoketest exploring the entire u64 space with random
* insertions.
*/
count = 0;
phase = jiffies + HZ/100 + 1;
do {
u64 context = i915_prandom_u64_state(&prng);
err = i915_syncmap_set(&sync, context, 0);
if (err)
goto out;
count++;
} while (!time_after(jiffies, phase));
seqno = 0;
phase = 0;
do {
I915_RND_STATE(ctx);
u32 last_seqno = seqno;
bool expect;
seqno = prandom_u32_state(&prng);
expect = seqno_later(last_seqno, seqno);
for (i = 0; i < count; i++) {
u64 context = i915_prandom_u64_state(&ctx);
if (i915_syncmap_is_later(&sync, context, seqno) != expect) {
pr_err("context=%llu, last=%u this=%u did not match expectation (%d)\n",
context, last_seqno, seqno, expect);
err = -EINVAL;
goto out;
}
err = i915_syncmap_set(&sync, context, seqno);
if (err)
goto out;
}
phase++;
} while (!__igt_timeout(end_time, NULL));
pr_debug("Completed %lu passes, each of %lu contexts\n", phase, count);
out:
return dump_syncmap(sync, err);
}
int i915_syncmap_mock_selftests(void)
{
static const struct i915_subtest tests[] = {
SUBTEST(igt_syncmap_init),
SUBTEST(igt_syncmap_one),
SUBTEST(igt_syncmap_join_above),
SUBTEST(igt_syncmap_join_below),
SUBTEST(igt_syncmap_neighbours),
SUBTEST(igt_syncmap_compact),
SUBTEST(igt_syncmap_random),
};
return i915_subtests(tests, NULL);
}
| linux-master | drivers/gpu/drm/i915/selftests/i915_syncmap.c |
/*
* Copyright © 2016 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
#include "gem/selftests/igt_gem_utils.h"
#include "gt/mock_engine.h"
#include "mock_request.h"
struct i915_request *
mock_request(struct intel_context *ce, unsigned long delay)
{
struct i915_request *request;
/* NB the i915->requests slab cache is enlarged to fit mock_request */
request = intel_context_create_request(ce);
if (IS_ERR(request))
return NULL;
request->mock.delay = delay;
return request;
}
bool mock_cancel_request(struct i915_request *request)
{
struct mock_engine *engine =
container_of(request->engine, typeof(*engine), base);
bool was_queued;
spin_lock_irq(&engine->hw_lock);
was_queued = !list_empty(&request->mock.link);
list_del_init(&request->mock.link);
spin_unlock_irq(&engine->hw_lock);
if (was_queued)
i915_request_unsubmit(request);
return was_queued;
}
| linux-master | drivers/gpu/drm/i915/selftests/mock_request.c |
/*
* Copyright © 2016 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
#include <linux/bitops.h>
#include <linux/kernel.h>
#include <linux/random.h>
#include <linux/slab.h>
#include <linux/types.h>
#include "i915_random.h"
#include "i915_utils.h"
u64 i915_prandom_u64_state(struct rnd_state *rnd)
{
u64 x;
x = prandom_u32_state(rnd);
x <<= 32;
x |= prandom_u32_state(rnd);
return x;
}
void i915_prandom_shuffle(void *arr, size_t elsz, size_t count,
struct rnd_state *state)
{
char stack[128];
if (WARN_ON(elsz > sizeof(stack) || count > U32_MAX))
return;
if (!elsz || !count)
return;
/* Fisher-Yates shuffle courtesy of Knuth */
while (--count) {
size_t swp;
swp = i915_prandom_u32_max_state(count + 1, state);
if (swp == count)
continue;
memcpy(stack, arr + count * elsz, elsz);
memcpy(arr + count * elsz, arr + swp * elsz, elsz);
memcpy(arr + swp * elsz, stack, elsz);
}
}
void i915_random_reorder(unsigned int *order, unsigned int count,
struct rnd_state *state)
{
i915_prandom_shuffle(order, sizeof(*order), count, state);
}
unsigned int *i915_random_order(unsigned int count, struct rnd_state *state)
{
unsigned int *order, i;
order = kmalloc_array(count, sizeof(*order),
GFP_KERNEL | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
if (!order)
return order;
for (i = 0; i < count; i++)
order[i] = i;
i915_random_reorder(order, count, state);
return order;
}
u64 igt_random_offset(struct rnd_state *state,
u64 start, u64 end,
u64 len, u64 align)
{
u64 range, addr;
BUG_ON(range_overflows(start, len, end));
BUG_ON(round_up(start, align) > round_down(end - len, align));
range = round_down(end - len, align) - round_up(start, align);
if (range) {
addr = i915_prandom_u64_state(state);
div64_u64_rem(addr, range, &addr);
start += addr;
}
return round_up(start, align);
}
| linux-master | drivers/gpu/drm/i915/selftests/i915_random.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2019 Intel Corporation
*/
#include <linux/prime_numbers.h>
#include <linux/sort.h>
#include <drm/drm_buddy.h>
#include "../i915_selftest.h"
#include "mock_drm.h"
#include "mock_gem_device.h"
#include "mock_region.h"
#include "gem/i915_gem_context.h"
#include "gem/i915_gem_lmem.h"
#include "gem/i915_gem_region.h"
#include "gem/i915_gem_ttm.h"
#include "gem/selftests/igt_gem_utils.h"
#include "gem/selftests/mock_context.h"
#include "gt/intel_engine_pm.h"
#include "gt/intel_engine_user.h"
#include "gt/intel_gt.h"
#include "gt/intel_migrate.h"
#include "i915_memcpy.h"
#include "i915_ttm_buddy_manager.h"
#include "selftests/igt_flush_test.h"
#include "selftests/i915_random.h"
static void close_objects(struct intel_memory_region *mem,
struct list_head *objects)
{
struct drm_i915_private *i915 = mem->i915;
struct drm_i915_gem_object *obj, *on;
list_for_each_entry_safe(obj, on, objects, st_link) {
i915_gem_object_lock(obj, NULL);
if (i915_gem_object_has_pinned_pages(obj))
i915_gem_object_unpin_pages(obj);
/* No polluting the memory region between tests */
__i915_gem_object_put_pages(obj);
i915_gem_object_unlock(obj);
list_del(&obj->st_link);
i915_gem_object_put(obj);
}
cond_resched();
i915_gem_drain_freed_objects(i915);
}
static int igt_mock_fill(void *arg)
{
struct intel_memory_region *mem = arg;
resource_size_t total = resource_size(&mem->region);
resource_size_t page_size;
resource_size_t rem;
unsigned long max_pages;
unsigned long page_num;
LIST_HEAD(objects);
int err = 0;
page_size = PAGE_SIZE;
max_pages = div64_u64(total, page_size);
rem = total;
for_each_prime_number_from(page_num, 1, max_pages) {
resource_size_t size = page_num * page_size;
struct drm_i915_gem_object *obj;
obj = i915_gem_object_create_region(mem, size, 0, 0);
if (IS_ERR(obj)) {
err = PTR_ERR(obj);
break;
}
err = i915_gem_object_pin_pages_unlocked(obj);
if (err) {
i915_gem_object_put(obj);
break;
}
list_add(&obj->st_link, &objects);
rem -= size;
}
if (err == -ENOMEM)
err = 0;
if (err == -ENXIO) {
if (page_num * page_size <= rem) {
pr_err("%s failed, space still left in region\n",
__func__);
err = -EINVAL;
} else {
err = 0;
}
}
close_objects(mem, &objects);
return err;
}
static struct drm_i915_gem_object *
igt_object_create(struct intel_memory_region *mem,
struct list_head *objects,
u64 size,
unsigned int flags)
{
struct drm_i915_gem_object *obj;
int err;
obj = i915_gem_object_create_region(mem, size, 0, flags);
if (IS_ERR(obj))
return obj;
err = i915_gem_object_pin_pages_unlocked(obj);
if (err)
goto put;
list_add(&obj->st_link, objects);
return obj;
put:
i915_gem_object_put(obj);
return ERR_PTR(err);
}
static void igt_object_release(struct drm_i915_gem_object *obj)
{
i915_gem_object_lock(obj, NULL);
i915_gem_object_unpin_pages(obj);
__i915_gem_object_put_pages(obj);
i915_gem_object_unlock(obj);
list_del(&obj->st_link);
i915_gem_object_put(obj);
}
static bool is_contiguous(struct drm_i915_gem_object *obj)
{
struct scatterlist *sg;
dma_addr_t addr = -1;
for (sg = obj->mm.pages->sgl; sg; sg = sg_next(sg)) {
if (addr != -1 && sg_dma_address(sg) != addr)
return false;
addr = sg_dma_address(sg) + sg_dma_len(sg);
}
return true;
}
static int igt_mock_reserve(void *arg)
{
struct intel_memory_region *mem = arg;
struct drm_i915_private *i915 = mem->i915;
resource_size_t avail = resource_size(&mem->region);
struct drm_i915_gem_object *obj;
const u32 chunk_size = SZ_32M;
u32 i, offset, count, *order;
u64 allocated, cur_avail;
I915_RND_STATE(prng);
LIST_HEAD(objects);
int err = 0;
count = avail / chunk_size;
order = i915_random_order(count, &prng);
if (!order)
return 0;
mem = mock_region_create(i915, 0, SZ_2G, I915_GTT_PAGE_SIZE_4K, 0, 0);
if (IS_ERR(mem)) {
pr_err("failed to create memory region\n");
err = PTR_ERR(mem);
goto out_free_order;
}
/* Reserve a bunch of ranges within the region */
for (i = 0; i < count; ++i) {
u64 start = order[i] * chunk_size;
u64 size = i915_prandom_u32_max_state(chunk_size, &prng);
/* Allow for some really big holes */
if (!size)
continue;
size = round_up(size, PAGE_SIZE);
offset = igt_random_offset(&prng, 0, chunk_size, size,
PAGE_SIZE);
err = intel_memory_region_reserve(mem, start + offset, size);
if (err) {
pr_err("%s failed to reserve range", __func__);
goto out_close;
}
/* XXX: maybe sanity check the block range here? */
avail -= size;
}
/* Try to see if we can allocate from the remaining space */
allocated = 0;
cur_avail = avail;
do {
u32 size = i915_prandom_u32_max_state(cur_avail, &prng);
size = max_t(u32, round_up(size, PAGE_SIZE), PAGE_SIZE);
obj = igt_object_create(mem, &objects, size, 0);
if (IS_ERR(obj)) {
if (PTR_ERR(obj) == -ENXIO)
break;
err = PTR_ERR(obj);
goto out_close;
}
cur_avail -= size;
allocated += size;
} while (1);
if (allocated != avail) {
pr_err("%s mismatch between allocation and free space", __func__);
err = -EINVAL;
}
out_close:
close_objects(mem, &objects);
intel_memory_region_destroy(mem);
out_free_order:
kfree(order);
return err;
}
static int igt_mock_contiguous(void *arg)
{
struct intel_memory_region *mem = arg;
struct drm_i915_gem_object *obj;
unsigned long n_objects;
LIST_HEAD(objects);
LIST_HEAD(holes);
I915_RND_STATE(prng);
resource_size_t total;
resource_size_t min;
u64 target;
int err = 0;
total = resource_size(&mem->region);
/* Min size */
obj = igt_object_create(mem, &objects, PAGE_SIZE,
I915_BO_ALLOC_CONTIGUOUS);
if (IS_ERR(obj))
return PTR_ERR(obj);
if (!is_contiguous(obj)) {
pr_err("%s min object spans disjoint sg entries\n", __func__);
err = -EINVAL;
goto err_close_objects;
}
igt_object_release(obj);
/* Max size */
obj = igt_object_create(mem, &objects, total, I915_BO_ALLOC_CONTIGUOUS);
if (IS_ERR(obj))
return PTR_ERR(obj);
if (!is_contiguous(obj)) {
pr_err("%s max object spans disjoint sg entries\n", __func__);
err = -EINVAL;
goto err_close_objects;
}
igt_object_release(obj);
/* Internal fragmentation should not bleed into the object size */
target = i915_prandom_u64_state(&prng);
div64_u64_rem(target, total, &target);
target = round_up(target, PAGE_SIZE);
target = max_t(u64, PAGE_SIZE, target);
obj = igt_object_create(mem, &objects, target,
I915_BO_ALLOC_CONTIGUOUS);
if (IS_ERR(obj))
return PTR_ERR(obj);
if (obj->base.size != target) {
pr_err("%s obj->base.size(%zx) != target(%llx)\n", __func__,
obj->base.size, target);
err = -EINVAL;
goto err_close_objects;
}
if (!is_contiguous(obj)) {
pr_err("%s object spans disjoint sg entries\n", __func__);
err = -EINVAL;
goto err_close_objects;
}
igt_object_release(obj);
/*
* Try to fragment the address space, such that half of it is free, but
* the max contiguous block size is SZ_64K.
*/
target = SZ_64K;
n_objects = div64_u64(total, target);
while (n_objects--) {
struct list_head *list;
if (n_objects % 2)
list = &holes;
else
list = &objects;
obj = igt_object_create(mem, list, target,
I915_BO_ALLOC_CONTIGUOUS);
if (IS_ERR(obj)) {
err = PTR_ERR(obj);
goto err_close_objects;
}
}
close_objects(mem, &holes);
min = target;
target = total >> 1;
/* Make sure we can still allocate all the fragmented space */
obj = igt_object_create(mem, &objects, target, 0);
if (IS_ERR(obj)) {
err = PTR_ERR(obj);
goto err_close_objects;
}
igt_object_release(obj);
/*
* Even though we have enough free space, we don't have a big enough
* contiguous block. Make sure that holds true.
*/
do {
bool should_fail = target > min;
obj = igt_object_create(mem, &objects, target,
I915_BO_ALLOC_CONTIGUOUS);
if (should_fail != IS_ERR(obj)) {
pr_err("%s target allocation(%llx) mismatch\n",
__func__, target);
err = -EINVAL;
goto err_close_objects;
}
target >>= 1;
} while (target >= PAGE_SIZE);
err_close_objects:
list_splice_tail(&holes, &objects);
close_objects(mem, &objects);
return err;
}
static int igt_mock_splintered_region(void *arg)
{
struct intel_memory_region *mem = arg;
struct drm_i915_private *i915 = mem->i915;
struct i915_ttm_buddy_resource *res;
struct drm_i915_gem_object *obj;
struct drm_buddy *mm;
unsigned int expected_order;
LIST_HEAD(objects);
u64 size;
int err = 0;
/*
* Sanity check we can still allocate everything even if the
* mm.max_order != mm.size. i.e our starting address space size is not a
* power-of-two.
*/
size = (SZ_4G - 1) & PAGE_MASK;
mem = mock_region_create(i915, 0, size, PAGE_SIZE, 0, 0);
if (IS_ERR(mem))
return PTR_ERR(mem);
obj = igt_object_create(mem, &objects, size, 0);
if (IS_ERR(obj)) {
err = PTR_ERR(obj);
goto out_close;
}
res = to_ttm_buddy_resource(obj->mm.res);
mm = res->mm;
if (mm->size != size) {
pr_err("%s size mismatch(%llu != %llu)\n",
__func__, mm->size, size);
err = -EINVAL;
goto out_put;
}
expected_order = get_order(rounddown_pow_of_two(size));
if (mm->max_order != expected_order) {
pr_err("%s order mismatch(%u != %u)\n",
__func__, mm->max_order, expected_order);
err = -EINVAL;
goto out_put;
}
close_objects(mem, &objects);
/*
* While we should be able allocate everything without any flag
* restrictions, if we consider I915_BO_ALLOC_CONTIGUOUS then we are
* actually limited to the largest power-of-two for the region size i.e
* max_order, due to the inner workings of the buddy allocator. So make
* sure that does indeed hold true.
*/
obj = igt_object_create(mem, &objects, size, I915_BO_ALLOC_CONTIGUOUS);
if (!IS_ERR(obj)) {
pr_err("%s too large contiguous allocation was not rejected\n",
__func__);
err = -EINVAL;
goto out_close;
}
obj = igt_object_create(mem, &objects, rounddown_pow_of_two(size),
I915_BO_ALLOC_CONTIGUOUS);
if (IS_ERR(obj)) {
pr_err("%s largest possible contiguous allocation failed\n",
__func__);
err = PTR_ERR(obj);
goto out_close;
}
out_close:
close_objects(mem, &objects);
out_put:
intel_memory_region_destroy(mem);
return err;
}
#ifndef SZ_8G
#define SZ_8G BIT_ULL(33)
#endif
static int igt_mock_max_segment(void *arg)
{
struct intel_memory_region *mem = arg;
struct drm_i915_private *i915 = mem->i915;
struct i915_ttm_buddy_resource *res;
struct drm_i915_gem_object *obj;
struct drm_buddy_block *block;
struct drm_buddy *mm;
struct list_head *blocks;
struct scatterlist *sg;
I915_RND_STATE(prng);
LIST_HEAD(objects);
unsigned int max_segment;
unsigned int ps;
u64 size;
int err = 0;
/*
* While we may create very large contiguous blocks, we may need
* to break those down for consumption elsewhere. In particular,
* dma-mapping with scatterlist elements have an implicit limit of
* UINT_MAX on each element.
*/
size = SZ_8G;
ps = PAGE_SIZE;
if (i915_prandom_u64_state(&prng) & 1)
ps = SZ_64K; /* For something like DG2 */
max_segment = round_down(UINT_MAX, ps);
mem = mock_region_create(i915, 0, size, ps, 0, 0);
if (IS_ERR(mem))
return PTR_ERR(mem);
obj = igt_object_create(mem, &objects, size, 0);
if (IS_ERR(obj)) {
err = PTR_ERR(obj);
goto out_put;
}
res = to_ttm_buddy_resource(obj->mm.res);
blocks = &res->blocks;
mm = res->mm;
size = 0;
list_for_each_entry(block, blocks, link) {
if (drm_buddy_block_size(mm, block) > size)
size = drm_buddy_block_size(mm, block);
}
if (size < max_segment) {
pr_err("%s: Failed to create a huge contiguous block [> %u], largest block %lld\n",
__func__, max_segment, size);
err = -EINVAL;
goto out_close;
}
for (sg = obj->mm.pages->sgl; sg; sg = sg_next(sg)) {
dma_addr_t daddr = sg_dma_address(sg);
if (sg->length > max_segment) {
pr_err("%s: Created an oversized scatterlist entry, %u > %u\n",
__func__, sg->length, max_segment);
err = -EINVAL;
goto out_close;
}
if (!IS_ALIGNED(daddr, ps)) {
pr_err("%s: Created an unaligned scatterlist entry, addr=%pa, ps=%u\n",
__func__, &daddr, ps);
err = -EINVAL;
goto out_close;
}
}
out_close:
close_objects(mem, &objects);
out_put:
intel_memory_region_destroy(mem);
return err;
}
static u64 igt_object_mappable_total(struct drm_i915_gem_object *obj)
{
struct intel_memory_region *mr = obj->mm.region;
struct i915_ttm_buddy_resource *bman_res =
to_ttm_buddy_resource(obj->mm.res);
struct drm_buddy *mm = bman_res->mm;
struct drm_buddy_block *block;
u64 total;
total = 0;
list_for_each_entry(block, &bman_res->blocks, link) {
u64 start = drm_buddy_block_offset(block);
u64 end = start + drm_buddy_block_size(mm, block);
if (start < mr->io_size)
total += min_t(u64, end, mr->io_size) - start;
}
return total;
}
static int igt_mock_io_size(void *arg)
{
struct intel_memory_region *mr = arg;
struct drm_i915_private *i915 = mr->i915;
struct drm_i915_gem_object *obj;
u64 mappable_theft_total;
u64 io_size;
u64 total;
u64 ps;
u64 rem;
u64 size;
I915_RND_STATE(prng);
LIST_HEAD(objects);
int err = 0;
ps = SZ_4K;
if (i915_prandom_u64_state(&prng) & 1)
ps = SZ_64K; /* For something like DG2 */
div64_u64_rem(i915_prandom_u64_state(&prng), SZ_8G, &total);
total = round_down(total, ps);
total = max_t(u64, total, SZ_1G);
div64_u64_rem(i915_prandom_u64_state(&prng), total - ps, &io_size);
io_size = round_down(io_size, ps);
io_size = max_t(u64, io_size, SZ_256M); /* 256M seems to be the common lower limit */
pr_info("%s with ps=%llx, io_size=%llx, total=%llx\n",
__func__, ps, io_size, total);
mr = mock_region_create(i915, 0, total, ps, 0, io_size);
if (IS_ERR(mr)) {
err = PTR_ERR(mr);
goto out_err;
}
mappable_theft_total = 0;
rem = total - io_size;
do {
div64_u64_rem(i915_prandom_u64_state(&prng), rem, &size);
size = round_down(size, ps);
size = max(size, ps);
obj = igt_object_create(mr, &objects, size,
I915_BO_ALLOC_GPU_ONLY);
if (IS_ERR(obj)) {
pr_err("%s TOPDOWN failed with rem=%llx, size=%llx\n",
__func__, rem, size);
err = PTR_ERR(obj);
goto out_close;
}
mappable_theft_total += igt_object_mappable_total(obj);
rem -= size;
} while (rem);
pr_info("%s mappable theft=(%lluMiB/%lluMiB), total=%lluMiB\n",
__func__,
(u64)mappable_theft_total >> 20,
(u64)io_size >> 20,
(u64)total >> 20);
/*
* Even if we allocate all of the non-mappable portion, we should still
* be able to dip into the mappable portion.
*/
obj = igt_object_create(mr, &objects, io_size,
I915_BO_ALLOC_GPU_ONLY);
if (IS_ERR(obj)) {
pr_err("%s allocation unexpectedly failed\n", __func__);
err = PTR_ERR(obj);
goto out_close;
}
close_objects(mr, &objects);
rem = io_size;
do {
div64_u64_rem(i915_prandom_u64_state(&prng), rem, &size);
size = round_down(size, ps);
size = max(size, ps);
obj = igt_object_create(mr, &objects, size, 0);
if (IS_ERR(obj)) {
pr_err("%s MAPPABLE failed with rem=%llx, size=%llx\n",
__func__, rem, size);
err = PTR_ERR(obj);
goto out_close;
}
if (igt_object_mappable_total(obj) != size) {
pr_err("%s allocation is not mappable(size=%llx)\n",
__func__, size);
err = -EINVAL;
goto out_close;
}
rem -= size;
} while (rem);
/*
* We assume CPU access is required by default, which should result in a
* failure here, even though the non-mappable portion is free.
*/
obj = igt_object_create(mr, &objects, ps, 0);
if (!IS_ERR(obj)) {
pr_err("%s allocation unexpectedly succeeded\n", __func__);
err = -EINVAL;
goto out_close;
}
out_close:
close_objects(mr, &objects);
intel_memory_region_destroy(mr);
out_err:
if (err == -ENOMEM)
err = 0;
return err;
}
static int igt_gpu_write_dw(struct intel_context *ce,
struct i915_vma *vma,
u32 dword,
u32 value)
{
return igt_gpu_fill_dw(ce, vma, dword * sizeof(u32),
vma->size >> PAGE_SHIFT, value);
}
static int igt_cpu_check(struct drm_i915_gem_object *obj, u32 dword, u32 val)
{
unsigned long n = obj->base.size >> PAGE_SHIFT;
u32 *ptr;
int err;
err = i915_gem_object_wait(obj, 0, MAX_SCHEDULE_TIMEOUT);
if (err)
return err;
ptr = i915_gem_object_pin_map(obj, I915_MAP_WC);
if (IS_ERR(ptr))
return PTR_ERR(ptr);
ptr += dword;
while (n--) {
if (*ptr != val) {
pr_err("base[%u]=%08x, val=%08x\n",
dword, *ptr, val);
err = -EINVAL;
break;
}
ptr += PAGE_SIZE / sizeof(*ptr);
}
i915_gem_object_unpin_map(obj);
return err;
}
static int igt_gpu_write(struct i915_gem_context *ctx,
struct drm_i915_gem_object *obj)
{
struct i915_gem_engines *engines;
struct i915_gem_engines_iter it;
struct i915_address_space *vm;
struct intel_context *ce;
I915_RND_STATE(prng);
IGT_TIMEOUT(end_time);
unsigned int count;
struct i915_vma *vma;
int *order;
int i, n;
int err = 0;
GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
n = 0;
count = 0;
for_each_gem_engine(ce, i915_gem_context_lock_engines(ctx), it) {
count++;
if (!intel_engine_can_store_dword(ce->engine))
continue;
vm = ce->vm;
n++;
}
i915_gem_context_unlock_engines(ctx);
if (!n)
return 0;
order = i915_random_order(count * count, &prng);
if (!order)
return -ENOMEM;
vma = i915_vma_instance(obj, vm, NULL);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto out_free;
}
err = i915_vma_pin(vma, 0, 0, PIN_USER);
if (err)
goto out_free;
i = 0;
engines = i915_gem_context_lock_engines(ctx);
do {
u32 rng = prandom_u32_state(&prng);
u32 dword = offset_in_page(rng) / 4;
ce = engines->engines[order[i] % engines->num_engines];
i = (i + 1) % (count * count);
if (!ce || !intel_engine_can_store_dword(ce->engine))
continue;
err = igt_gpu_write_dw(ce, vma, dword, rng);
if (err)
break;
i915_gem_object_lock(obj, NULL);
err = igt_cpu_check(obj, dword, rng);
i915_gem_object_unlock(obj);
if (err)
break;
} while (!__igt_timeout(end_time, NULL));
i915_gem_context_unlock_engines(ctx);
out_free:
kfree(order);
if (err == -ENOMEM)
err = 0;
return err;
}
static int igt_lmem_create(void *arg)
{
struct drm_i915_private *i915 = arg;
struct drm_i915_gem_object *obj;
int err = 0;
obj = i915_gem_object_create_lmem(i915, PAGE_SIZE, 0);
if (IS_ERR(obj))
return PTR_ERR(obj);
err = i915_gem_object_pin_pages_unlocked(obj);
if (err)
goto out_put;
i915_gem_object_unpin_pages(obj);
out_put:
i915_gem_object_put(obj);
return err;
}
static int igt_lmem_create_with_ps(void *arg)
{
struct drm_i915_private *i915 = arg;
int err = 0;
u32 ps;
for (ps = PAGE_SIZE; ps <= SZ_1G; ps <<= 1) {
struct drm_i915_gem_object *obj;
dma_addr_t daddr;
obj = __i915_gem_object_create_lmem_with_ps(i915, ps, ps, 0);
if (IS_ERR(obj)) {
err = PTR_ERR(obj);
if (err == -ENXIO || err == -E2BIG) {
pr_info("%s not enough lmem for ps(%u) err=%d\n",
__func__, ps, err);
err = 0;
}
break;
}
if (obj->base.size != ps) {
pr_err("%s size(%zu) != ps(%u)\n",
__func__, obj->base.size, ps);
err = -EINVAL;
goto out_put;
}
i915_gem_object_lock(obj, NULL);
err = i915_gem_object_pin_pages(obj);
if (err) {
if (err == -ENXIO || err == -E2BIG || err == -ENOMEM) {
pr_info("%s not enough lmem for ps(%u) err=%d\n",
__func__, ps, err);
err = 0;
}
goto out_put;
}
daddr = i915_gem_object_get_dma_address(obj, 0);
if (!IS_ALIGNED(daddr, ps)) {
pr_err("%s daddr(%pa) not aligned with ps(%u)\n",
__func__, &daddr, ps);
err = -EINVAL;
goto out_unpin;
}
out_unpin:
i915_gem_object_unpin_pages(obj);
__i915_gem_object_put_pages(obj);
out_put:
i915_gem_object_unlock(obj);
i915_gem_object_put(obj);
if (err)
break;
}
return err;
}
static int igt_lmem_create_cleared_cpu(void *arg)
{
struct drm_i915_private *i915 = arg;
I915_RND_STATE(prng);
IGT_TIMEOUT(end_time);
u32 size, i;
int err;
i915_gem_drain_freed_objects(i915);
size = max_t(u32, PAGE_SIZE, i915_prandom_u32_max_state(SZ_32M, &prng));
size = round_up(size, PAGE_SIZE);
i = 0;
do {
struct drm_i915_gem_object *obj;
unsigned int flags;
u32 dword, val;
void *vaddr;
/*
* Alternate between cleared and uncleared allocations, while
* also dirtying the pages each time to check that the pages are
* always cleared if requested, since we should get some overlap
* of the underlying pages, if not all, since we are the only
* user.
*/
flags = I915_BO_ALLOC_CPU_CLEAR;
if (i & 1)
flags = 0;
obj = i915_gem_object_create_lmem(i915, size, flags);
if (IS_ERR(obj))
return PTR_ERR(obj);
i915_gem_object_lock(obj, NULL);
err = i915_gem_object_pin_pages(obj);
if (err)
goto out_put;
dword = i915_prandom_u32_max_state(PAGE_SIZE / sizeof(u32),
&prng);
if (flags & I915_BO_ALLOC_CPU_CLEAR) {
err = igt_cpu_check(obj, dword, 0);
if (err) {
pr_err("%s failed with size=%u, flags=%u\n",
__func__, size, flags);
goto out_unpin;
}
}
vaddr = i915_gem_object_pin_map(obj, I915_MAP_WC);
if (IS_ERR(vaddr)) {
err = PTR_ERR(vaddr);
goto out_unpin;
}
val = prandom_u32_state(&prng);
memset32(vaddr, val, obj->base.size / sizeof(u32));
i915_gem_object_flush_map(obj);
i915_gem_object_unpin_map(obj);
out_unpin:
i915_gem_object_unpin_pages(obj);
__i915_gem_object_put_pages(obj);
out_put:
i915_gem_object_unlock(obj);
i915_gem_object_put(obj);
if (err)
break;
++i;
} while (!__igt_timeout(end_time, NULL));
pr_info("%s completed (%u) iterations\n", __func__, i);
return err;
}
static int igt_lmem_write_gpu(void *arg)
{
struct drm_i915_private *i915 = arg;
struct drm_i915_gem_object *obj;
struct i915_gem_context *ctx;
struct file *file;
I915_RND_STATE(prng);
u32 sz;
int err;
file = mock_file(i915);
if (IS_ERR(file))
return PTR_ERR(file);
ctx = live_context(i915, file);
if (IS_ERR(ctx)) {
err = PTR_ERR(ctx);
goto out_file;
}
sz = round_up(prandom_u32_state(&prng) % SZ_32M, PAGE_SIZE);
obj = i915_gem_object_create_lmem(i915, sz, 0);
if (IS_ERR(obj)) {
err = PTR_ERR(obj);
goto out_file;
}
err = i915_gem_object_pin_pages_unlocked(obj);
if (err)
goto out_put;
err = igt_gpu_write(ctx, obj);
if (err)
pr_err("igt_gpu_write failed(%d)\n", err);
i915_gem_object_unpin_pages(obj);
out_put:
i915_gem_object_put(obj);
out_file:
fput(file);
return err;
}
static struct intel_engine_cs *
random_engine_class(struct drm_i915_private *i915,
unsigned int class,
struct rnd_state *prng)
{
struct intel_engine_cs *engine;
unsigned int count;
count = 0;
for (engine = intel_engine_lookup_user(i915, class, 0);
engine && engine->uabi_class == class;
engine = rb_entry_safe(rb_next(&engine->uabi_node),
typeof(*engine), uabi_node))
count++;
count = i915_prandom_u32_max_state(count, prng);
return intel_engine_lookup_user(i915, class, count);
}
static int igt_lmem_write_cpu(void *arg)
{
struct drm_i915_private *i915 = arg;
struct drm_i915_gem_object *obj;
I915_RND_STATE(prng);
IGT_TIMEOUT(end_time);
u32 bytes[] = {
0, /* rng placeholder */
sizeof(u32),
sizeof(u64),
64, /* cl */
PAGE_SIZE,
PAGE_SIZE - sizeof(u32),
PAGE_SIZE - sizeof(u64),
PAGE_SIZE - 64,
};
struct intel_engine_cs *engine;
struct i915_request *rq;
u32 *vaddr;
u32 sz;
u32 i;
int *order;
int count;
int err;
engine = random_engine_class(i915, I915_ENGINE_CLASS_COPY, &prng);
if (!engine)
return 0;
pr_info("%s: using %s\n", __func__, engine->name);
sz = round_up(prandom_u32_state(&prng) % SZ_32M, PAGE_SIZE);
sz = max_t(u32, 2 * PAGE_SIZE, sz);
obj = i915_gem_object_create_lmem(i915, sz, I915_BO_ALLOC_CONTIGUOUS);
if (IS_ERR(obj))
return PTR_ERR(obj);
vaddr = i915_gem_object_pin_map_unlocked(obj, I915_MAP_WC);
if (IS_ERR(vaddr)) {
err = PTR_ERR(vaddr);
goto out_put;
}
i915_gem_object_lock(obj, NULL);
err = dma_resv_reserve_fences(obj->base.resv, 1);
if (err) {
i915_gem_object_unlock(obj);
goto out_put;
}
/* Put the pages into a known state -- from the gpu for added fun */
intel_engine_pm_get(engine);
err = intel_context_migrate_clear(engine->gt->migrate.context, NULL,
obj->mm.pages->sgl,
i915_gem_get_pat_index(i915,
I915_CACHE_NONE),
true, 0xdeadbeaf, &rq);
if (rq) {
dma_resv_add_fence(obj->base.resv, &rq->fence,
DMA_RESV_USAGE_WRITE);
i915_request_put(rq);
}
intel_engine_pm_put(engine);
if (!err)
err = i915_gem_object_set_to_wc_domain(obj, true);
i915_gem_object_unlock(obj);
if (err)
goto out_unpin;
count = ARRAY_SIZE(bytes);
order = i915_random_order(count * count, &prng);
if (!order) {
err = -ENOMEM;
goto out_unpin;
}
/* A random multiple of u32, picked between [64, PAGE_SIZE - 64] */
bytes[0] = igt_random_offset(&prng, 64, PAGE_SIZE - 64, 0, sizeof(u32));
GEM_BUG_ON(!IS_ALIGNED(bytes[0], sizeof(u32)));
i = 0;
do {
u32 offset;
u32 align;
u32 dword;
u32 size;
u32 val;
size = bytes[order[i] % count];
i = (i + 1) % (count * count);
align = bytes[order[i] % count];
i = (i + 1) % (count * count);
align = max_t(u32, sizeof(u32), rounddown_pow_of_two(align));
offset = igt_random_offset(&prng, 0, obj->base.size,
size, align);
val = prandom_u32_state(&prng);
memset32(vaddr + offset / sizeof(u32), val ^ 0xdeadbeaf,
size / sizeof(u32));
/*
* Sample random dw -- don't waste precious time reading every
* single dw.
*/
dword = igt_random_offset(&prng, offset,
offset + size,
sizeof(u32), sizeof(u32));
dword /= sizeof(u32);
if (vaddr[dword] != (val ^ 0xdeadbeaf)) {
pr_err("%s vaddr[%u]=%u, val=%u, size=%u, align=%u, offset=%u\n",
__func__, dword, vaddr[dword], val ^ 0xdeadbeaf,
size, align, offset);
err = -EINVAL;
break;
}
} while (!__igt_timeout(end_time, NULL));
out_unpin:
i915_gem_object_unpin_map(obj);
out_put:
i915_gem_object_put(obj);
return err;
}
static const char *repr_type(u32 type)
{
switch (type) {
case I915_MAP_WB:
return "WB";
case I915_MAP_WC:
return "WC";
}
return "";
}
static struct drm_i915_gem_object *
create_region_for_mapping(struct intel_memory_region *mr, u64 size, u32 type,
void **out_addr)
{
struct drm_i915_gem_object *obj;
void *addr;
obj = i915_gem_object_create_region(mr, size, 0, 0);
if (IS_ERR(obj)) {
if (PTR_ERR(obj) == -ENOSPC) /* Stolen memory */
return ERR_PTR(-ENODEV);
return obj;
}
addr = i915_gem_object_pin_map_unlocked(obj, type);
if (IS_ERR(addr)) {
i915_gem_object_put(obj);
if (PTR_ERR(addr) == -ENXIO)
return ERR_PTR(-ENODEV);
return addr;
}
*out_addr = addr;
return obj;
}
static int wrap_ktime_compare(const void *A, const void *B)
{
const ktime_t *a = A, *b = B;
return ktime_compare(*a, *b);
}
static void igt_memcpy_long(void *dst, const void *src, size_t size)
{
unsigned long *tmp = dst;
const unsigned long *s = src;
size = size / sizeof(unsigned long);
while (size--)
*tmp++ = *s++;
}
static inline void igt_memcpy(void *dst, const void *src, size_t size)
{
memcpy(dst, src, size);
}
static inline void igt_memcpy_from_wc(void *dst, const void *src, size_t size)
{
i915_memcpy_from_wc(dst, src, size);
}
static int _perf_memcpy(struct intel_memory_region *src_mr,
struct intel_memory_region *dst_mr,
u64 size, u32 src_type, u32 dst_type)
{
struct drm_i915_private *i915 = src_mr->i915;
const struct {
const char *name;
void (*copy)(void *dst, const void *src, size_t size);
bool skip;
} tests[] = {
{
"memcpy",
igt_memcpy,
},
{
"memcpy_long",
igt_memcpy_long,
},
{
"memcpy_from_wc",
igt_memcpy_from_wc,
!i915_has_memcpy_from_wc(),
},
};
struct drm_i915_gem_object *src, *dst;
void *src_addr, *dst_addr;
int ret = 0;
int i;
src = create_region_for_mapping(src_mr, size, src_type, &src_addr);
if (IS_ERR(src)) {
ret = PTR_ERR(src);
goto out;
}
dst = create_region_for_mapping(dst_mr, size, dst_type, &dst_addr);
if (IS_ERR(dst)) {
ret = PTR_ERR(dst);
goto out_unpin_src;
}
for (i = 0; i < ARRAY_SIZE(tests); ++i) {
ktime_t t[5];
int pass;
if (tests[i].skip)
continue;
for (pass = 0; pass < ARRAY_SIZE(t); pass++) {
ktime_t t0, t1;
t0 = ktime_get();
tests[i].copy(dst_addr, src_addr, size);
t1 = ktime_get();
t[pass] = ktime_sub(t1, t0);
}
sort(t, ARRAY_SIZE(t), sizeof(*t), wrap_ktime_compare, NULL);
if (t[0] <= 0) {
/* ignore the impossible to protect our sanity */
pr_debug("Skipping %s src(%s, %s) -> dst(%s, %s) %14s %4lluKiB copy, unstable measurement [%lld, %lld]\n",
__func__,
src_mr->name, repr_type(src_type),
dst_mr->name, repr_type(dst_type),
tests[i].name, size >> 10,
t[0], t[4]);
continue;
}
pr_info("%s src(%s, %s) -> dst(%s, %s) %14s %4llu KiB copy: %5lld MiB/s\n",
__func__,
src_mr->name, repr_type(src_type),
dst_mr->name, repr_type(dst_type),
tests[i].name, size >> 10,
div64_u64(mul_u32_u32(4 * size,
1000 * 1000 * 1000),
t[1] + 2 * t[2] + t[3]) >> 20);
cond_resched();
}
i915_gem_object_unpin_map(dst);
i915_gem_object_put(dst);
out_unpin_src:
i915_gem_object_unpin_map(src);
i915_gem_object_put(src);
i915_gem_drain_freed_objects(i915);
out:
if (ret == -ENODEV)
ret = 0;
return ret;
}
static int perf_memcpy(void *arg)
{
struct drm_i915_private *i915 = arg;
static const u32 types[] = {
I915_MAP_WB,
I915_MAP_WC,
};
static const u32 sizes[] = {
SZ_4K,
SZ_64K,
SZ_4M,
};
struct intel_memory_region *src_mr, *dst_mr;
int src_id, dst_id;
int i, j, k;
int ret;
for_each_memory_region(src_mr, i915, src_id) {
for_each_memory_region(dst_mr, i915, dst_id) {
for (i = 0; i < ARRAY_SIZE(sizes); ++i) {
for (j = 0; j < ARRAY_SIZE(types); ++j) {
for (k = 0; k < ARRAY_SIZE(types); ++k) {
ret = _perf_memcpy(src_mr,
dst_mr,
sizes[i],
types[j],
types[k]);
if (ret)
return ret;
}
}
}
}
}
return 0;
}
int intel_memory_region_mock_selftests(void)
{
static const struct i915_subtest tests[] = {
SUBTEST(igt_mock_reserve),
SUBTEST(igt_mock_fill),
SUBTEST(igt_mock_contiguous),
SUBTEST(igt_mock_splintered_region),
SUBTEST(igt_mock_max_segment),
SUBTEST(igt_mock_io_size),
};
struct intel_memory_region *mem;
struct drm_i915_private *i915;
int err;
i915 = mock_gem_device();
if (!i915)
return -ENOMEM;
mem = mock_region_create(i915, 0, SZ_2G, I915_GTT_PAGE_SIZE_4K, 0, 0);
if (IS_ERR(mem)) {
pr_err("failed to create memory region\n");
err = PTR_ERR(mem);
goto out_unref;
}
err = i915_subtests(tests, mem);
intel_memory_region_destroy(mem);
out_unref:
mock_destroy_device(i915);
return err;
}
int intel_memory_region_live_selftests(struct drm_i915_private *i915)
{
static const struct i915_subtest tests[] = {
SUBTEST(igt_lmem_create),
SUBTEST(igt_lmem_create_with_ps),
SUBTEST(igt_lmem_create_cleared_cpu),
SUBTEST(igt_lmem_write_cpu),
SUBTEST(igt_lmem_write_gpu),
};
if (!HAS_LMEM(i915)) {
pr_info("device lacks LMEM support, skipping\n");
return 0;
}
if (intel_gt_is_wedged(to_gt(i915)))
return 0;
return i915_live_subtests(tests, i915);
}
int intel_memory_region_perf_selftests(struct drm_i915_private *i915)
{
static const struct i915_subtest tests[] = {
SUBTEST(perf_memcpy),
};
if (intel_gt_is_wedged(to_gt(i915)))
return 0;
return i915_live_subtests(tests, i915);
}
| linux-master | drivers/gpu/drm/i915/selftests/intel_memory_region.c |
/*
* Copyright © 2016 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <linux/prime_numbers.h>
#include <linux/random.h>
#include "i915_selftest.h"
#include "i915_utils.h"
#define PFN_BIAS (1 << 10)
struct pfn_table {
struct sg_table st;
unsigned long start, end;
};
typedef unsigned int (*npages_fn_t)(unsigned long n,
unsigned long count,
struct rnd_state *rnd);
static noinline int expect_pfn_sg(struct pfn_table *pt,
npages_fn_t npages_fn,
struct rnd_state *rnd,
const char *who,
unsigned long timeout)
{
struct scatterlist *sg;
unsigned long pfn, n;
pfn = pt->start;
for_each_sg(pt->st.sgl, sg, pt->st.nents, n) {
struct page *page = sg_page(sg);
unsigned int npages = npages_fn(n, pt->st.nents, rnd);
if (page_to_pfn(page) != pfn) {
pr_err("%s: %s left pages out of order, expected pfn %lu, found pfn %lu (using for_each_sg)\n",
__func__, who, pfn, page_to_pfn(page));
return -EINVAL;
}
if (sg->length != npages * PAGE_SIZE) {
pr_err("%s: %s copied wrong sg length, expected size %lu, found %u (using for_each_sg)\n",
__func__, who, npages * PAGE_SIZE, sg->length);
return -EINVAL;
}
if (igt_timeout(timeout, "%s timed out\n", who))
return -EINTR;
pfn += npages;
}
if (pfn != pt->end) {
pr_err("%s: %s finished on wrong pfn, expected %lu, found %lu\n",
__func__, who, pt->end, pfn);
return -EINVAL;
}
return 0;
}
static noinline int expect_pfn_sg_page_iter(struct pfn_table *pt,
const char *who,
unsigned long timeout)
{
struct sg_page_iter sgiter;
unsigned long pfn;
pfn = pt->start;
for_each_sg_page(pt->st.sgl, &sgiter, pt->st.nents, 0) {
struct page *page = sg_page_iter_page(&sgiter);
if (page != pfn_to_page(pfn)) {
pr_err("%s: %s left pages out of order, expected pfn %lu, found pfn %lu (using for_each_sg_page)\n",
__func__, who, pfn, page_to_pfn(page));
return -EINVAL;
}
if (igt_timeout(timeout, "%s timed out\n", who))
return -EINTR;
pfn++;
}
if (pfn != pt->end) {
pr_err("%s: %s finished on wrong pfn, expected %lu, found %lu\n",
__func__, who, pt->end, pfn);
return -EINVAL;
}
return 0;
}
static noinline int expect_pfn_sgtiter(struct pfn_table *pt,
const char *who,
unsigned long timeout)
{
struct sgt_iter sgt;
struct page *page;
unsigned long pfn;
pfn = pt->start;
for_each_sgt_page(page, sgt, &pt->st) {
if (page != pfn_to_page(pfn)) {
pr_err("%s: %s left pages out of order, expected pfn %lu, found pfn %lu (using for_each_sgt_page)\n",
__func__, who, pfn, page_to_pfn(page));
return -EINVAL;
}
if (igt_timeout(timeout, "%s timed out\n", who))
return -EINTR;
pfn++;
}
if (pfn != pt->end) {
pr_err("%s: %s finished on wrong pfn, expected %lu, found %lu\n",
__func__, who, pt->end, pfn);
return -EINVAL;
}
return 0;
}
static int expect_pfn_sgtable(struct pfn_table *pt,
npages_fn_t npages_fn,
struct rnd_state *rnd,
const char *who,
unsigned long timeout)
{
int err;
err = expect_pfn_sg(pt, npages_fn, rnd, who, timeout);
if (err)
return err;
err = expect_pfn_sg_page_iter(pt, who, timeout);
if (err)
return err;
err = expect_pfn_sgtiter(pt, who, timeout);
if (err)
return err;
return 0;
}
static unsigned int one(unsigned long n,
unsigned long count,
struct rnd_state *rnd)
{
return 1;
}
static unsigned int grow(unsigned long n,
unsigned long count,
struct rnd_state *rnd)
{
return n + 1;
}
static unsigned int shrink(unsigned long n,
unsigned long count,
struct rnd_state *rnd)
{
return count - n;
}
static unsigned int random(unsigned long n,
unsigned long count,
struct rnd_state *rnd)
{
return 1 + (prandom_u32_state(rnd) % 1024);
}
static unsigned int random_page_size_pages(unsigned long n,
unsigned long count,
struct rnd_state *rnd)
{
/* 4K, 64K, 2M */
static unsigned int page_count[] = {
BIT(12) >> PAGE_SHIFT,
BIT(16) >> PAGE_SHIFT,
BIT(21) >> PAGE_SHIFT,
};
return page_count[(prandom_u32_state(rnd) % 3)];
}
static inline bool page_contiguous(struct page *first,
struct page *last,
unsigned long npages)
{
return first + npages == last;
}
static int alloc_table(struct pfn_table *pt,
unsigned long count, unsigned long max,
npages_fn_t npages_fn,
struct rnd_state *rnd,
int alloc_error)
{
struct scatterlist *sg;
unsigned long n, pfn;
/* restricted by sg_alloc_table */
if (overflows_type(max, unsigned int))
return -E2BIG;
if (sg_alloc_table(&pt->st, max,
GFP_KERNEL | __GFP_NORETRY | __GFP_NOWARN))
return alloc_error;
/* count should be less than 20 to prevent overflowing sg->length */
GEM_BUG_ON(overflows_type(count * PAGE_SIZE, sg->length));
/* Construct a table where each scatterlist contains different number
* of entries. The idea is to check that we can iterate the individual
* pages from inside the coalesced lists.
*/
pt->start = PFN_BIAS;
pfn = pt->start;
sg = pt->st.sgl;
for (n = 0; n < count; n++) {
unsigned long npages = npages_fn(n, count, rnd);
/* Nobody expects the Sparse Memmap! */
if (!page_contiguous(pfn_to_page(pfn),
pfn_to_page(pfn + npages),
npages)) {
sg_free_table(&pt->st);
return -ENOSPC;
}
if (n)
sg = sg_next(sg);
sg_set_page(sg, pfn_to_page(pfn), npages * PAGE_SIZE, 0);
GEM_BUG_ON(page_to_pfn(sg_page(sg)) != pfn);
GEM_BUG_ON(sg->length != npages * PAGE_SIZE);
GEM_BUG_ON(sg->offset != 0);
pfn += npages;
}
sg_mark_end(sg);
pt->st.nents = n;
pt->end = pfn;
return 0;
}
static const npages_fn_t npages_funcs[] = {
one,
grow,
shrink,
random,
random_page_size_pages,
NULL,
};
static int igt_sg_alloc(void *ignored)
{
IGT_TIMEOUT(end_time);
const unsigned long max_order = 20; /* approximating a 4GiB object */
struct rnd_state prng;
unsigned long prime;
int alloc_error = -ENOMEM;
for_each_prime_number(prime, max_order) {
unsigned long size = BIT(prime);
int offset;
for (offset = -1; offset <= 1; offset++) {
unsigned long sz = size + offset;
const npages_fn_t *npages;
struct pfn_table pt;
int err;
for (npages = npages_funcs; *npages; npages++) {
prandom_seed_state(&prng,
i915_selftest.random_seed);
err = alloc_table(&pt, sz, sz, *npages, &prng,
alloc_error);
if (err == -ENOSPC)
break;
if (err)
return err;
prandom_seed_state(&prng,
i915_selftest.random_seed);
err = expect_pfn_sgtable(&pt, *npages, &prng,
"sg_alloc_table",
end_time);
sg_free_table(&pt.st);
if (err)
return err;
}
}
/* Test at least one continuation before accepting oom */
if (size > SG_MAX_SINGLE_ALLOC)
alloc_error = -ENOSPC;
}
return 0;
}
static int igt_sg_trim(void *ignored)
{
IGT_TIMEOUT(end_time);
const unsigned long max = PAGE_SIZE; /* not prime! */
struct pfn_table pt;
unsigned long prime;
int alloc_error = -ENOMEM;
for_each_prime_number(prime, max) {
const npages_fn_t *npages;
int err;
for (npages = npages_funcs; *npages; npages++) {
struct rnd_state prng;
prandom_seed_state(&prng, i915_selftest.random_seed);
err = alloc_table(&pt, prime, max, *npages, &prng,
alloc_error);
if (err == -ENOSPC)
break;
if (err)
return err;
if (i915_sg_trim(&pt.st)) {
if (pt.st.orig_nents != prime ||
pt.st.nents != prime) {
pr_err("i915_sg_trim failed (nents %u, orig_nents %u), expected %lu\n",
pt.st.nents, pt.st.orig_nents, prime);
err = -EINVAL;
} else {
prandom_seed_state(&prng,
i915_selftest.random_seed);
err = expect_pfn_sgtable(&pt,
*npages, &prng,
"i915_sg_trim",
end_time);
}
}
sg_free_table(&pt.st);
if (err)
return err;
}
/* Test at least one continuation before accepting oom */
if (prime > SG_MAX_SINGLE_ALLOC)
alloc_error = -ENOSPC;
}
return 0;
}
int scatterlist_mock_selftests(void)
{
static const struct i915_subtest tests[] = {
SUBTEST(igt_sg_alloc),
SUBTEST(igt_sg_trim),
};
return i915_subtests(tests, NULL);
}
| linux-master | drivers/gpu/drm/i915/selftests/scatterlist.c |
/*
* SPDX-License-Identifier: MIT
*
* Copyright © 2018 Intel Corporation
*/
#include "igt_reset.h"
#include "gt/intel_engine.h"
#include "gt/intel_gt.h"
#include "../i915_drv.h"
void igt_global_reset_lock(struct intel_gt *gt)
{
struct intel_engine_cs *engine;
enum intel_engine_id id;
pr_debug("%s: current gpu_error=%08lx\n", __func__, gt->reset.flags);
while (test_and_set_bit(I915_RESET_BACKOFF, >->reset.flags))
wait_event(gt->reset.queue,
!test_bit(I915_RESET_BACKOFF, >->reset.flags));
for_each_engine(engine, gt, id) {
while (test_and_set_bit(I915_RESET_ENGINE + id,
>->reset.flags))
wait_on_bit(>->reset.flags, I915_RESET_ENGINE + id,
TASK_UNINTERRUPTIBLE);
}
}
void igt_global_reset_unlock(struct intel_gt *gt)
{
struct intel_engine_cs *engine;
enum intel_engine_id id;
for_each_engine(engine, gt, id)
clear_and_wake_up_bit(I915_RESET_ENGINE + id, >->reset.flags);
clear_bit(I915_RESET_BACKOFF, >->reset.flags);
wake_up_all(>->reset.queue);
}
bool igt_force_reset(struct intel_gt *gt)
{
intel_gt_set_wedged(gt);
intel_gt_reset(gt, 0, NULL);
return !intel_gt_is_wedged(gt);
}
| linux-master | drivers/gpu/drm/i915/selftests/igt_reset.c |
/*
* Copyright © 2016 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <linux/random.h>
#include "gt/intel_gt_pm.h"
#include "gt/uc/intel_gsc_fw.h"
#include "i915_driver.h"
#include "i915_drv.h"
#include "i915_selftest.h"
#include "igt_flush_test.h"
struct i915_selftest i915_selftest __read_mostly = {
.timeout_ms = 500,
};
int i915_mock_sanitycheck(void)
{
pr_info(DRIVER_NAME ": %s() - ok!\n", __func__);
return 0;
}
int i915_live_sanitycheck(struct drm_i915_private *i915)
{
pr_info("%s: %s() - ok!\n", i915->drm.driver->name, __func__);
return 0;
}
enum {
#define selftest(name, func) mock_##name,
#include "i915_mock_selftests.h"
#undef selftest
};
enum {
#define selftest(name, func) live_##name,
#include "i915_live_selftests.h"
#undef selftest
};
enum {
#define selftest(name, func) perf_##name,
#include "i915_perf_selftests.h"
#undef selftest
};
struct selftest {
bool enabled;
const char *name;
union {
int (*mock)(void);
int (*live)(struct drm_i915_private *);
};
};
#define selftest(n, f) [mock_##n] = { .name = #n, { .mock = f } },
static struct selftest mock_selftests[] = {
#include "i915_mock_selftests.h"
};
#undef selftest
#define selftest(n, f) [live_##n] = { .name = #n, { .live = f } },
static struct selftest live_selftests[] = {
#include "i915_live_selftests.h"
};
#undef selftest
#define selftest(n, f) [perf_##n] = { .name = #n, { .live = f } },
static struct selftest perf_selftests[] = {
#include "i915_perf_selftests.h"
};
#undef selftest
/* Embed the line number into the parameter name so that we can order tests */
#define selftest(n, func) selftest_0(n, func, param(n))
#define param(n) __PASTE(igt__, __PASTE(__LINE__, __mock_##n))
#define selftest_0(n, func, id) \
module_param_named(id, mock_selftests[mock_##n].enabled, bool, 0400);
#include "i915_mock_selftests.h"
#undef selftest_0
#undef param
#define param(n) __PASTE(igt__, __PASTE(__LINE__, __live_##n))
#define selftest_0(n, func, id) \
module_param_named(id, live_selftests[live_##n].enabled, bool, 0400);
#include "i915_live_selftests.h"
#undef selftest_0
#undef param
#define param(n) __PASTE(igt__, __PASTE(__LINE__, __perf_##n))
#define selftest_0(n, func, id) \
module_param_named(id, perf_selftests[perf_##n].enabled, bool, 0400);
#include "i915_perf_selftests.h"
#undef selftest_0
#undef param
#undef selftest
static void set_default_test_all(struct selftest *st, unsigned int count)
{
unsigned int i;
for (i = 0; i < count; i++)
if (st[i].enabled)
return;
for (i = 0; i < count; i++)
st[i].enabled = true;
}
static bool
__gsc_proxy_init_progressing(struct intel_gsc_uc *gsc)
{
return intel_gsc_uc_fw_proxy_get_status(gsc) == -EAGAIN;
}
static void
__wait_gsc_proxy_completed(struct drm_i915_private *i915)
{
bool need_to_wait = (IS_ENABLED(CONFIG_INTEL_MEI_GSC_PROXY) &&
i915->media_gt &&
HAS_ENGINE(i915->media_gt, GSC0) &&
intel_uc_fw_is_loadable(&i915->media_gt->uc.gsc.fw));
/*
* The gsc proxy component depends on the kernel component driver load ordering
* and in corner cases (the first time after an IFWI flash), init-completion
* firmware flows take longer.
*/
unsigned long timeout_ms = 8000;
if (need_to_wait && wait_for(!__gsc_proxy_init_progressing(&i915->media_gt->uc.gsc),
timeout_ms))
pr_warn(DRIVER_NAME "Timed out waiting for gsc_proxy_completion!\n");
}
static int __run_selftests(const char *name,
struct selftest *st,
unsigned int count,
void *data)
{
int err = 0;
while (!i915_selftest.random_seed)
i915_selftest.random_seed = get_random_u32();
i915_selftest.timeout_jiffies =
i915_selftest.timeout_ms ?
msecs_to_jiffies_timeout(i915_selftest.timeout_ms) :
MAX_SCHEDULE_TIMEOUT;
set_default_test_all(st, count);
pr_info(DRIVER_NAME ": Performing %s selftests with st_random_seed=0x%x st_timeout=%u\n",
name, i915_selftest.random_seed, i915_selftest.timeout_ms);
/* Tests are listed in order in i915_*_selftests.h */
for (; count--; st++) {
if (!st->enabled)
continue;
cond_resched();
if (signal_pending(current))
return -EINTR;
pr_info(DRIVER_NAME ": Running %s\n", st->name);
if (data)
err = st->live(data);
else
err = st->mock();
if (err == -EINTR && !signal_pending(current))
err = 0;
if (err)
break;
}
if (WARN(err > 0 || err == -ENOTTY,
"%s returned %d, conflicting with selftest's magic values!\n",
st->name, err))
err = -1;
return err;
}
#define run_selftests(x, data) \
__run_selftests(#x, x##_selftests, ARRAY_SIZE(x##_selftests), data)
int i915_mock_selftests(void)
{
int err;
if (!i915_selftest.mock)
return 0;
err = run_selftests(mock, NULL);
if (err) {
i915_selftest.mock = err;
return 1;
}
if (i915_selftest.mock < 0) {
i915_selftest.mock = -ENOTTY;
return 1;
}
return 0;
}
int i915_live_selftests(struct pci_dev *pdev)
{
int err;
if (!i915_selftest.live)
return 0;
__wait_gsc_proxy_completed(pdev_to_i915(pdev));
err = run_selftests(live, pdev_to_i915(pdev));
if (err) {
i915_selftest.live = err;
return err;
}
if (i915_selftest.live < 0) {
i915_selftest.live = -ENOTTY;
return 1;
}
return 0;
}
int i915_perf_selftests(struct pci_dev *pdev)
{
int err;
if (!i915_selftest.perf)
return 0;
__wait_gsc_proxy_completed(pdev_to_i915(pdev));
err = run_selftests(perf, pdev_to_i915(pdev));
if (err) {
i915_selftest.perf = err;
return err;
}
if (i915_selftest.perf < 0) {
i915_selftest.perf = -ENOTTY;
return 1;
}
return 0;
}
static bool apply_subtest_filter(const char *caller, const char *name)
{
char *filter, *sep, *tok;
bool result = true;
filter = kstrdup(i915_selftest.filter, GFP_KERNEL);
for (sep = filter; (tok = strsep(&sep, ","));) {
bool allow = true;
char *sl;
if (*tok == '!') {
allow = false;
tok++;
}
if (*tok == '\0')
continue;
sl = strchr(tok, '/');
if (sl) {
*sl++ = '\0';
if (strcmp(tok, caller)) {
if (allow)
result = false;
continue;
}
tok = sl;
}
if (strcmp(tok, name)) {
if (allow)
result = false;
continue;
}
result = allow;
break;
}
kfree(filter);
return result;
}
int __i915_nop_setup(void *data)
{
return 0;
}
int __i915_nop_teardown(int err, void *data)
{
return err;
}
int __i915_live_setup(void *data)
{
struct drm_i915_private *i915 = data;
/* The selftests expect an idle system */
if (intel_gt_pm_wait_for_idle(to_gt(i915)))
return -EIO;
return intel_gt_terminally_wedged(to_gt(i915));
}
int __i915_live_teardown(int err, void *data)
{
struct drm_i915_private *i915 = data;
if (igt_flush_test(i915))
err = -EIO;
i915_gem_drain_freed_objects(i915);
return err;
}
int __intel_gt_live_setup(void *data)
{
struct intel_gt *gt = data;
/* The selftests expect an idle system */
if (intel_gt_pm_wait_for_idle(gt))
return -EIO;
return intel_gt_terminally_wedged(gt);
}
int __intel_gt_live_teardown(int err, void *data)
{
struct intel_gt *gt = data;
if (igt_flush_test(gt->i915))
err = -EIO;
i915_gem_drain_freed_objects(gt->i915);
return err;
}
int __i915_subtests(const char *caller,
int (*setup)(void *data),
int (*teardown)(int err, void *data),
const struct i915_subtest *st,
unsigned int count,
void *data)
{
int err;
for (; count--; st++) {
cond_resched();
if (signal_pending(current))
return -EINTR;
if (!apply_subtest_filter(caller, st->name))
continue;
err = setup(data);
if (err) {
pr_err(DRIVER_NAME "/%s: setup failed for %s\n",
caller, st->name);
return err;
}
pr_info(DRIVER_NAME ": Running %s/%s\n", caller, st->name);
GEM_TRACE("Running %s/%s\n", caller, st->name);
err = teardown(st->func(data), data);
if (err && err != -EINTR) {
pr_err(DRIVER_NAME "/%s: %s failed with error %d\n",
caller, st->name, err);
return err;
}
}
return 0;
}
bool __igt_timeout(unsigned long timeout, const char *fmt, ...)
{
va_list va;
if (!signal_pending(current)) {
cond_resched();
if (time_before(jiffies, timeout))
return false;
}
if (fmt) {
va_start(va, fmt);
vprintk(fmt, va);
va_end(va);
}
return true;
}
void igt_hexdump(const void *buf, size_t len)
{
const size_t rowsize = 8 * sizeof(u32);
const void *prev = NULL;
bool skip = false;
size_t pos;
for (pos = 0; pos < len; pos += rowsize) {
char line[128];
if (prev && !memcmp(prev, buf + pos, rowsize)) {
if (!skip) {
pr_info("*\n");
skip = true;
}
continue;
}
WARN_ON_ONCE(hex_dump_to_buffer(buf + pos, len - pos,
rowsize, sizeof(u32),
line, sizeof(line),
false) >= sizeof(line));
pr_info("[%04zx] %s\n", pos, line);
prev = buf + pos;
skip = false;
}
}
module_param_named(st_random_seed, i915_selftest.random_seed, uint, 0400);
module_param_named(st_timeout, i915_selftest.timeout_ms, uint, 0400);
module_param_named(st_filter, i915_selftest.filter, charp, 0400);
module_param_named_unsafe(mock_selftests, i915_selftest.mock, int, 0400);
MODULE_PARM_DESC(mock_selftests, "Run selftests before loading, using mock hardware (0:disabled [default], 1:run tests then load driver, -1:run tests then leave dummy module)");
module_param_named_unsafe(live_selftests, i915_selftest.live, int, 0400);
MODULE_PARM_DESC(live_selftests, "Run selftests after driver initialisation on the live system (0:disabled [default], 1:run tests then continue, -1:run tests then exit module)");
module_param_named_unsafe(perf_selftests, i915_selftest.perf, int, 0400);
MODULE_PARM_DESC(perf_selftests, "Run performance orientated selftests after driver initialisation on the live system (0:disabled [default], 1:run tests then continue, -1:run tests then exit module)");
| linux-master | drivers/gpu/drm/i915/selftests/i915_selftest.c |
/*
* Copyright © 2016 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
#include "mock_gtt.h"
static void mock_insert_page(struct i915_address_space *vm,
dma_addr_t addr,
u64 offset,
unsigned int pat_index,
u32 flags)
{
}
static void mock_insert_entries(struct i915_address_space *vm,
struct i915_vma_resource *vma_res,
unsigned int pat_index, u32 flags)
{
}
static void mock_bind_ppgtt(struct i915_address_space *vm,
struct i915_vm_pt_stash *stash,
struct i915_vma_resource *vma_res,
unsigned int pat_index,
u32 flags)
{
GEM_BUG_ON(flags & I915_VMA_GLOBAL_BIND);
vma_res->bound_flags |= flags;
}
static void mock_unbind_ppgtt(struct i915_address_space *vm,
struct i915_vma_resource *vma_res)
{
}
static void mock_cleanup(struct i915_address_space *vm)
{
}
static void mock_clear_range(struct i915_address_space *vm,
u64 start, u64 length)
{
}
struct i915_ppgtt *mock_ppgtt(struct drm_i915_private *i915, const char *name)
{
struct i915_ppgtt *ppgtt;
ppgtt = kzalloc(sizeof(*ppgtt), GFP_KERNEL);
if (!ppgtt)
return NULL;
ppgtt->vm.gt = to_gt(i915);
ppgtt->vm.i915 = i915;
ppgtt->vm.total = round_down(U64_MAX, PAGE_SIZE);
ppgtt->vm.dma = i915->drm.dev;
i915_address_space_init(&ppgtt->vm, VM_CLASS_PPGTT);
ppgtt->vm.alloc_pt_dma = alloc_pt_dma;
ppgtt->vm.alloc_scratch_dma = alloc_pt_dma;
ppgtt->vm.clear_range = mock_clear_range;
ppgtt->vm.insert_page = mock_insert_page;
ppgtt->vm.insert_entries = mock_insert_entries;
ppgtt->vm.cleanup = mock_cleanup;
ppgtt->vm.vma_ops.bind_vma = mock_bind_ppgtt;
ppgtt->vm.vma_ops.unbind_vma = mock_unbind_ppgtt;
return ppgtt;
}
static void mock_bind_ggtt(struct i915_address_space *vm,
struct i915_vm_pt_stash *stash,
struct i915_vma_resource *vma_res,
unsigned int pat_index,
u32 flags)
{
}
static void mock_unbind_ggtt(struct i915_address_space *vm,
struct i915_vma_resource *vma_res)
{
}
void mock_init_ggtt(struct intel_gt *gt)
{
struct i915_ggtt *ggtt = gt->ggtt;
ggtt->vm.gt = gt;
ggtt->vm.i915 = gt->i915;
ggtt->vm.is_ggtt = true;
ggtt->gmadr = DEFINE_RES_MEM(0, 2048 * PAGE_SIZE);
ggtt->mappable_end = resource_size(&ggtt->gmadr);
ggtt->vm.total = 4096 * PAGE_SIZE;
ggtt->vm.alloc_pt_dma = alloc_pt_dma;
ggtt->vm.alloc_scratch_dma = alloc_pt_dma;
ggtt->vm.clear_range = mock_clear_range;
ggtt->vm.insert_page = mock_insert_page;
ggtt->vm.insert_entries = mock_insert_entries;
ggtt->vm.cleanup = mock_cleanup;
ggtt->vm.vma_ops.bind_vma = mock_bind_ggtt;
ggtt->vm.vma_ops.unbind_vma = mock_unbind_ggtt;
i915_address_space_init(&ggtt->vm, VM_CLASS_GGTT);
}
void mock_fini_ggtt(struct i915_ggtt *ggtt)
{
i915_address_space_fini(&ggtt->vm);
}
| linux-master | drivers/gpu/drm/i915/selftests/mock_gtt.c |
/*
* SPDX-License-Identifier: MIT
*
* Copyright © 2019 Intel Corporation
*/
#include <drm/drm_file.h>
#include "i915_drv.h"
#include "igt_mmap.h"
unsigned long igt_mmap_offset(struct drm_i915_private *i915,
u64 offset,
unsigned long size,
unsigned long prot,
unsigned long flags)
{
struct drm_vma_offset_node *node;
struct file *file;
unsigned long addr;
int err;
/* no need to refcount, we own this object */
drm_vma_offset_lock_lookup(i915->drm.vma_offset_manager);
node = drm_vma_offset_exact_lookup_locked(i915->drm.vma_offset_manager,
offset / PAGE_SIZE, size / PAGE_SIZE);
drm_vma_offset_unlock_lookup(i915->drm.vma_offset_manager);
if (GEM_WARN_ON(!node)) {
pr_info("Failed to lookup %llx\n", offset);
return -ENOENT;
}
/* Pretend to open("/dev/dri/card0") */
file = mock_drm_getfile(i915->drm.primary, O_RDWR);
if (IS_ERR(file))
return PTR_ERR(file);
err = drm_vma_node_allow(node, file->private_data);
if (err) {
addr = err;
goto out_file;
}
addr = vm_mmap(file, 0, drm_vma_node_size(node) << PAGE_SHIFT,
prot, flags, drm_vma_node_offset_addr(node));
drm_vma_node_revoke(node, file->private_data);
out_file:
fput(file);
return addr;
}
| linux-master | drivers/gpu/drm/i915/selftests/igt_mmap.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2021 Intel Corporation
*/
//#include "gt/intel_engine_user.h"
#include "gt/intel_gt.h"
#include "i915_drv.h"
#include "i915_selftest.h"
#include "selftests/intel_scheduler_helpers.h"
#define REDUCED_TIMESLICE 5
#define REDUCED_PREEMPT 10
#define WAIT_FOR_RESET_TIME 10000
struct intel_engine_cs *intel_selftest_find_any_engine(struct intel_gt *gt)
{
struct intel_engine_cs *engine;
enum intel_engine_id id;
for_each_engine(engine, gt, id)
return engine;
pr_err("No valid engine found!\n");
return NULL;
}
int intel_selftest_modify_policy(struct intel_engine_cs *engine,
struct intel_selftest_saved_policy *saved,
enum selftest_scheduler_modify modify_type)
{
int err;
saved->reset = engine->i915->params.reset;
saved->flags = engine->flags;
saved->timeslice = engine->props.timeslice_duration_ms;
saved->preempt_timeout = engine->props.preempt_timeout_ms;
switch (modify_type) {
case SELFTEST_SCHEDULER_MODIFY_FAST_RESET:
/*
* Enable force pre-emption on time slice expiration
* together with engine reset on pre-emption timeout.
* This is required to make the GuC notice and reset
* the single hanging context.
* Also, reduce the preemption timeout to something
* small to speed the test up.
*/
engine->i915->params.reset = 2;
engine->flags |= I915_ENGINE_WANT_FORCED_PREEMPTION;
engine->props.timeslice_duration_ms = REDUCED_TIMESLICE;
engine->props.preempt_timeout_ms = REDUCED_PREEMPT;
break;
case SELFTEST_SCHEDULER_MODIFY_NO_HANGCHECK:
engine->props.preempt_timeout_ms = 0;
break;
default:
pr_err("Invalid scheduler policy modification type: %d!\n", modify_type);
return -EINVAL;
}
if (!intel_engine_uses_guc(engine))
return 0;
err = intel_guc_global_policies_update(&engine->gt->uc.guc);
if (err)
intel_selftest_restore_policy(engine, saved);
return err;
}
int intel_selftest_restore_policy(struct intel_engine_cs *engine,
struct intel_selftest_saved_policy *saved)
{
/* Restore the original policies */
engine->i915->params.reset = saved->reset;
engine->flags = saved->flags;
engine->props.timeslice_duration_ms = saved->timeslice;
engine->props.preempt_timeout_ms = saved->preempt_timeout;
if (!intel_engine_uses_guc(engine))
return 0;
return intel_guc_global_policies_update(&engine->gt->uc.guc);
}
int intel_selftest_wait_for_rq(struct i915_request *rq)
{
long ret;
ret = i915_request_wait(rq, 0, WAIT_FOR_RESET_TIME);
if (ret < 0)
return ret;
return 0;
}
| linux-master | drivers/gpu/drm/i915/selftests/intel_scheduler_helpers.c |
/*
* SPDX-License-Identifier: MIT
*
* Copyright © 2018 Intel Corporation
*/
#include <linux/random.h>
#include "gem/i915_gem_internal.h"
#include "gem/i915_gem_pm.h"
#include "gem/selftests/igt_gem_utils.h"
#include "gem/selftests/mock_context.h"
#include "gt/intel_gt.h"
#include "gt/intel_gt_pm.h"
#include "i915_selftest.h"
#include "igt_flush_test.h"
#include "mock_drm.h"
static int switch_to_context(struct i915_gem_context *ctx)
{
struct i915_gem_engines_iter it;
struct intel_context *ce;
int err = 0;
for_each_gem_engine(ce, i915_gem_context_lock_engines(ctx), it) {
struct i915_request *rq;
rq = intel_context_create_request(ce);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
break;
}
i915_request_add(rq);
}
i915_gem_context_unlock_engines(ctx);
return err;
}
static void trash_stolen(struct drm_i915_private *i915)
{
struct i915_ggtt *ggtt = to_gt(i915)->ggtt;
const u64 slot = ggtt->error_capture.start;
const resource_size_t size = resource_size(&i915->dsm.stolen);
unsigned long page;
u32 prng = 0x12345678;
/* XXX: fsck. needs some more thought... */
if (!i915_ggtt_has_aperture(ggtt))
return;
for (page = 0; page < size; page += PAGE_SIZE) {
const dma_addr_t dma = i915->dsm.stolen.start + page;
u32 __iomem *s;
int x;
ggtt->vm.insert_page(&ggtt->vm, dma, slot,
i915_gem_get_pat_index(i915,
I915_CACHE_NONE),
0);
s = io_mapping_map_atomic_wc(&ggtt->iomap, slot);
for (x = 0; x < PAGE_SIZE / sizeof(u32); x++) {
prng = next_pseudo_random32(prng);
iowrite32(prng, &s[x]);
}
io_mapping_unmap_atomic(s);
}
ggtt->vm.clear_range(&ggtt->vm, slot, PAGE_SIZE);
}
static void simulate_hibernate(struct drm_i915_private *i915)
{
intel_wakeref_t wakeref;
wakeref = intel_runtime_pm_get(&i915->runtime_pm);
/*
* As a final sting in the tail, invalidate stolen. Under a real S4,
* stolen is lost and needs to be refilled on resume. However, under
* CI we merely do S4-device testing (as full S4 is too unreliable
* for automated testing across a cluster), so to simulate the effect
* of stolen being trashed across S4, we trash it ourselves.
*/
trash_stolen(i915);
intel_runtime_pm_put(&i915->runtime_pm, wakeref);
}
static int igt_pm_prepare(struct drm_i915_private *i915)
{
i915_gem_suspend(i915);
return 0;
}
static void igt_pm_suspend(struct drm_i915_private *i915)
{
intel_wakeref_t wakeref;
with_intel_runtime_pm(&i915->runtime_pm, wakeref) {
i915_ggtt_suspend(to_gt(i915)->ggtt);
i915_gem_suspend_late(i915);
}
}
static void igt_pm_hibernate(struct drm_i915_private *i915)
{
intel_wakeref_t wakeref;
with_intel_runtime_pm(&i915->runtime_pm, wakeref) {
i915_ggtt_suspend(to_gt(i915)->ggtt);
i915_gem_freeze(i915);
i915_gem_freeze_late(i915);
}
}
static void igt_pm_resume(struct drm_i915_private *i915)
{
intel_wakeref_t wakeref;
/*
* Both suspend and hibernate follow the same wakeup path and assume
* that runtime-pm just works.
*/
with_intel_runtime_pm(&i915->runtime_pm, wakeref) {
i915_ggtt_resume(to_gt(i915)->ggtt);
if (GRAPHICS_VER(i915) >= 8)
setup_private_pat(to_gt(i915));
i915_gem_resume(i915);
}
}
static int igt_gem_suspend(void *arg)
{
struct drm_i915_private *i915 = arg;
struct i915_gem_context *ctx;
struct file *file;
int err;
file = mock_file(i915);
if (IS_ERR(file))
return PTR_ERR(file);
err = -ENOMEM;
ctx = live_context(i915, file);
if (!IS_ERR(ctx))
err = switch_to_context(ctx);
if (err)
goto out;
err = igt_pm_prepare(i915);
if (err)
goto out;
igt_pm_suspend(i915);
/* Here be dragons! Note that with S3RST any S3 may become S4! */
simulate_hibernate(i915);
igt_pm_resume(i915);
err = switch_to_context(ctx);
out:
fput(file);
return err;
}
static int igt_gem_hibernate(void *arg)
{
struct drm_i915_private *i915 = arg;
struct i915_gem_context *ctx;
struct file *file;
int err;
file = mock_file(i915);
if (IS_ERR(file))
return PTR_ERR(file);
err = -ENOMEM;
ctx = live_context(i915, file);
if (!IS_ERR(ctx))
err = switch_to_context(ctx);
if (err)
goto out;
err = igt_pm_prepare(i915);
if (err)
goto out;
igt_pm_hibernate(i915);
/* Here be dragons! */
simulate_hibernate(i915);
igt_pm_resume(i915);
err = switch_to_context(ctx);
out:
fput(file);
return err;
}
static int igt_gem_ww_ctx(void *arg)
{
struct drm_i915_private *i915 = arg;
struct drm_i915_gem_object *obj, *obj2;
struct i915_gem_ww_ctx ww;
int err = 0;
obj = i915_gem_object_create_internal(i915, PAGE_SIZE);
if (IS_ERR(obj))
return PTR_ERR(obj);
obj2 = i915_gem_object_create_internal(i915, PAGE_SIZE);
if (IS_ERR(obj2)) {
err = PTR_ERR(obj2);
goto put1;
}
i915_gem_ww_ctx_init(&ww, true);
retry:
/* Lock the objects, twice for good measure (-EALREADY handling) */
err = i915_gem_object_lock(obj, &ww);
if (!err)
err = i915_gem_object_lock_interruptible(obj, &ww);
if (!err)
err = i915_gem_object_lock_interruptible(obj2, &ww);
if (!err)
err = i915_gem_object_lock(obj2, &ww);
if (err == -EDEADLK) {
err = i915_gem_ww_ctx_backoff(&ww);
if (!err)
goto retry;
}
i915_gem_ww_ctx_fini(&ww);
i915_gem_object_put(obj2);
put1:
i915_gem_object_put(obj);
return err;
}
int i915_gem_live_selftests(struct drm_i915_private *i915)
{
static const struct i915_subtest tests[] = {
SUBTEST(igt_gem_suspend),
SUBTEST(igt_gem_hibernate),
SUBTEST(igt_gem_ww_ctx),
};
if (intel_gt_is_wedged(to_gt(i915)))
return 0;
return i915_live_subtests(tests, i915);
}
| linux-master | drivers/gpu/drm/i915/selftests/i915_gem.c |
/*
* Copyright © 2017 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
#include "lib_sw_fence.h"
/* Small library of different fence types useful for writing tests */
static int
nop_fence_notify(struct i915_sw_fence *fence, enum i915_sw_fence_notify state)
{
return NOTIFY_DONE;
}
void __onstack_fence_init(struct i915_sw_fence *fence,
const char *name,
struct lock_class_key *key)
{
debug_fence_init_onstack(fence);
__init_waitqueue_head(&fence->wait, name, key);
atomic_set(&fence->pending, 1);
fence->error = 0;
fence->fn = nop_fence_notify;
}
void onstack_fence_fini(struct i915_sw_fence *fence)
{
if (!fence->fn)
return;
i915_sw_fence_commit(fence);
i915_sw_fence_fini(fence);
}
static void timed_fence_wake(struct timer_list *t)
{
struct timed_fence *tf = from_timer(tf, t, timer);
i915_sw_fence_commit(&tf->fence);
}
void timed_fence_init(struct timed_fence *tf, unsigned long expires)
{
onstack_fence_init(&tf->fence);
timer_setup_on_stack(&tf->timer, timed_fence_wake, 0);
if (time_after(expires, jiffies))
mod_timer(&tf->timer, expires);
else
i915_sw_fence_commit(&tf->fence);
}
void timed_fence_fini(struct timed_fence *tf)
{
if (del_timer_sync(&tf->timer))
i915_sw_fence_commit(&tf->fence);
destroy_timer_on_stack(&tf->timer);
i915_sw_fence_fini(&tf->fence);
}
struct heap_fence {
struct i915_sw_fence fence;
union {
struct kref ref;
struct rcu_head rcu;
};
};
static int
heap_fence_notify(struct i915_sw_fence *fence, enum i915_sw_fence_notify state)
{
struct heap_fence *h = container_of(fence, typeof(*h), fence);
switch (state) {
case FENCE_COMPLETE:
break;
case FENCE_FREE:
heap_fence_put(&h->fence);
}
return NOTIFY_DONE;
}
struct i915_sw_fence *heap_fence_create(gfp_t gfp)
{
struct heap_fence *h;
h = kmalloc(sizeof(*h), gfp);
if (!h)
return NULL;
i915_sw_fence_init(&h->fence, heap_fence_notify);
refcount_set(&h->ref.refcount, 2);
return &h->fence;
}
static void heap_fence_release(struct kref *ref)
{
struct heap_fence *h = container_of(ref, typeof(*h), ref);
i915_sw_fence_fini(&h->fence);
kfree_rcu(h, rcu);
}
void heap_fence_put(struct i915_sw_fence *fence)
{
struct heap_fence *h = container_of(fence, typeof(*h), fence);
kref_put(&h->ref, heap_fence_release);
}
| linux-master | drivers/gpu/drm/i915/selftests/lib_sw_fence.c |
/*
* SPDX-License-Identifier: MIT
*
* Copyright © 2018 Intel Corporation
*/
#include "i915_drv.h"
#include "gt/intel_gt.h"
#include "gt/intel_gt_print.h"
#include "../i915_selftest.h"
#include "igt_flush_test.h"
#include "igt_live_test.h"
int igt_live_test_begin(struct igt_live_test *t,
struct drm_i915_private *i915,
const char *func,
const char *name)
{
struct intel_engine_cs *engine;
enum intel_engine_id id;
struct intel_gt *gt;
unsigned int i;
int err;
t->i915 = i915;
t->func = func;
t->name = name;
for_each_gt(gt, i915, i) {
err = intel_gt_wait_for_idle(gt, MAX_SCHEDULE_TIMEOUT);
if (err) {
gt_err(gt, "%s(%s): GT failed to idle before, with err=%d!",
func, name, err);
return err;
}
for_each_engine(engine, gt, id)
t->reset_engine[id] =
i915_reset_engine_count(&i915->gpu_error, engine);
}
t->reset_global = i915_reset_count(&i915->gpu_error);
return 0;
}
int igt_live_test_end(struct igt_live_test *t)
{
struct drm_i915_private *i915 = t->i915;
struct intel_engine_cs *engine;
enum intel_engine_id id;
struct intel_gt *gt;
unsigned int i;
if (igt_flush_test(i915))
return -EIO;
if (t->reset_global != i915_reset_count(&i915->gpu_error)) {
pr_err("%s(%s): GPU was reset %d times!\n",
t->func, t->name,
i915_reset_count(&i915->gpu_error) - t->reset_global);
return -EIO;
}
for_each_gt(gt, i915, i) {
for_each_engine(engine, gt, id) {
if (t->reset_engine[id] ==
i915_reset_engine_count(&i915->gpu_error, engine))
continue;
gt_err(gt, "%s(%s): engine '%s' was reset %d times!\n",
t->func, t->name, engine->name,
i915_reset_engine_count(&i915->gpu_error, engine) -
t->reset_engine[id]);
return -EIO;
}
}
return 0;
}
| linux-master | drivers/gpu/drm/i915/selftests/igt_live_test.c |
/*
* Copyright © 2016 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
#include <linux/prime_numbers.h>
#include "gem/i915_gem_context.h"
#include "gem/i915_gem_internal.h"
#include "gem/selftests/mock_context.h"
#include "i915_scatterlist.h"
#include "i915_selftest.h"
#include "mock_gem_device.h"
#include "mock_gtt.h"
static bool assert_vma(struct i915_vma *vma,
struct drm_i915_gem_object *obj,
struct i915_gem_context *ctx)
{
bool ok = true;
if (vma->vm != ctx->vm) {
pr_err("VMA created with wrong VM\n");
ok = false;
}
if (vma->size != obj->base.size) {
pr_err("VMA created with wrong size, found %llu, expected %zu\n",
vma->size, obj->base.size);
ok = false;
}
if (vma->gtt_view.type != I915_GTT_VIEW_NORMAL) {
pr_err("VMA created with wrong type [%d]\n",
vma->gtt_view.type);
ok = false;
}
return ok;
}
static struct i915_vma *
checked_vma_instance(struct drm_i915_gem_object *obj,
struct i915_address_space *vm,
const struct i915_gtt_view *view)
{
struct i915_vma *vma;
bool ok = true;
vma = i915_vma_instance(obj, vm, view);
if (IS_ERR(vma))
return vma;
/* Manual checks, will be reinforced by i915_vma_compare! */
if (vma->vm != vm) {
pr_err("VMA's vm [%p] does not match request [%p]\n",
vma->vm, vm);
ok = false;
}
if (i915_is_ggtt(vm) != i915_vma_is_ggtt(vma)) {
pr_err("VMA ggtt status [%d] does not match parent [%d]\n",
i915_vma_is_ggtt(vma), i915_is_ggtt(vm));
ok = false;
}
if (i915_vma_compare(vma, vm, view)) {
pr_err("i915_vma_compare failed with create parameters!\n");
return ERR_PTR(-EINVAL);
}
if (i915_vma_compare(vma, vma->vm,
i915_vma_is_ggtt(vma) ? &vma->gtt_view : NULL)) {
pr_err("i915_vma_compare failed with itself\n");
return ERR_PTR(-EINVAL);
}
if (!ok) {
pr_err("i915_vma_compare failed to detect the difference!\n");
return ERR_PTR(-EINVAL);
}
return vma;
}
static int create_vmas(struct drm_i915_private *i915,
struct list_head *objects,
struct list_head *contexts)
{
struct drm_i915_gem_object *obj;
struct i915_gem_context *ctx;
int pinned;
list_for_each_entry(obj, objects, st_link) {
for (pinned = 0; pinned <= 1; pinned++) {
list_for_each_entry(ctx, contexts, link) {
struct i915_address_space *vm;
struct i915_vma *vma;
int err;
vm = i915_gem_context_get_eb_vm(ctx);
vma = checked_vma_instance(obj, vm, NULL);
i915_vm_put(vm);
if (IS_ERR(vma))
return PTR_ERR(vma);
if (!assert_vma(vma, obj, ctx)) {
pr_err("VMA lookup/create failed\n");
return -EINVAL;
}
if (!pinned) {
err = i915_vma_pin(vma, 0, 0, PIN_USER);
if (err) {
pr_err("Failed to pin VMA\n");
return err;
}
} else {
i915_vma_unpin(vma);
}
}
}
}
return 0;
}
static int igt_vma_create(void *arg)
{
struct i915_ggtt *ggtt = arg;
struct drm_i915_private *i915 = ggtt->vm.i915;
struct drm_i915_gem_object *obj, *on;
struct i915_gem_context *ctx, *cn;
unsigned long num_obj, num_ctx;
unsigned long no, nc;
IGT_TIMEOUT(end_time);
LIST_HEAD(contexts);
LIST_HEAD(objects);
int err = -ENOMEM;
/* Exercise creating many vma amonst many objections, checking the
* vma creation and lookup routines.
*/
no = 0;
for_each_prime_number(num_obj, ULONG_MAX - 1) {
for (; no < num_obj; no++) {
obj = i915_gem_object_create_internal(i915, PAGE_SIZE);
if (IS_ERR(obj))
goto out;
list_add(&obj->st_link, &objects);
}
nc = 0;
for_each_prime_number(num_ctx, 2 * BITS_PER_LONG) {
for (; nc < num_ctx; nc++) {
ctx = mock_context(i915, "mock");
if (!ctx)
goto out;
list_move(&ctx->link, &contexts);
}
err = create_vmas(i915, &objects, &contexts);
if (err)
goto out;
if (igt_timeout(end_time,
"%s timed out: after %lu objects in %lu contexts\n",
__func__, no, nc))
goto end;
}
list_for_each_entry_safe(ctx, cn, &contexts, link) {
list_del_init(&ctx->link);
mock_context_close(ctx);
}
cond_resched();
}
end:
/* Final pass to lookup all created contexts */
err = create_vmas(i915, &objects, &contexts);
out:
list_for_each_entry_safe(ctx, cn, &contexts, link) {
list_del_init(&ctx->link);
mock_context_close(ctx);
}
list_for_each_entry_safe(obj, on, &objects, st_link)
i915_gem_object_put(obj);
return err;
}
struct pin_mode {
u64 size;
u64 flags;
bool (*assert)(const struct i915_vma *,
const struct pin_mode *mode,
int result);
const char *string;
};
static bool assert_pin_valid(const struct i915_vma *vma,
const struct pin_mode *mode,
int result)
{
if (result)
return false;
if (i915_vma_misplaced(vma, mode->size, 0, mode->flags))
return false;
return true;
}
__maybe_unused
static bool assert_pin_enospc(const struct i915_vma *vma,
const struct pin_mode *mode,
int result)
{
return result == -ENOSPC;
}
__maybe_unused
static bool assert_pin_einval(const struct i915_vma *vma,
const struct pin_mode *mode,
int result)
{
return result == -EINVAL;
}
static int igt_vma_pin1(void *arg)
{
struct i915_ggtt *ggtt = arg;
const struct pin_mode modes[] = {
#define VALID(sz, fl) { .size = (sz), .flags = (fl), .assert = assert_pin_valid, .string = #sz ", " #fl ", (valid) " }
#define __INVALID(sz, fl, check, eval) { .size = (sz), .flags = (fl), .assert = (check), .string = #sz ", " #fl ", (invalid " #eval ")" }
#define INVALID(sz, fl) __INVALID(sz, fl, assert_pin_einval, EINVAL)
#define NOSPACE(sz, fl) __INVALID(sz, fl, assert_pin_enospc, ENOSPC)
VALID(0, PIN_GLOBAL),
VALID(0, PIN_GLOBAL | PIN_MAPPABLE),
VALID(0, PIN_GLOBAL | PIN_OFFSET_BIAS | 4096),
VALID(0, PIN_GLOBAL | PIN_OFFSET_BIAS | 8192),
VALID(0, PIN_GLOBAL | PIN_OFFSET_BIAS | (ggtt->mappable_end - 4096)),
VALID(0, PIN_GLOBAL | PIN_MAPPABLE | PIN_OFFSET_BIAS | (ggtt->mappable_end - 4096)),
VALID(0, PIN_GLOBAL | PIN_OFFSET_BIAS | (ggtt->vm.total - 4096)),
VALID(0, PIN_GLOBAL | PIN_MAPPABLE | PIN_OFFSET_FIXED | (ggtt->mappable_end - 4096)),
INVALID(0, PIN_GLOBAL | PIN_MAPPABLE | PIN_OFFSET_FIXED | ggtt->mappable_end),
VALID(0, PIN_GLOBAL | PIN_OFFSET_FIXED | (ggtt->vm.total - 4096)),
INVALID(0, PIN_GLOBAL | PIN_OFFSET_FIXED | ggtt->vm.total),
INVALID(0, PIN_GLOBAL | PIN_OFFSET_FIXED | round_down(U64_MAX, PAGE_SIZE)),
VALID(4096, PIN_GLOBAL),
VALID(8192, PIN_GLOBAL),
VALID(ggtt->mappable_end - 4096, PIN_GLOBAL | PIN_MAPPABLE),
VALID(ggtt->mappable_end, PIN_GLOBAL | PIN_MAPPABLE),
NOSPACE(ggtt->mappable_end + 4096, PIN_GLOBAL | PIN_MAPPABLE),
VALID(ggtt->vm.total - 4096, PIN_GLOBAL),
VALID(ggtt->vm.total, PIN_GLOBAL),
NOSPACE(ggtt->vm.total + 4096, PIN_GLOBAL),
NOSPACE(round_down(U64_MAX, PAGE_SIZE), PIN_GLOBAL),
INVALID(8192, PIN_GLOBAL | PIN_MAPPABLE | PIN_OFFSET_FIXED | (ggtt->mappable_end - 4096)),
INVALID(8192, PIN_GLOBAL | PIN_OFFSET_FIXED | (ggtt->vm.total - 4096)),
INVALID(8192, PIN_GLOBAL | PIN_OFFSET_FIXED | (round_down(U64_MAX, PAGE_SIZE) - 4096)),
VALID(8192, PIN_GLOBAL | PIN_OFFSET_BIAS | (ggtt->mappable_end - 4096)),
#if !IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM)
/* Misusing BIAS is a programming error (it is not controllable
* from userspace) so when debugging is enabled, it explodes.
* However, the tests are still quite interesting for checking
* variable start, end and size.
*/
NOSPACE(0, PIN_GLOBAL | PIN_MAPPABLE | PIN_OFFSET_BIAS | ggtt->mappable_end),
NOSPACE(0, PIN_GLOBAL | PIN_OFFSET_BIAS | ggtt->vm.total),
NOSPACE(8192, PIN_GLOBAL | PIN_MAPPABLE | PIN_OFFSET_BIAS | (ggtt->mappable_end - 4096)),
NOSPACE(8192, PIN_GLOBAL | PIN_OFFSET_BIAS | (ggtt->vm.total - 4096)),
#endif
{ },
#undef NOSPACE
#undef INVALID
#undef __INVALID
#undef VALID
}, *m;
struct drm_i915_gem_object *obj;
struct i915_vma *vma;
int err = -EINVAL;
/* Exercise all the weird and wonderful i915_vma_pin requests,
* focusing on error handling of boundary conditions.
*/
GEM_BUG_ON(!drm_mm_clean(&ggtt->vm.mm));
obj = i915_gem_object_create_internal(ggtt->vm.i915, PAGE_SIZE);
if (IS_ERR(obj))
return PTR_ERR(obj);
vma = checked_vma_instance(obj, &ggtt->vm, NULL);
if (IS_ERR(vma))
goto out;
for (m = modes; m->assert; m++) {
err = i915_vma_pin(vma, m->size, 0, m->flags);
if (!m->assert(vma, m, err)) {
pr_err("%s to pin single page into GGTT with mode[%d:%s]: size=%llx flags=%llx, err=%d\n",
m->assert == assert_pin_valid ? "Failed" : "Unexpectedly succeeded",
(int)(m - modes), m->string, m->size, m->flags,
err);
if (!err)
i915_vma_unpin(vma);
err = -EINVAL;
goto out;
}
if (!err) {
i915_vma_unpin(vma);
err = i915_vma_unbind_unlocked(vma);
if (err) {
pr_err("Failed to unbind single page from GGTT, err=%d\n", err);
goto out;
}
}
cond_resched();
}
err = 0;
out:
i915_gem_object_put(obj);
return err;
}
static unsigned long rotated_index(const struct intel_rotation_info *r,
unsigned int n,
unsigned int x,
unsigned int y)
{
return (r->plane[n].src_stride * (r->plane[n].height - y - 1) +
r->plane[n].offset + x);
}
static struct scatterlist *
assert_rotated(struct drm_i915_gem_object *obj,
const struct intel_rotation_info *r, unsigned int n,
struct scatterlist *sg)
{
unsigned int x, y;
for (x = 0; x < r->plane[n].width; x++) {
unsigned int left;
for (y = 0; y < r->plane[n].height; y++) {
unsigned long src_idx;
dma_addr_t src;
if (!sg) {
pr_err("Invalid sg table: too short at plane %d, (%d, %d)!\n",
n, x, y);
return ERR_PTR(-EINVAL);
}
src_idx = rotated_index(r, n, x, y);
src = i915_gem_object_get_dma_address(obj, src_idx);
if (sg_dma_len(sg) != PAGE_SIZE) {
pr_err("Invalid sg.length, found %d, expected %lu for rotated page (%d, %d) [src index %lu]\n",
sg_dma_len(sg), PAGE_SIZE,
x, y, src_idx);
return ERR_PTR(-EINVAL);
}
if (sg_dma_address(sg) != src) {
pr_err("Invalid address for rotated page (%d, %d) [src index %lu]\n",
x, y, src_idx);
return ERR_PTR(-EINVAL);
}
sg = sg_next(sg);
}
left = (r->plane[n].dst_stride - y) * PAGE_SIZE;
if (!left)
continue;
if (!sg) {
pr_err("Invalid sg table: too short at plane %d, (%d, %d)!\n",
n, x, y);
return ERR_PTR(-EINVAL);
}
if (sg_dma_len(sg) != left) {
pr_err("Invalid sg.length, found %d, expected %u for rotated page (%d, %d)\n",
sg_dma_len(sg), left, x, y);
return ERR_PTR(-EINVAL);
}
if (sg_dma_address(sg) != 0) {
pr_err("Invalid address, found %pad, expected 0 for remapped page (%d, %d)\n",
&sg_dma_address(sg), x, y);
return ERR_PTR(-EINVAL);
}
sg = sg_next(sg);
}
return sg;
}
static unsigned long remapped_index(const struct intel_remapped_info *r,
unsigned int n,
unsigned int x,
unsigned int y)
{
return (r->plane[n].src_stride * y +
r->plane[n].offset + x);
}
static struct scatterlist *
assert_remapped(struct drm_i915_gem_object *obj,
const struct intel_remapped_info *r, unsigned int n,
struct scatterlist *sg)
{
unsigned int x, y;
unsigned int left = 0;
unsigned int offset;
for (y = 0; y < r->plane[n].height; y++) {
for (x = 0; x < r->plane[n].width; x++) {
unsigned long src_idx;
dma_addr_t src;
if (!sg) {
pr_err("Invalid sg table: too short at plane %d, (%d, %d)!\n",
n, x, y);
return ERR_PTR(-EINVAL);
}
if (!left) {
offset = 0;
left = sg_dma_len(sg);
}
src_idx = remapped_index(r, n, x, y);
src = i915_gem_object_get_dma_address(obj, src_idx);
if (left < PAGE_SIZE || left & (PAGE_SIZE-1)) {
pr_err("Invalid sg.length, found %d, expected %lu for remapped page (%d, %d) [src index %lu]\n",
sg_dma_len(sg), PAGE_SIZE,
x, y, src_idx);
return ERR_PTR(-EINVAL);
}
if (sg_dma_address(sg) + offset != src) {
pr_err("Invalid address for remapped page (%d, %d) [src index %lu]\n",
x, y, src_idx);
return ERR_PTR(-EINVAL);
}
left -= PAGE_SIZE;
offset += PAGE_SIZE;
if (!left)
sg = sg_next(sg);
}
if (left) {
pr_err("Unexpected sg tail with %d size for remapped page (%d, %d)\n",
left,
x, y);
return ERR_PTR(-EINVAL);
}
left = (r->plane[n].dst_stride - r->plane[n].width) * PAGE_SIZE;
if (!left)
continue;
if (!sg) {
pr_err("Invalid sg table: too short at plane %d, (%d, %d)!\n",
n, x, y);
return ERR_PTR(-EINVAL);
}
if (sg_dma_len(sg) != left) {
pr_err("Invalid sg.length, found %u, expected %u for remapped page (%d, %d)\n",
sg_dma_len(sg), left,
x, y);
return ERR_PTR(-EINVAL);
}
if (sg_dma_address(sg) != 0) {
pr_err("Invalid address, found %pad, expected 0 for remapped page (%d, %d)\n",
&sg_dma_address(sg),
x, y);
return ERR_PTR(-EINVAL);
}
sg = sg_next(sg);
left = 0;
}
return sg;
}
static unsigned int remapped_size(enum i915_gtt_view_type view_type,
const struct intel_remapped_plane_info *a,
const struct intel_remapped_plane_info *b)
{
if (view_type == I915_GTT_VIEW_ROTATED)
return a->dst_stride * a->width + b->dst_stride * b->width;
else
return a->dst_stride * a->height + b->dst_stride * b->height;
}
static int igt_vma_rotate_remap(void *arg)
{
struct i915_ggtt *ggtt = arg;
struct i915_address_space *vm = &ggtt->vm;
struct drm_i915_gem_object *obj;
const struct intel_remapped_plane_info planes[] = {
{ .width = 1, .height = 1, .src_stride = 1 },
{ .width = 2, .height = 2, .src_stride = 2 },
{ .width = 4, .height = 4, .src_stride = 4 },
{ .width = 8, .height = 8, .src_stride = 8 },
{ .width = 3, .height = 5, .src_stride = 3 },
{ .width = 3, .height = 5, .src_stride = 4 },
{ .width = 3, .height = 5, .src_stride = 5 },
{ .width = 5, .height = 3, .src_stride = 5 },
{ .width = 5, .height = 3, .src_stride = 7 },
{ .width = 5, .height = 3, .src_stride = 9 },
{ .width = 4, .height = 6, .src_stride = 6 },
{ .width = 6, .height = 4, .src_stride = 6 },
{ .width = 2, .height = 2, .src_stride = 2, .dst_stride = 2 },
{ .width = 3, .height = 3, .src_stride = 3, .dst_stride = 4 },
{ .width = 5, .height = 6, .src_stride = 7, .dst_stride = 8 },
{ }
}, *a, *b;
enum i915_gtt_view_type types[] = {
I915_GTT_VIEW_ROTATED,
I915_GTT_VIEW_REMAPPED,
0,
}, *t;
const unsigned int max_pages = 64;
int err = -ENOMEM;
/* Create VMA for many different combinations of planes and check
* that the page layout within the rotated VMA match our expectations.
*/
obj = i915_gem_object_create_internal(vm->i915, max_pages * PAGE_SIZE);
if (IS_ERR(obj))
goto out;
for (t = types; *t; t++) {
for (a = planes; a->width; a++) {
for (b = planes + ARRAY_SIZE(planes); b-- != planes; ) {
struct i915_gtt_view view = {
.type = *t,
.remapped.plane[0] = *a,
.remapped.plane[1] = *b,
};
struct intel_remapped_plane_info *plane_info = view.remapped.plane;
unsigned int n, max_offset;
max_offset = max(plane_info[0].src_stride * plane_info[0].height,
plane_info[1].src_stride * plane_info[1].height);
GEM_BUG_ON(max_offset > max_pages);
max_offset = max_pages - max_offset;
if (!plane_info[0].dst_stride)
plane_info[0].dst_stride = view.type == I915_GTT_VIEW_ROTATED ?
plane_info[0].height :
plane_info[0].width;
if (!plane_info[1].dst_stride)
plane_info[1].dst_stride = view.type == I915_GTT_VIEW_ROTATED ?
plane_info[1].height :
plane_info[1].width;
for_each_prime_number_from(plane_info[0].offset, 0, max_offset) {
for_each_prime_number_from(plane_info[1].offset, 0, max_offset) {
struct scatterlist *sg;
struct i915_vma *vma;
unsigned int expected_pages;
vma = checked_vma_instance(obj, vm, &view);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto out_object;
}
err = i915_vma_pin(vma, 0, 0, PIN_GLOBAL);
if (err) {
pr_err("Failed to pin VMA, err=%d\n", err);
goto out_object;
}
expected_pages = remapped_size(view.type, &plane_info[0], &plane_info[1]);
if (view.type == I915_GTT_VIEW_ROTATED &&
vma->size != expected_pages * PAGE_SIZE) {
pr_err("VMA is wrong size, expected %lu, found %llu\n",
PAGE_SIZE * expected_pages, vma->size);
err = -EINVAL;
goto out_object;
}
if (view.type == I915_GTT_VIEW_REMAPPED &&
vma->size > expected_pages * PAGE_SIZE) {
pr_err("VMA is wrong size, expected %lu, found %llu\n",
PAGE_SIZE * expected_pages, vma->size);
err = -EINVAL;
goto out_object;
}
if (vma->pages->nents > expected_pages) {
pr_err("sg table is wrong sizeo, expected %u, found %u nents\n",
expected_pages, vma->pages->nents);
err = -EINVAL;
goto out_object;
}
if (vma->node.size < vma->size) {
pr_err("VMA binding too small, expected %llu, found %llu\n",
vma->size, vma->node.size);
err = -EINVAL;
goto out_object;
}
if (vma->pages == obj->mm.pages) {
pr_err("VMA using unrotated object pages!\n");
err = -EINVAL;
goto out_object;
}
sg = vma->pages->sgl;
for (n = 0; n < ARRAY_SIZE(view.rotated.plane); n++) {
if (view.type == I915_GTT_VIEW_ROTATED)
sg = assert_rotated(obj, &view.rotated, n, sg);
else
sg = assert_remapped(obj, &view.remapped, n, sg);
if (IS_ERR(sg)) {
pr_err("Inconsistent %s VMA pages for plane %d: [(%d, %d, %d, %d, %d), (%d, %d, %d, %d, %d)]\n",
view.type == I915_GTT_VIEW_ROTATED ?
"rotated" : "remapped", n,
plane_info[0].width,
plane_info[0].height,
plane_info[0].src_stride,
plane_info[0].dst_stride,
plane_info[0].offset,
plane_info[1].width,
plane_info[1].height,
plane_info[1].src_stride,
plane_info[1].dst_stride,
plane_info[1].offset);
err = -EINVAL;
goto out_object;
}
}
i915_vma_unpin(vma);
err = i915_vma_unbind_unlocked(vma);
if (err) {
pr_err("Unbinding returned %i\n", err);
goto out_object;
}
cond_resched();
}
}
}
}
}
out_object:
i915_gem_object_put(obj);
out:
return err;
}
static bool assert_partial(struct drm_i915_gem_object *obj,
struct i915_vma *vma,
unsigned long offset,
unsigned long size)
{
struct sgt_iter sgt;
dma_addr_t dma;
for_each_sgt_daddr(dma, sgt, vma->pages) {
dma_addr_t src;
if (!size) {
pr_err("Partial scattergather list too long\n");
return false;
}
src = i915_gem_object_get_dma_address(obj, offset);
if (src != dma) {
pr_err("DMA mismatch for partial page offset %lu\n",
offset);
return false;
}
offset++;
size--;
}
return true;
}
static bool assert_pin(struct i915_vma *vma,
struct i915_gtt_view *view,
u64 size,
const char *name)
{
bool ok = true;
if (vma->size != size) {
pr_err("(%s) VMA is wrong size, expected %llu, found %llu\n",
name, size, vma->size);
ok = false;
}
if (vma->node.size < vma->size) {
pr_err("(%s) VMA binding too small, expected %llu, found %llu\n",
name, vma->size, vma->node.size);
ok = false;
}
if (view && view->type != I915_GTT_VIEW_NORMAL) {
if (memcmp(&vma->gtt_view, view, sizeof(*view))) {
pr_err("(%s) VMA mismatch upon creation!\n",
name);
ok = false;
}
if (vma->pages == vma->obj->mm.pages) {
pr_err("(%s) VMA using original object pages!\n",
name);
ok = false;
}
} else {
if (vma->gtt_view.type != I915_GTT_VIEW_NORMAL) {
pr_err("Not the normal ggtt view! Found %d\n",
vma->gtt_view.type);
ok = false;
}
if (vma->pages != vma->obj->mm.pages) {
pr_err("VMA not using object pages!\n");
ok = false;
}
}
return ok;
}
static int igt_vma_partial(void *arg)
{
struct i915_ggtt *ggtt = arg;
struct i915_address_space *vm = &ggtt->vm;
const unsigned int npages = 1021; /* prime! */
struct drm_i915_gem_object *obj;
const struct phase {
const char *name;
} phases[] = {
{ "create" },
{ "lookup" },
{ },
}, *p;
unsigned int sz, offset;
struct i915_vma *vma;
int err = -ENOMEM;
/* Create lots of different VMA for the object and check that
* we are returned the same VMA when we later request the same range.
*/
obj = i915_gem_object_create_internal(vm->i915, npages * PAGE_SIZE);
if (IS_ERR(obj))
goto out;
for (p = phases; p->name; p++) { /* exercise both create/lookup */
unsigned int count, nvma;
nvma = 0;
for_each_prime_number_from(sz, 1, npages) {
for_each_prime_number_from(offset, 0, npages - sz) {
struct i915_gtt_view view;
view.type = I915_GTT_VIEW_PARTIAL;
view.partial.offset = offset;
view.partial.size = sz;
if (sz == npages)
view.type = I915_GTT_VIEW_NORMAL;
vma = checked_vma_instance(obj, vm, &view);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto out_object;
}
err = i915_vma_pin(vma, 0, 0, PIN_GLOBAL);
if (err)
goto out_object;
if (!assert_pin(vma, &view, sz*PAGE_SIZE, p->name)) {
pr_err("(%s) Inconsistent partial pinning for (offset=%d, size=%d)\n",
p->name, offset, sz);
err = -EINVAL;
goto out_object;
}
if (!assert_partial(obj, vma, offset, sz)) {
pr_err("(%s) Inconsistent partial pages for (offset=%d, size=%d)\n",
p->name, offset, sz);
err = -EINVAL;
goto out_object;
}
i915_vma_unpin(vma);
nvma++;
err = i915_vma_unbind_unlocked(vma);
if (err) {
pr_err("Unbinding returned %i\n", err);
goto out_object;
}
cond_resched();
}
}
count = 0;
list_for_each_entry(vma, &obj->vma.list, obj_link)
count++;
if (count != nvma) {
pr_err("(%s) All partial vma were not recorded on the obj->vma_list: found %u, expected %u\n",
p->name, count, nvma);
err = -EINVAL;
goto out_object;
}
/* Check that we did create the whole object mapping */
vma = checked_vma_instance(obj, vm, NULL);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto out_object;
}
err = i915_vma_pin(vma, 0, 0, PIN_GLOBAL);
if (err)
goto out_object;
if (!assert_pin(vma, NULL, obj->base.size, p->name)) {
pr_err("(%s) inconsistent full pin\n", p->name);
err = -EINVAL;
goto out_object;
}
i915_vma_unpin(vma);
err = i915_vma_unbind_unlocked(vma);
if (err) {
pr_err("Unbinding returned %i\n", err);
goto out_object;
}
count = 0;
list_for_each_entry(vma, &obj->vma.list, obj_link)
count++;
if (count != nvma) {
pr_err("(%s) allocated an extra full vma!\n", p->name);
err = -EINVAL;
goto out_object;
}
}
out_object:
i915_gem_object_put(obj);
out:
return err;
}
int i915_vma_mock_selftests(void)
{
static const struct i915_subtest tests[] = {
SUBTEST(igt_vma_create),
SUBTEST(igt_vma_pin1),
SUBTEST(igt_vma_rotate_remap),
SUBTEST(igt_vma_partial),
};
struct drm_i915_private *i915;
struct intel_gt *gt;
int err;
i915 = mock_gem_device();
if (!i915)
return -ENOMEM;
/* allocate the ggtt */
err = intel_gt_assign_ggtt(to_gt(i915));
if (err)
goto out_put;
gt = to_gt(i915);
mock_init_ggtt(gt);
err = i915_subtests(tests, gt->ggtt);
mock_device_flush(i915);
i915_gem_drain_freed_objects(i915);
mock_fini_ggtt(gt->ggtt);
out_put:
mock_destroy_device(i915);
return err;
}
static int igt_vma_remapped_gtt(void *arg)
{
struct drm_i915_private *i915 = arg;
const struct intel_remapped_plane_info planes[] = {
{ .width = 1, .height = 1, .src_stride = 1 },
{ .width = 2, .height = 2, .src_stride = 2 },
{ .width = 4, .height = 4, .src_stride = 4 },
{ .width = 8, .height = 8, .src_stride = 8 },
{ .width = 3, .height = 5, .src_stride = 3 },
{ .width = 3, .height = 5, .src_stride = 4 },
{ .width = 3, .height = 5, .src_stride = 5 },
{ .width = 5, .height = 3, .src_stride = 5 },
{ .width = 5, .height = 3, .src_stride = 7 },
{ .width = 5, .height = 3, .src_stride = 9 },
{ .width = 4, .height = 6, .src_stride = 6 },
{ .width = 6, .height = 4, .src_stride = 6 },
{ .width = 2, .height = 2, .src_stride = 2, .dst_stride = 2 },
{ .width = 3, .height = 3, .src_stride = 3, .dst_stride = 4 },
{ .width = 5, .height = 6, .src_stride = 7, .dst_stride = 8 },
{ }
}, *p;
enum i915_gtt_view_type types[] = {
I915_GTT_VIEW_ROTATED,
I915_GTT_VIEW_REMAPPED,
0,
}, *t;
struct drm_i915_gem_object *obj;
intel_wakeref_t wakeref;
int err = 0;
if (!i915_ggtt_has_aperture(to_gt(i915)->ggtt))
return 0;
obj = i915_gem_object_create_internal(i915, 10 * 10 * PAGE_SIZE);
if (IS_ERR(obj))
return PTR_ERR(obj);
wakeref = intel_runtime_pm_get(&i915->runtime_pm);
for (t = types; *t; t++) {
for (p = planes; p->width; p++) {
struct i915_gtt_view view = {
.type = *t,
.rotated.plane[0] = *p,
};
struct intel_remapped_plane_info *plane_info = view.rotated.plane;
struct i915_vma *vma;
u32 __iomem *map;
unsigned int x, y;
i915_gem_object_lock(obj, NULL);
err = i915_gem_object_set_to_gtt_domain(obj, true);
i915_gem_object_unlock(obj);
if (err)
goto out;
if (!plane_info[0].dst_stride)
plane_info[0].dst_stride = *t == I915_GTT_VIEW_ROTATED ?
p->height : p->width;
vma = i915_gem_object_ggtt_pin(obj, &view, 0, 0, PIN_MAPPABLE);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto out;
}
GEM_BUG_ON(vma->gtt_view.type != *t);
map = i915_vma_pin_iomap(vma);
i915_vma_unpin(vma);
if (IS_ERR(map)) {
err = PTR_ERR(map);
goto out;
}
for (y = 0 ; y < plane_info[0].height; y++) {
for (x = 0 ; x < plane_info[0].width; x++) {
unsigned int offset;
u32 val = y << 16 | x;
if (*t == I915_GTT_VIEW_ROTATED)
offset = (x * plane_info[0].dst_stride + y) * PAGE_SIZE;
else
offset = (y * plane_info[0].dst_stride + x) * PAGE_SIZE;
iowrite32(val, &map[offset / sizeof(*map)]);
}
}
i915_vma_unpin_iomap(vma);
vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0, PIN_MAPPABLE);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto out;
}
GEM_BUG_ON(vma->gtt_view.type != I915_GTT_VIEW_NORMAL);
map = i915_vma_pin_iomap(vma);
i915_vma_unpin(vma);
if (IS_ERR(map)) {
err = PTR_ERR(map);
goto out;
}
for (y = 0 ; y < plane_info[0].height; y++) {
for (x = 0 ; x < plane_info[0].width; x++) {
unsigned int offset, src_idx;
u32 exp = y << 16 | x;
u32 val;
if (*t == I915_GTT_VIEW_ROTATED)
src_idx = rotated_index(&view.rotated, 0, x, y);
else
src_idx = remapped_index(&view.remapped, 0, x, y);
offset = src_idx * PAGE_SIZE;
val = ioread32(&map[offset / sizeof(*map)]);
if (val != exp) {
pr_err("%s VMA write test failed, expected 0x%x, found 0x%x\n",
*t == I915_GTT_VIEW_ROTATED ? "Rotated" : "Remapped",
exp, val);
i915_vma_unpin_iomap(vma);
err = -EINVAL;
goto out;
}
}
}
i915_vma_unpin_iomap(vma);
cond_resched();
}
}
out:
intel_runtime_pm_put(&i915->runtime_pm, wakeref);
i915_gem_object_put(obj);
return err;
}
int i915_vma_live_selftests(struct drm_i915_private *i915)
{
static const struct i915_subtest tests[] = {
SUBTEST(igt_vma_remapped_gtt),
};
return i915_live_subtests(tests, i915);
}
| linux-master | drivers/gpu/drm/i915/selftests/i915_vma.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2019 Intel Corporation
*/
#include <linux/string_helpers.h>
#include "i915_drv.h"
#include "i915_perf_types.h"
#include "intel_engine_regs.h"
#include "intel_gt_regs.h"
#include "intel_sseu.h"
void intel_sseu_set_info(struct sseu_dev_info *sseu, u8 max_slices,
u8 max_subslices, u8 max_eus_per_subslice)
{
sseu->max_slices = max_slices;
sseu->max_subslices = max_subslices;
sseu->max_eus_per_subslice = max_eus_per_subslice;
}
unsigned int
intel_sseu_subslice_total(const struct sseu_dev_info *sseu)
{
unsigned int i, total = 0;
if (sseu->has_xehp_dss)
return bitmap_weight(sseu->subslice_mask.xehp,
XEHP_BITMAP_BITS(sseu->subslice_mask));
for (i = 0; i < ARRAY_SIZE(sseu->subslice_mask.hsw); i++)
total += hweight8(sseu->subslice_mask.hsw[i]);
return total;
}
unsigned int
intel_sseu_get_hsw_subslices(const struct sseu_dev_info *sseu, u8 slice)
{
WARN_ON(sseu->has_xehp_dss);
if (WARN_ON(slice >= sseu->max_slices))
return 0;
return sseu->subslice_mask.hsw[slice];
}
static u16 sseu_get_eus(const struct sseu_dev_info *sseu, int slice,
int subslice)
{
if (sseu->has_xehp_dss) {
WARN_ON(slice > 0);
return sseu->eu_mask.xehp[subslice];
} else {
return sseu->eu_mask.hsw[slice][subslice];
}
}
static void sseu_set_eus(struct sseu_dev_info *sseu, int slice, int subslice,
u16 eu_mask)
{
GEM_WARN_ON(eu_mask && __fls(eu_mask) >= sseu->max_eus_per_subslice);
if (sseu->has_xehp_dss) {
GEM_WARN_ON(slice > 0);
sseu->eu_mask.xehp[subslice] = eu_mask;
} else {
sseu->eu_mask.hsw[slice][subslice] = eu_mask;
}
}
static u16 compute_eu_total(const struct sseu_dev_info *sseu)
{
int s, ss, total = 0;
for (s = 0; s < sseu->max_slices; s++)
for (ss = 0; ss < sseu->max_subslices; ss++)
if (sseu->has_xehp_dss)
total += hweight16(sseu->eu_mask.xehp[ss]);
else
total += hweight16(sseu->eu_mask.hsw[s][ss]);
return total;
}
/**
* intel_sseu_copy_eumask_to_user - Copy EU mask into a userspace buffer
* @to: Pointer to userspace buffer to copy to
* @sseu: SSEU structure containing EU mask to copy
*
* Copies the EU mask to a userspace buffer in the format expected by
* the query ioctl's topology queries.
*
* Returns the result of the copy_to_user() operation.
*/
int intel_sseu_copy_eumask_to_user(void __user *to,
const struct sseu_dev_info *sseu)
{
u8 eu_mask[GEN_SS_MASK_SIZE * GEN_MAX_EU_STRIDE] = {};
int eu_stride = GEN_SSEU_STRIDE(sseu->max_eus_per_subslice);
int len = sseu->max_slices * sseu->max_subslices * eu_stride;
int s, ss, i;
for (s = 0; s < sseu->max_slices; s++) {
for (ss = 0; ss < sseu->max_subslices; ss++) {
int uapi_offset =
s * sseu->max_subslices * eu_stride +
ss * eu_stride;
u16 mask = sseu_get_eus(sseu, s, ss);
for (i = 0; i < eu_stride; i++)
eu_mask[uapi_offset + i] =
(mask >> (BITS_PER_BYTE * i)) & 0xff;
}
}
return copy_to_user(to, eu_mask, len);
}
/**
* intel_sseu_copy_ssmask_to_user - Copy subslice mask into a userspace buffer
* @to: Pointer to userspace buffer to copy to
* @sseu: SSEU structure containing subslice mask to copy
*
* Copies the subslice mask to a userspace buffer in the format expected by
* the query ioctl's topology queries.
*
* Returns the result of the copy_to_user() operation.
*/
int intel_sseu_copy_ssmask_to_user(void __user *to,
const struct sseu_dev_info *sseu)
{
u8 ss_mask[GEN_SS_MASK_SIZE] = {};
int ss_stride = GEN_SSEU_STRIDE(sseu->max_subslices);
int len = sseu->max_slices * ss_stride;
int s, ss, i;
for (s = 0; s < sseu->max_slices; s++) {
for (ss = 0; ss < sseu->max_subslices; ss++) {
i = s * ss_stride * BITS_PER_BYTE + ss;
if (!intel_sseu_has_subslice(sseu, s, ss))
continue;
ss_mask[i / BITS_PER_BYTE] |= BIT(i % BITS_PER_BYTE);
}
}
return copy_to_user(to, ss_mask, len);
}
static void gen11_compute_sseu_info(struct sseu_dev_info *sseu,
u32 ss_en, u16 eu_en)
{
u32 valid_ss_mask = GENMASK(sseu->max_subslices - 1, 0);
int ss;
sseu->slice_mask |= BIT(0);
sseu->subslice_mask.hsw[0] = ss_en & valid_ss_mask;
for (ss = 0; ss < sseu->max_subslices; ss++)
if (intel_sseu_has_subslice(sseu, 0, ss))
sseu_set_eus(sseu, 0, ss, eu_en);
sseu->eu_per_subslice = hweight16(eu_en);
sseu->eu_total = compute_eu_total(sseu);
}
static void xehp_compute_sseu_info(struct sseu_dev_info *sseu,
u16 eu_en)
{
int ss;
sseu->slice_mask |= BIT(0);
bitmap_or(sseu->subslice_mask.xehp,
sseu->compute_subslice_mask.xehp,
sseu->geometry_subslice_mask.xehp,
XEHP_BITMAP_BITS(sseu->subslice_mask));
for (ss = 0; ss < sseu->max_subslices; ss++)
if (intel_sseu_has_subslice(sseu, 0, ss))
sseu_set_eus(sseu, 0, ss, eu_en);
sseu->eu_per_subslice = hweight16(eu_en);
sseu->eu_total = compute_eu_total(sseu);
}
static void
xehp_load_dss_mask(struct intel_uncore *uncore,
intel_sseu_ss_mask_t *ssmask,
int numregs,
...)
{
va_list argp;
u32 fuse_val[I915_MAX_SS_FUSE_REGS] = {};
int i;
if (WARN_ON(numregs > I915_MAX_SS_FUSE_REGS))
numregs = I915_MAX_SS_FUSE_REGS;
va_start(argp, numregs);
for (i = 0; i < numregs; i++)
fuse_val[i] = intel_uncore_read(uncore, va_arg(argp, i915_reg_t));
va_end(argp);
bitmap_from_arr32(ssmask->xehp, fuse_val, numregs * 32);
}
static void xehp_sseu_info_init(struct intel_gt *gt)
{
struct sseu_dev_info *sseu = >->info.sseu;
struct intel_uncore *uncore = gt->uncore;
u16 eu_en = 0;
u8 eu_en_fuse;
int num_compute_regs, num_geometry_regs;
int eu;
if (IS_PONTEVECCHIO(gt->i915)) {
num_geometry_regs = 0;
num_compute_regs = 2;
} else {
num_geometry_regs = 1;
num_compute_regs = 1;
}
/*
* The concept of slice has been removed in Xe_HP. To be compatible
* with prior generations, assume a single slice across the entire
* device. Then calculate out the DSS for each workload type within
* that software slice.
*/
intel_sseu_set_info(sseu, 1,
32 * max(num_geometry_regs, num_compute_regs),
HAS_ONE_EU_PER_FUSE_BIT(gt->i915) ? 8 : 16);
sseu->has_xehp_dss = 1;
xehp_load_dss_mask(uncore, &sseu->geometry_subslice_mask,
num_geometry_regs,
GEN12_GT_GEOMETRY_DSS_ENABLE);
xehp_load_dss_mask(uncore, &sseu->compute_subslice_mask,
num_compute_regs,
GEN12_GT_COMPUTE_DSS_ENABLE,
XEHPC_GT_COMPUTE_DSS_ENABLE_EXT);
eu_en_fuse = intel_uncore_read(uncore, XEHP_EU_ENABLE) & XEHP_EU_ENA_MASK;
if (HAS_ONE_EU_PER_FUSE_BIT(gt->i915))
eu_en = eu_en_fuse;
else
for (eu = 0; eu < sseu->max_eus_per_subslice / 2; eu++)
if (eu_en_fuse & BIT(eu))
eu_en |= BIT(eu * 2) | BIT(eu * 2 + 1);
xehp_compute_sseu_info(sseu, eu_en);
}
static void gen12_sseu_info_init(struct intel_gt *gt)
{
struct sseu_dev_info *sseu = >->info.sseu;
struct intel_uncore *uncore = gt->uncore;
u32 g_dss_en;
u16 eu_en = 0;
u8 eu_en_fuse;
u8 s_en;
int eu;
/*
* Gen12 has Dual-Subslices, which behave similarly to 2 gen11 SS.
* Instead of splitting these, provide userspace with an array
* of DSS to more closely represent the hardware resource.
*/
intel_sseu_set_info(sseu, 1, 6, 16);
/*
* Although gen12 architecture supported multiple slices, TGL, RKL,
* DG1, and ADL only had a single slice.
*/
s_en = intel_uncore_read(uncore, GEN11_GT_SLICE_ENABLE) &
GEN11_GT_S_ENA_MASK;
drm_WARN_ON(>->i915->drm, s_en != 0x1);
g_dss_en = intel_uncore_read(uncore, GEN12_GT_GEOMETRY_DSS_ENABLE);
/* one bit per pair of EUs */
eu_en_fuse = ~(intel_uncore_read(uncore, GEN11_EU_DISABLE) &
GEN11_EU_DIS_MASK);
for (eu = 0; eu < sseu->max_eus_per_subslice / 2; eu++)
if (eu_en_fuse & BIT(eu))
eu_en |= BIT(eu * 2) | BIT(eu * 2 + 1);
gen11_compute_sseu_info(sseu, g_dss_en, eu_en);
/* TGL only supports slice-level power gating */
sseu->has_slice_pg = 1;
}
static void gen11_sseu_info_init(struct intel_gt *gt)
{
struct sseu_dev_info *sseu = >->info.sseu;
struct intel_uncore *uncore = gt->uncore;
u32 ss_en;
u8 eu_en;
u8 s_en;
if (IS_JASPERLAKE(gt->i915) || IS_ELKHARTLAKE(gt->i915))
intel_sseu_set_info(sseu, 1, 4, 8);
else
intel_sseu_set_info(sseu, 1, 8, 8);
/*
* Although gen11 architecture supported multiple slices, ICL and
* EHL/JSL only had a single slice in practice.
*/
s_en = intel_uncore_read(uncore, GEN11_GT_SLICE_ENABLE) &
GEN11_GT_S_ENA_MASK;
drm_WARN_ON(>->i915->drm, s_en != 0x1);
ss_en = ~intel_uncore_read(uncore, GEN11_GT_SUBSLICE_DISABLE);
eu_en = ~(intel_uncore_read(uncore, GEN11_EU_DISABLE) &
GEN11_EU_DIS_MASK);
gen11_compute_sseu_info(sseu, ss_en, eu_en);
/* ICL has no power gating restrictions. */
sseu->has_slice_pg = 1;
sseu->has_subslice_pg = 1;
sseu->has_eu_pg = 1;
}
static void cherryview_sseu_info_init(struct intel_gt *gt)
{
struct sseu_dev_info *sseu = >->info.sseu;
u32 fuse;
fuse = intel_uncore_read(gt->uncore, CHV_FUSE_GT);
sseu->slice_mask = BIT(0);
intel_sseu_set_info(sseu, 1, 2, 8);
if (!(fuse & CHV_FGT_DISABLE_SS0)) {
u8 disabled_mask =
((fuse & CHV_FGT_EU_DIS_SS0_R0_MASK) >>
CHV_FGT_EU_DIS_SS0_R0_SHIFT) |
(((fuse & CHV_FGT_EU_DIS_SS0_R1_MASK) >>
CHV_FGT_EU_DIS_SS0_R1_SHIFT) << 4);
sseu->subslice_mask.hsw[0] |= BIT(0);
sseu_set_eus(sseu, 0, 0, ~disabled_mask & 0xFF);
}
if (!(fuse & CHV_FGT_DISABLE_SS1)) {
u8 disabled_mask =
((fuse & CHV_FGT_EU_DIS_SS1_R0_MASK) >>
CHV_FGT_EU_DIS_SS1_R0_SHIFT) |
(((fuse & CHV_FGT_EU_DIS_SS1_R1_MASK) >>
CHV_FGT_EU_DIS_SS1_R1_SHIFT) << 4);
sseu->subslice_mask.hsw[0] |= BIT(1);
sseu_set_eus(sseu, 0, 1, ~disabled_mask & 0xFF);
}
sseu->eu_total = compute_eu_total(sseu);
/*
* CHV expected to always have a uniform distribution of EU
* across subslices.
*/
sseu->eu_per_subslice = intel_sseu_subslice_total(sseu) ?
sseu->eu_total /
intel_sseu_subslice_total(sseu) :
0;
/*
* CHV supports subslice power gating on devices with more than
* one subslice, and supports EU power gating on devices with
* more than one EU pair per subslice.
*/
sseu->has_slice_pg = 0;
sseu->has_subslice_pg = intel_sseu_subslice_total(sseu) > 1;
sseu->has_eu_pg = (sseu->eu_per_subslice > 2);
}
static void gen9_sseu_info_init(struct intel_gt *gt)
{
struct drm_i915_private *i915 = gt->i915;
struct sseu_dev_info *sseu = >->info.sseu;
struct intel_uncore *uncore = gt->uncore;
u32 fuse2, eu_disable, subslice_mask;
const u8 eu_mask = 0xff;
int s, ss;
fuse2 = intel_uncore_read(uncore, GEN8_FUSE2);
sseu->slice_mask = (fuse2 & GEN8_F2_S_ENA_MASK) >> GEN8_F2_S_ENA_SHIFT;
/* BXT has a single slice and at most 3 subslices. */
intel_sseu_set_info(sseu, IS_GEN9_LP(i915) ? 1 : 3,
IS_GEN9_LP(i915) ? 3 : 4, 8);
/*
* The subslice disable field is global, i.e. it applies
* to each of the enabled slices.
*/
subslice_mask = (1 << sseu->max_subslices) - 1;
subslice_mask &= ~((fuse2 & GEN9_F2_SS_DIS_MASK) >>
GEN9_F2_SS_DIS_SHIFT);
/*
* Iterate through enabled slices and subslices to
* count the total enabled EU.
*/
for (s = 0; s < sseu->max_slices; s++) {
if (!(sseu->slice_mask & BIT(s)))
/* skip disabled slice */
continue;
sseu->subslice_mask.hsw[s] = subslice_mask;
eu_disable = intel_uncore_read(uncore, GEN9_EU_DISABLE(s));
for (ss = 0; ss < sseu->max_subslices; ss++) {
int eu_per_ss;
u8 eu_disabled_mask;
if (!intel_sseu_has_subslice(sseu, s, ss))
/* skip disabled subslice */
continue;
eu_disabled_mask = (eu_disable >> (ss * 8)) & eu_mask;
sseu_set_eus(sseu, s, ss, ~eu_disabled_mask & eu_mask);
eu_per_ss = sseu->max_eus_per_subslice -
hweight8(eu_disabled_mask);
/*
* Record which subslice(s) has(have) 7 EUs. we
* can tune the hash used to spread work among
* subslices if they are unbalanced.
*/
if (eu_per_ss == 7)
sseu->subslice_7eu[s] |= BIT(ss);
}
}
sseu->eu_total = compute_eu_total(sseu);
/*
* SKL is expected to always have a uniform distribution
* of EU across subslices with the exception that any one
* EU in any one subslice may be fused off for die
* recovery. BXT is expected to be perfectly uniform in EU
* distribution.
*/
sseu->eu_per_subslice =
intel_sseu_subslice_total(sseu) ?
DIV_ROUND_UP(sseu->eu_total, intel_sseu_subslice_total(sseu)) :
0;
/*
* SKL+ supports slice power gating on devices with more than
* one slice, and supports EU power gating on devices with
* more than one EU pair per subslice. BXT+ supports subslice
* power gating on devices with more than one subslice, and
* supports EU power gating on devices with more than one EU
* pair per subslice.
*/
sseu->has_slice_pg =
!IS_GEN9_LP(i915) && hweight8(sseu->slice_mask) > 1;
sseu->has_subslice_pg =
IS_GEN9_LP(i915) && intel_sseu_subslice_total(sseu) > 1;
sseu->has_eu_pg = sseu->eu_per_subslice > 2;
if (IS_GEN9_LP(i915)) {
#define IS_SS_DISABLED(ss) (!(sseu->subslice_mask.hsw[0] & BIT(ss)))
RUNTIME_INFO(i915)->has_pooled_eu = hweight8(sseu->subslice_mask.hsw[0]) == 3;
sseu->min_eu_in_pool = 0;
if (HAS_POOLED_EU(i915)) {
if (IS_SS_DISABLED(2) || IS_SS_DISABLED(0))
sseu->min_eu_in_pool = 3;
else if (IS_SS_DISABLED(1))
sseu->min_eu_in_pool = 6;
else
sseu->min_eu_in_pool = 9;
}
#undef IS_SS_DISABLED
}
}
static void bdw_sseu_info_init(struct intel_gt *gt)
{
struct sseu_dev_info *sseu = >->info.sseu;
struct intel_uncore *uncore = gt->uncore;
int s, ss;
u32 fuse2, subslice_mask, eu_disable[3]; /* s_max */
u32 eu_disable0, eu_disable1, eu_disable2;
fuse2 = intel_uncore_read(uncore, GEN8_FUSE2);
sseu->slice_mask = (fuse2 & GEN8_F2_S_ENA_MASK) >> GEN8_F2_S_ENA_SHIFT;
intel_sseu_set_info(sseu, 3, 3, 8);
/*
* The subslice disable field is global, i.e. it applies
* to each of the enabled slices.
*/
subslice_mask = GENMASK(sseu->max_subslices - 1, 0);
subslice_mask &= ~((fuse2 & GEN8_F2_SS_DIS_MASK) >>
GEN8_F2_SS_DIS_SHIFT);
eu_disable0 = intel_uncore_read(uncore, GEN8_EU_DISABLE0);
eu_disable1 = intel_uncore_read(uncore, GEN8_EU_DISABLE1);
eu_disable2 = intel_uncore_read(uncore, GEN8_EU_DISABLE2);
eu_disable[0] = eu_disable0 & GEN8_EU_DIS0_S0_MASK;
eu_disable[1] = (eu_disable0 >> GEN8_EU_DIS0_S1_SHIFT) |
((eu_disable1 & GEN8_EU_DIS1_S1_MASK) <<
(32 - GEN8_EU_DIS0_S1_SHIFT));
eu_disable[2] = (eu_disable1 >> GEN8_EU_DIS1_S2_SHIFT) |
((eu_disable2 & GEN8_EU_DIS2_S2_MASK) <<
(32 - GEN8_EU_DIS1_S2_SHIFT));
/*
* Iterate through enabled slices and subslices to
* count the total enabled EU.
*/
for (s = 0; s < sseu->max_slices; s++) {
if (!(sseu->slice_mask & BIT(s)))
/* skip disabled slice */
continue;
sseu->subslice_mask.hsw[s] = subslice_mask;
for (ss = 0; ss < sseu->max_subslices; ss++) {
u8 eu_disabled_mask;
u32 n_disabled;
if (!intel_sseu_has_subslice(sseu, s, ss))
/* skip disabled subslice */
continue;
eu_disabled_mask =
eu_disable[s] >> (ss * sseu->max_eus_per_subslice);
sseu_set_eus(sseu, s, ss, ~eu_disabled_mask & 0xFF);
n_disabled = hweight8(eu_disabled_mask);
/*
* Record which subslices have 7 EUs.
*/
if (sseu->max_eus_per_subslice - n_disabled == 7)
sseu->subslice_7eu[s] |= 1 << ss;
}
}
sseu->eu_total = compute_eu_total(sseu);
/*
* BDW is expected to always have a uniform distribution of EU across
* subslices with the exception that any one EU in any one subslice may
* be fused off for die recovery.
*/
sseu->eu_per_subslice =
intel_sseu_subslice_total(sseu) ?
DIV_ROUND_UP(sseu->eu_total, intel_sseu_subslice_total(sseu)) :
0;
/*
* BDW supports slice power gating on devices with more than
* one slice.
*/
sseu->has_slice_pg = hweight8(sseu->slice_mask) > 1;
sseu->has_subslice_pg = 0;
sseu->has_eu_pg = 0;
}
static void hsw_sseu_info_init(struct intel_gt *gt)
{
struct drm_i915_private *i915 = gt->i915;
struct sseu_dev_info *sseu = >->info.sseu;
u32 fuse1;
u8 subslice_mask = 0;
int s, ss;
/*
* There isn't a register to tell us how many slices/subslices. We
* work off the PCI-ids here.
*/
switch (INTEL_INFO(i915)->gt) {
default:
MISSING_CASE(INTEL_INFO(i915)->gt);
fallthrough;
case 1:
sseu->slice_mask = BIT(0);
subslice_mask = BIT(0);
break;
case 2:
sseu->slice_mask = BIT(0);
subslice_mask = BIT(0) | BIT(1);
break;
case 3:
sseu->slice_mask = BIT(0) | BIT(1);
subslice_mask = BIT(0) | BIT(1);
break;
}
fuse1 = intel_uncore_read(gt->uncore, HSW_PAVP_FUSE1);
switch (REG_FIELD_GET(HSW_F1_EU_DIS_MASK, fuse1)) {
default:
MISSING_CASE(REG_FIELD_GET(HSW_F1_EU_DIS_MASK, fuse1));
fallthrough;
case HSW_F1_EU_DIS_10EUS:
sseu->eu_per_subslice = 10;
break;
case HSW_F1_EU_DIS_8EUS:
sseu->eu_per_subslice = 8;
break;
case HSW_F1_EU_DIS_6EUS:
sseu->eu_per_subslice = 6;
break;
}
intel_sseu_set_info(sseu, hweight8(sseu->slice_mask),
hweight8(subslice_mask),
sseu->eu_per_subslice);
for (s = 0; s < sseu->max_slices; s++) {
sseu->subslice_mask.hsw[s] = subslice_mask;
for (ss = 0; ss < sseu->max_subslices; ss++) {
sseu_set_eus(sseu, s, ss,
(1UL << sseu->eu_per_subslice) - 1);
}
}
sseu->eu_total = compute_eu_total(sseu);
/* No powergating for you. */
sseu->has_slice_pg = 0;
sseu->has_subslice_pg = 0;
sseu->has_eu_pg = 0;
}
void intel_sseu_info_init(struct intel_gt *gt)
{
struct drm_i915_private *i915 = gt->i915;
if (GRAPHICS_VER_FULL(i915) >= IP_VER(12, 50))
xehp_sseu_info_init(gt);
else if (GRAPHICS_VER(i915) >= 12)
gen12_sseu_info_init(gt);
else if (GRAPHICS_VER(i915) >= 11)
gen11_sseu_info_init(gt);
else if (GRAPHICS_VER(i915) >= 9)
gen9_sseu_info_init(gt);
else if (IS_BROADWELL(i915))
bdw_sseu_info_init(gt);
else if (IS_CHERRYVIEW(i915))
cherryview_sseu_info_init(gt);
else if (IS_HASWELL(i915))
hsw_sseu_info_init(gt);
}
u32 intel_sseu_make_rpcs(struct intel_gt *gt,
const struct intel_sseu *req_sseu)
{
struct drm_i915_private *i915 = gt->i915;
const struct sseu_dev_info *sseu = >->info.sseu;
bool subslice_pg = sseu->has_subslice_pg;
u8 slices, subslices;
u32 rpcs = 0;
/*
* No explicit RPCS request is needed to ensure full
* slice/subslice/EU enablement prior to Gen9.
*/
if (GRAPHICS_VER(i915) < 9)
return 0;
/*
* If i915/perf is active, we want a stable powergating configuration
* on the system. Use the configuration pinned by i915/perf.
*/
if (gt->perf.group && gt->perf.group[PERF_GROUP_OAG].exclusive_stream)
req_sseu = >->perf.sseu;
slices = hweight8(req_sseu->slice_mask);
subslices = hweight8(req_sseu->subslice_mask);
/*
* Since the SScount bitfield in GEN8_R_PWR_CLK_STATE is only three bits
* wide and Icelake has up to eight subslices, specfial programming is
* needed in order to correctly enable all subslices.
*
* According to documentation software must consider the configuration
* as 2x4x8 and hardware will translate this to 1x8x8.
*
* Furthemore, even though SScount is three bits, maximum documented
* value for it is four. From this some rules/restrictions follow:
*
* 1.
* If enabled subslice count is greater than four, two whole slices must
* be enabled instead.
*
* 2.
* When more than one slice is enabled, hardware ignores the subslice
* count altogether.
*
* From these restrictions it follows that it is not possible to enable
* a count of subslices between the SScount maximum of four restriction,
* and the maximum available number on a particular SKU. Either all
* subslices are enabled, or a count between one and four on the first
* slice.
*/
if (GRAPHICS_VER(i915) == 11 &&
slices == 1 &&
subslices > min_t(u8, 4, hweight8(sseu->subslice_mask.hsw[0]) / 2)) {
GEM_BUG_ON(subslices & 1);
subslice_pg = false;
slices *= 2;
}
/*
* Starting in Gen9, render power gating can leave
* slice/subslice/EU in a partially enabled state. We
* must make an explicit request through RPCS for full
* enablement.
*/
if (sseu->has_slice_pg) {
u32 mask, val = slices;
if (GRAPHICS_VER(i915) >= 11) {
mask = GEN11_RPCS_S_CNT_MASK;
val <<= GEN11_RPCS_S_CNT_SHIFT;
} else {
mask = GEN8_RPCS_S_CNT_MASK;
val <<= GEN8_RPCS_S_CNT_SHIFT;
}
GEM_BUG_ON(val & ~mask);
val &= mask;
rpcs |= GEN8_RPCS_ENABLE | GEN8_RPCS_S_CNT_ENABLE | val;
}
if (subslice_pg) {
u32 val = subslices;
val <<= GEN8_RPCS_SS_CNT_SHIFT;
GEM_BUG_ON(val & ~GEN8_RPCS_SS_CNT_MASK);
val &= GEN8_RPCS_SS_CNT_MASK;
rpcs |= GEN8_RPCS_ENABLE | GEN8_RPCS_SS_CNT_ENABLE | val;
}
if (sseu->has_eu_pg) {
u32 val;
val = req_sseu->min_eus_per_subslice << GEN8_RPCS_EU_MIN_SHIFT;
GEM_BUG_ON(val & ~GEN8_RPCS_EU_MIN_MASK);
val &= GEN8_RPCS_EU_MIN_MASK;
rpcs |= val;
val = req_sseu->max_eus_per_subslice << GEN8_RPCS_EU_MAX_SHIFT;
GEM_BUG_ON(val & ~GEN8_RPCS_EU_MAX_MASK);
val &= GEN8_RPCS_EU_MAX_MASK;
rpcs |= val;
rpcs |= GEN8_RPCS_ENABLE;
}
return rpcs;
}
void intel_sseu_dump(const struct sseu_dev_info *sseu, struct drm_printer *p)
{
int s;
if (sseu->has_xehp_dss) {
drm_printf(p, "subslice total: %u\n",
intel_sseu_subslice_total(sseu));
drm_printf(p, "geometry dss mask=%*pb\n",
XEHP_BITMAP_BITS(sseu->geometry_subslice_mask),
sseu->geometry_subslice_mask.xehp);
drm_printf(p, "compute dss mask=%*pb\n",
XEHP_BITMAP_BITS(sseu->compute_subslice_mask),
sseu->compute_subslice_mask.xehp);
} else {
drm_printf(p, "slice total: %u, mask=%04x\n",
hweight8(sseu->slice_mask), sseu->slice_mask);
drm_printf(p, "subslice total: %u\n",
intel_sseu_subslice_total(sseu));
for (s = 0; s < sseu->max_slices; s++) {
u8 ss_mask = sseu->subslice_mask.hsw[s];
drm_printf(p, "slice%d: %u subslices, mask=%08x\n",
s, hweight8(ss_mask), ss_mask);
}
}
drm_printf(p, "EU total: %u\n", sseu->eu_total);
drm_printf(p, "EU per subslice: %u\n", sseu->eu_per_subslice);
drm_printf(p, "has slice power gating: %s\n",
str_yes_no(sseu->has_slice_pg));
drm_printf(p, "has subslice power gating: %s\n",
str_yes_no(sseu->has_subslice_pg));
drm_printf(p, "has EU power gating: %s\n",
str_yes_no(sseu->has_eu_pg));
}
static void sseu_print_hsw_topology(const struct sseu_dev_info *sseu,
struct drm_printer *p)
{
int s, ss;
for (s = 0; s < sseu->max_slices; s++) {
u8 ss_mask = sseu->subslice_mask.hsw[s];
drm_printf(p, "slice%d: %u subslice(s) (0x%08x):\n",
s, hweight8(ss_mask), ss_mask);
for (ss = 0; ss < sseu->max_subslices; ss++) {
u16 enabled_eus = sseu_get_eus(sseu, s, ss);
drm_printf(p, "\tsubslice%d: %u EUs (0x%hx)\n",
ss, hweight16(enabled_eus), enabled_eus);
}
}
}
static void sseu_print_xehp_topology(const struct sseu_dev_info *sseu,
struct drm_printer *p)
{
int dss;
for (dss = 0; dss < sseu->max_subslices; dss++) {
u16 enabled_eus = sseu_get_eus(sseu, 0, dss);
drm_printf(p, "DSS_%02d: G:%3s C:%3s, %2u EUs (0x%04hx)\n", dss,
str_yes_no(test_bit(dss, sseu->geometry_subslice_mask.xehp)),
str_yes_no(test_bit(dss, sseu->compute_subslice_mask.xehp)),
hweight16(enabled_eus), enabled_eus);
}
}
void intel_sseu_print_topology(struct drm_i915_private *i915,
const struct sseu_dev_info *sseu,
struct drm_printer *p)
{
if (sseu->max_slices == 0) {
drm_printf(p, "Unavailable\n");
} else if (GRAPHICS_VER_FULL(i915) >= IP_VER(12, 50)) {
sseu_print_xehp_topology(sseu, p);
} else {
sseu_print_hsw_topology(sseu, p);
}
}
void intel_sseu_print_ss_info(const char *type,
const struct sseu_dev_info *sseu,
struct seq_file *m)
{
int s;
if (sseu->has_xehp_dss) {
seq_printf(m, " %s Geometry DSS: %u\n", type,
bitmap_weight(sseu->geometry_subslice_mask.xehp,
XEHP_BITMAP_BITS(sseu->geometry_subslice_mask)));
seq_printf(m, " %s Compute DSS: %u\n", type,
bitmap_weight(sseu->compute_subslice_mask.xehp,
XEHP_BITMAP_BITS(sseu->compute_subslice_mask)));
} else {
for (s = 0; s < fls(sseu->slice_mask); s++)
seq_printf(m, " %s Slice%i subslices: %u\n", type,
s, hweight8(sseu->subslice_mask.hsw[s]));
}
}
u16 intel_slicemask_from_xehp_dssmask(intel_sseu_ss_mask_t dss_mask,
int dss_per_slice)
{
intel_sseu_ss_mask_t per_slice_mask = {};
unsigned long slice_mask = 0;
int i;
WARN_ON(DIV_ROUND_UP(XEHP_BITMAP_BITS(dss_mask), dss_per_slice) >
8 * sizeof(slice_mask));
bitmap_fill(per_slice_mask.xehp, dss_per_slice);
for (i = 0; !bitmap_empty(dss_mask.xehp, XEHP_BITMAP_BITS(dss_mask)); i++) {
if (bitmap_intersects(dss_mask.xehp, per_slice_mask.xehp, dss_per_slice))
slice_mask |= BIT(i);
bitmap_shift_right(dss_mask.xehp, dss_mask.xehp, dss_per_slice,
XEHP_BITMAP_BITS(dss_mask));
}
return slice_mask;
}
| linux-master | drivers/gpu/drm/i915/gt/intel_sseu.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2014 Intel Corporation
*/
#include "gem/i915_gem_internal.h"
#include "i915_drv.h"
#include "intel_renderstate.h"
#include "intel_context.h"
#include "intel_gpu_commands.h"
#include "intel_ring.h"
static const struct intel_renderstate_rodata *
render_state_get_rodata(const struct intel_engine_cs *engine)
{
if (engine->class != RENDER_CLASS)
return NULL;
switch (GRAPHICS_VER(engine->i915)) {
case 6:
return &gen6_null_state;
case 7:
return &gen7_null_state;
case 8:
return &gen8_null_state;
case 9:
return &gen9_null_state;
}
return NULL;
}
/*
* Macro to add commands to auxiliary batch.
* This macro only checks for page overflow before inserting the commands,
* this is sufficient as the null state generator makes the final batch
* with two passes to build command and state separately. At this point
* the size of both are known and it compacts them by relocating the state
* right after the commands taking care of alignment so we should sufficient
* space below them for adding new commands.
*/
#define OUT_BATCH(batch, i, val) \
do { \
if ((i) >= PAGE_SIZE / sizeof(u32)) \
goto out; \
(batch)[(i)++] = (val); \
} while (0)
static int render_state_setup(struct intel_renderstate *so,
struct drm_i915_private *i915)
{
const struct intel_renderstate_rodata *rodata = so->rodata;
unsigned int i = 0, reloc_index = 0;
int ret = -EINVAL;
u32 *d;
d = i915_gem_object_pin_map(so->vma->obj, I915_MAP_WB);
if (IS_ERR(d))
return PTR_ERR(d);
while (i < rodata->batch_items) {
u32 s = rodata->batch[i];
if (i * 4 == rodata->reloc[reloc_index]) {
u64 r = s + i915_vma_offset(so->vma);
s = lower_32_bits(r);
if (HAS_64BIT_RELOC(i915)) {
if (i + 1 >= rodata->batch_items ||
rodata->batch[i + 1] != 0)
goto out;
d[i++] = s;
s = upper_32_bits(r);
}
reloc_index++;
}
d[i++] = s;
}
if (rodata->reloc[reloc_index] != -1) {
drm_err(&i915->drm, "only %d relocs resolved\n", reloc_index);
goto out;
}
so->batch_offset = i915_ggtt_offset(so->vma);
so->batch_size = rodata->batch_items * sizeof(u32);
while (i % CACHELINE_DWORDS)
OUT_BATCH(d, i, MI_NOOP);
so->aux_offset = i * sizeof(u32);
if (HAS_POOLED_EU(i915)) {
/*
* We always program 3x6 pool config but depending upon which
* subslice is disabled HW drops down to appropriate config
* shown below.
*
* In the below table 2x6 config always refers to
* fused-down version, native 2x6 is not available and can
* be ignored
*
* SNo subslices config eu pool configuration
* -----------------------------------------------------------
* 1 3 subslices enabled (3x6) - 0x00777000 (9+9)
* 2 ss0 disabled (2x6) - 0x00777000 (3+9)
* 3 ss1 disabled (2x6) - 0x00770000 (6+6)
* 4 ss2 disabled (2x6) - 0x00007000 (9+3)
*/
u32 eu_pool_config = 0x00777000;
OUT_BATCH(d, i, GEN9_MEDIA_POOL_STATE);
OUT_BATCH(d, i, GEN9_MEDIA_POOL_ENABLE);
OUT_BATCH(d, i, eu_pool_config);
OUT_BATCH(d, i, 0);
OUT_BATCH(d, i, 0);
OUT_BATCH(d, i, 0);
}
OUT_BATCH(d, i, MI_BATCH_BUFFER_END);
so->aux_size = i * sizeof(u32) - so->aux_offset;
so->aux_offset += so->batch_offset;
/*
* Since we are sending length, we need to strictly conform to
* all requirements. For Gen2 this must be a multiple of 8.
*/
so->aux_size = ALIGN(so->aux_size, 8);
ret = 0;
out:
__i915_gem_object_flush_map(so->vma->obj, 0, i * sizeof(u32));
__i915_gem_object_release_map(so->vma->obj);
return ret;
}
#undef OUT_BATCH
int intel_renderstate_init(struct intel_renderstate *so,
struct intel_context *ce)
{
struct intel_engine_cs *engine = ce->engine;
struct drm_i915_gem_object *obj = NULL;
int err;
memset(so, 0, sizeof(*so));
so->rodata = render_state_get_rodata(engine);
if (so->rodata) {
if (so->rodata->batch_items * 4 > PAGE_SIZE)
return -EINVAL;
obj = i915_gem_object_create_internal(engine->i915, PAGE_SIZE);
if (IS_ERR(obj))
return PTR_ERR(obj);
so->vma = i915_vma_instance(obj, &engine->gt->ggtt->vm, NULL);
if (IS_ERR(so->vma)) {
err = PTR_ERR(so->vma);
goto err_obj;
}
}
i915_gem_ww_ctx_init(&so->ww, true);
retry:
err = intel_context_pin_ww(ce, &so->ww);
if (err)
goto err_fini;
/* return early if there's nothing to setup */
if (!err && !so->rodata)
return 0;
err = i915_gem_object_lock(so->vma->obj, &so->ww);
if (err)
goto err_context;
err = i915_vma_pin_ww(so->vma, &so->ww, 0, 0, PIN_GLOBAL | PIN_HIGH);
if (err)
goto err_context;
err = render_state_setup(so, engine->i915);
if (err)
goto err_unpin;
return 0;
err_unpin:
i915_vma_unpin(so->vma);
err_context:
intel_context_unpin(ce);
err_fini:
if (err == -EDEADLK) {
err = i915_gem_ww_ctx_backoff(&so->ww);
if (!err)
goto retry;
}
i915_gem_ww_ctx_fini(&so->ww);
err_obj:
if (obj)
i915_gem_object_put(obj);
so->vma = NULL;
return err;
}
int intel_renderstate_emit(struct intel_renderstate *so,
struct i915_request *rq)
{
struct intel_engine_cs *engine = rq->engine;
int err;
if (!so->vma)
return 0;
err = i915_vma_move_to_active(so->vma, rq, 0);
if (err)
return err;
err = engine->emit_bb_start(rq,
so->batch_offset, so->batch_size,
I915_DISPATCH_SECURE);
if (err)
return err;
if (so->aux_size > 8) {
err = engine->emit_bb_start(rq,
so->aux_offset, so->aux_size,
I915_DISPATCH_SECURE);
if (err)
return err;
}
return 0;
}
void intel_renderstate_fini(struct intel_renderstate *so,
struct intel_context *ce)
{
if (so->vma) {
i915_vma_unpin(so->vma);
i915_vma_close(so->vma);
}
intel_context_unpin(ce);
i915_gem_ww_ctx_fini(&so->ww);
if (so->vma)
i915_gem_object_put(so->vma->obj);
}
| linux-master | drivers/gpu/drm/i915/gt/intel_renderstate.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2015-2021 Intel Corporation
*/
#include <linux/kthread.h>
#include <linux/string_helpers.h>
#include <trace/events/dma_fence.h>
#include <uapi/linux/sched/types.h>
#include "i915_drv.h"
#include "i915_trace.h"
#include "intel_breadcrumbs.h"
#include "intel_context.h"
#include "intel_engine_pm.h"
#include "intel_gt_pm.h"
#include "intel_gt_requests.h"
static bool irq_enable(struct intel_breadcrumbs *b)
{
return intel_engine_irq_enable(b->irq_engine);
}
static void irq_disable(struct intel_breadcrumbs *b)
{
intel_engine_irq_disable(b->irq_engine);
}
static void __intel_breadcrumbs_arm_irq(struct intel_breadcrumbs *b)
{
/*
* Since we are waiting on a request, the GPU should be busy
* and should have its own rpm reference.
*/
if (GEM_WARN_ON(!intel_gt_pm_get_if_awake(b->irq_engine->gt)))
return;
/*
* The breadcrumb irq will be disarmed on the interrupt after the
* waiters are signaled. This gives us a single interrupt window in
* which we can add a new waiter and avoid the cost of re-enabling
* the irq.
*/
WRITE_ONCE(b->irq_armed, true);
/* Requests may have completed before we could enable the interrupt. */
if (!b->irq_enabled++ && b->irq_enable(b))
irq_work_queue(&b->irq_work);
}
static void intel_breadcrumbs_arm_irq(struct intel_breadcrumbs *b)
{
if (!b->irq_engine)
return;
spin_lock(&b->irq_lock);
if (!b->irq_armed)
__intel_breadcrumbs_arm_irq(b);
spin_unlock(&b->irq_lock);
}
static void __intel_breadcrumbs_disarm_irq(struct intel_breadcrumbs *b)
{
GEM_BUG_ON(!b->irq_enabled);
if (!--b->irq_enabled)
b->irq_disable(b);
WRITE_ONCE(b->irq_armed, false);
intel_gt_pm_put_async(b->irq_engine->gt);
}
static void intel_breadcrumbs_disarm_irq(struct intel_breadcrumbs *b)
{
spin_lock(&b->irq_lock);
if (b->irq_armed)
__intel_breadcrumbs_disarm_irq(b);
spin_unlock(&b->irq_lock);
}
static void add_signaling_context(struct intel_breadcrumbs *b,
struct intel_context *ce)
{
lockdep_assert_held(&ce->signal_lock);
spin_lock(&b->signalers_lock);
list_add_rcu(&ce->signal_link, &b->signalers);
spin_unlock(&b->signalers_lock);
}
static bool remove_signaling_context(struct intel_breadcrumbs *b,
struct intel_context *ce)
{
lockdep_assert_held(&ce->signal_lock);
if (!list_empty(&ce->signals))
return false;
spin_lock(&b->signalers_lock);
list_del_rcu(&ce->signal_link);
spin_unlock(&b->signalers_lock);
return true;
}
__maybe_unused static bool
check_signal_order(struct intel_context *ce, struct i915_request *rq)
{
if (rq->context != ce)
return false;
if (!list_is_last(&rq->signal_link, &ce->signals) &&
i915_seqno_passed(rq->fence.seqno,
list_next_entry(rq, signal_link)->fence.seqno))
return false;
if (!list_is_first(&rq->signal_link, &ce->signals) &&
i915_seqno_passed(list_prev_entry(rq, signal_link)->fence.seqno,
rq->fence.seqno))
return false;
return true;
}
static bool
__dma_fence_signal(struct dma_fence *fence)
{
return !test_and_set_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags);
}
static void
__dma_fence_signal__timestamp(struct dma_fence *fence, ktime_t timestamp)
{
fence->timestamp = timestamp;
set_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags);
trace_dma_fence_signaled(fence);
}
static void
__dma_fence_signal__notify(struct dma_fence *fence,
const struct list_head *list)
{
struct dma_fence_cb *cur, *tmp;
lockdep_assert_held(fence->lock);
list_for_each_entry_safe(cur, tmp, list, node) {
INIT_LIST_HEAD(&cur->node);
cur->func(fence, cur);
}
}
static void add_retire(struct intel_breadcrumbs *b, struct intel_timeline *tl)
{
if (b->irq_engine)
intel_engine_add_retire(b->irq_engine, tl);
}
static struct llist_node *
slist_add(struct llist_node *node, struct llist_node *head)
{
node->next = head;
return node;
}
static void signal_irq_work(struct irq_work *work)
{
struct intel_breadcrumbs *b = container_of(work, typeof(*b), irq_work);
const ktime_t timestamp = ktime_get();
struct llist_node *signal, *sn;
struct intel_context *ce;
signal = NULL;
if (unlikely(!llist_empty(&b->signaled_requests)))
signal = llist_del_all(&b->signaled_requests);
/*
* Keep the irq armed until the interrupt after all listeners are gone.
*
* Enabling/disabling the interrupt is rather costly, roughly a couple
* of hundred microseconds. If we are proactive and enable/disable
* the interrupt around every request that wants a breadcrumb, we
* quickly drown in the extra orders of magnitude of latency imposed
* on request submission.
*
* So we try to be lazy, and keep the interrupts enabled until no
* more listeners appear within a breadcrumb interrupt interval (that
* is until a request completes that no one cares about). The
* observation is that listeners come in batches, and will often
* listen to a bunch of requests in succession. Though note on icl+,
* interrupts are always enabled due to concerns with rc6 being
* dysfunctional with per-engine interrupt masking.
*
* We also try to avoid raising too many interrupts, as they may
* be generated by userspace batches and it is unfortunately rather
* too easy to drown the CPU under a flood of GPU interrupts. Thus
* whenever no one appears to be listening, we turn off the interrupts.
* Fewer interrupts should conserve power -- at the very least, fewer
* interrupt draw less ire from other users of the system and tools
* like powertop.
*/
if (!signal && READ_ONCE(b->irq_armed) && list_empty(&b->signalers))
intel_breadcrumbs_disarm_irq(b);
rcu_read_lock();
atomic_inc(&b->signaler_active);
list_for_each_entry_rcu(ce, &b->signalers, signal_link) {
struct i915_request *rq;
list_for_each_entry_rcu(rq, &ce->signals, signal_link) {
bool release;
if (!__i915_request_is_complete(rq))
break;
if (!test_and_clear_bit(I915_FENCE_FLAG_SIGNAL,
&rq->fence.flags))
break;
/*
* Queue for execution after dropping the signaling
* spinlock as the callback chain may end up adding
* more signalers to the same context or engine.
*/
spin_lock(&ce->signal_lock);
list_del_rcu(&rq->signal_link);
release = remove_signaling_context(b, ce);
spin_unlock(&ce->signal_lock);
if (release) {
if (intel_timeline_is_last(ce->timeline, rq))
add_retire(b, ce->timeline);
intel_context_put(ce);
}
if (__dma_fence_signal(&rq->fence))
/* We own signal_node now, xfer to local list */
signal = slist_add(&rq->signal_node, signal);
else
i915_request_put(rq);
}
}
atomic_dec(&b->signaler_active);
rcu_read_unlock();
llist_for_each_safe(signal, sn, signal) {
struct i915_request *rq =
llist_entry(signal, typeof(*rq), signal_node);
struct list_head cb_list;
if (rq->engine->sched_engine->retire_inflight_request_prio)
rq->engine->sched_engine->retire_inflight_request_prio(rq);
spin_lock(&rq->lock);
list_replace(&rq->fence.cb_list, &cb_list);
__dma_fence_signal__timestamp(&rq->fence, timestamp);
__dma_fence_signal__notify(&rq->fence, &cb_list);
spin_unlock(&rq->lock);
i915_request_put(rq);
}
if (!READ_ONCE(b->irq_armed) && !list_empty(&b->signalers))
intel_breadcrumbs_arm_irq(b);
}
struct intel_breadcrumbs *
intel_breadcrumbs_create(struct intel_engine_cs *irq_engine)
{
struct intel_breadcrumbs *b;
b = kzalloc(sizeof(*b), GFP_KERNEL);
if (!b)
return NULL;
kref_init(&b->ref);
spin_lock_init(&b->signalers_lock);
INIT_LIST_HEAD(&b->signalers);
init_llist_head(&b->signaled_requests);
spin_lock_init(&b->irq_lock);
init_irq_work(&b->irq_work, signal_irq_work);
b->irq_engine = irq_engine;
b->irq_enable = irq_enable;
b->irq_disable = irq_disable;
return b;
}
void intel_breadcrumbs_reset(struct intel_breadcrumbs *b)
{
unsigned long flags;
if (!b->irq_engine)
return;
spin_lock_irqsave(&b->irq_lock, flags);
if (b->irq_enabled)
b->irq_enable(b);
else
b->irq_disable(b);
spin_unlock_irqrestore(&b->irq_lock, flags);
}
void __intel_breadcrumbs_park(struct intel_breadcrumbs *b)
{
if (!READ_ONCE(b->irq_armed))
return;
/* Kick the work once more to drain the signalers, and disarm the irq */
irq_work_sync(&b->irq_work);
while (READ_ONCE(b->irq_armed) && !atomic_read(&b->active)) {
local_irq_disable();
signal_irq_work(&b->irq_work);
local_irq_enable();
cond_resched();
}
}
void intel_breadcrumbs_free(struct kref *kref)
{
struct intel_breadcrumbs *b = container_of(kref, typeof(*b), ref);
irq_work_sync(&b->irq_work);
GEM_BUG_ON(!list_empty(&b->signalers));
GEM_BUG_ON(b->irq_armed);
kfree(b);
}
static void irq_signal_request(struct i915_request *rq,
struct intel_breadcrumbs *b)
{
if (!__dma_fence_signal(&rq->fence))
return;
i915_request_get(rq);
if (llist_add(&rq->signal_node, &b->signaled_requests))
irq_work_queue(&b->irq_work);
}
static void insert_breadcrumb(struct i915_request *rq)
{
struct intel_breadcrumbs *b = READ_ONCE(rq->engine)->breadcrumbs;
struct intel_context *ce = rq->context;
struct list_head *pos;
if (test_bit(I915_FENCE_FLAG_SIGNAL, &rq->fence.flags))
return;
/*
* If the request is already completed, we can transfer it
* straight onto a signaled list, and queue the irq worker for
* its signal completion.
*/
if (__i915_request_is_complete(rq)) {
irq_signal_request(rq, b);
return;
}
if (list_empty(&ce->signals)) {
intel_context_get(ce);
add_signaling_context(b, ce);
pos = &ce->signals;
} else {
/*
* We keep the seqno in retirement order, so we can break
* inside intel_engine_signal_breadcrumbs as soon as we've
* passed the last completed request (or seen a request that
* hasn't event started). We could walk the timeline->requests,
* but keeping a separate signalers_list has the advantage of
* hopefully being much smaller than the full list and so
* provides faster iteration and detection when there are no
* more interrupts required for this context.
*
* We typically expect to add new signalers in order, so we
* start looking for our insertion point from the tail of
* the list.
*/
list_for_each_prev(pos, &ce->signals) {
struct i915_request *it =
list_entry(pos, typeof(*it), signal_link);
if (i915_seqno_passed(rq->fence.seqno, it->fence.seqno))
break;
}
}
i915_request_get(rq);
list_add_rcu(&rq->signal_link, pos);
GEM_BUG_ON(!check_signal_order(ce, rq));
GEM_BUG_ON(test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &rq->fence.flags));
set_bit(I915_FENCE_FLAG_SIGNAL, &rq->fence.flags);
/*
* Defer enabling the interrupt to after HW submission and recheck
* the request as it may have completed and raised the interrupt as
* we were attaching it into the lists.
*/
if (!b->irq_armed || __i915_request_is_complete(rq))
irq_work_queue(&b->irq_work);
}
bool i915_request_enable_breadcrumb(struct i915_request *rq)
{
struct intel_context *ce = rq->context;
/* Serialises with i915_request_retire() using rq->lock */
if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &rq->fence.flags))
return true;
/*
* Peek at i915_request_submit()/i915_request_unsubmit() status.
*
* If the request is not yet active (and not signaled), we will
* attach the breadcrumb later.
*/
if (!test_bit(I915_FENCE_FLAG_ACTIVE, &rq->fence.flags))
return true;
spin_lock(&ce->signal_lock);
if (test_bit(I915_FENCE_FLAG_ACTIVE, &rq->fence.flags))
insert_breadcrumb(rq);
spin_unlock(&ce->signal_lock);
return true;
}
void i915_request_cancel_breadcrumb(struct i915_request *rq)
{
struct intel_breadcrumbs *b = READ_ONCE(rq->engine)->breadcrumbs;
struct intel_context *ce = rq->context;
bool release;
spin_lock(&ce->signal_lock);
if (!test_and_clear_bit(I915_FENCE_FLAG_SIGNAL, &rq->fence.flags)) {
spin_unlock(&ce->signal_lock);
return;
}
list_del_rcu(&rq->signal_link);
release = remove_signaling_context(b, ce);
spin_unlock(&ce->signal_lock);
if (release)
intel_context_put(ce);
if (__i915_request_is_complete(rq))
irq_signal_request(rq, b);
i915_request_put(rq);
}
void intel_context_remove_breadcrumbs(struct intel_context *ce,
struct intel_breadcrumbs *b)
{
struct i915_request *rq, *rn;
bool release = false;
unsigned long flags;
spin_lock_irqsave(&ce->signal_lock, flags);
if (list_empty(&ce->signals))
goto unlock;
list_for_each_entry_safe(rq, rn, &ce->signals, signal_link) {
GEM_BUG_ON(!__i915_request_is_complete(rq));
if (!test_and_clear_bit(I915_FENCE_FLAG_SIGNAL,
&rq->fence.flags))
continue;
list_del_rcu(&rq->signal_link);
irq_signal_request(rq, b);
i915_request_put(rq);
}
release = remove_signaling_context(b, ce);
unlock:
spin_unlock_irqrestore(&ce->signal_lock, flags);
if (release)
intel_context_put(ce);
while (atomic_read(&b->signaler_active))
cpu_relax();
}
static void print_signals(struct intel_breadcrumbs *b, struct drm_printer *p)
{
struct intel_context *ce;
struct i915_request *rq;
drm_printf(p, "Signals:\n");
rcu_read_lock();
list_for_each_entry_rcu(ce, &b->signalers, signal_link) {
list_for_each_entry_rcu(rq, &ce->signals, signal_link)
drm_printf(p, "\t[%llx:%llx%s] @ %dms\n",
rq->fence.context, rq->fence.seqno,
__i915_request_is_complete(rq) ? "!" :
__i915_request_has_started(rq) ? "*" :
"",
jiffies_to_msecs(jiffies - rq->emitted_jiffies));
}
rcu_read_unlock();
}
void intel_engine_print_breadcrumbs(struct intel_engine_cs *engine,
struct drm_printer *p)
{
struct intel_breadcrumbs *b;
b = engine->breadcrumbs;
if (!b)
return;
drm_printf(p, "IRQ: %s\n", str_enabled_disabled(b->irq_armed));
if (!list_empty(&b->signalers))
print_signals(b, p);
}
| linux-master | drivers/gpu/drm/i915/gt/intel_breadcrumbs.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2020 Intel Corporation
*/
/* Just a quick and causal check of the shmem_utils API */
static int igt_shmem_basic(void *ignored)
{
u32 datum = 0xdeadbeef, result;
struct file *file;
u32 *map;
int err;
file = shmem_create_from_data("mock", &datum, sizeof(datum));
if (IS_ERR(file))
return PTR_ERR(file);
result = 0;
err = shmem_read(file, 0, &result, sizeof(result));
if (err)
goto out_file;
if (result != datum) {
pr_err("Incorrect read back from shmemfs: %x != %x\n",
result, datum);
err = -EINVAL;
goto out_file;
}
result = 0xc0ffee;
err = shmem_write(file, 0, &result, sizeof(result));
if (err)
goto out_file;
map = shmem_pin_map(file);
if (!map) {
err = -ENOMEM;
goto out_file;
}
if (*map != result) {
pr_err("Incorrect read back via mmap of last write: %x != %x\n",
*map, result);
err = -EINVAL;
goto out_map;
}
out_map:
shmem_unpin_map(file, map);
out_file:
fput(file);
return err;
}
int shmem_utils_mock_selftests(void)
{
static const struct i915_subtest tests[] = {
SUBTEST(igt_shmem_basic),
};
return i915_subtests(tests, NULL);
}
| linux-master | drivers/gpu/drm/i915/gt/st_shmem_utils.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2018 Intel Corporation
*/
#include "gem/i915_gem_internal.h"
#include "gem/i915_gem_pm.h"
#include "gt/intel_engine_user.h"
#include "gt/intel_gt.h"
#include "i915_selftest.h"
#include "intel_reset.h"
#include "selftests/igt_flush_test.h"
#include "selftests/igt_reset.h"
#include "selftests/igt_spinner.h"
#include "selftests/intel_scheduler_helpers.h"
#include "selftests/mock_drm.h"
#include "gem/selftests/igt_gem_utils.h"
#include "gem/selftests/mock_context.h"
static const struct wo_register {
enum intel_platform platform;
u32 reg;
} wo_registers[] = {
{ INTEL_GEMINILAKE, 0x731c }
};
struct wa_lists {
struct i915_wa_list gt_wa_list;
struct {
struct i915_wa_list wa_list;
struct i915_wa_list ctx_wa_list;
} engine[I915_NUM_ENGINES];
};
static int request_add_sync(struct i915_request *rq, int err)
{
i915_request_get(rq);
i915_request_add(rq);
if (i915_request_wait(rq, 0, HZ / 5) < 0)
err = -EIO;
i915_request_put(rq);
return err;
}
static int request_add_spin(struct i915_request *rq, struct igt_spinner *spin)
{
int err = 0;
i915_request_get(rq);
i915_request_add(rq);
if (spin && !igt_wait_for_spinner(spin, rq))
err = -ETIMEDOUT;
i915_request_put(rq);
return err;
}
static void
reference_lists_init(struct intel_gt *gt, struct wa_lists *lists)
{
struct intel_engine_cs *engine;
enum intel_engine_id id;
memset(lists, 0, sizeof(*lists));
wa_init_start(&lists->gt_wa_list, gt, "GT_REF", "global");
gt_init_workarounds(gt, &lists->gt_wa_list);
wa_init_finish(&lists->gt_wa_list);
for_each_engine(engine, gt, id) {
struct i915_wa_list *wal = &lists->engine[id].wa_list;
wa_init_start(wal, gt, "REF", engine->name);
engine_init_workarounds(engine, wal);
wa_init_finish(wal);
__intel_engine_init_ctx_wa(engine,
&lists->engine[id].ctx_wa_list,
"CTX_REF");
}
}
static void
reference_lists_fini(struct intel_gt *gt, struct wa_lists *lists)
{
struct intel_engine_cs *engine;
enum intel_engine_id id;
for_each_engine(engine, gt, id)
intel_wa_list_free(&lists->engine[id].wa_list);
intel_wa_list_free(&lists->gt_wa_list);
}
static struct drm_i915_gem_object *
read_nonprivs(struct intel_context *ce)
{
struct intel_engine_cs *engine = ce->engine;
const u32 base = engine->mmio_base;
struct drm_i915_gem_object *result;
struct i915_request *rq;
struct i915_vma *vma;
u32 srm, *cs;
int err;
int i;
result = i915_gem_object_create_internal(engine->i915, PAGE_SIZE);
if (IS_ERR(result))
return result;
i915_gem_object_set_cache_coherency(result, I915_CACHE_LLC);
cs = i915_gem_object_pin_map_unlocked(result, I915_MAP_WB);
if (IS_ERR(cs)) {
err = PTR_ERR(cs);
goto err_obj;
}
memset(cs, 0xc5, PAGE_SIZE);
i915_gem_object_flush_map(result);
i915_gem_object_unpin_map(result);
vma = i915_vma_instance(result, &engine->gt->ggtt->vm, NULL);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto err_obj;
}
err = i915_vma_pin(vma, 0, 0, PIN_GLOBAL);
if (err)
goto err_obj;
rq = intel_context_create_request(ce);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
goto err_pin;
}
err = igt_vma_move_to_active_unlocked(vma, rq, EXEC_OBJECT_WRITE);
if (err)
goto err_req;
srm = MI_STORE_REGISTER_MEM | MI_SRM_LRM_GLOBAL_GTT;
if (GRAPHICS_VER(engine->i915) >= 8)
srm++;
cs = intel_ring_begin(rq, 4 * RING_MAX_NONPRIV_SLOTS);
if (IS_ERR(cs)) {
err = PTR_ERR(cs);
goto err_req;
}
for (i = 0; i < RING_MAX_NONPRIV_SLOTS; i++) {
*cs++ = srm;
*cs++ = i915_mmio_reg_offset(RING_FORCE_TO_NONPRIV(base, i));
*cs++ = i915_ggtt_offset(vma) + sizeof(u32) * i;
*cs++ = 0;
}
intel_ring_advance(rq, cs);
i915_request_add(rq);
i915_vma_unpin(vma);
return result;
err_req:
i915_request_add(rq);
err_pin:
i915_vma_unpin(vma);
err_obj:
i915_gem_object_put(result);
return ERR_PTR(err);
}
static u32
get_whitelist_reg(const struct intel_engine_cs *engine, unsigned int i)
{
i915_reg_t reg = i < engine->whitelist.count ?
engine->whitelist.list[i].reg :
RING_NOPID(engine->mmio_base);
return i915_mmio_reg_offset(reg);
}
static void
print_results(const struct intel_engine_cs *engine, const u32 *results)
{
unsigned int i;
for (i = 0; i < RING_MAX_NONPRIV_SLOTS; i++) {
u32 expected = get_whitelist_reg(engine, i);
u32 actual = results[i];
pr_info("RING_NONPRIV[%d]: expected 0x%08x, found 0x%08x\n",
i, expected, actual);
}
}
static int check_whitelist(struct intel_context *ce)
{
struct intel_engine_cs *engine = ce->engine;
struct drm_i915_gem_object *results;
struct intel_wedge_me wedge;
u32 *vaddr;
int err;
int i;
results = read_nonprivs(ce);
if (IS_ERR(results))
return PTR_ERR(results);
err = 0;
i915_gem_object_lock(results, NULL);
intel_wedge_on_timeout(&wedge, engine->gt, HZ / 5) /* safety net! */
err = i915_gem_object_set_to_cpu_domain(results, false);
if (intel_gt_is_wedged(engine->gt))
err = -EIO;
if (err)
goto out_put;
vaddr = i915_gem_object_pin_map(results, I915_MAP_WB);
if (IS_ERR(vaddr)) {
err = PTR_ERR(vaddr);
goto out_put;
}
for (i = 0; i < RING_MAX_NONPRIV_SLOTS; i++) {
u32 expected = get_whitelist_reg(engine, i);
u32 actual = vaddr[i];
if (expected != actual) {
print_results(engine, vaddr);
pr_err("Invalid RING_NONPRIV[%d], expected 0x%08x, found 0x%08x\n",
i, expected, actual);
err = -EINVAL;
break;
}
}
i915_gem_object_unpin_map(results);
out_put:
i915_gem_object_unlock(results);
i915_gem_object_put(results);
return err;
}
static int do_device_reset(struct intel_engine_cs *engine)
{
intel_gt_reset(engine->gt, engine->mask, "live_workarounds");
return 0;
}
static int do_engine_reset(struct intel_engine_cs *engine)
{
return intel_engine_reset(engine, "live_workarounds");
}
static int do_guc_reset(struct intel_engine_cs *engine)
{
/* Currently a no-op as the reset is handled by GuC */
return 0;
}
static int
switch_to_scratch_context(struct intel_engine_cs *engine,
struct igt_spinner *spin,
struct i915_request **rq)
{
struct intel_context *ce;
int err = 0;
ce = intel_context_create(engine);
if (IS_ERR(ce))
return PTR_ERR(ce);
*rq = igt_spinner_create_request(spin, ce, MI_NOOP);
intel_context_put(ce);
if (IS_ERR(*rq)) {
spin = NULL;
err = PTR_ERR(*rq);
goto err;
}
err = request_add_spin(*rq, spin);
err:
if (err && spin)
igt_spinner_end(spin);
return err;
}
static int check_whitelist_across_reset(struct intel_engine_cs *engine,
int (*reset)(struct intel_engine_cs *),
const char *name)
{
struct intel_context *ce, *tmp;
struct igt_spinner spin;
struct i915_request *rq;
intel_wakeref_t wakeref;
int err;
pr_info("Checking %d whitelisted registers on %s (RING_NONPRIV) [%s]\n",
engine->whitelist.count, engine->name, name);
ce = intel_context_create(engine);
if (IS_ERR(ce))
return PTR_ERR(ce);
err = igt_spinner_init(&spin, engine->gt);
if (err)
goto out_ctx;
err = check_whitelist(ce);
if (err) {
pr_err("Invalid whitelist *before* %s reset!\n", name);
goto out_spin;
}
err = switch_to_scratch_context(engine, &spin, &rq);
if (err)
goto out_spin;
/* Ensure the spinner hasn't aborted */
if (i915_request_completed(rq)) {
pr_err("%s spinner failed to start\n", name);
err = -ETIMEDOUT;
goto out_spin;
}
with_intel_runtime_pm(engine->uncore->rpm, wakeref)
err = reset(engine);
/* Ensure the reset happens and kills the engine */
if (err == 0)
err = intel_selftest_wait_for_rq(rq);
igt_spinner_end(&spin);
if (err) {
pr_err("%s reset failed\n", name);
goto out_spin;
}
err = check_whitelist(ce);
if (err) {
pr_err("Whitelist not preserved in context across %s reset!\n",
name);
goto out_spin;
}
tmp = intel_context_create(engine);
if (IS_ERR(tmp)) {
err = PTR_ERR(tmp);
goto out_spin;
}
intel_context_put(ce);
ce = tmp;
err = check_whitelist(ce);
if (err) {
pr_err("Invalid whitelist *after* %s reset in fresh context!\n",
name);
goto out_spin;
}
out_spin:
igt_spinner_fini(&spin);
out_ctx:
intel_context_put(ce);
return err;
}
static struct i915_vma *create_batch(struct i915_address_space *vm)
{
struct drm_i915_gem_object *obj;
struct i915_vma *vma;
int err;
obj = i915_gem_object_create_internal(vm->i915, 16 * PAGE_SIZE);
if (IS_ERR(obj))
return ERR_CAST(obj);
vma = i915_vma_instance(obj, vm, NULL);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto err_obj;
}
err = i915_vma_pin(vma, 0, 0, PIN_USER);
if (err)
goto err_obj;
return vma;
err_obj:
i915_gem_object_put(obj);
return ERR_PTR(err);
}
static u32 reg_write(u32 old, u32 new, u32 rsvd)
{
if (rsvd == 0x0000ffff) {
old &= ~(new >> 16);
old |= new & (new >> 16);
} else {
old &= ~rsvd;
old |= new & rsvd;
}
return old;
}
static bool wo_register(struct intel_engine_cs *engine, u32 reg)
{
enum intel_platform platform = INTEL_INFO(engine->i915)->platform;
int i;
if ((reg & RING_FORCE_TO_NONPRIV_ACCESS_MASK) ==
RING_FORCE_TO_NONPRIV_ACCESS_WR)
return true;
for (i = 0; i < ARRAY_SIZE(wo_registers); i++) {
if (wo_registers[i].platform == platform &&
wo_registers[i].reg == reg)
return true;
}
return false;
}
static bool timestamp(const struct intel_engine_cs *engine, u32 reg)
{
reg = (reg - engine->mmio_base) & ~RING_FORCE_TO_NONPRIV_ACCESS_MASK;
switch (reg) {
case 0x358:
case 0x35c:
case 0x3a8:
return true;
default:
return false;
}
}
static bool ro_register(u32 reg)
{
if ((reg & RING_FORCE_TO_NONPRIV_ACCESS_MASK) ==
RING_FORCE_TO_NONPRIV_ACCESS_RD)
return true;
return false;
}
static int whitelist_writable_count(struct intel_engine_cs *engine)
{
int count = engine->whitelist.count;
int i;
for (i = 0; i < engine->whitelist.count; i++) {
u32 reg = i915_mmio_reg_offset(engine->whitelist.list[i].reg);
if (ro_register(reg))
count--;
}
return count;
}
static int check_dirty_whitelist(struct intel_context *ce)
{
const u32 values[] = {
0x00000000,
0x01010101,
0x10100101,
0x03030303,
0x30300303,
0x05050505,
0x50500505,
0x0f0f0f0f,
0xf00ff00f,
0x10101010,
0xf0f01010,
0x30303030,
0xa0a03030,
0x50505050,
0xc0c05050,
0xf0f0f0f0,
0x11111111,
0x33333333,
0x55555555,
0x0000ffff,
0x00ff00ff,
0xff0000ff,
0xffff00ff,
0xffffffff,
};
struct intel_engine_cs *engine = ce->engine;
struct i915_vma *scratch;
struct i915_vma *batch;
int err = 0, i, v, sz;
u32 *cs, *results;
sz = (2 * ARRAY_SIZE(values) + 1) * sizeof(u32);
scratch = __vm_create_scratch_for_read_pinned(ce->vm, sz);
if (IS_ERR(scratch))
return PTR_ERR(scratch);
batch = create_batch(ce->vm);
if (IS_ERR(batch)) {
err = PTR_ERR(batch);
goto out_scratch;
}
for (i = 0; i < engine->whitelist.count; i++) {
u32 reg = i915_mmio_reg_offset(engine->whitelist.list[i].reg);
struct i915_gem_ww_ctx ww;
u64 addr = i915_vma_offset(scratch);
struct i915_request *rq;
u32 srm, lrm, rsvd;
u32 expect;
int idx;
bool ro_reg;
if (wo_register(engine, reg))
continue;
if (timestamp(engine, reg))
continue; /* timestamps are expected to autoincrement */
ro_reg = ro_register(reg);
i915_gem_ww_ctx_init(&ww, false);
retry:
cs = NULL;
err = i915_gem_object_lock(scratch->obj, &ww);
if (!err)
err = i915_gem_object_lock(batch->obj, &ww);
if (!err)
err = intel_context_pin_ww(ce, &ww);
if (err)
goto out;
cs = i915_gem_object_pin_map(batch->obj, I915_MAP_WC);
if (IS_ERR(cs)) {
err = PTR_ERR(cs);
goto out_ctx;
}
results = i915_gem_object_pin_map(scratch->obj, I915_MAP_WB);
if (IS_ERR(results)) {
err = PTR_ERR(results);
goto out_unmap_batch;
}
/* Clear non priv flags */
reg &= RING_FORCE_TO_NONPRIV_ADDRESS_MASK;
srm = MI_STORE_REGISTER_MEM;
lrm = MI_LOAD_REGISTER_MEM;
if (GRAPHICS_VER(engine->i915) >= 8)
lrm++, srm++;
pr_debug("%s: Writing garbage to %x\n",
engine->name, reg);
/* SRM original */
*cs++ = srm;
*cs++ = reg;
*cs++ = lower_32_bits(addr);
*cs++ = upper_32_bits(addr);
idx = 1;
for (v = 0; v < ARRAY_SIZE(values); v++) {
/* LRI garbage */
*cs++ = MI_LOAD_REGISTER_IMM(1);
*cs++ = reg;
*cs++ = values[v];
/* SRM result */
*cs++ = srm;
*cs++ = reg;
*cs++ = lower_32_bits(addr + sizeof(u32) * idx);
*cs++ = upper_32_bits(addr + sizeof(u32) * idx);
idx++;
}
for (v = 0; v < ARRAY_SIZE(values); v++) {
/* LRI garbage */
*cs++ = MI_LOAD_REGISTER_IMM(1);
*cs++ = reg;
*cs++ = ~values[v];
/* SRM result */
*cs++ = srm;
*cs++ = reg;
*cs++ = lower_32_bits(addr + sizeof(u32) * idx);
*cs++ = upper_32_bits(addr + sizeof(u32) * idx);
idx++;
}
GEM_BUG_ON(idx * sizeof(u32) > scratch->size);
/* LRM original -- don't leave garbage in the context! */
*cs++ = lrm;
*cs++ = reg;
*cs++ = lower_32_bits(addr);
*cs++ = upper_32_bits(addr);
*cs++ = MI_BATCH_BUFFER_END;
i915_gem_object_flush_map(batch->obj);
i915_gem_object_unpin_map(batch->obj);
intel_gt_chipset_flush(engine->gt);
cs = NULL;
rq = i915_request_create(ce);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
goto out_unmap_scratch;
}
if (engine->emit_init_breadcrumb) { /* Be nice if we hang */
err = engine->emit_init_breadcrumb(rq);
if (err)
goto err_request;
}
err = i915_vma_move_to_active(batch, rq, 0);
if (err)
goto err_request;
err = i915_vma_move_to_active(scratch, rq,
EXEC_OBJECT_WRITE);
if (err)
goto err_request;
err = engine->emit_bb_start(rq,
i915_vma_offset(batch), PAGE_SIZE,
0);
if (err)
goto err_request;
err_request:
err = request_add_sync(rq, err);
if (err) {
pr_err("%s: Futzing %x timedout; cancelling test\n",
engine->name, reg);
intel_gt_set_wedged(engine->gt);
goto out_unmap_scratch;
}
GEM_BUG_ON(values[ARRAY_SIZE(values) - 1] != 0xffffffff);
if (!ro_reg) {
/* detect write masking */
rsvd = results[ARRAY_SIZE(values)];
if (!rsvd) {
pr_err("%s: Unable to write to whitelisted register %x\n",
engine->name, reg);
err = -EINVAL;
goto out_unmap_scratch;
}
} else {
rsvd = 0;
}
expect = results[0];
idx = 1;
for (v = 0; v < ARRAY_SIZE(values); v++) {
if (ro_reg)
expect = results[0];
else
expect = reg_write(expect, values[v], rsvd);
if (results[idx] != expect)
err++;
idx++;
}
for (v = 0; v < ARRAY_SIZE(values); v++) {
if (ro_reg)
expect = results[0];
else
expect = reg_write(expect, ~values[v], rsvd);
if (results[idx] != expect)
err++;
idx++;
}
if (err) {
pr_err("%s: %d mismatch between values written to whitelisted register [%x], and values read back!\n",
engine->name, err, reg);
if (ro_reg)
pr_info("%s: Whitelisted read-only register: %x, original value %08x\n",
engine->name, reg, results[0]);
else
pr_info("%s: Whitelisted register: %x, original value %08x, rsvd %08x\n",
engine->name, reg, results[0], rsvd);
expect = results[0];
idx = 1;
for (v = 0; v < ARRAY_SIZE(values); v++) {
u32 w = values[v];
if (ro_reg)
expect = results[0];
else
expect = reg_write(expect, w, rsvd);
pr_info("Wrote %08x, read %08x, expect %08x\n",
w, results[idx], expect);
idx++;
}
for (v = 0; v < ARRAY_SIZE(values); v++) {
u32 w = ~values[v];
if (ro_reg)
expect = results[0];
else
expect = reg_write(expect, w, rsvd);
pr_info("Wrote %08x, read %08x, expect %08x\n",
w, results[idx], expect);
idx++;
}
err = -EINVAL;
}
out_unmap_scratch:
i915_gem_object_unpin_map(scratch->obj);
out_unmap_batch:
if (cs)
i915_gem_object_unpin_map(batch->obj);
out_ctx:
intel_context_unpin(ce);
out:
if (err == -EDEADLK) {
err = i915_gem_ww_ctx_backoff(&ww);
if (!err)
goto retry;
}
i915_gem_ww_ctx_fini(&ww);
if (err)
break;
}
if (igt_flush_test(engine->i915))
err = -EIO;
i915_vma_unpin_and_release(&batch, 0);
out_scratch:
i915_vma_unpin_and_release(&scratch, 0);
return err;
}
static int live_dirty_whitelist(void *arg)
{
struct intel_gt *gt = arg;
struct intel_engine_cs *engine;
enum intel_engine_id id;
/* Can the user write to the whitelisted registers? */
if (GRAPHICS_VER(gt->i915) < 7) /* minimum requirement for LRI, SRM, LRM */
return 0;
for_each_engine(engine, gt, id) {
struct intel_context *ce;
int err;
if (engine->whitelist.count == 0)
continue;
ce = intel_context_create(engine);
if (IS_ERR(ce))
return PTR_ERR(ce);
err = check_dirty_whitelist(ce);
intel_context_put(ce);
if (err)
return err;
}
return 0;
}
static int live_reset_whitelist(void *arg)
{
struct intel_gt *gt = arg;
struct intel_engine_cs *engine;
enum intel_engine_id id;
int err = 0;
/* If we reset the gpu, we should not lose the RING_NONPRIV */
igt_global_reset_lock(gt);
for_each_engine(engine, gt, id) {
if (engine->whitelist.count == 0)
continue;
if (intel_has_reset_engine(gt)) {
if (intel_engine_uses_guc(engine)) {
struct intel_selftest_saved_policy saved;
int err2;
err = intel_selftest_modify_policy(engine, &saved,
SELFTEST_SCHEDULER_MODIFY_FAST_RESET);
if (err)
goto out;
err = check_whitelist_across_reset(engine,
do_guc_reset,
"guc");
err2 = intel_selftest_restore_policy(engine, &saved);
if (err == 0)
err = err2;
} else {
err = check_whitelist_across_reset(engine,
do_engine_reset,
"engine");
}
if (err)
goto out;
}
if (intel_has_gpu_reset(gt)) {
err = check_whitelist_across_reset(engine,
do_device_reset,
"device");
if (err)
goto out;
}
}
out:
igt_global_reset_unlock(gt);
return err;
}
static int read_whitelisted_registers(struct intel_context *ce,
struct i915_vma *results)
{
struct intel_engine_cs *engine = ce->engine;
struct i915_request *rq;
int i, err = 0;
u32 srm, *cs;
rq = intel_context_create_request(ce);
if (IS_ERR(rq))
return PTR_ERR(rq);
err = igt_vma_move_to_active_unlocked(results, rq, EXEC_OBJECT_WRITE);
if (err)
goto err_req;
srm = MI_STORE_REGISTER_MEM;
if (GRAPHICS_VER(engine->i915) >= 8)
srm++;
cs = intel_ring_begin(rq, 4 * engine->whitelist.count);
if (IS_ERR(cs)) {
err = PTR_ERR(cs);
goto err_req;
}
for (i = 0; i < engine->whitelist.count; i++) {
u64 offset = i915_vma_offset(results) + sizeof(u32) * i;
u32 reg = i915_mmio_reg_offset(engine->whitelist.list[i].reg);
/* Clear non priv flags */
reg &= RING_FORCE_TO_NONPRIV_ADDRESS_MASK;
*cs++ = srm;
*cs++ = reg;
*cs++ = lower_32_bits(offset);
*cs++ = upper_32_bits(offset);
}
intel_ring_advance(rq, cs);
err_req:
return request_add_sync(rq, err);
}
static int scrub_whitelisted_registers(struct intel_context *ce)
{
struct intel_engine_cs *engine = ce->engine;
struct i915_request *rq;
struct i915_vma *batch;
int i, err = 0;
u32 *cs;
batch = create_batch(ce->vm);
if (IS_ERR(batch))
return PTR_ERR(batch);
cs = i915_gem_object_pin_map_unlocked(batch->obj, I915_MAP_WC);
if (IS_ERR(cs)) {
err = PTR_ERR(cs);
goto err_batch;
}
*cs++ = MI_LOAD_REGISTER_IMM(whitelist_writable_count(engine));
for (i = 0; i < engine->whitelist.count; i++) {
u32 reg = i915_mmio_reg_offset(engine->whitelist.list[i].reg);
if (ro_register(reg))
continue;
/* Clear non priv flags */
reg &= RING_FORCE_TO_NONPRIV_ADDRESS_MASK;
*cs++ = reg;
*cs++ = 0xffffffff;
}
*cs++ = MI_BATCH_BUFFER_END;
i915_gem_object_flush_map(batch->obj);
intel_gt_chipset_flush(engine->gt);
rq = intel_context_create_request(ce);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
goto err_unpin;
}
if (engine->emit_init_breadcrumb) { /* Be nice if we hang */
err = engine->emit_init_breadcrumb(rq);
if (err)
goto err_request;
}
err = igt_vma_move_to_active_unlocked(batch, rq, 0);
if (err)
goto err_request;
/* Perform the writes from an unprivileged "user" batch */
err = engine->emit_bb_start(rq, i915_vma_offset(batch), 0, 0);
err_request:
err = request_add_sync(rq, err);
err_unpin:
i915_gem_object_unpin_map(batch->obj);
err_batch:
i915_vma_unpin_and_release(&batch, 0);
return err;
}
struct regmask {
i915_reg_t reg;
u8 graphics_ver;
};
static bool find_reg(struct drm_i915_private *i915,
i915_reg_t reg,
const struct regmask *tbl,
unsigned long count)
{
u32 offset = i915_mmio_reg_offset(reg);
while (count--) {
if (GRAPHICS_VER(i915) == tbl->graphics_ver &&
i915_mmio_reg_offset(tbl->reg) == offset)
return true;
tbl++;
}
return false;
}
static bool pardon_reg(struct drm_i915_private *i915, i915_reg_t reg)
{
/* Alas, we must pardon some whitelists. Mistakes already made */
static const struct regmask pardon[] = {
{ GEN9_CTX_PREEMPT_REG, 9 },
{ _MMIO(0xb118), 9 }, /* GEN8_L3SQCREG4 */
};
return find_reg(i915, reg, pardon, ARRAY_SIZE(pardon));
}
static bool result_eq(struct intel_engine_cs *engine,
u32 a, u32 b, i915_reg_t reg)
{
if (a != b && !pardon_reg(engine->i915, reg)) {
pr_err("Whitelisted register 0x%4x not context saved: A=%08x, B=%08x\n",
i915_mmio_reg_offset(reg), a, b);
return false;
}
return true;
}
static bool writeonly_reg(struct drm_i915_private *i915, i915_reg_t reg)
{
/* Some registers do not seem to behave and our writes unreadable */
static const struct regmask wo[] = {
{ GEN9_SLICE_COMMON_ECO_CHICKEN1, 9 },
};
return find_reg(i915, reg, wo, ARRAY_SIZE(wo));
}
static bool result_neq(struct intel_engine_cs *engine,
u32 a, u32 b, i915_reg_t reg)
{
if (a == b && !writeonly_reg(engine->i915, reg)) {
pr_err("Whitelist register 0x%4x:%08x was unwritable\n",
i915_mmio_reg_offset(reg), a);
return false;
}
return true;
}
static int
check_whitelisted_registers(struct intel_engine_cs *engine,
struct i915_vma *A,
struct i915_vma *B,
bool (*fn)(struct intel_engine_cs *engine,
u32 a, u32 b,
i915_reg_t reg))
{
u32 *a, *b;
int i, err;
a = i915_gem_object_pin_map_unlocked(A->obj, I915_MAP_WB);
if (IS_ERR(a))
return PTR_ERR(a);
b = i915_gem_object_pin_map_unlocked(B->obj, I915_MAP_WB);
if (IS_ERR(b)) {
err = PTR_ERR(b);
goto err_a;
}
err = 0;
for (i = 0; i < engine->whitelist.count; i++) {
const struct i915_wa *wa = &engine->whitelist.list[i];
if (i915_mmio_reg_offset(wa->reg) &
RING_FORCE_TO_NONPRIV_ACCESS_RD)
continue;
if (!fn(engine, a[i], b[i], wa->reg))
err = -EINVAL;
}
i915_gem_object_unpin_map(B->obj);
err_a:
i915_gem_object_unpin_map(A->obj);
return err;
}
static int live_isolated_whitelist(void *arg)
{
struct intel_gt *gt = arg;
struct {
struct i915_vma *scratch[2];
} client[2] = {};
struct intel_engine_cs *engine;
enum intel_engine_id id;
int i, err = 0;
/*
* Check that a write into a whitelist register works, but
* invisible to a second context.
*/
if (!intel_engines_has_context_isolation(gt->i915))
return 0;
for (i = 0; i < ARRAY_SIZE(client); i++) {
client[i].scratch[0] =
__vm_create_scratch_for_read_pinned(gt->vm, 4096);
if (IS_ERR(client[i].scratch[0])) {
err = PTR_ERR(client[i].scratch[0]);
goto err;
}
client[i].scratch[1] =
__vm_create_scratch_for_read_pinned(gt->vm, 4096);
if (IS_ERR(client[i].scratch[1])) {
err = PTR_ERR(client[i].scratch[1]);
i915_vma_unpin_and_release(&client[i].scratch[0], 0);
goto err;
}
}
for_each_engine(engine, gt, id) {
struct intel_context *ce[2];
if (!engine->kernel_context->vm)
continue;
if (!whitelist_writable_count(engine))
continue;
ce[0] = intel_context_create(engine);
if (IS_ERR(ce[0])) {
err = PTR_ERR(ce[0]);
break;
}
ce[1] = intel_context_create(engine);
if (IS_ERR(ce[1])) {
err = PTR_ERR(ce[1]);
intel_context_put(ce[0]);
break;
}
/* Read default values */
err = read_whitelisted_registers(ce[0], client[0].scratch[0]);
if (err)
goto err_ce;
/* Try to overwrite registers (should only affect ctx0) */
err = scrub_whitelisted_registers(ce[0]);
if (err)
goto err_ce;
/* Read values from ctx1, we expect these to be defaults */
err = read_whitelisted_registers(ce[1], client[1].scratch[0]);
if (err)
goto err_ce;
/* Verify that both reads return the same default values */
err = check_whitelisted_registers(engine,
client[0].scratch[0],
client[1].scratch[0],
result_eq);
if (err)
goto err_ce;
/* Read back the updated values in ctx0 */
err = read_whitelisted_registers(ce[0], client[0].scratch[1]);
if (err)
goto err_ce;
/* User should be granted privilege to overwhite regs */
err = check_whitelisted_registers(engine,
client[0].scratch[0],
client[0].scratch[1],
result_neq);
err_ce:
intel_context_put(ce[1]);
intel_context_put(ce[0]);
if (err)
break;
}
err:
for (i = 0; i < ARRAY_SIZE(client); i++) {
i915_vma_unpin_and_release(&client[i].scratch[1], 0);
i915_vma_unpin_and_release(&client[i].scratch[0], 0);
}
if (igt_flush_test(gt->i915))
err = -EIO;
return err;
}
static bool
verify_wa_lists(struct intel_gt *gt, struct wa_lists *lists,
const char *str)
{
struct intel_engine_cs *engine;
enum intel_engine_id id;
bool ok = true;
ok &= wa_list_verify(gt, &lists->gt_wa_list, str);
for_each_engine(engine, gt, id) {
struct intel_context *ce;
ce = intel_context_create(engine);
if (IS_ERR(ce))
return false;
ok &= engine_wa_list_verify(ce,
&lists->engine[id].wa_list,
str) == 0;
ok &= engine_wa_list_verify(ce,
&lists->engine[id].ctx_wa_list,
str) == 0;
intel_context_put(ce);
}
return ok;
}
static int
live_gpu_reset_workarounds(void *arg)
{
struct intel_gt *gt = arg;
intel_wakeref_t wakeref;
struct wa_lists *lists;
bool ok;
if (!intel_has_gpu_reset(gt))
return 0;
lists = kzalloc(sizeof(*lists), GFP_KERNEL);
if (!lists)
return -ENOMEM;
pr_info("Verifying after GPU reset...\n");
igt_global_reset_lock(gt);
wakeref = intel_runtime_pm_get(gt->uncore->rpm);
reference_lists_init(gt, lists);
ok = verify_wa_lists(gt, lists, "before reset");
if (!ok)
goto out;
intel_gt_reset(gt, ALL_ENGINES, "live_workarounds");
ok = verify_wa_lists(gt, lists, "after reset");
out:
reference_lists_fini(gt, lists);
intel_runtime_pm_put(gt->uncore->rpm, wakeref);
igt_global_reset_unlock(gt);
kfree(lists);
return ok ? 0 : -ESRCH;
}
static int
live_engine_reset_workarounds(void *arg)
{
struct intel_gt *gt = arg;
struct intel_engine_cs *engine;
enum intel_engine_id id;
struct intel_context *ce;
struct igt_spinner spin;
struct i915_request *rq;
intel_wakeref_t wakeref;
struct wa_lists *lists;
int ret = 0;
if (!intel_has_reset_engine(gt))
return 0;
lists = kzalloc(sizeof(*lists), GFP_KERNEL);
if (!lists)
return -ENOMEM;
igt_global_reset_lock(gt);
wakeref = intel_runtime_pm_get(gt->uncore->rpm);
reference_lists_init(gt, lists);
for_each_engine(engine, gt, id) {
struct intel_selftest_saved_policy saved;
bool using_guc = intel_engine_uses_guc(engine);
bool ok;
int ret2;
pr_info("Verifying after %s reset...\n", engine->name);
ret = intel_selftest_modify_policy(engine, &saved,
SELFTEST_SCHEDULER_MODIFY_FAST_RESET);
if (ret)
break;
ce = intel_context_create(engine);
if (IS_ERR(ce)) {
ret = PTR_ERR(ce);
goto restore;
}
if (!using_guc) {
ok = verify_wa_lists(gt, lists, "before reset");
if (!ok) {
ret = -ESRCH;
goto err;
}
ret = intel_engine_reset(engine, "live_workarounds:idle");
if (ret) {
pr_err("%s: Reset failed while idle\n", engine->name);
goto err;
}
ok = verify_wa_lists(gt, lists, "after idle reset");
if (!ok) {
ret = -ESRCH;
goto err;
}
}
ret = igt_spinner_init(&spin, engine->gt);
if (ret)
goto err;
rq = igt_spinner_create_request(&spin, ce, MI_NOOP);
if (IS_ERR(rq)) {
ret = PTR_ERR(rq);
igt_spinner_fini(&spin);
goto err;
}
ret = request_add_spin(rq, &spin);
if (ret) {
pr_err("%s: Spinner failed to start\n", engine->name);
igt_spinner_fini(&spin);
goto err;
}
/* Ensure the spinner hasn't aborted */
if (i915_request_completed(rq)) {
ret = -ETIMEDOUT;
goto skip;
}
if (!using_guc) {
ret = intel_engine_reset(engine, "live_workarounds:active");
if (ret) {
pr_err("%s: Reset failed on an active spinner\n",
engine->name);
igt_spinner_fini(&spin);
goto err;
}
}
/* Ensure the reset happens and kills the engine */
if (ret == 0)
ret = intel_selftest_wait_for_rq(rq);
skip:
igt_spinner_end(&spin);
igt_spinner_fini(&spin);
ok = verify_wa_lists(gt, lists, "after busy reset");
if (!ok)
ret = -ESRCH;
err:
intel_context_put(ce);
restore:
ret2 = intel_selftest_restore_policy(engine, &saved);
if (ret == 0)
ret = ret2;
if (ret)
break;
}
reference_lists_fini(gt, lists);
intel_runtime_pm_put(gt->uncore->rpm, wakeref);
igt_global_reset_unlock(gt);
kfree(lists);
igt_flush_test(gt->i915);
return ret;
}
int intel_workarounds_live_selftests(struct drm_i915_private *i915)
{
static const struct i915_subtest tests[] = {
SUBTEST(live_dirty_whitelist),
SUBTEST(live_reset_whitelist),
SUBTEST(live_isolated_whitelist),
SUBTEST(live_gpu_reset_workarounds),
SUBTEST(live_engine_reset_workarounds),
};
if (intel_gt_is_wedged(to_gt(i915)))
return 0;
return intel_gt_live_subtests(tests, to_gt(i915));
}
| linux-master | drivers/gpu/drm/i915/gt/selftest_workarounds.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2020 Intel Corporation
*/
#include <linux/pm_qos.h>
#include <linux/sort.h>
#include "gem/i915_gem_internal.h"
#include "i915_reg.h"
#include "intel_engine_heartbeat.h"
#include "intel_engine_pm.h"
#include "intel_engine_regs.h"
#include "intel_gpu_commands.h"
#include "intel_gt_clock_utils.h"
#include "intel_gt_pm.h"
#include "intel_rc6.h"
#include "selftest_engine_heartbeat.h"
#include "selftest_rps.h"
#include "selftests/igt_flush_test.h"
#include "selftests/igt_spinner.h"
#include "selftests/librapl.h"
/* Try to isolate the impact of cstates from determing frequency response */
#define CPU_LATENCY 0 /* -1 to disable pm_qos, 0 to disable cstates */
static void dummy_rps_work(struct work_struct *wrk)
{
}
static int cmp_u64(const void *A, const void *B)
{
const u64 *a = A, *b = B;
if (*a < *b)
return -1;
else if (*a > *b)
return 1;
else
return 0;
}
static int cmp_u32(const void *A, const void *B)
{
const u32 *a = A, *b = B;
if (*a < *b)
return -1;
else if (*a > *b)
return 1;
else
return 0;
}
static struct i915_vma *
create_spin_counter(struct intel_engine_cs *engine,
struct i915_address_space *vm,
bool srm,
u32 **cancel,
u32 **counter)
{
enum {
COUNT,
INC,
__NGPR__,
};
#define CS_GPR(x) GEN8_RING_CS_GPR(engine->mmio_base, x)
struct drm_i915_gem_object *obj;
struct i915_vma *vma;
unsigned long end;
u32 *base, *cs;
int loop, i;
int err;
obj = i915_gem_object_create_internal(vm->i915, 64 << 10);
if (IS_ERR(obj))
return ERR_CAST(obj);
end = obj->base.size / sizeof(u32) - 1;
vma = i915_vma_instance(obj, vm, NULL);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto err_put;
}
err = i915_vma_pin(vma, 0, 0, PIN_USER);
if (err)
goto err_unlock;
i915_vma_lock(vma);
base = i915_gem_object_pin_map(obj, I915_MAP_WC);
if (IS_ERR(base)) {
err = PTR_ERR(base);
goto err_unpin;
}
cs = base;
*cs++ = MI_LOAD_REGISTER_IMM(__NGPR__ * 2);
for (i = 0; i < __NGPR__; i++) {
*cs++ = i915_mmio_reg_offset(CS_GPR(i));
*cs++ = 0;
*cs++ = i915_mmio_reg_offset(CS_GPR(i)) + 4;
*cs++ = 0;
}
*cs++ = MI_LOAD_REGISTER_IMM(1);
*cs++ = i915_mmio_reg_offset(CS_GPR(INC));
*cs++ = 1;
loop = cs - base;
/* Unroll the loop to avoid MI_BB_START stalls impacting measurements */
for (i = 0; i < 1024; i++) {
*cs++ = MI_MATH(4);
*cs++ = MI_MATH_LOAD(MI_MATH_REG_SRCA, MI_MATH_REG(COUNT));
*cs++ = MI_MATH_LOAD(MI_MATH_REG_SRCB, MI_MATH_REG(INC));
*cs++ = MI_MATH_ADD;
*cs++ = MI_MATH_STORE(MI_MATH_REG(COUNT), MI_MATH_REG_ACCU);
if (srm) {
*cs++ = MI_STORE_REGISTER_MEM_GEN8;
*cs++ = i915_mmio_reg_offset(CS_GPR(COUNT));
*cs++ = lower_32_bits(i915_vma_offset(vma) + end * sizeof(*cs));
*cs++ = upper_32_bits(i915_vma_offset(vma) + end * sizeof(*cs));
}
}
*cs++ = MI_BATCH_BUFFER_START_GEN8;
*cs++ = lower_32_bits(i915_vma_offset(vma) + loop * sizeof(*cs));
*cs++ = upper_32_bits(i915_vma_offset(vma) + loop * sizeof(*cs));
GEM_BUG_ON(cs - base > end);
i915_gem_object_flush_map(obj);
*cancel = base + loop;
*counter = srm ? memset32(base + end, 0, 1) : NULL;
return vma;
err_unpin:
i915_vma_unpin(vma);
err_unlock:
i915_vma_unlock(vma);
err_put:
i915_gem_object_put(obj);
return ERR_PTR(err);
}
static u8 wait_for_freq(struct intel_rps *rps, u8 freq, int timeout_ms)
{
u8 history[64], i;
unsigned long end;
int sleep;
i = 0;
memset(history, freq, sizeof(history));
sleep = 20;
/* The PCU does not change instantly, but drifts towards the goal? */
end = jiffies + msecs_to_jiffies(timeout_ms);
do {
u8 act;
act = read_cagf(rps);
if (time_after(jiffies, end))
return act;
/* Target acquired */
if (act == freq)
return act;
/* Any change within the last N samples? */
if (!memchr_inv(history, act, sizeof(history)))
return act;
history[i] = act;
i = (i + 1) % ARRAY_SIZE(history);
usleep_range(sleep, 2 * sleep);
sleep *= 2;
if (sleep > timeout_ms * 20)
sleep = timeout_ms * 20;
} while (1);
}
static u8 rps_set_check(struct intel_rps *rps, u8 freq)
{
mutex_lock(&rps->lock);
GEM_BUG_ON(!intel_rps_is_active(rps));
if (wait_for(!intel_rps_set(rps, freq), 50)) {
mutex_unlock(&rps->lock);
return 0;
}
GEM_BUG_ON(rps->last_freq != freq);
mutex_unlock(&rps->lock);
return wait_for_freq(rps, freq, 50);
}
static void show_pstate_limits(struct intel_rps *rps)
{
struct drm_i915_private *i915 = rps_to_i915(rps);
if (IS_BROXTON(i915)) {
pr_info("P_STATE_CAP[%x]: 0x%08x\n",
i915_mmio_reg_offset(BXT_RP_STATE_CAP),
intel_uncore_read(rps_to_uncore(rps),
BXT_RP_STATE_CAP));
} else if (GRAPHICS_VER(i915) == 9) {
pr_info("P_STATE_LIMITS[%x]: 0x%08x\n",
i915_mmio_reg_offset(GEN9_RP_STATE_LIMITS),
intel_uncore_read(rps_to_uncore(rps),
GEN9_RP_STATE_LIMITS));
}
}
int live_rps_clock_interval(void *arg)
{
struct intel_gt *gt = arg;
struct intel_rps *rps = >->rps;
void (*saved_work)(struct work_struct *wrk);
struct intel_engine_cs *engine;
enum intel_engine_id id;
struct igt_spinner spin;
int err = 0;
if (!intel_rps_is_enabled(rps) || GRAPHICS_VER(gt->i915) < 6)
return 0;
if (igt_spinner_init(&spin, gt))
return -ENOMEM;
intel_gt_pm_wait_for_idle(gt);
saved_work = rps->work.func;
rps->work.func = dummy_rps_work;
intel_gt_pm_get(gt);
intel_rps_disable(>->rps);
intel_gt_check_clock_frequency(gt);
for_each_engine(engine, gt, id) {
struct i915_request *rq;
u32 cycles;
u64 dt;
if (!intel_engine_can_store_dword(engine))
continue;
st_engine_heartbeat_disable(engine);
rq = igt_spinner_create_request(&spin,
engine->kernel_context,
MI_NOOP);
if (IS_ERR(rq)) {
st_engine_heartbeat_enable(engine);
err = PTR_ERR(rq);
break;
}
i915_request_add(rq);
if (!igt_wait_for_spinner(&spin, rq)) {
pr_err("%s: RPS spinner did not start\n",
engine->name);
igt_spinner_end(&spin);
st_engine_heartbeat_enable(engine);
intel_gt_set_wedged(engine->gt);
err = -EIO;
break;
}
intel_uncore_forcewake_get(gt->uncore, FORCEWAKE_ALL);
intel_uncore_write_fw(gt->uncore, GEN6_RP_CUR_UP_EI, 0);
/* Set the evaluation interval to infinity! */
intel_uncore_write_fw(gt->uncore,
GEN6_RP_UP_EI, 0xffffffff);
intel_uncore_write_fw(gt->uncore,
GEN6_RP_UP_THRESHOLD, 0xffffffff);
intel_uncore_write_fw(gt->uncore, GEN6_RP_CONTROL,
GEN6_RP_ENABLE | GEN6_RP_UP_BUSY_AVG);
if (wait_for(intel_uncore_read_fw(gt->uncore,
GEN6_RP_CUR_UP_EI),
10)) {
/* Just skip the test; assume lack of HW support */
pr_notice("%s: rps evaluation interval not ticking\n",
engine->name);
err = -ENODEV;
} else {
ktime_t dt_[5];
u32 cycles_[5];
int i;
for (i = 0; i < 5; i++) {
preempt_disable();
cycles_[i] = -intel_uncore_read_fw(gt->uncore, GEN6_RP_CUR_UP_EI);
dt_[i] = ktime_get();
udelay(1000);
cycles_[i] += intel_uncore_read_fw(gt->uncore, GEN6_RP_CUR_UP_EI);
dt_[i] = ktime_sub(ktime_get(), dt_[i]);
preempt_enable();
}
/* Use the median of both cycle/dt; close enough */
sort(cycles_, 5, sizeof(*cycles_), cmp_u32, NULL);
cycles = (cycles_[1] + 2 * cycles_[2] + cycles_[3]) / 4;
sort(dt_, 5, sizeof(*dt_), cmp_u64, NULL);
dt = div_u64(dt_[1] + 2 * dt_[2] + dt_[3], 4);
}
intel_uncore_write_fw(gt->uncore, GEN6_RP_CONTROL, 0);
intel_uncore_forcewake_put(gt->uncore, FORCEWAKE_ALL);
igt_spinner_end(&spin);
st_engine_heartbeat_enable(engine);
if (err == 0) {
u64 time = intel_gt_pm_interval_to_ns(gt, cycles);
u32 expected =
intel_gt_ns_to_pm_interval(gt, dt);
pr_info("%s: rps counted %d C0 cycles [%lldns] in %lldns [%d cycles], using GT clock frequency of %uKHz\n",
engine->name, cycles, time, dt, expected,
gt->clock_frequency / 1000);
if (10 * time < 8 * dt ||
8 * time > 10 * dt) {
pr_err("%s: rps clock time does not match walltime!\n",
engine->name);
err = -EINVAL;
}
if (10 * expected < 8 * cycles ||
8 * expected > 10 * cycles) {
pr_err("%s: walltime does not match rps clock ticks!\n",
engine->name);
err = -EINVAL;
}
}
if (igt_flush_test(gt->i915))
err = -EIO;
break; /* once is enough */
}
intel_rps_enable(>->rps);
intel_gt_pm_put(gt);
igt_spinner_fini(&spin);
intel_gt_pm_wait_for_idle(gt);
rps->work.func = saved_work;
if (err == -ENODEV) /* skipped, don't report a fail */
err = 0;
return err;
}
int live_rps_control(void *arg)
{
struct intel_gt *gt = arg;
struct intel_rps *rps = >->rps;
void (*saved_work)(struct work_struct *wrk);
struct intel_engine_cs *engine;
enum intel_engine_id id;
struct igt_spinner spin;
int err = 0;
/*
* Check that the actual frequency matches our requested frequency,
* to verify our control mechanism. We have to be careful that the
* PCU may throttle the GPU in which case the actual frequency used
* will be lowered than requested.
*/
if (!intel_rps_is_enabled(rps))
return 0;
if (IS_CHERRYVIEW(gt->i915)) /* XXX fragile PCU */
return 0;
if (igt_spinner_init(&spin, gt))
return -ENOMEM;
intel_gt_pm_wait_for_idle(gt);
saved_work = rps->work.func;
rps->work.func = dummy_rps_work;
intel_gt_pm_get(gt);
for_each_engine(engine, gt, id) {
struct i915_request *rq;
ktime_t min_dt, max_dt;
int f, limit;
int min, max;
if (!intel_engine_can_store_dword(engine))
continue;
st_engine_heartbeat_disable(engine);
rq = igt_spinner_create_request(&spin,
engine->kernel_context,
MI_NOOP);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
break;
}
i915_request_add(rq);
if (!igt_wait_for_spinner(&spin, rq)) {
pr_err("%s: RPS spinner did not start\n",
engine->name);
igt_spinner_end(&spin);
st_engine_heartbeat_enable(engine);
intel_gt_set_wedged(engine->gt);
err = -EIO;
break;
}
if (rps_set_check(rps, rps->min_freq) != rps->min_freq) {
pr_err("%s: could not set minimum frequency [%x], only %x!\n",
engine->name, rps->min_freq, read_cagf(rps));
igt_spinner_end(&spin);
st_engine_heartbeat_enable(engine);
show_pstate_limits(rps);
err = -EINVAL;
break;
}
for (f = rps->min_freq + 1; f < rps->max_freq; f++) {
if (rps_set_check(rps, f) < f)
break;
}
limit = rps_set_check(rps, f);
if (rps_set_check(rps, rps->min_freq) != rps->min_freq) {
pr_err("%s: could not restore minimum frequency [%x], only %x!\n",
engine->name, rps->min_freq, read_cagf(rps));
igt_spinner_end(&spin);
st_engine_heartbeat_enable(engine);
show_pstate_limits(rps);
err = -EINVAL;
break;
}
max_dt = ktime_get();
max = rps_set_check(rps, limit);
max_dt = ktime_sub(ktime_get(), max_dt);
min_dt = ktime_get();
min = rps_set_check(rps, rps->min_freq);
min_dt = ktime_sub(ktime_get(), min_dt);
igt_spinner_end(&spin);
st_engine_heartbeat_enable(engine);
pr_info("%s: range:[%x:%uMHz, %x:%uMHz] limit:[%x:%uMHz], %x:%x response %lluns:%lluns\n",
engine->name,
rps->min_freq, intel_gpu_freq(rps, rps->min_freq),
rps->max_freq, intel_gpu_freq(rps, rps->max_freq),
limit, intel_gpu_freq(rps, limit),
min, max, ktime_to_ns(min_dt), ktime_to_ns(max_dt));
if (limit == rps->min_freq) {
pr_err("%s: GPU throttled to minimum!\n",
engine->name);
show_pstate_limits(rps);
err = -ENODEV;
break;
}
if (igt_flush_test(gt->i915)) {
err = -EIO;
break;
}
}
intel_gt_pm_put(gt);
igt_spinner_fini(&spin);
intel_gt_pm_wait_for_idle(gt);
rps->work.func = saved_work;
return err;
}
static void show_pcu_config(struct intel_rps *rps)
{
struct drm_i915_private *i915 = rps_to_i915(rps);
unsigned int max_gpu_freq, min_gpu_freq;
intel_wakeref_t wakeref;
int gpu_freq;
if (!HAS_LLC(i915))
return;
min_gpu_freq = rps->min_freq;
max_gpu_freq = rps->max_freq;
if (GRAPHICS_VER(i915) >= 9) {
/* Convert GT frequency to 50 HZ units */
min_gpu_freq /= GEN9_FREQ_SCALER;
max_gpu_freq /= GEN9_FREQ_SCALER;
}
wakeref = intel_runtime_pm_get(rps_to_uncore(rps)->rpm);
pr_info("%5s %5s %5s\n", "GPU", "eCPU", "eRing");
for (gpu_freq = min_gpu_freq; gpu_freq <= max_gpu_freq; gpu_freq++) {
int ia_freq = gpu_freq;
snb_pcode_read(rps_to_gt(rps)->uncore, GEN6_PCODE_READ_MIN_FREQ_TABLE,
&ia_freq, NULL);
pr_info("%5d %5d %5d\n",
gpu_freq * 50,
((ia_freq >> 0) & 0xff) * 100,
((ia_freq >> 8) & 0xff) * 100);
}
intel_runtime_pm_put(rps_to_uncore(rps)->rpm, wakeref);
}
static u64 __measure_frequency(u32 *cntr, int duration_ms)
{
u64 dc, dt;
dc = READ_ONCE(*cntr);
dt = ktime_get();
usleep_range(1000 * duration_ms, 2000 * duration_ms);
dc = READ_ONCE(*cntr) - dc;
dt = ktime_get() - dt;
return div64_u64(1000 * 1000 * dc, dt);
}
static u64 measure_frequency_at(struct intel_rps *rps, u32 *cntr, int *freq)
{
u64 x[5];
int i;
*freq = rps_set_check(rps, *freq);
for (i = 0; i < 5; i++)
x[i] = __measure_frequency(cntr, 2);
*freq = (*freq + read_cagf(rps)) / 2;
/* A simple triangle filter for better result stability */
sort(x, 5, sizeof(*x), cmp_u64, NULL);
return div_u64(x[1] + 2 * x[2] + x[3], 4);
}
static u64 __measure_cs_frequency(struct intel_engine_cs *engine,
int duration_ms)
{
u64 dc, dt;
dc = intel_uncore_read_fw(engine->uncore, CS_GPR(0));
dt = ktime_get();
usleep_range(1000 * duration_ms, 2000 * duration_ms);
dc = intel_uncore_read_fw(engine->uncore, CS_GPR(0)) - dc;
dt = ktime_get() - dt;
return div64_u64(1000 * 1000 * dc, dt);
}
static u64 measure_cs_frequency_at(struct intel_rps *rps,
struct intel_engine_cs *engine,
int *freq)
{
u64 x[5];
int i;
*freq = rps_set_check(rps, *freq);
for (i = 0; i < 5; i++)
x[i] = __measure_cs_frequency(engine, 2);
*freq = (*freq + read_cagf(rps)) / 2;
/* A simple triangle filter for better result stability */
sort(x, 5, sizeof(*x), cmp_u64, NULL);
return div_u64(x[1] + 2 * x[2] + x[3], 4);
}
static bool scaled_within(u64 x, u64 y, u32 f_n, u32 f_d)
{
return f_d * x > f_n * y && f_n * x < f_d * y;
}
int live_rps_frequency_cs(void *arg)
{
void (*saved_work)(struct work_struct *wrk);
struct intel_gt *gt = arg;
struct intel_rps *rps = >->rps;
struct intel_engine_cs *engine;
struct pm_qos_request qos;
enum intel_engine_id id;
int err = 0;
/*
* The premise is that the GPU does change frequency at our behest.
* Let's check there is a correspondence between the requested
* frequency, the actual frequency, and the observed clock rate.
*/
if (!intel_rps_is_enabled(rps))
return 0;
if (GRAPHICS_VER(gt->i915) < 8) /* for CS simplicity */
return 0;
if (CPU_LATENCY >= 0)
cpu_latency_qos_add_request(&qos, CPU_LATENCY);
intel_gt_pm_wait_for_idle(gt);
saved_work = rps->work.func;
rps->work.func = dummy_rps_work;
for_each_engine(engine, gt, id) {
struct i915_request *rq;
struct i915_vma *vma;
u32 *cancel, *cntr;
struct {
u64 count;
int freq;
} min, max;
st_engine_heartbeat_disable(engine);
vma = create_spin_counter(engine,
engine->kernel_context->vm, false,
&cancel, &cntr);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
st_engine_heartbeat_enable(engine);
break;
}
rq = intel_engine_create_kernel_request(engine);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
goto err_vma;
}
err = i915_vma_move_to_active(vma, rq, 0);
if (!err)
err = rq->engine->emit_bb_start(rq,
i915_vma_offset(vma),
PAGE_SIZE, 0);
i915_request_add(rq);
if (err)
goto err_vma;
if (wait_for(intel_uncore_read(engine->uncore, CS_GPR(0)),
10)) {
pr_err("%s: timed loop did not start\n",
engine->name);
goto err_vma;
}
min.freq = rps->min_freq;
min.count = measure_cs_frequency_at(rps, engine, &min.freq);
max.freq = rps->max_freq;
max.count = measure_cs_frequency_at(rps, engine, &max.freq);
pr_info("%s: min:%lluKHz @ %uMHz, max:%lluKHz @ %uMHz [%d%%]\n",
engine->name,
min.count, intel_gpu_freq(rps, min.freq),
max.count, intel_gpu_freq(rps, max.freq),
(int)DIV64_U64_ROUND_CLOSEST(100 * min.freq * max.count,
max.freq * min.count));
if (!scaled_within(max.freq * min.count,
min.freq * max.count,
2, 3)) {
int f;
pr_err("%s: CS did not scale with frequency! scaled min:%llu, max:%llu\n",
engine->name,
max.freq * min.count,
min.freq * max.count);
show_pcu_config(rps);
for (f = min.freq + 1; f <= rps->max_freq; f++) {
int act = f;
u64 count;
count = measure_cs_frequency_at(rps, engine, &act);
if (act < f)
break;
pr_info("%s: %x:%uMHz: %lluKHz [%d%%]\n",
engine->name,
act, intel_gpu_freq(rps, act), count,
(int)DIV64_U64_ROUND_CLOSEST(100 * min.freq * count,
act * min.count));
f = act; /* may skip ahead [pcu granularity] */
}
err = -EINTR; /* ignore error, continue on with test */
}
err_vma:
*cancel = MI_BATCH_BUFFER_END;
i915_gem_object_flush_map(vma->obj);
i915_gem_object_unpin_map(vma->obj);
i915_vma_unpin(vma);
i915_vma_unlock(vma);
i915_vma_put(vma);
st_engine_heartbeat_enable(engine);
if (igt_flush_test(gt->i915))
err = -EIO;
if (err)
break;
}
intel_gt_pm_wait_for_idle(gt);
rps->work.func = saved_work;
if (CPU_LATENCY >= 0)
cpu_latency_qos_remove_request(&qos);
return err;
}
int live_rps_frequency_srm(void *arg)
{
void (*saved_work)(struct work_struct *wrk);
struct intel_gt *gt = arg;
struct intel_rps *rps = >->rps;
struct intel_engine_cs *engine;
struct pm_qos_request qos;
enum intel_engine_id id;
int err = 0;
/*
* The premise is that the GPU does change frequency at our behest.
* Let's check there is a correspondence between the requested
* frequency, the actual frequency, and the observed clock rate.
*/
if (!intel_rps_is_enabled(rps))
return 0;
if (GRAPHICS_VER(gt->i915) < 8) /* for CS simplicity */
return 0;
if (CPU_LATENCY >= 0)
cpu_latency_qos_add_request(&qos, CPU_LATENCY);
intel_gt_pm_wait_for_idle(gt);
saved_work = rps->work.func;
rps->work.func = dummy_rps_work;
for_each_engine(engine, gt, id) {
struct i915_request *rq;
struct i915_vma *vma;
u32 *cancel, *cntr;
struct {
u64 count;
int freq;
} min, max;
st_engine_heartbeat_disable(engine);
vma = create_spin_counter(engine,
engine->kernel_context->vm, true,
&cancel, &cntr);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
st_engine_heartbeat_enable(engine);
break;
}
rq = intel_engine_create_kernel_request(engine);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
goto err_vma;
}
err = i915_vma_move_to_active(vma, rq, 0);
if (!err)
err = rq->engine->emit_bb_start(rq,
i915_vma_offset(vma),
PAGE_SIZE, 0);
i915_request_add(rq);
if (err)
goto err_vma;
if (wait_for(READ_ONCE(*cntr), 10)) {
pr_err("%s: timed loop did not start\n",
engine->name);
goto err_vma;
}
min.freq = rps->min_freq;
min.count = measure_frequency_at(rps, cntr, &min.freq);
max.freq = rps->max_freq;
max.count = measure_frequency_at(rps, cntr, &max.freq);
pr_info("%s: min:%lluKHz @ %uMHz, max:%lluKHz @ %uMHz [%d%%]\n",
engine->name,
min.count, intel_gpu_freq(rps, min.freq),
max.count, intel_gpu_freq(rps, max.freq),
(int)DIV64_U64_ROUND_CLOSEST(100 * min.freq * max.count,
max.freq * min.count));
if (!scaled_within(max.freq * min.count,
min.freq * max.count,
1, 2)) {
int f;
pr_err("%s: CS did not scale with frequency! scaled min:%llu, max:%llu\n",
engine->name,
max.freq * min.count,
min.freq * max.count);
show_pcu_config(rps);
for (f = min.freq + 1; f <= rps->max_freq; f++) {
int act = f;
u64 count;
count = measure_frequency_at(rps, cntr, &act);
if (act < f)
break;
pr_info("%s: %x:%uMHz: %lluKHz [%d%%]\n",
engine->name,
act, intel_gpu_freq(rps, act), count,
(int)DIV64_U64_ROUND_CLOSEST(100 * min.freq * count,
act * min.count));
f = act; /* may skip ahead [pcu granularity] */
}
err = -EINTR; /* ignore error, continue on with test */
}
err_vma:
*cancel = MI_BATCH_BUFFER_END;
i915_gem_object_flush_map(vma->obj);
i915_gem_object_unpin_map(vma->obj);
i915_vma_unpin(vma);
i915_vma_unlock(vma);
i915_vma_put(vma);
st_engine_heartbeat_enable(engine);
if (igt_flush_test(gt->i915))
err = -EIO;
if (err)
break;
}
intel_gt_pm_wait_for_idle(gt);
rps->work.func = saved_work;
if (CPU_LATENCY >= 0)
cpu_latency_qos_remove_request(&qos);
return err;
}
static void sleep_for_ei(struct intel_rps *rps, int timeout_us)
{
/* Flush any previous EI */
usleep_range(timeout_us, 2 * timeout_us);
/* Reset the interrupt status */
rps_disable_interrupts(rps);
GEM_BUG_ON(rps->pm_iir);
rps_enable_interrupts(rps);
/* And then wait for the timeout, for real this time */
usleep_range(2 * timeout_us, 3 * timeout_us);
}
static int __rps_up_interrupt(struct intel_rps *rps,
struct intel_engine_cs *engine,
struct igt_spinner *spin)
{
struct intel_uncore *uncore = engine->uncore;
struct i915_request *rq;
u32 timeout;
if (!intel_engine_can_store_dword(engine))
return 0;
rps_set_check(rps, rps->min_freq);
rq = igt_spinner_create_request(spin, engine->kernel_context, MI_NOOP);
if (IS_ERR(rq))
return PTR_ERR(rq);
i915_request_get(rq);
i915_request_add(rq);
if (!igt_wait_for_spinner(spin, rq)) {
pr_err("%s: RPS spinner did not start\n",
engine->name);
i915_request_put(rq);
intel_gt_set_wedged(engine->gt);
return -EIO;
}
if (!intel_rps_is_active(rps)) {
pr_err("%s: RPS not enabled on starting spinner\n",
engine->name);
igt_spinner_end(spin);
i915_request_put(rq);
return -EINVAL;
}
if (!(rps->pm_events & GEN6_PM_RP_UP_THRESHOLD)) {
pr_err("%s: RPS did not register UP interrupt\n",
engine->name);
i915_request_put(rq);
return -EINVAL;
}
if (rps->last_freq != rps->min_freq) {
pr_err("%s: RPS did not program min frequency\n",
engine->name);
i915_request_put(rq);
return -EINVAL;
}
timeout = intel_uncore_read(uncore, GEN6_RP_UP_EI);
timeout = intel_gt_pm_interval_to_ns(engine->gt, timeout);
timeout = DIV_ROUND_UP(timeout, 1000);
sleep_for_ei(rps, timeout);
GEM_BUG_ON(i915_request_completed(rq));
igt_spinner_end(spin);
i915_request_put(rq);
if (rps->cur_freq != rps->min_freq) {
pr_err("%s: Frequency unexpectedly changed [up], now %d!\n",
engine->name, intel_rps_read_actual_frequency(rps));
return -EINVAL;
}
if (!(rps->pm_iir & GEN6_PM_RP_UP_THRESHOLD)) {
pr_err("%s: UP interrupt not recorded for spinner, pm_iir:%x, prev_up:%x, up_threshold:%x, up_ei:%x\n",
engine->name, rps->pm_iir,
intel_uncore_read(uncore, GEN6_RP_PREV_UP),
intel_uncore_read(uncore, GEN6_RP_UP_THRESHOLD),
intel_uncore_read(uncore, GEN6_RP_UP_EI));
return -EINVAL;
}
return 0;
}
static int __rps_down_interrupt(struct intel_rps *rps,
struct intel_engine_cs *engine)
{
struct intel_uncore *uncore = engine->uncore;
u32 timeout;
rps_set_check(rps, rps->max_freq);
if (!(rps->pm_events & GEN6_PM_RP_DOWN_THRESHOLD)) {
pr_err("%s: RPS did not register DOWN interrupt\n",
engine->name);
return -EINVAL;
}
if (rps->last_freq != rps->max_freq) {
pr_err("%s: RPS did not program max frequency\n",
engine->name);
return -EINVAL;
}
timeout = intel_uncore_read(uncore, GEN6_RP_DOWN_EI);
timeout = intel_gt_pm_interval_to_ns(engine->gt, timeout);
timeout = DIV_ROUND_UP(timeout, 1000);
sleep_for_ei(rps, timeout);
if (rps->cur_freq != rps->max_freq) {
pr_err("%s: Frequency unexpectedly changed [down], now %d!\n",
engine->name,
intel_rps_read_actual_frequency(rps));
return -EINVAL;
}
if (!(rps->pm_iir & (GEN6_PM_RP_DOWN_THRESHOLD | GEN6_PM_RP_DOWN_TIMEOUT))) {
pr_err("%s: DOWN interrupt not recorded for idle, pm_iir:%x, prev_down:%x, down_threshold:%x, down_ei:%x [prev_up:%x, up_threshold:%x, up_ei:%x]\n",
engine->name, rps->pm_iir,
intel_uncore_read(uncore, GEN6_RP_PREV_DOWN),
intel_uncore_read(uncore, GEN6_RP_DOWN_THRESHOLD),
intel_uncore_read(uncore, GEN6_RP_DOWN_EI),
intel_uncore_read(uncore, GEN6_RP_PREV_UP),
intel_uncore_read(uncore, GEN6_RP_UP_THRESHOLD),
intel_uncore_read(uncore, GEN6_RP_UP_EI));
return -EINVAL;
}
return 0;
}
int live_rps_interrupt(void *arg)
{
struct intel_gt *gt = arg;
struct intel_rps *rps = >->rps;
void (*saved_work)(struct work_struct *wrk);
struct intel_engine_cs *engine;
enum intel_engine_id id;
struct igt_spinner spin;
u32 pm_events;
int err = 0;
/*
* First, let's check whether or not we are receiving interrupts.
*/
if (!intel_rps_has_interrupts(rps) || GRAPHICS_VER(gt->i915) < 6)
return 0;
intel_gt_pm_get(gt);
pm_events = rps->pm_events;
intel_gt_pm_put(gt);
if (!pm_events) {
pr_err("No RPS PM events registered, but RPS is enabled?\n");
return -ENODEV;
}
if (igt_spinner_init(&spin, gt))
return -ENOMEM;
intel_gt_pm_wait_for_idle(gt);
saved_work = rps->work.func;
rps->work.func = dummy_rps_work;
for_each_engine(engine, gt, id) {
/* Keep the engine busy with a spinner; expect an UP! */
if (pm_events & GEN6_PM_RP_UP_THRESHOLD) {
intel_gt_pm_wait_for_idle(engine->gt);
GEM_BUG_ON(intel_rps_is_active(rps));
st_engine_heartbeat_disable(engine);
err = __rps_up_interrupt(rps, engine, &spin);
st_engine_heartbeat_enable(engine);
if (err)
goto out;
intel_gt_pm_wait_for_idle(engine->gt);
}
/* Keep the engine awake but idle and check for DOWN */
if (pm_events & GEN6_PM_RP_DOWN_THRESHOLD) {
st_engine_heartbeat_disable(engine);
intel_rc6_disable(>->rc6);
err = __rps_down_interrupt(rps, engine);
intel_rc6_enable(>->rc6);
st_engine_heartbeat_enable(engine);
if (err)
goto out;
}
}
out:
if (igt_flush_test(gt->i915))
err = -EIO;
igt_spinner_fini(&spin);
intel_gt_pm_wait_for_idle(gt);
rps->work.func = saved_work;
return err;
}
static u64 __measure_power(int duration_ms)
{
u64 dE, dt;
dE = librapl_energy_uJ();
dt = ktime_get();
usleep_range(1000 * duration_ms, 2000 * duration_ms);
dE = librapl_energy_uJ() - dE;
dt = ktime_get() - dt;
return div64_u64(1000 * 1000 * dE, dt);
}
static u64 measure_power(struct intel_rps *rps, int *freq)
{
u64 x[5];
int i;
for (i = 0; i < 5; i++)
x[i] = __measure_power(5);
*freq = (*freq + intel_rps_read_actual_frequency(rps)) / 2;
/* A simple triangle filter for better result stability */
sort(x, 5, sizeof(*x), cmp_u64, NULL);
return div_u64(x[1] + 2 * x[2] + x[3], 4);
}
static u64 measure_power_at(struct intel_rps *rps, int *freq)
{
*freq = rps_set_check(rps, *freq);
return measure_power(rps, freq);
}
int live_rps_power(void *arg)
{
struct intel_gt *gt = arg;
struct intel_rps *rps = >->rps;
void (*saved_work)(struct work_struct *wrk);
struct intel_engine_cs *engine;
enum intel_engine_id id;
struct igt_spinner spin;
int err = 0;
/*
* Our fundamental assumption is that running at lower frequency
* actually saves power. Let's see if our RAPL measurement support
* that theory.
*/
if (!intel_rps_is_enabled(rps) || GRAPHICS_VER(gt->i915) < 6)
return 0;
if (!librapl_supported(gt->i915))
return 0;
if (igt_spinner_init(&spin, gt))
return -ENOMEM;
intel_gt_pm_wait_for_idle(gt);
saved_work = rps->work.func;
rps->work.func = dummy_rps_work;
for_each_engine(engine, gt, id) {
struct i915_request *rq;
struct {
u64 power;
int freq;
} min, max;
if (!intel_engine_can_store_dword(engine))
continue;
st_engine_heartbeat_disable(engine);
rq = igt_spinner_create_request(&spin,
engine->kernel_context,
MI_NOOP);
if (IS_ERR(rq)) {
st_engine_heartbeat_enable(engine);
err = PTR_ERR(rq);
break;
}
i915_request_add(rq);
if (!igt_wait_for_spinner(&spin, rq)) {
pr_err("%s: RPS spinner did not start\n",
engine->name);
igt_spinner_end(&spin);
st_engine_heartbeat_enable(engine);
intel_gt_set_wedged(engine->gt);
err = -EIO;
break;
}
max.freq = rps->max_freq;
max.power = measure_power_at(rps, &max.freq);
min.freq = rps->min_freq;
min.power = measure_power_at(rps, &min.freq);
igt_spinner_end(&spin);
st_engine_heartbeat_enable(engine);
pr_info("%s: min:%llumW @ %uMHz, max:%llumW @ %uMHz\n",
engine->name,
min.power, intel_gpu_freq(rps, min.freq),
max.power, intel_gpu_freq(rps, max.freq));
if (10 * min.freq >= 9 * max.freq) {
pr_notice("Could not control frequency, ran at [%d:%uMHz, %d:%uMhz]\n",
min.freq, intel_gpu_freq(rps, min.freq),
max.freq, intel_gpu_freq(rps, max.freq));
continue;
}
if (11 * min.power > 10 * max.power) {
pr_err("%s: did not conserve power when setting lower frequency!\n",
engine->name);
err = -EINVAL;
break;
}
if (igt_flush_test(gt->i915)) {
err = -EIO;
break;
}
}
igt_spinner_fini(&spin);
intel_gt_pm_wait_for_idle(gt);
rps->work.func = saved_work;
return err;
}
int live_rps_dynamic(void *arg)
{
struct intel_gt *gt = arg;
struct intel_rps *rps = >->rps;
struct intel_engine_cs *engine;
enum intel_engine_id id;
struct igt_spinner spin;
int err = 0;
/*
* We've looked at the bascs, and have established that we
* can change the clock frequency and that the HW will generate
* interrupts based on load. Now we check how we integrate those
* moving parts into dynamic reclocking based on load.
*/
if (!intel_rps_is_enabled(rps) || GRAPHICS_VER(gt->i915) < 6)
return 0;
if (igt_spinner_init(&spin, gt))
return -ENOMEM;
if (intel_rps_has_interrupts(rps))
pr_info("RPS has interrupt support\n");
if (intel_rps_uses_timer(rps))
pr_info("RPS has timer support\n");
for_each_engine(engine, gt, id) {
struct i915_request *rq;
struct {
ktime_t dt;
u8 freq;
} min, max;
if (!intel_engine_can_store_dword(engine))
continue;
intel_gt_pm_wait_for_idle(gt);
GEM_BUG_ON(intel_rps_is_active(rps));
rps->cur_freq = rps->min_freq;
intel_engine_pm_get(engine);
intel_rc6_disable(>->rc6);
GEM_BUG_ON(rps->last_freq != rps->min_freq);
rq = igt_spinner_create_request(&spin,
engine->kernel_context,
MI_NOOP);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
goto err;
}
i915_request_add(rq);
max.dt = ktime_get();
max.freq = wait_for_freq(rps, rps->max_freq, 500);
max.dt = ktime_sub(ktime_get(), max.dt);
igt_spinner_end(&spin);
min.dt = ktime_get();
min.freq = wait_for_freq(rps, rps->min_freq, 2000);
min.dt = ktime_sub(ktime_get(), min.dt);
pr_info("%s: dynamically reclocked to %u:%uMHz while busy in %lluns, and %u:%uMHz while idle in %lluns\n",
engine->name,
max.freq, intel_gpu_freq(rps, max.freq),
ktime_to_ns(max.dt),
min.freq, intel_gpu_freq(rps, min.freq),
ktime_to_ns(min.dt));
if (min.freq >= max.freq) {
pr_err("%s: dynamic reclocking of spinner failed\n!",
engine->name);
err = -EINVAL;
}
err:
intel_rc6_enable(>->rc6);
intel_engine_pm_put(engine);
if (igt_flush_test(gt->i915))
err = -EIO;
if (err)
break;
}
igt_spinner_fini(&spin);
return err;
}
| linux-master | drivers/gpu/drm/i915/gt/selftest_rps.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2019 Intel Corporation
*/
#include "intel_context.h"
#include "intel_engine_pm.h"
#include "intel_gpu_commands.h"
#include "intel_gt_requests.h"
#include "intel_ring.h"
#include "selftest_rc6.h"
#include "selftests/i915_random.h"
#include "selftests/librapl.h"
static u64 rc6_residency(struct intel_rc6 *rc6)
{
u64 result;
/* XXX VLV_GT_MEDIA_RC6? */
result = intel_rc6_residency_ns(rc6, INTEL_RC6_RES_RC6);
if (HAS_RC6p(rc6_to_i915(rc6)))
result += intel_rc6_residency_ns(rc6, INTEL_RC6_RES_RC6p);
if (HAS_RC6pp(rc6_to_i915(rc6)))
result += intel_rc6_residency_ns(rc6, INTEL_RC6_RES_RC6pp);
return result;
}
int live_rc6_manual(void *arg)
{
struct intel_gt *gt = arg;
struct intel_rc6 *rc6 = >->rc6;
u64 rc0_power, rc6_power;
intel_wakeref_t wakeref;
bool has_power;
ktime_t dt;
u64 res[2];
int err = 0;
/*
* Our claim is that we can "encourage" the GPU to enter rc6 at will.
* Let's try it!
*/
if (!rc6->enabled)
return 0;
/* bsw/byt use a PCU and decouple RC6 from our manual control */
if (IS_VALLEYVIEW(gt->i915) || IS_CHERRYVIEW(gt->i915))
return 0;
has_power = librapl_supported(gt->i915);
wakeref = intel_runtime_pm_get(gt->uncore->rpm);
/* Force RC6 off for starters */
__intel_rc6_disable(rc6);
msleep(1); /* wakeup is not immediate, takes about 100us on icl */
res[0] = rc6_residency(rc6);
dt = ktime_get();
rc0_power = librapl_energy_uJ();
msleep(250);
rc0_power = librapl_energy_uJ() - rc0_power;
dt = ktime_sub(ktime_get(), dt);
res[1] = rc6_residency(rc6);
if ((res[1] - res[0]) >> 10) {
pr_err("RC6 residency increased by %lldus while disabled for 250ms!\n",
(res[1] - res[0]) >> 10);
err = -EINVAL;
goto out_unlock;
}
if (has_power) {
rc0_power = div64_u64(NSEC_PER_SEC * rc0_power,
ktime_to_ns(dt));
if (!rc0_power) {
pr_err("No power measured while in RC0\n");
err = -EINVAL;
goto out_unlock;
}
}
/* Manually enter RC6 */
intel_rc6_park(rc6);
res[0] = rc6_residency(rc6);
intel_uncore_forcewake_flush(rc6_to_uncore(rc6), FORCEWAKE_ALL);
dt = ktime_get();
rc6_power = librapl_energy_uJ();
msleep(100);
rc6_power = librapl_energy_uJ() - rc6_power;
dt = ktime_sub(ktime_get(), dt);
res[1] = rc6_residency(rc6);
if (res[1] == res[0]) {
pr_err("Did not enter RC6! RC6_STATE=%08x, RC6_CONTROL=%08x, residency=%lld\n",
intel_uncore_read_fw(gt->uncore, GEN6_RC_STATE),
intel_uncore_read_fw(gt->uncore, GEN6_RC_CONTROL),
res[0]);
err = -EINVAL;
}
if (has_power) {
rc6_power = div64_u64(NSEC_PER_SEC * rc6_power,
ktime_to_ns(dt));
pr_info("GPU consumed %llduW in RC0 and %llduW in RC6\n",
rc0_power, rc6_power);
if (2 * rc6_power > rc0_power) {
pr_err("GPU leaked energy while in RC6!\n");
err = -EINVAL;
goto out_unlock;
}
}
/* Restore what should have been the original state! */
intel_rc6_unpark(rc6);
out_unlock:
intel_runtime_pm_put(gt->uncore->rpm, wakeref);
return err;
}
static const u32 *__live_rc6_ctx(struct intel_context *ce)
{
struct i915_request *rq;
const u32 *result;
u32 cmd;
u32 *cs;
rq = intel_context_create_request(ce);
if (IS_ERR(rq))
return ERR_CAST(rq);
cs = intel_ring_begin(rq, 4);
if (IS_ERR(cs)) {
i915_request_add(rq);
return cs;
}
cmd = MI_STORE_REGISTER_MEM | MI_USE_GGTT;
if (GRAPHICS_VER(rq->i915) >= 8)
cmd++;
*cs++ = cmd;
*cs++ = i915_mmio_reg_offset(GEN8_RC6_CTX_INFO);
*cs++ = ce->timeline->hwsp_offset + 8;
*cs++ = 0;
intel_ring_advance(rq, cs);
result = rq->hwsp_seqno + 2;
i915_request_add(rq);
return result;
}
static struct intel_engine_cs **
randomised_engines(struct intel_gt *gt,
struct rnd_state *prng,
unsigned int *count)
{
struct intel_engine_cs *engine, **engines;
enum intel_engine_id id;
int n;
n = 0;
for_each_engine(engine, gt, id)
n++;
if (!n)
return NULL;
engines = kmalloc_array(n, sizeof(*engines), GFP_KERNEL);
if (!engines)
return NULL;
n = 0;
for_each_engine(engine, gt, id)
engines[n++] = engine;
i915_prandom_shuffle(engines, sizeof(*engines), n, prng);
*count = n;
return engines;
}
int live_rc6_ctx_wa(void *arg)
{
struct intel_gt *gt = arg;
struct intel_engine_cs **engines;
unsigned int n, count;
I915_RND_STATE(prng);
int err = 0;
/* A read of CTX_INFO upsets rc6. Poke the bear! */
if (GRAPHICS_VER(gt->i915) < 8)
return 0;
engines = randomised_engines(gt, &prng, &count);
if (!engines)
return 0;
for (n = 0; n < count; n++) {
struct intel_engine_cs *engine = engines[n];
int pass;
for (pass = 0; pass < 2; pass++) {
struct i915_gpu_error *error = >->i915->gpu_error;
struct intel_context *ce;
unsigned int resets =
i915_reset_engine_count(error, engine);
const u32 *res;
/* Use a sacrifical context */
ce = intel_context_create(engine);
if (IS_ERR(ce)) {
err = PTR_ERR(ce);
goto out;
}
intel_engine_pm_get(engine);
res = __live_rc6_ctx(ce);
intel_engine_pm_put(engine);
intel_context_put(ce);
if (IS_ERR(res)) {
err = PTR_ERR(res);
goto out;
}
if (intel_gt_wait_for_idle(gt, HZ / 5) == -ETIME) {
intel_gt_set_wedged(gt);
err = -ETIME;
goto out;
}
intel_gt_pm_wait_for_idle(gt);
pr_debug("%s: CTX_INFO=%0x\n",
engine->name, READ_ONCE(*res));
if (resets !=
i915_reset_engine_count(error, engine)) {
pr_err("%s: GPU reset required\n",
engine->name);
add_taint_for_CI(gt->i915, TAINT_WARN);
err = -EIO;
goto out;
}
}
}
out:
kfree(engines);
return err;
}
| linux-master | drivers/gpu/drm/i915/gt/selftest_rc6.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2019 Intel Corporation
*/
#include "i915_drv.h"
#include "i915_request.h"
#include "intel_context.h"
#include "intel_engine_heartbeat.h"
#include "intel_engine_pm.h"
#include "intel_engine.h"
#include "intel_gt.h"
#include "intel_reset.h"
/*
* While the engine is active, we send a periodic pulse along the engine
* to check on its health and to flush any idle-barriers. If that request
* is stuck, and we fail to preempt it, we declare the engine hung and
* issue a reset -- in the hope that restores progress.
*/
static bool next_heartbeat(struct intel_engine_cs *engine)
{
struct i915_request *rq;
long delay;
delay = READ_ONCE(engine->props.heartbeat_interval_ms);
rq = engine->heartbeat.systole;
/*
* FIXME: The final period extension is disabled if the period has been
* modified from the default. This is to prevent issues with certain
* selftests which override the value and expect specific behaviour.
* Once the selftests have been updated to either cope with variable
* heartbeat periods (or to override the pre-emption timeout as well,
* or just to add a selftest specific override of the extension), the
* generic override can be removed.
*/
if (rq && rq->sched.attr.priority >= I915_PRIORITY_BARRIER &&
delay == engine->defaults.heartbeat_interval_ms) {
long longer;
/*
* The final try is at the highest priority possible. Up until now
* a pre-emption might not even have been attempted. So make sure
* this last attempt allows enough time for a pre-emption to occur.
*/
longer = READ_ONCE(engine->props.preempt_timeout_ms) * 2;
longer = intel_clamp_heartbeat_interval_ms(engine, longer);
if (longer > delay)
delay = longer;
}
if (!delay)
return false;
delay = msecs_to_jiffies_timeout(delay);
if (delay >= HZ)
delay = round_jiffies_up_relative(delay);
mod_delayed_work(system_highpri_wq, &engine->heartbeat.work, delay + 1);
return true;
}
static struct i915_request *
heartbeat_create(struct intel_context *ce, gfp_t gfp)
{
struct i915_request *rq;
intel_context_enter(ce);
rq = __i915_request_create(ce, gfp);
intel_context_exit(ce);
return rq;
}
static void idle_pulse(struct intel_engine_cs *engine, struct i915_request *rq)
{
engine->wakeref_serial = READ_ONCE(engine->serial) + 1;
i915_request_add_active_barriers(rq);
if (!engine->heartbeat.systole && intel_engine_has_heartbeat(engine))
engine->heartbeat.systole = i915_request_get(rq);
}
static void heartbeat_commit(struct i915_request *rq,
const struct i915_sched_attr *attr)
{
idle_pulse(rq->engine, rq);
__i915_request_commit(rq);
__i915_request_queue(rq, attr);
}
static void show_heartbeat(const struct i915_request *rq,
struct intel_engine_cs *engine)
{
struct drm_printer p = drm_debug_printer("heartbeat");
if (!rq) {
intel_engine_dump(engine, &p,
"%s heartbeat not ticking\n",
engine->name);
} else {
intel_engine_dump(engine, &p,
"%s heartbeat {seqno:%llx:%lld, prio:%d} not ticking\n",
engine->name,
rq->fence.context,
rq->fence.seqno,
rq->sched.attr.priority);
}
}
static void
reset_engine(struct intel_engine_cs *engine, struct i915_request *rq)
{
if (IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM))
show_heartbeat(rq, engine);
if (intel_engine_uses_guc(engine))
/*
* GuC itself is toast or GuC's hang detection
* is disabled. Either way, need to find the
* hang culprit manually.
*/
intel_guc_find_hung_context(engine);
intel_gt_handle_error(engine->gt, engine->mask,
I915_ERROR_CAPTURE,
"stopped heartbeat on %s",
engine->name);
}
static void heartbeat(struct work_struct *wrk)
{
struct i915_sched_attr attr = { .priority = I915_PRIORITY_MIN };
struct intel_engine_cs *engine =
container_of(wrk, typeof(*engine), heartbeat.work.work);
struct intel_context *ce = engine->kernel_context;
struct i915_request *rq;
unsigned long serial;
/* Just in case everything has gone horribly wrong, give it a kick */
intel_engine_flush_submission(engine);
rq = engine->heartbeat.systole;
if (rq && i915_request_completed(rq)) {
i915_request_put(rq);
engine->heartbeat.systole = NULL;
}
if (!intel_engine_pm_get_if_awake(engine))
return;
if (intel_gt_is_wedged(engine->gt))
goto out;
if (i915_sched_engine_disabled(engine->sched_engine)) {
reset_engine(engine, engine->heartbeat.systole);
goto out;
}
if (engine->heartbeat.systole) {
long delay = READ_ONCE(engine->props.heartbeat_interval_ms);
/* Safeguard against too-fast worker invocations */
if (!time_after(jiffies,
rq->emitted_jiffies + msecs_to_jiffies(delay)))
goto out;
if (!i915_sw_fence_signaled(&rq->submit)) {
/*
* Not yet submitted, system is stalled.
*
* This more often happens for ring submission,
* where all contexts are funnelled into a common
* ringbuffer. If one context is blocked on an
* external fence, not only is it not submitted,
* but all other contexts, including the kernel
* context are stuck waiting for the signal.
*/
} else if (engine->sched_engine->schedule &&
rq->sched.attr.priority < I915_PRIORITY_BARRIER) {
/*
* Gradually raise the priority of the heartbeat to
* give high priority work [which presumably desires
* low latency and no jitter] the chance to naturally
* complete before being preempted.
*/
attr.priority = 0;
if (rq->sched.attr.priority >= attr.priority)
attr.priority = I915_PRIORITY_HEARTBEAT;
if (rq->sched.attr.priority >= attr.priority)
attr.priority = I915_PRIORITY_BARRIER;
local_bh_disable();
engine->sched_engine->schedule(rq, &attr);
local_bh_enable();
} else {
reset_engine(engine, rq);
}
rq->emitted_jiffies = jiffies;
goto out;
}
serial = READ_ONCE(engine->serial);
if (engine->wakeref_serial == serial)
goto out;
if (!mutex_trylock(&ce->timeline->mutex)) {
/* Unable to lock the kernel timeline, is the engine stuck? */
if (xchg(&engine->heartbeat.blocked, serial) == serial)
intel_gt_handle_error(engine->gt, engine->mask,
I915_ERROR_CAPTURE,
"no heartbeat on %s",
engine->name);
goto out;
}
rq = heartbeat_create(ce, GFP_NOWAIT | __GFP_NOWARN);
if (IS_ERR(rq))
goto unlock;
heartbeat_commit(rq, &attr);
unlock:
mutex_unlock(&ce->timeline->mutex);
out:
if (!engine->i915->params.enable_hangcheck || !next_heartbeat(engine))
i915_request_put(fetch_and_zero(&engine->heartbeat.systole));
intel_engine_pm_put(engine);
}
void intel_engine_unpark_heartbeat(struct intel_engine_cs *engine)
{
if (!CONFIG_DRM_I915_HEARTBEAT_INTERVAL)
return;
next_heartbeat(engine);
}
void intel_engine_park_heartbeat(struct intel_engine_cs *engine)
{
if (cancel_delayed_work(&engine->heartbeat.work))
i915_request_put(fetch_and_zero(&engine->heartbeat.systole));
}
void intel_gt_unpark_heartbeats(struct intel_gt *gt)
{
struct intel_engine_cs *engine;
enum intel_engine_id id;
for_each_engine(engine, gt, id)
if (intel_engine_pm_is_awake(engine))
intel_engine_unpark_heartbeat(engine);
}
void intel_gt_park_heartbeats(struct intel_gt *gt)
{
struct intel_engine_cs *engine;
enum intel_engine_id id;
for_each_engine(engine, gt, id)
intel_engine_park_heartbeat(engine);
}
void intel_engine_init_heartbeat(struct intel_engine_cs *engine)
{
INIT_DELAYED_WORK(&engine->heartbeat.work, heartbeat);
}
static int __intel_engine_pulse(struct intel_engine_cs *engine)
{
struct i915_sched_attr attr = { .priority = I915_PRIORITY_BARRIER };
struct intel_context *ce = engine->kernel_context;
struct i915_request *rq;
lockdep_assert_held(&ce->timeline->mutex);
GEM_BUG_ON(!intel_engine_has_preemption(engine));
GEM_BUG_ON(!intel_engine_pm_is_awake(engine));
rq = heartbeat_create(ce, GFP_NOWAIT | __GFP_NOWARN);
if (IS_ERR(rq))
return PTR_ERR(rq);
__set_bit(I915_FENCE_FLAG_SENTINEL, &rq->fence.flags);
heartbeat_commit(rq, &attr);
GEM_BUG_ON(rq->sched.attr.priority < I915_PRIORITY_BARRIER);
return 0;
}
static unsigned long set_heartbeat(struct intel_engine_cs *engine,
unsigned long delay)
{
unsigned long old;
old = xchg(&engine->props.heartbeat_interval_ms, delay);
if (delay)
intel_engine_unpark_heartbeat(engine);
else
intel_engine_park_heartbeat(engine);
return old;
}
int intel_engine_set_heartbeat(struct intel_engine_cs *engine,
unsigned long delay)
{
struct intel_context *ce = engine->kernel_context;
int err = 0;
if (!delay && !intel_engine_has_preempt_reset(engine))
return -ENODEV;
/* FIXME: Remove together with equally marked hack in next_heartbeat. */
if (delay != engine->defaults.heartbeat_interval_ms &&
delay < 2 * engine->props.preempt_timeout_ms) {
if (intel_engine_uses_guc(engine))
drm_notice(&engine->i915->drm, "%s heartbeat interval adjusted to a non-default value which may downgrade individual engine resets to full GPU resets!\n",
engine->name);
else
drm_notice(&engine->i915->drm, "%s heartbeat interval adjusted to a non-default value which may cause engine resets to target innocent contexts!\n",
engine->name);
}
intel_engine_pm_get(engine);
err = mutex_lock_interruptible(&ce->timeline->mutex);
if (err)
goto out_rpm;
if (delay != engine->props.heartbeat_interval_ms) {
unsigned long saved = set_heartbeat(engine, delay);
/* recheck current execution */
if (intel_engine_has_preemption(engine)) {
err = __intel_engine_pulse(engine);
if (err)
set_heartbeat(engine, saved);
}
}
mutex_unlock(&ce->timeline->mutex);
out_rpm:
intel_engine_pm_put(engine);
return err;
}
int intel_engine_pulse(struct intel_engine_cs *engine)
{
struct intel_context *ce = engine->kernel_context;
int err;
if (!intel_engine_has_preemption(engine))
return -ENODEV;
if (!intel_engine_pm_get_if_awake(engine))
return 0;
err = -EINTR;
if (!mutex_lock_interruptible(&ce->timeline->mutex)) {
err = __intel_engine_pulse(engine);
mutex_unlock(&ce->timeline->mutex);
}
intel_engine_flush_submission(engine);
intel_engine_pm_put(engine);
return err;
}
int intel_engine_flush_barriers(struct intel_engine_cs *engine)
{
struct i915_sched_attr attr = { .priority = I915_PRIORITY_MIN };
struct intel_context *ce = engine->kernel_context;
struct i915_request *rq;
int err;
if (llist_empty(&engine->barrier_tasks))
return 0;
if (!intel_engine_pm_get_if_awake(engine))
return 0;
if (mutex_lock_interruptible(&ce->timeline->mutex)) {
err = -EINTR;
goto out_rpm;
}
rq = heartbeat_create(ce, GFP_KERNEL);
if (IS_ERR(rq)) {
err = PTR_ERR(rq);
goto out_unlock;
}
heartbeat_commit(rq, &attr);
err = 0;
out_unlock:
mutex_unlock(&ce->timeline->mutex);
out_rpm:
intel_engine_pm_put(engine);
return err;
}
#if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
#include "selftest_engine_heartbeat.c"
#endif
| linux-master | drivers/gpu/drm/i915/gt/intel_engine_heartbeat.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2019 Intel Corporation
*/
#include <linux/sort.h>
#include "intel_engine_regs.h"
#include "intel_gt_clock_utils.h"
#include "selftest_llc.h"
#include "selftest_rc6.h"
#include "selftest_rps.h"
static int cmp_u64(const void *A, const void *B)
{
const u64 *a = A, *b = B;
if (a < b)
return -1;
else if (a > b)
return 1;
else
return 0;
}
static int cmp_u32(const void *A, const void *B)
{
const u32 *a = A, *b = B;
if (a < b)
return -1;
else if (a > b)
return 1;
else
return 0;
}
static u32 read_timestamp(struct intel_engine_cs *engine)
{
struct drm_i915_private *i915 = engine->i915;
/* On i965 the first read tends to give a stale value */
ENGINE_READ_FW(engine, RING_TIMESTAMP);
if (GRAPHICS_VER(i915) == 5 || IS_G4X(i915))
return ENGINE_READ_FW(engine, RING_TIMESTAMP_UDW);
else
return ENGINE_READ_FW(engine, RING_TIMESTAMP);
}
static void measure_clocks(struct intel_engine_cs *engine,
u32 *out_cycles, ktime_t *out_dt)
{
ktime_t dt[5];
u32 cycles[5];
int i;
for (i = 0; i < 5; i++) {
local_irq_disable();
cycles[i] = -read_timestamp(engine);
dt[i] = ktime_get();
udelay(1000);
cycles[i] += read_timestamp(engine);
dt[i] = ktime_sub(ktime_get(), dt[i]);
local_irq_enable();
}
/* Use the median of both cycle/dt; close enough */
sort(cycles, 5, sizeof(*cycles), cmp_u32, NULL);
*out_cycles = (cycles[1] + 2 * cycles[2] + cycles[3]) / 4;
sort(dt, 5, sizeof(*dt), cmp_u64, NULL);
*out_dt = div_u64(dt[1] + 2 * dt[2] + dt[3], 4);
}
static int live_gt_clocks(void *arg)
{
struct intel_gt *gt = arg;
struct intel_engine_cs *engine;
enum intel_engine_id id;
int err = 0;
if (!gt->clock_frequency) { /* unknown */
pr_info("CS_TIMESTAMP frequency unknown\n");
return 0;
}
if (GRAPHICS_VER(gt->i915) < 4) /* Any CS_TIMESTAMP? */
return 0;
intel_gt_pm_get(gt);
intel_uncore_forcewake_get(gt->uncore, FORCEWAKE_ALL);
for_each_engine(engine, gt, id) {
u32 cycles;
u32 expected;
u64 time;
u64 dt;
if (GRAPHICS_VER(engine->i915) < 7 && engine->id != RCS0)
continue;
measure_clocks(engine, &cycles, &dt);
time = intel_gt_clock_interval_to_ns(engine->gt, cycles);
expected = intel_gt_ns_to_clock_interval(engine->gt, dt);
pr_info("%s: TIMESTAMP %d cycles [%lldns] in %lldns [%d cycles], using CS clock frequency of %uKHz\n",
engine->name, cycles, time, dt, expected,
engine->gt->clock_frequency / 1000);
if (9 * time < 8 * dt || 8 * time > 9 * dt) {
pr_err("%s: CS ticks did not match walltime!\n",
engine->name);
err = -EINVAL;
break;
}
if (9 * expected < 8 * cycles || 8 * expected > 9 * cycles) {
pr_err("%s: walltime did not match CS ticks!\n",
engine->name);
err = -EINVAL;
break;
}
}
intel_uncore_forcewake_put(gt->uncore, FORCEWAKE_ALL);
intel_gt_pm_put(gt);
return err;
}
static int live_gt_resume(void *arg)
{
struct intel_gt *gt = arg;
IGT_TIMEOUT(end_time);
int err;
/* Do several suspend/resume cycles to check we don't explode! */
do {
intel_gt_suspend_prepare(gt);
intel_gt_suspend_late(gt);
if (gt->rc6.enabled) {
pr_err("rc6 still enabled after suspend!\n");
intel_gt_set_wedged_on_init(gt);
err = -EINVAL;
break;
}
err = intel_gt_resume(gt);
if (err)
break;
if (gt->rc6.supported && !gt->rc6.enabled) {
pr_err("rc6 not enabled upon resume!\n");
intel_gt_set_wedged_on_init(gt);
err = -EINVAL;
break;
}
err = st_llc_verify(>->llc);
if (err) {
pr_err("llc state not restored upon resume!\n");
intel_gt_set_wedged_on_init(gt);
break;
}
} while (!__igt_timeout(end_time, NULL));
return err;
}
int intel_gt_pm_live_selftests(struct drm_i915_private *i915)
{
static const struct i915_subtest tests[] = {
SUBTEST(live_gt_clocks),
SUBTEST(live_rc6_manual),
SUBTEST(live_rps_clock_interval),
SUBTEST(live_rps_control),
SUBTEST(live_rps_frequency_cs),
SUBTEST(live_rps_frequency_srm),
SUBTEST(live_rps_power),
SUBTEST(live_rps_interrupt),
SUBTEST(live_rps_dynamic),
SUBTEST(live_gt_resume),
};
if (intel_gt_is_wedged(to_gt(i915)))
return 0;
return intel_gt_live_subtests(tests, to_gt(i915));
}
int intel_gt_pm_late_selftests(struct drm_i915_private *i915)
{
static const struct i915_subtest tests[] = {
/*
* These tests may leave the system in an undesirable state.
* They are intended to be run last in CI and the system
* rebooted afterwards.
*/
SUBTEST(live_rc6_ctx_wa),
};
if (intel_gt_is_wedged(to_gt(i915)))
return 0;
return intel_gt_live_subtests(tests, to_gt(i915));
}
| linux-master | drivers/gpu/drm/i915/gt/selftest_gt_pm.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2020 Intel Corporation
*/
#include "gen2_engine_cs.h"
#include "i915_drv.h"
#include "i915_reg.h"
#include "intel_engine.h"
#include "intel_engine_regs.h"
#include "intel_gpu_commands.h"
#include "intel_gt.h"
#include "intel_gt_irq.h"
#include "intel_ring.h"
int gen2_emit_flush(struct i915_request *rq, u32 mode)
{
unsigned int num_store_dw = 12;
u32 cmd, *cs;
cmd = MI_FLUSH;
if (mode & EMIT_INVALIDATE)
cmd |= MI_READ_FLUSH;
cs = intel_ring_begin(rq, 2 + 4 * num_store_dw);
if (IS_ERR(cs))
return PTR_ERR(cs);
*cs++ = cmd;
while (num_store_dw--) {
*cs++ = MI_STORE_DWORD_INDEX;
*cs++ = I915_GEM_HWS_SCRATCH * sizeof(u32);
*cs++ = 0;
*cs++ = MI_FLUSH | MI_NO_WRITE_FLUSH;
}
*cs++ = cmd;
intel_ring_advance(rq, cs);
return 0;
}
int gen4_emit_flush_rcs(struct i915_request *rq, u32 mode)
{
u32 cmd, *cs;
int i;
/*
* read/write caches:
*
* I915_GEM_DOMAIN_RENDER is always invalidated, but is
* only flushed if MI_NO_WRITE_FLUSH is unset. On 965, it is
* also flushed at 2d versus 3d pipeline switches.
*
* read-only caches:
*
* I915_GEM_DOMAIN_SAMPLER is flushed on pre-965 if
* MI_READ_FLUSH is set, and is always flushed on 965.
*
* I915_GEM_DOMAIN_COMMAND may not exist?
*
* I915_GEM_DOMAIN_INSTRUCTION, which exists on 965, is
* invalidated when MI_EXE_FLUSH is set.
*
* I915_GEM_DOMAIN_VERTEX, which exists on 965, is
* invalidated with every MI_FLUSH.
*
* TLBs:
*
* On 965, TLBs associated with I915_GEM_DOMAIN_COMMAND
* and I915_GEM_DOMAIN_CPU in are invalidated at PTE write and
* I915_GEM_DOMAIN_RENDER and I915_GEM_DOMAIN_SAMPLER
* are flushed at any MI_FLUSH.
*/
cmd = MI_FLUSH;
if (mode & EMIT_INVALIDATE) {
cmd |= MI_EXE_FLUSH;
if (IS_G4X(rq->i915) || GRAPHICS_VER(rq->i915) == 5)
cmd |= MI_INVALIDATE_ISP;
}
i = 2;
if (mode & EMIT_INVALIDATE)
i += 20;
cs = intel_ring_begin(rq, i);
if (IS_ERR(cs))
return PTR_ERR(cs);
*cs++ = cmd;
/*
* A random delay to let the CS invalidate take effect? Without this
* delay, the GPU relocation path fails as the CS does not see
* the updated contents. Just as important, if we apply the flushes
* to the EMIT_FLUSH branch (i.e. immediately after the relocation
* write and before the invalidate on the next batch), the relocations
* still fail. This implies that is a delay following invalidation
* that is required to reset the caches as opposed to a delay to
* ensure the memory is written.
*/
if (mode & EMIT_INVALIDATE) {
*cs++ = GFX_OP_PIPE_CONTROL(4) | PIPE_CONTROL_QW_WRITE;
*cs++ = intel_gt_scratch_offset(rq->engine->gt,
INTEL_GT_SCRATCH_FIELD_DEFAULT) |
PIPE_CONTROL_GLOBAL_GTT;
*cs++ = 0;
*cs++ = 0;
for (i = 0; i < 12; i++)
*cs++ = MI_FLUSH;
*cs++ = GFX_OP_PIPE_CONTROL(4) | PIPE_CONTROL_QW_WRITE;
*cs++ = intel_gt_scratch_offset(rq->engine->gt,
INTEL_GT_SCRATCH_FIELD_DEFAULT) |
PIPE_CONTROL_GLOBAL_GTT;
*cs++ = 0;
*cs++ = 0;
}
*cs++ = cmd;
intel_ring_advance(rq, cs);
return 0;
}
int gen4_emit_flush_vcs(struct i915_request *rq, u32 mode)
{
u32 *cs;
cs = intel_ring_begin(rq, 2);
if (IS_ERR(cs))
return PTR_ERR(cs);
*cs++ = MI_FLUSH;
*cs++ = MI_NOOP;
intel_ring_advance(rq, cs);
return 0;
}
static u32 *__gen2_emit_breadcrumb(struct i915_request *rq, u32 *cs,
int flush, int post)
{
GEM_BUG_ON(i915_request_active_timeline(rq)->hwsp_ggtt != rq->engine->status_page.vma);
GEM_BUG_ON(offset_in_page(rq->hwsp_seqno) != I915_GEM_HWS_SEQNO_ADDR);
*cs++ = MI_FLUSH;
while (flush--) {
*cs++ = MI_STORE_DWORD_INDEX;
*cs++ = I915_GEM_HWS_SCRATCH * sizeof(u32);
*cs++ = rq->fence.seqno;
}
while (post--) {
*cs++ = MI_STORE_DWORD_INDEX;
*cs++ = I915_GEM_HWS_SEQNO_ADDR;
*cs++ = rq->fence.seqno;
}
*cs++ = MI_USER_INTERRUPT;
rq->tail = intel_ring_offset(rq, cs);
assert_ring_tail_valid(rq->ring, rq->tail);
return cs;
}
u32 *gen3_emit_breadcrumb(struct i915_request *rq, u32 *cs)
{
return __gen2_emit_breadcrumb(rq, cs, 16, 8);
}
u32 *gen5_emit_breadcrumb(struct i915_request *rq, u32 *cs)
{
return __gen2_emit_breadcrumb(rq, cs, 8, 8);
}
/* Just userspace ABI convention to limit the wa batch bo to a resonable size */
#define I830_BATCH_LIMIT SZ_256K
#define I830_TLB_ENTRIES (2)
#define I830_WA_SIZE max(I830_TLB_ENTRIES * SZ_4K, I830_BATCH_LIMIT)
int i830_emit_bb_start(struct i915_request *rq,
u64 offset, u32 len,
unsigned int dispatch_flags)
{
u32 *cs, cs_offset =
intel_gt_scratch_offset(rq->engine->gt,
INTEL_GT_SCRATCH_FIELD_DEFAULT);
GEM_BUG_ON(rq->engine->gt->scratch->size < I830_WA_SIZE);
cs = intel_ring_begin(rq, 6);
if (IS_ERR(cs))
return PTR_ERR(cs);
/* Evict the invalid PTE TLBs */
*cs++ = COLOR_BLT_CMD | BLT_WRITE_RGBA;
*cs++ = BLT_DEPTH_32 | BLT_ROP_COLOR_COPY | 4096;
*cs++ = I830_TLB_ENTRIES << 16 | 4; /* load each page */
*cs++ = cs_offset;
*cs++ = 0xdeadbeef;
*cs++ = MI_NOOP;
intel_ring_advance(rq, cs);
if ((dispatch_flags & I915_DISPATCH_PINNED) == 0) {
if (len > I830_BATCH_LIMIT)
return -ENOSPC;
cs = intel_ring_begin(rq, 6 + 2);
if (IS_ERR(cs))
return PTR_ERR(cs);
/*
* Blit the batch (which has now all relocs applied) to the
* stable batch scratch bo area (so that the CS never
* stumbles over its tlb invalidation bug) ...
*/
*cs++ = SRC_COPY_BLT_CMD | BLT_WRITE_RGBA | (6 - 2);
*cs++ = BLT_DEPTH_32 | BLT_ROP_SRC_COPY | 4096;
*cs++ = DIV_ROUND_UP(len, 4096) << 16 | 4096;
*cs++ = cs_offset;
*cs++ = 4096;
*cs++ = offset;
*cs++ = MI_FLUSH;
*cs++ = MI_NOOP;
intel_ring_advance(rq, cs);
/* ... and execute it. */
offset = cs_offset;
}
if (!(dispatch_flags & I915_DISPATCH_SECURE))
offset |= MI_BATCH_NON_SECURE;
cs = intel_ring_begin(rq, 2);
if (IS_ERR(cs))
return PTR_ERR(cs);
*cs++ = MI_BATCH_BUFFER_START | MI_BATCH_GTT;
*cs++ = offset;
intel_ring_advance(rq, cs);
return 0;
}
int gen3_emit_bb_start(struct i915_request *rq,
u64 offset, u32 len,
unsigned int dispatch_flags)
{
u32 *cs;
if (!(dispatch_flags & I915_DISPATCH_SECURE))
offset |= MI_BATCH_NON_SECURE;
cs = intel_ring_begin(rq, 2);
if (IS_ERR(cs))
return PTR_ERR(cs);
*cs++ = MI_BATCH_BUFFER_START | MI_BATCH_GTT;
*cs++ = offset;
intel_ring_advance(rq, cs);
return 0;
}
int gen4_emit_bb_start(struct i915_request *rq,
u64 offset, u32 length,
unsigned int dispatch_flags)
{
u32 security;
u32 *cs;
security = MI_BATCH_NON_SECURE_I965;
if (dispatch_flags & I915_DISPATCH_SECURE)
security = 0;
cs = intel_ring_begin(rq, 2);
if (IS_ERR(cs))
return PTR_ERR(cs);
*cs++ = MI_BATCH_BUFFER_START | MI_BATCH_GTT | security;
*cs++ = offset;
intel_ring_advance(rq, cs);
return 0;
}
void gen2_irq_enable(struct intel_engine_cs *engine)
{
struct drm_i915_private *i915 = engine->i915;
i915->irq_mask &= ~engine->irq_enable_mask;
intel_uncore_write16(&i915->uncore, GEN2_IMR, i915->irq_mask);
ENGINE_POSTING_READ16(engine, RING_IMR);
}
void gen2_irq_disable(struct intel_engine_cs *engine)
{
struct drm_i915_private *i915 = engine->i915;
i915->irq_mask |= engine->irq_enable_mask;
intel_uncore_write16(&i915->uncore, GEN2_IMR, i915->irq_mask);
}
void gen3_irq_enable(struct intel_engine_cs *engine)
{
engine->i915->irq_mask &= ~engine->irq_enable_mask;
intel_uncore_write(engine->uncore, GEN2_IMR, engine->i915->irq_mask);
intel_uncore_posting_read_fw(engine->uncore, GEN2_IMR);
}
void gen3_irq_disable(struct intel_engine_cs *engine)
{
engine->i915->irq_mask |= engine->irq_enable_mask;
intel_uncore_write(engine->uncore, GEN2_IMR, engine->i915->irq_mask);
}
void gen5_irq_enable(struct intel_engine_cs *engine)
{
gen5_gt_enable_irq(engine->gt, engine->irq_enable_mask);
}
void gen5_irq_disable(struct intel_engine_cs *engine)
{
gen5_gt_disable_irq(engine->gt, engine->irq_enable_mask);
}
| linux-master | drivers/gpu/drm/i915/gt/gen2_engine_cs.c |
// SPDX-License-Identifier: MIT
/*
* Copyright © 2014 Intel Corporation
*
* Generated by: intel-gpu-tools-1.19-177-g68e2eab2
*/
#include "intel_renderstate.h"
static const u32 gen9_null_state_relocs[] = {
0x000007a8,
0x000007b4,
0x000007bc,
0x000007cc,
-1,
};
static const u32 gen9_null_state_batch[] = {
0x7a000004,
0x01000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x69040300,
0x78140000,
0x04000000,
0x7820000a,
0x00000000,
0x00000000,
0x80000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x78130002,
0x00000000,
0x00000000,
0x02001808,
0x781f0004,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x78510009,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x78100007,
0x00000000,
0x00000000,
0x00010000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x781b0007,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000800,
0x00000000,
0x78110008,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x781e0003,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x781d0009,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x78120002,
0x00000000,
0x00000000,
0x00000000,
0x78500003,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x781c0002,
0x00000000,
0x00000000,
0x00000000,
0x780c0000,
0x00000000,
0x78520003,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x78300000,
0x08010040,
0x78310000,
0x1e000000,
0x78320000,
0x1e000000,
0x78330000,
0x1e000000,
0x79190002,
0x00000000,
0x00000000,
0x00000000,
0x791a0002,
0x00000000,
0x00000000,
0x00000000,
0x791b0002,
0x00000000,
0x00000000,
0x00000000,
0x79120000,
0x00000000,
0x79130000,
0x00000000,
0x79140000,
0x00000000,
0x79150000,
0x00000000,
0x79160000,
0x00000000,
0x78150009,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x78190009,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x781a0009,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x78160009,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x78170009,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x78490001,
0x00000000,
0x00000000,
0x784a0000,
0x00000000,
0x784b0000,
0x00000004,
0x79170101,
0x00000000,
0x00000080,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x79180006,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x79180006,
0x20000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x79180006,
0x40000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x79180006,
0x60000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x61010011,
0x00000001, /* reloc */
0x00000000,
0x00000000,
0x00000001, /* reloc */
0x00000000,
0x00000001, /* reloc */
0x00000000,
0x00000001,
0x00000000,
0x00000001, /* reloc */
0x00000000,
0x00001001,
0x00001001,
0x00000001,
0x00001001,
0x00000000,
0x00000000,
0x00000000,
0x61020001,
0x00000000,
0x00000000,
0x79000002,
0x00000000,
0x00000000,
0x00000000,
0x78050006,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x79040002,
0x00000000,
0x00000000,
0x00000000,
0x79040002,
0x40000000,
0x00000000,
0x00000000,
0x79040002,
0x80000000,
0x00000000,
0x00000000,
0x79040002,
0xc0000000,
0x00000000,
0x00000000,
0x79080001,
0x00000000,
0x00000000,
0x790a0001,
0x00000000,
0x00000000,
0x78060003,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x78070003,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x78040001,
0x00000000,
0x00000000,
0x79110000,
0x00000000,
0x780d0000,
0x00000000,
0x79060000,
0x00000000,
0x7907001f,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x7902000f,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x790c000f,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x780a0003,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x78080083,
0x00004000,
0x00000000,
0x00000000,
0x00000000,
0x04004000,
0x00000000,
0x00000000,
0x00000000,
0x08004000,
0x00000000,
0x00000000,
0x00000000,
0x0c004000,
0x00000000,
0x00000000,
0x00000000,
0x10004000,
0x00000000,
0x00000000,
0x00000000,
0x14004000,
0x00000000,
0x00000000,
0x00000000,
0x18004000,
0x00000000,
0x00000000,
0x00000000,
0x1c004000,
0x00000000,
0x00000000,
0x00000000,
0x20004000,
0x00000000,
0x00000000,
0x00000000,
0x24004000,
0x00000000,
0x00000000,
0x00000000,
0x28004000,
0x00000000,
0x00000000,
0x00000000,
0x2c004000,
0x00000000,
0x00000000,
0x00000000,
0x30004000,
0x00000000,
0x00000000,
0x00000000,
0x34004000,
0x00000000,
0x00000000,
0x00000000,
0x38004000,
0x00000000,
0x00000000,
0x00000000,
0x3c004000,
0x00000000,
0x00000000,
0x00000000,
0x40004000,
0x00000000,
0x00000000,
0x00000000,
0x44004000,
0x00000000,
0x00000000,
0x00000000,
0x48004000,
0x00000000,
0x00000000,
0x00000000,
0x4c004000,
0x00000000,
0x00000000,
0x00000000,
0x50004000,
0x00000000,
0x00000000,
0x00000000,
0x54004000,
0x00000000,
0x00000000,
0x00000000,
0x58004000,
0x00000000,
0x00000000,
0x00000000,
0x5c004000,
0x00000000,
0x00000000,
0x00000000,
0x60004000,
0x00000000,
0x00000000,
0x00000000,
0x64004000,
0x00000000,
0x00000000,
0x00000000,
0x68004000,
0x00000000,
0x00000000,
0x00000000,
0x6c004000,
0x00000000,
0x00000000,
0x00000000,
0x70004000,
0x00000000,
0x00000000,
0x00000000,
0x74004000,
0x00000000,
0x00000000,
0x00000000,
0x78004000,
0x00000000,
0x00000000,
0x00000000,
0x7c004000,
0x00000000,
0x00000000,
0x00000000,
0x80004000,
0x00000000,
0x00000000,
0x00000000,
0x78090043,
0x02000000,
0x22220000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x78550003,
0x0000000f,
0x00000000,
0x00000000,
0x00000000,
0x680b0001,
0x780e0000,
0x00000e01,
0x78240000,
0x00000e41,
0x784f0000,
0x80000100,
0x784d0000,
0x40000000,
0x782b0000,
0x00000000,
0x782c0000,
0x00000000,
0x782d0000,
0x00000000,
0x782e0000,
0x00000000,
0x782f0000,
0x00000000,
0x780f0000,
0x00000000,
0x78230000,
0x00000ea0,
0x78210000,
0x00000ec0,
0x78260000,
0x00000000,
0x78270000,
0x00000000,
0x78280000,
0x00000000,
0x78290000,
0x00000000,
0x782a0000,
0x00000000,
0x7b000005,
0x00000004,
0x00000001,
0x00000000,
0x00000001,
0x00000000,
0x00000000,
0x05000000, /* cmds end */
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000, /* state start */
0x00000000,
0x3f800000,
0x3f800000,
0x3f800000,
0x3f800000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
0x00000000, /* state end */
};
RO_RENDERSTATE(9);
| linux-master | drivers/gpu/drm/i915/gt/gen9_renderstate.c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.