Home | History | Annotate | Line # | Download | only in i915
i915_gem.c revision 1.1.1.3
      1 /*	$NetBSD: i915_gem.c,v 1.1.1.3 2018/08/27 01:34:53 riastradh Exp $	*/
      2 
      3 /*
      4  * Copyright  2008-2015 Intel Corporation
      5  *
      6  * Permission is hereby granted, free of charge, to any person obtaining a
      7  * copy of this software and associated documentation files (the "Software"),
      8  * to deal in the Software without restriction, including without limitation
      9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
     10  * and/or sell copies of the Software, and to permit persons to whom the
     11  * Software is furnished to do so, subject to the following conditions:
     12  *
     13  * The above copyright notice and this permission notice (including the next
     14  * paragraph) shall be included in all copies or substantial portions of the
     15  * Software.
     16  *
     17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
     20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
     22  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
     23  * IN THE SOFTWARE.
     24  *
     25  * Authors:
     26  *    Eric Anholt <eric (at) anholt.net>
     27  *
     28  */
     29 
     30 #include <sys/cdefs.h>
     31 __KERNEL_RCSID(0, "$NetBSD: i915_gem.c,v 1.1.1.3 2018/08/27 01:34:53 riastradh Exp $");
     32 
     33 #include <drm/drmP.h>
     34 #include <drm/drm_vma_manager.h>
     35 #include <drm/i915_drm.h>
     36 #include "i915_drv.h"
     37 #include "i915_vgpu.h"
     38 #include "i915_trace.h"
     39 #include "intel_drv.h"
     40 #include <linux/shmem_fs.h>
     41 #include <linux/slab.h>
     42 #include <linux/swap.h>
     43 #include <linux/pci.h>
     44 #include <linux/dma-buf.h>
     45 
     46 #define RQ_BUG_ON(expr)
     47 
     48 static void i915_gem_object_flush_gtt_write_domain(struct drm_i915_gem_object *obj);
     49 static void i915_gem_object_flush_cpu_write_domain(struct drm_i915_gem_object *obj);
     50 static void
     51 i915_gem_object_retire__write(struct drm_i915_gem_object *obj);
     52 static void
     53 i915_gem_object_retire__read(struct drm_i915_gem_object *obj, int ring);
     54 
     55 static bool cpu_cache_is_coherent(struct drm_device *dev,
     56 				  enum i915_cache_level level)
     57 {
     58 	return HAS_LLC(dev) || level != I915_CACHE_NONE;
     59 }
     60 
     61 static bool cpu_write_needs_clflush(struct drm_i915_gem_object *obj)
     62 {
     63 	if (!cpu_cache_is_coherent(obj->base.dev, obj->cache_level))
     64 		return true;
     65 
     66 	return obj->pin_display;
     67 }
     68 
     69 /* some bookkeeping */
     70 static void i915_gem_info_add_obj(struct drm_i915_private *dev_priv,
     71 				  size_t size)
     72 {
     73 	spin_lock(&dev_priv->mm.object_stat_lock);
     74 	dev_priv->mm.object_count++;
     75 	dev_priv->mm.object_memory += size;
     76 	spin_unlock(&dev_priv->mm.object_stat_lock);
     77 }
     78 
     79 static void i915_gem_info_remove_obj(struct drm_i915_private *dev_priv,
     80 				     size_t size)
     81 {
     82 	spin_lock(&dev_priv->mm.object_stat_lock);
     83 	dev_priv->mm.object_count--;
     84 	dev_priv->mm.object_memory -= size;
     85 	spin_unlock(&dev_priv->mm.object_stat_lock);
     86 }
     87 
     88 static int
     89 i915_gem_wait_for_error(struct i915_gpu_error *error)
     90 {
     91 	int ret;
     92 
     93 #define EXIT_COND (!i915_reset_in_progress(error) || \
     94 		   i915_terminally_wedged(error))
     95 	if (EXIT_COND)
     96 		return 0;
     97 
     98 	/*
     99 	 * Only wait 10 seconds for the gpu reset to complete to avoid hanging
    100 	 * userspace. If it takes that long something really bad is going on and
    101 	 * we should simply try to bail out and fail as gracefully as possible.
    102 	 */
    103 	ret = wait_event_interruptible_timeout(error->reset_queue,
    104 					       EXIT_COND,
    105 					       10*HZ);
    106 	if (ret == 0) {
    107 		DRM_ERROR("Timed out waiting for the gpu reset to complete\n");
    108 		return -EIO;
    109 	} else if (ret < 0) {
    110 		return ret;
    111 	}
    112 #undef EXIT_COND
    113 
    114 	return 0;
    115 }
    116 
    117 int i915_mutex_lock_interruptible(struct drm_device *dev)
    118 {
    119 	struct drm_i915_private *dev_priv = dev->dev_private;
    120 	int ret;
    121 
    122 	ret = i915_gem_wait_for_error(&dev_priv->gpu_error);
    123 	if (ret)
    124 		return ret;
    125 
    126 	ret = mutex_lock_interruptible(&dev->struct_mutex);
    127 	if (ret)
    128 		return ret;
    129 
    130 	WARN_ON(i915_verify_lists(dev));
    131 	return 0;
    132 }
    133 
    134 int
    135 i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
    136 			    struct drm_file *file)
    137 {
    138 	struct drm_i915_private *dev_priv = dev->dev_private;
    139 	struct drm_i915_gem_get_aperture *args = data;
    140 	struct i915_gtt *ggtt = &dev_priv->gtt;
    141 	struct i915_vma *vma;
    142 	size_t pinned;
    143 
    144 	pinned = 0;
    145 	mutex_lock(&dev->struct_mutex);
    146 	list_for_each_entry(vma, &ggtt->base.active_list, mm_list)
    147 		if (vma->pin_count)
    148 			pinned += vma->node.size;
    149 	list_for_each_entry(vma, &ggtt->base.inactive_list, mm_list)
    150 		if (vma->pin_count)
    151 			pinned += vma->node.size;
    152 	mutex_unlock(&dev->struct_mutex);
    153 
    154 	args->aper_size = dev_priv->gtt.base.total;
    155 	args->aper_available_size = args->aper_size - pinned;
    156 
    157 	return 0;
    158 }
    159 
    160 static int
    161 i915_gem_object_get_pages_phys(struct drm_i915_gem_object *obj)
    162 {
    163 	struct address_space *mapping = file_inode(obj->base.filp)->i_mapping;
    164 	char *vaddr = obj->phys_handle->vaddr;
    165 	struct sg_table *st;
    166 	struct scatterlist *sg;
    167 	int i;
    168 
    169 	if (WARN_ON(i915_gem_object_needs_bit17_swizzle(obj)))
    170 		return -EINVAL;
    171 
    172 	for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
    173 		struct page *page;
    174 		char *src;
    175 
    176 		page = shmem_read_mapping_page(mapping, i);
    177 		if (IS_ERR(page))
    178 			return PTR_ERR(page);
    179 
    180 		src = kmap_atomic(page);
    181 		memcpy(vaddr, src, PAGE_SIZE);
    182 		drm_clflush_virt_range(vaddr, PAGE_SIZE);
    183 		kunmap_atomic(src);
    184 
    185 		page_cache_release(page);
    186 		vaddr += PAGE_SIZE;
    187 	}
    188 
    189 	i915_gem_chipset_flush(obj->base.dev);
    190 
    191 	st = kmalloc(sizeof(*st), GFP_KERNEL);
    192 	if (st == NULL)
    193 		return -ENOMEM;
    194 
    195 	if (sg_alloc_table(st, 1, GFP_KERNEL)) {
    196 		kfree(st);
    197 		return -ENOMEM;
    198 	}
    199 
    200 	sg = st->sgl;
    201 	sg->offset = 0;
    202 	sg->length = obj->base.size;
    203 
    204 	sg_dma_address(sg) = obj->phys_handle->busaddr;
    205 	sg_dma_len(sg) = obj->base.size;
    206 
    207 	obj->pages = st;
    208 	return 0;
    209 }
    210 
    211 static void
    212 i915_gem_object_put_pages_phys(struct drm_i915_gem_object *obj)
    213 {
    214 	int ret;
    215 
    216 	BUG_ON(obj->madv == __I915_MADV_PURGED);
    217 
    218 	ret = i915_gem_object_set_to_cpu_domain(obj, true);
    219 	if (ret) {
    220 		/* In the event of a disaster, abandon all caches and
    221 		 * hope for the best.
    222 		 */
    223 		WARN_ON(ret != -EIO);
    224 		obj->base.read_domains = obj->base.write_domain = I915_GEM_DOMAIN_CPU;
    225 	}
    226 
    227 	if (obj->madv == I915_MADV_DONTNEED)
    228 		obj->dirty = 0;
    229 
    230 	if (obj->dirty) {
    231 		struct address_space *mapping = file_inode(obj->base.filp)->i_mapping;
    232 		char *vaddr = obj->phys_handle->vaddr;
    233 		int i;
    234 
    235 		for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
    236 			struct page *page;
    237 			char *dst;
    238 
    239 			page = shmem_read_mapping_page(mapping, i);
    240 			if (IS_ERR(page))
    241 				continue;
    242 
    243 			dst = kmap_atomic(page);
    244 			drm_clflush_virt_range(vaddr, PAGE_SIZE);
    245 			memcpy(dst, vaddr, PAGE_SIZE);
    246 			kunmap_atomic(dst);
    247 
    248 			set_page_dirty(page);
    249 			if (obj->madv == I915_MADV_WILLNEED)
    250 				mark_page_accessed(page);
    251 			page_cache_release(page);
    252 			vaddr += PAGE_SIZE;
    253 		}
    254 		obj->dirty = 0;
    255 	}
    256 
    257 	sg_free_table(obj->pages);
    258 	kfree(obj->pages);
    259 }
    260 
    261 static void
    262 i915_gem_object_release_phys(struct drm_i915_gem_object *obj)
    263 {
    264 	drm_pci_free(obj->base.dev, obj->phys_handle);
    265 }
    266 
    267 static const struct drm_i915_gem_object_ops i915_gem_phys_ops = {
    268 	.get_pages = i915_gem_object_get_pages_phys,
    269 	.put_pages = i915_gem_object_put_pages_phys,
    270 	.release = i915_gem_object_release_phys,
    271 };
    272 
    273 static int
    274 drop_pages(struct drm_i915_gem_object *obj)
    275 {
    276 	struct i915_vma *vma, *next;
    277 	int ret;
    278 
    279 	drm_gem_object_reference(&obj->base);
    280 	list_for_each_entry_safe(vma, next, &obj->vma_list, vma_link)
    281 		if (i915_vma_unbind(vma))
    282 			break;
    283 
    284 	ret = i915_gem_object_put_pages(obj);
    285 	drm_gem_object_unreference(&obj->base);
    286 
    287 	return ret;
    288 }
    289 
    290 int
    291 i915_gem_object_attach_phys(struct drm_i915_gem_object *obj,
    292 			    int align)
    293 {
    294 	drm_dma_handle_t *phys;
    295 	int ret;
    296 
    297 	if (obj->phys_handle) {
    298 		if ((unsigned long)obj->phys_handle->vaddr & (align -1))
    299 			return -EBUSY;
    300 
    301 		return 0;
    302 	}
    303 
    304 	if (obj->madv != I915_MADV_WILLNEED)
    305 		return -EFAULT;
    306 
    307 	if (obj->base.filp == NULL)
    308 		return -EINVAL;
    309 
    310 	ret = drop_pages(obj);
    311 	if (ret)
    312 		return ret;
    313 
    314 	/* create a new object */
    315 	phys = drm_pci_alloc(obj->base.dev, obj->base.size, align);
    316 	if (!phys)
    317 		return -ENOMEM;
    318 
    319 	obj->phys_handle = phys;
    320 	obj->ops = &i915_gem_phys_ops;
    321 
    322 	return i915_gem_object_get_pages(obj);
    323 }
    324 
    325 static int
    326 i915_gem_phys_pwrite(struct drm_i915_gem_object *obj,
    327 		     struct drm_i915_gem_pwrite *args,
    328 		     struct drm_file *file_priv)
    329 {
    330 	struct drm_device *dev = obj->base.dev;
    331 	void *vaddr = obj->phys_handle->vaddr + args->offset;
    332 	char __user *user_data = to_user_ptr(args->data_ptr);
    333 	int ret = 0;
    334 
    335 	/* We manually control the domain here and pretend that it
    336 	 * remains coherent i.e. in the GTT domain, like shmem_pwrite.
    337 	 */
    338 	ret = i915_gem_object_wait_rendering(obj, false);
    339 	if (ret)
    340 		return ret;
    341 
    342 	intel_fb_obj_invalidate(obj, ORIGIN_CPU);
    343 	if (__copy_from_user_inatomic_nocache(vaddr, user_data, args->size)) {
    344 		unsigned long unwritten;
    345 
    346 		/* The physical object once assigned is fixed for the lifetime
    347 		 * of the obj, so we can safely drop the lock and continue
    348 		 * to access vaddr.
    349 		 */
    350 		mutex_unlock(&dev->struct_mutex);
    351 		unwritten = copy_from_user(vaddr, user_data, args->size);
    352 		mutex_lock(&dev->struct_mutex);
    353 		if (unwritten) {
    354 			ret = -EFAULT;
    355 			goto out;
    356 		}
    357 	}
    358 
    359 	drm_clflush_virt_range(vaddr, args->size);
    360 	i915_gem_chipset_flush(dev);
    361 
    362 out:
    363 	intel_fb_obj_flush(obj, false, ORIGIN_CPU);
    364 	return ret;
    365 }
    366 
    367 void *i915_gem_object_alloc(struct drm_device *dev)
    368 {
    369 	struct drm_i915_private *dev_priv = dev->dev_private;
    370 	return kmem_cache_zalloc(dev_priv->objects, GFP_KERNEL);
    371 }
    372 
    373 void i915_gem_object_free(struct drm_i915_gem_object *obj)
    374 {
    375 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
    376 	kmem_cache_free(dev_priv->objects, obj);
    377 }
    378 
    379 static int
    380 i915_gem_create(struct drm_file *file,
    381 		struct drm_device *dev,
    382 		uint64_t size,
    383 		uint32_t *handle_p)
    384 {
    385 	struct drm_i915_gem_object *obj;
    386 	int ret;
    387 	u32 handle;
    388 
    389 	size = roundup(size, PAGE_SIZE);
    390 	if (size == 0)
    391 		return -EINVAL;
    392 
    393 	/* Allocate the new object */
    394 	obj = i915_gem_alloc_object(dev, size);
    395 	if (obj == NULL)
    396 		return -ENOMEM;
    397 
    398 	ret = drm_gem_handle_create(file, &obj->base, &handle);
    399 	/* drop reference from allocate - handle holds it now */
    400 	drm_gem_object_unreference_unlocked(&obj->base);
    401 	if (ret)
    402 		return ret;
    403 
    404 	*handle_p = handle;
    405 	return 0;
    406 }
    407 
    408 int
    409 i915_gem_dumb_create(struct drm_file *file,
    410 		     struct drm_device *dev,
    411 		     struct drm_mode_create_dumb *args)
    412 {
    413 	/* have to work out size/pitch and return them */
    414 	args->pitch = ALIGN(args->width * DIV_ROUND_UP(args->bpp, 8), 64);
    415 	args->size = args->pitch * args->height;
    416 	return i915_gem_create(file, dev,
    417 			       args->size, &args->handle);
    418 }
    419 
    420 /**
    421  * Creates a new mm object and returns a handle to it.
    422  */
    423 int
    424 i915_gem_create_ioctl(struct drm_device *dev, void *data,
    425 		      struct drm_file *file)
    426 {
    427 	struct drm_i915_gem_create *args = data;
    428 
    429 	return i915_gem_create(file, dev,
    430 			       args->size, &args->handle);
    431 }
    432 
    433 static inline int
    434 __copy_to_user_swizzled(char __user *cpu_vaddr,
    435 			const char *gpu_vaddr, int gpu_offset,
    436 			int length)
    437 {
    438 	int ret, cpu_offset = 0;
    439 
    440 	while (length > 0) {
    441 		int cacheline_end = ALIGN(gpu_offset + 1, 64);
    442 		int this_length = min(cacheline_end - gpu_offset, length);
    443 		int swizzled_gpu_offset = gpu_offset ^ 64;
    444 
    445 		ret = __copy_to_user(cpu_vaddr + cpu_offset,
    446 				     gpu_vaddr + swizzled_gpu_offset,
    447 				     this_length);
    448 		if (ret)
    449 			return ret + length;
    450 
    451 		cpu_offset += this_length;
    452 		gpu_offset += this_length;
    453 		length -= this_length;
    454 	}
    455 
    456 	return 0;
    457 }
    458 
    459 static inline int
    460 __copy_from_user_swizzled(char *gpu_vaddr, int gpu_offset,
    461 			  const char __user *cpu_vaddr,
    462 			  int length)
    463 {
    464 	int ret, cpu_offset = 0;
    465 
    466 	while (length > 0) {
    467 		int cacheline_end = ALIGN(gpu_offset + 1, 64);
    468 		int this_length = min(cacheline_end - gpu_offset, length);
    469 		int swizzled_gpu_offset = gpu_offset ^ 64;
    470 
    471 		ret = __copy_from_user(gpu_vaddr + swizzled_gpu_offset,
    472 				       cpu_vaddr + cpu_offset,
    473 				       this_length);
    474 		if (ret)
    475 			return ret + length;
    476 
    477 		cpu_offset += this_length;
    478 		gpu_offset += this_length;
    479 		length -= this_length;
    480 	}
    481 
    482 	return 0;
    483 }
    484 
    485 /*
    486  * Pins the specified object's pages and synchronizes the object with
    487  * GPU accesses. Sets needs_clflush to non-zero if the caller should
    488  * flush the object from the CPU cache.
    489  */
    490 int i915_gem_obj_prepare_shmem_read(struct drm_i915_gem_object *obj,
    491 				    int *needs_clflush)
    492 {
    493 	int ret;
    494 
    495 	*needs_clflush = 0;
    496 
    497 	if (!obj->base.filp)
    498 		return -EINVAL;
    499 
    500 	if (!(obj->base.read_domains & I915_GEM_DOMAIN_CPU)) {
    501 		/* If we're not in the cpu read domain, set ourself into the gtt
    502 		 * read domain and manually flush cachelines (if required). This
    503 		 * optimizes for the case when the gpu will dirty the data
    504 		 * anyway again before the next pread happens. */
    505 		*needs_clflush = !cpu_cache_is_coherent(obj->base.dev,
    506 							obj->cache_level);
    507 		ret = i915_gem_object_wait_rendering(obj, true);
    508 		if (ret)
    509 			return ret;
    510 	}
    511 
    512 	ret = i915_gem_object_get_pages(obj);
    513 	if (ret)
    514 		return ret;
    515 
    516 	i915_gem_object_pin_pages(obj);
    517 
    518 	return ret;
    519 }
    520 
    521 /* Per-page copy function for the shmem pread fastpath.
    522  * Flushes invalid cachelines before reading the target if
    523  * needs_clflush is set. */
    524 static int
    525 shmem_pread_fast(struct page *page, int shmem_page_offset, int page_length,
    526 		 char __user *user_data,
    527 		 bool page_do_bit17_swizzling, bool needs_clflush)
    528 {
    529 	char *vaddr;
    530 	int ret;
    531 
    532 	if (unlikely(page_do_bit17_swizzling))
    533 		return -EINVAL;
    534 
    535 	vaddr = kmap_atomic(page);
    536 	if (needs_clflush)
    537 		drm_clflush_virt_range(vaddr + shmem_page_offset,
    538 				       page_length);
    539 	ret = __copy_to_user_inatomic(user_data,
    540 				      vaddr + shmem_page_offset,
    541 				      page_length);
    542 	kunmap_atomic(vaddr);
    543 
    544 	return ret ? -EFAULT : 0;
    545 }
    546 
    547 static void
    548 shmem_clflush_swizzled_range(char *addr, unsigned long length,
    549 			     bool swizzled)
    550 {
    551 	if (unlikely(swizzled)) {
    552 		unsigned long start = (unsigned long) addr;
    553 		unsigned long end = (unsigned long) addr + length;
    554 
    555 		/* For swizzling simply ensure that we always flush both
    556 		 * channels. Lame, but simple and it works. Swizzled
    557 		 * pwrite/pread is far from a hotpath - current userspace
    558 		 * doesn't use it at all. */
    559 		start = round_down(start, 128);
    560 		end = round_up(end, 128);
    561 
    562 		drm_clflush_virt_range((void *)start, end - start);
    563 	} else {
    564 		drm_clflush_virt_range(addr, length);
    565 	}
    566 
    567 }
    568 
    569 /* Only difference to the fast-path function is that this can handle bit17
    570  * and uses non-atomic copy and kmap functions. */
    571 static int
    572 shmem_pread_slow(struct page *page, int shmem_page_offset, int page_length,
    573 		 char __user *user_data,
    574 		 bool page_do_bit17_swizzling, bool needs_clflush)
    575 {
    576 	char *vaddr;
    577 	int ret;
    578 
    579 	vaddr = kmap(page);
    580 	if (needs_clflush)
    581 		shmem_clflush_swizzled_range(vaddr + shmem_page_offset,
    582 					     page_length,
    583 					     page_do_bit17_swizzling);
    584 
    585 	if (page_do_bit17_swizzling)
    586 		ret = __copy_to_user_swizzled(user_data,
    587 					      vaddr, shmem_page_offset,
    588 					      page_length);
    589 	else
    590 		ret = __copy_to_user(user_data,
    591 				     vaddr + shmem_page_offset,
    592 				     page_length);
    593 	kunmap(page);
    594 
    595 	return ret ? - EFAULT : 0;
    596 }
    597 
    598 static int
    599 i915_gem_shmem_pread(struct drm_device *dev,
    600 		     struct drm_i915_gem_object *obj,
    601 		     struct drm_i915_gem_pread *args,
    602 		     struct drm_file *file)
    603 {
    604 	char __user *user_data;
    605 	ssize_t remain;
    606 	loff_t offset;
    607 	int shmem_page_offset, page_length, ret = 0;
    608 	int obj_do_bit17_swizzling, page_do_bit17_swizzling;
    609 	int prefaulted = 0;
    610 	int needs_clflush = 0;
    611 	struct sg_page_iter sg_iter;
    612 
    613 	user_data = to_user_ptr(args->data_ptr);
    614 	remain = args->size;
    615 
    616 	obj_do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
    617 
    618 	ret = i915_gem_obj_prepare_shmem_read(obj, &needs_clflush);
    619 	if (ret)
    620 		return ret;
    621 
    622 	offset = args->offset;
    623 
    624 	for_each_sg_page(obj->pages->sgl, &sg_iter, obj->pages->nents,
    625 			 offset >> PAGE_SHIFT) {
    626 		struct page *page = sg_page_iter_page(&sg_iter);
    627 
    628 		if (remain <= 0)
    629 			break;
    630 
    631 		/* Operation in this page
    632 		 *
    633 		 * shmem_page_offset = offset within page in shmem file
    634 		 * page_length = bytes to copy for this page
    635 		 */
    636 		shmem_page_offset = offset_in_page(offset);
    637 		page_length = remain;
    638 		if ((shmem_page_offset + page_length) > PAGE_SIZE)
    639 			page_length = PAGE_SIZE - shmem_page_offset;
    640 
    641 		page_do_bit17_swizzling = obj_do_bit17_swizzling &&
    642 			(page_to_phys(page) & (1 << 17)) != 0;
    643 
    644 		ret = shmem_pread_fast(page, shmem_page_offset, page_length,
    645 				       user_data, page_do_bit17_swizzling,
    646 				       needs_clflush);
    647 		if (ret == 0)
    648 			goto next_page;
    649 
    650 		mutex_unlock(&dev->struct_mutex);
    651 
    652 		if (likely(!i915.prefault_disable) && !prefaulted) {
    653 			ret = fault_in_multipages_writeable(user_data, remain);
    654 			/* Userspace is tricking us, but we've already clobbered
    655 			 * its pages with the prefault and promised to write the
    656 			 * data up to the first fault. Hence ignore any errors
    657 			 * and just continue. */
    658 			(void)ret;
    659 			prefaulted = 1;
    660 		}
    661 
    662 		ret = shmem_pread_slow(page, shmem_page_offset, page_length,
    663 				       user_data, page_do_bit17_swizzling,
    664 				       needs_clflush);
    665 
    666 		mutex_lock(&dev->struct_mutex);
    667 
    668 		if (ret)
    669 			goto out;
    670 
    671 next_page:
    672 		remain -= page_length;
    673 		user_data += page_length;
    674 		offset += page_length;
    675 	}
    676 
    677 out:
    678 	i915_gem_object_unpin_pages(obj);
    679 
    680 	return ret;
    681 }
    682 
    683 /**
    684  * Reads data from the object referenced by handle.
    685  *
    686  * On error, the contents of *data are undefined.
    687  */
    688 int
    689 i915_gem_pread_ioctl(struct drm_device *dev, void *data,
    690 		     struct drm_file *file)
    691 {
    692 	struct drm_i915_gem_pread *args = data;
    693 	struct drm_i915_gem_object *obj;
    694 	int ret = 0;
    695 
    696 	if (args->size == 0)
    697 		return 0;
    698 
    699 	if (!access_ok(VERIFY_WRITE,
    700 		       to_user_ptr(args->data_ptr),
    701 		       args->size))
    702 		return -EFAULT;
    703 
    704 	ret = i915_mutex_lock_interruptible(dev);
    705 	if (ret)
    706 		return ret;
    707 
    708 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
    709 	if (&obj->base == NULL) {
    710 		ret = -ENOENT;
    711 		goto unlock;
    712 	}
    713 
    714 	/* Bounds check source.  */
    715 	if (args->offset > obj->base.size ||
    716 	    args->size > obj->base.size - args->offset) {
    717 		ret = -EINVAL;
    718 		goto out;
    719 	}
    720 
    721 	/* prime objects have no backing filp to GEM pread/pwrite
    722 	 * pages from.
    723 	 */
    724 	if (!obj->base.filp) {
    725 		ret = -EINVAL;
    726 		goto out;
    727 	}
    728 
    729 	trace_i915_gem_object_pread(obj, args->offset, args->size);
    730 
    731 	ret = i915_gem_shmem_pread(dev, obj, args, file);
    732 
    733 out:
    734 	drm_gem_object_unreference(&obj->base);
    735 unlock:
    736 	mutex_unlock(&dev->struct_mutex);
    737 	return ret;
    738 }
    739 
    740 /* This is the fast write path which cannot handle
    741  * page faults in the source data
    742  */
    743 
    744 static inline int
    745 fast_user_write(struct io_mapping *mapping,
    746 		loff_t page_base, int page_offset,
    747 		char __user *user_data,
    748 		int length)
    749 {
    750 	void __iomem *vaddr_atomic;
    751 	void *vaddr;
    752 	unsigned long unwritten;
    753 
    754 	vaddr_atomic = io_mapping_map_atomic_wc(mapping, page_base);
    755 	/* We can use the cpu mem copy function because this is X86. */
    756 	vaddr = (void __force*)vaddr_atomic + page_offset;
    757 	unwritten = __copy_from_user_inatomic_nocache(vaddr,
    758 						      user_data, length);
    759 	io_mapping_unmap_atomic(vaddr_atomic);
    760 	return unwritten;
    761 }
    762 
    763 /**
    764  * This is the fast pwrite path, where we copy the data directly from the
    765  * user into the GTT, uncached.
    766  */
    767 static int
    768 i915_gem_gtt_pwrite_fast(struct drm_device *dev,
    769 			 struct drm_i915_gem_object *obj,
    770 			 struct drm_i915_gem_pwrite *args,
    771 			 struct drm_file *file)
    772 {
    773 	struct drm_i915_private *dev_priv = dev->dev_private;
    774 	ssize_t remain;
    775 	loff_t offset, page_base;
    776 	char __user *user_data;
    777 	int page_offset, page_length, ret;
    778 
    779 	ret = i915_gem_obj_ggtt_pin(obj, 0, PIN_MAPPABLE | PIN_NONBLOCK);
    780 	if (ret)
    781 		goto out;
    782 
    783 	ret = i915_gem_object_set_to_gtt_domain(obj, true);
    784 	if (ret)
    785 		goto out_unpin;
    786 
    787 	ret = i915_gem_object_put_fence(obj);
    788 	if (ret)
    789 		goto out_unpin;
    790 
    791 	user_data = to_user_ptr(args->data_ptr);
    792 	remain = args->size;
    793 
    794 	offset = i915_gem_obj_ggtt_offset(obj) + args->offset;
    795 
    796 	intel_fb_obj_invalidate(obj, ORIGIN_GTT);
    797 
    798 	while (remain > 0) {
    799 		/* Operation in this page
    800 		 *
    801 		 * page_base = page offset within aperture
    802 		 * page_offset = offset within page
    803 		 * page_length = bytes to copy for this page
    804 		 */
    805 		page_base = offset & PAGE_MASK;
    806 		page_offset = offset_in_page(offset);
    807 		page_length = remain;
    808 		if ((page_offset + remain) > PAGE_SIZE)
    809 			page_length = PAGE_SIZE - page_offset;
    810 
    811 		/* If we get a fault while copying data, then (presumably) our
    812 		 * source page isn't available.  Return the error and we'll
    813 		 * retry in the slow path.
    814 		 */
    815 		if (fast_user_write(dev_priv->gtt.mappable, page_base,
    816 				    page_offset, user_data, page_length)) {
    817 			ret = -EFAULT;
    818 			goto out_flush;
    819 		}
    820 
    821 		remain -= page_length;
    822 		user_data += page_length;
    823 		offset += page_length;
    824 	}
    825 
    826 out_flush:
    827 	intel_fb_obj_flush(obj, false, ORIGIN_GTT);
    828 out_unpin:
    829 	i915_gem_object_ggtt_unpin(obj);
    830 out:
    831 	return ret;
    832 }
    833 
    834 /* Per-page copy function for the shmem pwrite fastpath.
    835  * Flushes invalid cachelines before writing to the target if
    836  * needs_clflush_before is set and flushes out any written cachelines after
    837  * writing if needs_clflush is set. */
    838 static int
    839 shmem_pwrite_fast(struct page *page, int shmem_page_offset, int page_length,
    840 		  char __user *user_data,
    841 		  bool page_do_bit17_swizzling,
    842 		  bool needs_clflush_before,
    843 		  bool needs_clflush_after)
    844 {
    845 	char *vaddr;
    846 	int ret;
    847 
    848 	if (unlikely(page_do_bit17_swizzling))
    849 		return -EINVAL;
    850 
    851 	vaddr = kmap_atomic(page);
    852 	if (needs_clflush_before)
    853 		drm_clflush_virt_range(vaddr + shmem_page_offset,
    854 				       page_length);
    855 	ret = __copy_from_user_inatomic(vaddr + shmem_page_offset,
    856 					user_data, page_length);
    857 	if (needs_clflush_after)
    858 		drm_clflush_virt_range(vaddr + shmem_page_offset,
    859 				       page_length);
    860 	kunmap_atomic(vaddr);
    861 
    862 	return ret ? -EFAULT : 0;
    863 }
    864 
    865 /* Only difference to the fast-path function is that this can handle bit17
    866  * and uses non-atomic copy and kmap functions. */
    867 static int
    868 shmem_pwrite_slow(struct page *page, int shmem_page_offset, int page_length,
    869 		  char __user *user_data,
    870 		  bool page_do_bit17_swizzling,
    871 		  bool needs_clflush_before,
    872 		  bool needs_clflush_after)
    873 {
    874 	char *vaddr;
    875 	int ret;
    876 
    877 	vaddr = kmap(page);
    878 	if (unlikely(needs_clflush_before || page_do_bit17_swizzling))
    879 		shmem_clflush_swizzled_range(vaddr + shmem_page_offset,
    880 					     page_length,
    881 					     page_do_bit17_swizzling);
    882 	if (page_do_bit17_swizzling)
    883 		ret = __copy_from_user_swizzled(vaddr, shmem_page_offset,
    884 						user_data,
    885 						page_length);
    886 	else
    887 		ret = __copy_from_user(vaddr + shmem_page_offset,
    888 				       user_data,
    889 				       page_length);
    890 	if (needs_clflush_after)
    891 		shmem_clflush_swizzled_range(vaddr + shmem_page_offset,
    892 					     page_length,
    893 					     page_do_bit17_swizzling);
    894 	kunmap(page);
    895 
    896 	return ret ? -EFAULT : 0;
    897 }
    898 
    899 static int
    900 i915_gem_shmem_pwrite(struct drm_device *dev,
    901 		      struct drm_i915_gem_object *obj,
    902 		      struct drm_i915_gem_pwrite *args,
    903 		      struct drm_file *file)
    904 {
    905 	ssize_t remain;
    906 	loff_t offset;
    907 	char __user *user_data;
    908 	int shmem_page_offset, page_length, ret = 0;
    909 	int obj_do_bit17_swizzling, page_do_bit17_swizzling;
    910 	int hit_slowpath = 0;
    911 	int needs_clflush_after = 0;
    912 	int needs_clflush_before = 0;
    913 	struct sg_page_iter sg_iter;
    914 
    915 	user_data = to_user_ptr(args->data_ptr);
    916 	remain = args->size;
    917 
    918 	obj_do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
    919 
    920 	if (obj->base.write_domain != I915_GEM_DOMAIN_CPU) {
    921 		/* If we're not in the cpu write domain, set ourself into the gtt
    922 		 * write domain and manually flush cachelines (if required). This
    923 		 * optimizes for the case when the gpu will use the data
    924 		 * right away and we therefore have to clflush anyway. */
    925 		needs_clflush_after = cpu_write_needs_clflush(obj);
    926 		ret = i915_gem_object_wait_rendering(obj, false);
    927 		if (ret)
    928 			return ret;
    929 	}
    930 	/* Same trick applies to invalidate partially written cachelines read
    931 	 * before writing. */
    932 	if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0)
    933 		needs_clflush_before =
    934 			!cpu_cache_is_coherent(dev, obj->cache_level);
    935 
    936 	ret = i915_gem_object_get_pages(obj);
    937 	if (ret)
    938 		return ret;
    939 
    940 	intel_fb_obj_invalidate(obj, ORIGIN_CPU);
    941 
    942 	i915_gem_object_pin_pages(obj);
    943 
    944 	offset = args->offset;
    945 	obj->dirty = 1;
    946 
    947 	for_each_sg_page(obj->pages->sgl, &sg_iter, obj->pages->nents,
    948 			 offset >> PAGE_SHIFT) {
    949 		struct page *page = sg_page_iter_page(&sg_iter);
    950 		int partial_cacheline_write;
    951 
    952 		if (remain <= 0)
    953 			break;
    954 
    955 		/* Operation in this page
    956 		 *
    957 		 * shmem_page_offset = offset within page in shmem file
    958 		 * page_length = bytes to copy for this page
    959 		 */
    960 		shmem_page_offset = offset_in_page(offset);
    961 
    962 		page_length = remain;
    963 		if ((shmem_page_offset + page_length) > PAGE_SIZE)
    964 			page_length = PAGE_SIZE - shmem_page_offset;
    965 
    966 		/* If we don't overwrite a cacheline completely we need to be
    967 		 * careful to have up-to-date data by first clflushing. Don't
    968 		 * overcomplicate things and flush the entire patch. */
    969 		partial_cacheline_write = needs_clflush_before &&
    970 			((shmem_page_offset | page_length)
    971 				& (boot_cpu_data.x86_clflush_size - 1));
    972 
    973 		page_do_bit17_swizzling = obj_do_bit17_swizzling &&
    974 			(page_to_phys(page) & (1 << 17)) != 0;
    975 
    976 		ret = shmem_pwrite_fast(page, shmem_page_offset, page_length,
    977 					user_data, page_do_bit17_swizzling,
    978 					partial_cacheline_write,
    979 					needs_clflush_after);
    980 		if (ret == 0)
    981 			goto next_page;
    982 
    983 		hit_slowpath = 1;
    984 		mutex_unlock(&dev->struct_mutex);
    985 		ret = shmem_pwrite_slow(page, shmem_page_offset, page_length,
    986 					user_data, page_do_bit17_swizzling,
    987 					partial_cacheline_write,
    988 					needs_clflush_after);
    989 
    990 		mutex_lock(&dev->struct_mutex);
    991 
    992 		if (ret)
    993 			goto out;
    994 
    995 next_page:
    996 		remain -= page_length;
    997 		user_data += page_length;
    998 		offset += page_length;
    999 	}
   1000 
   1001 out:
   1002 	i915_gem_object_unpin_pages(obj);
   1003 
   1004 	if (hit_slowpath) {
   1005 		/*
   1006 		 * Fixup: Flush cpu caches in case we didn't flush the dirty
   1007 		 * cachelines in-line while writing and the object moved
   1008 		 * out of the cpu write domain while we've dropped the lock.
   1009 		 */
   1010 		if (!needs_clflush_after &&
   1011 		    obj->base.write_domain != I915_GEM_DOMAIN_CPU) {
   1012 			if (i915_gem_clflush_object(obj, obj->pin_display))
   1013 				needs_clflush_after = true;
   1014 		}
   1015 	}
   1016 
   1017 	if (needs_clflush_after)
   1018 		i915_gem_chipset_flush(dev);
   1019 	else
   1020 		obj->cache_dirty = true;
   1021 
   1022 	intel_fb_obj_flush(obj, false, ORIGIN_CPU);
   1023 	return ret;
   1024 }
   1025 
   1026 /**
   1027  * Writes data to the object referenced by handle.
   1028  *
   1029  * On error, the contents of the buffer that were to be modified are undefined.
   1030  */
   1031 int
   1032 i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
   1033 		      struct drm_file *file)
   1034 {
   1035 	struct drm_i915_private *dev_priv = dev->dev_private;
   1036 	struct drm_i915_gem_pwrite *args = data;
   1037 	struct drm_i915_gem_object *obj;
   1038 	int ret;
   1039 
   1040 	if (args->size == 0)
   1041 		return 0;
   1042 
   1043 	if (!access_ok(VERIFY_READ,
   1044 		       to_user_ptr(args->data_ptr),
   1045 		       args->size))
   1046 		return -EFAULT;
   1047 
   1048 	if (likely(!i915.prefault_disable)) {
   1049 		ret = fault_in_multipages_readable(to_user_ptr(args->data_ptr),
   1050 						   args->size);
   1051 		if (ret)
   1052 			return -EFAULT;
   1053 	}
   1054 
   1055 	intel_runtime_pm_get(dev_priv);
   1056 
   1057 	ret = i915_mutex_lock_interruptible(dev);
   1058 	if (ret)
   1059 		goto put_rpm;
   1060 
   1061 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
   1062 	if (&obj->base == NULL) {
   1063 		ret = -ENOENT;
   1064 		goto unlock;
   1065 	}
   1066 
   1067 	/* Bounds check destination. */
   1068 	if (args->offset > obj->base.size ||
   1069 	    args->size > obj->base.size - args->offset) {
   1070 		ret = -EINVAL;
   1071 		goto out;
   1072 	}
   1073 
   1074 	/* prime objects have no backing filp to GEM pread/pwrite
   1075 	 * pages from.
   1076 	 */
   1077 	if (!obj->base.filp) {
   1078 		ret = -EINVAL;
   1079 		goto out;
   1080 	}
   1081 
   1082 	trace_i915_gem_object_pwrite(obj, args->offset, args->size);
   1083 
   1084 	ret = -EFAULT;
   1085 	/* We can only do the GTT pwrite on untiled buffers, as otherwise
   1086 	 * it would end up going through the fenced access, and we'll get
   1087 	 * different detiling behavior between reading and writing.
   1088 	 * pread/pwrite currently are reading and writing from the CPU
   1089 	 * perspective, requiring manual detiling by the client.
   1090 	 */
   1091 	if (obj->tiling_mode == I915_TILING_NONE &&
   1092 	    obj->base.write_domain != I915_GEM_DOMAIN_CPU &&
   1093 	    cpu_write_needs_clflush(obj)) {
   1094 		ret = i915_gem_gtt_pwrite_fast(dev, obj, args, file);
   1095 		/* Note that the gtt paths might fail with non-page-backed user
   1096 		 * pointers (e.g. gtt mappings when moving data between
   1097 		 * textures). Fallback to the shmem path in that case. */
   1098 	}
   1099 
   1100 	if (ret == -EFAULT || ret == -ENOSPC) {
   1101 		if (obj->phys_handle)
   1102 			ret = i915_gem_phys_pwrite(obj, args, file);
   1103 		else
   1104 			ret = i915_gem_shmem_pwrite(dev, obj, args, file);
   1105 	}
   1106 
   1107 out:
   1108 	drm_gem_object_unreference(&obj->base);
   1109 unlock:
   1110 	mutex_unlock(&dev->struct_mutex);
   1111 put_rpm:
   1112 	intel_runtime_pm_put(dev_priv);
   1113 
   1114 	return ret;
   1115 }
   1116 
   1117 int
   1118 i915_gem_check_wedge(struct i915_gpu_error *error,
   1119 		     bool interruptible)
   1120 {
   1121 	if (i915_reset_in_progress(error)) {
   1122 		/* Non-interruptible callers can't handle -EAGAIN, hence return
   1123 		 * -EIO unconditionally for these. */
   1124 		if (!interruptible)
   1125 			return -EIO;
   1126 
   1127 		/* Recovery complete, but the reset failed ... */
   1128 		if (i915_terminally_wedged(error))
   1129 			return -EIO;
   1130 
   1131 		/*
   1132 		 * Check if GPU Reset is in progress - we need intel_ring_begin
   1133 		 * to work properly to reinit the hw state while the gpu is
   1134 		 * still marked as reset-in-progress. Handle this with a flag.
   1135 		 */
   1136 		if (!error->reload_in_reset)
   1137 			return -EAGAIN;
   1138 	}
   1139 
   1140 	return 0;
   1141 }
   1142 
   1143 static void fake_irq(unsigned long data)
   1144 {
   1145 	wake_up_process((struct task_struct *)data);
   1146 }
   1147 
   1148 static bool missed_irq(struct drm_i915_private *dev_priv,
   1149 		       struct intel_engine_cs *ring)
   1150 {
   1151 	return test_bit(ring->id, &dev_priv->gpu_error.missed_irq_rings);
   1152 }
   1153 
   1154 static unsigned long local_clock_us(unsigned *cpu)
   1155 {
   1156 	unsigned long t;
   1157 
   1158 	/* Cheaply and approximately convert from nanoseconds to microseconds.
   1159 	 * The result and subsequent calculations are also defined in the same
   1160 	 * approximate microseconds units. The principal source of timing
   1161 	 * error here is from the simple truncation.
   1162 	 *
   1163 	 * Note that local_clock() is only defined wrt to the current CPU;
   1164 	 * the comparisons are no longer valid if we switch CPUs. Instead of
   1165 	 * blocking preemption for the entire busywait, we can detect the CPU
   1166 	 * switch and use that as indicator of system load and a reason to
   1167 	 * stop busywaiting, see busywait_stop().
   1168 	 */
   1169 	*cpu = get_cpu();
   1170 	t = local_clock() >> 10;
   1171 	put_cpu();
   1172 
   1173 	return t;
   1174 }
   1175 
   1176 static bool busywait_stop(unsigned long timeout, unsigned cpu)
   1177 {
   1178 	unsigned this_cpu;
   1179 
   1180 	if (time_after(local_clock_us(&this_cpu), timeout))
   1181 		return true;
   1182 
   1183 	return this_cpu != cpu;
   1184 }
   1185 
   1186 static int __i915_spin_request(struct drm_i915_gem_request *req, int state)
   1187 {
   1188 	unsigned long timeout;
   1189 	unsigned cpu;
   1190 
   1191 	/* When waiting for high frequency requests, e.g. during synchronous
   1192 	 * rendering split between the CPU and GPU, the finite amount of time
   1193 	 * required to set up the irq and wait upon it limits the response
   1194 	 * rate. By busywaiting on the request completion for a short while we
   1195 	 * can service the high frequency waits as quick as possible. However,
   1196 	 * if it is a slow request, we want to sleep as quickly as possible.
   1197 	 * The tradeoff between waiting and sleeping is roughly the time it
   1198 	 * takes to sleep on a request, on the order of a microsecond.
   1199 	 */
   1200 
   1201 	if (req->ring->irq_refcount)
   1202 		return -EBUSY;
   1203 
   1204 	/* Only spin if we know the GPU is processing this request */
   1205 	if (!i915_gem_request_started(req, true))
   1206 		return -EAGAIN;
   1207 
   1208 	timeout = local_clock_us(&cpu) + 5;
   1209 	while (!need_resched()) {
   1210 		if (i915_gem_request_completed(req, true))
   1211 			return 0;
   1212 
   1213 		if (signal_pending_state(state, current))
   1214 			break;
   1215 
   1216 		if (busywait_stop(timeout, cpu))
   1217 			break;
   1218 
   1219 		cpu_relax_lowlatency();
   1220 	}
   1221 
   1222 	if (i915_gem_request_completed(req, false))
   1223 		return 0;
   1224 
   1225 	return -EAGAIN;
   1226 }
   1227 
   1228 /**
   1229  * __i915_wait_request - wait until execution of request has finished
   1230  * @req: duh!
   1231  * @reset_counter: reset sequence associated with the given request
   1232  * @interruptible: do an interruptible wait (normally yes)
   1233  * @timeout: in - how long to wait (NULL forever); out - how much time remaining
   1234  *
   1235  * Note: It is of utmost importance that the passed in seqno and reset_counter
   1236  * values have been read by the caller in an smp safe manner. Where read-side
   1237  * locks are involved, it is sufficient to read the reset_counter before
   1238  * unlocking the lock that protects the seqno. For lockless tricks, the
   1239  * reset_counter _must_ be read before, and an appropriate smp_rmb must be
   1240  * inserted.
   1241  *
   1242  * Returns 0 if the request was found within the alloted time. Else returns the
   1243  * errno with remaining time filled in timeout argument.
   1244  */
   1245 int __i915_wait_request(struct drm_i915_gem_request *req,
   1246 			unsigned reset_counter,
   1247 			bool interruptible,
   1248 			s64 *timeout,
   1249 			struct intel_rps_client *rps)
   1250 {
   1251 	struct intel_engine_cs *ring = i915_gem_request_get_ring(req);
   1252 	struct drm_device *dev = ring->dev;
   1253 	struct drm_i915_private *dev_priv = dev->dev_private;
   1254 	const bool irq_test_in_progress =
   1255 		ACCESS_ONCE(dev_priv->gpu_error.test_irq_rings) & intel_ring_flag(ring);
   1256 	int state = interruptible ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE;
   1257 	DEFINE_WAIT(wait);
   1258 	unsigned long timeout_expire;
   1259 	s64 before, now;
   1260 	int ret;
   1261 
   1262 	WARN(!intel_irqs_enabled(dev_priv), "IRQs disabled");
   1263 
   1264 	if (list_empty(&req->list))
   1265 		return 0;
   1266 
   1267 	if (i915_gem_request_completed(req, true))
   1268 		return 0;
   1269 
   1270 	timeout_expire = 0;
   1271 	if (timeout) {
   1272 		if (WARN_ON(*timeout < 0))
   1273 			return -EINVAL;
   1274 
   1275 		if (*timeout == 0)
   1276 			return -ETIME;
   1277 
   1278 		timeout_expire = jiffies + nsecs_to_jiffies_timeout(*timeout);
   1279 	}
   1280 
   1281 	if (INTEL_INFO(dev_priv)->gen >= 6)
   1282 		gen6_rps_boost(dev_priv, rps, req->emitted_jiffies);
   1283 
   1284 	/* Record current time in case interrupted by signal, or wedged */
   1285 	trace_i915_gem_request_wait_begin(req);
   1286 	before = ktime_get_raw_ns();
   1287 
   1288 	/* Optimistic spin for the next jiffie before touching IRQs */
   1289 	ret = __i915_spin_request(req, state);
   1290 	if (ret == 0)
   1291 		goto out;
   1292 
   1293 	if (!irq_test_in_progress && WARN_ON(!ring->irq_get(ring))) {
   1294 		ret = -ENODEV;
   1295 		goto out;
   1296 	}
   1297 
   1298 	for (;;) {
   1299 		struct timer_list timer;
   1300 
   1301 		prepare_to_wait(&ring->irq_queue, &wait, state);
   1302 
   1303 		/* We need to check whether any gpu reset happened in between
   1304 		 * the caller grabbing the seqno and now ... */
   1305 		if (reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter)) {
   1306 			/* ... but upgrade the -EAGAIN to an -EIO if the gpu
   1307 			 * is truely gone. */
   1308 			ret = i915_gem_check_wedge(&dev_priv->gpu_error, interruptible);
   1309 			if (ret == 0)
   1310 				ret = -EAGAIN;
   1311 			break;
   1312 		}
   1313 
   1314 		if (i915_gem_request_completed(req, false)) {
   1315 			ret = 0;
   1316 			break;
   1317 		}
   1318 
   1319 		if (signal_pending_state(state, current)) {
   1320 			ret = -ERESTARTSYS;
   1321 			break;
   1322 		}
   1323 
   1324 		if (timeout && time_after_eq(jiffies, timeout_expire)) {
   1325 			ret = -ETIME;
   1326 			break;
   1327 		}
   1328 
   1329 		timer.function = NULL;
   1330 		if (timeout || missed_irq(dev_priv, ring)) {
   1331 			unsigned long expire;
   1332 
   1333 			setup_timer_on_stack(&timer, fake_irq, (unsigned long)current);
   1334 			expire = missed_irq(dev_priv, ring) ? jiffies + 1 : timeout_expire;
   1335 			mod_timer(&timer, expire);
   1336 		}
   1337 
   1338 		io_schedule();
   1339 
   1340 		if (timer.function) {
   1341 			del_singleshot_timer_sync(&timer);
   1342 			destroy_timer_on_stack(&timer);
   1343 		}
   1344 	}
   1345 	if (!irq_test_in_progress)
   1346 		ring->irq_put(ring);
   1347 
   1348 	finish_wait(&ring->irq_queue, &wait);
   1349 
   1350 out:
   1351 	now = ktime_get_raw_ns();
   1352 	trace_i915_gem_request_wait_end(req);
   1353 
   1354 	if (timeout) {
   1355 		s64 tres = *timeout - (now - before);
   1356 
   1357 		*timeout = tres < 0 ? 0 : tres;
   1358 
   1359 		/*
   1360 		 * Apparently ktime isn't accurate enough and occasionally has a
   1361 		 * bit of mismatch in the jiffies<->nsecs<->ktime loop. So patch
   1362 		 * things up to make the test happy. We allow up to 1 jiffy.
   1363 		 *
   1364 		 * This is a regrssion from the timespec->ktime conversion.
   1365 		 */
   1366 		if (ret == -ETIME && *timeout < jiffies_to_usecs(1)*1000)
   1367 			*timeout = 0;
   1368 	}
   1369 
   1370 	return ret;
   1371 }
   1372 
   1373 int i915_gem_request_add_to_client(struct drm_i915_gem_request *req,
   1374 				   struct drm_file *file)
   1375 {
   1376 	struct drm_i915_private *dev_private;
   1377 	struct drm_i915_file_private *file_priv;
   1378 
   1379 	WARN_ON(!req || !file || req->file_priv);
   1380 
   1381 	if (!req || !file)
   1382 		return -EINVAL;
   1383 
   1384 	if (req->file_priv)
   1385 		return -EINVAL;
   1386 
   1387 	dev_private = req->ring->dev->dev_private;
   1388 	file_priv = file->driver_priv;
   1389 
   1390 	spin_lock(&file_priv->mm.lock);
   1391 	req->file_priv = file_priv;
   1392 	list_add_tail(&req->client_list, &file_priv->mm.request_list);
   1393 	spin_unlock(&file_priv->mm.lock);
   1394 
   1395 	req->pid = get_pid(task_pid(current));
   1396 
   1397 	return 0;
   1398 }
   1399 
   1400 static inline void
   1401 i915_gem_request_remove_from_client(struct drm_i915_gem_request *request)
   1402 {
   1403 	struct drm_i915_file_private *file_priv = request->file_priv;
   1404 
   1405 	if (!file_priv)
   1406 		return;
   1407 
   1408 	spin_lock(&file_priv->mm.lock);
   1409 	list_del(&request->client_list);
   1410 	request->file_priv = NULL;
   1411 	spin_unlock(&file_priv->mm.lock);
   1412 
   1413 	put_pid(request->pid);
   1414 	request->pid = NULL;
   1415 }
   1416 
   1417 static void i915_gem_request_retire(struct drm_i915_gem_request *request)
   1418 {
   1419 	trace_i915_gem_request_retire(request);
   1420 
   1421 	/* We know the GPU must have read the request to have
   1422 	 * sent us the seqno + interrupt, so use the position
   1423 	 * of tail of the request to update the last known position
   1424 	 * of the GPU head.
   1425 	 *
   1426 	 * Note this requires that we are always called in request
   1427 	 * completion order.
   1428 	 */
   1429 	request->ringbuf->last_retired_head = request->postfix;
   1430 
   1431 	list_del_init(&request->list);
   1432 	i915_gem_request_remove_from_client(request);
   1433 
   1434 	i915_gem_request_unreference(request);
   1435 }
   1436 
   1437 static void
   1438 __i915_gem_request_retire__upto(struct drm_i915_gem_request *req)
   1439 {
   1440 	struct intel_engine_cs *engine = req->ring;
   1441 	struct drm_i915_gem_request *tmp;
   1442 
   1443 	lockdep_assert_held(&engine->dev->struct_mutex);
   1444 
   1445 	if (list_empty(&req->list))
   1446 		return;
   1447 
   1448 	do {
   1449 		tmp = list_first_entry(&engine->request_list,
   1450 				       typeof(*tmp), list);
   1451 
   1452 		i915_gem_request_retire(tmp);
   1453 	} while (tmp != req);
   1454 
   1455 	WARN_ON(i915_verify_lists(engine->dev));
   1456 }
   1457 
   1458 /**
   1459  * Waits for a request to be signaled, and cleans up the
   1460  * request and object lists appropriately for that event.
   1461  */
   1462 int
   1463 i915_wait_request(struct drm_i915_gem_request *req)
   1464 {
   1465 	struct drm_device *dev;
   1466 	struct drm_i915_private *dev_priv;
   1467 	bool interruptible;
   1468 	int ret;
   1469 
   1470 	BUG_ON(req == NULL);
   1471 
   1472 	dev = req->ring->dev;
   1473 	dev_priv = dev->dev_private;
   1474 	interruptible = dev_priv->mm.interruptible;
   1475 
   1476 	BUG_ON(!mutex_is_locked(&dev->struct_mutex));
   1477 
   1478 	ret = i915_gem_check_wedge(&dev_priv->gpu_error, interruptible);
   1479 	if (ret)
   1480 		return ret;
   1481 
   1482 	ret = __i915_wait_request(req,
   1483 				  atomic_read(&dev_priv->gpu_error.reset_counter),
   1484 				  interruptible, NULL, NULL);
   1485 	if (ret)
   1486 		return ret;
   1487 
   1488 	__i915_gem_request_retire__upto(req);
   1489 	return 0;
   1490 }
   1491 
   1492 /**
   1493  * Ensures that all rendering to the object has completed and the object is
   1494  * safe to unbind from the GTT or access from the CPU.
   1495  */
   1496 int
   1497 i915_gem_object_wait_rendering(struct drm_i915_gem_object *obj,
   1498 			       bool readonly)
   1499 {
   1500 	int ret, i;
   1501 
   1502 	if (!obj->active)
   1503 		return 0;
   1504 
   1505 	if (readonly) {
   1506 		if (obj->last_write_req != NULL) {
   1507 			ret = i915_wait_request(obj->last_write_req);
   1508 			if (ret)
   1509 				return ret;
   1510 
   1511 			i = obj->last_write_req->ring->id;
   1512 			if (obj->last_read_req[i] == obj->last_write_req)
   1513 				i915_gem_object_retire__read(obj, i);
   1514 			else
   1515 				i915_gem_object_retire__write(obj);
   1516 		}
   1517 	} else {
   1518 		for (i = 0; i < I915_NUM_RINGS; i++) {
   1519 			if (obj->last_read_req[i] == NULL)
   1520 				continue;
   1521 
   1522 			ret = i915_wait_request(obj->last_read_req[i]);
   1523 			if (ret)
   1524 				return ret;
   1525 
   1526 			i915_gem_object_retire__read(obj, i);
   1527 		}
   1528 		RQ_BUG_ON(obj->active);
   1529 	}
   1530 
   1531 	return 0;
   1532 }
   1533 
   1534 static void
   1535 i915_gem_object_retire_request(struct drm_i915_gem_object *obj,
   1536 			       struct drm_i915_gem_request *req)
   1537 {
   1538 	int ring = req->ring->id;
   1539 
   1540 	if (obj->last_read_req[ring] == req)
   1541 		i915_gem_object_retire__read(obj, ring);
   1542 	else if (obj->last_write_req == req)
   1543 		i915_gem_object_retire__write(obj);
   1544 
   1545 	__i915_gem_request_retire__upto(req);
   1546 }
   1547 
   1548 /* A nonblocking variant of the above wait. This is a highly dangerous routine
   1549  * as the object state may change during this call.
   1550  */
   1551 static __must_check int
   1552 i915_gem_object_wait_rendering__nonblocking(struct drm_i915_gem_object *obj,
   1553 					    struct intel_rps_client *rps,
   1554 					    bool readonly)
   1555 {
   1556 	struct drm_device *dev = obj->base.dev;
   1557 	struct drm_i915_private *dev_priv = dev->dev_private;
   1558 	struct drm_i915_gem_request *requests[I915_NUM_RINGS];
   1559 	unsigned reset_counter;
   1560 	int ret, i, n = 0;
   1561 
   1562 	BUG_ON(!mutex_is_locked(&dev->struct_mutex));
   1563 	BUG_ON(!dev_priv->mm.interruptible);
   1564 
   1565 	if (!obj->active)
   1566 		return 0;
   1567 
   1568 	ret = i915_gem_check_wedge(&dev_priv->gpu_error, true);
   1569 	if (ret)
   1570 		return ret;
   1571 
   1572 	reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
   1573 
   1574 	if (readonly) {
   1575 		struct drm_i915_gem_request *req;
   1576 
   1577 		req = obj->last_write_req;
   1578 		if (req == NULL)
   1579 			return 0;
   1580 
   1581 		requests[n++] = i915_gem_request_reference(req);
   1582 	} else {
   1583 		for (i = 0; i < I915_NUM_RINGS; i++) {
   1584 			struct drm_i915_gem_request *req;
   1585 
   1586 			req = obj->last_read_req[i];
   1587 			if (req == NULL)
   1588 				continue;
   1589 
   1590 			requests[n++] = i915_gem_request_reference(req);
   1591 		}
   1592 	}
   1593 
   1594 	mutex_unlock(&dev->struct_mutex);
   1595 	for (i = 0; ret == 0 && i < n; i++)
   1596 		ret = __i915_wait_request(requests[i], reset_counter, true,
   1597 					  NULL, rps);
   1598 	mutex_lock(&dev->struct_mutex);
   1599 
   1600 	for (i = 0; i < n; i++) {
   1601 		if (ret == 0)
   1602 			i915_gem_object_retire_request(obj, requests[i]);
   1603 		i915_gem_request_unreference(requests[i]);
   1604 	}
   1605 
   1606 	return ret;
   1607 }
   1608 
   1609 static struct intel_rps_client *to_rps_client(struct drm_file *file)
   1610 {
   1611 	struct drm_i915_file_private *fpriv = file->driver_priv;
   1612 	return &fpriv->rps;
   1613 }
   1614 
   1615 /**
   1616  * Called when user space prepares to use an object with the CPU, either
   1617  * through the mmap ioctl's mapping or a GTT mapping.
   1618  */
   1619 int
   1620 i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
   1621 			  struct drm_file *file)
   1622 {
   1623 	struct drm_i915_gem_set_domain *args = data;
   1624 	struct drm_i915_gem_object *obj;
   1625 	uint32_t read_domains = args->read_domains;
   1626 	uint32_t write_domain = args->write_domain;
   1627 	int ret;
   1628 
   1629 	/* Only handle setting domains to types used by the CPU. */
   1630 	if (write_domain & I915_GEM_GPU_DOMAINS)
   1631 		return -EINVAL;
   1632 
   1633 	if (read_domains & I915_GEM_GPU_DOMAINS)
   1634 		return -EINVAL;
   1635 
   1636 	/* Having something in the write domain implies it's in the read
   1637 	 * domain, and only that read domain.  Enforce that in the request.
   1638 	 */
   1639 	if (write_domain != 0 && read_domains != write_domain)
   1640 		return -EINVAL;
   1641 
   1642 	ret = i915_mutex_lock_interruptible(dev);
   1643 	if (ret)
   1644 		return ret;
   1645 
   1646 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
   1647 	if (&obj->base == NULL) {
   1648 		ret = -ENOENT;
   1649 		goto unlock;
   1650 	}
   1651 
   1652 	/* Try to flush the object off the GPU without holding the lock.
   1653 	 * We will repeat the flush holding the lock in the normal manner
   1654 	 * to catch cases where we are gazumped.
   1655 	 */
   1656 	ret = i915_gem_object_wait_rendering__nonblocking(obj,
   1657 							  to_rps_client(file),
   1658 							  !write_domain);
   1659 	if (ret)
   1660 		goto unref;
   1661 
   1662 	if (read_domains & I915_GEM_DOMAIN_GTT)
   1663 		ret = i915_gem_object_set_to_gtt_domain(obj, write_domain != 0);
   1664 	else
   1665 		ret = i915_gem_object_set_to_cpu_domain(obj, write_domain != 0);
   1666 
   1667 	if (write_domain != 0)
   1668 		intel_fb_obj_invalidate(obj,
   1669 					write_domain == I915_GEM_DOMAIN_GTT ?
   1670 					ORIGIN_GTT : ORIGIN_CPU);
   1671 
   1672 unref:
   1673 	drm_gem_object_unreference(&obj->base);
   1674 unlock:
   1675 	mutex_unlock(&dev->struct_mutex);
   1676 	return ret;
   1677 }
   1678 
   1679 /**
   1680  * Called when user space has done writes to this buffer
   1681  */
   1682 int
   1683 i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
   1684 			 struct drm_file *file)
   1685 {
   1686 	struct drm_i915_gem_sw_finish *args = data;
   1687 	struct drm_i915_gem_object *obj;
   1688 	int ret = 0;
   1689 
   1690 	ret = i915_mutex_lock_interruptible(dev);
   1691 	if (ret)
   1692 		return ret;
   1693 
   1694 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
   1695 	if (&obj->base == NULL) {
   1696 		ret = -ENOENT;
   1697 		goto unlock;
   1698 	}
   1699 
   1700 	/* Pinned buffers may be scanout, so flush the cache */
   1701 	if (obj->pin_display)
   1702 		i915_gem_object_flush_cpu_write_domain(obj);
   1703 
   1704 	drm_gem_object_unreference(&obj->base);
   1705 unlock:
   1706 	mutex_unlock(&dev->struct_mutex);
   1707 	return ret;
   1708 }
   1709 
   1710 /**
   1711  * Maps the contents of an object, returning the address it is mapped
   1712  * into.
   1713  *
   1714  * While the mapping holds a reference on the contents of the object, it doesn't
   1715  * imply a ref on the object itself.
   1716  *
   1717  * IMPORTANT:
   1718  *
   1719  * DRM driver writers who look a this function as an example for how to do GEM
   1720  * mmap support, please don't implement mmap support like here. The modern way
   1721  * to implement DRM mmap support is with an mmap offset ioctl (like
   1722  * i915_gem_mmap_gtt) and then using the mmap syscall on the DRM fd directly.
   1723  * That way debug tooling like valgrind will understand what's going on, hiding
   1724  * the mmap call in a driver private ioctl will break that. The i915 driver only
   1725  * does cpu mmaps this way because we didn't know better.
   1726  */
   1727 int
   1728 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
   1729 		    struct drm_file *file)
   1730 {
   1731 	struct drm_i915_gem_mmap *args = data;
   1732 	struct drm_gem_object *obj;
   1733 	unsigned long addr;
   1734 
   1735 	if (args->flags & ~(I915_MMAP_WC))
   1736 		return -EINVAL;
   1737 
   1738 	if (args->flags & I915_MMAP_WC && !cpu_has_pat)
   1739 		return -ENODEV;
   1740 
   1741 	obj = drm_gem_object_lookup(dev, file, args->handle);
   1742 	if (obj == NULL)
   1743 		return -ENOENT;
   1744 
   1745 	/* prime objects have no backing filp to GEM mmap
   1746 	 * pages from.
   1747 	 */
   1748 	if (!obj->filp) {
   1749 		drm_gem_object_unreference_unlocked(obj);
   1750 		return -EINVAL;
   1751 	}
   1752 
   1753 	addr = vm_mmap(obj->filp, 0, args->size,
   1754 		       PROT_READ | PROT_WRITE, MAP_SHARED,
   1755 		       args->offset);
   1756 	if (args->flags & I915_MMAP_WC) {
   1757 		struct mm_struct *mm = current->mm;
   1758 		struct vm_area_struct *vma;
   1759 
   1760 		down_write(&mm->mmap_sem);
   1761 		vma = find_vma(mm, addr);
   1762 		if (vma)
   1763 			vma->vm_page_prot =
   1764 				pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
   1765 		else
   1766 			addr = -ENOMEM;
   1767 		up_write(&mm->mmap_sem);
   1768 	}
   1769 	drm_gem_object_unreference_unlocked(obj);
   1770 	if (IS_ERR((void *)addr))
   1771 		return addr;
   1772 
   1773 	args->addr_ptr = (uint64_t) addr;
   1774 
   1775 	return 0;
   1776 }
   1777 
   1778 /**
   1779  * i915_gem_fault - fault a page into the GTT
   1780  * @vma: VMA in question
   1781  * @vmf: fault info
   1782  *
   1783  * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
   1784  * from userspace.  The fault handler takes care of binding the object to
   1785  * the GTT (if needed), allocating and programming a fence register (again,
   1786  * only if needed based on whether the old reg is still valid or the object
   1787  * is tiled) and inserting a new PTE into the faulting process.
   1788  *
   1789  * Note that the faulting process may involve evicting existing objects
   1790  * from the GTT and/or fence registers to make room.  So performance may
   1791  * suffer if the GTT working set is large or there are few fence registers
   1792  * left.
   1793  */
   1794 int i915_gem_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
   1795 {
   1796 	struct drm_i915_gem_object *obj = to_intel_bo(vma->vm_private_data);
   1797 	struct drm_device *dev = obj->base.dev;
   1798 	struct drm_i915_private *dev_priv = dev->dev_private;
   1799 	struct i915_ggtt_view view = i915_ggtt_view_normal;
   1800 	pgoff_t page_offset;
   1801 	unsigned long pfn;
   1802 	int ret = 0;
   1803 	bool write = !!(vmf->flags & FAULT_FLAG_WRITE);
   1804 
   1805 	intel_runtime_pm_get(dev_priv);
   1806 
   1807 	/* We don't use vmf->pgoff since that has the fake offset */
   1808 	page_offset = ((unsigned long)vmf->virtual_address - vma->vm_start) >>
   1809 		PAGE_SHIFT;
   1810 
   1811 	ret = i915_mutex_lock_interruptible(dev);
   1812 	if (ret)
   1813 		goto out;
   1814 
   1815 	trace_i915_gem_object_fault(obj, page_offset, true, write);
   1816 
   1817 	/* Try to flush the object off the GPU first without holding the lock.
   1818 	 * Upon reacquiring the lock, we will perform our sanity checks and then
   1819 	 * repeat the flush holding the lock in the normal manner to catch cases
   1820 	 * where we are gazumped.
   1821 	 */
   1822 	ret = i915_gem_object_wait_rendering__nonblocking(obj, NULL, !write);
   1823 	if (ret)
   1824 		goto unlock;
   1825 
   1826 	/* Access to snoopable pages through the GTT is incoherent. */
   1827 	if (obj->cache_level != I915_CACHE_NONE && !HAS_LLC(dev)) {
   1828 		ret = -EFAULT;
   1829 		goto unlock;
   1830 	}
   1831 
   1832 	/* Use a partial view if the object is bigger than the aperture. */
   1833 	if (obj->base.size >= dev_priv->gtt.mappable_end &&
   1834 	    obj->tiling_mode == I915_TILING_NONE) {
   1835 		static const unsigned int chunk_size = 256; // 1 MiB
   1836 
   1837 		memset(&view, 0, sizeof(view));
   1838 		view.type = I915_GGTT_VIEW_PARTIAL;
   1839 		view.params.partial.offset = rounddown(page_offset, chunk_size);
   1840 		view.params.partial.size =
   1841 			min_t(unsigned int,
   1842 			      chunk_size,
   1843 			      (vma->vm_end - vma->vm_start)/PAGE_SIZE -
   1844 			      view.params.partial.offset);
   1845 	}
   1846 
   1847 	/* Now pin it into the GTT if needed */
   1848 	ret = i915_gem_object_ggtt_pin(obj, &view, 0, PIN_MAPPABLE);
   1849 	if (ret)
   1850 		goto unlock;
   1851 
   1852 	ret = i915_gem_object_set_to_gtt_domain(obj, write);
   1853 	if (ret)
   1854 		goto unpin;
   1855 
   1856 	ret = i915_gem_object_get_fence(obj);
   1857 	if (ret)
   1858 		goto unpin;
   1859 
   1860 	/* Finally, remap it using the new GTT offset */
   1861 	pfn = dev_priv->gtt.mappable_base +
   1862 		i915_gem_obj_ggtt_offset_view(obj, &view);
   1863 	pfn >>= PAGE_SHIFT;
   1864 
   1865 	if (unlikely(view.type == I915_GGTT_VIEW_PARTIAL)) {
   1866 		/* Overriding existing pages in partial view does not cause
   1867 		 * us any trouble as TLBs are still valid because the fault
   1868 		 * is due to userspace losing part of the mapping or never
   1869 		 * having accessed it before (at this partials' range).
   1870 		 */
   1871 		unsigned long base = vma->vm_start +
   1872 				     (view.params.partial.offset << PAGE_SHIFT);
   1873 		unsigned int i;
   1874 
   1875 		for (i = 0; i < view.params.partial.size; i++) {
   1876 			ret = vm_insert_pfn(vma, base + i * PAGE_SIZE, pfn + i);
   1877 			if (ret)
   1878 				break;
   1879 		}
   1880 
   1881 		obj->fault_mappable = true;
   1882 	} else {
   1883 		if (!obj->fault_mappable) {
   1884 			unsigned long size = min_t(unsigned long,
   1885 						   vma->vm_end - vma->vm_start,
   1886 						   obj->base.size);
   1887 			int i;
   1888 
   1889 			for (i = 0; i < size >> PAGE_SHIFT; i++) {
   1890 				ret = vm_insert_pfn(vma,
   1891 						    (unsigned long)vma->vm_start + i * PAGE_SIZE,
   1892 						    pfn + i);
   1893 				if (ret)
   1894 					break;
   1895 			}
   1896 
   1897 			obj->fault_mappable = true;
   1898 		} else
   1899 			ret = vm_insert_pfn(vma,
   1900 					    (unsigned long)vmf->virtual_address,
   1901 					    pfn + page_offset);
   1902 	}
   1903 unpin:
   1904 	i915_gem_object_ggtt_unpin_view(obj, &view);
   1905 unlock:
   1906 	mutex_unlock(&dev->struct_mutex);
   1907 out:
   1908 	switch (ret) {
   1909 	case -EIO:
   1910 		/*
   1911 		 * We eat errors when the gpu is terminally wedged to avoid
   1912 		 * userspace unduly crashing (gl has no provisions for mmaps to
   1913 		 * fail). But any other -EIO isn't ours (e.g. swap in failure)
   1914 		 * and so needs to be reported.
   1915 		 */
   1916 		if (!i915_terminally_wedged(&dev_priv->gpu_error)) {
   1917 			ret = VM_FAULT_SIGBUS;
   1918 			break;
   1919 		}
   1920 	case -EAGAIN:
   1921 		/*
   1922 		 * EAGAIN means the gpu is hung and we'll wait for the error
   1923 		 * handler to reset everything when re-faulting in
   1924 		 * i915_mutex_lock_interruptible.
   1925 		 */
   1926 	case 0:
   1927 	case -ERESTARTSYS:
   1928 	case -EINTR:
   1929 	case -EBUSY:
   1930 		/*
   1931 		 * EBUSY is ok: this just means that another thread
   1932 		 * already did the job.
   1933 		 */
   1934 		ret = VM_FAULT_NOPAGE;
   1935 		break;
   1936 	case -ENOMEM:
   1937 		ret = VM_FAULT_OOM;
   1938 		break;
   1939 	case -ENOSPC:
   1940 	case -EFAULT:
   1941 		ret = VM_FAULT_SIGBUS;
   1942 		break;
   1943 	default:
   1944 		WARN_ONCE(ret, "unhandled error in i915_gem_fault: %i\n", ret);
   1945 		ret = VM_FAULT_SIGBUS;
   1946 		break;
   1947 	}
   1948 
   1949 	intel_runtime_pm_put(dev_priv);
   1950 	return ret;
   1951 }
   1952 
   1953 /**
   1954  * i915_gem_release_mmap - remove physical page mappings
   1955  * @obj: obj in question
   1956  *
   1957  * Preserve the reservation of the mmapping with the DRM core code, but
   1958  * relinquish ownership of the pages back to the system.
   1959  *
   1960  * It is vital that we remove the page mapping if we have mapped a tiled
   1961  * object through the GTT and then lose the fence register due to
   1962  * resource pressure. Similarly if the object has been moved out of the
   1963  * aperture, than pages mapped into userspace must be revoked. Removing the
   1964  * mapping will then trigger a page fault on the next user access, allowing
   1965  * fixup by i915_gem_fault().
   1966  */
   1967 void
   1968 i915_gem_release_mmap(struct drm_i915_gem_object *obj)
   1969 {
   1970 	if (!obj->fault_mappable)
   1971 		return;
   1972 
   1973 	drm_vma_node_unmap(&obj->base.vma_node,
   1974 			   obj->base.dev->anon_inode->i_mapping);
   1975 	obj->fault_mappable = false;
   1976 }
   1977 
   1978 void
   1979 i915_gem_release_all_mmaps(struct drm_i915_private *dev_priv)
   1980 {
   1981 	struct drm_i915_gem_object *obj;
   1982 
   1983 	list_for_each_entry(obj, &dev_priv->mm.bound_list, global_list)
   1984 		i915_gem_release_mmap(obj);
   1985 }
   1986 
   1987 uint32_t
   1988 i915_gem_get_gtt_size(struct drm_device *dev, uint32_t size, int tiling_mode)
   1989 {
   1990 	uint32_t gtt_size;
   1991 
   1992 	if (INTEL_INFO(dev)->gen >= 4 ||
   1993 	    tiling_mode == I915_TILING_NONE)
   1994 		return size;
   1995 
   1996 	/* Previous chips need a power-of-two fence region when tiling */
   1997 	if (INTEL_INFO(dev)->gen == 3)
   1998 		gtt_size = 1024*1024;
   1999 	else
   2000 		gtt_size = 512*1024;
   2001 
   2002 	while (gtt_size < size)
   2003 		gtt_size <<= 1;
   2004 
   2005 	return gtt_size;
   2006 }
   2007 
   2008 /**
   2009  * i915_gem_get_gtt_alignment - return required GTT alignment for an object
   2010  * @obj: object to check
   2011  *
   2012  * Return the required GTT alignment for an object, taking into account
   2013  * potential fence register mapping.
   2014  */
   2015 uint32_t
   2016 i915_gem_get_gtt_alignment(struct drm_device *dev, uint32_t size,
   2017 			   int tiling_mode, bool fenced)
   2018 {
   2019 	/*
   2020 	 * Minimum alignment is 4k (GTT page size), but might be greater
   2021 	 * if a fence register is needed for the object.
   2022 	 */
   2023 	if (INTEL_INFO(dev)->gen >= 4 || (!fenced && IS_G33(dev)) ||
   2024 	    tiling_mode == I915_TILING_NONE)
   2025 		return 4096;
   2026 
   2027 	/*
   2028 	 * Previous chips need to be aligned to the size of the smallest
   2029 	 * fence register that can contain the object.
   2030 	 */
   2031 	return i915_gem_get_gtt_size(dev, size, tiling_mode);
   2032 }
   2033 
   2034 static int i915_gem_object_create_mmap_offset(struct drm_i915_gem_object *obj)
   2035 {
   2036 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   2037 	int ret;
   2038 
   2039 	if (drm_vma_node_has_offset(&obj->base.vma_node))
   2040 		return 0;
   2041 
   2042 	dev_priv->mm.shrinker_no_lock_stealing = true;
   2043 
   2044 	ret = drm_gem_create_mmap_offset(&obj->base);
   2045 	if (ret != -ENOSPC)
   2046 		goto out;
   2047 
   2048 	/* Badly fragmented mmap space? The only way we can recover
   2049 	 * space is by destroying unwanted objects. We can't randomly release
   2050 	 * mmap_offsets as userspace expects them to be persistent for the
   2051 	 * lifetime of the objects. The closest we can is to release the
   2052 	 * offsets on purgeable objects by truncating it and marking it purged,
   2053 	 * which prevents userspace from ever using that object again.
   2054 	 */
   2055 	i915_gem_shrink(dev_priv,
   2056 			obj->base.size >> PAGE_SHIFT,
   2057 			I915_SHRINK_BOUND |
   2058 			I915_SHRINK_UNBOUND |
   2059 			I915_SHRINK_PURGEABLE);
   2060 	ret = drm_gem_create_mmap_offset(&obj->base);
   2061 	if (ret != -ENOSPC)
   2062 		goto out;
   2063 
   2064 	i915_gem_shrink_all(dev_priv);
   2065 	ret = drm_gem_create_mmap_offset(&obj->base);
   2066 out:
   2067 	dev_priv->mm.shrinker_no_lock_stealing = false;
   2068 
   2069 	return ret;
   2070 }
   2071 
   2072 static void i915_gem_object_free_mmap_offset(struct drm_i915_gem_object *obj)
   2073 {
   2074 	drm_gem_free_mmap_offset(&obj->base);
   2075 }
   2076 
   2077 int
   2078 i915_gem_mmap_gtt(struct drm_file *file,
   2079 		  struct drm_device *dev,
   2080 		  uint32_t handle,
   2081 		  uint64_t *offset)
   2082 {
   2083 	struct drm_i915_gem_object *obj;
   2084 	int ret;
   2085 
   2086 	ret = i915_mutex_lock_interruptible(dev);
   2087 	if (ret)
   2088 		return ret;
   2089 
   2090 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, handle));
   2091 	if (&obj->base == NULL) {
   2092 		ret = -ENOENT;
   2093 		goto unlock;
   2094 	}
   2095 
   2096 	if (obj->madv != I915_MADV_WILLNEED) {
   2097 		DRM_DEBUG("Attempting to mmap a purgeable buffer\n");
   2098 		ret = -EFAULT;
   2099 		goto out;
   2100 	}
   2101 
   2102 	ret = i915_gem_object_create_mmap_offset(obj);
   2103 	if (ret)
   2104 		goto out;
   2105 
   2106 	*offset = drm_vma_node_offset_addr(&obj->base.vma_node);
   2107 
   2108 out:
   2109 	drm_gem_object_unreference(&obj->base);
   2110 unlock:
   2111 	mutex_unlock(&dev->struct_mutex);
   2112 	return ret;
   2113 }
   2114 
   2115 /**
   2116  * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
   2117  * @dev: DRM device
   2118  * @data: GTT mapping ioctl data
   2119  * @file: GEM object info
   2120  *
   2121  * Simply returns the fake offset to userspace so it can mmap it.
   2122  * The mmap call will end up in drm_gem_mmap(), which will set things
   2123  * up so we can get faults in the handler above.
   2124  *
   2125  * The fault handler will take care of binding the object into the GTT
   2126  * (since it may have been evicted to make room for something), allocating
   2127  * a fence register, and mapping the appropriate aperture address into
   2128  * userspace.
   2129  */
   2130 int
   2131 i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
   2132 			struct drm_file *file)
   2133 {
   2134 	struct drm_i915_gem_mmap_gtt *args = data;
   2135 
   2136 	return i915_gem_mmap_gtt(file, dev, args->handle, &args->offset);
   2137 }
   2138 
   2139 /* Immediately discard the backing storage */
   2140 static void
   2141 i915_gem_object_truncate(struct drm_i915_gem_object *obj)
   2142 {
   2143 	i915_gem_object_free_mmap_offset(obj);
   2144 
   2145 	if (obj->base.filp == NULL)
   2146 		return;
   2147 
   2148 	/* Our goal here is to return as much of the memory as
   2149 	 * is possible back to the system as we are called from OOM.
   2150 	 * To do this we must instruct the shmfs to drop all of its
   2151 	 * backing pages, *now*.
   2152 	 */
   2153 	shmem_truncate_range(file_inode(obj->base.filp), 0, (loff_t)-1);
   2154 	obj->madv = __I915_MADV_PURGED;
   2155 }
   2156 
   2157 /* Try to discard unwanted pages */
   2158 static void
   2159 i915_gem_object_invalidate(struct drm_i915_gem_object *obj)
   2160 {
   2161 	struct address_space *mapping;
   2162 
   2163 	switch (obj->madv) {
   2164 	case I915_MADV_DONTNEED:
   2165 		i915_gem_object_truncate(obj);
   2166 	case __I915_MADV_PURGED:
   2167 		return;
   2168 	}
   2169 
   2170 	if (obj->base.filp == NULL)
   2171 		return;
   2172 
   2173 	mapping = file_inode(obj->base.filp)->i_mapping,
   2174 	invalidate_mapping_pages(mapping, 0, (loff_t)-1);
   2175 }
   2176 
   2177 static void
   2178 i915_gem_object_put_pages_gtt(struct drm_i915_gem_object *obj)
   2179 {
   2180 	struct sg_page_iter sg_iter;
   2181 	int ret;
   2182 
   2183 	BUG_ON(obj->madv == __I915_MADV_PURGED);
   2184 
   2185 	ret = i915_gem_object_set_to_cpu_domain(obj, true);
   2186 	if (ret) {
   2187 		/* In the event of a disaster, abandon all caches and
   2188 		 * hope for the best.
   2189 		 */
   2190 		WARN_ON(ret != -EIO);
   2191 		i915_gem_clflush_object(obj, true);
   2192 		obj->base.read_domains = obj->base.write_domain = I915_GEM_DOMAIN_CPU;
   2193 	}
   2194 
   2195 	i915_gem_gtt_finish_object(obj);
   2196 
   2197 	if (i915_gem_object_needs_bit17_swizzle(obj))
   2198 		i915_gem_object_save_bit_17_swizzle(obj);
   2199 
   2200 	if (obj->madv == I915_MADV_DONTNEED)
   2201 		obj->dirty = 0;
   2202 
   2203 	for_each_sg_page(obj->pages->sgl, &sg_iter, obj->pages->nents, 0) {
   2204 		struct page *page = sg_page_iter_page(&sg_iter);
   2205 
   2206 		if (obj->dirty)
   2207 			set_page_dirty(page);
   2208 
   2209 		if (obj->madv == I915_MADV_WILLNEED)
   2210 			mark_page_accessed(page);
   2211 
   2212 		page_cache_release(page);
   2213 	}
   2214 	obj->dirty = 0;
   2215 
   2216 	sg_free_table(obj->pages);
   2217 	kfree(obj->pages);
   2218 }
   2219 
   2220 int
   2221 i915_gem_object_put_pages(struct drm_i915_gem_object *obj)
   2222 {
   2223 	const struct drm_i915_gem_object_ops *ops = obj->ops;
   2224 
   2225 	if (obj->pages == NULL)
   2226 		return 0;
   2227 
   2228 	if (obj->pages_pin_count)
   2229 		return -EBUSY;
   2230 
   2231 	BUG_ON(i915_gem_obj_bound_any(obj));
   2232 
   2233 	/* ->put_pages might need to allocate memory for the bit17 swizzle
   2234 	 * array, hence protect them from being reaped by removing them from gtt
   2235 	 * lists early. */
   2236 	list_del(&obj->global_list);
   2237 
   2238 	ops->put_pages(obj);
   2239 	obj->pages = NULL;
   2240 
   2241 	i915_gem_object_invalidate(obj);
   2242 
   2243 	return 0;
   2244 }
   2245 
   2246 static int
   2247 i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj)
   2248 {
   2249 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   2250 	int page_count, i;
   2251 	struct address_space *mapping;
   2252 	struct sg_table *st;
   2253 	struct scatterlist *sg;
   2254 	struct sg_page_iter sg_iter;
   2255 	struct page *page;
   2256 	unsigned long last_pfn = 0;	/* suppress gcc warning */
   2257 	int ret;
   2258 	gfp_t gfp;
   2259 
   2260 	/* Assert that the object is not currently in any GPU domain. As it
   2261 	 * wasn't in the GTT, there shouldn't be any way it could have been in
   2262 	 * a GPU cache
   2263 	 */
   2264 	BUG_ON(obj->base.read_domains & I915_GEM_GPU_DOMAINS);
   2265 	BUG_ON(obj->base.write_domain & I915_GEM_GPU_DOMAINS);
   2266 
   2267 	st = kmalloc(sizeof(*st), GFP_KERNEL);
   2268 	if (st == NULL)
   2269 		return -ENOMEM;
   2270 
   2271 	page_count = obj->base.size / PAGE_SIZE;
   2272 	if (sg_alloc_table(st, page_count, GFP_KERNEL)) {
   2273 		kfree(st);
   2274 		return -ENOMEM;
   2275 	}
   2276 
   2277 	/* Get the list of pages out of our struct file.  They'll be pinned
   2278 	 * at this point until we release them.
   2279 	 *
   2280 	 * Fail silently without starting the shrinker
   2281 	 */
   2282 	mapping = file_inode(obj->base.filp)->i_mapping;
   2283 	gfp = mapping_gfp_constraint(mapping, ~(__GFP_IO | __GFP_RECLAIM));
   2284 	gfp |= __GFP_NORETRY | __GFP_NOWARN;
   2285 	sg = st->sgl;
   2286 	st->nents = 0;
   2287 	for (i = 0; i < page_count; i++) {
   2288 		page = shmem_read_mapping_page_gfp(mapping, i, gfp);
   2289 		if (IS_ERR(page)) {
   2290 			i915_gem_shrink(dev_priv,
   2291 					page_count,
   2292 					I915_SHRINK_BOUND |
   2293 					I915_SHRINK_UNBOUND |
   2294 					I915_SHRINK_PURGEABLE);
   2295 			page = shmem_read_mapping_page_gfp(mapping, i, gfp);
   2296 		}
   2297 		if (IS_ERR(page)) {
   2298 			/* We've tried hard to allocate the memory by reaping
   2299 			 * our own buffer, now let the real VM do its job and
   2300 			 * go down in flames if truly OOM.
   2301 			 */
   2302 			i915_gem_shrink_all(dev_priv);
   2303 			page = shmem_read_mapping_page(mapping, i);
   2304 			if (IS_ERR(page)) {
   2305 				ret = PTR_ERR(page);
   2306 				goto err_pages;
   2307 			}
   2308 		}
   2309 #ifdef CONFIG_SWIOTLB
   2310 		if (swiotlb_nr_tbl()) {
   2311 			st->nents++;
   2312 			sg_set_page(sg, page, PAGE_SIZE, 0);
   2313 			sg = sg_next(sg);
   2314 			continue;
   2315 		}
   2316 #endif
   2317 		if (!i || page_to_pfn(page) != last_pfn + 1) {
   2318 			if (i)
   2319 				sg = sg_next(sg);
   2320 			st->nents++;
   2321 			sg_set_page(sg, page, PAGE_SIZE, 0);
   2322 		} else {
   2323 			sg->length += PAGE_SIZE;
   2324 		}
   2325 		last_pfn = page_to_pfn(page);
   2326 
   2327 		/* Check that the i965g/gm workaround works. */
   2328 		WARN_ON((gfp & __GFP_DMA32) && (last_pfn >= 0x00100000UL));
   2329 	}
   2330 #ifdef CONFIG_SWIOTLB
   2331 	if (!swiotlb_nr_tbl())
   2332 #endif
   2333 		sg_mark_end(sg);
   2334 	obj->pages = st;
   2335 
   2336 	ret = i915_gem_gtt_prepare_object(obj);
   2337 	if (ret)
   2338 		goto err_pages;
   2339 
   2340 	if (i915_gem_object_needs_bit17_swizzle(obj))
   2341 		i915_gem_object_do_bit_17_swizzle(obj);
   2342 
   2343 	if (obj->tiling_mode != I915_TILING_NONE &&
   2344 	    dev_priv->quirks & QUIRK_PIN_SWIZZLED_PAGES)
   2345 		i915_gem_object_pin_pages(obj);
   2346 
   2347 	return 0;
   2348 
   2349 err_pages:
   2350 	sg_mark_end(sg);
   2351 	for_each_sg_page(st->sgl, &sg_iter, st->nents, 0)
   2352 		page_cache_release(sg_page_iter_page(&sg_iter));
   2353 	sg_free_table(st);
   2354 	kfree(st);
   2355 
   2356 	/* shmemfs first checks if there is enough memory to allocate the page
   2357 	 * and reports ENOSPC should there be insufficient, along with the usual
   2358 	 * ENOMEM for a genuine allocation failure.
   2359 	 *
   2360 	 * We use ENOSPC in our driver to mean that we have run out of aperture
   2361 	 * space and so want to translate the error from shmemfs back to our
   2362 	 * usual understanding of ENOMEM.
   2363 	 */
   2364 	if (ret == -ENOSPC)
   2365 		ret = -ENOMEM;
   2366 
   2367 	return ret;
   2368 }
   2369 
   2370 /* Ensure that the associated pages are gathered from the backing storage
   2371  * and pinned into our object. i915_gem_object_get_pages() may be called
   2372  * multiple times before they are released by a single call to
   2373  * i915_gem_object_put_pages() - once the pages are no longer referenced
   2374  * either as a result of memory pressure (reaping pages under the shrinker)
   2375  * or as the object is itself released.
   2376  */
   2377 int
   2378 i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
   2379 {
   2380 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   2381 	const struct drm_i915_gem_object_ops *ops = obj->ops;
   2382 	int ret;
   2383 
   2384 	if (obj->pages)
   2385 		return 0;
   2386 
   2387 	if (obj->madv != I915_MADV_WILLNEED) {
   2388 		DRM_DEBUG("Attempting to obtain a purgeable object\n");
   2389 		return -EFAULT;
   2390 	}
   2391 
   2392 	BUG_ON(obj->pages_pin_count);
   2393 
   2394 	ret = ops->get_pages(obj);
   2395 	if (ret)
   2396 		return ret;
   2397 
   2398 	list_add_tail(&obj->global_list, &dev_priv->mm.unbound_list);
   2399 
   2400 	obj->get_page.sg = obj->pages->sgl;
   2401 	obj->get_page.last = 0;
   2402 
   2403 	return 0;
   2404 }
   2405 
   2406 void i915_vma_move_to_active(struct i915_vma *vma,
   2407 			     struct drm_i915_gem_request *req)
   2408 {
   2409 	struct drm_i915_gem_object *obj = vma->obj;
   2410 	struct intel_engine_cs *ring;
   2411 
   2412 	ring = i915_gem_request_get_ring(req);
   2413 
   2414 	/* Add a reference if we're newly entering the active list. */
   2415 	if (obj->active == 0)
   2416 		drm_gem_object_reference(&obj->base);
   2417 	obj->active |= intel_ring_flag(ring);
   2418 
   2419 	list_move_tail(&obj->ring_list[ring->id], &ring->active_list);
   2420 	i915_gem_request_assign(&obj->last_read_req[ring->id], req);
   2421 
   2422 	list_move_tail(&vma->mm_list, &vma->vm->active_list);
   2423 }
   2424 
   2425 static void
   2426 i915_gem_object_retire__write(struct drm_i915_gem_object *obj)
   2427 {
   2428 	RQ_BUG_ON(obj->last_write_req == NULL);
   2429 	RQ_BUG_ON(!(obj->active & intel_ring_flag(obj->last_write_req->ring)));
   2430 
   2431 	i915_gem_request_assign(&obj->last_write_req, NULL);
   2432 	intel_fb_obj_flush(obj, true, ORIGIN_CS);
   2433 }
   2434 
   2435 static void
   2436 i915_gem_object_retire__read(struct drm_i915_gem_object *obj, int ring)
   2437 {
   2438 	struct i915_vma *vma;
   2439 
   2440 	RQ_BUG_ON(obj->last_read_req[ring] == NULL);
   2441 	RQ_BUG_ON(!(obj->active & (1 << ring)));
   2442 
   2443 	list_del_init(&obj->ring_list[ring]);
   2444 	i915_gem_request_assign(&obj->last_read_req[ring], NULL);
   2445 
   2446 	if (obj->last_write_req && obj->last_write_req->ring->id == ring)
   2447 		i915_gem_object_retire__write(obj);
   2448 
   2449 	obj->active &= ~(1 << ring);
   2450 	if (obj->active)
   2451 		return;
   2452 
   2453 	/* Bump our place on the bound list to keep it roughly in LRU order
   2454 	 * so that we don't steal from recently used but inactive objects
   2455 	 * (unless we are forced to ofc!)
   2456 	 */
   2457 	list_move_tail(&obj->global_list,
   2458 		       &to_i915(obj->base.dev)->mm.bound_list);
   2459 
   2460 	list_for_each_entry(vma, &obj->vma_list, vma_link) {
   2461 		if (!list_empty(&vma->mm_list))
   2462 			list_move_tail(&vma->mm_list, &vma->vm->inactive_list);
   2463 	}
   2464 
   2465 	i915_gem_request_assign(&obj->last_fenced_req, NULL);
   2466 	drm_gem_object_unreference(&obj->base);
   2467 }
   2468 
   2469 static int
   2470 i915_gem_init_seqno(struct drm_device *dev, u32 seqno)
   2471 {
   2472 	struct drm_i915_private *dev_priv = dev->dev_private;
   2473 	struct intel_engine_cs *ring;
   2474 	int ret, i, j;
   2475 
   2476 	/* Carefully retire all requests without writing to the rings */
   2477 	for_each_ring(ring, dev_priv, i) {
   2478 		ret = intel_ring_idle(ring);
   2479 		if (ret)
   2480 			return ret;
   2481 	}
   2482 	i915_gem_retire_requests(dev);
   2483 
   2484 	/* Finally reset hw state */
   2485 	for_each_ring(ring, dev_priv, i) {
   2486 		intel_ring_init_seqno(ring, seqno);
   2487 
   2488 		for (j = 0; j < ARRAY_SIZE(ring->semaphore.sync_seqno); j++)
   2489 			ring->semaphore.sync_seqno[j] = 0;
   2490 	}
   2491 
   2492 	return 0;
   2493 }
   2494 
   2495 int i915_gem_set_seqno(struct drm_device *dev, u32 seqno)
   2496 {
   2497 	struct drm_i915_private *dev_priv = dev->dev_private;
   2498 	int ret;
   2499 
   2500 	if (seqno == 0)
   2501 		return -EINVAL;
   2502 
   2503 	/* HWS page needs to be set less than what we
   2504 	 * will inject to ring
   2505 	 */
   2506 	ret = i915_gem_init_seqno(dev, seqno - 1);
   2507 	if (ret)
   2508 		return ret;
   2509 
   2510 	/* Carefully set the last_seqno value so that wrap
   2511 	 * detection still works
   2512 	 */
   2513 	dev_priv->next_seqno = seqno;
   2514 	dev_priv->last_seqno = seqno - 1;
   2515 	if (dev_priv->last_seqno == 0)
   2516 		dev_priv->last_seqno--;
   2517 
   2518 	return 0;
   2519 }
   2520 
   2521 int
   2522 i915_gem_get_seqno(struct drm_device *dev, u32 *seqno)
   2523 {
   2524 	struct drm_i915_private *dev_priv = dev->dev_private;
   2525 
   2526 	/* reserve 0 for non-seqno */
   2527 	if (dev_priv->next_seqno == 0) {
   2528 		int ret = i915_gem_init_seqno(dev, 0);
   2529 		if (ret)
   2530 			return ret;
   2531 
   2532 		dev_priv->next_seqno = 1;
   2533 	}
   2534 
   2535 	*seqno = dev_priv->last_seqno = dev_priv->next_seqno++;
   2536 	return 0;
   2537 }
   2538 
   2539 /*
   2540  * NB: This function is not allowed to fail. Doing so would mean the the
   2541  * request is not being tracked for completion but the work itself is
   2542  * going to happen on the hardware. This would be a Bad Thing(tm).
   2543  */
   2544 void __i915_add_request(struct drm_i915_gem_request *request,
   2545 			struct drm_i915_gem_object *obj,
   2546 			bool flush_caches)
   2547 {
   2548 	struct intel_engine_cs *ring;
   2549 	struct drm_i915_private *dev_priv;
   2550 	struct intel_ringbuffer *ringbuf;
   2551 	u32 request_start;
   2552 	int ret;
   2553 
   2554 	if (WARN_ON(request == NULL))
   2555 		return;
   2556 
   2557 	ring = request->ring;
   2558 	dev_priv = ring->dev->dev_private;
   2559 	ringbuf = request->ringbuf;
   2560 
   2561 	/*
   2562 	 * To ensure that this call will not fail, space for its emissions
   2563 	 * should already have been reserved in the ring buffer. Let the ring
   2564 	 * know that it is time to use that space up.
   2565 	 */
   2566 	intel_ring_reserved_space_use(ringbuf);
   2567 
   2568 	request_start = intel_ring_get_tail(ringbuf);
   2569 	/*
   2570 	 * Emit any outstanding flushes - execbuf can fail to emit the flush
   2571 	 * after having emitted the batchbuffer command. Hence we need to fix
   2572 	 * things up similar to emitting the lazy request. The difference here
   2573 	 * is that the flush _must_ happen before the next request, no matter
   2574 	 * what.
   2575 	 */
   2576 	if (flush_caches) {
   2577 		if (i915.enable_execlists)
   2578 			ret = logical_ring_flush_all_caches(request);
   2579 		else
   2580 			ret = intel_ring_flush_all_caches(request);
   2581 		/* Not allowed to fail! */
   2582 		WARN(ret, "*_ring_flush_all_caches failed: %d!\n", ret);
   2583 	}
   2584 
   2585 	/* Record the position of the start of the request so that
   2586 	 * should we detect the updated seqno part-way through the
   2587 	 * GPU processing the request, we never over-estimate the
   2588 	 * position of the head.
   2589 	 */
   2590 	request->postfix = intel_ring_get_tail(ringbuf);
   2591 
   2592 	if (i915.enable_execlists)
   2593 		ret = ring->emit_request(request);
   2594 	else {
   2595 		ret = ring->add_request(request);
   2596 
   2597 		request->tail = intel_ring_get_tail(ringbuf);
   2598 	}
   2599 	/* Not allowed to fail! */
   2600 	WARN(ret, "emit|add_request failed: %d!\n", ret);
   2601 
   2602 	request->head = request_start;
   2603 
   2604 	/* Whilst this request exists, batch_obj will be on the
   2605 	 * active_list, and so will hold the active reference. Only when this
   2606 	 * request is retired will the the batch_obj be moved onto the
   2607 	 * inactive_list and lose its active reference. Hence we do not need
   2608 	 * to explicitly hold another reference here.
   2609 	 */
   2610 	request->batch_obj = obj;
   2611 
   2612 	request->emitted_jiffies = jiffies;
   2613 	request->previous_seqno = ring->last_submitted_seqno;
   2614 	ring->last_submitted_seqno = request->seqno;
   2615 	list_add_tail(&request->list, &ring->request_list);
   2616 
   2617 	trace_i915_gem_request_add(request);
   2618 
   2619 	i915_queue_hangcheck(ring->dev);
   2620 
   2621 	queue_delayed_work(dev_priv->wq,
   2622 			   &dev_priv->mm.retire_work,
   2623 			   round_jiffies_up_relative(HZ));
   2624 	intel_mark_busy(dev_priv->dev);
   2625 
   2626 	/* Sanity check that the reserved size was large enough. */
   2627 	intel_ring_reserved_space_end(ringbuf);
   2628 }
   2629 
   2630 static bool i915_context_is_banned(struct drm_i915_private *dev_priv,
   2631 				   const struct intel_context *ctx)
   2632 {
   2633 	unsigned long elapsed;
   2634 
   2635 	elapsed = get_seconds() - ctx->hang_stats.guilty_ts;
   2636 
   2637 	if (ctx->hang_stats.banned)
   2638 		return true;
   2639 
   2640 	if (ctx->hang_stats.ban_period_seconds &&
   2641 	    elapsed <= ctx->hang_stats.ban_period_seconds) {
   2642 		if (!i915_gem_context_is_default(ctx)) {
   2643 			DRM_DEBUG("context hanging too fast, banning!\n");
   2644 			return true;
   2645 		} else if (i915_stop_ring_allow_ban(dev_priv)) {
   2646 			if (i915_stop_ring_allow_warn(dev_priv))
   2647 				DRM_ERROR("gpu hanging too fast, banning!\n");
   2648 			return true;
   2649 		}
   2650 	}
   2651 
   2652 	return false;
   2653 }
   2654 
   2655 static void i915_set_reset_status(struct drm_i915_private *dev_priv,
   2656 				  struct intel_context *ctx,
   2657 				  const bool guilty)
   2658 {
   2659 	struct i915_ctx_hang_stats *hs;
   2660 
   2661 	if (WARN_ON(!ctx))
   2662 		return;
   2663 
   2664 	hs = &ctx->hang_stats;
   2665 
   2666 	if (guilty) {
   2667 		hs->banned = i915_context_is_banned(dev_priv, ctx);
   2668 		hs->batch_active++;
   2669 		hs->guilty_ts = get_seconds();
   2670 	} else {
   2671 		hs->batch_pending++;
   2672 	}
   2673 }
   2674 
   2675 void i915_gem_request_free(struct kref *req_ref)
   2676 {
   2677 	struct drm_i915_gem_request *req = container_of(req_ref,
   2678 						 typeof(*req), ref);
   2679 	struct intel_context *ctx = req->ctx;
   2680 
   2681 	if (req->file_priv)
   2682 		i915_gem_request_remove_from_client(req);
   2683 
   2684 	if (ctx) {
   2685 		if (i915.enable_execlists) {
   2686 			if (ctx != req->ring->default_context)
   2687 				intel_lr_context_unpin(req);
   2688 		}
   2689 
   2690 		i915_gem_context_unreference(ctx);
   2691 	}
   2692 
   2693 	kmem_cache_free(req->i915->requests, req);
   2694 }
   2695 
   2696 int i915_gem_request_alloc(struct intel_engine_cs *ring,
   2697 			   struct intel_context *ctx,
   2698 			   struct drm_i915_gem_request **req_out)
   2699 {
   2700 	struct drm_i915_private *dev_priv = to_i915(ring->dev);
   2701 	struct drm_i915_gem_request *req;
   2702 	int ret;
   2703 
   2704 	if (!req_out)
   2705 		return -EINVAL;
   2706 
   2707 	*req_out = NULL;
   2708 
   2709 	req = kmem_cache_zalloc(dev_priv->requests, GFP_KERNEL);
   2710 	if (req == NULL)
   2711 		return -ENOMEM;
   2712 
   2713 	ret = i915_gem_get_seqno(ring->dev, &req->seqno);
   2714 	if (ret)
   2715 		goto err;
   2716 
   2717 	kref_init(&req->ref);
   2718 	req->i915 = dev_priv;
   2719 	req->ring = ring;
   2720 	req->ctx  = ctx;
   2721 	i915_gem_context_reference(req->ctx);
   2722 
   2723 	if (i915.enable_execlists)
   2724 		ret = intel_logical_ring_alloc_request_extras(req);
   2725 	else
   2726 		ret = intel_ring_alloc_request_extras(req);
   2727 	if (ret) {
   2728 		i915_gem_context_unreference(req->ctx);
   2729 		goto err;
   2730 	}
   2731 
   2732 	/*
   2733 	 * Reserve space in the ring buffer for all the commands required to
   2734 	 * eventually emit this request. This is to guarantee that the
   2735 	 * i915_add_request() call can't fail. Note that the reserve may need
   2736 	 * to be redone if the request is not actually submitted straight
   2737 	 * away, e.g. because a GPU scheduler has deferred it.
   2738 	 */
   2739 	if (i915.enable_execlists)
   2740 		ret = intel_logical_ring_reserve_space(req);
   2741 	else
   2742 		ret = intel_ring_reserve_space(req);
   2743 	if (ret) {
   2744 		/*
   2745 		 * At this point, the request is fully allocated even if not
   2746 		 * fully prepared. Thus it can be cleaned up using the proper
   2747 		 * free code.
   2748 		 */
   2749 		i915_gem_request_cancel(req);
   2750 		return ret;
   2751 	}
   2752 
   2753 	*req_out = req;
   2754 	return 0;
   2755 
   2756 err:
   2757 	kmem_cache_free(dev_priv->requests, req);
   2758 	return ret;
   2759 }
   2760 
   2761 void i915_gem_request_cancel(struct drm_i915_gem_request *req)
   2762 {
   2763 	intel_ring_reserved_space_cancel(req->ringbuf);
   2764 
   2765 	i915_gem_request_unreference(req);
   2766 }
   2767 
   2768 struct drm_i915_gem_request *
   2769 i915_gem_find_active_request(struct intel_engine_cs *ring)
   2770 {
   2771 	struct drm_i915_gem_request *request;
   2772 
   2773 	list_for_each_entry(request, &ring->request_list, list) {
   2774 		if (i915_gem_request_completed(request, false))
   2775 			continue;
   2776 
   2777 		return request;
   2778 	}
   2779 
   2780 	return NULL;
   2781 }
   2782 
   2783 static void i915_gem_reset_ring_status(struct drm_i915_private *dev_priv,
   2784 				       struct intel_engine_cs *ring)
   2785 {
   2786 	struct drm_i915_gem_request *request;
   2787 	bool ring_hung;
   2788 
   2789 	request = i915_gem_find_active_request(ring);
   2790 
   2791 	if (request == NULL)
   2792 		return;
   2793 
   2794 	ring_hung = ring->hangcheck.score >= HANGCHECK_SCORE_RING_HUNG;
   2795 
   2796 	i915_set_reset_status(dev_priv, request->ctx, ring_hung);
   2797 
   2798 	list_for_each_entry_continue(request, &ring->request_list, list)
   2799 		i915_set_reset_status(dev_priv, request->ctx, false);
   2800 }
   2801 
   2802 static void i915_gem_reset_ring_cleanup(struct drm_i915_private *dev_priv,
   2803 					struct intel_engine_cs *ring)
   2804 {
   2805 	while (!list_empty(&ring->active_list)) {
   2806 		struct drm_i915_gem_object *obj;
   2807 
   2808 		obj = list_first_entry(&ring->active_list,
   2809 				       struct drm_i915_gem_object,
   2810 				       ring_list[ring->id]);
   2811 
   2812 		i915_gem_object_retire__read(obj, ring->id);
   2813 	}
   2814 
   2815 	/*
   2816 	 * Clear the execlists queue up before freeing the requests, as those
   2817 	 * are the ones that keep the context and ringbuffer backing objects
   2818 	 * pinned in place.
   2819 	 */
   2820 	while (!list_empty(&ring->execlist_queue)) {
   2821 		struct drm_i915_gem_request *submit_req;
   2822 
   2823 		submit_req = list_first_entry(&ring->execlist_queue,
   2824 				struct drm_i915_gem_request,
   2825 				execlist_link);
   2826 		list_del(&submit_req->execlist_link);
   2827 
   2828 		if (submit_req->ctx != ring->default_context)
   2829 			intel_lr_context_unpin(submit_req);
   2830 
   2831 		i915_gem_request_unreference(submit_req);
   2832 	}
   2833 
   2834 	/*
   2835 	 * We must free the requests after all the corresponding objects have
   2836 	 * been moved off active lists. Which is the same order as the normal
   2837 	 * retire_requests function does. This is important if object hold
   2838 	 * implicit references on things like e.g. ppgtt address spaces through
   2839 	 * the request.
   2840 	 */
   2841 	while (!list_empty(&ring->request_list)) {
   2842 		struct drm_i915_gem_request *request;
   2843 
   2844 		request = list_first_entry(&ring->request_list,
   2845 					   struct drm_i915_gem_request,
   2846 					   list);
   2847 
   2848 		i915_gem_request_retire(request);
   2849 	}
   2850 }
   2851 
   2852 void i915_gem_reset(struct drm_device *dev)
   2853 {
   2854 	struct drm_i915_private *dev_priv = dev->dev_private;
   2855 	struct intel_engine_cs *ring;
   2856 	int i;
   2857 
   2858 	/*
   2859 	 * Before we free the objects from the requests, we need to inspect
   2860 	 * them for finding the guilty party. As the requests only borrow
   2861 	 * their reference to the objects, the inspection must be done first.
   2862 	 */
   2863 	for_each_ring(ring, dev_priv, i)
   2864 		i915_gem_reset_ring_status(dev_priv, ring);
   2865 
   2866 	for_each_ring(ring, dev_priv, i)
   2867 		i915_gem_reset_ring_cleanup(dev_priv, ring);
   2868 
   2869 	i915_gem_context_reset(dev);
   2870 
   2871 	i915_gem_restore_fences(dev);
   2872 
   2873 	WARN_ON(i915_verify_lists(dev));
   2874 }
   2875 
   2876 /**
   2877  * This function clears the request list as sequence numbers are passed.
   2878  */
   2879 void
   2880 i915_gem_retire_requests_ring(struct intel_engine_cs *ring)
   2881 {
   2882 	WARN_ON(i915_verify_lists(ring->dev));
   2883 
   2884 	/* Retire requests first as we use it above for the early return.
   2885 	 * If we retire requests last, we may use a later seqno and so clear
   2886 	 * the requests lists without clearing the active list, leading to
   2887 	 * confusion.
   2888 	 */
   2889 	while (!list_empty(&ring->request_list)) {
   2890 		struct drm_i915_gem_request *request;
   2891 
   2892 		request = list_first_entry(&ring->request_list,
   2893 					   struct drm_i915_gem_request,
   2894 					   list);
   2895 
   2896 		if (!i915_gem_request_completed(request, true))
   2897 			break;
   2898 
   2899 		i915_gem_request_retire(request);
   2900 	}
   2901 
   2902 	/* Move any buffers on the active list that are no longer referenced
   2903 	 * by the ringbuffer to the flushing/inactive lists as appropriate,
   2904 	 * before we free the context associated with the requests.
   2905 	 */
   2906 	while (!list_empty(&ring->active_list)) {
   2907 		struct drm_i915_gem_object *obj;
   2908 
   2909 		obj = list_first_entry(&ring->active_list,
   2910 				      struct drm_i915_gem_object,
   2911 				      ring_list[ring->id]);
   2912 
   2913 		if (!list_empty(&obj->last_read_req[ring->id]->list))
   2914 			break;
   2915 
   2916 		i915_gem_object_retire__read(obj, ring->id);
   2917 	}
   2918 
   2919 	if (unlikely(ring->trace_irq_req &&
   2920 		     i915_gem_request_completed(ring->trace_irq_req, true))) {
   2921 		ring->irq_put(ring);
   2922 		i915_gem_request_assign(&ring->trace_irq_req, NULL);
   2923 	}
   2924 
   2925 	WARN_ON(i915_verify_lists(ring->dev));
   2926 }
   2927 
   2928 bool
   2929 i915_gem_retire_requests(struct drm_device *dev)
   2930 {
   2931 	struct drm_i915_private *dev_priv = dev->dev_private;
   2932 	struct intel_engine_cs *ring;
   2933 	bool idle = true;
   2934 	int i;
   2935 
   2936 	for_each_ring(ring, dev_priv, i) {
   2937 		i915_gem_retire_requests_ring(ring);
   2938 		idle &= list_empty(&ring->request_list);
   2939 		if (i915.enable_execlists) {
   2940 			unsigned long flags;
   2941 
   2942 			spin_lock_irqsave(&ring->execlist_lock, flags);
   2943 			idle &= list_empty(&ring->execlist_queue);
   2944 			spin_unlock_irqrestore(&ring->execlist_lock, flags);
   2945 
   2946 			intel_execlists_retire_requests(ring);
   2947 		}
   2948 	}
   2949 
   2950 	if (idle)
   2951 		mod_delayed_work(dev_priv->wq,
   2952 				   &dev_priv->mm.idle_work,
   2953 				   msecs_to_jiffies(100));
   2954 
   2955 	return idle;
   2956 }
   2957 
   2958 static void
   2959 i915_gem_retire_work_handler(struct work_struct *work)
   2960 {
   2961 	struct drm_i915_private *dev_priv =
   2962 		container_of(work, typeof(*dev_priv), mm.retire_work.work);
   2963 	struct drm_device *dev = dev_priv->dev;
   2964 	bool idle;
   2965 
   2966 	/* Come back later if the device is busy... */
   2967 	idle = false;
   2968 	if (mutex_trylock(&dev->struct_mutex)) {
   2969 		idle = i915_gem_retire_requests(dev);
   2970 		mutex_unlock(&dev->struct_mutex);
   2971 	}
   2972 	if (!idle)
   2973 		queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work,
   2974 				   round_jiffies_up_relative(HZ));
   2975 }
   2976 
   2977 static void
   2978 i915_gem_idle_work_handler(struct work_struct *work)
   2979 {
   2980 	struct drm_i915_private *dev_priv =
   2981 		container_of(work, typeof(*dev_priv), mm.idle_work.work);
   2982 	struct drm_device *dev = dev_priv->dev;
   2983 	struct intel_engine_cs *ring;
   2984 	int i;
   2985 
   2986 	for_each_ring(ring, dev_priv, i)
   2987 		if (!list_empty(&ring->request_list))
   2988 			return;
   2989 
   2990 	intel_mark_idle(dev);
   2991 
   2992 	if (mutex_trylock(&dev->struct_mutex)) {
   2993 		struct intel_engine_cs *ring;
   2994 		int i;
   2995 
   2996 		for_each_ring(ring, dev_priv, i)
   2997 			i915_gem_batch_pool_fini(&ring->batch_pool);
   2998 
   2999 		mutex_unlock(&dev->struct_mutex);
   3000 	}
   3001 }
   3002 
   3003 /**
   3004  * Ensures that an object will eventually get non-busy by flushing any required
   3005  * write domains, emitting any outstanding lazy request and retiring and
   3006  * completed requests.
   3007  */
   3008 static int
   3009 i915_gem_object_flush_active(struct drm_i915_gem_object *obj)
   3010 {
   3011 	int i;
   3012 
   3013 	if (!obj->active)
   3014 		return 0;
   3015 
   3016 	for (i = 0; i < I915_NUM_RINGS; i++) {
   3017 		struct drm_i915_gem_request *req;
   3018 
   3019 		req = obj->last_read_req[i];
   3020 		if (req == NULL)
   3021 			continue;
   3022 
   3023 		if (list_empty(&req->list))
   3024 			goto retire;
   3025 
   3026 		if (i915_gem_request_completed(req, true)) {
   3027 			__i915_gem_request_retire__upto(req);
   3028 retire:
   3029 			i915_gem_object_retire__read(obj, i);
   3030 		}
   3031 	}
   3032 
   3033 	return 0;
   3034 }
   3035 
   3036 /**
   3037  * i915_gem_wait_ioctl - implements DRM_IOCTL_I915_GEM_WAIT
   3038  * @DRM_IOCTL_ARGS: standard ioctl arguments
   3039  *
   3040  * Returns 0 if successful, else an error is returned with the remaining time in
   3041  * the timeout parameter.
   3042  *  -ETIME: object is still busy after timeout
   3043  *  -ERESTARTSYS: signal interrupted the wait
   3044  *  -ENONENT: object doesn't exist
   3045  * Also possible, but rare:
   3046  *  -EAGAIN: GPU wedged
   3047  *  -ENOMEM: damn
   3048  *  -ENODEV: Internal IRQ fail
   3049  *  -E?: The add request failed
   3050  *
   3051  * The wait ioctl with a timeout of 0 reimplements the busy ioctl. With any
   3052  * non-zero timeout parameter the wait ioctl will wait for the given number of
   3053  * nanoseconds on an object becoming unbusy. Since the wait itself does so
   3054  * without holding struct_mutex the object may become re-busied before this
   3055  * function completes. A similar but shorter * race condition exists in the busy
   3056  * ioctl
   3057  */
   3058 int
   3059 i915_gem_wait_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
   3060 {
   3061 	struct drm_i915_private *dev_priv = dev->dev_private;
   3062 	struct drm_i915_gem_wait *args = data;
   3063 	struct drm_i915_gem_object *obj;
   3064 	struct drm_i915_gem_request *req[I915_NUM_RINGS];
   3065 	unsigned reset_counter;
   3066 	int i, n = 0;
   3067 	int ret;
   3068 
   3069 	if (args->flags != 0)
   3070 		return -EINVAL;
   3071 
   3072 	ret = i915_mutex_lock_interruptible(dev);
   3073 	if (ret)
   3074 		return ret;
   3075 
   3076 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->bo_handle));
   3077 	if (&obj->base == NULL) {
   3078 		mutex_unlock(&dev->struct_mutex);
   3079 		return -ENOENT;
   3080 	}
   3081 
   3082 	/* Need to make sure the object gets inactive eventually. */
   3083 	ret = i915_gem_object_flush_active(obj);
   3084 	if (ret)
   3085 		goto out;
   3086 
   3087 	if (!obj->active)
   3088 		goto out;
   3089 
   3090 	/* Do this after OLR check to make sure we make forward progress polling
   3091 	 * on this IOCTL with a timeout == 0 (like busy ioctl)
   3092 	 */
   3093 	if (args->timeout_ns == 0) {
   3094 		ret = -ETIME;
   3095 		goto out;
   3096 	}
   3097 
   3098 	drm_gem_object_unreference(&obj->base);
   3099 	reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
   3100 
   3101 	for (i = 0; i < I915_NUM_RINGS; i++) {
   3102 		if (obj->last_read_req[i] == NULL)
   3103 			continue;
   3104 
   3105 		req[n++] = i915_gem_request_reference(obj->last_read_req[i]);
   3106 	}
   3107 
   3108 	mutex_unlock(&dev->struct_mutex);
   3109 
   3110 	for (i = 0; i < n; i++) {
   3111 		if (ret == 0)
   3112 			ret = __i915_wait_request(req[i], reset_counter, true,
   3113 						  args->timeout_ns > 0 ? &args->timeout_ns : NULL,
   3114 						  file->driver_priv);
   3115 		i915_gem_request_unreference__unlocked(req[i]);
   3116 	}
   3117 	return ret;
   3118 
   3119 out:
   3120 	drm_gem_object_unreference(&obj->base);
   3121 	mutex_unlock(&dev->struct_mutex);
   3122 	return ret;
   3123 }
   3124 
   3125 static int
   3126 __i915_gem_object_sync(struct drm_i915_gem_object *obj,
   3127 		       struct intel_engine_cs *to,
   3128 		       struct drm_i915_gem_request *from_req,
   3129 		       struct drm_i915_gem_request **to_req)
   3130 {
   3131 	struct intel_engine_cs *from;
   3132 	int ret;
   3133 
   3134 	from = i915_gem_request_get_ring(from_req);
   3135 	if (to == from)
   3136 		return 0;
   3137 
   3138 	if (i915_gem_request_completed(from_req, true))
   3139 		return 0;
   3140 
   3141 	if (!i915_semaphore_is_enabled(obj->base.dev)) {
   3142 		struct drm_i915_private *i915 = to_i915(obj->base.dev);
   3143 		ret = __i915_wait_request(from_req,
   3144 					  atomic_read(&i915->gpu_error.reset_counter),
   3145 					  i915->mm.interruptible,
   3146 					  NULL,
   3147 					  &i915->rps.semaphores);
   3148 		if (ret)
   3149 			return ret;
   3150 
   3151 		i915_gem_object_retire_request(obj, from_req);
   3152 	} else {
   3153 		int idx = intel_ring_sync_index(from, to);
   3154 		u32 seqno = i915_gem_request_get_seqno(from_req);
   3155 
   3156 		WARN_ON(!to_req);
   3157 
   3158 		if (seqno <= from->semaphore.sync_seqno[idx])
   3159 			return 0;
   3160 
   3161 		if (*to_req == NULL) {
   3162 			ret = i915_gem_request_alloc(to, to->default_context, to_req);
   3163 			if (ret)
   3164 				return ret;
   3165 		}
   3166 
   3167 		trace_i915_gem_ring_sync_to(*to_req, from, from_req);
   3168 		ret = to->semaphore.sync_to(*to_req, from, seqno);
   3169 		if (ret)
   3170 			return ret;
   3171 
   3172 		/* We use last_read_req because sync_to()
   3173 		 * might have just caused seqno wrap under
   3174 		 * the radar.
   3175 		 */
   3176 		from->semaphore.sync_seqno[idx] =
   3177 			i915_gem_request_get_seqno(obj->last_read_req[from->id]);
   3178 	}
   3179 
   3180 	return 0;
   3181 }
   3182 
   3183 /**
   3184  * i915_gem_object_sync - sync an object to a ring.
   3185  *
   3186  * @obj: object which may be in use on another ring.
   3187  * @to: ring we wish to use the object on. May be NULL.
   3188  * @to_req: request we wish to use the object for. See below.
   3189  *          This will be allocated and returned if a request is
   3190  *          required but not passed in.
   3191  *
   3192  * This code is meant to abstract object synchronization with the GPU.
   3193  * Calling with NULL implies synchronizing the object with the CPU
   3194  * rather than a particular GPU ring. Conceptually we serialise writes
   3195  * between engines inside the GPU. We only allow one engine to write
   3196  * into a buffer at any time, but multiple readers. To ensure each has
   3197  * a coherent view of memory, we must:
   3198  *
   3199  * - If there is an outstanding write request to the object, the new
   3200  *   request must wait for it to complete (either CPU or in hw, requests
   3201  *   on the same ring will be naturally ordered).
   3202  *
   3203  * - If we are a write request (pending_write_domain is set), the new
   3204  *   request must wait for outstanding read requests to complete.
   3205  *
   3206  * For CPU synchronisation (NULL to) no request is required. For syncing with
   3207  * rings to_req must be non-NULL. However, a request does not have to be
   3208  * pre-allocated. If *to_req is NULL and sync commands will be emitted then a
   3209  * request will be allocated automatically and returned through *to_req. Note
   3210  * that it is not guaranteed that commands will be emitted (because the system
   3211  * might already be idle). Hence there is no need to create a request that
   3212  * might never have any work submitted. Note further that if a request is
   3213  * returned in *to_req, it is the responsibility of the caller to submit
   3214  * that request (after potentially adding more work to it).
   3215  *
   3216  * Returns 0 if successful, else propagates up the lower layer error.
   3217  */
   3218 int
   3219 i915_gem_object_sync(struct drm_i915_gem_object *obj,
   3220 		     struct intel_engine_cs *to,
   3221 		     struct drm_i915_gem_request **to_req)
   3222 {
   3223 	const bool readonly = obj->base.pending_write_domain == 0;
   3224 	struct drm_i915_gem_request *req[I915_NUM_RINGS];
   3225 	int ret, i, n;
   3226 
   3227 	if (!obj->active)
   3228 		return 0;
   3229 
   3230 	if (to == NULL)
   3231 		return i915_gem_object_wait_rendering(obj, readonly);
   3232 
   3233 	n = 0;
   3234 	if (readonly) {
   3235 		if (obj->last_write_req)
   3236 			req[n++] = obj->last_write_req;
   3237 	} else {
   3238 		for (i = 0; i < I915_NUM_RINGS; i++)
   3239 			if (obj->last_read_req[i])
   3240 				req[n++] = obj->last_read_req[i];
   3241 	}
   3242 	for (i = 0; i < n; i++) {
   3243 		ret = __i915_gem_object_sync(obj, to, req[i], to_req);
   3244 		if (ret)
   3245 			return ret;
   3246 	}
   3247 
   3248 	return 0;
   3249 }
   3250 
   3251 static void i915_gem_object_finish_gtt(struct drm_i915_gem_object *obj)
   3252 {
   3253 	u32 old_write_domain, old_read_domains;
   3254 
   3255 	/* Force a pagefault for domain tracking on next user access */
   3256 	i915_gem_release_mmap(obj);
   3257 
   3258 	if ((obj->base.read_domains & I915_GEM_DOMAIN_GTT) == 0)
   3259 		return;
   3260 
   3261 	/* Wait for any direct GTT access to complete */
   3262 	mb();
   3263 
   3264 	old_read_domains = obj->base.read_domains;
   3265 	old_write_domain = obj->base.write_domain;
   3266 
   3267 	obj->base.read_domains &= ~I915_GEM_DOMAIN_GTT;
   3268 	obj->base.write_domain &= ~I915_GEM_DOMAIN_GTT;
   3269 
   3270 	trace_i915_gem_object_change_domain(obj,
   3271 					    old_read_domains,
   3272 					    old_write_domain);
   3273 }
   3274 
   3275 static int __i915_vma_unbind(struct i915_vma *vma, bool wait)
   3276 {
   3277 	struct drm_i915_gem_object *obj = vma->obj;
   3278 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   3279 	int ret;
   3280 
   3281 	if (list_empty(&vma->vma_link))
   3282 		return 0;
   3283 
   3284 	if (!drm_mm_node_allocated(&vma->node)) {
   3285 		i915_gem_vma_destroy(vma);
   3286 		return 0;
   3287 	}
   3288 
   3289 	if (vma->pin_count)
   3290 		return -EBUSY;
   3291 
   3292 	BUG_ON(obj->pages == NULL);
   3293 
   3294 	if (wait) {
   3295 		ret = i915_gem_object_wait_rendering(obj, false);
   3296 		if (ret)
   3297 			return ret;
   3298 	}
   3299 
   3300 	if (i915_is_ggtt(vma->vm) &&
   3301 	    vma->ggtt_view.type == I915_GGTT_VIEW_NORMAL) {
   3302 		i915_gem_object_finish_gtt(obj);
   3303 
   3304 		/* release the fence reg _after_ flushing */
   3305 		ret = i915_gem_object_put_fence(obj);
   3306 		if (ret)
   3307 			return ret;
   3308 	}
   3309 
   3310 	trace_i915_vma_unbind(vma);
   3311 
   3312 	vma->vm->unbind_vma(vma);
   3313 	vma->bound = 0;
   3314 
   3315 	list_del_init(&vma->mm_list);
   3316 	if (i915_is_ggtt(vma->vm)) {
   3317 		if (vma->ggtt_view.type == I915_GGTT_VIEW_NORMAL) {
   3318 			obj->map_and_fenceable = false;
   3319 		} else if (vma->ggtt_view.pages) {
   3320 			sg_free_table(vma->ggtt_view.pages);
   3321 			kfree(vma->ggtt_view.pages);
   3322 		}
   3323 		vma->ggtt_view.pages = NULL;
   3324 	}
   3325 
   3326 	drm_mm_remove_node(&vma->node);
   3327 	i915_gem_vma_destroy(vma);
   3328 
   3329 	/* Since the unbound list is global, only move to that list if
   3330 	 * no more VMAs exist. */
   3331 	if (list_empty(&obj->vma_list))
   3332 		list_move_tail(&obj->global_list, &dev_priv->mm.unbound_list);
   3333 
   3334 	/* And finally now the object is completely decoupled from this vma,
   3335 	 * we can drop its hold on the backing storage and allow it to be
   3336 	 * reaped by the shrinker.
   3337 	 */
   3338 	i915_gem_object_unpin_pages(obj);
   3339 
   3340 	return 0;
   3341 }
   3342 
   3343 int i915_vma_unbind(struct i915_vma *vma)
   3344 {
   3345 	return __i915_vma_unbind(vma, true);
   3346 }
   3347 
   3348 int __i915_vma_unbind_no_wait(struct i915_vma *vma)
   3349 {
   3350 	return __i915_vma_unbind(vma, false);
   3351 }
   3352 
   3353 int i915_gpu_idle(struct drm_device *dev)
   3354 {
   3355 	struct drm_i915_private *dev_priv = dev->dev_private;
   3356 	struct intel_engine_cs *ring;
   3357 	int ret, i;
   3358 
   3359 	/* Flush everything onto the inactive list. */
   3360 	for_each_ring(ring, dev_priv, i) {
   3361 		if (!i915.enable_execlists) {
   3362 			struct drm_i915_gem_request *req;
   3363 
   3364 			ret = i915_gem_request_alloc(ring, ring->default_context, &req);
   3365 			if (ret)
   3366 				return ret;
   3367 
   3368 			ret = i915_switch_context(req);
   3369 			if (ret) {
   3370 				i915_gem_request_cancel(req);
   3371 				return ret;
   3372 			}
   3373 
   3374 			i915_add_request_no_flush(req);
   3375 		}
   3376 
   3377 		ret = intel_ring_idle(ring);
   3378 		if (ret)
   3379 			return ret;
   3380 	}
   3381 
   3382 	WARN_ON(i915_verify_lists(dev));
   3383 	return 0;
   3384 }
   3385 
   3386 static bool i915_gem_valid_gtt_space(struct i915_vma *vma,
   3387 				     unsigned long cache_level)
   3388 {
   3389 	struct drm_mm_node *gtt_space = &vma->node;
   3390 	struct drm_mm_node *other;
   3391 
   3392 	/*
   3393 	 * On some machines we have to be careful when putting differing types
   3394 	 * of snoopable memory together to avoid the prefetcher crossing memory
   3395 	 * domains and dying. During vm initialisation, we decide whether or not
   3396 	 * these constraints apply and set the drm_mm.color_adjust
   3397 	 * appropriately.
   3398 	 */
   3399 	if (vma->vm->mm.color_adjust == NULL)
   3400 		return true;
   3401 
   3402 	if (!drm_mm_node_allocated(gtt_space))
   3403 		return true;
   3404 
   3405 	if (list_empty(&gtt_space->node_list))
   3406 		return true;
   3407 
   3408 	other = list_entry(gtt_space->node_list.prev, struct drm_mm_node, node_list);
   3409 	if (other->allocated && !other->hole_follows && other->color != cache_level)
   3410 		return false;
   3411 
   3412 	other = list_entry(gtt_space->node_list.next, struct drm_mm_node, node_list);
   3413 	if (other->allocated && !gtt_space->hole_follows && other->color != cache_level)
   3414 		return false;
   3415 
   3416 	return true;
   3417 }
   3418 
   3419 /**
   3420  * Finds free space in the GTT aperture and binds the object or a view of it
   3421  * there.
   3422  */
   3423 static struct i915_vma *
   3424 i915_gem_object_bind_to_vm(struct drm_i915_gem_object *obj,
   3425 			   struct i915_address_space *vm,
   3426 			   const struct i915_ggtt_view *ggtt_view,
   3427 			   unsigned alignment,
   3428 			   uint64_t flags)
   3429 {
   3430 	struct drm_device *dev = obj->base.dev;
   3431 	struct drm_i915_private *dev_priv = dev->dev_private;
   3432 	u32 fence_alignment, unfenced_alignment;
   3433 	u32 search_flag, alloc_flag;
   3434 	u64 start, end;
   3435 	u64 size, fence_size;
   3436 	struct i915_vma *vma;
   3437 	int ret;
   3438 
   3439 	if (i915_is_ggtt(vm)) {
   3440 		u32 view_size;
   3441 
   3442 		if (WARN_ON(!ggtt_view))
   3443 			return ERR_PTR(-EINVAL);
   3444 
   3445 		view_size = i915_ggtt_view_size(obj, ggtt_view);
   3446 
   3447 		fence_size = i915_gem_get_gtt_size(dev,
   3448 						   view_size,
   3449 						   obj->tiling_mode);
   3450 		fence_alignment = i915_gem_get_gtt_alignment(dev,
   3451 							     view_size,
   3452 							     obj->tiling_mode,
   3453 							     true);
   3454 		unfenced_alignment = i915_gem_get_gtt_alignment(dev,
   3455 								view_size,
   3456 								obj->tiling_mode,
   3457 								false);
   3458 		size = flags & PIN_MAPPABLE ? fence_size : view_size;
   3459 	} else {
   3460 		fence_size = i915_gem_get_gtt_size(dev,
   3461 						   obj->base.size,
   3462 						   obj->tiling_mode);
   3463 		fence_alignment = i915_gem_get_gtt_alignment(dev,
   3464 							     obj->base.size,
   3465 							     obj->tiling_mode,
   3466 							     true);
   3467 		unfenced_alignment =
   3468 			i915_gem_get_gtt_alignment(dev,
   3469 						   obj->base.size,
   3470 						   obj->tiling_mode,
   3471 						   false);
   3472 		size = flags & PIN_MAPPABLE ? fence_size : obj->base.size;
   3473 	}
   3474 
   3475 	start = flags & PIN_OFFSET_BIAS ? flags & PIN_OFFSET_MASK : 0;
   3476 	end = vm->total;
   3477 	if (flags & PIN_MAPPABLE)
   3478 		end = min_t(u64, end, dev_priv->gtt.mappable_end);
   3479 	if (flags & PIN_ZONE_4G)
   3480 		end = min_t(u64, end, (1ULL << 32));
   3481 
   3482 	if (alignment == 0)
   3483 		alignment = flags & PIN_MAPPABLE ? fence_alignment :
   3484 						unfenced_alignment;
   3485 	if (flags & PIN_MAPPABLE && alignment & (fence_alignment - 1)) {
   3486 		DRM_DEBUG("Invalid object (view type=%u) alignment requested %u\n",
   3487 			  ggtt_view ? ggtt_view->type : 0,
   3488 			  alignment);
   3489 		return ERR_PTR(-EINVAL);
   3490 	}
   3491 
   3492 	/* If binding the object/GGTT view requires more space than the entire
   3493 	 * aperture has, reject it early before evicting everything in a vain
   3494 	 * attempt to find space.
   3495 	 */
   3496 	if (size > end) {
   3497 		DRM_DEBUG("Attempting to bind an object (view type=%u) larger than the aperture: size=%llu > %s aperture=%llu\n",
   3498 			  ggtt_view ? ggtt_view->type : 0,
   3499 			  size,
   3500 			  flags & PIN_MAPPABLE ? "mappable" : "total",
   3501 			  end);
   3502 		return ERR_PTR(-E2BIG);
   3503 	}
   3504 
   3505 	ret = i915_gem_object_get_pages(obj);
   3506 	if (ret)
   3507 		return ERR_PTR(ret);
   3508 
   3509 	i915_gem_object_pin_pages(obj);
   3510 
   3511 	vma = ggtt_view ? i915_gem_obj_lookup_or_create_ggtt_vma(obj, ggtt_view) :
   3512 			  i915_gem_obj_lookup_or_create_vma(obj, vm);
   3513 
   3514 	if (IS_ERR(vma))
   3515 		goto err_unpin;
   3516 
   3517 	if (flags & PIN_HIGH) {
   3518 		search_flag = DRM_MM_SEARCH_BELOW;
   3519 		alloc_flag = DRM_MM_CREATE_TOP;
   3520 	} else {
   3521 		search_flag = DRM_MM_SEARCH_DEFAULT;
   3522 		alloc_flag = DRM_MM_CREATE_DEFAULT;
   3523 	}
   3524 
   3525 search_free:
   3526 	ret = drm_mm_insert_node_in_range_generic(&vm->mm, &vma->node,
   3527 						  size, alignment,
   3528 						  obj->cache_level,
   3529 						  start, end,
   3530 						  search_flag,
   3531 						  alloc_flag);
   3532 	if (ret) {
   3533 		ret = i915_gem_evict_something(dev, vm, size, alignment,
   3534 					       obj->cache_level,
   3535 					       start, end,
   3536 					       flags);
   3537 		if (ret == 0)
   3538 			goto search_free;
   3539 
   3540 		goto err_free_vma;
   3541 	}
   3542 	if (WARN_ON(!i915_gem_valid_gtt_space(vma, obj->cache_level))) {
   3543 		ret = -EINVAL;
   3544 		goto err_remove_node;
   3545 	}
   3546 
   3547 	trace_i915_vma_bind(vma, flags);
   3548 	ret = i915_vma_bind(vma, obj->cache_level, flags);
   3549 	if (ret)
   3550 		goto err_remove_node;
   3551 
   3552 	list_move_tail(&obj->global_list, &dev_priv->mm.bound_list);
   3553 	list_add_tail(&vma->mm_list, &vm->inactive_list);
   3554 
   3555 	return vma;
   3556 
   3557 err_remove_node:
   3558 	drm_mm_remove_node(&vma->node);
   3559 err_free_vma:
   3560 	i915_gem_vma_destroy(vma);
   3561 	vma = ERR_PTR(ret);
   3562 err_unpin:
   3563 	i915_gem_object_unpin_pages(obj);
   3564 	return vma;
   3565 }
   3566 
   3567 bool
   3568 i915_gem_clflush_object(struct drm_i915_gem_object *obj,
   3569 			bool force)
   3570 {
   3571 	/* If we don't have a page list set up, then we're not pinned
   3572 	 * to GPU, and we can ignore the cache flush because it'll happen
   3573 	 * again at bind time.
   3574 	 */
   3575 	if (obj->pages == NULL)
   3576 		return false;
   3577 
   3578 	/*
   3579 	 * Stolen memory is always coherent with the GPU as it is explicitly
   3580 	 * marked as wc by the system, or the system is cache-coherent.
   3581 	 */
   3582 	if (obj->stolen || obj->phys_handle)
   3583 		return false;
   3584 
   3585 	/* If the GPU is snooping the contents of the CPU cache,
   3586 	 * we do not need to manually clear the CPU cache lines.  However,
   3587 	 * the caches are only snooped when the render cache is
   3588 	 * flushed/invalidated.  As we always have to emit invalidations
   3589 	 * and flushes when moving into and out of the RENDER domain, correct
   3590 	 * snooping behaviour occurs naturally as the result of our domain
   3591 	 * tracking.
   3592 	 */
   3593 	if (!force && cpu_cache_is_coherent(obj->base.dev, obj->cache_level)) {
   3594 		obj->cache_dirty = true;
   3595 		return false;
   3596 	}
   3597 
   3598 	trace_i915_gem_object_clflush(obj);
   3599 	drm_clflush_sg(obj->pages);
   3600 	obj->cache_dirty = false;
   3601 
   3602 	return true;
   3603 }
   3604 
   3605 /** Flushes the GTT write domain for the object if it's dirty. */
   3606 static void
   3607 i915_gem_object_flush_gtt_write_domain(struct drm_i915_gem_object *obj)
   3608 {
   3609 	uint32_t old_write_domain;
   3610 
   3611 	if (obj->base.write_domain != I915_GEM_DOMAIN_GTT)
   3612 		return;
   3613 
   3614 	/* No actual flushing is required for the GTT write domain.  Writes
   3615 	 * to it immediately go to main memory as far as we know, so there's
   3616 	 * no chipset flush.  It also doesn't land in render cache.
   3617 	 *
   3618 	 * However, we do have to enforce the order so that all writes through
   3619 	 * the GTT land before any writes to the device, such as updates to
   3620 	 * the GATT itself.
   3621 	 */
   3622 	wmb();
   3623 
   3624 	old_write_domain = obj->base.write_domain;
   3625 	obj->base.write_domain = 0;
   3626 
   3627 	intel_fb_obj_flush(obj, false, ORIGIN_GTT);
   3628 
   3629 	trace_i915_gem_object_change_domain(obj,
   3630 					    obj->base.read_domains,
   3631 					    old_write_domain);
   3632 }
   3633 
   3634 /** Flushes the CPU write domain for the object if it's dirty. */
   3635 static void
   3636 i915_gem_object_flush_cpu_write_domain(struct drm_i915_gem_object *obj)
   3637 {
   3638 	uint32_t old_write_domain;
   3639 
   3640 	if (obj->base.write_domain != I915_GEM_DOMAIN_CPU)
   3641 		return;
   3642 
   3643 	if (i915_gem_clflush_object(obj, obj->pin_display))
   3644 		i915_gem_chipset_flush(obj->base.dev);
   3645 
   3646 	old_write_domain = obj->base.write_domain;
   3647 	obj->base.write_domain = 0;
   3648 
   3649 	intel_fb_obj_flush(obj, false, ORIGIN_CPU);
   3650 
   3651 	trace_i915_gem_object_change_domain(obj,
   3652 					    obj->base.read_domains,
   3653 					    old_write_domain);
   3654 }
   3655 
   3656 /**
   3657  * Moves a single object to the GTT read, and possibly write domain.
   3658  *
   3659  * This function returns when the move is complete, including waiting on
   3660  * flushes to occur.
   3661  */
   3662 int
   3663 i915_gem_object_set_to_gtt_domain(struct drm_i915_gem_object *obj, bool write)
   3664 {
   3665 	uint32_t old_write_domain, old_read_domains;
   3666 	struct i915_vma *vma;
   3667 	int ret;
   3668 
   3669 	if (obj->base.write_domain == I915_GEM_DOMAIN_GTT)
   3670 		return 0;
   3671 
   3672 	ret = i915_gem_object_wait_rendering(obj, !write);
   3673 	if (ret)
   3674 		return ret;
   3675 
   3676 	/* Flush and acquire obj->pages so that we are coherent through
   3677 	 * direct access in memory with previous cached writes through
   3678 	 * shmemfs and that our cache domain tracking remains valid.
   3679 	 * For example, if the obj->filp was moved to swap without us
   3680 	 * being notified and releasing the pages, we would mistakenly
   3681 	 * continue to assume that the obj remained out of the CPU cached
   3682 	 * domain.
   3683 	 */
   3684 	ret = i915_gem_object_get_pages(obj);
   3685 	if (ret)
   3686 		return ret;
   3687 
   3688 	i915_gem_object_flush_cpu_write_domain(obj);
   3689 
   3690 	/* Serialise direct access to this object with the barriers for
   3691 	 * coherent writes from the GPU, by effectively invalidating the
   3692 	 * GTT domain upon first access.
   3693 	 */
   3694 	if ((obj->base.read_domains & I915_GEM_DOMAIN_GTT) == 0)
   3695 		mb();
   3696 
   3697 	old_write_domain = obj->base.write_domain;
   3698 	old_read_domains = obj->base.read_domains;
   3699 
   3700 	/* It should now be out of any other write domains, and we can update
   3701 	 * the domain values for our changes.
   3702 	 */
   3703 	BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
   3704 	obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
   3705 	if (write) {
   3706 		obj->base.read_domains = I915_GEM_DOMAIN_GTT;
   3707 		obj->base.write_domain = I915_GEM_DOMAIN_GTT;
   3708 		obj->dirty = 1;
   3709 	}
   3710 
   3711 	trace_i915_gem_object_change_domain(obj,
   3712 					    old_read_domains,
   3713 					    old_write_domain);
   3714 
   3715 	/* And bump the LRU for this access */
   3716 	vma = i915_gem_obj_to_ggtt(obj);
   3717 	if (vma && drm_mm_node_allocated(&vma->node) && !obj->active)
   3718 		list_move_tail(&vma->mm_list,
   3719 			       &to_i915(obj->base.dev)->gtt.base.inactive_list);
   3720 
   3721 	return 0;
   3722 }
   3723 
   3724 /**
   3725  * Changes the cache-level of an object across all VMA.
   3726  *
   3727  * After this function returns, the object will be in the new cache-level
   3728  * across all GTT and the contents of the backing storage will be coherent,
   3729  * with respect to the new cache-level. In order to keep the backing storage
   3730  * coherent for all users, we only allow a single cache level to be set
   3731  * globally on the object and prevent it from being changed whilst the
   3732  * hardware is reading from the object. That is if the object is currently
   3733  * on the scanout it will be set to uncached (or equivalent display
   3734  * cache coherency) and all non-MOCS GPU access will also be uncached so
   3735  * that all direct access to the scanout remains coherent.
   3736  */
   3737 int i915_gem_object_set_cache_level(struct drm_i915_gem_object *obj,
   3738 				    enum i915_cache_level cache_level)
   3739 {
   3740 	struct drm_device *dev = obj->base.dev;
   3741 	struct i915_vma *vma, *next;
   3742 	bool bound = false;
   3743 	int ret = 0;
   3744 
   3745 	if (obj->cache_level == cache_level)
   3746 		goto out;
   3747 
   3748 	/* Inspect the list of currently bound VMA and unbind any that would
   3749 	 * be invalid given the new cache-level. This is principally to
   3750 	 * catch the issue of the CS prefetch crossing page boundaries and
   3751 	 * reading an invalid PTE on older architectures.
   3752 	 */
   3753 	list_for_each_entry_safe(vma, next, &obj->vma_list, vma_link) {
   3754 		if (!drm_mm_node_allocated(&vma->node))
   3755 			continue;
   3756 
   3757 		if (vma->pin_count) {
   3758 			DRM_DEBUG("can not change the cache level of pinned objects\n");
   3759 			return -EBUSY;
   3760 		}
   3761 
   3762 		if (!i915_gem_valid_gtt_space(vma, cache_level)) {
   3763 			ret = i915_vma_unbind(vma);
   3764 			if (ret)
   3765 				return ret;
   3766 		} else
   3767 			bound = true;
   3768 	}
   3769 
   3770 	/* We can reuse the existing drm_mm nodes but need to change the
   3771 	 * cache-level on the PTE. We could simply unbind them all and
   3772 	 * rebind with the correct cache-level on next use. However since
   3773 	 * we already have a valid slot, dma mapping, pages etc, we may as
   3774 	 * rewrite the PTE in the belief that doing so tramples upon less
   3775 	 * state and so involves less work.
   3776 	 */
   3777 	if (bound) {
   3778 		/* Before we change the PTE, the GPU must not be accessing it.
   3779 		 * If we wait upon the object, we know that all the bound
   3780 		 * VMA are no longer active.
   3781 		 */
   3782 		ret = i915_gem_object_wait_rendering(obj, false);
   3783 		if (ret)
   3784 			return ret;
   3785 
   3786 		if (!HAS_LLC(dev) && cache_level != I915_CACHE_NONE) {
   3787 			/* Access to snoopable pages through the GTT is
   3788 			 * incoherent and on some machines causes a hard
   3789 			 * lockup. Relinquish the CPU mmaping to force
   3790 			 * userspace to refault in the pages and we can
   3791 			 * then double check if the GTT mapping is still
   3792 			 * valid for that pointer access.
   3793 			 */
   3794 			i915_gem_release_mmap(obj);
   3795 
   3796 			/* As we no longer need a fence for GTT access,
   3797 			 * we can relinquish it now (and so prevent having
   3798 			 * to steal a fence from someone else on the next
   3799 			 * fence request). Note GPU activity would have
   3800 			 * dropped the fence as all snoopable access is
   3801 			 * supposed to be linear.
   3802 			 */
   3803 			ret = i915_gem_object_put_fence(obj);
   3804 			if (ret)
   3805 				return ret;
   3806 		} else {
   3807 			/* We either have incoherent backing store and
   3808 			 * so no GTT access or the architecture is fully
   3809 			 * coherent. In such cases, existing GTT mmaps
   3810 			 * ignore the cache bit in the PTE and we can
   3811 			 * rewrite it without confusing the GPU or having
   3812 			 * to force userspace to fault back in its mmaps.
   3813 			 */
   3814 		}
   3815 
   3816 		list_for_each_entry(vma, &obj->vma_list, vma_link) {
   3817 			if (!drm_mm_node_allocated(&vma->node))
   3818 				continue;
   3819 
   3820 			ret = i915_vma_bind(vma, cache_level, PIN_UPDATE);
   3821 			if (ret)
   3822 				return ret;
   3823 		}
   3824 	}
   3825 
   3826 	list_for_each_entry(vma, &obj->vma_list, vma_link)
   3827 		vma->node.color = cache_level;
   3828 	obj->cache_level = cache_level;
   3829 
   3830 out:
   3831 	/* Flush the dirty CPU caches to the backing storage so that the
   3832 	 * object is now coherent at its new cache level (with respect
   3833 	 * to the access domain).
   3834 	 */
   3835 	if (obj->cache_dirty &&
   3836 	    obj->base.write_domain != I915_GEM_DOMAIN_CPU &&
   3837 	    cpu_write_needs_clflush(obj)) {
   3838 		if (i915_gem_clflush_object(obj, true))
   3839 			i915_gem_chipset_flush(obj->base.dev);
   3840 	}
   3841 
   3842 	return 0;
   3843 }
   3844 
   3845 int i915_gem_get_caching_ioctl(struct drm_device *dev, void *data,
   3846 			       struct drm_file *file)
   3847 {
   3848 	struct drm_i915_gem_caching *args = data;
   3849 	struct drm_i915_gem_object *obj;
   3850 
   3851 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
   3852 	if (&obj->base == NULL)
   3853 		return -ENOENT;
   3854 
   3855 	switch (obj->cache_level) {
   3856 	case I915_CACHE_LLC:
   3857 	case I915_CACHE_L3_LLC:
   3858 		args->caching = I915_CACHING_CACHED;
   3859 		break;
   3860 
   3861 	case I915_CACHE_WT:
   3862 		args->caching = I915_CACHING_DISPLAY;
   3863 		break;
   3864 
   3865 	default:
   3866 		args->caching = I915_CACHING_NONE;
   3867 		break;
   3868 	}
   3869 
   3870 	drm_gem_object_unreference_unlocked(&obj->base);
   3871 	return 0;
   3872 }
   3873 
   3874 int i915_gem_set_caching_ioctl(struct drm_device *dev, void *data,
   3875 			       struct drm_file *file)
   3876 {
   3877 	struct drm_i915_private *dev_priv = dev->dev_private;
   3878 	struct drm_i915_gem_caching *args = data;
   3879 	struct drm_i915_gem_object *obj;
   3880 	enum i915_cache_level level;
   3881 	int ret;
   3882 
   3883 	switch (args->caching) {
   3884 	case I915_CACHING_NONE:
   3885 		level = I915_CACHE_NONE;
   3886 		break;
   3887 	case I915_CACHING_CACHED:
   3888 		/*
   3889 		 * Due to a HW issue on BXT A stepping, GPU stores via a
   3890 		 * snooped mapping may leave stale data in a corresponding CPU
   3891 		 * cacheline, whereas normally such cachelines would get
   3892 		 * invalidated.
   3893 		 */
   3894 		if (IS_BROXTON(dev) && INTEL_REVID(dev) < BXT_REVID_B0)
   3895 			return -ENODEV;
   3896 
   3897 		level = I915_CACHE_LLC;
   3898 		break;
   3899 	case I915_CACHING_DISPLAY:
   3900 		level = HAS_WT(dev) ? I915_CACHE_WT : I915_CACHE_NONE;
   3901 		break;
   3902 	default:
   3903 		return -EINVAL;
   3904 	}
   3905 
   3906 	intel_runtime_pm_get(dev_priv);
   3907 
   3908 	ret = i915_mutex_lock_interruptible(dev);
   3909 	if (ret)
   3910 		goto rpm_put;
   3911 
   3912 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
   3913 	if (&obj->base == NULL) {
   3914 		ret = -ENOENT;
   3915 		goto unlock;
   3916 	}
   3917 
   3918 	ret = i915_gem_object_set_cache_level(obj, level);
   3919 
   3920 	drm_gem_object_unreference(&obj->base);
   3921 unlock:
   3922 	mutex_unlock(&dev->struct_mutex);
   3923 rpm_put:
   3924 	intel_runtime_pm_put(dev_priv);
   3925 
   3926 	return ret;
   3927 }
   3928 
   3929 /*
   3930  * Prepare buffer for display plane (scanout, cursors, etc).
   3931  * Can be called from an uninterruptible phase (modesetting) and allows
   3932  * any flushes to be pipelined (for pageflips).
   3933  */
   3934 int
   3935 i915_gem_object_pin_to_display_plane(struct drm_i915_gem_object *obj,
   3936 				     u32 alignment,
   3937 				     struct intel_engine_cs *pipelined,
   3938 				     struct drm_i915_gem_request **pipelined_request,
   3939 				     const struct i915_ggtt_view *view)
   3940 {
   3941 	u32 old_read_domains, old_write_domain;
   3942 	int ret;
   3943 
   3944 	ret = i915_gem_object_sync(obj, pipelined, pipelined_request);
   3945 	if (ret)
   3946 		return ret;
   3947 
   3948 	/* Mark the pin_display early so that we account for the
   3949 	 * display coherency whilst setting up the cache domains.
   3950 	 */
   3951 	obj->pin_display++;
   3952 
   3953 	/* The display engine is not coherent with the LLC cache on gen6.  As
   3954 	 * a result, we make sure that the pinning that is about to occur is
   3955 	 * done with uncached PTEs. This is lowest common denominator for all
   3956 	 * chipsets.
   3957 	 *
   3958 	 * However for gen6+, we could do better by using the GFDT bit instead
   3959 	 * of uncaching, which would allow us to flush all the LLC-cached data
   3960 	 * with that bit in the PTE to main memory with just one PIPE_CONTROL.
   3961 	 */
   3962 	ret = i915_gem_object_set_cache_level(obj,
   3963 					      HAS_WT(obj->base.dev) ? I915_CACHE_WT : I915_CACHE_NONE);
   3964 	if (ret)
   3965 		goto err_unpin_display;
   3966 
   3967 	/* As the user may map the buffer once pinned in the display plane
   3968 	 * (e.g. libkms for the bootup splash), we have to ensure that we
   3969 	 * always use map_and_fenceable for all scanout buffers.
   3970 	 */
   3971 	ret = i915_gem_object_ggtt_pin(obj, view, alignment,
   3972 				       view->type == I915_GGTT_VIEW_NORMAL ?
   3973 				       PIN_MAPPABLE : 0);
   3974 	if (ret)
   3975 		goto err_unpin_display;
   3976 
   3977 	i915_gem_object_flush_cpu_write_domain(obj);
   3978 
   3979 	old_write_domain = obj->base.write_domain;
   3980 	old_read_domains = obj->base.read_domains;
   3981 
   3982 	/* It should now be out of any other write domains, and we can update
   3983 	 * the domain values for our changes.
   3984 	 */
   3985 	obj->base.write_domain = 0;
   3986 	obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
   3987 
   3988 	trace_i915_gem_object_change_domain(obj,
   3989 					    old_read_domains,
   3990 					    old_write_domain);
   3991 
   3992 	return 0;
   3993 
   3994 err_unpin_display:
   3995 	obj->pin_display--;
   3996 	return ret;
   3997 }
   3998 
   3999 void
   4000 i915_gem_object_unpin_from_display_plane(struct drm_i915_gem_object *obj,
   4001 					 const struct i915_ggtt_view *view)
   4002 {
   4003 	if (WARN_ON(obj->pin_display == 0))
   4004 		return;
   4005 
   4006 	i915_gem_object_ggtt_unpin_view(obj, view);
   4007 
   4008 	obj->pin_display--;
   4009 }
   4010 
   4011 /**
   4012  * Moves a single object to the CPU read, and possibly write domain.
   4013  *
   4014  * This function returns when the move is complete, including waiting on
   4015  * flushes to occur.
   4016  */
   4017 int
   4018 i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj, bool write)
   4019 {
   4020 	uint32_t old_write_domain, old_read_domains;
   4021 	int ret;
   4022 
   4023 	if (obj->base.write_domain == I915_GEM_DOMAIN_CPU)
   4024 		return 0;
   4025 
   4026 	ret = i915_gem_object_wait_rendering(obj, !write);
   4027 	if (ret)
   4028 		return ret;
   4029 
   4030 	i915_gem_object_flush_gtt_write_domain(obj);
   4031 
   4032 	old_write_domain = obj->base.write_domain;
   4033 	old_read_domains = obj->base.read_domains;
   4034 
   4035 	/* Flush the CPU cache if it's still invalid. */
   4036 	if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0) {
   4037 		i915_gem_clflush_object(obj, false);
   4038 
   4039 		obj->base.read_domains |= I915_GEM_DOMAIN_CPU;
   4040 	}
   4041 
   4042 	/* It should now be out of any other write domains, and we can update
   4043 	 * the domain values for our changes.
   4044 	 */
   4045 	BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
   4046 
   4047 	/* If we're writing through the CPU, then the GPU read domains will
   4048 	 * need to be invalidated at next use.
   4049 	 */
   4050 	if (write) {
   4051 		obj->base.read_domains = I915_GEM_DOMAIN_CPU;
   4052 		obj->base.write_domain = I915_GEM_DOMAIN_CPU;
   4053 	}
   4054 
   4055 	trace_i915_gem_object_change_domain(obj,
   4056 					    old_read_domains,
   4057 					    old_write_domain);
   4058 
   4059 	return 0;
   4060 }
   4061 
   4062 /* Throttle our rendering by waiting until the ring has completed our requests
   4063  * emitted over 20 msec ago.
   4064  *
   4065  * Note that if we were to use the current jiffies each time around the loop,
   4066  * we wouldn't escape the function with any frames outstanding if the time to
   4067  * render a frame was over 20ms.
   4068  *
   4069  * This should get us reasonable parallelism between CPU and GPU but also
   4070  * relatively low latency when blocking on a particular request to finish.
   4071  */
   4072 static int
   4073 i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file)
   4074 {
   4075 	struct drm_i915_private *dev_priv = dev->dev_private;
   4076 	struct drm_i915_file_private *file_priv = file->driver_priv;
   4077 	unsigned long recent_enough = jiffies - DRM_I915_THROTTLE_JIFFIES;
   4078 	struct drm_i915_gem_request *request, *target = NULL;
   4079 	unsigned reset_counter;
   4080 	int ret;
   4081 
   4082 	ret = i915_gem_wait_for_error(&dev_priv->gpu_error);
   4083 	if (ret)
   4084 		return ret;
   4085 
   4086 	ret = i915_gem_check_wedge(&dev_priv->gpu_error, false);
   4087 	if (ret)
   4088 		return ret;
   4089 
   4090 	spin_lock(&file_priv->mm.lock);
   4091 	list_for_each_entry(request, &file_priv->mm.request_list, client_list) {
   4092 		if (time_after_eq(request->emitted_jiffies, recent_enough))
   4093 			break;
   4094 
   4095 		/*
   4096 		 * Note that the request might not have been submitted yet.
   4097 		 * In which case emitted_jiffies will be zero.
   4098 		 */
   4099 		if (!request->emitted_jiffies)
   4100 			continue;
   4101 
   4102 		target = request;
   4103 	}
   4104 	reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
   4105 	if (target)
   4106 		i915_gem_request_reference(target);
   4107 	spin_unlock(&file_priv->mm.lock);
   4108 
   4109 	if (target == NULL)
   4110 		return 0;
   4111 
   4112 	ret = __i915_wait_request(target, reset_counter, true, NULL, NULL);
   4113 	if (ret == 0)
   4114 		queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, 0);
   4115 
   4116 	i915_gem_request_unreference__unlocked(target);
   4117 
   4118 	return ret;
   4119 }
   4120 
   4121 static bool
   4122 i915_vma_misplaced(struct i915_vma *vma, uint32_t alignment, uint64_t flags)
   4123 {
   4124 	struct drm_i915_gem_object *obj = vma->obj;
   4125 
   4126 	if (alignment &&
   4127 	    vma->node.start & (alignment - 1))
   4128 		return true;
   4129 
   4130 	if (flags & PIN_MAPPABLE && !obj->map_and_fenceable)
   4131 		return true;
   4132 
   4133 	if (flags & PIN_OFFSET_BIAS &&
   4134 	    vma->node.start < (flags & PIN_OFFSET_MASK))
   4135 		return true;
   4136 
   4137 	return false;
   4138 }
   4139 
   4140 void __i915_vma_set_map_and_fenceable(struct i915_vma *vma)
   4141 {
   4142 	struct drm_i915_gem_object *obj = vma->obj;
   4143 	bool mappable, fenceable;
   4144 	u32 fence_size, fence_alignment;
   4145 
   4146 	fence_size = i915_gem_get_gtt_size(obj->base.dev,
   4147 					   obj->base.size,
   4148 					   obj->tiling_mode);
   4149 	fence_alignment = i915_gem_get_gtt_alignment(obj->base.dev,
   4150 						     obj->base.size,
   4151 						     obj->tiling_mode,
   4152 						     true);
   4153 
   4154 	fenceable = (vma->node.size == fence_size &&
   4155 		     (vma->node.start & (fence_alignment - 1)) == 0);
   4156 
   4157 	mappable = (vma->node.start + fence_size <=
   4158 		    to_i915(obj->base.dev)->gtt.mappable_end);
   4159 
   4160 	obj->map_and_fenceable = mappable && fenceable;
   4161 }
   4162 
   4163 static int
   4164 i915_gem_object_do_pin(struct drm_i915_gem_object *obj,
   4165 		       struct i915_address_space *vm,
   4166 		       const struct i915_ggtt_view *ggtt_view,
   4167 		       uint32_t alignment,
   4168 		       uint64_t flags)
   4169 {
   4170 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   4171 	struct i915_vma *vma;
   4172 	unsigned bound;
   4173 	int ret;
   4174 
   4175 	if (WARN_ON(vm == &dev_priv->mm.aliasing_ppgtt->base))
   4176 		return -ENODEV;
   4177 
   4178 	if (WARN_ON(flags & (PIN_GLOBAL | PIN_MAPPABLE) && !i915_is_ggtt(vm)))
   4179 		return -EINVAL;
   4180 
   4181 	if (WARN_ON((flags & (PIN_MAPPABLE | PIN_GLOBAL)) == PIN_MAPPABLE))
   4182 		return -EINVAL;
   4183 
   4184 	if (WARN_ON(i915_is_ggtt(vm) != !!ggtt_view))
   4185 		return -EINVAL;
   4186 
   4187 	vma = ggtt_view ? i915_gem_obj_to_ggtt_view(obj, ggtt_view) :
   4188 			  i915_gem_obj_to_vma(obj, vm);
   4189 
   4190 	if (IS_ERR(vma))
   4191 		return PTR_ERR(vma);
   4192 
   4193 	if (vma) {
   4194 		if (WARN_ON(vma->pin_count == DRM_I915_GEM_OBJECT_MAX_PIN_COUNT))
   4195 			return -EBUSY;
   4196 
   4197 		if (i915_vma_misplaced(vma, alignment, flags)) {
   4198 			WARN(vma->pin_count,
   4199 			     "bo is already pinned in %s with incorrect alignment:"
   4200 			     " offset=%08x %08x, req.alignment=%x, req.map_and_fenceable=%d,"
   4201 			     " obj->map_and_fenceable=%d\n",
   4202 			     ggtt_view ? "ggtt" : "ppgtt",
   4203 			     upper_32_bits(vma->node.start),
   4204 			     lower_32_bits(vma->node.start),
   4205 			     alignment,
   4206 			     !!(flags & PIN_MAPPABLE),
   4207 			     obj->map_and_fenceable);
   4208 			ret = i915_vma_unbind(vma);
   4209 			if (ret)
   4210 				return ret;
   4211 
   4212 			vma = NULL;
   4213 		}
   4214 	}
   4215 
   4216 	bound = vma ? vma->bound : 0;
   4217 	if (vma == NULL || !drm_mm_node_allocated(&vma->node)) {
   4218 		vma = i915_gem_object_bind_to_vm(obj, vm, ggtt_view, alignment,
   4219 						 flags);
   4220 		if (IS_ERR(vma))
   4221 			return PTR_ERR(vma);
   4222 	} else {
   4223 		ret = i915_vma_bind(vma, obj->cache_level, flags);
   4224 		if (ret)
   4225 			return ret;
   4226 	}
   4227 
   4228 	if (ggtt_view && ggtt_view->type == I915_GGTT_VIEW_NORMAL &&
   4229 	    (bound ^ vma->bound) & GLOBAL_BIND) {
   4230 		__i915_vma_set_map_and_fenceable(vma);
   4231 		WARN_ON(flags & PIN_MAPPABLE && !obj->map_and_fenceable);
   4232 	}
   4233 
   4234 	vma->pin_count++;
   4235 	return 0;
   4236 }
   4237 
   4238 int
   4239 i915_gem_object_pin(struct drm_i915_gem_object *obj,
   4240 		    struct i915_address_space *vm,
   4241 		    uint32_t alignment,
   4242 		    uint64_t flags)
   4243 {
   4244 	return i915_gem_object_do_pin(obj, vm,
   4245 				      i915_is_ggtt(vm) ? &i915_ggtt_view_normal : NULL,
   4246 				      alignment, flags);
   4247 }
   4248 
   4249 int
   4250 i915_gem_object_ggtt_pin(struct drm_i915_gem_object *obj,
   4251 			 const struct i915_ggtt_view *view,
   4252 			 uint32_t alignment,
   4253 			 uint64_t flags)
   4254 {
   4255 	if (WARN_ONCE(!view, "no view specified"))
   4256 		return -EINVAL;
   4257 
   4258 	return i915_gem_object_do_pin(obj, i915_obj_to_ggtt(obj), view,
   4259 				      alignment, flags | PIN_GLOBAL);
   4260 }
   4261 
   4262 void
   4263 i915_gem_object_ggtt_unpin_view(struct drm_i915_gem_object *obj,
   4264 				const struct i915_ggtt_view *view)
   4265 {
   4266 	struct i915_vma *vma = i915_gem_obj_to_ggtt_view(obj, view);
   4267 
   4268 	BUG_ON(!vma);
   4269 	WARN_ON(vma->pin_count == 0);
   4270 	WARN_ON(!i915_gem_obj_ggtt_bound_view(obj, view));
   4271 
   4272 	--vma->pin_count;
   4273 }
   4274 
   4275 int
   4276 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
   4277 		    struct drm_file *file)
   4278 {
   4279 	struct drm_i915_gem_busy *args = data;
   4280 	struct drm_i915_gem_object *obj;
   4281 	int ret;
   4282 
   4283 	ret = i915_mutex_lock_interruptible(dev);
   4284 	if (ret)
   4285 		return ret;
   4286 
   4287 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
   4288 	if (&obj->base == NULL) {
   4289 		ret = -ENOENT;
   4290 		goto unlock;
   4291 	}
   4292 
   4293 	/* Count all active objects as busy, even if they are currently not used
   4294 	 * by the gpu. Users of this interface expect objects to eventually
   4295 	 * become non-busy without any further actions, therefore emit any
   4296 	 * necessary flushes here.
   4297 	 */
   4298 	ret = i915_gem_object_flush_active(obj);
   4299 	if (ret)
   4300 		goto unref;
   4301 
   4302 	BUILD_BUG_ON(I915_NUM_RINGS > 16);
   4303 	args->busy = obj->active << 16;
   4304 	if (obj->last_write_req)
   4305 		args->busy |= obj->last_write_req->ring->id;
   4306 
   4307 unref:
   4308 	drm_gem_object_unreference(&obj->base);
   4309 unlock:
   4310 	mutex_unlock(&dev->struct_mutex);
   4311 	return ret;
   4312 }
   4313 
   4314 int
   4315 i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
   4316 			struct drm_file *file_priv)
   4317 {
   4318 	return i915_gem_ring_throttle(dev, file_priv);
   4319 }
   4320 
   4321 int
   4322 i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
   4323 		       struct drm_file *file_priv)
   4324 {
   4325 	struct drm_i915_private *dev_priv = dev->dev_private;
   4326 	struct drm_i915_gem_madvise *args = data;
   4327 	struct drm_i915_gem_object *obj;
   4328 	int ret;
   4329 
   4330 	switch (args->madv) {
   4331 	case I915_MADV_DONTNEED:
   4332 	case I915_MADV_WILLNEED:
   4333 	    break;
   4334 	default:
   4335 	    return -EINVAL;
   4336 	}
   4337 
   4338 	ret = i915_mutex_lock_interruptible(dev);
   4339 	if (ret)
   4340 		return ret;
   4341 
   4342 	obj = to_intel_bo(drm_gem_object_lookup(dev, file_priv, args->handle));
   4343 	if (&obj->base == NULL) {
   4344 		ret = -ENOENT;
   4345 		goto unlock;
   4346 	}
   4347 
   4348 	if (i915_gem_obj_is_pinned(obj)) {
   4349 		ret = -EINVAL;
   4350 		goto out;
   4351 	}
   4352 
   4353 	if (obj->pages &&
   4354 	    obj->tiling_mode != I915_TILING_NONE &&
   4355 	    dev_priv->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
   4356 		if (obj->madv == I915_MADV_WILLNEED)
   4357 			i915_gem_object_unpin_pages(obj);
   4358 		if (args->madv == I915_MADV_WILLNEED)
   4359 			i915_gem_object_pin_pages(obj);
   4360 	}
   4361 
   4362 	if (obj->madv != __I915_MADV_PURGED)
   4363 		obj->madv = args->madv;
   4364 
   4365 	/* if the object is no longer attached, discard its backing storage */
   4366 	if (obj->madv == I915_MADV_DONTNEED && obj->pages == NULL)
   4367 		i915_gem_object_truncate(obj);
   4368 
   4369 	args->retained = obj->madv != __I915_MADV_PURGED;
   4370 
   4371 out:
   4372 	drm_gem_object_unreference(&obj->base);
   4373 unlock:
   4374 	mutex_unlock(&dev->struct_mutex);
   4375 	return ret;
   4376 }
   4377 
   4378 void i915_gem_object_init(struct drm_i915_gem_object *obj,
   4379 			  const struct drm_i915_gem_object_ops *ops)
   4380 {
   4381 	int i;
   4382 
   4383 	INIT_LIST_HEAD(&obj->global_list);
   4384 	for (i = 0; i < I915_NUM_RINGS; i++)
   4385 		INIT_LIST_HEAD(&obj->ring_list[i]);
   4386 	INIT_LIST_HEAD(&obj->obj_exec_link);
   4387 	INIT_LIST_HEAD(&obj->vma_list);
   4388 	INIT_LIST_HEAD(&obj->batch_pool_link);
   4389 
   4390 	obj->ops = ops;
   4391 
   4392 	obj->fence_reg = I915_FENCE_REG_NONE;
   4393 	obj->madv = I915_MADV_WILLNEED;
   4394 
   4395 	i915_gem_info_add_obj(obj->base.dev->dev_private, obj->base.size);
   4396 }
   4397 
   4398 static const struct drm_i915_gem_object_ops i915_gem_object_ops = {
   4399 	.get_pages = i915_gem_object_get_pages_gtt,
   4400 	.put_pages = i915_gem_object_put_pages_gtt,
   4401 };
   4402 
   4403 struct drm_i915_gem_object *i915_gem_alloc_object(struct drm_device *dev,
   4404 						  size_t size)
   4405 {
   4406 	struct drm_i915_gem_object *obj;
   4407 	struct address_space *mapping;
   4408 	gfp_t mask;
   4409 
   4410 	obj = i915_gem_object_alloc(dev);
   4411 	if (obj == NULL)
   4412 		return NULL;
   4413 
   4414 	if (drm_gem_object_init(dev, &obj->base, size) != 0) {
   4415 		i915_gem_object_free(obj);
   4416 		return NULL;
   4417 	}
   4418 
   4419 	mask = GFP_HIGHUSER | __GFP_RECLAIMABLE;
   4420 	if (IS_CRESTLINE(dev) || IS_BROADWATER(dev)) {
   4421 		/* 965gm cannot relocate objects above 4GiB. */
   4422 		mask &= ~__GFP_HIGHMEM;
   4423 		mask |= __GFP_DMA32;
   4424 	}
   4425 
   4426 	mapping = file_inode(obj->base.filp)->i_mapping;
   4427 	mapping_set_gfp_mask(mapping, mask);
   4428 
   4429 	i915_gem_object_init(obj, &i915_gem_object_ops);
   4430 
   4431 	obj->base.write_domain = I915_GEM_DOMAIN_CPU;
   4432 	obj->base.read_domains = I915_GEM_DOMAIN_CPU;
   4433 
   4434 	if (HAS_LLC(dev)) {
   4435 		/* On some devices, we can have the GPU use the LLC (the CPU
   4436 		 * cache) for about a 10% performance improvement
   4437 		 * compared to uncached.  Graphics requests other than
   4438 		 * display scanout are coherent with the CPU in
   4439 		 * accessing this cache.  This means in this mode we
   4440 		 * don't need to clflush on the CPU side, and on the
   4441 		 * GPU side we only need to flush internal caches to
   4442 		 * get data visible to the CPU.
   4443 		 *
   4444 		 * However, we maintain the display planes as UC, and so
   4445 		 * need to rebind when first used as such.
   4446 		 */
   4447 		obj->cache_level = I915_CACHE_LLC;
   4448 	} else
   4449 		obj->cache_level = I915_CACHE_NONE;
   4450 
   4451 	trace_i915_gem_object_create(obj);
   4452 
   4453 	return obj;
   4454 }
   4455 
   4456 static bool discard_backing_storage(struct drm_i915_gem_object *obj)
   4457 {
   4458 	/* If we are the last user of the backing storage (be it shmemfs
   4459 	 * pages or stolen etc), we know that the pages are going to be
   4460 	 * immediately released. In this case, we can then skip copying
   4461 	 * back the contents from the GPU.
   4462 	 */
   4463 
   4464 	if (obj->madv != I915_MADV_WILLNEED)
   4465 		return false;
   4466 
   4467 	if (obj->base.filp == NULL)
   4468 		return true;
   4469 
   4470 	/* At first glance, this looks racy, but then again so would be
   4471 	 * userspace racing mmap against close. However, the first external
   4472 	 * reference to the filp can only be obtained through the
   4473 	 * i915_gem_mmap_ioctl() which safeguards us against the user
   4474 	 * acquiring such a reference whilst we are in the middle of
   4475 	 * freeing the object.
   4476 	 */
   4477 	return atomic_long_read(&obj->base.filp->f_count) == 1;
   4478 }
   4479 
   4480 void i915_gem_free_object(struct drm_gem_object *gem_obj)
   4481 {
   4482 	struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
   4483 	struct drm_device *dev = obj->base.dev;
   4484 	struct drm_i915_private *dev_priv = dev->dev_private;
   4485 	struct i915_vma *vma, *next;
   4486 
   4487 	intel_runtime_pm_get(dev_priv);
   4488 
   4489 	trace_i915_gem_object_destroy(obj);
   4490 
   4491 	list_for_each_entry_safe(vma, next, &obj->vma_list, vma_link) {
   4492 		int ret;
   4493 
   4494 		vma->pin_count = 0;
   4495 		ret = i915_vma_unbind(vma);
   4496 		if (WARN_ON(ret == -ERESTARTSYS)) {
   4497 			bool was_interruptible;
   4498 
   4499 			was_interruptible = dev_priv->mm.interruptible;
   4500 			dev_priv->mm.interruptible = false;
   4501 
   4502 			WARN_ON(i915_vma_unbind(vma));
   4503 
   4504 			dev_priv->mm.interruptible = was_interruptible;
   4505 		}
   4506 	}
   4507 
   4508 	/* Stolen objects don't hold a ref, but do hold pin count. Fix that up
   4509 	 * before progressing. */
   4510 	if (obj->stolen)
   4511 		i915_gem_object_unpin_pages(obj);
   4512 
   4513 	WARN_ON(obj->frontbuffer_bits);
   4514 
   4515 	if (obj->pages && obj->madv == I915_MADV_WILLNEED &&
   4516 	    dev_priv->quirks & QUIRK_PIN_SWIZZLED_PAGES &&
   4517 	    obj->tiling_mode != I915_TILING_NONE)
   4518 		i915_gem_object_unpin_pages(obj);
   4519 
   4520 	if (WARN_ON(obj->pages_pin_count))
   4521 		obj->pages_pin_count = 0;
   4522 	if (discard_backing_storage(obj))
   4523 		obj->madv = I915_MADV_DONTNEED;
   4524 	i915_gem_object_put_pages(obj);
   4525 	i915_gem_object_free_mmap_offset(obj);
   4526 
   4527 	BUG_ON(obj->pages);
   4528 
   4529 	if (obj->base.import_attach)
   4530 		drm_prime_gem_destroy(&obj->base, NULL);
   4531 
   4532 	if (obj->ops->release)
   4533 		obj->ops->release(obj);
   4534 
   4535 	drm_gem_object_release(&obj->base);
   4536 	i915_gem_info_remove_obj(dev_priv, obj->base.size);
   4537 
   4538 	kfree(obj->bit_17);
   4539 	i915_gem_object_free(obj);
   4540 
   4541 	intel_runtime_pm_put(dev_priv);
   4542 }
   4543 
   4544 struct i915_vma *i915_gem_obj_to_vma(struct drm_i915_gem_object *obj,
   4545 				     struct i915_address_space *vm)
   4546 {
   4547 	struct i915_vma *vma;
   4548 	list_for_each_entry(vma, &obj->vma_list, vma_link) {
   4549 		if (i915_is_ggtt(vma->vm) &&
   4550 		    vma->ggtt_view.type != I915_GGTT_VIEW_NORMAL)
   4551 			continue;
   4552 		if (vma->vm == vm)
   4553 			return vma;
   4554 	}
   4555 	return NULL;
   4556 }
   4557 
   4558 struct i915_vma *i915_gem_obj_to_ggtt_view(struct drm_i915_gem_object *obj,
   4559 					   const struct i915_ggtt_view *view)
   4560 {
   4561 	struct i915_address_space *ggtt = i915_obj_to_ggtt(obj);
   4562 	struct i915_vma *vma;
   4563 
   4564 	if (WARN_ONCE(!view, "no view specified"))
   4565 		return ERR_PTR(-EINVAL);
   4566 
   4567 	list_for_each_entry(vma, &obj->vma_list, vma_link)
   4568 		if (vma->vm == ggtt &&
   4569 		    i915_ggtt_view_equal(&vma->ggtt_view, view))
   4570 			return vma;
   4571 	return NULL;
   4572 }
   4573 
   4574 void i915_gem_vma_destroy(struct i915_vma *vma)
   4575 {
   4576 	struct i915_address_space *vm = NULL;
   4577 	WARN_ON(vma->node.allocated);
   4578 
   4579 	/* Keep the vma as a placeholder in the execbuffer reservation lists */
   4580 	if (!list_empty(&vma->exec_list))
   4581 		return;
   4582 
   4583 	vm = vma->vm;
   4584 
   4585 	if (!i915_is_ggtt(vm))
   4586 		i915_ppgtt_put(i915_vm_to_ppgtt(vm));
   4587 
   4588 	list_del(&vma->vma_link);
   4589 
   4590 	kmem_cache_free(to_i915(vma->obj->base.dev)->vmas, vma);
   4591 }
   4592 
   4593 static void
   4594 i915_gem_stop_ringbuffers(struct drm_device *dev)
   4595 {
   4596 	struct drm_i915_private *dev_priv = dev->dev_private;
   4597 	struct intel_engine_cs *ring;
   4598 	int i;
   4599 
   4600 	for_each_ring(ring, dev_priv, i)
   4601 		dev_priv->gt.stop_ring(ring);
   4602 }
   4603 
   4604 int
   4605 i915_gem_suspend(struct drm_device *dev)
   4606 {
   4607 	struct drm_i915_private *dev_priv = dev->dev_private;
   4608 	int ret = 0;
   4609 
   4610 	mutex_lock(&dev->struct_mutex);
   4611 	ret = i915_gpu_idle(dev);
   4612 	if (ret)
   4613 		goto err;
   4614 
   4615 	i915_gem_retire_requests(dev);
   4616 
   4617 	i915_gem_stop_ringbuffers(dev);
   4618 	mutex_unlock(&dev->struct_mutex);
   4619 
   4620 	cancel_delayed_work_sync(&dev_priv->gpu_error.hangcheck_work);
   4621 	cancel_delayed_work_sync(&dev_priv->mm.retire_work);
   4622 	flush_delayed_work(&dev_priv->mm.idle_work);
   4623 
   4624 	/* Assert that we sucessfully flushed all the work and
   4625 	 * reset the GPU back to its idle, low power state.
   4626 	 */
   4627 	WARN_ON(dev_priv->mm.busy);
   4628 
   4629 	return 0;
   4630 
   4631 err:
   4632 	mutex_unlock(&dev->struct_mutex);
   4633 	return ret;
   4634 }
   4635 
   4636 int i915_gem_l3_remap(struct drm_i915_gem_request *req, int slice)
   4637 {
   4638 	struct intel_engine_cs *ring = req->ring;
   4639 	struct drm_device *dev = ring->dev;
   4640 	struct drm_i915_private *dev_priv = dev->dev_private;
   4641 	u32 reg_base = GEN7_L3LOG_BASE + (slice * 0x200);
   4642 	u32 *remap_info = dev_priv->l3_parity.remap_info[slice];
   4643 	int i, ret;
   4644 
   4645 	if (!HAS_L3_DPF(dev) || !remap_info)
   4646 		return 0;
   4647 
   4648 	ret = intel_ring_begin(req, GEN7_L3LOG_SIZE / 4 * 3);
   4649 	if (ret)
   4650 		return ret;
   4651 
   4652 	/*
   4653 	 * Note: We do not worry about the concurrent register cacheline hang
   4654 	 * here because no other code should access these registers other than
   4655 	 * at initialization time.
   4656 	 */
   4657 	for (i = 0; i < GEN7_L3LOG_SIZE; i += 4) {
   4658 		intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
   4659 		intel_ring_emit(ring, reg_base + i);
   4660 		intel_ring_emit(ring, remap_info[i/4]);
   4661 	}
   4662 
   4663 	intel_ring_advance(ring);
   4664 
   4665 	return ret;
   4666 }
   4667 
   4668 void i915_gem_init_swizzling(struct drm_device *dev)
   4669 {
   4670 	struct drm_i915_private *dev_priv = dev->dev_private;
   4671 
   4672 	if (INTEL_INFO(dev)->gen < 5 ||
   4673 	    dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_NONE)
   4674 		return;
   4675 
   4676 	I915_WRITE(DISP_ARB_CTL, I915_READ(DISP_ARB_CTL) |
   4677 				 DISP_TILE_SURFACE_SWIZZLING);
   4678 
   4679 	if (IS_GEN5(dev))
   4680 		return;
   4681 
   4682 	I915_WRITE(TILECTL, I915_READ(TILECTL) | TILECTL_SWZCTL);
   4683 	if (IS_GEN6(dev))
   4684 		I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_SNB));
   4685 	else if (IS_GEN7(dev))
   4686 		I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_IVB));
   4687 	else if (IS_GEN8(dev))
   4688 		I915_WRITE(GAMTARBMODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_BDW));
   4689 	else
   4690 		BUG();
   4691 }
   4692 
   4693 static void init_unused_ring(struct drm_device *dev, u32 base)
   4694 {
   4695 	struct drm_i915_private *dev_priv = dev->dev_private;
   4696 
   4697 	I915_WRITE(RING_CTL(base), 0);
   4698 	I915_WRITE(RING_HEAD(base), 0);
   4699 	I915_WRITE(RING_TAIL(base), 0);
   4700 	I915_WRITE(RING_START(base), 0);
   4701 }
   4702 
   4703 static void init_unused_rings(struct drm_device *dev)
   4704 {
   4705 	if (IS_I830(dev)) {
   4706 		init_unused_ring(dev, PRB1_BASE);
   4707 		init_unused_ring(dev, SRB0_BASE);
   4708 		init_unused_ring(dev, SRB1_BASE);
   4709 		init_unused_ring(dev, SRB2_BASE);
   4710 		init_unused_ring(dev, SRB3_BASE);
   4711 	} else if (IS_GEN2(dev)) {
   4712 		init_unused_ring(dev, SRB0_BASE);
   4713 		init_unused_ring(dev, SRB1_BASE);
   4714 	} else if (IS_GEN3(dev)) {
   4715 		init_unused_ring(dev, PRB1_BASE);
   4716 		init_unused_ring(dev, PRB2_BASE);
   4717 	}
   4718 }
   4719 
   4720 int i915_gem_init_rings(struct drm_device *dev)
   4721 {
   4722 	struct drm_i915_private *dev_priv = dev->dev_private;
   4723 	int ret;
   4724 
   4725 	ret = intel_init_render_ring_buffer(dev);
   4726 	if (ret)
   4727 		return ret;
   4728 
   4729 	if (HAS_BSD(dev)) {
   4730 		ret = intel_init_bsd_ring_buffer(dev);
   4731 		if (ret)
   4732 			goto cleanup_render_ring;
   4733 	}
   4734 
   4735 	if (HAS_BLT(dev)) {
   4736 		ret = intel_init_blt_ring_buffer(dev);
   4737 		if (ret)
   4738 			goto cleanup_bsd_ring;
   4739 	}
   4740 
   4741 	if (HAS_VEBOX(dev)) {
   4742 		ret = intel_init_vebox_ring_buffer(dev);
   4743 		if (ret)
   4744 			goto cleanup_blt_ring;
   4745 	}
   4746 
   4747 	if (HAS_BSD2(dev)) {
   4748 		ret = intel_init_bsd2_ring_buffer(dev);
   4749 		if (ret)
   4750 			goto cleanup_vebox_ring;
   4751 	}
   4752 
   4753 	return 0;
   4754 
   4755 cleanup_vebox_ring:
   4756 	intel_cleanup_ring_buffer(&dev_priv->ring[VECS]);
   4757 cleanup_blt_ring:
   4758 	intel_cleanup_ring_buffer(&dev_priv->ring[BCS]);
   4759 cleanup_bsd_ring:
   4760 	intel_cleanup_ring_buffer(&dev_priv->ring[VCS]);
   4761 cleanup_render_ring:
   4762 	intel_cleanup_ring_buffer(&dev_priv->ring[RCS]);
   4763 
   4764 	return ret;
   4765 }
   4766 
   4767 int
   4768 i915_gem_init_hw(struct drm_device *dev)
   4769 {
   4770 	struct drm_i915_private *dev_priv = dev->dev_private;
   4771 	struct intel_engine_cs *ring;
   4772 	int ret, i, j;
   4773 
   4774 	if (INTEL_INFO(dev)->gen < 6 && !intel_enable_gtt())
   4775 		return -EIO;
   4776 
   4777 	/* Double layer security blanket, see i915_gem_init() */
   4778 	intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
   4779 
   4780 	if (dev_priv->ellc_size)
   4781 		I915_WRITE(HSW_IDICR, I915_READ(HSW_IDICR) | IDIHASHMSK(0xf));
   4782 
   4783 	if (IS_HASWELL(dev))
   4784 		I915_WRITE(MI_PREDICATE_RESULT_2, IS_HSW_GT3(dev) ?
   4785 			   LOWER_SLICE_ENABLED : LOWER_SLICE_DISABLED);
   4786 
   4787 	if (HAS_PCH_NOP(dev)) {
   4788 		if (IS_IVYBRIDGE(dev)) {
   4789 			u32 temp = I915_READ(GEN7_MSG_CTL);
   4790 			temp &= ~(WAIT_FOR_PCH_FLR_ACK | WAIT_FOR_PCH_RESET_ACK);
   4791 			I915_WRITE(GEN7_MSG_CTL, temp);
   4792 		} else if (INTEL_INFO(dev)->gen >= 7) {
   4793 			u32 temp = I915_READ(HSW_NDE_RSTWRN_OPT);
   4794 			temp &= ~RESET_PCH_HANDSHAKE_ENABLE;
   4795 			I915_WRITE(HSW_NDE_RSTWRN_OPT, temp);
   4796 		}
   4797 	}
   4798 
   4799 	i915_gem_init_swizzling(dev);
   4800 
   4801 	/*
   4802 	 * At least 830 can leave some of the unused rings
   4803 	 * "active" (ie. head != tail) after resume which
   4804 	 * will prevent c3 entry. Makes sure all unused rings
   4805 	 * are totally idle.
   4806 	 */
   4807 	init_unused_rings(dev);
   4808 
   4809 	BUG_ON(!dev_priv->ring[RCS].default_context);
   4810 
   4811 	ret = i915_ppgtt_init_hw(dev);
   4812 	if (ret) {
   4813 		DRM_ERROR("PPGTT enable HW failed %d\n", ret);
   4814 		goto out;
   4815 	}
   4816 
   4817 	/* Need to do basic initialisation of all rings first: */
   4818 	for_each_ring(ring, dev_priv, i) {
   4819 		ret = ring->init_hw(ring);
   4820 		if (ret)
   4821 			goto out;
   4822 	}
   4823 
   4824 	/* We can't enable contexts until all firmware is loaded */
   4825 	if (HAS_GUC_UCODE(dev)) {
   4826 		ret = intel_guc_ucode_load(dev);
   4827 		if (ret) {
   4828 			/*
   4829 			 * If we got an error and GuC submission is enabled, map
   4830 			 * the error to -EIO so the GPU will be declared wedged.
   4831 			 * OTOH, if we didn't intend to use the GuC anyway, just
   4832 			 * discard the error and carry on.
   4833 			 */
   4834 			DRM_ERROR("Failed to initialize GuC, error %d%s\n", ret,
   4835 				  i915.enable_guc_submission ? "" :
   4836 				  " (ignored)");
   4837 			ret = i915.enable_guc_submission ? -EIO : 0;
   4838 			if (ret)
   4839 				goto out;
   4840 		}
   4841 	}
   4842 
   4843 	/*
   4844 	 * Increment the next seqno by 0x100 so we have a visible break
   4845 	 * on re-initialisation
   4846 	 */
   4847 	ret = i915_gem_set_seqno(dev, dev_priv->next_seqno+0x100);
   4848 	if (ret)
   4849 		goto out;
   4850 
   4851 	/* Now it is safe to go back round and do everything else: */
   4852 	for_each_ring(ring, dev_priv, i) {
   4853 		struct drm_i915_gem_request *req;
   4854 
   4855 		WARN_ON(!ring->default_context);
   4856 
   4857 		ret = i915_gem_request_alloc(ring, ring->default_context, &req);
   4858 		if (ret) {
   4859 			i915_gem_cleanup_ringbuffer(dev);
   4860 			goto out;
   4861 		}
   4862 
   4863 		if (ring->id == RCS) {
   4864 			for (j = 0; j < NUM_L3_SLICES(dev); j++)
   4865 				i915_gem_l3_remap(req, j);
   4866 		}
   4867 
   4868 		ret = i915_ppgtt_init_ring(req);
   4869 		if (ret && ret != -EIO) {
   4870 			DRM_ERROR("PPGTT enable ring #%d failed %d\n", i, ret);
   4871 			i915_gem_request_cancel(req);
   4872 			i915_gem_cleanup_ringbuffer(dev);
   4873 			goto out;
   4874 		}
   4875 
   4876 		ret = i915_gem_context_enable(req);
   4877 		if (ret && ret != -EIO) {
   4878 			DRM_ERROR("Context enable ring #%d failed %d\n", i, ret);
   4879 			i915_gem_request_cancel(req);
   4880 			i915_gem_cleanup_ringbuffer(dev);
   4881 			goto out;
   4882 		}
   4883 
   4884 		i915_add_request_no_flush(req);
   4885 	}
   4886 
   4887 out:
   4888 	intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
   4889 	return ret;
   4890 }
   4891 
   4892 int i915_gem_init(struct drm_device *dev)
   4893 {
   4894 	struct drm_i915_private *dev_priv = dev->dev_private;
   4895 	int ret;
   4896 
   4897 	i915.enable_execlists = intel_sanitize_enable_execlists(dev,
   4898 			i915.enable_execlists);
   4899 
   4900 	mutex_lock(&dev->struct_mutex);
   4901 
   4902 	if (IS_VALLEYVIEW(dev)) {
   4903 		/* VLVA0 (potential hack), BIOS isn't actually waking us */
   4904 		I915_WRITE(VLV_GTLC_WAKE_CTRL, VLV_GTLC_ALLOWWAKEREQ);
   4905 		if (wait_for((I915_READ(VLV_GTLC_PW_STATUS) &
   4906 			      VLV_GTLC_ALLOWWAKEACK), 10))
   4907 			DRM_DEBUG_DRIVER("allow wake ack timed out\n");
   4908 	}
   4909 
   4910 	if (!i915.enable_execlists) {
   4911 		dev_priv->gt.execbuf_submit = i915_gem_ringbuffer_submission;
   4912 		dev_priv->gt.init_rings = i915_gem_init_rings;
   4913 		dev_priv->gt.cleanup_ring = intel_cleanup_ring_buffer;
   4914 		dev_priv->gt.stop_ring = intel_stop_ring_buffer;
   4915 	} else {
   4916 		dev_priv->gt.execbuf_submit = intel_execlists_submission;
   4917 		dev_priv->gt.init_rings = intel_logical_rings_init;
   4918 		dev_priv->gt.cleanup_ring = intel_logical_ring_cleanup;
   4919 		dev_priv->gt.stop_ring = intel_logical_ring_stop;
   4920 	}
   4921 
   4922 	/* This is just a security blanket to placate dragons.
   4923 	 * On some systems, we very sporadically observe that the first TLBs
   4924 	 * used by the CS may be stale, despite us poking the TLB reset. If
   4925 	 * we hold the forcewake during initialisation these problems
   4926 	 * just magically go away.
   4927 	 */
   4928 	intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
   4929 
   4930 	ret = i915_gem_init_userptr(dev);
   4931 	if (ret)
   4932 		goto out_unlock;
   4933 
   4934 	i915_gem_init_global_gtt(dev);
   4935 
   4936 	ret = i915_gem_context_init(dev);
   4937 	if (ret)
   4938 		goto out_unlock;
   4939 
   4940 	ret = dev_priv->gt.init_rings(dev);
   4941 	if (ret)
   4942 		goto out_unlock;
   4943 
   4944 	ret = i915_gem_init_hw(dev);
   4945 	if (ret == -EIO) {
   4946 		/* Allow ring initialisation to fail by marking the GPU as
   4947 		 * wedged. But we only want to do this where the GPU is angry,
   4948 		 * for all other failure, such as an allocation failure, bail.
   4949 		 */
   4950 		DRM_ERROR("Failed to initialize GPU, declaring it wedged\n");
   4951 		atomic_or(I915_WEDGED, &dev_priv->gpu_error.reset_counter);
   4952 		ret = 0;
   4953 	}
   4954 
   4955 out_unlock:
   4956 	intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
   4957 	mutex_unlock(&dev->struct_mutex);
   4958 
   4959 	return ret;
   4960 }
   4961 
   4962 void
   4963 i915_gem_cleanup_ringbuffer(struct drm_device *dev)
   4964 {
   4965 	struct drm_i915_private *dev_priv = dev->dev_private;
   4966 	struct intel_engine_cs *ring;
   4967 	int i;
   4968 
   4969 	for_each_ring(ring, dev_priv, i)
   4970 		dev_priv->gt.cleanup_ring(ring);
   4971 
   4972     if (i915.enable_execlists)
   4973             /*
   4974              * Neither the BIOS, ourselves or any other kernel
   4975              * expects the system to be in execlists mode on startup,
   4976              * so we need to reset the GPU back to legacy mode.
   4977              */
   4978             intel_gpu_reset(dev);
   4979 }
   4980 
   4981 static void
   4982 init_ring_lists(struct intel_engine_cs *ring)
   4983 {
   4984 	INIT_LIST_HEAD(&ring->active_list);
   4985 	INIT_LIST_HEAD(&ring->request_list);
   4986 }
   4987 
   4988 void
   4989 i915_gem_load(struct drm_device *dev)
   4990 {
   4991 	struct drm_i915_private *dev_priv = dev->dev_private;
   4992 	int i;
   4993 
   4994 	dev_priv->objects =
   4995 		kmem_cache_create("i915_gem_object",
   4996 				  sizeof(struct drm_i915_gem_object), 0,
   4997 				  SLAB_HWCACHE_ALIGN,
   4998 				  NULL);
   4999 	dev_priv->vmas =
   5000 		kmem_cache_create("i915_gem_vma",
   5001 				  sizeof(struct i915_vma), 0,
   5002 				  SLAB_HWCACHE_ALIGN,
   5003 				  NULL);
   5004 	dev_priv->requests =
   5005 		kmem_cache_create("i915_gem_request",
   5006 				  sizeof(struct drm_i915_gem_request), 0,
   5007 				  SLAB_HWCACHE_ALIGN,
   5008 				  NULL);
   5009 
   5010 	INIT_LIST_HEAD(&dev_priv->vm_list);
   5011 	INIT_LIST_HEAD(&dev_priv->context_list);
   5012 	INIT_LIST_HEAD(&dev_priv->mm.unbound_list);
   5013 	INIT_LIST_HEAD(&dev_priv->mm.bound_list);
   5014 	INIT_LIST_HEAD(&dev_priv->mm.fence_list);
   5015 	for (i = 0; i < I915_NUM_RINGS; i++)
   5016 		init_ring_lists(&dev_priv->ring[i]);
   5017 	for (i = 0; i < I915_MAX_NUM_FENCES; i++)
   5018 		INIT_LIST_HEAD(&dev_priv->fence_regs[i].lru_list);
   5019 	INIT_DELAYED_WORK(&dev_priv->mm.retire_work,
   5020 			  i915_gem_retire_work_handler);
   5021 	INIT_DELAYED_WORK(&dev_priv->mm.idle_work,
   5022 			  i915_gem_idle_work_handler);
   5023 	init_waitqueue_head(&dev_priv->gpu_error.reset_queue);
   5024 
   5025 	dev_priv->relative_constants_mode = I915_EXEC_CONSTANTS_REL_GENERAL;
   5026 
   5027 	if (INTEL_INFO(dev)->gen >= 7 && !IS_VALLEYVIEW(dev))
   5028 		dev_priv->num_fence_regs = 32;
   5029 	else if (INTEL_INFO(dev)->gen >= 4 || IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
   5030 		dev_priv->num_fence_regs = 16;
   5031 	else
   5032 		dev_priv->num_fence_regs = 8;
   5033 
   5034 	if (intel_vgpu_active(dev))
   5035 		dev_priv->num_fence_regs =
   5036 				I915_READ(vgtif_reg(avail_rs.fence_num));
   5037 
   5038 	/*
   5039 	 * Set initial sequence number for requests.
   5040 	 * Using this number allows the wraparound to happen early,
   5041 	 * catching any obvious problems.
   5042 	 */
   5043 	dev_priv->next_seqno = ((u32)~0 - 0x1100);
   5044 	dev_priv->last_seqno = ((u32)~0 - 0x1101);
   5045 
   5046 	/* Initialize fence registers to zero */
   5047 	INIT_LIST_HEAD(&dev_priv->mm.fence_list);
   5048 	i915_gem_restore_fences(dev);
   5049 
   5050 	i915_gem_detect_bit_6_swizzle(dev);
   5051 	init_waitqueue_head(&dev_priv->pending_flip_queue);
   5052 
   5053 	dev_priv->mm.interruptible = true;
   5054 
   5055 	i915_gem_shrinker_init(dev_priv);
   5056 
   5057 	mutex_init(&dev_priv->fb_tracking.lock);
   5058 }
   5059 
   5060 void i915_gem_release(struct drm_device *dev, struct drm_file *file)
   5061 {
   5062 	struct drm_i915_file_private *file_priv = file->driver_priv;
   5063 
   5064 	/* Clean up our request list when the client is going away, so that
   5065 	 * later retire_requests won't dereference our soon-to-be-gone
   5066 	 * file_priv.
   5067 	 */
   5068 	spin_lock(&file_priv->mm.lock);
   5069 	while (!list_empty(&file_priv->mm.request_list)) {
   5070 		struct drm_i915_gem_request *request;
   5071 
   5072 		request = list_first_entry(&file_priv->mm.request_list,
   5073 					   struct drm_i915_gem_request,
   5074 					   client_list);
   5075 		list_del(&request->client_list);
   5076 		request->file_priv = NULL;
   5077 	}
   5078 	spin_unlock(&file_priv->mm.lock);
   5079 
   5080 	if (!list_empty(&file_priv->rps.link)) {
   5081 		spin_lock(&to_i915(dev)->rps.client_lock);
   5082 		list_del(&file_priv->rps.link);
   5083 		spin_unlock(&to_i915(dev)->rps.client_lock);
   5084 	}
   5085 }
   5086 
   5087 int i915_gem_open(struct drm_device *dev, struct drm_file *file)
   5088 {
   5089 	struct drm_i915_file_private *file_priv;
   5090 	int ret;
   5091 
   5092 	DRM_DEBUG_DRIVER("\n");
   5093 
   5094 	file_priv = kzalloc(sizeof(*file_priv), GFP_KERNEL);
   5095 	if (!file_priv)
   5096 		return -ENOMEM;
   5097 
   5098 	file->driver_priv = file_priv;
   5099 	file_priv->dev_priv = dev->dev_private;
   5100 	file_priv->file = file;
   5101 	INIT_LIST_HEAD(&file_priv->rps.link);
   5102 
   5103 	spin_lock_init(&file_priv->mm.lock);
   5104 	INIT_LIST_HEAD(&file_priv->mm.request_list);
   5105 
   5106 	ret = i915_gem_context_open(dev, file);
   5107 	if (ret)
   5108 		kfree(file_priv);
   5109 
   5110 	return ret;
   5111 }
   5112 
   5113 /**
   5114  * i915_gem_track_fb - update frontbuffer tracking
   5115  * @old: current GEM buffer for the frontbuffer slots
   5116  * @new: new GEM buffer for the frontbuffer slots
   5117  * @frontbuffer_bits: bitmask of frontbuffer slots
   5118  *
   5119  * This updates the frontbuffer tracking bits @frontbuffer_bits by clearing them
   5120  * from @old and setting them in @new. Both @old and @new can be NULL.
   5121  */
   5122 void i915_gem_track_fb(struct drm_i915_gem_object *old,
   5123 		       struct drm_i915_gem_object *new,
   5124 		       unsigned frontbuffer_bits)
   5125 {
   5126 	if (old) {
   5127 		WARN_ON(!mutex_is_locked(&old->base.dev->struct_mutex));
   5128 		WARN_ON(!(old->frontbuffer_bits & frontbuffer_bits));
   5129 		old->frontbuffer_bits &= ~frontbuffer_bits;
   5130 	}
   5131 
   5132 	if (new) {
   5133 		WARN_ON(!mutex_is_locked(&new->base.dev->struct_mutex));
   5134 		WARN_ON(new->frontbuffer_bits & frontbuffer_bits);
   5135 		new->frontbuffer_bits |= frontbuffer_bits;
   5136 	}
   5137 }
   5138 
   5139 /* All the new VM stuff */
   5140 u64 i915_gem_obj_offset(struct drm_i915_gem_object *o,
   5141 			struct i915_address_space *vm)
   5142 {
   5143 	struct drm_i915_private *dev_priv = o->base.dev->dev_private;
   5144 	struct i915_vma *vma;
   5145 
   5146 	WARN_ON(vm == &dev_priv->mm.aliasing_ppgtt->base);
   5147 
   5148 	list_for_each_entry(vma, &o->vma_list, vma_link) {
   5149 		if (i915_is_ggtt(vma->vm) &&
   5150 		    vma->ggtt_view.type != I915_GGTT_VIEW_NORMAL)
   5151 			continue;
   5152 		if (vma->vm == vm)
   5153 			return vma->node.start;
   5154 	}
   5155 
   5156 	WARN(1, "%s vma for this object not found.\n",
   5157 	     i915_is_ggtt(vm) ? "global" : "ppgtt");
   5158 	return -1;
   5159 }
   5160 
   5161 u64 i915_gem_obj_ggtt_offset_view(struct drm_i915_gem_object *o,
   5162 				  const struct i915_ggtt_view *view)
   5163 {
   5164 	struct i915_address_space *ggtt = i915_obj_to_ggtt(o);
   5165 	struct i915_vma *vma;
   5166 
   5167 	list_for_each_entry(vma, &o->vma_list, vma_link)
   5168 		if (vma->vm == ggtt &&
   5169 		    i915_ggtt_view_equal(&vma->ggtt_view, view))
   5170 			return vma->node.start;
   5171 
   5172 	WARN(1, "global vma for this object not found. (view=%u)\n", view->type);
   5173 	return -1;
   5174 }
   5175 
   5176 bool i915_gem_obj_bound(struct drm_i915_gem_object *o,
   5177 			struct i915_address_space *vm)
   5178 {
   5179 	struct i915_vma *vma;
   5180 
   5181 	list_for_each_entry(vma, &o->vma_list, vma_link) {
   5182 		if (i915_is_ggtt(vma->vm) &&
   5183 		    vma->ggtt_view.type != I915_GGTT_VIEW_NORMAL)
   5184 			continue;
   5185 		if (vma->vm == vm && drm_mm_node_allocated(&vma->node))
   5186 			return true;
   5187 	}
   5188 
   5189 	return false;
   5190 }
   5191 
   5192 bool i915_gem_obj_ggtt_bound_view(struct drm_i915_gem_object *o,
   5193 				  const struct i915_ggtt_view *view)
   5194 {
   5195 	struct i915_address_space *ggtt = i915_obj_to_ggtt(o);
   5196 	struct i915_vma *vma;
   5197 
   5198 	list_for_each_entry(vma, &o->vma_list, vma_link)
   5199 		if (vma->vm == ggtt &&
   5200 		    i915_ggtt_view_equal(&vma->ggtt_view, view) &&
   5201 		    drm_mm_node_allocated(&vma->node))
   5202 			return true;
   5203 
   5204 	return false;
   5205 }
   5206 
   5207 bool i915_gem_obj_bound_any(struct drm_i915_gem_object *o)
   5208 {
   5209 	struct i915_vma *vma;
   5210 
   5211 	list_for_each_entry(vma, &o->vma_list, vma_link)
   5212 		if (drm_mm_node_allocated(&vma->node))
   5213 			return true;
   5214 
   5215 	return false;
   5216 }
   5217 
   5218 unsigned long i915_gem_obj_size(struct drm_i915_gem_object *o,
   5219 				struct i915_address_space *vm)
   5220 {
   5221 	struct drm_i915_private *dev_priv = o->base.dev->dev_private;
   5222 	struct i915_vma *vma;
   5223 
   5224 	WARN_ON(vm == &dev_priv->mm.aliasing_ppgtt->base);
   5225 
   5226 	BUG_ON(list_empty(&o->vma_list));
   5227 
   5228 	list_for_each_entry(vma, &o->vma_list, vma_link) {
   5229 		if (i915_is_ggtt(vma->vm) &&
   5230 		    vma->ggtt_view.type != I915_GGTT_VIEW_NORMAL)
   5231 			continue;
   5232 		if (vma->vm == vm)
   5233 			return vma->node.size;
   5234 	}
   5235 	return 0;
   5236 }
   5237 
   5238 bool i915_gem_obj_is_pinned(struct drm_i915_gem_object *obj)
   5239 {
   5240 	struct i915_vma *vma;
   5241 	list_for_each_entry(vma, &obj->vma_list, vma_link)
   5242 		if (vma->pin_count > 0)
   5243 			return true;
   5244 
   5245 	return false;
   5246 }
   5247 
   5248 /* Allocate a new GEM object and fill it with the supplied data */
   5249 struct drm_i915_gem_object *
   5250 i915_gem_object_create_from_data(struct drm_device *dev,
   5251 			         const void *data, size_t size)
   5252 {
   5253 	struct drm_i915_gem_object *obj;
   5254 	struct sg_table *sg;
   5255 	size_t bytes;
   5256 	int ret;
   5257 
   5258 	obj = i915_gem_alloc_object(dev, round_up(size, PAGE_SIZE));
   5259 	if (IS_ERR_OR_NULL(obj))
   5260 		return obj;
   5261 
   5262 	ret = i915_gem_object_set_to_cpu_domain(obj, true);
   5263 	if (ret)
   5264 		goto fail;
   5265 
   5266 	ret = i915_gem_object_get_pages(obj);
   5267 	if (ret)
   5268 		goto fail;
   5269 
   5270 	i915_gem_object_pin_pages(obj);
   5271 	sg = obj->pages;
   5272 	bytes = sg_copy_from_buffer(sg->sgl, sg->nents, (void *)data, size);
   5273 	i915_gem_object_unpin_pages(obj);
   5274 
   5275 	if (WARN_ON(bytes != size)) {
   5276 		DRM_ERROR("Incomplete copy, wrote %zu of %zu", bytes, size);
   5277 		ret = -EFAULT;
   5278 		goto fail;
   5279 	}
   5280 
   5281 	return obj;
   5282 
   5283 fail:
   5284 	drm_gem_object_unreference(&obj->base);
   5285 	return ERR_PTR(ret);
   5286 }
   5287